* feat(cursor): bump hub thinking on ACP harness wake
When Cursor resumes after idle (notify_on_output / mid-idle ACP activity
or a permission request), flip thinking via the existing session-alive
keepalive so the hub list matches reality. Fixes#1470.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cursor): emit thinking true/false edges for ACP harness wake
Address Codex Major on #1487: activity listener now reports idle as
false, and the launcher only keepalives on actual thinking transitions
so streamed chunks do not spam session-alive.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cursor): reattach activity thinking listener after session/new remap
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
The first test in claudeRemote.test.ts imports the full remote-module
graph and intermittently exceeds vitest's default 5s timeout on loaded
CI runners, failing PRs that touch no cli/ files. Give that one test a
15s per-test timeout; verified: typecheck exit 0, claudeRemote suite
6/6 pass (~2s cold), full suite 223/224 files pass (runner.integration
fails identically on pristine base in this sandbox).
Fixes#1491
Pi finalizes a failed assistant message with stopReason 'error' and
errorMessage on both message_end and turn_end, but PiMessageAccumulator
only handled text/thinking deltas, so the error was silently dropped and
the web showed nothing (spinner stop + partial text at most).
Emit an AgentMessage {type:'error'} once per failed message (message_end
wins, turn_end is the safety net for Pi builds that skip message_end);
the web already renders AGENT_MESSAGE_PAYLOAD_TYPE error payloads as
system messages. User-initiated aborts stay silent.
Closes#1478
* fix(opencode): report why a prompt failed instead of pointing at logs
The provider's own explanation already reaches this process: the ACP
transport rejects session/prompt with the JSON-RPC error message
verbatim. The launcher caught it, logged it, and handed the user a fixed
"OpenCode prompt failed. Check logs for details." — a remote user is by
definition not at the machine holding those logs, so a rate-limited
session simply stopped with no stated reason.
Only the message is used; that channel carries no response headers,
cookies or body. It is unbounded though (a 20KB provider body produced a
20,210-character message), so it is capped at the same 200 characters
the compaction bridge already applies to provider text, and the JSON-RPC
"Internal error: " wrapper is stripped. A failure with nothing readable
to say still renders the sentence it always did.
* feat(opencode): surface upstream retries from the agent event stream
A provider rate limit leaves OpenCode retrying indefinitely, and it
announces that on exactly one channel: its own server event stream.
Measured against a provider stubbed to answer 429 — 40 minutes, 85
retries, zero ACP notifications, zero stderr bytes, session/prompt never
settling. HAPI showed a session that looked like it was thinking and
said nothing else.
Subscribes to that stream once the ACP session id is known and reports
retries as the same api_error system message Claude sessions already
use, so the web timeline folds a run of them into one block whose
attempt count climbs. The reason rides along in the payload, and the
presentation now appends it to "Retrying..." when an agent supplies one;
sessions that supply nothing render exactly as before.
Not every attempt is announced. The backoff tops out at 30 seconds and
OpenCode does not give up, so a session held against a daily quota would
otherwise persist two messages a minute for as long as it is left
running. The first few attempts are reported, then only attempt numbers
that are powers of two, which needs no clock to decide.
The subscription must be scoped with ?directory=: without it the
endpoint delivers heartbeats and no session events at all, with neither
an error nor a 404 to notice. Its session.error event is deliberately
not read — it carries the Authorization header, cookies and the full
response body verbatim, and the same failure already reaches the user
stripped to a message through the ACP prompt error.
Delegated turns are not covered: OpenCode's subagent tool runs them in a
child session with its own id, and this follows only the one it was
opened for.
No countdown is rendered, though the payload offers one: a timeline
block outlives the turn it describes. Turn state is left alone; a
retrying session really is busy.
* fix(opencode): only relay prompt failures OpenCode itself reported
AcpStdioTransport flattens a JSON-RPC error response to
new Error(response.error.message), so a rejected session/prompt is
indistinguishable by shape from an error the transport built locally.
Its process-close error appends up to 4KB of raw subprocess stderr to
the message, which the formatter would then have published to the hub
and every connected client.
Requiring the "Internal error: " wrapper OpenCode puts on every service
failure turns this into an allowlist: an unrecognised rejection renders
the sentence this path rendered before rather than whatever it happened
to contain. Retry text is collapsed to one line before it is judged,
since a whitespace-only message is truthy and embedded newlines break
the one-line contract the helper states.
* fix(pi): sync native session name
* fix(pi): sync live native renames via session_info_changed
Pi emits session_info_changed on /name and set_session_name. Share the
native-title sync callback between get_state startup/resume and the live
rename event so HAPI metadata.summary.text mirrors Pi's authoritative
session name without a change_title flow. Explicit HAPI/web renames
(metadata.name) keep precedence per sessionTitle.ts.
* fix(agy): sync native Anti-Gravity conversation titles (#1439)
Read the Anti-Gravity CLI's conversation_summaries.db title for the
active brain UUID and mirror it into HAPI session metadata.summary,
reusing the existing native-title normalizer so placeholder/empty
titles are ignored and a user-defined metadata.name stays preferred
by the web title logic.
The existing AGY scanner polls every 5s while a brain is known, so the
title follows native generation/rename without PTY parsing. Lookup is
best-effort: missing/locked DB or schema drift degrades to no-op.
* test(agy): cover delayed/renamed native title polling and cleanup stop
Addresses HAPI Bot review suggestion on #1476: scanner re-reads the
native title on later scans (null -> generated -> renamed) and stops
reading after cleanup.
* fix(agy): preserve PTY running status
* fix(agent): let a trailing idle marker win over a same-chunk busy marker
runAgentPty treated any busy marker in a chunk as authoritative, so a
chunk carrying both 'Generating' and the idle footer discarded the idle
marker. With the silence watchdog disabled (agy), nothing re-armed
inputReady and the session stayed 'running' forever. Compare marker
positions: the last one in the chunk reflects the final repaint.
Adds lastMarkerIndex for string and non-global RegExp markers and a
null-watchdog regression with both markers in one ANSI-decorated chunk.
* fix(agent): scan the full chunk and keep busy-run completion bookkeeping
- Scan promptBuffer + data before truncating to PROMPT_BUFFER_SIZE, so a
busy marker followed by more than 4096 bytes in one callback is still
seen; otherwise the run never completes and a pending web delivery can
block subsequent messages.
- When an idle marker wins over a same-chunk busy marker, keep the busy
confirmation so completeAgentRun fires for the run that just ended.
- lastMarkerIndex now clones non-global RegExps with the g flag and scans
the original string, preserving anchors and terminating on zero-width
matches (previously /$/ looped forever).
* fix(cli): skip invalid set_mode for interactive Copilot sessions
applyInitialAgentMode() unconditionally sent session/set_mode with
modeId 'interactive', which the Copilot ACP server rejects (Invalid
mode 'interactive' - supported: agent/plan/autopilot), killing every
default-mode Copilot session at startup.
- Short-circuit applyAgentMode('interactive') as a no-op success,
mirroring buildCopilotAcpArgs which already omits --mode at spawn
- Classify 'Invalid mode' responses as unsupported runtime switching so
server-side mode rejections degrade gracefully (restart to apply)
Verified: bun typecheck + bun run test (full suite green).
* fix(cli): map Copilot interactive mode to ACP agent mode
Address review findings: the previous no-op for interactive left the
backend in Plan/Autopilot after a runtime switch while HAPI reported
Interactive, and classifying 'Invalid mode' responses permanently
disabled switching for valid modes too.
- Map interactive -> the ACP 'agent' mode id (the spawn default) so
session/set_mode always receives a valid mode and runtime switches
back to Interactive stay in sync with the backend
- Keep 'Invalid mode' out of the capability-loss classifier: it is a
per-mode rejection, not evidence that set_mode is unavailable
* fix(cli): remap bracketed Cursor wires onto bare/SKU catalogs
#1271 only handled the grok-4.5 legacy alias family. Persisted wires like
gpt-5.3-codex[fast=false] still failed agent --model on resume against
today's bare ACP catalogs. Remap non-legacy wires to bare bases / CLI
SKUs (and nearest configOption wires), and prefer spawn-safe ids in
session state.
Fixes#1428
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): harden Cursor stale-model remap against silent wrong picks
Address Codex Major review on #1430: prefer spawn-safe ids even on exact
bracket cache hits, require explicit wire params when ranking configOption
candidates, and stop downgrading unavailable CLI SKU variants.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): preserve desired Cursor variant across spawn-safe remap
Do not overwrite session.model with the bare/SKU spawn id before ACP
apply, and keep spawn-safe requested ids in wireIdForCursorSessionState
so apply does not re-poison hub state with bracket wires.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): remap-retry Cursor session/new on stale model reject
Initialize and session/load already retried once after Cannot use this
model; session/new had the same failure mode with an empty shared cache.
Mirror the one-shot remap+respawn path and cover it with a launcher test.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): resolve Cursor apply against ACP option values first
Spawn-safe remap prefers bare/SKU ids, but set_config_option may only
accept full bracket wires. Resolve against the model option list before
falling back to metadata so apply does not pick a rejected bare base.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): fail Cursor launch when remapped spawn cannot restore model
When --model was remapped for spawn, restoring the original desired
variant via ACP is mandatory. Soft-failing left sessions running on the
wrong model. Cover success and hard-fail paths in launcher tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(cli): cross-flavor inline image display via MCP and ACP
Share display_image prompt across MCP-bridge flavors (Cursor, Gemini,
Kimi, Codex, Claude, OpenCode), auto-approve the tool in
buildHapiMcpBridge, handle ACP image content blocks, and harden
generated-image registration with content sniffing.
Closes tiann/hapi#956
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): render generated-image cards reliably in chat
Keep object URLs stable across refetch, upscale tiny inline images,
fetch generated-image bytes with cache no-store (avoid empty 304 bodies),
and load hapiMcpUrl from per-session API in hapi-display-image tooling.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(cli+web): display_video MCP for inline mp4/webm (#956)
Add display_video alongside display_image, video MIME sniffing with avif
guard, web GeneratedImageCard video player, and hapi-display-image auto-routing.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(cli+web): cross-flavor display_video parity with images (#956)
Share display_video prompts across MCP-bridge flavors, auto-approve the
tool, register mp4/webm via path sniffing, render inline video in web on
the existing generated-image RPC path, and restore robust media card fetch.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): ACP image ordering and inline media source provenance
Flush buffered assistant text before async generated_image emit from ACP
image blocks (PR #958 review Major). Add optional source metadata on
generated-image wire messages (ingress, flavor, toolCallId, toolName) for
MCP, ACP, and Codex tool-result paths. Seeds artifact-event follow-up #966.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli+web): address PR #958 review Majors on media order and stale blobs
Queue ACP session updates and await async image registration before later
events; clear GeneratedImageCard blob state when imageId changes.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): await ACP queue after late-drain before turn_complete
Straggler session/update during drainLateBuffers can queue async image
registration; re-await sessionUpdateQueue so generated_image is not emitted
after turn_complete.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(scripts): route AVIF ftyp brands to display_image in helper
Match server-side detectImageMimeType so .avif files are not sent to
display_video and rejected as unsupported video.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(#956): agent inline-media doctor and discovery fixes
- hapi doctor inline-media: probe bridges, print per-session inline commands
- Expose hapiMcpUrl on session list summaries (stops false "no MCP" scans)
- Helper script: match cursorSessionId prefixes; HAPI_SESSION_ID path-only mode
- ACP bridge prompt: shell fallback + HAPI session id vs agent id rule
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): allow immutable cache for generated media blobs
Drop cache: no-store on generated-image fetch so browser can reuse hub
immutable responses; on 304 re-read via force-cache (#927, PR review).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(#956): Cursor native MCP overlay; drop user-turn bridge prepend
Cursor ACP ignores session/new mcpServers. Write .cursor/mcp.json and
run agent mcp enable hapi instead. Remove HAPI_MCP_BRIDGE_PROMPT from
user turns on ACP remotes; enrich MCP tool descriptions for discovery.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): preserve non-HAPI mcp.json keys on Cursor overlay cleanup
Cleanup only removes or restores the hapi MCP entry instead of rewriting
the full pre-session snapshot, so concurrent edits to other servers survive.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): handle generated_image in Grok ACP launcher switch
Upstream Grok launcher exhaustiveness broke after AgentMessage gained
generated_image for cross-flavor inline media.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): rebase fallout for display_video + OpenCode skill lookup
Gate display_video in the STDIO bridge, restore OpenCode first-prompt
TITLE_INSTRUCTION (skill_lookup), and update tool-list test expectations.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): leave user-owned hapi MCP entry alone on overlay cleanup
Only undo mcpServers.hapi when it still matches the exact entry this
session installed; concurrent Cursor/user edits of that key survive.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): exact-match auto-approve for display_image and display_video
Move media tools off substring name/id hints onto the exact-name set so
forged lookalike tools are not approved in default permission mode.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): drop dead Cursor bridge prompt; put guidance in MCP descriptions
Cursor must not get a user-turn media prepend (prompt-taint). Remove unused
HAPI_MCP_BRIDGE_PROMPT_CURSOR and embed DISPLAY_*_PROMPT_CURSOR in the
display_image/display_video MCP tool descriptions instead.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): require user approval for display_image and display_video
Those tools read arbitrary local paths into chat; keep them on MCP
approval_mode prompt and out of default-mode auto-approve exact names.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: re-trigger Codex PR review after provider 503
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): ignore URI-only ACP image blocks that read local disk
Passive ACP agentMessageChunk handling must not load file:// or bare
paths; local media goes through prompt-gated display_image/display_video.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): allowlist MP4 ftyp brands for video sniffing
Reject HEIC/HEIF and other non-video ISO-BMFF containers instead of
treating every non-AVIF ftyp as video/mp4.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): keep Cursor ACP startup if MCP overlay fails
Wrap installCursorMcpOverlay so a malformed project .cursor/mcp.json
cannot abort the session; continue without inline media tools.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): fail doctor inline-media when checks fail
Exit non-zero whenever required checks fail, even if an active
hapiMcpUrl bridge is present.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): expect display_video when change_title is disabled
Native ACP title mode still exposes display_image and display_video;
update startHappyServer test after rebase onto 0.23.4.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): keep ACP title sync synchronous outside media queue
session_info_update title forwarding (#1028) must not wait on the
async message-handler queue used for inline media ordering.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): sniff media headers only; advertise OpenCode display_video
Read 16 bytes for detectMediaTool instead of the whole file, and include
hapi_display_video in OPENCODE_NATIVE_TOOL_INSTRUCTION for remote ACP.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): show Cursor generate_image inline in HAPI chat
cursor/generate_image only emitted a tool card; register filePath or
base64 imageData into generatedImages and emit generated_image so the
web chat card renders (issue #956 / swear01 report).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): ignore path-only Cursor generate_image reads
Path-only filePath registration bypassed permission-gated display_image /
display_video MCP tools. Keep base64 imageData only; local paths must go
through MCP approval.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): gate inline media base64 length before decode
Reject oversized ACP/Cursor base64 payloads by character count so the
CLI never allocates past the 25 MB generated-image cap.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): require EBML DocType webm for inline video sniff
Bare EBML magic matches Matroska/MKV too; only accept DocType webm.
Also restore annotated Playwright cursor in annotatedVideoUseOption.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(scripts): read 128-byte header for WebM DocType sniff
detectMediaTool only loaded 16 bytes, so EBML DocType webm was often
missing and valid WebM files fell through to display_image.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): compare generated-image source by value in reconcile
Wire normalization allocates a fresh source object each pass; reference
equality forced media-card recomputation on every reload/SSE refresh.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): inject Cursor MCP enable for overlay unit tests
installCursorMcpOverlay always spawned `agent mcp enable`; tests now pass
a noop so the suite never shells out to a real Cursor binary.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): shell-quote doctor inline-media helper command
Paths and session prefixes with spaces/metacharacters broke the copied
snippet; JSON.stringify each interpolated argument.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(cli): fix doctor inline-media quote path expectation
Repo root from scriptPath is three levels up (cli/), not the parent of cli.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli/web): per-session Cursor MCP overlay id and bound tiny-image scale
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): redact generate_image base64 from logs and fix doctor MCP ids
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): harden inline-media doctor for packaged installs and hub headers
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): lock Cursor mcp.json updates and bound ACP media filenames
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): preserve mcp.json mode and token-scoped overlay locks
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): publish Cursor MCP lock owners via link(2) and treat EPERM as alive
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): fail closed on stale MCP locks; keep concurrent mcp.json top-level keys
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): roll back Cursor MCP overlay when agent mcp enable fails
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): await ACP session queue in suppressUpdatesDuring tests
#958 queues handleUpdate for media registration; upstream compact tests
assumed sync delivery after restore.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): capture ACP handler at enqueue; keep display_video manual
Close two Major review findings on #958: suppress queue leak after
restore, and Claude --allowedTools auto-approving local-path video.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: write through symlinked mcp.json; lazy-load inline video
Preserve user Cursor MCP symlinks on atomic overlay writes, and require
explicit Load video before fetching large generated-video blobs.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): use valid TerminalToolDisplayMode in media card test
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(scripts): require unique session prefix in display helper
Reject ambiguous prefix matches so images/videos cannot land in the
wrong HAPI chat when multiple agent session ids share a prefix.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): always cleanup Cursor MCP overlay on teardown
Run overlay cleanup in finally so cancelAll/disconnect failures cannot
leave a dead hapi-<sessionId> entry in .cursor/mcp.json.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): handle Copilot generated_image; refuse MCP symlinks
Unblock typecheck after Antigravity/Copilot merge, and fail closed when
.cursor/mcp.json or .cursor is a project-controlled symlink.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: abort restore deliveryMode; prune dead Cursor MCP overlays
Unblock web typecheck after steer merge, and recover orphaned hapi-*
mcp.json entries via HAPI_MCP_OVERLAY_PID ownership stamps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): recover dead-PID Cursor MCP overlay locks
Token-matched unlock so a crash mid-lock no longer permanently disables
inline media; keep live-owner waits identity-safe.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): serialize Cursor MCP stale-lock recovery
Acquire an exclusive recovery lock before token-matched unlink so two
recoverers cannot remove a successor's live mcp.json lock.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): fail closed on stale Cursor MCP overlay locks
Withdraw racy auto-recovery: pathname check-then-unlink/rename can steal
a successor lock. Stale locks throw with an explicit rm hint instead.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): drop duplicate deliveryMode on abort restore
Merge left both steer and queue; keep queue so retries after abort
do not re-bind to a later Pi turn.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): bound inline media reads on open fd
Close TOCTOU between pathname size check and readFile for display_image /
display_video and registerGeneratedImageFromPath. Also preserve non-PID
env edits on Cursor MCP overlay cleanup.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): repair happyMcpStdioBridge test syntax after merge
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): write Cursor MCP overlay to ~/.cursor, not the project
Keep ephemeral hapi-<sessionId> bridges out of the checked-out tree so
agents cannot git-add a live loopback URL. Tests inject mcpConfigDir.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): point Cursor MCP diagnostics at ~/.cursor/mcp.json
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(media): add audio and file display
---------
Co-authored-by: HeavyGee <133152184+heavygee@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
* refactor(agy): make sweepAgyHookCarriers async via fs/promises
Convert the carrier sweep's directory scan (readdir/lstat/readFile/rm)
from sync fs calls to fs/promises, so it no longer blocks the event
loop while it runs. The call site in runAgy.ts still awaits it in
place, so this preserves the current blocking-before-hook-server
ordering exactly -- only the mechanism changes.
Also adds racing-safety tests proving a carrier created after the
readdir() snapshot was taken (or written by this session's own
prepareAgyHookCarrier() while a sweep is in flight) is never examined,
since decoupling the call site (next commit) makes that interleaving
possible for the first time.
* perf(agy): decouple carrier sweep from session startup
sweepAgyHookCarriers is a backup path -- normal teardown already
removes a carrier via cleanupAgyHookCarrier, so sweep only matters
after a crash. There is no reason for it to delay this session's own
startup (hook server, carrier prep, PTY spawn).
Now that it is async (previous commit), fire it without awaiting it
instead of blocking on it before startHookServer. It runs concurrently
with this session's own prepareAgyHookCarrier() call further down;
the previous commit's racing-safety tests prove that interleaving is
safe. Still guaranteed to never throw or leave an unhandled rejection.
* refactor(agy): add a process-lifetime cache for carrier scope
The upcoming macOS/Windows identity probes are async child-process
calls (ioreg/sysctl, reg query), but writeOwnerMetadata is called
synchronously from prepareAgyHookCarrier -- including from
agyPtyLauncher.ts's respawn path, which must stay synchronous per its
fail-closed contract. A warm cache lets that synchronous call read a
value computed ahead of time instead of needing to await a probe.
Adds computeLocalCarrierScopeAsync (platform dispatcher, Linux-only
for now -- delegates to the exact same sync read computeLocalCarrierScope
already does, so no platform's observable output changes here),
warmCarrierScope (populates the cache once, including caching a
failed probe so it is never retried), and resolveLocalCarrierScope
(used by sweepAgyHookCarriers; bypasses the cache for any non-default
probe so the many existing custom-probe tests keep forcing a fresh
computation per call). writeOwnerMetadata reads the cache first and
falls back to the existing synchronous Linux computation when the
cache was never warmed -- unchanged behavior wherever nothing calls
warmCarrierScope yet.
* feat(agy): enable carrier sweep on macOS
computeLocalCarrierScope was Linux-only, so sweepAgyHookCarriers was a
no-op on macOS -- only crash leftovers there ever accumulated (normal
teardown still works via cleanupAgyHookCarrier), but they accumulated
forever.
Adds a strong-identity scope for macOS: IOPlatformUUID (ioreg) +
kern.bootsessionuuid (sysctl), the macOS analogue of Linux's boot_id
-- NOT kern.boottime, which a live re-measurement showed drifts by
over a second across 8 days on the same boot (recomputed from
NTP-adjusted wall clock time under the hood). The probe runs by
absolute path via execFile (never a shell, never PATH-dependent) with
a 2s timeout; a failed or timed-out probe still resolves to undefined,
preserving sweepAgyHookCarriers's existing "cannot identify -> preserve
everything" contract unchanged.
Windows is deliberately not enabled. MachineGuid -- the obvious
candidate for a win32 scope -- is a machine identifier, not a
PID-space identifier: it is written once at OS install time and is
NOT regenerated by cloning a disk image (that is exactly what sysprep
exists to fix). Two clones of the same image sharing a HAPI_HOME (SMB
share, sync folder, shared VM folder) would compute the identical
win32:<guid> scope while having completely independent PID spaces,
so sweep could delete a live session's carrier and its
--dangerously-skip-permissions approval bridge with it. No cheap
per-boot alternative exists on Windows: no boot-id registry key,
Get-CimInstance's LastBootUpTime measured 1.4-2.5s per call (an order
of magnitude too slow for identity plumbing), and net
statistics/systeminfo output is locale-dependent. computeLocalCarrierScopeAsync's
docstring records the full reasoning and the bar for re-enabling it
(a boot-scoped, not machine-scoped, identifier cheaper than CIM).
Windows carriers keep accumulating exactly as before this change --
this is a purely additive capability for macOS.
Wires warmCarrierScope into runAgy.ts's PTY setup: fired without
awaiting it right after the sweep call (so the probe cost -- two
child processes on macOS -- overlaps with hook server startup instead
of adding to it), then awaited immediately before prepareAgyHookCarrier()
so its synchronous owner.json write reads a warm cache. agyPtyLauncher.ts's
respawn path needs no equivalent wiring: it always runs in the same,
by-then-warm process.
* feat(settings): onboard hub transcription provider credentials in UI
Env-only keys made dictation invisible; Settings can now add/edit/clear
hub-side credentials (masked), with env still winning as override.
Refs tiann/hapi#1384.
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(settings): onboard voice-assistant backends alongside dictation
Same Settings credential surface now covers ElevenLabs, Gemini Live, and
Qwen Realtime (alias env pairs), not only transcription providers.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): address PR #1392 Major credential onboard findings
Alias env locks, non-destructive Save (omit empty fields), and
owner-only settings.json permissions for hub-stored provider secrets.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): harden credential onboard for second-pass Majors
Owner-namespace gate, stage-then-sync env after persist, and
per-field OpenAI-compatible editability under mixed env locks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): serialize settings RMW and clear partial compatible creds
Per-file settings lock for concurrent credential PUTs, and Clear shown
for partial OpenAI-compatible entries (key/url/model alone).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): serialize all settings writers via updateSettings
Route credentials, relay auth, generators, server settings, and CLI
token persistence through a locked RMW helper; reset Clear form state.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): share cross-process settings lock with CLI
Extract withSettingsFileLock for hub+CLI, keep owner-only 0o600
rewrites, and race hub credential updates against CLI-style writers.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): keep UI secrets out of process.env; PID-own settings locks
Settings-backed provider credentials now live in an in-memory overlay
(getProviderEnvironment) so tunnel/ACP/Codex children do not inherit them.
Settings file locks record pid+token and only reclaim dead or legacy locks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): never reclaim ownerless settings lock sidecars
wx creates the lock path before the owner JSON is visible; unlinking
null owners let a waiter steal a live acquisition and collide on
settings.json.tmp (CI ENOENT). Only reclaim parsed owners with dead PIDs.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): reclaim dead locks via rename; clean up failed publishes
Stale reclaim renames the sidecar to a unique break path and re-verifies
the expected dead owner before deleting it, so a loser cannot unlink a
successor's live lock. Failed owner writes unlink the wx sidecar.
Reclaim uses a sync owner read so contenders do not all observe one
dead owner across an await and race the exclusive create.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): reclaim dead locks under exclusive reaper sidecar
Stale reclaim now takes a fixed settings.json.lock.reap lock, re-validates
pid+token, then unlinks — so a delayed contender cannot move a successor's
live lock aside. Also document providerCredentials in settings.schema.json.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): fail closed on corrupt CLI settings; backoff busy reaper
CLI updateSettings now uses a strict read that rejects invalid JSON
instead of treating errors as {}, which could wipe providerCredentials.
Settings lock reclaim sleeps when another process holds .reap so retries
are not burned synchronously.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): publish locks via candidate+link; fix CLI vitest hoist
Acquire settings locks by writing a complete candidate then linkSync to
the fixed path so a crash cannot leave an empty live sidecar. Fix the
CLI persistence regression test to create its temp dir inside vi.hoisted.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): replace bespoke lock with proper-lockfile; hide tenant creds UI
Codex kept finding crash windows in hand-rolled lock sidecars. Switch the
shared settings lock to proper-lockfile's mkdir + mtime lease. Hide the
owner-only credentials editor from non-default namespaces on the voice page.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(settings): adapt sessionSummaryContract to outcome updateSettings
Rebase onto main brought #1376 unique tmp + outcome-shaped writers;
wire sessionSummaryContract and the write-failure credential test to match.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: retrigger CI after rebase onto upstream/main
Empty commit — Meta reported no checks on da0c6c258 after tip-forward rebase.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: settings toggle for AGENT_NOTIFY_SUMMARY contract injection
Add a hub-persisted, default-off Settings control so operators can opt agents into emitting the trailing AGENT_NOTIFY_SUMMARY line. Propagate the resolved flag on CLI session bootstrap and inject at call time for Claude, Codex, OpenCode, and Grok (Cursor still unsupported).
Closes#1375
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: lock hub settings RMW and restore abort deliveryMode
Serialize settings.json updates with the shared .lock protocol and unique
temp files so the new hub toggle cannot clobber CLI/relay fields under
concurrency. Also supply deliveryMode on abort send-error restore so web
typecheck (and CI) pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): wrap SettingsGeneralPage tests with QueryClientProvider
The hub-settings toggle uses TanStack Query; the settings page suite
was rendering without a QueryClient and blew up CI.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): defer summary-contract toggle until settings load
Avoid rendering an interactive false switch while the hub GET is still
in flight, which could overwrite an enabled preference on early click.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): clarify Grok coverage for summary-contract toggle
Local Grok has no instruction inject path; settings copy now matches
remote-only Grok support (and still excludes Cursor).
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Normalize usage input at parse time, mark inclusive producers, rebuild derived usage indexes, and preserve valid primary usage when cache partitions are malformed.
Fixes#1389
* feat(cli): MCP list_peers + runner hub auth inheritance
Runner-spawned agents could not discover same-hub peers without
sitting on the hub host or pasting a session id. Add MCP list_peers
(in-process credentials), export HAPI_API_URL/CLI_API_TOKEN after
auth init for shell fallbacks, and clearer auth failure hints.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): do not export default hub URL into HAPI_API_URL
exportHapiHubAuthEnv was writing the implicit localhost default into
process.env, which made maybeAutoStartServer skip starting the bundled
hub. Only export HAPI_API_URL when the URL came from env or settings;
always still export CLI_API_TOKEN. Also fill missing deliveryMode on
abort restore so web typecheck matches RawSendError (main tip unblock).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): widen initializeApiUrl mock return type in test
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): never export CLI_API_TOKEN; exclude self from list_peers
Keep settings/prompt-backed hub secrets out of wrapped agent env so
shell JWT+curl cannot bypass peer-tool approval. Fresh hapi re-reads
settings; env-backed tokens already inherit. list_peers omits the
calling session from the shortlist.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): resolve peer labels via summary/path like web titles
list_peers was showing (unnamed) for ordinary sessions because titles
live in metadata.summary.text. Match web getSessionTitle and collapse
whitespace so each peer stays one agent-readable line.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli,hub): emit full peer ids and honor GET /sessions?limit
Short 8-char prefixes collide across UUID namespaces; print full ids so
resolveSessionByPrefix stays unambiguous. Honor optional limit after sort
so listPeerSessions stops loading the whole namespace for scheduled counts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(hub): type sessions limit test mock as Map<string, number>
CI tsc rejected Map<string, null> for getNextScheduledAtBySessionIds.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli,hub): unbounded ping resolve; peer list order=updatedAt
Keep GET /sessions?limit only for discovery callers. ping/inspect omit
limit so full UUIDs outside the first 500 stay resolvable. Peer lists
pass order=updatedAt so truncation matches newest-first. Basename
fallback splits Windows paths.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): auto-approve ACP title List Peer Sessions
Permission derivation prefers request.title; match the MCP tool title
form so default-mode ACP sessions do not prompt on discovery.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): pad list_peers fetch; split hub URL vs token hints
Fetch limit+2 when excluding the caller so overflow still surfaces at
limit=100. Clarify that auth login only saves the token, not HAPI_API_URL.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli): use boolean overflow for ping-peer --list
Match MCP list_peers: fetch limit+1 and mark hasMore instead of claiming
an exact omitted count from a 200-row sample.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(hub): tolerate mocked machineCache without expireInactive
CI flake: 5s inactivity tick hit test doubles that only stubbed
getOnlineMachinesByNamespace. Optional-call + stub the method.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(pi): advertise runner capabilities at registration and on connect
The hub only persists registration-time runner state for brand-new
machines, and the socket heartbeat replays only what the hub already
persisted. A runner upgraded in place (e.g. to 0.27.0, which adds
piExistingSessionResume) never gets its new capabilities observed: the
stale runner_state stays in the hub DB and Pi resume fails with
"Pi resume requires an upgraded runner".
- shared: RUNNER_CAPABILITIES single source of truth
- runner: advertise capabilities again on every socket connect, so a
reconnected runner self-heals without a hub-side change
- hub: merge registration-time capabilities into an existing machine's
runner_state, leaving live fields (status/pid/startedAt) socket-owned
* fix(hub): backfill runner capabilities when metadata also changes
The existing-machine registration path returned early after the metadata
merge, skipping the capabilities backfill whenever registration changed
metadata too. An upgraded runner necessarily changes happyCliVersion, so
its first upgraded registration missed the backfill and Pi resume could
still fail until the async socket state update landed.
Merge both fields in the same call and return the latest row; add a test
covering metadata and capabilities changing together.
* feat(pi): expose local session transcripts over machine rpc
* feat(pi): import and incrementally reconcile local sessions
* feat(web): import and resume local Pi sessions
* build(web): precache the expanded app bundle
* fix(pi): harden imported history reconciliation
* fix(pi): persist import cursors and media placeholders
* docs(web): warn about concurrent native Pi writers
* feat(pi): sync native history from session menu
* fix(pi): address import review findings
* fix(web): preserve delivery mode for abort restores
* test(hub): use the Bun test runtime
* fix(pi): preserve custom names during sync
* docs(pi): clarify concurrent session guidance
* perf(hub): index imported Pi sessions once
* perf(hub): reuse Pi import lookup for batches
* fix(web): ignore stale Pi session scans
* feat(a2a): steer session citations toward inspect_peer
Copy-reference prose and markdown /sessions/<id> links both parse to hub
ids; MCP/CLI descriptions and flavor prompts forbid treating them as local
FS paths so agents call inspect_peer first (tiann/hapi#1370).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(a2a): fail closed on ambiguous session citations
Codex #1373: do not silently pick ids[0] when a paste contains multiple
/sessions/ links (shared by inspect_peer and ping_peer). Also strip
trailing prose punctuation from bare citation ids.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(a2a): prefer Copy-reference path over title /sessions/
Codex #1373 MINOR: titles containing /sessions/<other> must not make
normalizeSessionIdPrefix fail closed on an otherwise valid paste.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(a2a): do not short-circuit multi-citation Copy-reference pastes
Codex #1373 MAJOR: only treat parenthesized Copy-reference as canonical
when the paste is that citation alone (plus optional steer suffix).
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* refactor(agy): extract brain UUID adoption from the PreToolUse hook handler
Pull the first-wins UUID-adoption block out of onPreToolUse into a
standalone adoptBrainUuidIfUnset() helper so it can be shared with the
upcoming PreInvocation hook handler without duplicating the guard logic.
No behavior change.
* feat(agy): discover the brain UUID from agy's PreInvocation hook
PreToolUse only fires once a tool actually runs, so a tool-free turn
(e.g. a plain "hi") never gets a brain UUID from it. Register agy's
PreInvocation hook alongside PreToolUse: it fires before every model
call regardless of tool use, carries the same conversationId, and lets
discovery resolve deterministically instead of depending on a tool
being invoked.
PreInvocation uses agy's flat hook schema (distinct from PreToolUse's
grouped {matcher,hooks} shape) and a short 5s timeout, since it blocks
the agent loop synchronously on every model call. The forwarder gains
an explicit --event flag (default pre-tool-use, unchanged) to route to
a new /hook/agy-invocation endpoint; that path is fail-open (always
responds 200 / stdout "{}") since a lost discovery signal must never
block a model call, unlike a permission decision.
Both hooks funnel into the same first-wins UUID adoption guard, so a
resume-seeded sessionId is never overwritten by either.
* refactor(agy): drop transcript content-matching now that the hook is authoritative
The scanner's content-match discovery was the fallback for turns where
the PreToolUse hook never fired (no tool used). Now that PreInvocation
covers exactly that case, the fallback never actually gets a chance to
run in practice: carrier hook loading fails all-or-nothing (both events
live in the same hooks.json), and a failed carrier already aborts the
PTY session before discovery matters. Keeping unreachable code around
just keeps the risk it was flagged for — attaching to an unrelated agy
session that happens to share the same first prompt.
Removes the scan-window heuristics, the wrapped-USER_REQUEST content
matcher, and the ambiguity-reporting path entirely. The scanner is now
purely reactive: it watches nothing until onNewSession() (driven by a
hook) tells it which brain to watch. extractUserRequest/
normalizeUserInput and the launcher's userRequestMatches are untouched
— they answer a different question (did the web-submitted message echo
back into the PTY), which hook payloads carry no text to answer.
* feat(agy): drop the PreInvocation discovery hook once the conversation is identified
PreInvocation fires on every model call (~424ms round trip measured), but the
brain UUID only needs to be discovered once. agy re-reads hooks.json before
every model call, so the carrier's hooks.json can be rewritten in place (via
a temp-file-plus-rename atomic write) to drop the PreInvocation block the
moment handleSessionFound confirms the UUID, leaving PreToolUse untouched.
PreInvocation is restored before every respawn, since a resume that silently
fails would otherwise leave no way to discover the replacement conversation's
UUID. If the carrier itself has vanished (e.g. /tmp's tmpfiles.d sweep on a
long-lived session), it is rebuilt from scratch and hookCarrierDir is
repointed for the next agy spawn.
* refactor(cli): extract resolveHapiHomeDir from Configuration's constructor
Configuration.happyHomeDir is a singleton computed once at process
startup, which the upcoming agy carrier relocation can't reuse directly
without breaking per-test HAPI_HOME isolation. Extract the priority
logic into a standalone, env-injectable function with no behavior
change.
* feat(agy): relocate the hook carrier under HAPI_HOME and sweep dead ones
Carriers used to live under mkdtempSync(join(tmpdir(), 'hapi-agy-
carrier-')). On this machine /tmp is swept by tmpfiles.d after 30 days,
and agy re-reads hooks.json on every model call (not just at spawn), so
a long-lived session's carrier could be deleted out from under it,
silently killing both the permission bridge and discovery at once.
Move carriers to <HAPI_HOME>/agy-carriers/<random>/, record owner
metadata (pid, startedAt) at the carrier root (outside .agents/, which
agy itself reads), and sweep carriers whose owner process has
confirmed-died at session start. Liveness is judged strictly by
process.kill(pid, 0): ESRCH means dead and safe to remove, EPERM means
alive but not ours and must be preserved, anything else is unknown and
also preserved. Carriers with unreadable or missing owner metadata
(pre-existing or corrupted) are only swept once old enough to rule out
a carrier still mid-creation. Every ambiguous case defaults to
preservation, since deleting a live session's carrier is far more
costly than leaving an inert directory on disk.
* fix(agy): abort respawn instead of spawning agy without a permission bridge
syncPreInvocationHookForLaunch used to log-and-return when the hook
carrier could not be recreated before a respawn, letting launchOnce
spawn agy anyway with --dangerously-skip-permissions and no PreToolUse
hook wired up — every tool call would auto-approve with nobody in the
loop. Throw instead, matching runAgy.ts's existing fail-closed contract
for the initial carrier, and notify the web chat via sendSessionEvent
so the abort isn't silent.
* fix(agy): sweep carriers only when the owner is positively identified
An unreadable owner.json is not evidence of staleness: a live session
whose metadata cannot be parsed would have its carrier removed once it
aged past the threshold, taking the PreToolUse approval bridge with it.
Hostname is not an identity either — containers sharing a HAPI_HOME can
share a hostname while their PIDs live in unrelated namespaces, so a
liveness probe there reports ESRCH for a process that is very much alive.
Scope the owner record to the boot id and PID namespace on Linux, fall
back to a distinguishable hostname-only scope elsewhere, and delete only
when the scope matches and the pid is confirmed dead. Carriers whose
owner cannot be identified are now kept.
* fix(agy): drop the hostname scope fallback rather than guess ownership
Hostname is not an identity. Where /proc is unavailable, two machines or
containers sharing a HAPI_HOME and a hostname compute the same scope, so a
pid that is live on the owning system reads as ESRCH here and its carrier
is deleted — taking the PreToolUse approval bridge with it while agy runs
with --dangerously-skip-permissions.
Without a strong boot and PID-namespace identity the scope is now
undefined, which makes the sweep preserve everything. Orphaned carriers
accumulate on those platforms instead, which is the cheaper failure:
ordinary teardown still removes carriers, so only crash leftovers remain.
* fix(agy): point carrier failures at HAPI_HOME instead of the temp dir
The carrier moved under HAPI_HOME/agy-carriers earlier in this branch,
but the abort messages still told users to check the temporary directory.
On a custom or quota-limited HAPI_HOME that sends remediation to a
filesystem that has nothing to do with the failure.
Both the initial-preparation path and the respawn-recreation path carried
the stale hint, so both are updated — otherwise the same failure would
suggest two different places to look.
* test: reproduce issue #865
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(opencode): surface stall errors and clear thinking spinner (closes#865)
Route quota/rate-limit/HTTP-2 cancel stderr through error-styled agent
messages, cancel the in-flight prompt, and clear thinking so the web UI
does not stay stuck while OpenCode retries upstream.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(opencode): non-stall stderr surfaces error without canceling prompt
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(acp): use agent-neutral retry stderr message in shared transport
AcpStdioTransport is shared by Cursor, Gemini, Kimi, and OpenCode.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(opencode): surface stall errors and clear thinking spinner
* fix(acp): parse split stderr stall records
Buffer stderr through newline-delimited records so split retry and HTTP/2 cancel
signatures still clear stalled OpenCode turns, and retain one web error
presentation branch.
Verified: targeted ACP and presentation tests plus CLI/web typechecks.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(acp): emit stalled stderr tails immediately
Classify buffered retry and HTTP/2 cancellation tails as soon as their signatures
are complete, without waiting for the ACP process to close.
Verified: targeted ACP transport test and CLI typecheck.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(acp): flush newline-free quota errors
* fix(acp): surface newline-free stderr errors
* fix(acp): scope stall cancellation and bound stderr
* fix(opencode): bind stall cancellation to prompt RPC
* fix(acp): preserve partial stderr until classification
* fix(acp): report complete cancellation records
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(pi): complete RPC interaction parity
* feat(pi): integrate native conversation history
* fix(pi): harden RPC lifecycle boundaries
* fix(pi): address review lifecycle and upload boundaries
* fix(pi): release history transaction on rollback deadline
* fix(pi): isolate preflight and timed-out mutations
* fix(pi): preserve retry and editor boundaries
* fix(pi): disable unavailable history synchronization
* fix(pi): gate fallback readiness on history baseline
* fix(pi): bind uploads and retire extension requests
* fix(pi): preserve canceled and legacy stream boundaries
* fix(pi): preserve native fork runtime state
* fix(pi): persist dialogs and preserve select values
* fix(pi): keep upload authorization path-stable
* feat(pi): preserve native steer semantics
Route ordinary sends during an active Pi main turn through native steer while keeping explicit queue delivery on the existing composer gestures. Persist the delivery contract across Hub replay and Web retries, and guard stale steer dispatch with streaming generations and ordered prompt fallback.
* fix(pi): queue deferred steer deliveries
Keep native steer only for the initial live emit. Reconnect replay, CLI backfill, clear-gate release, and mature delivery now downgrade turn-scoped steer intent to the durable HAPI queue without mutating stored provenance.
* fix(pi): retain abort guard through preflight miss
Treat an immediate no-active abort rejection as a possible async-preflight race. Keep the existing abort boundary alive so a late agent_start receives the compensating abort before queued work is released.
* fix(pi): queue stale steer retries
A failed send no longer reuses turn-scoped steer intent after its original Pi generation is lost. Text restoration, attachment retry, and legacy retry provenance all enter the durable HAPI queue while fresh ordinary sends retain native steer behavior.
* fix(pi): invalidate rejected abort generation
After a no-active preflight abort waits through late-start compensation, mark the target stream idle while the runtime mutation lease is still held. Waiting native steers therefore fall back instead of entering the aborted generation.
* fix(pi): queue idempotent steer retries
Track whether a localId insert created a new row. Initial inserts may retain live Pi steer, while duplicate-localId retries deliver a queue-safe view of the stored row without overwriting its original provenance.
* fix(pi): sync command-only history before fallback
Read the Pi append log before retiring a successful prompt that produced no agent lifecycle. Preserve FIFO history associations across missing entry events, and fail the wrapper closed if that mandatory synchronization cannot be completed.
* feat(web): in-place cursor variant drill-down (closes#48)
Rebased onto upstream/main: iOS-style nested picker keeps overlay open on
multi-variant base pick, applies default variant immediately, dismisses on
variant selection; preserves upstream Pi model panels and Codex Fast mode.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web+cli): accept bare Cursor ACP model ids in picker catalog
Current Cursor ACP returns bare bases (composer-2.5, …) with empty
cliModelSkus. The bracket-only wire gate emptied the catalog so the
picker showed only Default. Treat bare non-default ACP ids as catalog
rows, keep CLI effort/speed SKUs as variants, and widen SKU enrichment
the same way. Closes#1129.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): ignore stale selectedModelVariant during Cursor base drill-down
Only highlight a session variant when it is still among the visible
rows, so a multi-variant base switch uses the new default until parent
state catches up (Codex Minor on #947).
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(cli+shared): do not attach CLI variant SKUs to bare ACP catalogs
Bare ACP bases cannot express effort/speed (apply is model+fast on
parameterized wires). Drop suffixed SKUs unless a base has bracket
wires, and refuse matchCliSkuToAcpWireId collapse onto bare-only rows.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(web): serialize Cursor model applies across base/variant picks
Drill-down default apply and a quick variant click could race setModel
RPCs; last-finisher wins. Queue Cursor applies in SessionChat so the
explicit variant cannot be overwritten by a late default.
Co-authored-by: Cursor <cursoragent@cursor.com>
* test(web): align cursor picker auto-row label with upstream Auto
Rebase onto main picked up Default→Auto rename; keep #1129 coverage.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
* fix codex stale terminal recovery
* fix(codex): ignore stale retry failures
* fix(codex): ignore stale retry terminal failures
Only task completion may bypass stale-turn duplicate handling during same-thread recovery, preventing delayed failed events from finalizing the active retry.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(codex): separate stale turn recovery guard
Limit matching-thread status events to missing turn IDs so delayed status failures cannot affect an active retry turn.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(codex): scope stale completion recovery turn
Accept a stale completion only for the immediately finalized turn, so older retries cannot finalize the active turn.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Ignore Cursor's Using worktree stdout banner without masking other
non-JSON ACP frames (markClosed + kill). Skip --cursor-worktree when
spawn directory is already a linked git worktree so ACP can initialize.
Fixes#1085
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(cli): add GitHub Copilot CLI agent support via ACP
Wrap `copilot --acp --stdio` for remote sessions and spawn the native TUI locally, with full hub/web integration for spawn, resume, and permissions.
Fixestiann/hapi#362
Co-Authored-By: HAPI <noreply@hapi.run>
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat(copilot): agent modes, models, slash/file UX, local session sync
Add Interactive/Plan/Autopilot (fleet is slash-only), subscription-aware
model discovery, web StatusBar/permission UX, @ file mentions, and fix
local Safe Yolo plus session-id locator for handoff/resume.
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: re-trigger Codex PR review after auth outage
Co-authored-by: Cursor <cursoragent@cursor.com>
* chore: retry Codex PR review
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): preserve agent mode on resume and apply via ACP set_mode
Resume was dropping copilotAgentMode so Plan/Autopilot reset to interactive.
Also switch local/remote mode application to --mode / session set_mode instead of slash prompts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): wake remote loop when agent mode changes
Empty isolated queue tick lets setMode apply without inventing a user prompt.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): confirm mode changes before persisting
Await Copilot mode changes and expose discovered models so session state reflects backend acceptance.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): guard mode discovery and slash updates
Keep model probes within runner roots and preserve active sessions when mode switching is unavailable or rejected.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): preserve resume and auto semantics
Deduplicate Copilot resume rows, apply Auto explicitly, and fail closed on denied permissions.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): close permission and model discovery gaps
Keep write-capable commands pending in read-only mode, extend model probe RPCs, and preserve explicit model validation before session creation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): persist runtime model and agent mode
Fallback to ACP model options when direct model switching is unavailable and retain Copilot agent mode across hub restarts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): normalize composer auto selection
Use the null session sentinel for Copilot Auto so the composer selects and resets default models consistently.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix(copilot): reject local permission mode changes
* style(copilot): remove trailing blank line
* fix(copilot): secure local config handoffs
* fix(copilot): reject local agent mode slashes
* fix(copilot): reject mode changes during turns
* fix(copilot): consume rejected slash updates
* fix(copilot): preserve thinking across slash handling
* fix(copilot): stabilize async config changes
* fix(copilot): roll back rejected startup model
* fix(copilot): preserve cancellation and file mentions
* fix(copilot): hide local permission controls
* fix(deps): support clean workspace installs
* test(copilot): account for spawn mode argument
* fix(copilot): attribute usage to active model
---------
Co-authored-by: HAPI <noreply@hapi.run>
Co-authored-by: Cursor <cursoragent@cursor.com>
* feat: add cache-aware token usage dashboard
Track normalized Claude, Codex, and ACP usage with incremental SQLite backfill. Exclude imported transcript history, rebuild usage after history rewrites, and expose an owner-only dashboard with cache-aware totals and breakdowns.
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix: preserve usage model and local dates
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
* fix: normalize cached usage and timezone buckets
via [HAPI](https://hapi.run)
Co-Authored-By: HAPI <noreply@hapi.run>
---------
Co-authored-by: HAPI <noreply@hapi.run>
* feat(web): show hidden directories in workspace browser
Add optional includeHidden param to the machine list-directory RPC so the
WorkspaceBrowser can toggle hidden (dot-prefixed) entries. Default remains
filtered for backward compatibility; the toggle persists via localStorage.
* fix(web): disable show-hidden toggle while directory loading
Prevent overlapping list-directory requests with opposite includeHidden
values; the toggle is now disabled while a directory load is active.
* feat: add message-level conversation fork and rewind
Expose native Codex/Grok/Claude history controls through hub REST+RPC and web ConfirmDialog actions, without file rewind or composed forks. Also reconcile the duplicate hub V14→V15 migration so typecheck can pass.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: hydrate fork transcript and consume Claude --fork-session
Forked HAPI children now copy the source transcript prefix so navigation is not a blank thread, and Claude drops --fork-session after the first launch so relaunches do not branch again.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: harden fork/rewind concurrency and durable history points
Skip pending scheduled rows when hydrating fork transcripts, serialize fork/rewind per session, and persist conversation history points/indexes across existing-session bootstrap and Grok relaunches.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: close remaining fork/rewind races and UI anchoring
Block sends and scheduled maturation while history actions run, order fork prefixes by invocation time, inherit history locators into children, and only offer Fork current on the live tail boundary.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: address remaining fork/rewind bot findings
Materialize Claude --fork-session before the first child prompt, validate
HAPI history boundaries before native RPC, expose forkCurrent on a latest
user boundary, fully demote unsupported conversationHistory capabilities,
and fix the truncate test setup order.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: align fork-current ids and Claude fork bootstrap
Compare the latest fork boundary in assistant-ui threadMessageId space,
spawn Claude forks with the persisted session mode, and preserve
forkedFrom across existing-session bootstrap.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: close fork/rewind consistency holes at the contract layer
Hold the source history lock until Claude child binds a distinct native
id, persist Codex localId→turnId locators, and mark/block diverged
sessions when native rewind outruns HAPI truncate.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: use Codex stable lastTurnId for historical fork
Map HAPI's exclusive boundary to the previous turn's inclusive
lastTurnId so native fork context matches the hydrated transcript.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: require exact Grok native resume for fork children
Reject newSession fallback when forkedFrom is set, and keep the hub
history lock until the child binds the forked grokSessionId.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: kill active fork children before failed-fork cleanup
Bind/readiness failures can leave the child process running; deleteSession
rejects active rows, so terminate first then remove the HAPI session.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: close remaining fork lock, hydrate, and todos gaps
Reject mode switches during history actions, batch-copy fork
transcripts in one SQLite transaction, and rebuild todos after
fork hydrate / rewind truncate.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: allow Codex historical fork before the first turn
Use experimental beforeTurnId when there is no previous turn for the
stable inclusive lastTurnId boundary.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: mark Grok history busy immediately after dequeue
Hub idle checks clear once messages-consumed fires; hold the busy flag
across permission sync and rewind-points lookup before prompt starts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* fix: encode copied conversation history content
* fix(web): hide local conversation history actions
* style(codex): remove trailing whitespace
* fix(fork): preserve children when cleanup is unconfirmed
* fix(history): confirm cleanup and guard rewind divergence
* fix(history): probe capabilities before advertising
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
Add permission mode tracking across the local→remote switch so mode changes
made inside the interactive Claude TUI (shift+tab) are inherited when
launching remote. Previously, a mode picked in local TUI was invisible to
remote sessions.
Implementation:
- generateHookSettings: add trackPermissionMode option to register UserPromptSubmit
and PreToolUse hooks (their payloads carry permission_mode; SessionStart's does
not). Export buildHookSettings for testing and make matcher optional.
- New hookPermissionMode.ts: normalizer for hook permission_mode → HAPI mode
('manual' → 'default'; unknown modes like 'dontAsk' → null/ignored).
- runClaude.ts: generate a second, local-TUI-only hook settings file with
trackPermissionMode enabled (remote SDK process keeps the SessionStart-only
file — these hooks block Claude per prompt/tool, and remote state is owned
by hub/RPC). Hook callback inherits mode when session.mode === 'local': updates
currentPermissionMode, syncs session, pushes keepalive, emits permission-mode-
changed event.
- session.ts, loop.ts, claudeLocalLauncher.ts: plumb localHookSettingsPath
(defaults to hookSettingsPath when not provided).
When a batch is parked after a mode switch (pending delivery), the next
attempt that resumes from the parked batch must still seed modeHash/mode
into the relaunch gate. Without this, the gate keeps modeHash=null, so the
NEXT mode switch fails the hash check and gets silently fed into a process
spawned with the old --permission-mode (e.g. 'auto' silently running as
'default'). Fix adds hash to the pending type and seeds modeHash/mode when
delivering a parked batch.