diff --git a/AGENTS.md b/AGENTS.md index 99277c95..e5d883c8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,7 @@ Start with the task's files; read only relevant sections of these references, no | Shared wire types and validation | `shared/src/types.ts`, `schemas.ts`, `socket.ts`, `modes.ts` | | Native API contract, chat conformance | [client contract](docs/api/client-contract/index.md), [iOS](ios/README.md), [Android](android/README.md) | | Encrypted native push relay | [relay/README.md](relay/README.md) | +| Session-attached jobs (outliving work) | [session jobs guide](docs/guide/session-jobs.md), `cli/src/commands/job.ts` | | User docs / marketing site | `docs/` (VitePress) / `website/` | ## Repository conventions @@ -39,6 +40,20 @@ Start with the task's files; read only relevant sections of these references, no - Metadata/state updates are versioned; preserve stale-update rejection. Permission controls use per-flavor catalogs in `shared/src/modes.ts`, further constrained by session capabilities. - `shared/fixtures/**` is generated from the web chat pipeline, the source of truth for native conformance. Never hand-edit fixtures. For changes to fixture inputs or generation (paths in [.github/workflows/fixtures.yml](.github/workflows/fixtures.yml)), run `bun run gen:fixtures` and include any generated changes in the deliverable. CI checks drift and runs native conformance on fixture changes. +## Session-attached jobs (outliving work) + +When an agent starts process-shaped work that will keep running after the agent goes idle (`nohup`, batch imports, long scripts, external daemons), attach it so the session list stays truthful while `active: false`. This is **not** thinking progress / todos / in-agent background tools. + +Agent contract (idle agents cannot heartbeat — bare set + nohup freezes the bar): + +1. **Required for process-shaped work:** Shell `hapi job run --label … --progress unknown|fraction|until … -- ` (auto-heartbeat + exit status; `--progress` required). Use `"$HAPI_SESSION_ID"` only when it matches the operator chat row (`/sessions/` in the web URL). +2. MCP `session_job` **refuses `action=set`**. Use it only for `update` / `clear` / `list` on a job the supervisor already created. +3. Manual CLI `set` only with a self-heartbeating wrapper (`update` ≥~10m); never MCP set + nohup. +4. Prefer honest `--remaining`+`--total` or `--done`/`--total` for a determinate fill; omit counts if unknown — list shows a subtle indeterminate striped bar (no %). Never invent a percent. +5. Elapsed wall clock is always shown from `startedAt` (not an ETA). + +Full guide: [docs/guide/session-jobs.md](docs/guide/session-jobs.md). CLI: `hapi job --help`. + ## Verification and completion Choose checks by the change's impact, not by the number of workflow steps: diff --git a/cli/README.md b/cli/README.md index 2a303e95..fe1962cd 100644 --- a/cli/README.md +++ b/cli/README.md @@ -47,6 +47,7 @@ Choose a supported coding agent from your terminal and control its sessions remo - `hapi usage [--since 24h|7d||] [--until …] [--json]` - When agents were working across every machine on the hub, from `GET /api/activity`. `--json` prints one `hapi.activity.v1` report for other tools (time trackers); errors go to stderr with exit codes 2 (arguments), 3 (no token or refused), 4 (hub too old), 1 (other). - `hapi inspect-peer ` - Read-only peer metadata + recent message text (no resume). Prefer this or MCP `inspect_peer` when a user cites `[title](/sessions/)` or Copy-reference `See session "…" (/sessions/) for context`. `/sessions/` is a hub path, not a local file. Optional `--limit`. - `hapi set-mode ` - Change the permission mode of an existing session, like the web permission picker. Active sessions switch immediately; inactive ones use it on next resume. An invalid mode prints the modes allowed for that agent. +- `hapi job set|update|clear|list|run` - Attach long-running outliving work to a session so the list UI shows progress while the agent is idle (`tiann/hapi#1404`). Prefer `"$HAPI_SESSION_ID"`. Heartbeat via `update` (or `run`); honest `--remaining` or `--done`/`--total` (omit counts if unknown — never invent a percent). Late-attach clock fix: `set --started-at ` or clear+set. See `docs/guide/session-jobs.md` and `hapi job --help`. Peer messages default to `auto`: use the target's live capabilities and turn state to steer an active, eligible turn; otherwise queue. Inactive peers require explicit `wake: true`; awakened peers enter the ordinary queue. This applies to every steering-supported diff --git a/cli/src/agent/backends/acp/AcpSdkBackend.ts b/cli/src/agent/backends/acp/AcpSdkBackend.ts index 7a744de1..ecf5737d 100644 --- a/cli/src/agent/backends/acp/AcpSdkBackend.ts +++ b/cli/src/agent/backends/acp/AcpSdkBackend.ts @@ -5,6 +5,16 @@ import { AcpStdioTransport, type AcpStderrError } from './AcpStdioTransport'; import { AcpMessageHandler, type AcpTextChunkMode } from './AcpMessageHandler'; import { ACP_SESSION_UPDATE_TYPES, OPENCODE_CHILD_SESSION_UPDATES, OPENCODE_CHILD_UPDATE_METHOD } from './constants'; import { thinkingHintFromSessionUpdate } from './shouldBumpThinkingFromSessionUpdate'; + +/** Why the backend is bumping/clearing hub thinking — launchers filter chatter here (#1553). */ +export type AgentActivitySource = + | 'state_update_running' + | 'state_update_idle' + | 'state_update_requires_action' + | 'permission' + | 'form_elicitation'; + +export type AgentActivityListener = (thinking: boolean, source: AgentActivitySource) => void; import { logger } from '@/ui/logger'; import { withRetry } from '@/utils/time'; import packageJson from '../../../../package.json'; @@ -135,7 +145,7 @@ export class AcpSdkBackend implements AgentBackend { private sessionInfoUpdateListener: ((update: AcpSessionInfoUpdate) => void) | null = null; private userMessageChunkListener: ((text: string) => void) | null = null; /** Fired on foreground ACP state / permission so launchers can bump hub thinking (#1470). */ - private agentActivityListener: ((thinking: boolean) => void) | null = null; + private agentActivityListener: AgentActivityListener | null = null; /** Debounce timer for state_update running → thinking (#1502 chatter). */ private runningThinkingTimer: ReturnType | null = null; private lastForwardedUsageUpdate: AcpUsageUpdate | null = null; @@ -664,7 +674,7 @@ export class AcpSdkBackend implements AgentBackend { * `false` = `state_update` idle (skipped while a HAPI prompt turn is still draining). * Launchers should ignore no-ops when session.thinking already matches. */ - setAgentActivityListener(listener: ((thinking: boolean) => void) | null): void { + setAgentActivityListener(listener: AgentActivityListener | null): void { this.agentActivityListener = listener; } @@ -1030,7 +1040,7 @@ export class AcpSdkBackend implements AgentBackend { } }; this.pendingElicitations.add(pending); - this.agentActivityListener?.(true); + this.agentActivityListener?.(true, 'form_elicitation'); this.formElicitationHandler!(request).then( (response) => pending.settle(response), (error) => { @@ -1370,7 +1380,7 @@ export class AcpSdkBackend implements AgentBackend { if (this.isProcessingMessage) { return; } - this.agentActivityListener(false); + this.agentActivityListener(false, 'state_update_idle'); return; } @@ -1381,13 +1391,17 @@ export class AcpSdkBackend implements AgentBackend { } this.runningThinkingTimer = setTimeout(() => { this.runningThinkingTimer = null; - this.agentActivityListener?.(true); + this.agentActivityListener?.(true, 'state_update_running'); }, AcpSdkBackend.RUNNING_THINKING_DEBOUNCE_MS); return; } this.clearRunningThinkingTimer(); - this.agentActivityListener(true); + const source: AgentActivitySource = update.sessionUpdate === 'state_update' + && update.state === 'requires_action' + ? 'state_update_requires_action' + : 'state_update_running'; + this.agentActivityListener(true, source); } private clearRunningThinkingTimer(): void { @@ -1573,7 +1587,7 @@ export class AcpSdkBackend implements AgentBackend { if (this.permissionHandler) { try { // Permission prompts imply the agent is awake (#1470). - this.agentActivityListener?.(true); + this.agentActivityListener?.(true, 'permission'); this.permissionHandler(request); } catch (error) { this.pendingPermissions.delete(toolCallId); diff --git a/cli/src/agent/runners/runAgentSession.test.ts b/cli/src/agent/runners/runAgentSession.test.ts index b81ffe26..72044b4c 100644 --- a/cli/src/agent/runners/runAgentSession.test.ts +++ b/cli/src/agent/runners/runAgentSession.test.ts @@ -76,7 +76,7 @@ vi.mock('@/claude/utils/startHappyServer', () => ({ harness.startHappyServerOptions = options return { url: 'http://127.0.0.1:1234', - toolNames: ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'skill_lookup'], + toolNames: ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'session_job', 'skill_lookup'], stop: harness.stopServer } }) @@ -169,7 +169,7 @@ describe('runAgentSession', () => { '--url', 'http://127.0.0.1:1234', '--tools', - 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,skill_lookup', + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,session_job,skill_lookup', '--hapi-session-id', 'hub-session-acp-1', ]) diff --git a/cli/src/agent/sessionFactory.test.ts b/cli/src/agent/sessionFactory.test.ts index 8270b251..027f0bff 100644 --- a/cli/src/agent/sessionFactory.test.ts +++ b/cli/src/agent/sessionFactory.test.ts @@ -159,6 +159,41 @@ describe('bootstrapExistingSession', () => { ) }) + it('exports the requested existing session id for Cursor runner resume (#1404)', async () => { + // Runner passes --existing-session-id (buildCliArgs); child bootstrap must + // publish that same hub row into HAPI_SESSION_ID for shell `hapi job run`. + const session = createSession() + session.metadata = { + ...session.metadata!, + flavor: 'cursor', + cursorSessionId: 'cursor-csid-1', + cursorSessionProtocol: 'acp' + } + const sessionClient = { updateMetadata: vi.fn() } + getSessionMock.mockResolvedValue(session) + getOrCreateMachineMock.mockResolvedValue({ id: 'machine-1' }) + sessionSyncClientMock.mockReturnValue(sessionClient) + readSettingsMock.mockResolvedValue({ machineId: 'machine-1' }) + + await bootstrapExistingSession({ + sessionId: 'hapi-session-1', + flavor: 'cursor', + startedBy: 'runner', + workingDirectory: '/tmp/project' + }) + + expect(getSessionMock).toHaveBeenCalledWith('hapi-session-1') + expect(process.env[HAPI_SESSION_ID_ENV]).toBe('hapi-session-1') + expect(notifyRunnerSessionStartedMock).toHaveBeenCalledWith( + 'hapi-session-1', + expect.objectContaining({ + flavor: 'cursor', + startedBy: 'runner', + startedFromRunner: true + }) + ) + }) + it('refuses to reopen a hub-archived session (hub-archive resurrection guard)', async () => { // #1911 M1 belt: hub-archived only (matches store merge-preserve scope). const session = createSession() diff --git a/cli/src/claude/utils/startHappyServer.test.ts b/cli/src/claude/utils/startHappyServer.test.ts index 575f5482..a56d8db1 100644 --- a/cli/src/claude/utils/startHappyServer.test.ts +++ b/cli/src/claude/utils/startHappyServer.test.ts @@ -111,15 +111,16 @@ describe('startHappyServer skill_lookup', () => { const mcp = await connect(false) const tools = await mcp.listTools() - expect(tools.tools.map((tool) => tool.name)).toEqual([ + expect(tools.tools.map((tool) => tool.name).sort()).toEqual([ 'change_title', 'display_image', - 'display_video', 'display_media', - 'ping_peer', - 'spawn_peer', + 'display_video', 'inspect_peer', - 'list_peers' + 'list_peers', + 'ping_peer', + 'session_job', + 'spawn_peer', ]) }) @@ -439,6 +440,7 @@ describe('startHappyServer skill_lookup', () => { it('does not expose change_title when native ACP titles are enabled', async () => { const sessionClient = { + sessionId: 'test-session-id', updateMetadata: vi.fn(), sendAgentMessage: vi.fn(), sendClaudeSessionMessage: vi.fn() @@ -451,15 +453,25 @@ describe('startHappyServer skill_lookup', () => { await mcp.connect(new StreamableHTTPClientTransport(new URL(server.url))) const tools = await mcp.listTools() - expect(server.toolNames).toEqual(['display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer']) - expect(tools.tools.map((tool) => tool.name)).toEqual([ + expect(server.toolNames).toEqual([ 'display_image', 'display_video', 'display_media', + 'list_peers', 'ping_peer', - 'spawn_peer', 'inspect_peer', - 'list_peers' + 'spawn_peer', + 'session_job', + ]) + expect(tools.tools.map((tool) => tool.name).sort()).toEqual([ + 'display_image', + 'display_media', + 'display_video', + 'inspect_peer', + 'list_peers', + 'ping_peer', + 'session_job', + 'spawn_peer', ]) }) @@ -677,11 +689,13 @@ describe('toClaudeAllowedHapiMcpTools', () => { 'ping_peer', 'inspect_peer', 'spawn_peer', + 'session_job', 'skill_lookup' ])).toEqual([ 'mcp__hapi__change_title', 'mcp__hapi__display_image', 'mcp__hapi__list_peers', + 'mcp__hapi__session_job', 'mcp__hapi__skill_lookup' ]) expect(toClaudeAllowedHapiMcpTools(['display_video'])).not.toContain('mcp__hapi__display_video') @@ -787,13 +801,25 @@ describe('startHappyServer peer tools kill switch', () => { it('omits peer tools from registration and toolNames when HAPI_DISABLE_PEER_TOOLS is set', async () => { process.env.HAPI_DISABLE_PEER_TOOLS = '1' const { toolNames } = await startServer() - expect(toolNames).toEqual(['change_title', 'display_image', 'display_video', 'display_media']) + // session_job is own-session (not peer) — stays available when peer tools are off. + expect(toolNames).toEqual([ + 'change_title', + 'display_image', + 'display_video', + 'display_media', + 'session_job', + ]) const tools = await client!.listTools() const names = tools.tools.map((tool) => tool.name) expect(names).not.toContain('list_peers') expect(names).not.toContain('ping_peer') expect(names).not.toContain('inspect_peer') expect(names).not.toContain('spawn_peer') - expect(names).toEqual(expect.arrayContaining(['display_image', 'display_video', 'display_media'])) + expect(names).toEqual(expect.arrayContaining([ + 'display_image', + 'display_video', + 'display_media', + 'session_job', + ])) }) }) diff --git a/cli/src/claude/utils/startHappyServer.ts b/cli/src/claude/utils/startHappyServer.ts index a3750f4e..0e7eba4b 100644 --- a/cli/src/claude/utils/startHappyServer.ts +++ b/cli/src/claude/utils/startHappyServer.ts @@ -39,6 +39,13 @@ import { CREATABLE_AGENT_FLAVORS } from '@hapi/protocol/modes' import { PermissionModeSchema } from '@hapi/protocol/schemas' import { PingPeerError, formatInspectPeerReport, formatPeerSessionsList, forwardPeerReply, inspectPeer, listPeerSessions, peerListFetchLimit, pingPeer, supportsPeerReply } from "@/modules/pingPeer/pingPeer"; import { applySessionDisplayRename, normalizeSessionDisplayTitle } from "@/agent/sessionDisplayRename"; +import { + SESSION_JOB_TOOL_DESCRIPTION, + SESSION_JOB_TOOL_NAME, + handleSessionJobTool, + sessionJobInputSchema, + type SessionJobToolArgs, +} from "@/modules/sessionJob/sessionJobMcp"; import { SpawnPeerError, spawnPeer } from "@/modules/spawnPeer/spawnPeer"; export type HapiMcpToolName = @@ -50,6 +57,7 @@ export type HapiMcpToolName = | 'ping_peer' | 'inspect_peer' | 'spawn_peer' + | 'session_job' | 'skill_lookup'; type StartHappyServerOptions = { @@ -432,6 +440,19 @@ function createHapiMcpServer( } }); + registerTool(SESSION_JOB_TOOL_NAME, { + description: SESSION_JOB_TOOL_DESCRIPTION, + title: 'Session-Attached Job', + inputSchema: sessionJobInputSchema, + }, async (args: SessionJobToolArgs) => { + logger.debug('[hapiMCP] session_job:', args.action, args.jobKey); + const result = await handleSessionJobTool(args, client.sessionId); + return { + content: [{ type: 'text' as const, text: result.text }], + isError: result.isError, + }; + }); + if (!peerToolsDisabled) { registerTool('ping_peer', { description: PING_PEER_TOOL_DESCRIPTION, @@ -710,6 +731,7 @@ export async function startHappyServer(client: ApiSessionClient, options: StartH if (includeTool(name)) toolNames.push(name); } } + if (includeTool(SESSION_JOB_TOOL_NAME)) toolNames.push(SESSION_JOB_TOOL_NAME); if (options.skillLookup && includeTool('skill_lookup')) toolNames.push('skill_lookup'); if (toolNames.length === 0) { throw new Error('startHappyServer requires at least one enabled tool'); diff --git a/cli/src/claude/utils/systemPrompt.ts b/cli/src/claude/utils/systemPrompt.ts index 8a49b1d0..b90d4ecf 100644 --- a/cli/src/claude/utils/systemPrompt.ts +++ b/cli/src/claude/utils/systemPrompt.ts @@ -3,6 +3,7 @@ import { buildSessionCitationSteerInstruction, SESSION_CITATION_DISABLED_STEER } import { isPeerToolsDisabled } from "@/modules/common/peerTools"; import { shouldIncludeCoAuthoredBy } from "./claudeSettings"; import { DISPLAY_IMAGE_PROMPT_CLAUDE, DISPLAY_MEDIA_PROMPT_CLAUDE, DISPLAY_VIDEO_PROMPT_CLAUDE } from "@/modules/common/displayImagePrompt"; +import { withSessionJobInstruction } from "@/modules/common/sessionJobInstruction"; import { withSessionSummaryInstruction } from "@/modules/common/sessionSummaryInstruction"; /** @@ -44,5 +45,5 @@ export function getSystemPrompt(): string { const base = includeCoAuthored ? BASE_SYSTEM_PROMPT + '\n\n' + CO_AUTHORED_CREDITS : BASE_SYSTEM_PROMPT; - return withSessionSummaryInstruction(base); + return withSessionSummaryInstruction(withSessionJobInstruction(base)); } diff --git a/cli/src/codex/happyMcpStdioBridge.test.ts b/cli/src/codex/happyMcpStdioBridge.test.ts index a8930dd7..0a169e88 100644 --- a/cli/src/codex/happyMcpStdioBridge.test.ts +++ b/cli/src/codex/happyMcpStdioBridge.test.ts @@ -70,16 +70,20 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { '--url', 'http://127.0.0.1:43006', '--tools', - 'change_title,display_image,display_video,display_media,skill_lookup' + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,session_job,skill_lookup' ]) - expect([...harness.tools.keys()]).toEqual([ + expect([...harness.tools.keys()].sort()).toEqual([ 'change_title', 'display_image', - 'display_video', 'display_media', - 'skill_lookup' - ]) + 'display_video', + 'inspect_peer', + 'list_peers', + 'ping_peer', + 'session_job', + 'skill_lookup', + ].sort()) const handler = harness.tools.get('skill_lookup') expect(handler).toBeDefined() @@ -140,6 +144,24 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { ]) }) + it('registers session_job when included in --tools', async () => { + await runHappyMcpStdioBridge([ + '--url', + 'http://127.0.0.1:43006', + '--tools', + 'change_title,display_image,list_peers,ping_peer,inspect_peer,session_job' + ]) + + expect([...harness.tools.keys()].sort()).toEqual([ + 'change_title', + 'display_image', + 'inspect_peer', + 'list_peers', + 'ping_peer', + 'session_job', + ].sort()) + }) + it.each(['auto', 'queue', 'steer'])('advertises and forwards ping_peer delivery mode %s', async (deliveryMode) => { await runHappyMcpStdioBridge(['--url', 'http://127.0.0.1:43006', '--tools', 'ping_peer']) const schema = harness.configs.get('ping_peer')?.inputSchema as { @@ -234,6 +256,7 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { 'display_image', 'display_video', 'display_media', + 'session_job', 'ping_peer', 'spawn_peer', 'inspect_peer', @@ -247,11 +270,13 @@ describe('runHappyMcpStdioBridge tool forwarding', () => { try { await runHappyMcpStdioBridge(['--url', 'http://127.0.0.1:43006']) + // session_job is own-session — kept when peer tools are stripped. expect([...harness.tools.keys()]).toEqual([ 'change_title', 'display_image', 'display_video', - 'display_media' + 'display_media', + 'session_job', ]) } finally { delete process.env.HAPI_DISABLE_PEER_TOOLS diff --git a/cli/src/codex/happyMcpStdioBridge.ts b/cli/src/codex/happyMcpStdioBridge.ts index e0ccdb95..225eabe9 100644 --- a/cli/src/codex/happyMcpStdioBridge.ts +++ b/cli/src/codex/happyMcpStdioBridge.ts @@ -33,8 +33,23 @@ import { SESSION_NAME_MAX_LENGTH } from '@hapi/protocol'; import { CREATABLE_AGENT_FLAVORS } from '@hapi/protocol/modes'; import { PermissionModeSchema } from '@hapi/protocol/schemas'; import { isPeerToolsDisabled, PEER_TOOL_NAMES } from '@/modules/common/peerTools'; +import { + SESSION_JOB_TOOL_DESCRIPTION, + SESSION_JOB_TOOL_NAME, + sessionJobInputSchema, +} from '@/modules/sessionJob/sessionJobMcp'; -const DEFAULT_TOOL_NAMES = ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer']; +const DEFAULT_TOOL_NAMES = [ + 'change_title', + 'display_image', + 'display_video', + 'display_media', + 'list_peers', + 'ping_peer', + 'inspect_peer', + 'spawn_peer', + SESSION_JOB_TOOL_NAME, +]; function parseArgs(argv: string[]): { url: string | null; toolNames: Set } { let url: string | null = null; @@ -219,6 +234,34 @@ export async function runHappyMcpStdioBridge(argv: string[]): Promise { ); } + if (toolNames.has(SESSION_JOB_TOOL_NAME)) { + server.registerTool( + SESSION_JOB_TOOL_NAME, + { + description: SESSION_JOB_TOOL_DESCRIPTION, + title: 'Session-Attached Job', + inputSchema: sessionJobInputSchema, + }, + async (args: Record) => { + try { + const client = await ensureHttpClient(); + const response = await client.callTool({ name: SESSION_JOB_TOOL_NAME, arguments: args }); + return response as any; + } catch (error) { + return { + content: [ + { + type: 'text' as const, + text: `Failed to run session_job: ${error instanceof Error ? error.message : String(error)}`, + }, + ], + isError: true, + }; + } + } + ); + } + const pingPeerInputSchema: z.ZodTypeAny = z.object({ sessionIdPrefix: z.string().trim().min(1).describe(SESSION_ID_PREFIX_PARAM_DESCRIPTION), message: z.string().min(1).describe('Message text to deliver to the target session'), diff --git a/cli/src/codex/utils/appServerConfig.test.ts b/cli/src/codex/utils/appServerConfig.test.ts index 2a45177e..9c002c6b 100644 --- a/cli/src/codex/utils/appServerConfig.test.ts +++ b/cli/src/codex/utils/appServerConfig.test.ts @@ -7,7 +7,7 @@ import { codexCollaborationSpawnAgentInstructions, supportsReasoningSummary } from './appServerConfig'; -import { codexSystemPrompt } from './systemPrompt'; +import { getCodexSystemPrompt } from './systemPrompt'; describe('appServerConfig', () => { const mcpServers = { hapi: { command: 'node', args: ['mcp'] } }; @@ -23,7 +23,7 @@ describe('appServerConfig', () => { }); expect(params).not.toHaveProperty('baseInstructions'); - expect(params.developerInstructions).toBe(codexSystemPrompt); + expect(params.developerInstructions).toBe(getCodexSystemPrompt()); }); it('keeps an explicit base instruction override separate from HAPI developer instructions', () => { @@ -35,7 +35,7 @@ describe('appServerConfig', () => { }); expect(params.baseInstructions).toBe('Custom base instructions.'); - expect(params.developerInstructions).toBe(codexSystemPrompt); + expect(params.developerInstructions).toBe(getCodexSystemPrompt()); }); it('applies CLI overrides when permission mode is default', () => { @@ -50,13 +50,13 @@ describe('appServerConfig', () => { expect(params.sandbox).toBe('danger-full-access'); expect(params.approvalPolicy).toBe('never'); expect(params.baseInstructions).toBeUndefined(); - expect(params.developerInstructions).toBe(codexSystemPrompt); + expect(params.developerInstructions).toBe(getCodexSystemPrompt()); expect(params.config).toEqual({ 'mcp_servers.hapi': { command: 'node', args: ['mcp'] }, - developer_instructions: codexSystemPrompt + developer_instructions: getCodexSystemPrompt() }); }); @@ -98,7 +98,7 @@ describe('appServerConfig', () => { } } }, - developer_instructions: codexSystemPrompt + developer_instructions: getCodexSystemPrompt() }); }); @@ -184,13 +184,13 @@ describe('appServerConfig', () => { }); expect(params.baseInstructions).toBeUndefined(); - expect(params.developerInstructions).toBe(`${codexSystemPrompt}\n\nOnly respond in Chinese.`); + expect(params.developerInstructions).toBe(`${getCodexSystemPrompt()}\n\nOnly respond in Chinese.`); expect(params.config).toEqual({ 'mcp_servers.hapi': { command: 'node', args: ['mcp'] }, - developer_instructions: `${codexSystemPrompt}\n\nOnly respond in Chinese.` + developer_instructions: `${getCodexSystemPrompt()}\n\nOnly respond in Chinese.` }); }); @@ -206,7 +206,7 @@ describe('appServerConfig', () => { command: 'node', args: ['mcp'] }, - developer_instructions: codexSystemPrompt, + developer_instructions: getCodexSystemPrompt(), model_reasoning_effort: 'ultra' }); }); @@ -372,7 +372,7 @@ describe('appServerConfig', () => { settings: { model: 'o3', reasoning_effort: 'high', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); expect(params.model).toBeUndefined(); @@ -398,7 +398,7 @@ describe('appServerConfig', () => { settings: { model: 'gpt-5.3-codex-spark', reasoning_effort: 'high', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); }); @@ -562,7 +562,7 @@ describe('appServerConfig', () => { mode: 'default', settings: { model: 'o3', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); }); @@ -582,7 +582,7 @@ describe('appServerConfig', () => { mode: 'default', settings: { model: 'o3', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); }); @@ -601,7 +601,7 @@ describe('appServerConfig', () => { mode: 'default', settings: { model: 'gpt-5', - developer_instructions: withCollaborationInstructions(codexSystemPrompt) + developer_instructions: withCollaborationInstructions(getCodexSystemPrompt()) } }); expect(params.model).toBeUndefined(); diff --git a/cli/src/codex/utils/buildHapiMcpBridge.test.ts b/cli/src/codex/utils/buildHapiMcpBridge.test.ts index ad66b538..f5012502 100644 --- a/cli/src/codex/utils/buildHapiMcpBridge.test.ts +++ b/cli/src/codex/utils/buildHapiMcpBridge.test.ts @@ -14,8 +14,8 @@ vi.mock('@/claude/utils/startHappyServer', () => ({ return { url: 'http://127.0.0.1:43006/', toolNames: options.skillLookup - ? ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'skill_lookup'] - : ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer'], + ? ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'session_job', 'skill_lookup'] + : ['change_title', 'display_image', 'display_video', 'display_media', 'list_peers', 'ping_peer', 'inspect_peer', 'spawn_peer', 'session_job'], stop: vi.fn() } }) @@ -73,16 +73,17 @@ describe('buildHapiMcpBridge skill lookup config', () => { '--url', 'http://127.0.0.1:43006/', '--tools', - 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,skill_lookup', + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,session_job,skill_lookup', '--hapi-session-id', 'hub-session-1', ]) expect(bridge.mcpServers.hapi.tools).toEqual({ - change_title: { approval_mode: 'approve' }, display_image: { approval_mode: 'prompt' }, display_video: { approval_mode: 'prompt' }, display_media: { approval_mode: 'prompt' }, + change_title: { approval_mode: 'approve' }, list_peers: { approval_mode: 'approve' }, + session_job: { approval_mode: 'approve' }, skill_lookup: { approval_mode: 'approve' } }) }) @@ -95,16 +96,17 @@ describe('buildHapiMcpBridge skill lookup config', () => { '--url', 'http://127.0.0.1:43006/', '--tools', - 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer', + 'change_title,display_image,display_video,display_media,list_peers,ping_peer,inspect_peer,spawn_peer,session_job', '--hapi-session-id', 'hub-session-1', ]) expect(bridge.mcpServers.hapi.tools).toEqual({ - change_title: { approval_mode: 'approve' }, display_image: { approval_mode: 'prompt' }, display_video: { approval_mode: 'prompt' }, display_media: { approval_mode: 'prompt' }, - list_peers: { approval_mode: 'approve' } + change_title: { approval_mode: 'approve' }, + list_peers: { approval_mode: 'approve' }, + session_job: { approval_mode: 'approve' } }) }) diff --git a/cli/src/codex/utils/buildHapiMcpBridge.ts b/cli/src/codex/utils/buildHapiMcpBridge.ts index 085e41d6..d41928dd 100644 --- a/cli/src/codex/utils/buildHapiMcpBridge.ts +++ b/cli/src/codex/utils/buildHapiMcpBridge.ts @@ -124,6 +124,10 @@ export async function buildHapiMcpBridge( approval_mode: 'approve' }; } + // Own-session progress meter (tiann/hapi#1404) — hub REST, not peer inject. + tools.session_job = { + approval_mode: 'approve' + }; // ping_peer / inspect_peer / spawn_peer are registered on the HTTP MCP // server / stdio bridge, but are not auto-approved: they target another // session (resume + inject, read peer histories, or create + inject). diff --git a/cli/src/codex/utils/systemPrompt.ts b/cli/src/codex/utils/systemPrompt.ts index 8ed6b658..cdab5534 100644 --- a/cli/src/codex/utils/systemPrompt.ts +++ b/cli/src/codex/utils/systemPrompt.ts @@ -9,6 +9,7 @@ import { trimIdent } from '@/utils/trimIdent'; import { buildSessionCitationSteerInstruction, SESSION_CITATION_DISABLED_STEER } from '@hapi/protocol/sessionCitation'; import { DISPLAY_IMAGE_PROMPT_CODEX, DISPLAY_MEDIA_PROMPT_CODEX, DISPLAY_VIDEO_PROMPT_CODEX } from '@/modules/common/displayImagePrompt'; import { isPeerToolsDisabled } from '@/modules/common/peerTools'; +import { withSessionJobInstruction } from '@/modules/common/sessionJobInstruction'; import { withSessionSummaryInstruction } from '@/modules/common/sessionSummaryInstruction'; /** @@ -38,7 +39,7 @@ export const TITLE_INSTRUCTION = trimIdent(` * Session-summary contract is resolved at call time (hub toggle / env). */ export function getCodexSystemPrompt(env: NodeJS.ProcessEnv = process.env): string { - return withSessionSummaryInstruction(TITLE_INSTRUCTION, env) + return withSessionSummaryInstruction(withSessionJobInstruction(TITLE_INSTRUCTION), env) } /** Alias kept for existing call sites / tests that expect a string constant name. */ diff --git a/cli/src/commands/job.test.ts b/cli/src/commands/job.test.ts new file mode 100644 index 00000000..7b8a1133 --- /dev/null +++ b/cli/src/commands/job.test.ts @@ -0,0 +1,360 @@ +import { describe, expect, it } from 'vitest' +import { formatJobLine, parseJobArgs } from '@/commands/job' +import { + SessionJobError, + exitCodeForSessionJobError, + resolveSessionByPrefix, + resolveSessionIdForJobCli +} from '@/modules/sessionJob/sessionJob' + +describe('parseJobArgs', () => { + it('parses set with long flags', () => { + const parsed = parseJobArgs([ + 'set', + 'abcd1234', + 'beets', + '--label', + 'beets import', + '--progress=fraction', + '--remaining', + '12', + '--total', + '100', + '--unit=tracks' + ]) + expect(parsed.action).toBe('set') + expect(parsed.sessionIdPrefix).toBe('abcd1234') + expect(parsed.jobKey).toBe('beets') + expect(parsed.label).toBe('beets import') + expect(parsed.progress).toBe('fraction') + expect(parsed.remaining).toBe(12) + expect(parsed.total).toBe(100) + expect(parsed.unit).toBe('tracks') + }) + + it('parses run with command after --', () => { + const parsed = parseJobArgs([ + 'run', + 'sid', + 'drain', + '--label=rsync', + '--progress=unknown', + '--heartbeat-sec=60', + '--', + 'bash', + '-c', + 'echo hi' + ]) + expect(parsed.action).toBe('run') + expect(parsed.label).toBe('rsync') + expect(parsed.progress).toBe('unknown') + expect(parsed.heartbeatSec).toBe(60) + expect(parsed.command).toEqual(['bash', '-c', 'echo hi']) + }) + + it('parses wake-on-terminal flags', () => { + const parsed = parseJobArgs([ + 'run', + 'sid', + 'drain', + '--label=rsync', + '--progress=unknown', + '--wake-on-terminal', + '--wake-prompt=Next chunk', + '--', + 'true' + ]) + expect(parsed.wakeOnTerminal).toBe(true) + expect(parsed.wakePrompt).toBe('Next chunk') + expect(parsed.command).toEqual(['true']) + }) + + it('requires --progress on run/set and stamps until mode', () => { + expect(() => parseJobArgs([ + 'run', + 'sid', + 'drain', + '--label=rsync', + '--', + 'true' + ])).toThrow(/requires --progress/) + + const until = parseJobArgs([ + 'run', + 'sid', + 'dogfood', + '--label=countdown', + '--progress=until', + '--until=2099-01-01T00:00:00.000Z', + '--', + 'sleep', + '1' + ]) + expect(until.progress).toBe('until') + expect(until.untilMs).toBe(Date.parse('2099-01-01T00:00:00.000Z')) + expect(until.remaining).toBeGreaterThan(0) + expect(until.total).toBe(until.remaining) + expect(until.unit).toBe('s') + }) + + it('parses --wake-on-terminal and --wake-prompt on update (dogfood arm-later)', () => { + const parsed = parseJobArgs([ + 'update', + 'sid', + 'oos-llm-from-studio', + '--done', + '1', + '--total', + '2', + '--wake-on-terminal', + '--wake-prompt', + 'delete studio dupes' + ]) + expect(parsed.action).toBe('update') + expect(parsed.wakeOnTerminal).toBe(true) + expect(parsed.wakePrompt).toBe('delete studio dupes') + expect(parsed.done).toBe(1) + expect(parsed.total).toBe(2) + }) + + it('rejects --wake-prompt without a value', () => { + expect(() => parseJobArgs([ + 'update', + 'sid', + 'k', + '--wake-on-terminal', + '--wake-prompt' + ])).toThrow(/--wake-prompt requires a value/) + }) + + it('rejects bad status', () => { + expect(() => parseJobArgs(['update', 's', 'k', '--status', 'nope'])).toThrow(SessionJobError) + }) + + it('parses --started-at for set', () => { + const parsed = parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--started-at=1785304595000' + ]) + expect(parsed.startedAt).toBe(1_785_304_595_000) + }) + + it('allows --started-at on until run and stamps full-window total', () => { + const until = Date.now() + 48 * 3600 * 1000 + const windowStart = until - 48 * 3600 * 1000 + const parsed = parseJobArgs([ + 'run', + 'sid', + 'dogfood', + '--label=countdown', + '--progress=until', + `--until=${until}`, + `--started-at=${windowStart}`, + '--', + 'sleep', + '999999' + ]) + expect(parsed.startedAt).toBe(windowStart) + expect(parsed.total).toBe(48 * 3600) + expect(parsed.remaining).toBeLessThanOrEqual(parsed.total!) + expect(parsed.remaining).toBeGreaterThan(47 * 3600) + }) + + it('rejects numeric sleep under --progress unknown', () => { + expect(() => parseJobArgs([ + 'run', + 'sid', + 'dogfood', + '--label=countdown', + '--progress=unknown', + '--', + 'sleep', + '150747' + ])).toThrow(/--progress until/) + }) + + it('rejects --started-at on update', () => { + expect(() => parseJobArgs([ + 'update', + 'sid', + 'beets', + '--started-at=1785304595000' + ])).toThrow(/--started-at is only valid with job set/) + }) + + it('rejects --started-at on unknown run', () => { + expect(() => parseJobArgs([ + 'run', + 'sid', + 'k', + '--label=x', + '--progress=unknown', + '--started-at=1785304595000', + '--', + 'true' + ])).toThrow(/only valid with --progress until/) + }) + + it('rejects --heartbeat-sec on non-run actions', () => { + expect(() => parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--heartbeat-sec=300' + ])).toThrow(/--heartbeat-sec is only valid with job run/) + expect(() => parseJobArgs([ + 'update', + 'sid', + 'beets', + '--heartbeat-sec=60' + ])).toThrow(/--heartbeat-sec is only valid with job run/) + }) + + it.each([ + ['list', ['list', 'sid', '--label=x'], /job list does not accept mutation flags/], + ['clear+status', ['clear', 'sid', 'beets', '--status', 'completed'], /job clear only accepts --expected-run-id/], + ['run+status', ['run', 'sid', 'beets', '--label=x', '--progress=unknown', '--status', 'completed', '--', 'true'], /--status is not valid with job run/], + ['clear+cmd', ['clear', 'sid', 'beets', '--', 'rm', '-rf', '/'], /-- is only valid with job run/] + ] as const)('rejects unsupported flags for %s', (_name, argv, pattern) => { + expect(() => parseJobArgs([...argv])).toThrow(pattern) + }) + + it('parses --clear-remaining as null for update patches', () => { + const parsed = parseJobArgs([ + 'update', + 'sid', + 'beets', + '--clear-remaining', + '--done', + '3', + '--total', + '10' + ]) + expect(parsed.remaining).toBeNull() + expect(parsed.done).toBe(3) + expect(parsed.total).toBe(10) + }) + + it('parses --run-id on set and --expected-run-id on update/clear', () => { + const setParsed = parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--run-id=11111111-1111-1111-1111-111111111111' + ]) + expect(setParsed.runId).toBe('11111111-1111-1111-1111-111111111111') + + const updateParsed = parseJobArgs([ + 'update', + 'sid', + 'beets', + '--remaining=9', + '--expected-run-id=11111111-1111-1111-1111-111111111111' + ]) + expect(updateParsed.expectedRunId).toBe('11111111-1111-1111-1111-111111111111') + + const clearParsed = parseJobArgs([ + 'clear', + 'sid', + 'beets', + '--expected-run-id=11111111-1111-1111-1111-111111111111' + ]) + expect(clearParsed.expectedRunId).toBe('11111111-1111-1111-1111-111111111111') + }) + + it('rejects --run-id on update and --expected-run-id on set', () => { + expect(() => parseJobArgs([ + 'update', + 'sid', + 'beets', + '--run-id=11111111-1111-1111-1111-111111111111' + ])).toThrow(/--run-id is only valid with job set/) + expect(() => parseJobArgs([ + 'set', + 'sid', + 'beets', + '--label=beets', + '--progress=unknown', + '--expected-run-id=11111111-1111-1111-1111-111111111111' + ])).toThrow(/--expected-run-id is only valid with job update or clear/) + }) +}) + +describe('resolveSessionByPrefix', () => { + const sessions = [ + { id: 'aaaaaaaa-1111-1111-1111-111111111111' }, + { id: 'bbbbbbbb-2222-2222-2222-222222222222' }, + { id: 'bbbbcccc-3333-3333-3333-333333333333' } + ] + + it('matches exact id', () => { + expect(resolveSessionByPrefix(sessions, sessions[0]!.id).id).toBe(sessions[0]!.id) + }) + + it('matches unique prefix', () => { + expect(resolveSessionByPrefix(sessions, 'aaaa').id).toBe(sessions[0]!.id) + }) + + it('errors on ambiguous prefix', () => { + expect(() => resolveSessionByPrefix(sessions, 'bbbb')).toThrow(/matches 2 sessions/) + }) + + it('errors on no match', () => { + expect(() => resolveSessionByPrefix(sessions, 'zzzz')).toThrow(/no session matching/) + }) +}) + +describe('resolveSessionIdForJobCli', () => { + it('passes a full UUID through when missing from the session list', () => { + const deleted = 'cccccccc-4444-4444-4444-444444444444' + expect(resolveSessionIdForJobCli([], deleted)).toBe(deleted) + }) + + it('still errors for a non-uuid prefix with no list match', () => { + expect(() => resolveSessionIdForJobCli([], 'deadbeef')).toThrow(/no session matching/) + }) +}) + +describe('exitCodeForSessionJobError', () => { + it('maps codes', () => { + expect(exitCodeForSessionJobError(new SessionJobError('bad_args', 'x'))).toBe(2) + expect(exitCodeForSessionJobError(new SessionJobError('auth_failed', 'x'))).toBe(3) + expect(exitCodeForSessionJobError(new SessionJobError('not_found', 'x'))).toBe(4) + expect(exitCodeForSessionJobError(new SessionJobError('ambiguous', 'x'))).toBe(5) + expect(exitCodeForSessionJobError(new SessionJobError('request_failed', 'x'))).toBe(1) + }) +}) + +describe('formatJobLine terminal sanitization', () => { + it('strips ANSI/OSC and C0 controls from job text fields', () => { + const line = formatJobLine({ + key: 'beets\u0007', + label: '\u001b[31mimport\u001b[0m', + status: 'running', + unit: 'tracks\u001b]8;;http://evil\u0007', + detail: 'phase\u001b]52;c;QUFB\u0007done\u009devil\u009c', + runId: 'run-\u001b[1mid\u001b[0m', + remaining: 3, + heartbeatAt: Date.now() - 5_000, + startedAt: Date.now() - 60_000 + }, { includeTiming: true }) + expect(line).not.toMatch(/\u001b/) + expect(line).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/) + expect(line).toContain('beets') + expect(line).toContain('import') + expect(line).toContain('3 tracks left') + expect(line).toContain('phase') + expect(line).toContain('done') + expect(line).toContain('runId run-id') + expect(line).not.toMatch(/http:\/\/evil/) + expect(line).not.toMatch(/QUFB/) + }) +}) diff --git a/cli/src/commands/job.ts b/cli/src/commands/job.ts new file mode 100644 index 00000000..7e209f25 --- /dev/null +++ b/cli/src/commands/job.ts @@ -0,0 +1,628 @@ +import chalk from 'chalk' +import { initializeToken } from '@/ui/tokenInit' +import type { AttachedJobPatch, AttachedJobUpsert } from '@hapi/protocol' +import { + SessionJobError, + SESSION_JOB_REMAINING_ZERO_HINT, + clearSessionJob, + exitCodeForSessionJobError, + formatSessionJobNotFoundHint, + listSessionJobs, + setSessionJob, + updateSessionJob +} from '@/modules/sessionJob/sessionJob' +import { formatJobLine } from '@/modules/sessionJob/formatJobLine' +import { runSessionJob } from '@/modules/sessionJob/runSessionJob' +import { + assertCreateProgressMode, + assertNumericSleepUsesUntil, + type JobProgressMode, + parseUntilTimestamp, + stampUntilProgress +} from '@/modules/sessionJob/jobProgressMode' +import type { CommandDefinition } from './types' + +export { formatJobLine, terminalText } from '@/modules/sessionJob/formatJobLine' + +export type ParsedJobArgs = { + help: boolean + action?: 'set' | 'update' | 'clear' | 'list' | 'run' + sessionIdPrefix?: string + jobKey?: string + label?: string + status?: 'running' | 'completed' | 'failed' + progress?: JobProgressMode + untilMs?: number + done?: number | null + total?: number | null + remaining?: number | null + unit?: string | null + detail?: string | null + startedAt?: number + heartbeatSec?: number + runId?: string + expectedRunId?: string + wakeOnTerminal?: boolean + wakePrompt?: string + command?: string[] +} + +function showHelp(): void { + console.log(` +${chalk.bold('hapi job')} - Attach long-running work to a HAPI session (tiann/hapi#1404) + +${chalk.bold('When to use:')} + Work that outlives the agent (batch / long scripts / external daemons) + while the session may be idle. Not thinking progress or in-agent background tools. + +${chalk.bold('Agent contract:')} + Prefer ${chalk.bold('hapi job run')} — it heartbeats for you and marks completed/failed on exit. + An idle agent cannot heartbeat; set-once jobs go amber after ~15m. + ${chalk.bold('run/set require --progress')} unknown|fraction|until (explicit affordance). + unknown → indeterminate stripes (no counts). fraction → remaining+total or done+total. + until → --until ; remaining/total derived (job run heartbeats re-stamp remaining). + Fraction without a continuous updater freezes under heartbeats — keep + ${chalk.bold('job update')}ing done/remaining (or use --progress unknown). + Numeric ${chalk.bold('sleep N')} requires ${chalk.bold('--progress until')}. + Never invent a fake percent. + Do not wrap hapi-restart-hub / stack-switch in job run (hub down → zombie running meter). + +${chalk.bold('Usage:')} + hapi job run --label --progress unknown|fraction|until […] -- … + hapi job set --label --progress unknown|fraction|until […] + hapi job update [--expected-run-id UUID] [--remaining N] [--done N] [--total N] [--status running|completed|failed] [--wake-on-terminal] [--wake-prompt ] [--detail ...] + [--clear-remaining|--clear-done|--clear-total|--clear-unit|--clear-detail] + hapi job clear [--expected-run-id UUID] + hapi job list + +${chalk.bold('Wake on terminal (tiann/hapi#1489, default off):')} + --wake-on-terminal When the job hits completed/failed, hub resumes the owning + session and posts a prompt so an idle agent can continue. + --wake-prompt TEXT Optional prescription appended to the wake message. + +${chalk.bold('Progress UI (--progress):')} + unknown → "running · 2h" + subtle indeterminate striped bar (no %) + fraction → remaining+total or done+total → fill bar + until → determinate countdown from --until (unit s) + elapsed always from startedAt (wall clock) — never an ETA field + --clear-remaining → drop leftover meter so done/total can take over (PATCH null) + +${chalk.bold('startedAt / elapsed:')} + Prefer ${chalk.bold('update')} for heartbeats/progress so the clock is never wiped. + PATCH rejects startedAt. PUT/set without --started-at keeps the existing clock. + Late attach or wrong clock: ${chalk.bold('set --started-at ')} (explicit PUT), + or clear then set with --started-at (works on older hubs that ignored PUT corrections). + Mid-window countdown re-attach: ${chalk.bold('run --progress until --until … --started-at ')} + so heartbeat total stays until−start (not "time left from this restart"). + Manual babysitter wrappers: mint one UUID per run (${chalk.bold('set --run-id ')}), + then pass the same value on every heartbeat (${chalk.bold('update --expected-run-id ')}) + and on clear (${chalk.bold('clear --expected-run-id ')}) so a key-reuse cannot + steal the older wrapper's PATCHes or DELETE the newer run. + +${chalk.bold('Notes:')} + Hub-persisted. Prefer "$HAPI_SESSION_ID" when it matches the operator chat row + (/sessions/ in the web URL). Remote Cursor runner may export a worker-row id — + pass that URL uuid explicitly (see docs/guide/session-jobs.md). + Needs a hub/CLI that includes the job subcommand (soup / feat build — not every npm release). + Job key: 1-128 chars, alnum / . _ - + Session lookup prefers exact id; prefix scan is the 500 most-recently-updated sessions. + Docs: docs/guide/session-jobs.md + +${chalk.bold('Env:')} + HAPI_API_URL / CLI_API_TOKEN (or ~/.hapi/settings.json via \`hapi auth login\`) +`) +} + +function parseOptionalNumber(flag: string, value: string | undefined): number { + if (value === undefined) { + throw new SessionJobError('bad_args', `${flag} requires a number`) + } + const n = Number(value) + if (!Number.isFinite(n)) { + throw new SessionJobError('bad_args', `${flag} must be a number`) + } + return n +} + +export function parseJobArgs(args: string[]): ParsedJobArgs { + const result: ParsedJobArgs = { help: false } + const dashDash = args.indexOf('--') + const flagArgs = dashDash >= 0 ? args.slice(0, dashDash) : args + if (dashDash >= 0) { + result.command = args.slice(dashDash + 1) + } + + for (let i = 0; i < flagArgs.length; i++) { + const arg = flagArgs[i]! + if (arg === '--help' || arg === '-h') { + result.help = true + continue + } + if (arg === '--label') { + result.label = flagArgs[++i] + if (!result.label) throw new SessionJobError('bad_args', '--label requires a value') + continue + } + if (arg.startsWith('--label=')) { + result.label = arg.slice('--label='.length) + continue + } + if (arg === '--status') { + const value = flagArgs[++i] + if (value !== 'running' && value !== 'completed' && value !== 'failed') { + throw new SessionJobError('bad_args', '--status must be running|completed|failed') + } + result.status = value + continue + } + if (arg.startsWith('--status=')) { + const value = arg.slice('--status='.length) + if (value !== 'running' && value !== 'completed' && value !== 'failed') { + throw new SessionJobError('bad_args', '--status must be running|completed|failed') + } + result.status = value + continue + } + if (arg === '--done') { + result.done = parseOptionalNumber('--done', flagArgs[++i]) + continue + } + if (arg.startsWith('--done=')) { + result.done = parseOptionalNumber('--done', arg.slice('--done='.length)) + continue + } + if (arg === '--total') { + result.total = parseOptionalNumber('--total', flagArgs[++i]) + continue + } + if (arg.startsWith('--total=')) { + result.total = parseOptionalNumber('--total', arg.slice('--total='.length)) + continue + } + if (arg === '--remaining') { + result.remaining = parseOptionalNumber('--remaining', flagArgs[++i]) + continue + } + if (arg.startsWith('--remaining=')) { + result.remaining = parseOptionalNumber('--remaining', arg.slice('--remaining='.length)) + continue + } + if (arg === '--unit') { + result.unit = flagArgs[++i] + if (!result.unit) throw new SessionJobError('bad_args', '--unit requires a value') + continue + } + if (arg.startsWith('--unit=')) { + result.unit = arg.slice('--unit='.length) + continue + } + if (arg === '--detail') { + result.detail = flagArgs[++i] + if (result.detail === undefined) throw new SessionJobError('bad_args', '--detail requires a value') + continue + } + if (arg.startsWith('--detail=')) { + result.detail = arg.slice('--detail='.length) + continue + } + if (arg === '--heartbeat-sec') { + result.heartbeatSec = parseOptionalNumber('--heartbeat-sec', flagArgs[++i]) + continue + } + if (arg.startsWith('--heartbeat-sec=')) { + result.heartbeatSec = parseOptionalNumber('--heartbeat-sec', arg.slice('--heartbeat-sec='.length)) + continue + } + if (arg === '--started-at') { + result.startedAt = parseOptionalNumber('--started-at', flagArgs[++i]) + continue + } + if (arg.startsWith('--started-at=')) { + result.startedAt = parseOptionalNumber('--started-at', arg.slice('--started-at='.length)) + continue + } + if (arg === '--clear-remaining') { + result.remaining = null + continue + } + if (arg === '--clear-done') { + result.done = null + continue + } + if (arg === '--clear-total') { + result.total = null + continue + } + if (arg === '--clear-unit') { + result.unit = null + continue + } + if (arg === '--clear-detail') { + result.detail = null + continue + } + if (arg === '--run-id') { + result.runId = flagArgs[++i] + if (!result.runId) throw new SessionJobError('bad_args', '--run-id requires a value') + continue + } + if (arg.startsWith('--run-id=')) { + result.runId = arg.slice('--run-id='.length) + if (!result.runId) throw new SessionJobError('bad_args', '--run-id requires a value') + continue + } + if (arg === '--expected-run-id') { + result.expectedRunId = flagArgs[++i] + if (!result.expectedRunId) { + throw new SessionJobError('bad_args', '--expected-run-id requires a value') + } + continue + } + if (arg.startsWith('--expected-run-id=')) { + result.expectedRunId = arg.slice('--expected-run-id='.length) + if (!result.expectedRunId) { + throw new SessionJobError('bad_args', '--expected-run-id requires a value') + } + continue + } + if (arg === '--wake-on-terminal') { + result.wakeOnTerminal = true + continue + } + if (arg === '--wake-prompt') { + result.wakePrompt = flagArgs[++i] + if (result.wakePrompt === undefined) { + throw new SessionJobError('bad_args', '--wake-prompt requires a value') + } + continue + } + if (arg.startsWith('--wake-prompt=')) { + result.wakePrompt = arg.slice('--wake-prompt='.length) + continue + } + if (arg === '--progress') { + const value = flagArgs[++i] + if (value !== 'unknown' && value !== 'fraction' && value !== 'until') { + throw new SessionJobError('bad_args', '--progress must be unknown|fraction|until') + } + result.progress = value + continue + } + if (arg.startsWith('--progress=')) { + const value = arg.slice('--progress='.length) + if (value !== 'unknown' && value !== 'fraction' && value !== 'until') { + throw new SessionJobError('bad_args', '--progress must be unknown|fraction|until') + } + result.progress = value + continue + } + if (arg === '--until') { + const value = flagArgs[++i] + if (value === undefined) { + throw new SessionJobError('bad_args', '--until requires a value') + } + result.untilMs = parseUntilTimestamp(value) + continue + } + if (arg.startsWith('--until=')) { + result.untilMs = parseUntilTimestamp(arg.slice('--until='.length)) + continue + } + if (arg.startsWith('-')) { + throw new SessionJobError('bad_args', `unexpected flag: ${arg}`) + } + if (!result.action) { + if ( + arg !== 'set' + && arg !== 'update' + && arg !== 'clear' + && arg !== 'list' + && arg !== 'run' + ) { + throw new SessionJobError('bad_args', `unknown action '${arg}' (set|update|clear|list|run)`) + } + result.action = arg + continue + } + if (!result.sessionIdPrefix) { + result.sessionIdPrefix = arg + continue + } + if (!result.jobKey && result.action !== 'list') { + result.jobKey = arg + continue + } + throw new SessionJobError('bad_args', `unexpected arg: ${arg}`) + } + + if (result.startedAt !== undefined && result.action !== undefined) { + if (result.action === 'set') { + // ok — correct historical clock / window start + } else if (result.action === 'run' && result.progress === 'until') { + // ok — mid-window countdown: heartbeats keep total = until - startedAt + } else if (result.action === 'run') { + throw new SessionJobError( + 'bad_args', + '--started-at on job run is only valid with --progress until ' + + '(pass the window start so total stays honest across re-attach)' + ) + } else { + throw new SessionJobError( + 'bad_args', + '--started-at is only valid with job set, or job run --progress until' + ) + } + } + + if ( + result.heartbeatSec !== undefined + && result.action !== undefined + && result.action !== 'run' + ) { + throw new SessionJobError('bad_args', '--heartbeat-sec is only valid with job run') + } + + const clearUsed = + result.done === null + || result.total === null + || result.remaining === null + || result.unit === null + || result.detail === null + if (clearUsed && result.action !== undefined && result.action !== 'update') { + throw new SessionJobError('bad_args', '--clear-* flags are only valid with job update') + } + if (result.runId !== undefined && result.action !== undefined && result.action !== 'set') { + throw new SessionJobError('bad_args', '--run-id is only valid with job set') + } + if ( + result.expectedRunId !== undefined + && result.action !== undefined + && result.action !== 'update' + && result.action !== 'clear' + ) { + throw new SessionJobError('bad_args', '--expected-run-id is only valid with job update or clear') + } + + const mutationFieldsUsed = [ + result.label, + result.status, + result.done, + result.total, + result.remaining, + result.unit, + result.detail + ].some((value) => value !== undefined) + + if (result.action === 'list' && mutationFieldsUsed) { + throw new SessionJobError('bad_args', 'job list does not accept mutation flags') + } + if (result.action === 'clear' && mutationFieldsUsed) { + throw new SessionJobError('bad_args', 'job clear only accepts --expected-run-id') + } + if (result.action === 'run' && result.status !== undefined) { + throw new SessionJobError('bad_args', '--status is not valid with job run') + } + + if ( + result.command !== undefined + && result.action !== undefined + && result.action !== 'run' + ) { + throw new SessionJobError('bad_args', '-- is only valid with job run') + } + + if ( + (result.progress !== undefined || result.untilMs !== undefined) + && result.action !== undefined + && result.action !== 'run' + && result.action !== 'set' + ) { + throw new SessionJobError('bad_args', '--progress/--until are only valid with job run or set') + } + + if (result.action === 'run' || result.action === 'set') { + assertCreateProgressMode(result.action, { + progress: result.progress, + untilMs: result.untilMs, + done: result.done, + total: result.total, + remaining: result.remaining + }) + if (result.progress === 'until' && result.untilMs !== undefined) { + const startedAt = result.startedAt ?? Date.now() + const stamped = stampUntilProgress(result.untilMs, Date.now(), startedAt) + result.remaining = stamped.remaining + result.total = stamped.total + result.unit = result.unit ?? stamped.unit + } + if (result.action === 'run' && result.command) { + assertNumericSleepUsesUntil(result.progress!, result.command) + } + } + + return result +} + +function formatCliJobLine(job: { + key: string + label: string + status: string + done?: number + total?: number + remaining?: number + unit?: string + detail?: string + runId?: string + heartbeatAt: number + startedAt: number +}): string { + return formatJobLine(job, { includeTiming: true }) +} + +export async function handleJobCommand(args: string[]): Promise { + const parsed = parseJobArgs(args) + if (parsed.help || !parsed.action) { + showHelp() + if (!parsed.action && !parsed.help) { + throw new SessionJobError('bad_args', 'missing action; usage: hapi job set|update|clear|list|run ...') + } + return + } + + await initializeToken() + + if (!parsed.sessionIdPrefix) { + showHelp() + throw new SessionJobError('bad_args', 'missing session id') + } + + if (parsed.action === 'list') { + const result = await listSessionJobs({ sessionIdPrefix: parsed.sessionIdPrefix }) + console.log(`session ${result.sessionId}`) + if (result.jobs.length === 0) { + console.log('(no jobs)') + return + } + for (const job of result.jobs) { + const mark = result.primary?.key === job.key ? '*' : ' ' + console.log(`${mark} ${formatCliJobLine(job)}`) + } + return + } + + if (!parsed.jobKey) { + throw new SessionJobError('bad_args', 'missing job key') + } + + if (parsed.action === 'clear') { + const result = await clearSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + ...(parsed.expectedRunId !== undefined + ? { expectedRunId: parsed.expectedRunId } + : {}) + }) + console.log(`cleared ${parsed.jobKey} on ${result.sessionId}`) + return + } + + if (parsed.action === 'set') { + if (!parsed.label) { + throw new SessionJobError('bad_args', 'set requires --label') + } + if (parsed.startedAt !== undefined && !Number.isFinite(parsed.startedAt)) { + throw new SessionJobError('bad_args', '--started-at must be epoch milliseconds') + } + // --progress already asserted + until stamped in parseJobArgs + const body: AttachedJobUpsert = { + label: parsed.label, + status: parsed.status ?? 'running', + ...(typeof parsed.done === 'number' ? { done: parsed.done } : {}), + ...(typeof parsed.total === 'number' ? { total: parsed.total } : {}), + ...(typeof parsed.remaining === 'number' ? { remaining: parsed.remaining } : {}), + ...(typeof parsed.unit === 'string' ? { unit: parsed.unit } : {}), + ...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}), + ...(parsed.startedAt !== undefined ? { startedAt: parsed.startedAt } : {}), + ...(parsed.runId !== undefined ? { runId: parsed.runId } : {}), + ...(parsed.wakeOnTerminal !== undefined ? { wakeOnTerminal: parsed.wakeOnTerminal } : {}), + ...(parsed.wakePrompt !== undefined ? { wakePrompt: parsed.wakePrompt } : {}) + } + const result = await setSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + body + }) + console.log(`set ${formatCliJobLine(result.job)}`) + return + } + + if (parsed.action === 'run') { + if (!parsed.label) { + throw new SessionJobError('bad_args', 'run requires --label') + } + if (!parsed.command || parsed.command.length === 0) { + throw new SessionJobError('bad_args', 'run requires a command after --') + } + if (parsed.startedAt !== undefined && !Number.isFinite(parsed.startedAt)) { + throw new SessionJobError('bad_args', '--started-at must be epoch milliseconds') + } + const exitCode = await runSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + label: parsed.label, + command: parsed.command, + ...(parsed.heartbeatSec !== undefined + ? { heartbeatMs: Math.max(5, parsed.heartbeatSec) * 1000 } + : {}), + ...(typeof parsed.done === 'number' ? { done: parsed.done } : {}), + ...(typeof parsed.total === 'number' ? { total: parsed.total } : {}), + ...(typeof parsed.remaining === 'number' ? { remaining: parsed.remaining } : {}), + ...(typeof parsed.unit === 'string' ? { unit: parsed.unit } : {}), + ...(typeof parsed.detail === 'string' ? { detail: parsed.detail } : {}), + ...(parsed.untilMs !== undefined ? { untilMs: parsed.untilMs } : {}), + ...(parsed.startedAt !== undefined ? { startedAtMs: parsed.startedAt } : {}), + ...(parsed.wakeOnTerminal !== undefined ? { wakeOnTerminal: parsed.wakeOnTerminal } : {}), + ...(parsed.wakePrompt !== undefined ? { wakePrompt: parsed.wakePrompt } : {}) + }) + if (exitCode !== 0) { + process.exitCode = exitCode + } + console.log(`run finished exit=${exitCode} job=${parsed.jobKey}`) + return + } + + // update + const body: AttachedJobPatch = { + ...(parsed.label !== undefined ? { label: parsed.label } : {}), + ...(parsed.status !== undefined ? { status: parsed.status } : {}), + ...(parsed.done !== undefined ? { done: parsed.done } : {}), + ...(parsed.total !== undefined ? { total: parsed.total } : {}), + ...(parsed.remaining !== undefined ? { remaining: parsed.remaining } : {}), + ...(parsed.unit !== undefined ? { unit: parsed.unit } : {}), + ...(parsed.detail !== undefined ? { detail: parsed.detail } : {}), + ...(parsed.expectedRunId !== undefined ? { expectedRunId: parsed.expectedRunId } : {}), + ...(parsed.wakeOnTerminal !== undefined ? { wakeOnTerminal: parsed.wakeOnTerminal } : {}), + ...(parsed.wakePrompt !== undefined ? { wakePrompt: parsed.wakePrompt } : {}) + } + // Empty body is a heartbeat-only update; hub stamps heartbeatAt. + let result + try { + result = await updateSessionJob({ + sessionIdPrefix: parsed.sessionIdPrefix, + jobKey: parsed.jobKey, + body + }) + } catch (error) { + if (error instanceof SessionJobError && error.code === 'not_found') { + throw new SessionJobError('not_found', formatSessionJobNotFoundHint('update')) + } + throw error + } + console.log(`updated ${formatCliJobLine(result.job)}`) + if (result.job.status === 'running' && result.job.remaining === 0) { + console.error(chalk.yellow('hapi job hint:'), SESSION_JOB_REMAINING_ZERO_HINT) + } +} + +export const jobCommand: CommandDefinition = { + name: 'job', + requiresRuntimeAssets: false, + run: async ({ commandArgs }) => { + try { + await handleJobCommand(commandArgs) + } catch (error) { + if (error instanceof SessionJobError) { + console.error(chalk.red('hapi job:'), error.message) + process.exit(exitCodeForSessionJobError(error)) + } + console.error( + chalk.red('hapi job:'), + error instanceof Error ? error.message : 'Unknown error' + ) + if (process.env.DEBUG) { + console.error(error) + } + process.exit(1) + } + } +} diff --git a/cli/src/commands/registry.ts b/cli/src/commands/registry.ts index 8fa70881..b396166c 100644 --- a/cli/src/commands/registry.ts +++ b/cli/src/commands/registry.ts @@ -24,6 +24,7 @@ import { inspectPeerCommand } from './inspectPeer' import { spawnPeerCommand } from './spawnPeer' import { usageCommand } from './usage' import { setModeCommand } from './setMode' +import { jobCommand } from './job' import type { CommandContext, CommandDefinition } from './types' // Gemini CLI was sunset (Google stopped serving the consumer Gemini CLI on @@ -68,6 +69,7 @@ const COMMANDS: CommandDefinition[] = [ inspectPeerCommand, spawnPeerCommand, setModeCommand, + jobCommand, usageCommand ] diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts index 3911159a..29c632c6 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.test.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.test.ts @@ -44,7 +44,7 @@ const harness = vi.hoisted(() => ({ stderrErrorHandler: null as ((error: { type: string; message: string; raw?: string }) => void) | null, disconnectError: null as Error | null, overlayCleanup: null as ReturnType | null, - agentActivityListener: null as ((thinking: boolean) => void) | null, + agentActivityListener: null as ((thinking: boolean, source?: string) => void) | null, titleSyncControllers: [] as unknown[], titleSyncRegistered: [] as unknown[], onChangeTitle: null as ((title: string) => void) | null, @@ -235,7 +235,7 @@ vi.mock('./utils/cursorAcpBackend', () => ({ harness.stderrErrorHandler = handler ?? null; }), setUsageUpdateListener: vi.fn(), - setAgentActivityListener: vi.fn((listener: ((thinking: boolean) => void) | null) => { + setAgentActivityListener: vi.fn((listener: ((thinking: boolean, source?: string) => void) | null) => { harness.agentActivityListener = listener; }), setSessionInfoUpdateListener: vi.fn(), @@ -776,7 +776,7 @@ describe('cursorAcpRemoteLauncher', () => { expect(session.model).toBe('auto'); }); - it('applies harness thinking transitions once per edge (#1470)', async () => { + it('ignores ambient state_update_running without a prompt; still applies idle/permission (#1553)', async () => { const keepAlive = vi.fn(); const queue = new MessageQueue2(() => 'mode'); const client = { @@ -797,20 +797,74 @@ describe('cursorAcpRemoteLauncher', () => { permissionMode: 'default' }); session.onSessionFoundWithProtocol = vi.fn(); - // Keep the launcher in the main loop long enough to wire the listener. const runPromise = cursorAcpRemoteLauncher(session); await vi.waitFor(() => expect(harness.agentActivityListener).not.toBeNull()); expect(session.thinking).toBe(false); keepAlive.mockClear(); - harness.agentActivityListener!(true); - harness.agentActivityListener!(true); - harness.agentActivityListener!(false); - + // Ambient Cursor chatter while queue-idle must not float Working. + harness.agentActivityListener!(true, 'state_update_running'); expect(session.thinking).toBe(false); - expect(keepAlive.mock.calls.map((call) => call[0])).toEqual([true, false]); + expect(keepAlive).not.toHaveBeenCalled(); + harness.agentActivityListener!(true, 'permission'); + expect(session.thinking).toBe(true); + expect(keepAlive).toHaveBeenCalled(); + + keepAlive.mockClear(); + harness.agentActivityListener!(false, 'state_update_idle'); + expect(session.thinking).toBe(false); + expect(keepAlive).toHaveBeenCalled(); + + queue.close(); + await runPromise; + }); + + it('applies state_update_running while a prompt is in flight (#1470)', async () => { + const keepAlive = vi.fn(); + const queue = new MessageQueue2(() => 'mode'); + const client = { + ...makeClient(), + keepAlive + } as unknown as ApiSessionClient; + const session = new CursorSession({ + api: {} as never, + client, + path: '/tmp/project', + logPath: '/tmp/log', + sessionId: null, + messageQueue: queue, + onModeChange: vi.fn(), + mode: 'remote', + startedBy: 'runner', + startingMode: 'remote', + permissionMode: 'default' + }); + session.onSessionFoundWithProtocol = vi.fn(); + + harness.deferPrompt = new Promise((resolve) => { + harness.releasePrompt = resolve; + }); + queue.push('do work', { permissionMode: 'default' }); + + const runPromise = cursorAcpRemoteLauncher(session); + await vi.waitFor(() => expect(harness.promptCalls).toBeGreaterThan(0)); + await vi.waitFor(() => expect(harness.agentActivityListener).not.toBeNull()); + + // Prompt start already set thinking; clear so we can assert the listener edge. + session.onThinkingChange(false); + keepAlive.mockClear(); + harness.agentActivityListener!(true, 'state_update_running'); + expect(session.thinking).toBe(true); + expect(keepAlive).toHaveBeenCalled(); + + harness.agentActivityListener!(true, 'state_update_requires_action'); + expect(session.thinking).toBe(true); + + harness.releasePrompt?.(); + harness.releasePrompt = null; + harness.deferPrompt = null; queue.close(); await runPromise; }); diff --git a/cli/src/cursor/cursorAcpRemoteLauncher.ts b/cli/src/cursor/cursorAcpRemoteLauncher.ts index 471b591e..855acba3 100644 --- a/cli/src/cursor/cursorAcpRemoteLauncher.ts +++ b/cli/src/cursor/cursorAcpRemoteLauncher.ts @@ -982,15 +982,21 @@ class CursorAcpRemoteLauncher extends RemoteLauncherBase { } /** - * #1470 / #1502: ACP foreground state → hub thinking via keepalive. - * Background tool/content updates are ignored; running is debounced in the backend. + * #1470 / #1502 / #1553: ACP foreground state → hub thinking via keepalive. + * Ignore ambient Cursor `state_update_running` when no HAPI prompt is in + * flight — that chatter otherwise floats quiet sessions into Working and + * hides an attached job from the Jobs bucket. Prompt-owned running, + * permission, and requires_action still bump thinking. */ private softSteerOutstanding(): boolean { return this.softSteerWaiters.length > 0; } private wireAgentActivityThinking(backend: AcpSdkBackend, session: CursorSession): void { - backend.setAgentActivityListener((thinking) => { + backend.setAgentActivityListener((thinking, source) => { + if (source === 'state_update_running' && !this.promptInFlight) { + return; + } if (shouldSuppressPostCloseHarnessThinking(this.postCloseHarnessGate, { promptInFlight: this.promptInFlight, softSteerOutstanding: this.softSteerOutstanding(), diff --git a/cli/src/grok/utils/systemPrompt.ts b/cli/src/grok/utils/systemPrompt.ts index 695bc9ea..07af91a8 100644 --- a/cli/src/grok/utils/systemPrompt.ts +++ b/cli/src/grok/utils/systemPrompt.ts @@ -1,9 +1,10 @@ import { SKILL_LOOKUP_INSTRUCTION } from '@/modules/common/skillLookupInstruction' +import { withSessionJobInstruction } from '@/modules/common/sessionJobInstruction' import { withSessionSummaryInstruction } from '@/modules/common/sessionSummaryInstruction' export const GROK_TITLE_INSTRUCTION = `Use the tool "hapi_change_title" once after the initial request is clear to set a concise session title. Do not rename for routine progress or substeps.\n${SKILL_LOOKUP_INSTRUCTION}` export function getGrokTitleInstruction(env: NodeJS.ProcessEnv = process.env): string { - return withSessionSummaryInstruction(GROK_TITLE_INSTRUCTION, env) + return withSessionSummaryInstruction(withSessionJobInstruction(GROK_TITLE_INSTRUCTION), env) } diff --git a/cli/src/modules/common/permission/BasePermissionHandler.test.ts b/cli/src/modules/common/permission/BasePermissionHandler.test.ts index ae4350a6..aa2c2e7a 100644 --- a/cli/src/modules/common/permission/BasePermissionHandler.test.ts +++ b/cli/src/modules/common/permission/BasePermissionHandler.test.ts @@ -121,3 +121,15 @@ describe('resolveToolAutoApprovalDecision list_peers', () => { )).toBeNull() }) }) + +describe('resolveToolAutoApprovalDecision session_job', () => { + it.each([ + 'session_job', + 'hapi_session_job', + 'mcp__hapi__session_job', + 'Session-Attached Job' + ])('does not name-only auto-approve spoofable job tool %s', (toolName) => { + // Bridge / --allowedTools own the approve path; global title allowlist must not. + expect(resolveToolAutoApprovalDecision('default', toolName, 'call-1')).toBeNull() + }) +}) diff --git a/cli/src/modules/common/permission/BasePermissionHandler.ts b/cli/src/modules/common/permission/BasePermissionHandler.ts index 679efe75..ef8b268f 100644 --- a/cli/src/modules/common/permission/BasePermissionHandler.ts +++ b/cli/src/modules/common/permission/BasePermissionHandler.ts @@ -39,6 +39,9 @@ const AUTO_APPROVE_EXACT_TOOL_NAMES = new Set([ // ACP permission requests often surface MCP tool title, not the snake_case name. 'list peer sessions' ]); +// session_job is intentionally NOT in this name-only allowlist: ACP titles are +// spoofable (tool-name derivation prefers backend title). Auto-approve only via +// trusted HAPI bridge config (Codex tools map / Claude --allowedTools). // ping_peer / inspect_peer / spawn_peer intentionally omitted from always-approve: // they can resume+inject into another session, read peer histories, or create a // new session with an injected remit, so permission modes must still gate them. diff --git a/cli/src/modules/common/sessionJobInstruction.test.ts b/cli/src/modules/common/sessionJobInstruction.test.ts new file mode 100644 index 00000000..c1dd6c40 --- /dev/null +++ b/cli/src/modules/common/sessionJobInstruction.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { + SESSION_JOB_INSTRUCTION, + withSessionJobInstruction +} from './sessionJobInstruction' + +describe('sessionJobInstruction', () => { + it('requires job run and forbids MCP set / fake percent', () => { + expect(SESSION_JOB_INSTRUCTION).toContain('session_job') + expect(SESSION_JOB_INSTRUCTION).toContain('ping_peer') + expect(SESSION_JOB_INSTRUCTION).toContain('hapi job run') + expect(SESSION_JOB_INSTRUCTION).toContain('idle agents cannot') + expect(SESSION_JOB_INSTRUCTION).toMatch(/action=set \(refused\)/) + expect(SESSION_JOB_INSTRUCTION).toContain('Never invent a fake percent') + expect(SESSION_JOB_INSTRUCTION).toContain('HAPI_SESSION_ID') + expect(SESSION_JOB_INSTRUCTION).toMatch(/operator chat URL uuid|URL uuid explicitly/i) + expect(SESSION_JOB_INSTRUCTION).toMatch(/action=list on start\/resume/i) + expect(SESSION_JOB_INSTRUCTION).toMatch(/before done\/archive/i) + expect(SESSION_JOB_INSTRUCTION).toMatch(/never ask the operator/i) + expect(SESSION_JOB_INSTRUCTION).toContain('--progress until') + + expect(SESSION_JOB_INSTRUCTION).toMatch(/--progress unknown\|fraction\|until/) + expect(SESSION_JOB_INSTRUCTION).toMatch(/frozen 0\/N/) + expect(SESSION_JOB_INSTRUCTION).toMatch(/--progress until/) + expect(SESSION_JOB_INSTRUCTION).toMatch(/Exit≠semantic failure|Exit!=semantic failure/) + }) + + it('appends after an existing prompt block', () => { + expect(withSessionJobInstruction('Base.')).toBe(`Base.\n\n${SESSION_JOB_INSTRUCTION}`) + expect(withSessionJobInstruction('')).toBe(SESSION_JOB_INSTRUCTION) + }) +}) diff --git a/cli/src/modules/common/sessionJobInstruction.ts b/cli/src/modules/common/sessionJobInstruction.ts new file mode 100644 index 00000000..fdcaa4ee --- /dev/null +++ b/cli/src/modules/common/sessionJobInstruction.ts @@ -0,0 +1,49 @@ +/** + * Always-on steer for session-attached long-running jobs (tiann/hapi#1404). + * + * Injected into flavors that have a HAPI system / developer-instructions seam + * today: Claude, Codex, OpenCode, Grok. Cursor/Kimi/Copilot/Pi get the same + * MCP tool (`session_job`) via the HAPI MCP bridge — catalog discovery, not + * this prompt block. Estate skill remains a Cursor backup. + */ + +/** Canonical one-block contract. Keep short — every session's prompt budget. */ +export const SESSION_JOB_INSTRUCTION = [ + 'Session-attached jobs (outliving work):', + 'When you start work that will keep running after this agent goes idle', + '(batch imports, long scripts, external daemons), attach a session job so', + 'the session list shows progress while you are idle — same class of HAPI', + 'tooling as ping_peer / inspect_peer.', + 'REQUIRED for process-shaped work (idle agents cannot heartbeat):', + 'Shell → hapi job run --label ', + '--progress unknown|fraction|until … -- …', + '(--progress is required: unknown=indeterminate stripes; fraction=remaining+total', + 'or done+total; until=--until for known deadlines — heartbeats re-stamp remaining).', + 'Fraction without a continuous updater freezes — keep job update feeder from t=0.', + 'FORBIDDEN: --progress fraction --done 0 --total N with no count writer (frozen 0/N).', + 'Known wall-clock windows MUST use --progress until, not unknown.', + 'Numeric sleep N requires --progress until --until (CLI refuses otherwise).', + + 'Use "$HAPI_SESSION_ID" only when it matches the operator chat URL uuid;', + 'remote Cursor runner may export a worker-row id — pass /sessions/ explicitly.', + '(auto-heartbeats + completed/failed on exit code). Wrap the real cmd — never a sleep', + 'stub while work runs elsewhere (SSH/wget/nohup), except intentional --progress until countdowns.', + 'Exit≠semantic failure: nonzero exit stamps failed even if the batch mostly', + 'succeeded — prefer exit 0 when the run finished; put item errors in detail/logs.', + 'Non-JSONL children need an adapter or --progress unknown — do not invent a percent.', + 'HYGIENE: MCP session_job action=list on start/resume AND before done/archive.', + 'Clear or fail zombie running meters (dead process) yourself — never ask the operator.', + 'Leave live jobs with fresh heartbeats alone.', + 'Do NOT use MCP session_job action=set (refused) or bare set+nohup — that freezes the bar.', + 'MCP session_job is only update / clear / list after job run created the meter.', + 'remaining=0 does not finish the job — pass --status completed or job clear when done.', + 'Never invent a fake percent. Full contract: hapi job --help; docs/guide/session-jobs.md.' +].join(' ') + +/** Append instruction to an existing prompt block (blank line separator). */ +export function withSessionJobInstruction(base: string): string { + const trimmed = base.trimEnd() + return trimmed.length > 0 + ? `${trimmed}\n\n${SESSION_JOB_INSTRUCTION}` + : SESSION_JOB_INSTRUCTION +} diff --git a/cli/src/modules/sessionJob/formatJobLine.ts b/cli/src/modules/sessionJob/formatJobLine.ts new file mode 100644 index 00000000..4c6ac76c --- /dev/null +++ b/cli/src/modules/sessionJob/formatJobLine.ts @@ -0,0 +1,69 @@ +import { stripVTControlCharacters } from 'node:util' + +/** + * Job fields can carry agent- or repo-supplied text. Strip VT/ANSI and remaining + * C0 controls before printing so CLI stdout and MCP tool results cannot emit + * OSC clipboard / title escapes into agent or operator terminals. + */ +export function terminalText(value: string): string { + // stripVT removes ESC-based VT; also scrub C0 + DEL + C1 (incl. 8-bit OSC/ST). + return stripVTControlCharacters(value).replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ') +} + +export type FormatJobLineJob = { + key: string + label: string + status: string + done?: number + total?: number + remaining?: number + unit?: string + detail?: string + runId?: string + heartbeatAt?: number + startedAt?: number +} + +export type FormatJobLineOptions = { + /** CLI list/set/update include wall-clock elapsed + heartbeat age. */ + includeTiming?: boolean + nowMs?: number +} + +export function formatJobLine( + job: FormatJobLineJob, + options: FormatJobLineOptions = {} +): string { + const unit = job.unit ? ` ${terminalText(job.unit)}` : '' + const parts = [terminalText(job.key), terminalText(job.label), terminalText(job.status)] + if (job.remaining !== undefined) { + parts.push(`${job.remaining}${unit} left`) + } else if (job.done !== undefined && job.total !== undefined) { + parts.push(`${job.done}/${job.total}${unit}`) + } + if (options.includeTiming && job.startedAt !== undefined) { + const nowMs = options.nowMs ?? Date.now() + const elapsedSec = Math.max(0, Math.round((nowMs - job.startedAt) / 1000)) + if (elapsedSec < 60) { + parts.push(`elapsed ${elapsedSec}s`) + } else if (elapsedSec < 3600) { + parts.push(`elapsed ${Math.floor(elapsedSec / 60)}m`) + } else if (elapsedSec < 86400) { + const h = Math.floor(elapsedSec / 3600) + const m = Math.floor((elapsedSec % 3600) / 60) + parts.push(m > 0 ? `elapsed ${h}h ${m}m` : `elapsed ${h}h`) + } else { + const d = Math.floor(elapsedSec / 86400) + const h = Math.floor((elapsedSec % 86400) / 3600) + parts.push(h > 0 ? `elapsed ${d}d ${h}h` : `elapsed ${d}d`) + } + } + if (job.detail) parts.push(terminalText(job.detail)) + if (job.runId) parts.push(`runId ${terminalText(job.runId)}`) + if (options.includeTiming && job.heartbeatAt !== undefined) { + const nowMs = options.nowMs ?? Date.now() + const ageSec = Math.max(0, Math.round((nowMs - job.heartbeatAt) / 1000)) + parts.push(`heartbeat ${ageSec}s ago`) + } + return parts.join(' · ') +} diff --git a/cli/src/modules/sessionJob/jobProgressMode.test.ts b/cli/src/modules/sessionJob/jobProgressMode.test.ts new file mode 100644 index 00000000..ea536981 --- /dev/null +++ b/cli/src/modules/sessionJob/jobProgressMode.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, it } from 'vitest' +import { SessionJobError } from './sessionJob' +import { + assertCreateProgressMode, + assertNumericSleepUsesUntil, + commandLooksLikeNumericSleep, + parseUntilTimestamp, + stampUntilProgress +} from './jobProgressMode' + +describe('commandLooksLikeNumericSleep', () => { + it('detects sleep N and rejects infinity / bare sleep', () => { + expect(commandLooksLikeNumericSleep(['sleep', '150747'])).toBe(true) + expect(commandLooksLikeNumericSleep(['/bin/sleep', '60'])).toBe(true) + expect(commandLooksLikeNumericSleep(['sleep', '999999'])).toBe(true) + expect(commandLooksLikeNumericSleep(['sleep', 'infinity'])).toBe(false) + expect(commandLooksLikeNumericSleep(['sleep'])).toBe(false) + expect(commandLooksLikeNumericSleep(['./beets-import.sh'])).toBe(false) + }) +}) + +describe('assertNumericSleepUsesUntil', () => { + it('refuses numeric sleep under unknown (dogfootgun)', () => { + expect(() => assertNumericSleepUsesUntil('unknown', ['sleep', '150747'])) + .toThrow(/--progress until/) + expect(() => assertNumericSleepUsesUntil('fraction', ['sleep', '60'])) + .toThrow(/--progress until/) + expect(() => assertNumericSleepUsesUntil('until', ['sleep', '150747'])) + .not.toThrow() + expect(() => assertNumericSleepUsesUntil('unknown', ['sleep', 'infinity'])) + .not.toThrow() + }) +}) + + +describe('assertCreateProgressMode', () => { + it('requires --progress on create', () => { + expect(() => assertCreateProgressMode('run', {})).toThrow(/requires --progress/) + expect(() => assertCreateProgressMode('set', {})).toThrow(/requires --progress/) + }) + + it('unknown forbids count and until fields', () => { + expect(() => assertCreateProgressMode('run', { + progress: 'unknown', + remaining: 1 + })).toThrow(/forbids/) + expect(() => assertCreateProgressMode('run', { + progress: 'unknown', + untilMs: Date.now() + 60_000 + })).toThrow(/forbids/) + expect(() => assertCreateProgressMode('run', { progress: 'unknown' })).not.toThrow() + }) + + it('fraction requires a remaining+total or done+total pair', () => { + expect(() => assertCreateProgressMode('set', { + progress: 'fraction', + remaining: 10 + })).toThrow(/requires --remaining N --total M/) + expect(() => assertCreateProgressMode('set', { + progress: 'fraction', + remaining: 10, + total: 100 + })).not.toThrow() + expect(() => assertCreateProgressMode('set', { + progress: 'fraction', + done: 3, + total: 10 + })).not.toThrow() + }) + + it('until requires --until and forbids manual counts', () => { + expect(() => assertCreateProgressMode('run', { progress: 'until' })) + .toThrow(/requires --until/) + expect(() => assertCreateProgressMode('run', { + progress: 'until', + untilMs: Date.now() + 60_000, + remaining: 1 + })).toThrow(/derives remaining\/total/) + expect(() => assertCreateProgressMode('run', { + progress: 'until', + untilMs: Date.now() + 60_000 + })).not.toThrow() + }) +}) + +describe('parseUntilTimestamp', () => { + it('parses ISO and rejects past', () => { + const now = Date.parse('2026-11-08T03:00:00.000Z') + expect(parseUntilTimestamp('2026-11-09T21:20:14.000Z', now)) + .toBe(Date.parse('2026-11-09T21:20:14.000Z')) + expect(() => parseUntilTimestamp('2026-11-07T00:00:00.000Z', now)) + .toThrow(SessionJobError) + }) +}) + +describe('stampUntilProgress', () => { + it('stamps remaining/total in seconds from until and start', () => { + const start = Date.parse('2026-11-07T21:20:14.000Z') + const until = Date.parse('2026-11-09T21:20:14.000Z') + const mid = Date.parse('2026-11-08T21:20:14.000Z') + const stamped = stampUntilProgress(until, mid, start) + expect(stamped.unit).toBe('s') + expect(stamped.total).toBe(172_800) + expect(stamped.remaining).toBe(86_400) + }) + + it('clamps remaining to total when now is before window start', () => { + const start = Date.parse('2026-11-08T00:00:00.000Z') + const until = Date.parse('2026-11-09T00:00:00.000Z') + const before = Date.parse('2026-11-07T00:00:00.000Z') + const stamped = stampUntilProgress(until, before, start) + expect(stamped.total).toBe(86_400) + expect(stamped.remaining).toBe(86_400) + }) +}) diff --git a/cli/src/modules/sessionJob/jobProgressMode.ts b/cli/src/modules/sessionJob/jobProgressMode.ts new file mode 100644 index 00000000..0570d3c8 --- /dev/null +++ b/cli/src/modules/sessionJob/jobProgressMode.ts @@ -0,0 +1,161 @@ +/** + * Explicit progress mode for job create (run/set). + * Omission used to default to indeterminate stripes — that hid known-duration + * countdowns (2026-11-08 dogfood postmortem). Mode must be chosen on purpose. + */ + +import { basename } from 'node:path' +import { SessionJobError } from './sessionJob' + +export const JOB_PROGRESS_MODES = ['unknown', 'fraction', 'until'] as const +export type JobProgressMode = (typeof JOB_PROGRESS_MODES)[number] + +export type ProgressFields = { + progress?: JobProgressMode + untilMs?: number + done?: number | null + total?: number | null + remaining?: number | null + unit?: string | null +} + +export function parseUntilTimestamp(raw: string, nowMs: number = Date.now()): number { + const trimmed = raw.trim() + if (!trimmed) { + throw new SessionJobError('bad_args', '--until requires an ISO-8601 timestamp or epoch ms') + } + if (/^\d+$/.test(trimmed)) { + const n = Number(trimmed) + // 10-digit epoch seconds vs 13-digit ms + const ms = trimmed.length <= 10 ? n * 1000 : n + if (!Number.isFinite(ms)) { + throw new SessionJobError('bad_args', '--until must be a finite epoch') + } + return ms + } + const parsed = Date.parse(trimmed) + if (!Number.isFinite(parsed)) { + throw new SessionJobError( + 'bad_args', + `--until must be ISO-8601 or epoch ms (got ${JSON.stringify(trimmed)})` + ) + } + if (parsed <= nowMs) { + throw new SessionJobError('bad_args', '--until must be in the future') + } + return parsed +} + +export function assertCreateProgressMode( + action: 'run' | 'set', + fields: ProgressFields +): asserts fields is ProgressFields & { progress: JobProgressMode } { + if (fields.progress === undefined) { + throw new SessionJobError( + 'bad_args', + `${action} requires --progress unknown|fraction|until ` + + '(explicit affordance — do not omit; unknown = indeterminate stripes, ' + + 'fraction = remaining+total or done+total, until = --until )' + ) + } + if (!(JOB_PROGRESS_MODES as readonly string[]).includes(fields.progress)) { + throw new SessionJobError( + 'bad_args', + `--progress must be unknown|fraction|until (got ${JSON.stringify(fields.progress)})` + ) + } + + const hasCount = (v: number | null | undefined): v is number => typeof v === 'number' + const hasDone = hasCount(fields.done) + const hasTotal = hasCount(fields.total) + const hasRemaining = hasCount(fields.remaining) + + if (fields.progress === 'unknown') { + if (hasDone || hasTotal || hasRemaining || fields.untilMs !== undefined) { + throw new SessionJobError( + 'bad_args', + '--progress unknown forbids --done/--total/--remaining/--until ' + + '(claim unknown size explicitly; use fraction or until when you know bounds)' + ) + } + return + } + + if (fields.progress === 'fraction') { + if (fields.untilMs !== undefined) { + throw new SessionJobError('bad_args', '--until is only valid with --progress until') + } + const remainingPair = hasRemaining && hasTotal + const donePair = hasDone && hasTotal + if (!remainingPair && !donePair) { + throw new SessionJobError( + 'bad_args', + '--progress fraction requires --remaining N --total M, or --done N --total M' + ) + } + return + } + + // until + if (fields.untilMs === undefined) { + throw new SessionJobError( + 'bad_args', + '--progress until requires --until ' + ) + } + if (hasDone || hasRemaining || hasTotal) { + throw new SessionJobError( + 'bad_args', + '--progress until derives remaining/total from --until; omit --done/--remaining/--total' + ) + } +} + +/** Stamp remaining+total(+unit) for until mode at `nowMs` / optional startedAt. */ +export function stampUntilProgress( + untilMs: number, + nowMs: number = Date.now(), + startedAtMs: number = nowMs +): { remaining: number; total: number; unit: string } { + const totalSec = Math.max(1, Math.ceil((untilMs - startedAtMs) / 1000)) + // Clamp to the window: remaining cannot exceed total (mid-window attach / + // clock skew) and cannot go negative after the deadline. + const remainingSec = Math.max( + 0, + Math.min(totalSec, Math.ceil((untilMs - nowMs) / 1000)) + ) + return { + remaining: remainingSec, + total: totalSec, + unit: 's' + } +} + +/** + * `sleep ` encodes a known wall duration. Bare/alive-only attach + * was the 2026-11-08 dogfood footgun (stripes / frozen one-shot remaining). + * `sleep infinity` stays allowed under `--progress unknown`. + */ +export function commandLooksLikeNumericSleep(command: string[]): boolean { + if (command.length < 2) return false + const bin = basename(command[0]!) + if (bin !== 'sleep') return false + const arg = command[1]!.trim() + if (!/^\d+$/.test(arg)) return false + return Number(arg) > 0 +} + +export function assertNumericSleepUsesUntil( + progress: JobProgressMode, + command: string[] +): void { + if (!commandLooksLikeNumericSleep(command)) return + if (progress === 'until') return + throw new SessionJobError( + 'bad_args', + 'numeric `sleep N` is a known-duration countdown — use ' + + '`--progress until --until ` (heartbeats keep the bar honest). ' + + '`sleep infinity` is OK with `--progress unknown`; do not encode a deadline ' + + 'as sleep-seconds under unknown/fraction (dogfood postmortem 2026-11-08).' + ) +} diff --git a/cli/src/modules/sessionJob/runSessionJob.test.ts b/cli/src/modules/sessionJob/runSessionJob.test.ts new file mode 100644 index 00000000..966327cb --- /dev/null +++ b/cli/src/modules/sessionJob/runSessionJob.test.ts @@ -0,0 +1,1000 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { SESSION_JOB_JWT_REFRESH_AFTER_MS, resolveSessionJobClient, updateSessionJob } from './sessionJob' +import { runSessionJob } from './runSessionJob' + +function fakeChild(exitCode: number, deferExit = false) { + const child = new EventEmitter() as EventEmitter & { + pid: number + killed: boolean + exit: () => void + } + child.pid = 4242 + child.killed = false + child.exit = () => child.emit('exit', exitCode, null) + if (!deferExit) { + queueMicrotask(() => child.exit()) + } + return child +} + +describe('runSessionJob', () => { + it('until heartbeats re-stamp remaining against explicit window startedAt', async () => { + const windowStart = Date.parse('2098-12-01T00:00:00.000Z') + const until = Date.parse('2099-01-01T00:00:00.000Z') + const nowMs = Date.parse('2098-12-15T00:00:00.000Z') + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async (_url: string, body: { startedAt?: number }) => ({ + status: 200, + data: { + job: { + key: 'dogfood', + label: 'dogfood', + status: 'running', + heartbeatAt: 1, + startedAt: body.startedAt ?? 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, _body: { + remaining?: number + total?: number + unit?: string + expectedRunId?: string + }) => ({ + status: 200, + data: { + job: { + key: 'dogfood', + label: 'dogfood', + status: 'running', + heartbeatAt: 2, + startedAt: windowStart, + updatedAt: 2 + } + } + })) + } + + const timers: Array<() => void> = [] + const child = fakeChild(0, true) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'dogfood', + label: 'dogfood', + command: ['sleep', '999999'], + untilMs: until, + startedAtMs: windowStart, + remaining: Math.ceil((until - nowMs) / 1000), + total: Math.ceil((until - windowStart) / 1000), + unit: 's', + heartbeatMs: 10, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + nowImpl: () => nowMs, + spawnImpl: (() => child) as never, + setIntervalImpl: ((fn: () => void) => { + timers.push(fn) + return 1 as unknown as NodeJS.Timeout + }) as never, + clearIntervalImpl: (() => undefined) as never + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + expect(http.put.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ + startedAt: windowStart, + remaining: Math.ceil((until - nowMs) / 1000), + total: Math.ceil((until - windowStart) / 1000) + })) + + timers[0]!() + await vi.waitFor(() => expect(http.patch).toHaveBeenCalled()) + expect(http.patch.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ + remaining: Math.ceil((until - nowMs) / 1000), + total: Math.ceil((until - windowStart) / 1000), + unit: 's' + })) + + child.exit() + await expect(running).resolves.toBe(0) + }) + + it('sets running, heartbeats, then marks completed on exit 0', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async (_url: string, body: { status?: string; startedAt?: number }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 1, + startedAt: body.startedAt ?? 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + })) + } + + const timers: Array<() => void> = [] + const child = fakeChild(0, true) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + heartbeatMs: 10, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: ((fn: () => void) => { + timers.push(fn) + return 1 as unknown as NodeJS.Timeout + }) as never, + clearIntervalImpl: (() => undefined) as never + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + expect(http.put.mock.calls[0]?.[1]).toEqual(expect.objectContaining({ + status: 'running', + runId: expect.any(String) + })) + expect((http.put.mock.calls[0]?.[1] as { startedAt?: number }).startedAt).toBeUndefined() + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + // Heartbeat ticks reuse resolved client (no extra auth) and must not + // send status:running (late heartbeat must not resurrect after exit). + expect(timers.length).toBe(1) + timers[0]!() + await vi.waitFor(() => expect(http.patch).toHaveBeenCalled()) + const putRunId = (http.put.mock.calls[0]?.[1] as { runId: string }).runId + expect(putRunId).toMatch( + /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + ) + const heartbeatBody = http.patch.mock.calls[0]?.[1] as { + status?: string + expectedRunId?: string + } + expect(heartbeatBody.status).toBeUndefined() + expect(heartbeatBody.expectedRunId).toBe(putRunId) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + child.exit() + const exitCode = await running + expect(exitCode).toBe(0) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { + status?: string + expectedRunId?: string + } + expect(lastPatch.status).toBe('completed') + expect(lastPatch.expectedRunId).toBe(putRunId) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + }) + + it('does not mark terminal when hub reports run mismatch (key reused)', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async (_url: string, body: { startedAt?: number }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: body.startedAt ?? 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => ({ + status: 409, + data: { error: 'Job run mismatch' } + })) + } + + const child = fakeChild(0, true) + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: ((() => 1) as unknown as typeof setInterval), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async () => undefined + }) + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + child.exit() + const exitCode = await running + expect(exitCode).toBe(0) + expect(http.patch).toHaveBeenCalledTimes(1) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/run mismatch|Job run mismatch/i)) + err.mockRestore() + }) + + it('retries terminal status write after transient failures', async () => { + let patchCalls = 0 + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + patchCalls += 1 + if (body.status === 'completed' && patchCalls < 3) { + throw new Error('transient hub 503') + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const sleeps: number[] = [] + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { sleeps.push(ms) } + }) + + expect(exitCode).toBe(0) + expect(patchCalls).toBe(3) + expect(sleeps).toEqual([1_000, 2_000]) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + }) + + it('exits 0 when child succeeds but meter was cleared before terminal write', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + if (body.status === 'completed') { + return { status: 404, data: { error: 'job not found' } } + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async () => undefined + }) + + expect(exitCode).toBe(0) + expect(http.patch).toHaveBeenCalled() + }) + + it('exits 1 when child succeeds but terminal status never persists', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => { + // Non-connection failure: short retry budget only (3 attempts). + throw new Error('permanent write rejected') + }) + } + + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async () => undefined + }) + + expect(exitCode).toBe(1) + expect(http.patch).toHaveBeenCalledTimes(3) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/failed to mark job completed/i)) + err.mockRestore() + }) + + it('exits 1 when hub stays unreachable past the terminal hub-down deadline', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => { + throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:3006'), { + code: 'ECONNREFUSED' + }) + }) + } + + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + let nowMs = 0 + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { nowMs += ms }, + nowImpl: () => nowMs, + terminalHubDownDeadlineMs: 8_000 + }) + + expect(exitCode).toBe(1) + expect(http.patch.mock.calls.length).toBeGreaterThan(3) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/hub unreachable after child exit/i)) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/failed to mark job completed/i)) + err.mockRestore() + }) + + it('marks failed on non-zero exit', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + })) + } + + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['false'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(7)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never + }) + + expect(exitCode).toBe(7) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('failed') + }) + + it('re-exchanges JWT on heartbeat 401 and still marks completed (hub 4h expiry)', async () => { + let jwtIssue = 0 + let patchCalls = 0 + const http = { + post: vi.fn(async () => { + jwtIssue += 1 + return { status: 200, data: { token: `jwt-${jwtIssue}` } } + }), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }, cfg?: { headers?: Record }) => { + patchCalls += 1 + const auth = cfg?.headers?.Authorization ?? '' + // First heartbeat still carries jwt-1 after hub expiry → 401. + if (patchCalls === 1 && auth.includes('jwt-1')) { + return { status: 401, data: { error: 'expired' } } + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const timers: Array<() => void> = [] + const child = fakeChild(0, true) + const errSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + heartbeatMs: 10, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: ((fn: () => void) => { + timers.push(fn) + return 1 as unknown as NodeJS.Timeout + }) as never, + clearIntervalImpl: (() => undefined) as never + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + timers[0]!() + await vi.waitFor(() => expect(http.post).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => expect(http.patch.mock.calls.length).toBeGreaterThanOrEqual(2)) + // Session list not re-fetched — only JWT refresh. + expect(http.get).toHaveBeenCalledTimes(1) + + child.exit() + const exitCode = await running + expect(exitCode).toBe(0) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + errSpy.mockRestore() + }) + + it('proactively re-exchanges JWT after 3h without re-listing sessions', async () => { + let jwtIssue = 0 + const http = { + post: vi.fn(async () => { + jwtIssue += 1 + return { status: 200, data: { token: `jwt-${jwtIssue}` } } + }), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + patch: vi.fn(async (_url: string, _body: unknown, cfg?: { headers?: Record }) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + }, + _auth: cfg?.headers?.Authorization + } + })) + } + + const resolved = await resolveSessionJobClient({ + sessionIdPrefix: 'aaaa', + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(1) + expect(http.get).toHaveBeenCalledTimes(1) + + // Inside the window: no second exchange. + await updateSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + body: { remaining: 9 }, + resolved, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(1) + + // Past proactive refresh threshold: exchange once, keep session id. + resolved.jwtIssuedAtMs = Date.now() - SESSION_JOB_JWT_REFRESH_AFTER_MS - 1 + await updateSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + body: { remaining: 8 }, + resolved, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(2) + expect(http.get).toHaveBeenCalledTimes(1) + expect(resolved.jwt).toBe('jwt-2') + const auth = (http.patch.mock.calls.at(-1)?.[2] as { headers?: Record } | undefined) + ?.headers?.Authorization + expect(auth).toContain('jwt-2') + + // Next tick inside the new window: no exchange storm. + await updateSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + body: { remaining: 7 }, + resolved, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + }) + expect(http.post).toHaveBeenCalledTimes(2) + expect(http.get).toHaveBeenCalledTimes(1) + }) + + it('forwards SIGINT/SIGTERM via tree-kill so grandchildren cannot outlive the job', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + runId: 'run-1', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'completed', + runId: 'run-1', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + })) + } + + const child = fakeChild(0, true) + const killChild = vi.fn(async () => true) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['sleep', '30'], + heartbeatMs: 60_000, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: (() => 1 as unknown as NodeJS.Timeout) as never, + clearIntervalImpl: (() => undefined) as never, + killChildImpl: killChild + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + process.emit('SIGINT') + expect(killChild).toHaveBeenCalledWith(child, 'SIGINT') + child.exit() + await running + }) + + it('awaits verified tree-kill before writing terminal job state', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + runId: 'run-1', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async ( + _url: string, + body: { status?: string; detail?: string } + ) => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'failed', + runId: 'run-1', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2, + ...(body.detail !== undefined ? { detail: body.detail } : {}), + } + } + })) + } + + let resolveKill: ((ok: boolean) => void) | undefined + const killChild = vi.fn(() => new Promise((resolve) => { + resolveKill = resolve + })) + const child = fakeChild(0, true) + const err = vi.spyOn(console, 'error').mockImplementation(() => undefined) + const running = runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['sleep', '30'], + heartbeatMs: 60_000, + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => child) as never, + setIntervalImpl: (() => 1 as unknown as NodeJS.Timeout) as never, + clearIntervalImpl: (() => undefined) as never, + killChildImpl: killChild + }) + + await vi.waitFor(() => expect(http.put).toHaveBeenCalled()) + process.emit('SIGTERM') + expect(killChild).toHaveBeenCalledWith(child, 'SIGTERM') + child.exit() + + // Child exited, but tree-kill still pending → no terminal write yet. + await Promise.resolve() + expect(http.patch).not.toHaveBeenCalled() + + resolveKill?.(false) + const exitCode = await running + expect(exitCode).toBe(1) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] + expect(lastPatch?.status).toBe('failed') + expect(lastPatch?.detail).toMatch(/complete child process tree/i) + expect(err).toHaveBeenCalledWith(expect.stringMatching(/complete child process tree/i)) + err.mockRestore() + }) + + it('keeps retrying terminal completed after ECONNREFUSED until hub returns (hub restart)', async () => { + let patchCalls = 0 + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'restart-hub', + label: 'restart', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + patchCalls += 1 + if (body.status === 'completed' && patchCalls < 6) { + throw Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:3006'), { + code: 'ECONNREFUSED' + }) + } + return { + status: 200, + data: { + job: { + key: 'restart-hub', + label: 'restart', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + const sleeps: number[] = [] + let nowMs = 0 + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'restart-hub', + label: 'restart', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { + sleeps.push(ms) + nowMs += ms + }, + nowImpl: () => nowMs, + terminalHubDownDeadlineMs: 60_000 + }) + + expect(exitCode).toBe(0) + expect(patchCalls).toBe(6) + expect(sleeps.length).toBeGreaterThanOrEqual(5) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + }) + + it('treats structured HTTP 503 as hub-down for the long terminal retry window', async () => { + let patchCalls = 0 + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(async () => ({ + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: 'running', + heartbeatAt: 1, + startedAt: 1, + updatedAt: 1 + } + } + })), + patch: vi.fn(async (_url: string, body: { status?: string }) => { + patchCalls += 1 + if (body.status === 'completed' && patchCalls < 5) { + // Hub returns JSON error text without "HTTP 503" in the message — + // classification must use the numeric status, not the detail string. + return { status: 503, data: { error: 'Not connected' } } + } + return { + status: 200, + data: { + job: { + key: 'drain', + label: 'drain', + status: body.status ?? 'running', + heartbeatAt: 2, + startedAt: 1, + updatedAt: 2 + } + } + } + }) + } + + let nowMs = 0 + const exitCode = await runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'drain', + label: 'drain', + command: ['true'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never, + spawnImpl: (() => fakeChild(0)) as never, + setIntervalImpl: ((() => 1) as never), + clearIntervalImpl: (() => undefined) as never, + sleepImpl: async (ms) => { nowMs += ms }, + nowImpl: () => nowMs, + terminalHubDownDeadlineMs: 60_000 + }) + + expect(exitCode).toBe(0) + expect(patchCalls).toBe(5) + const lastPatch = http.patch.mock.calls.at(-1)?.[1] as { status?: string } + expect(lastPatch.status).toBe('completed') + }) + + it('refuses wrapping hapi-restart-hub in job run before creating a meter', async () => { + const http = { + post: vi.fn(async () => ({ status: 200, data: { token: 'jwt' } })), + get: vi.fn(async () => ({ + status: 200, + data: { sessions: [{ id: 'aaaaaaaa-1111-1111-1111-111111111111' }] } + })), + put: vi.fn(), + patch: vi.fn() + } + + await expect(runSessionJob({ + sessionIdPrefix: 'aaaa', + jobKey: 'restart-hub', + label: 'Patient hub restart', + command: ['env', 'HAPI_AGENT_LABEL=x', 'hapi-restart-hub'], + accessToken: 'token', + apiUrl: 'http://127.0.0.1:3006', + http: http as never + })).rejects.toMatchObject({ + code: 'bad_args', + message: expect.stringMatching(/hapi-restart-hub|outside the job|hub restart/i) + }) + expect(http.put).not.toHaveBeenCalled() + expect(http.patch).not.toHaveBeenCalled() + }) +}) diff --git a/cli/src/modules/sessionJob/runSessionJob.ts b/cli/src/modules/sessionJob/runSessionJob.ts new file mode 100644 index 00000000..d36b9042 --- /dev/null +++ b/cli/src/modules/sessionJob/runSessionJob.ts @@ -0,0 +1,380 @@ +/** + * Supervise a child command while heartbeating a session-attached job. + * Fixes the idle-agent heartbeat gap (cold review #1404). + */ + +import { randomUUID } from 'node:crypto' +import { basename } from 'node:path' +import { spawn, type ChildProcess } from 'node:child_process' +import { constants as osConstants } from 'node:os' +import type { AttachedJobUpsert } from '@hapi/protocol' +import { killProcessByChildProcess } from '@/utils/process' +import { + SessionJobError, + resolveSessionJobClient, + setSessionJob, + updateSessionJob, + type SessionJobClientOptions, + type SessionJobResolvedClient +} from './sessionJob' +import { stampUntilProgress } from './jobProgressMode' + +export type RunSessionJobOptions = SessionJobClientOptions & { + jobKey: string + label: string + command: string[] + heartbeatMs?: number + remaining?: number + done?: number + total?: number + unit?: string + detail?: string + /** When set, heartbeats re-stamp remaining from wall clock (progress until). */ + untilMs?: number + /** + * Window start for until-mode total (until − startedAt). Defaults to supervisor + * launch time. Pass the original window start on mid-window re-attach so the + * bar does not reset to "time left from this restart." + */ + startedAtMs?: number + wakeOnTerminal?: boolean + wakePrompt?: string + /** Injected for tests. */ + spawnImpl?: typeof spawn + setIntervalImpl?: typeof setInterval + clearIntervalImpl?: typeof clearInterval + /** Injected for tests (terminal-status retry backoff). */ + sleepImpl?: (ms: number) => Promise + /** Injected for tests — wall clock for hub-down terminal retry deadline. */ + nowImpl?: () => number + /** + * How long to keep retrying terminal PATCH while the hub is unreachable + * (ECONNREFUSED after `hapi-restart-hub`, brief remat, etc.). Default 10m. + */ + terminalHubDownDeadlineMs?: number + /** Injected for tests — defaults to tree-kill via killProcessByChildProcess. */ + killChildImpl?: (child: ChildProcess, signal: NodeJS.Signals) => void | Promise +} + +const DEFAULT_HEARTBEAT_MS = 5 * 60 * 1000 +const TERMINAL_STATUS_ATTEMPTS = 3 +const DEFAULT_TERMINAL_HUB_DOWN_DEADLINE_MS = 10 * 60 * 1000 +const TERMINAL_HUB_DOWN_BACKOFF_CAP_MS = 30_000 + +/** Argv tokens that take this hub (or active stack) down mid-supervision. */ +const HUB_STACK_CONTROL_BASENAMES = new Set([ + 'hapi-restart-hub', + 'hapi-use-worktree', + 'hapi-use-driver', + 'hapi-watch-activate-driver', +]) + +/** + * True when the supervised argv would restart/swap this hub while `job run` + * still needs a terminal PATCH — wrapping these creates zombie `running` meters + * unless the hub is reachable again within the hub-down retry window. + */ +export function commandLooksLikeHubStackControl(command: string[]): boolean { + for (const arg of command) { + for (const token of arg.split(/[\s]+/).filter(Boolean)) { + const base = basename(token) + if (HUB_STACK_CONTROL_BASENAMES.has(base)) return true + } + } + return false +} + +/** Connection / gateway failures where retrying after hub restart can succeed. */ +export function isHubUnreachableError(error: unknown): boolean { + if (error instanceof SessionJobError) { + if (error.code === 'run_mismatch' || error.code === 'not_found') return false + // Prefer numeric status: httpStatusError may replace "HTTP 503" with hub JSON text + // like "Not connected", which must still use the hub-down retry window. + if (error.httpStatus !== undefined && error.httpStatus >= 502 && error.httpStatus <= 504) { + return true + } + if (/HTTP 502|HTTP 503|HTTP 504|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|hub unreachable|Network Error/i.test(error.message)) { + return true + } + } + if (error && typeof error === 'object') { + const e = error as { code?: string; message?: string; cause?: unknown } + if (typeof e.code === 'string' + && /^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|EPIPE|EHOSTUNREACH)$/.test(e.code)) { + return true + } + if (typeof e.message === 'string' + && /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|Network Error|hub unreachable/i.test(e.message)) { + return true + } + if (e.cause !== undefined) return isHubUnreachableError(e.cause) + } + if (error instanceof Error) { + return /ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOTFOUND|socket hang up|Network Error|hub unreachable/i.test(error.message) + } + return false +} + +function terminalBackoffMs(attempt: number, hubDown: boolean): number { + if (!hubDown) return 1_000 * 2 ** attempt + return Math.min(2_000 * 2 ** attempt, TERMINAL_HUB_DOWN_BACKOFF_CAP_MS) +} + +async function markTerminalWithRetry(options: { + clientOpts: SessionJobClientOptions & { resolved: SessionJobResolvedClient } + jobKey: string + status: 'completed' | 'failed' + detail?: string + expectedRunId: string + sleep: (ms: number) => Promise + now: () => number + hubDownDeadlineMs: number +}): Promise { + let lastError: unknown + let attempt = 0 + const startedAt = options.now() + let loggedHubDownWait = false + for (;;) { + try { + await updateSessionJob({ + ...options.clientOpts, + jobKey: options.jobKey, + body: { + status: options.status, + expectedRunId: options.expectedRunId, + ...(options.detail !== undefined ? { detail: options.detail } : {}), + }, + }) + return + } catch (error) { + lastError = error + // Another run owns the key — retrying cannot help and may confuse logs. + if (error instanceof SessionJobError && error.code === 'run_mismatch') { + break + } + + const hubDown = isHubUnreachableError(error) + const elapsed = options.now() - startedAt + const withinHubDownBudget = hubDown && elapsed < options.hubDownDeadlineMs + const withinShortBudget = !hubDown && attempt < TERMINAL_STATUS_ATTEMPTS - 1 + + // Operator cleared the meter while the child still ran — detached, not a + // supervision failure. Retry transient 404s; accept absence when budget ends. + if (error instanceof SessionJobError && error.code === 'not_found') { + if (!withinShortBudget && !withinHubDownBudget) { + return + } + } else if (!withinShortBudget && !withinHubDownBudget) { + break + } + + if (hubDown && !loggedHubDownWait) { + loggedHubDownWait = true + const message = error instanceof Error ? error.message : String(error) + console.error( + `[hapi job run] hub unreachable after child exit (${message}); ` + + `retrying terminal ${options.status} for up to ` + + `${Math.round(options.hubDownDeadlineMs / 1000)}s` + ) + } + + await options.sleep(terminalBackoffMs(attempt, hubDown)) + attempt += 1 + } + } + throw lastError instanceof Error ? lastError : new Error(String(lastError)) +} + +export async function runSessionJob(options: RunSessionJobOptions): Promise { + if (options.command.length === 0) { + throw new SessionJobError('bad_args', 'run requires a command after --') + } + + if (commandLooksLikeHubStackControl(options.command)) { + throw new SessionJobError( + 'bad_args', + 'do not wrap hapi-restart-hub / hapi-use-worktree / hapi-use-driver / ' + + 'hapi-watch-activate-driver in `hapi job run` — the hub is down exactly when ' + + 'the terminal status PATCH must land, leaving a zombie running meter. ' + + 'Run the hub restart outside the job (job = remat/work only; restart after exit).' + ) + } + + // Hub stamps startedAt when runId starts a new generation (runner/hub + // clocks may skew) unless the caller passes an explicit window start. + // runId is the unique generation fence. + const runId = randomUUID() + const body: AttachedJobUpsert = { + label: options.label, + status: 'running', + runId, + ...(options.done !== undefined ? { done: options.done } : {}), + ...(options.total !== undefined ? { total: options.total } : {}), + ...(options.remaining !== undefined ? { remaining: options.remaining } : {}), + ...(options.unit !== undefined ? { unit: options.unit } : {}), + ...(options.detail !== undefined ? { detail: options.detail } : {}), + ...(options.startedAtMs !== undefined ? { startedAt: options.startedAtMs } : {}), + ...(options.wakeOnTerminal !== undefined ? { wakeOnTerminal: options.wakeOnTerminal } : {}), + ...(options.wakePrompt !== undefined ? { wakePrompt: options.wakePrompt } : {}) + } + + // Cache sessionId for the run. JWT is refreshed in-place before hub's 4h + // expiry and on 401 (see sessionJob.withAuthedRequest) — do not skip refresh. + const resolved: SessionJobResolvedClient = await resolveSessionJobClient(options) + const clientOpts = { + sessionIdPrefix: options.sessionIdPrefix, + resolved, + accessToken: options.accessToken, + apiUrl: options.apiUrl, + http: options.http + } + + await setSessionJob({ + ...clientOpts, + jobKey: options.jobKey, + body + }) + + const spawnFn = options.spawnImpl ?? spawn + const setIntervalFn = options.setIntervalImpl ?? setInterval + const clearIntervalFn = options.clearIntervalImpl ?? clearInterval + const sleep = options.sleepImpl + ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))) + const now = options.nowImpl ?? Date.now + const hubDownDeadlineMs = options.terminalHubDownDeadlineMs ?? DEFAULT_TERMINAL_HUB_DOWN_DEADLINE_MS + const heartbeatMs = options.heartbeatMs ?? DEFAULT_HEARTBEAT_MS + + const child: ChildProcess = spawnFn(options.command[0]!, options.command.slice(1), { + stdio: 'inherit', + env: process.env + }) + + let loggedHeartbeatFailure = false + let inflightHeartbeat: Promise = Promise.resolve() + // Until-mode total = until − windowStart. Prefer explicit startedAtMs so a + // mid-window move keeps the original 48h (etc.) denominator. + const untilWindowStartMs = options.startedAtMs ?? now() + const heartbeat = setIntervalFn(() => { + // Never PATCH status:running on the heartbeat — a late in-flight + // request must not resurrect running after the terminal write. + // Fence with runId so a superseded run cannot touch a key reuse. + // Do not re-send --detail: MCP/CLI progress updates would otherwise be + // clobbered by the next timer tick with the launch-time string. + const untilBody = options.untilMs !== undefined + ? (() => { + const stamped = stampUntilProgress(options.untilMs!, now(), untilWindowStartMs) + return { + remaining: stamped.remaining, + total: stamped.total, + unit: options.unit ?? stamped.unit + } + })() + : {} + inflightHeartbeat = updateSessionJob({ + ...clientOpts, + jobKey: options.jobKey, + body: { expectedRunId: runId, ...untilBody } + }).catch((error: unknown) => { + // Best-effort — exit path still marks terminal status. Log once so + // a broken supervisor is visible (stuck chip with dead PID is worse). + if (!loggedHeartbeatFailure) { + loggedHeartbeatFailure = true + const message = error instanceof Error ? error.message : String(error) + console.error(`[hapi job run] heartbeat failed (will keep trying): ${message}`) + } + }) + }, heartbeatMs) + // Don't keep the event loop alive solely for heartbeats if child already exited. + heartbeat.unref?.() + + // Forward the received signal through tree-kill (not always SIGTERM) and + // await verified teardown before writing terminal job state. + let terminationPromise: Promise | null = null + const forward = (signal: NodeJS.Signals) => { + if (child.pid && !child.killed) { + // Tree-kill: a supervised shell can exit while a grandchild keeps + // running; bare process.kill(child.pid) would leave orphans and let + // the wrapper mark the job terminal while work continues. + const killChild = options.killChildImpl + ?? ((target: ChildProcess, sig: NodeJS.Signals) => + killProcessByChildProcess(target, false, sig)) + terminationPromise ??= Promise.resolve(killChild(child, signal)).then( + (result) => result !== false + ) + } + } + const onSigInt = () => forward('SIGINT') + const onSigTerm = () => forward('SIGTERM') + process.on('SIGINT', onSigInt) + process.on('SIGTERM', onSigTerm) + + let spawnErrorDetail: string | undefined + const exitCode = await new Promise((resolve) => { + child.on('error', async (error) => { + clearIntervalFn(heartbeat) + spawnErrorDetail = error.message + resolve(127) + }) + child.on('exit', (code, signal) => { + clearIntervalFn(heartbeat) + if (signal) { + const signalNumber = osConstants.signals[signal] ?? 1 + resolve(128 + signalNumber) + return + } + resolve(code ?? 1) + }) + }) + + process.off('SIGINT', onSigInt) + process.off('SIGTERM', onSigTerm) + + // Drain any in-flight heartbeat so a late status:running cannot clobber + // the terminal completed/failed write. + await inflightHeartbeat.catch(() => undefined) + + let treeKillFailed = false + if (terminationPromise) { + const stopped = await terminationPromise + if (!stopped) { + treeKillFailed = true + console.error('[hapi job run] failed to terminate the complete child process tree') + } + } + + const terminalStatus = exitCode === 0 && !treeKillFailed ? 'completed' : 'failed' + let terminalWriteFailed = false + try { + await markTerminalWithRetry({ + clientOpts, + jobKey: options.jobKey, + status: terminalStatus, + expectedRunId: runId, + ...(spawnErrorDetail !== undefined + ? { detail: spawnErrorDetail } + : treeKillFailed + ? { detail: 'failed to terminate the complete child process tree' } + : {}), + sleep, + now, + hubDownDeadlineMs, + }) + } catch (error) { + // run_mismatch means another generation owns the key — not our meter to fix. + // not_found means the meter was cleared externally (e.g. session_job clear). + terminalWriteFailed = !( + error instanceof SessionJobError + && (error.code === 'run_mismatch' || error.code === 'not_found') + ) + const message = error instanceof Error ? error.message : String(error) + console.error(`[hapi job run] failed to mark job ${terminalStatus}: ${message}`) + } + + // Child success with a frozen "running" meter (or uncleared descendants) is + // worse than a nonzero exit — surface the supervision failure so wrappers/CI + // cannot claim green. + if (treeKillFailed) { + return exitCode === 0 ? 1 : exitCode + } + return exitCode === 0 && terminalWriteFailed ? 1 : exitCode +} diff --git a/cli/src/modules/sessionJob/sessionJob.ts b/cli/src/modules/sessionJob/sessionJob.ts new file mode 100644 index 00000000..4c5dfa8b --- /dev/null +++ b/cli/src/modules/sessionJob/sessionJob.ts @@ -0,0 +1,458 @@ +/** + * Register / update / clear session-attached jobs (tiann/hapi#1404). + * Same hub JWT flow as ping-peer — works while the agent session is idle. + */ + +import axios, { type AxiosInstance } from 'axios' +import type { AttachedJob, AttachedJobPatch, AttachedJobUpsert } from '@hapi/protocol' +import { configuration } from '@/configuration' +import { getAuthToken } from '@/api/auth' +import { buildHubRequestHeaders } from '@/api/hubExtraHeaders' + +export type SessionJobErrorCode = + | 'bad_args' + | 'auth_failed' + | 'not_found' + | 'ambiguous' + | 'run_mismatch' + | 'request_failed' + +export class SessionJobError extends Error { + readonly code: SessionJobErrorCode + /** Present when the failure came from an HTTP response (for outage classification). */ + readonly httpStatus?: number + + constructor(code: SessionJobErrorCode, message: string, httpStatus?: number) { + super(message) + this.name = 'SessionJobError' + this.code = code + if (httpStatus !== undefined) this.httpStatus = httpStatus + } +} + +/** Exact Shell recipe agents should run instead of MCP set or update-before-create. */ +export const SESSION_JOB_RUN_RECIPE = + 'hapi job run --label "