Commit Graph
466 Commits
Author SHA1 Message Date
AnanovoandGitHub d644d4f30f feat(cli): follow conversation language in status prompt (#1584) 2026-08-16 23:06:06 +08:00
SSU-WEI HUANGandGitHub 6c6f4b4929 feat(agy): replace fragile PTY/TUI wrapper with headless print-mode transport (#1591)
Replace the Antigravity (agy) integration — a PTY wrapping the TUI with
output-marker scraping ('? for shortcuts', 'Generating', trust dialogs,
/model picker navigation, quota-screen regex) — with a headless print-mode
transport: every user turn spawns `agy -p <msg> --conversation <uuid>
--output-format stream-json`, and NDJSON events (init/step_update/result)
map onto the existing transcript-entry channel (sendAgySessionMessage), so
hub/web rendering is unchanged. ~8.3k LOC (incl. tests) removed.

Fixes #1588. Design: docs/design/agy-headless-transport.md.

CLI:
- new cli/src/agy/headless/: agyNdjsonParser (pure functions, malformed-line
  tolerance, step conversation-id adoption), AgyPlannerAccumulator (per-step
  delta accumulation with settling retries), AgyHeadlessDriver (per-turn
  spawn/kill loop, NDJSON chunk buffering, authoritative delivery ack via
  user_input/result, interrupt + retry + shutdown lifecycle with consume/
  restore, process-tree termination, SSH agent preserved, prompt log
  redaction, per-turn model snapshot with conversation-DB fallback)
- runAgy/loop/session rewired; agy is remote-only (no PTY, no local mode,
  no local-switch action); queued batches snapshot model/effort/mode
- deleted agyPty, agyPtyLauncher, agyHookCarrier(+scope cache), agyModelKeys,
  agyQuestionKeys, agyAskQuestion, agySessionScanner, agyPermissionHandler
  (+tests); buildAgyHooksJson removed; startHookServer agy-pre-invocation
  route → 200 no-op
- runner: agy reopen/resume via generic --existing-session-id; commands/
  agy.ts defaults remote; resume rejects ACTIVE agy sessions (remote-only,
  in-flight turns cannot hand off)
- MCP stays user-managed (agy reads ~/.gemini/config/mcp_config.json and
  workspace .agents/mcp_config.json natively in headless — verified)

Hub/web:
- machines.ts drops agy→pty forcing and rejects non-remote startingMode
- NewSession drops agy startingMode='pty'; terminal toggle disappears
  automatically; RemoteModeDisplay hides the local-switch hint when absent
- docs/guide/agents.md updated: headless print mode, no PTY/hooks, MCP via
  user's own mcp_config.json

Tests: 47 parser+driver tests (fake-binary e2e, chunk-split NDJSON, delivery
ack semantics, interrupt/retry/shutdown races, model attribution, EOF
framing, malformed envelopes); full suite green (cli ~2340, hub 1093,
web 2474, shared 262). Real-binary smoke on agy 1.1.13: single turn exit 0,
--conversation resume keeps the same conversation_id.
2026-08-16 22:44:27 +08:00
SSU-WEI HUANGandGitHub a6feb6e8ba feat: unified agent configuration descriptors (session config consolidation) (#1469)
* feat(config): add agent config descriptor protocol and advertise via runner capability

Introduce shared agent configuration descriptors covering model, effort,
permission, and secondary settings per agent flavor, plus the canonical
HAPI YOLO -> native permission mode mapping. Runners advertise the
builtin descriptors through the runner-state capability so hubs and web
can render configuration without hardcoded flavor branches.

Migrate the OpenCode create-session model picker from a bespoke radio
list to the shared SelectControl combobox.

* feat(web): render create-session permission from agent config descriptor

Replace the flavor-branched Grok/Codex-family/YOLO permission block with
a descriptor-driven PermissionField. Pi now reports permission as managed
instead of silently ignoring the YOLO toggle, and YOLO-only flavors show
the native permission mode the preference maps to.

Removes the superseded GrokPermissionModeSelector and
CodexFamilyPermissionModeSelector components.

* ci: retry flaky claudeRemote 5s-timeout failure

* fix(web): persist explicit OpenCode Default selection instead of restoring a concrete model

The parent initialization effect treated every null selected model as
'uninitialized' and auto-picked a concrete advertised model, clobbering
the user's explicit Default choice (and a restored Default preference).
null now means explicit Default and is preserved; only undefined (no
choice made yet) triggers probe-based initialization. Add parent-level
regression tests for Default persistence and remembered-model restore.

* fix(web): accept undefined selected model in OpencodeModelSelector props

* feat(web+cli+hub): unify create-session model/effort fields and add Pi model/effort support

Pi's agent config descriptor now advertises model (machine) and effort
(static thinking levels) for create AND session availability:
- cli: ListPiModelsForMachine RPC runs 'pi --list-models' (cached, inflight
  deduped) and parses the provider/model table; startup model match accepts
  provider-qualified ids
- hub: GET /api/machines/:id/pi-models route + rpcGateway/syncEngine passthrough
- web: NewSession renders Pi models grouped by provider through the generic
  ModelSelector and a new descriptor-driven EffortField (replaces the
  per-flavor LaunchEffortSelector/ReasoningEffortSelector pair); launch payload
  forwards Pi model + thinking-level effort (runner already supported --model/
  --effort for pi)

* fix(web): render Pi provider groups in ModelSelector and scope Grok availability warning

- ModelSelector now renders grouped options as <optgroup> (Pi models are
  provider-grouped; identical modelIds from different providers stay distinct)
- PermissionField only receives autoPermissionModeSupported for Grok — a
  cached Grok probe result no longer leaks the Grok warning onto other agents

Addresses HAPI Bot Minor findings on #1469.

* fix(web): drop Object.groupBy from ModelSelector; revalidate restored Pi models against the catalog

- ModelSelector buckets options with a reduce instead of Object.groupBy
  (Safari < 17.4 has no polyfill — New Session would throw on those clients)
- Pi restored model/effort are cleared when the value is absent from the live
  machine catalog, and Create waits for the catalog while a non-default Pi
  choice is being validated (mirrors Codex/Grok/Copilot handling)

Addresses HAPI Bot findings on #1469.

* fix(pi+web): serialize startup model before thinking level; hide Pi launch controls during history import

- PiSession gains startupModelSettled; the startup set_thinking_level waits for
  the requested model's set_model attempt to settle first, so a level the
  default model rejects is not lost before the requested model is confirmed
  (set_model and set_thinking_level were already serialized by the runtime
  mutation lock; this pins the model-first ordering)
- Create Session hides Pi model/effort controls while a Pi history import is
  selected — the import reopens the native session as-is and would silently
  ignore launch-only model/effort values

Addresses HAPI Bot findings on #1469.

* fix(pi): settle startup-model gate when model discovery fails or returns no models

A failed or empty get_available_models response would leave the
startupModelSettled gate unresolved, stranding a requested startup effort
indefinitely. Resolve the gate on the error path and the empty-models path;
adds regression tests for both.
2026-08-16 22:43:39 +08:00
SSU-WEI HUANGandGitHub ca6a6f0939 fix(cursor): retry transient ACP connection errors (#1541)
* fix(cursor): retry transient ACP connection errors

* fix(cursor): keep retry classification conservative

* fix(cursor): avoid retrying completed tool effects

* fix(cursor): require terminal retry failures

* fix(cursor): track retry activity across extension events

* fix(cursor): honor permission abort before retry
2026-08-16 22:42:10 +08:00
AnanovoandGitHub 7909c46fff feat(search): support wildcard patterns across search fields (#1571)
* feat(search): add wildcard matching to search fields

* fix(search): harden wildcard matching and file globs

* fix(search): align file matching with shared wildcard semantics

* fix(search): bound file wildcard search in runner

* fix(search): normalize outline queries through shared matcher

* fix(web): remove duplicate markdown test context field
2026-08-16 22:41:24 +08:00
KorenKritaandGitHub bf6bae1924 fix(pi): settle autonomous agent lifecycles instead of swallowing them (#1563)
* fix(pi): settle autonomous agent lifecycles instead of swallowing them

When Pi starts an agent lifecycle on its own — a subagent completion
wake-up, scheduled work — no HAPI prompt is in flight, so the previous
prompt lifecycle has already delivered its settlement and
deliveredSettlement is still true. agent_start unconditionally set
thinking=true, but every settlement path (agent_settled delivery, the
legacy agent_end grace, the prompt-lifecycle fallback) was gated shut by
that stale flag, so the autonomous turn's completion was swallowed:
thinking stayed true forever, the FIFO pump stayed blocked
(piIsStreaming), new messages queued without ever being sent, and abort
waited on a settlement that could never arrive. The only escape was
killing the session.

Open a fresh settlement cycle when agent_start/turn_start arrives with
deliveredSettlement still true: reset deliveredSettlement,
agentEndObserved and activeAgentSettledSeen so the existing settlement
paths (direct agent_settled, legacy agent_end grace) apply to the
autonomous lifecycle. Prompt-driven lifecycles are unaffected because
beginPromptLifecycle has already reset the flag before their agent_start
arrives; mid-cycle retries are unaffected because their cycle has not
settled yet.

Evidence: hapi log 2026-08-13-18-39-10-pid-85758.log — 19:24:07
agent_start (no prompt accepted) → 19:25:40 agent_end + agent_settled
both swallowed → session stuck thinking=true for 27+ minutes until
killed.

* fix(pi): generation-scope the settled callback against autonomous lifecycle races

Review follow-up (HAPI Bot, Major): deliverSettlement() notifies
onAgentSettled only after an async conversationHistory.syncEntries().
An autonomous lifecycle can begin in that window; the stale finally
callback would then mark the new lifecycle's abort boundary as settled
before it emits agent_settled.

Capture lifecycleGeneration at settlement time and skip the
notification when it no longer matches, and advance the generation when
agent_start reopens a settlement cycle for an autonomous lifecycle so
the in-flight callback turns stale.

New regression test holds syncEntries open across the autonomous
agent_start and asserts the stale callback does not settle the new
boundary (fails without the fix).
2026-08-16 22:40:15 +08:00
SSU-WEI HUANGandGitHub 44aff5a924 fix(codex): cache codex model list to avoid spawning app-server per request (#1534)
* fix(codex): cache codex model list to avoid spawning app-server per request

listCodexModels() spawned a fresh `codex app-server` subprocess on every
request: exec a version probe, boot the app-server, validate the ChatGPT
session (token refresh over the network when needed), list models, then
kill the process. Fleet measurement showed 0.5-4.4s per call on healthy
machines and 33s (initialize timeout) on a machine with a slow OpenAI
network path, and the web refetches on every session open / dialog mount
(staleTime 30s).

Mirror the opencode model cache: cache successful non-empty lists for 5
minutes and coalesce concurrent requests into a single app-server spawn.
Failures and empty results are never cached, so a broken machine retries
on the next request.

Fixes #1533

* test(codex): cover TTL expiration of the model list cache
2026-08-16 22:39:57 +08:00
Shawn TianandGitHub 5c81ed69e2 fix(runner) preserve native instructions (#1557)
* fix(codex): preserve native instructions

Keep HAPI guidance in the developer layer so app-server retains Codex persistence rules. Align long-running goal states with the Codex 0.147 protocol.

* fix(codex): filter new goal statuses
2026-08-16 22:38:15 +08:00
SSU-WEI HUANGandGitHub 1f2fbcb142 fix(web): map codex-enveloped compact-summary to the chat block (#1582)
* fix(web): map codex-enveloped compact-summary to the chat block

The merged #1570 renders Pi compaction summaries as a dedicated chat
block via the event envelope. A compact-summary arriving in the codex
payload envelope (older import paths, future producers) would still be
silently dropped by the codex-content filter; map it to the same
agent-event the live pi wrapper emits, mirroring the existing
context_compacted handling. Adds a normalizeAgent regression test and
tightens the /compact thinking-state test to assert the last keepAlive
flips true (RPC outstanding) then false (settled).

Verified: bun typecheck clean; web normalizeAgent 12/12, cli runPi
57/57 in an isolated TMPDIR.

* fix(web): remove duplicate showSessionSummaryInChat in markdown-a fixture

Regression from #1530: the fixture object literal sets the key twice,
which breaks `bun typecheck` on upstream/main (Test workflow failing on
push). One-line cleanup; no behavior change.

Verified: bun typecheck exit 0 across cli/web/hub.
2026-08-16 22:35:31 +08:00
901f17d0ca feat(pi): support Pi slash commands from HAPI web (compact/session/model/help) (#1570)
* feat(pi): support Pi slash commands from HAPI web (compact/session/model/help)

Pi runs as 'pi --mode rpc' over piped stdio, so TUI slash commands typed in
web chat previously fell through to the LLM as plain text and silently did
nothing (notably /compact).

- shared: add Pi builtin slash command list (help/compact/session/model) so
  the web / menu exposes them; web test updated to match
- cli: intercept Pi builtin commands in runPi's user-message path
  * /compact [instructions] -> Pi compact RPC (120s timeout, works while
    streaming; summary + token delta reported back as chat messages)
  * /session -> get_session_stats formatted stats
  * /model [modelId] -> list/switch via set_model
  * /help -> supported-commands list
  * other Pi TUI builtins (/tree, /export, /reload, ...) -> explicit
    terminal-only notice instead of silent LLM pass-through
  * unknown slash text still passes through (extension commands, skills,
    templates keep working)
- gate the prompt pump with piCompactInFlight so queued prompts are not
  rejected by Pi mid-compaction; buffer commands until ready like prompts
- ListSlashCommands RPC merges HAPI builtins with Pi extension commands
- tests: parser unit tests + runPi integration tests (compact execution,
  streaming steer interception, failure reporting, FIFO blocking, model
  switch, unsupported commands, slash list merge)
- docs: document Pi slash command support in docs/guide/agents.md

* fix(pi): address review findings on slash command lifecycle

- compact timeout: fail the session (indeterminate outcome, runtime lease
  poisoned) instead of reopening the prompt FIFO into a possibly-compacting
  Pi; pump only when cleanup has not been initiated
- special commands: release the cancellation reservation before executing so
  a cancel landing mid-command is not acknowledged (hub would delete the
  queued row while the command still runs)
- tests: drop the duplicated slash-command describe block; add focused tests
  for compaction timeout with a queued prompt and cancellation during an
  in-flight special command

* fix(pi): route slash commands through the prompt FIFO and reject ambiguous models

- slash commands now share the prompt FIFO with ordinary messages: a
  /compact or /model typed after a queued prompt dispatches only after it
  (and after the active turn settles), instead of jumping the queue from
  the preparation chain
- the pump dispatches special entries out-of-band while piSpecialCommandInFlight
  keeps the FIFO blocked; steer promotion refuses slash commands
- /model <id> prefers an exact provider/modelId match and reports bare IDs
  shared by multiple providers as ambiguous instead of picking the first
- tests: FIFO ordering (queued prompt before /compact), steer-delivered
  /compact queued until settle, ambiguous/qualified model selection

* fix(pi): keep /compact interruptible, honor extension precedence, require token boundary

- head-of-line /compact dispatches even while Pi is streaming (Pi's
  compact() aborts the active generation itself); every other queued item
  still waits for the stream to settle, preserving FIFO order
- discovered extension commands / prompt templates override same-name
  builtins at message time, matching the slash-list merge precedence
- parsePiSpecialCommand requires a command-token boundary, so path-like
  text such as /compact.md or /model/config stays an ordinary prompt
- tests: interrupt rule, extension collision, reserved-name path prefixes,
  non-compact commands waiting for stream settle

* fix(pi): honor cancellation acknowledged during slash-command discovery

A cancel arriving while the chain awaits get_commands (cold cache) was
acknowledged via the preparing reservation but never re-checked, so a
canceled /compact could still execute. Re-check the cancellation marker
after discovery and drop the message before dispatch.

* fix(pi): qualify /model selectors and report failed slash RPCs once

- /model lists provider-qualified selectors (openai/gpt-5.2) so duplicate
  bare IDs remain usable and copy-pasteable; current model is qualified too
- compact/set_model failures are owned by the awaited slash/config handlers:
  the common response handler no longer emits the raw Pi error a second time
- tests: qualified listing with duplicate providers, single-message failure
  reporting for rejected /compact and /model

* fix(pi): consume slash-command queue row at dispatch

Special commands (/compact, /session, /model, /help) are executed by HAPI
itself and never delivered to Pi as prompts. Consumption was deferred until
the command finished, so a /compact run — an LLM summarization pass that can
take minutes — left the row stuck in the web queued bar for its whole
duration, then surfaced as a sent message. Consume the row the moment
dispatch starts; failures still surface via the explicit event message.

* fix(pi): guard special-command dispatch against unexpected rejections

* ci: retry Codex PR Review after infra failure (proxy 503)

* fix(pi): keep session queued-thinking grace during /compact dispatch

The queued-thinking grace is session-scoped, so clearing it while
acknowledging a dispatch-time /compact row also drops the grace for any
prompt queued behind it. /compact keeps running for minutes without
toggling Pi thinking state, which would leave the web session looking idle
while compaction and the following prompt are still pending. Only the
fast, synchronous commands (/session, /model, /help) clear the grace.

* fix(pi): render compaction summary as a dedicated chat block

The manual /compact RPC result was reported as two plain message
events ("📦 Compaction completed (tokens: …)" + "📦 Compaction
summary: …"), which the web chat renders as tiny centered status
lines — unusable for a real summary payload. Emit a structured
compact-summary event instead (summary + token delta) and render
it as an independent block: header with the delta and the summary
markdown in a scrollable panel.

Also emit the same structured event when importing Pi session
files (compaction entries), and queue the event lossless like
other user-visible messages so a disconnect cannot drop it.

Verified: bun typecheck clean; bun run test exit 0 (cli 2481
passed, web 2451 passed, hub/shared clean); runPi/loop/apiSession/
piSessions/presentation suites green.

* fix(pi): address HAPI Bot findings on compact dispatch and import

- Track compaction as thinking for its whole duration: /compact runs for
  minutes without a Pi streaming event, so the 15s queued-thinking grace
  alone left the web session looking idle while compaction and any queued
  prompts were still pending (updateThinkingState around the compact RPC).
- Imported Pi compaction summaries must use the event envelope
  (content.type: 'event') like the live wrapper's compact RPC result; the
  codex payload envelope is dropped by the web normalizer. Extend
  CodexImportedMessageSchema with the event variant.

* fix(pi): /model retries discovery when the model cache is empty

Startup model discovery can be late or fail once; using only the cached
catalog made /model report valid models as unknown. getPiModels() falls
back to the get_available_models RPC on an empty cache, used for both
listing and switching.

* fix(pi): interrupt in-flight /compact on Abort; surface startup model rejection

- The Abort action no longer waits on the runtime-mutation lease when a
  manual /compact is in flight (compaction can hold it for up to 120s,
  blowing the 25s abort deadline and failing closed). It sends the abort
  RPC directly so Pi cancels its compaction AbortController; the compact
  RPC's 'Compaction cancelled' error is not double-reported as a failure
  since Pi already emits the compaction_end(aborted) lifecycle event.
- A rejected detached startup set_model now emits a visible ⚠️ event into
  chat instead of only a debug log, restoring the pre-existing behavior.

* fix(pi): close the Abort race when /compact is queued on the mutation lock

Abort previously assumed an in-flight /compact always had its RPC issued;
the command is marked active at queue dispatch, but the compact RPC is sent
only after the runtime-mutation lock is acquired. An Abort landing in that
gap acknowledged success while the compact RPC still ran afterwards.
Track the compact's rpcStarted/cancelled state: Abort cancels a not-yet-
started compact in place (the queued callback skips it), and interrupts a
started one via the abort RPC as before.

* fix(pi): persist provider-qualified selection after /model switch

The success path updated currentModel/currentProvider and keepalive with a
bare model ID, leaving metadata.piSelectedModel on the previous provider.
The web picker prefers that metadata for selection, context-window
resolution, and effort options, so a switch like openai/gpt-5.2 ->
azure/gpt-5.2 was invisible. Persist piSelectedModel with the full
provider/modelId pair on every confirmed switch.

* fix(pi): retire pending extension UI requests when /compact interrupts a turn

The streaming-interrupt path sent the compact RPC without cancelling
pending extension UI requests first, unlike the Abort path. Editor
requests have no timeout, so the web could stay stuck on a stale
input/permission card and a later answer could be routed to the aborted
turn. Cancel all pending requests (with a response) before compacting.

* fix(pi): fail closed when the direct compact-abort RPC times out

The in-flight /compact abort branch awaited the abort RPC without the
ordinary Abort path's timeout handling: an unanswered abort left the
compaction outcome indeterminate (the compact RPC keeps the mutation
lease for up to 120s) while the wrapper still looked live. Fail the
session on PiRpcTimeoutError, mirroring the standard abort fail-closed
path.

---------

Co-authored-by: swear01 <swear01@users.noreply.github.com>
2026-08-15 11:21:45 +08:00
AnanovoandGitHub effc505a07 fix(mcp): clarify display_image user-output semantics (#1568) 2026-08-15 11:15:27 +08:00
df1a56e1db fix(cursor): exclusive agent spawn lease for list-models vs ACP (#1529)
* fix(cursor): exclusive agent spawn lease for list-models vs ACP (#1520)

Add a proper-lockfile spawn lease beside agent-acp-active so model probes
and ACP transport acquire mutual exclusion atomically before spawning
agent children, closing the post-#1518 check-then-act overlap window.

Fixes #1520

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(web): fix markdown-a test HappyChatContext mock for typecheck

Adds showSessionSummaryInChat to chatContext() so CI typecheck passes on
the PR branch (pre-existing main breakage unrelated to #1520).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Revert "chore(web): fix markdown-a test HappyChatContext mock for typecheck"

This reverts commit 4973f321a31fda772e8990ea6cda20517ca906aa.

* fix(cursor): scope spawn lease to agent spawn window only (#1520)

Hold agent-cli.spawn only around spawn('agent') in AcpStdioTransport, not
for the full ACP session. Restores N concurrent cursor sessions per host;
list-models probe lease unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): tighten spawn lease lifecycle for babysit (#1520)

Acquire spawn lease before ACP marker publish; unregister on spawn failure.
Hold list-models probe lease until child exit on timeout. Add missing
showSessionSummaryInChat to markdown-a test mock (unblocks CI typecheck).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): re-check ACP marker after spawn lease acquire (#1520)

Close check-then-act window where ACP could publish its marker between
the inactive guard read and list-models spawn. Add regression test.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(cursor): fix ACP-after-acquire mock call order (#1520)

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): async spawn lease + force-kill probe timeout (#1520)

Add acquireAgentCliSpawnLease (setTimeout yields) for ACP create path;
AcpStdioTransport.create() async factory. Probe timeout uses
killProcessByChildProcess(force) while holding lease until child exit.

Addresses Bugbot Majors: session-lifetime mutex (fe07b708d), probe lease
release, post-acquire re-check (137baa779), sync loop starvation, timeout
escalation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(acp): coalesce concurrent initialize() transport spawns (#1520)

Await shared bootstrapTransport promise so overlapping initialize calls
do not spawn duplicate ACP children while create() is in flight.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 18:42:43 +01:00
c69a88afae fix(cursor): close ACP list-models race and false exit 143 window (#1518)
* fix(cursor): close ACP list-models race and false exit 143 window

Register the agent-acp-active guard before spawn, hold it until stdio
close (not bare exit), record the ACP child PID, and align lock/cache
home with resolveHapiHomeDir so runner and session children agree.
Richer exit attribution distinguishes live-PID transport disruption
from confirmed child death. Fixes residual #1472 after #835.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test(cursor): isolate ACP guard teardown from ~/.hapi

Reset afterEach under the temp HAPI_HOME only, and restore the
isolated home before teardown in the unset-HAPI_HOME case, so tests
cannot wipe a live agent-acp-active lock. Use distinct child PIDs in
registration tests.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): publish ACP lock pid before count

Fail-closed reservation order: write pids/<hostPid> before count so
concurrent reconcile cannot treat a mid-register lock as stale and
clear it for list-models. Keep a short mtime grace only when pids/ is
missing (mkdir gap). Regression covers mid-publish readers.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): keep empty pids/ ACP reservation fail-closed

Between mkdir(pids) and the host pid writeFile, reconcile could see
liveCount=0 and clear the lock. Keep that window when count is still
absent and the lock is fresh; re-scan for pids published mid-reconcile.
Regression hooks the mkdir/write gap.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): keep ACP lock across last-unregister publish race

Write a short-lived registering marker before pids/count so empty pids
with leftover count cannot erase a concurrent mid-addLockPid reservation.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): use per-pid ACP registering markers

Crash/reboot must not pin list-models forever on a bare registering
file; prune dead owners and only keep live registrar PIDs.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:55:26 +08:00
7c4b3ab17b fix(cursor): stop session-list spinner flicker from ACP state_update (#1503)
* fix(cursor): stop session-list spinner flicker from ACP state_update

#1487 mapped Cursor ACP state_update running/idle onto hub thinking.
Cursor chatters those states while HAPI is queue-idle, so keepAlive flipped
thinking every ~1-2s and the session list spinner danced. Ignore
state_update for thinking; only bump on real activity, clear via prompt
finally/abort.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): clear thinking on ACP idle without bumping on running

Refine #1502 hotfix: ignore state_update running/requires_action (Cursor
chatter caused spinner flicker) but still clear on idle so mid-idle harness
wakes do not stick thinking=true forever.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cursor): stop ACP background updates from flickering thinking

Ignore tool/content session updates for hub thinking (ACP allows them while
idle). Drive thinking from state_update only, debounce running 750ms, and skip
idle clears during an in-flight HAPI prompt so #1502 residual flicker dies.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-12 09:54:37 +08:00
SSU-WEI HUANGandGitHub 291e7bc40b fix(test): stop runner integration suite from leaking detached process trees (#1515) (#1521)
* fix(test): stop runner integration suite from leaking detached process trees (#1515)

The default CLI test run included runner.integration.test.ts, which spawns
real detached runner/session process trees. A failing, timed-out, or
interrupted test (or a plain runner stop) left those trees alive under
PID 1 — on the Mac this accumulated ~600 Node/Bun/agent processes and
several GiB of RSS over repeated runs.

Test harness changes only; production runner session-preservation
semantics are untouched:

- Exclude runner.integration.test.ts from the default parallel unit-test
  suite; move it into a dedicated serial integration project
  (vitest.integration.config.ts, 'bun run test:integration'). The
  20-session stress test is opt-in via HAPI_RUN_STRESS_TESTS=true.
- Add a test-owned process/session registry (processRegistry.ts): every
  runner, runner-spawned session, and terminal-style child is registered
  immediately after spawn; afterEach/afterAll run two-stage cleanup
  (logical stopRunnerSession first, then bounded process-tree kill),
  followed by a marker sweep for agent grandchildren reparented to PID 1.
- Add a per-run HAPI_TEST_MARKER env stamp + identity/secret env
  neutralization for test children (integrationEnv.ts) so outer HAPI/pi
  session variables never leak into test processes and the final audit
  can recognize test-owned processes by env alone.
- Final suite audit in globalSetup teardown: reap anything still
  carrying the run marker and fail with PID/command diagnostics if
  anything cannot be reaped, before removing the temp home.
- Regression coverage: a deliberately failing test registers a detached
  child and the follow-up audit must find zero test-owned processes.
- CI: replace the dead .env.integration-test step with a dedicated
  integration job running the serial project.

* refactor(test): drop unused killByChildProcess import and child field from registry

* chore(test): raise integration hookTimeout to 60s for slow teardown hosts

* fix(test): fail loudly when the process-table audit cannot scan; assert regression child death

Bot review #1521 findings:
- A failed `ps` scan (unsupported flags, buffer exhaustion, permissions)
  previously returned [] and silently disabled both teardown audit layers.
  It now throws; globalSetup teardown catches the scan error into the
  audit error (temp home is still removed) so the run fails visibly.
- The regression audit test cleaned the leak with the reaper before
  asserting, and force-killed the fresh marked runner. The failing
  test's direct child PID is now asserted dead in afterEach right after
  registry cleanup (before the marker sweep), and the audit test stops
  its own runner gracefully before reaping.

* fix(test): bound the logical cleanup phase so a hung runner cannot stall the hook

Bot review #1521: stopRunnerSession carries the worker's 60s HTTP timeout
(setup.ts raises HAPI_RUNNER_HTTP_TIMEOUT for the stress test), and the
integration hook timeout is also 60s — N sequential stops could exhaust
the hook budget before the process-tree fallback and marker sweep ran,
recreating the very leak this change prevents.

Logical shutdown is now parallel (Promise.allSettled over all tracked
sessions) and the whole phase (stops + PID resolution) races against a
15s budget, so stage-2 tree-kill and the marker sweep always get their
share of the hook window.

* fix(test): bound graceful runner stop in hooks; keep credentials out of audit diagnostics

Bot review #1521 (follow-up):
- stopRunner()'s HTTP stop can burn the worker-wide 60s timeout on a
  hung-but-live runner, starving the marker sweep within the hook budget.
  afterEach/afterAll now race the graceful stop against a 10s bound; a
  runner that does not stop in time is force-reaped by the sweep (it
  carries the run marker) and the next beforeEach's alive-PID guard
  ignores any stale state file.
- The env-bearing ps scan (ps eww) was also used for diagnostics, so the
  first 500 chars of a short-command process could print inherited
  credentials (CLI_API_TOKEN etc.) into teardown error logs. The scan now
  only identifies marked PIDs; command lines are fetched separately
  without 'e', falling back to '(command unavailable)' instead of the
  env dump.

* fix(test): reap runner model-probe orphans before the zero-survivor inspection

Bot review #1521 (Minor): inspect-before-reap. Applying it exposed a real
race: each test's runner legitimately spawns marker-carrying children at
startup (agent acp + agent --list-models model-catalog probes). Stopping
the runner orphans them (ppid 1) with the run marker, so the audit test's
OWN runner polluted the pure inspection with fresh probes spawned after
the failing test's sweep window.

- reapTestOwnedProcesses now re-kills every re-scan iteration instead of
  killing once and only re-scanning, so a process that survived its first
  SIGKILL (mid-exec) or spawned mid-kill is not given a free pass.
- The regression audit test stops its runner, reaps (clearing its own
  legitimate orphan probes), then inspects: anything still marked is a
  genuine survivor the bounded reaper could not remove and fails the
  suite. Killable leaks from the failing test are already asserted dead
  in afterEach before the sweep runs.

* fix(test): strictly bound the marker reaper; make per-test sweep unconditional and verified

Bot review #1521 (follow-up):
- The 10s reap deadline did not bound the awaited per-tree kills: each
  killProcessTreeByPid can wait up to 2s per PID, so several stuck
  processes could still exceed the 60s hook budget. Every process in a
  test-owned tree carries the marker (env is inherited), so tree-walking
  is unnecessary: the reaper now SIGKILLs every marked PID found by each
  scan, fire-and-forget, and re-scans every 250ms — the deadline strictly
  bounds the function.
- The per-test sweep was skipped when the direct-child assertion failed
  first, and its survivors were ignored. afterEach now snapshots the
  regression-child state BEFORE the unconditional sweep, then verifies
  both the registry result and the sweep leftovers.

* fix(test): replace it.fails regression with a direct assertion test

Bot review #1521 (Minor): Vitest applies the it.fails expected-failure
inversion after afterEach, so a broken registry assertion inside the hook
would be masked as an expected failure, and the marker sweep would erase
the evidence before the follow-up audit ran.

The regression is now a normal test that registers a detached child at
spawn time, deliberately performs NO per-test teardown, runs only the
spawn-time registered cleanup, and asserts the child PID is dead. The
afterEach no longer carries the registry-leak assertion (moved into the
test body where it cannot be inverted); the per-test sweep assertion and
the final audit test are unchanged.

* fix(test): bound registry stage-2 tree-kills; require live regression fixture

Bot review #1521 (follow-up):
- Stage-2 killProcessTreeByPid awaits per descendant serially and can
  consume the whole 60s hook for a large/stuck tree. Signals are all
  delivered synchronously (children first) before any waiting, so racing
  the awaits against a 5s budget bounds the phase without skipping any
  kill; waitForAllDead still verifies the outcome.
- The regression test could pass vacuously if its fixture exited during
  the startup delay (the registry exit listener would remove it before
  cleanup). It now asserts the child is alive before running cleanup.

* fix(test): kill registered roots with bare synchronous SIGKILL, no pgrep walk

Bot review #1521 (follow-up): racing the mapped killProcessTreeByPid
calls against a timer does not bound the phase — evaluating the map
invokes each call immediately, and each runs the recursive synchronous
pgrep walk before its first await, which can consume the hook before the
timer, runner stop, or marker sweep run.

Stage-2 now SIGKILLs registered roots directly (fire-and-forget, no
tree walk, no per-PID waits) and waits a bounded 5s for death.
Descendants are reaped by the unconditional marker sweep immediately
afterward — every descendant inherits the run marker, so tree-walking is
unnecessary.

* fix(test): drop duplicate process-death wait in registry cleanup

Bot review #1521 (Minor): the duplicated waitForAllDead delayed the
authoritative marker sweep by another 5s under the exact stuck-process
condition the harness must handle. Keep the single bounded wait; the
afterEach marker sweep remains the guarantee.
2026-08-12 09:29:59 +08:00
11964b4b0d fix(a2a): stamp causing inbound on work_ad notify ingest (#1510)
* fix(a2a): stamp causing inbound on work_ad notify ingest

Resolve the turn cause from the full session messages table at insert so
consumers do not guess from a truncated transcript. Stamp causeMessageId,
causeText, causeKind, and related_event_id, and link follows to the
previous work_ad.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): ignore scheduled and client-posted work_ads in cause chain

Future-scheduled inbounds are not this turn's cause. Only AGENT_NOTIFY_SUMMARY
rows chain related_event_id / sticky cause, so HTTP-posted work_ads cannot
steer hub-derived attribution.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): skip transcript echoes and reserve notify provenance

Claude jsonl echoes remote prompts as extra role=user CLI rows; mark them
and ignore them when choosing a work_ad cause. HTTP event writes cannot
claim AGENT_NOTIFY_SUMMARY provenance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): stamp transcript echo only for hub-delivered prompts

Local Claude TTY prompts share isExternalUserMessage; matching pending
web/telegram text keeps those rows as work_ad causes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): match Claude queue text and bound cause message scan

Register pending transcript echoes at the formatted queue boundary
(and drop them on cancel). Later work_ad notifies scan after causeSeq
instead of decoding the full session transcript.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): note delivered Claude batch and skip uninvoked causes

Register transcript-echo text at SDK delivery after batch join and
skill expansion. Keep the marker when cancel misses the queue.
Cause candidates require invokedAt so queued localId rows wait.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): note parked Claude batches and chain work_ads by insert order

Stamp echo markers on the pending mode-switch delivery path. Advance
causeSeq past every invoked inbound in the same batch. List session
work_ads by rowid so backdated transcript timestamps cannot rewind the chain.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): pick latest invoked inbound after history hydration

Fork/merge copies leave old user rows without prior work_ads; choose
the newest invoked inbound before the assistant. Echo markers now keep
batch localIds so cancel can drop a restored-then-cancelled prompt.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): drop echo markers when a Claude batch is abandoned

The three-failure launcher cap discarded the in-flight prompt without
clearing pending transcript-echo text, so a later identical local
prompt could be misclassified.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): replace echo markers when a restored prompt is rebatched

Recoverable launch failure keeps the original marker; a later same-mode
prompt joins into new delivered text. Drop overlapping localId markers
so a later identical local prompt is not stamped isTranscriptEcho.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): keep notify cause chain across session merge

Re-key AGENT_NOTIFY_SUMMARY work_ads onto the surviving session and
bound later scans by causeCursorMessageId so merge seq-shift cannot
revive an already-consumed batch inbound as the sticky cause.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): keep notify rows on live source during history merge

mergeSessionHistory leaves the source socket alive. Only re-key
AGENT_NOTIFY_SUMMARY work_ads when mergeSessions deletes that id.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(a2a): drop id-less echo markers on rebatch and launch drop

API callers may omit localId. Replace the nameless in-flight marker
when a new id-less delivery is noted, and discard by delivered text
when the three-failure path abandons the batch. Do not mint hub
localIds (that would change invokedAt ack semantics).

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 18:08:02 +01:00
SSU-WEI HUANGandGitHub e6b9fd68e6 feat(pi): queue mid-turn messages by default; steer only via explicit per-message Steer button (#1480)
* feat(pi): queue mid-turn messages by default; steer only via explicit per-message Steer button

Pi (PyAgent) was the only flavor whose ordinary composer submission while
streaming bypassed the queue: the web resolved it to deliveryMode 'steer'
and the CLI dispatched a native steer into the running turn immediately,
with no waiting state. This makes Pi match Codex/Claude behavior (issue
#1466): mid-turn messages wait in the queue by default, and the operator
delivers one into the running turn with the new per-queued-message Steer
button.

- web: resolveMessageDeliveryMode now queues for every flavor; QueuedMessagesBar
  gains a Steer button (pi + thinking + remote-controlled + immediate rows)
  backed by a new useSteerQueuedMessage hook + api.steerMessage.
- hub: POST /sessions/:id/messages/:messageId/steer -> syncEngine.steerQueuedMessage
  (pi-only gate, remote-only, scheduled/absent/invoked rejection) -> RPC.
- cli: pi runner registers 'steer-queued-message'; a queued message is promoted
  into the active turn via the existing PiSteerDispatcher (target generation
  captured at promote time; turn-ended steers fall back to the prompt FIFO).
  Steers requested while the message is still preparing are deferred and
  promoted right after preparation completes.
- Removed the now-dead Alt+Enter / touch-hold queue gesture (its only purpose
  was opting out of the removed automatic steer).

Verified: bun typecheck; cli/hub/web/shared suites (env-dependent runner
integration + kimi wire-locator flakes reproduce on pristine upstream and
are unrelated to this diff).

* fix(pi): preserve queued messages on rejected steers and pin the steering generation

Addresses both Major findings from the HAPI Bot review of PR #1480.

- steerDispatcher: a deterministic native rejection (Pi responded error) now
  degrades the message to the ordinary prompt FIFO instead of emitting
  messages-consumed. A promoted queued message must not be lost just because
  the steer was rejected; the hub row stays queued until the FIFO delivers it.
  The indeterminate-timeout path keeps its fail-closed consume + escalate
  behavior (a duplicate delivery would be worse).
- runPi: the deferred-steer path now captures the streaming generation at RPC
  request time (Map<localId, generation>) instead of reading it after
  preparation completes, so a steer requested against turn G1 can never be
  injected into a turn G2 that started while the message was preparing — the
  dispatcher's generation-mismatch check degrades it to the FIFO.

Regression coverage: negative steer response preserves the entry via the FIFO
(no consume); generation rollover while preparing delivers as a normal prompt
at the next settle (no steer into the new turn).

Verified: bun typecheck; cli pi suites (48 tests), hub 1041, web 2301, shared
240 — all green; only the pre-existing environment-dependent runner
integration test fails locally (reproduces on pristine upstream).

* fix(pi): reject all scheduled steers and always clear deferred-steer bookkeeping

Addresses the two Minor findings from the HAPI Bot follow-up review.

- hub: steerQueuedMessage rejects every scheduled row — mature ones included —
  aligning the endpoint with the web UI (Steer is never offered on scheduled
  rows) and preserving scheduled-FIFO delivery semantics.
- cli: the deferred-steer bookkeeping map is now cleared in a finally on the
  preparation chain, covering the early exits (cancellation before/after
  attachment I/O, empty prepared message, preparation failure) that previously
  could leave a stale generation entry behind for the session lifetime.

Regression coverage: hub steer gate tests (mature scheduled row stays queued,
non-pi flavor rejected) and a runPi test proving cancellation wins over a
deferred steer (no steer/prompt/consume after preparation completes).

Verified: bun typecheck; hub 1043 pass, cli 2421 pass (only the pre-existing
environment-dependent runner integration suite fails locally), web 2301 and
shared 240 unchanged since their green runs.

* fix(web): reconcile stale queued rows when a steer returns invoked

Addresses the remaining Minor finding from the HAPI Bot follow-up review:
when the steer endpoint reports the message was already invoked and the
messages-consumed SSE was missed while the row was still queued, the hook
now marks the row consumed locally (mirroring useCancelQueuedMessage) so
the queued bar cannot keep a stale actionable row until the next sync.

Regression coverage: steer returning status 'invoked' reconciles the row
via markMessagesConsumed and shows no toast.

Verified: bun typecheck; web 2302 pass (hub/cli/shared unchanged since
their green runs).
2026-08-11 22:27:14 +08:00
1cd4d1137a feat(hub,cli,web): fleet runner version governance (skew, self-upgrade, soft-fail reopen) (#1108)
* fix(hub): govern runner capabilities so Cursor reopen soft-fails on skew

Hub↔runner protocol drift was reported as missing Cursor chat data when
cursor-chat-store-status was unregistered. Soft-fail reopen on probe errors,
advertise required machine capabilities, surface an unmissable upgrade banner,
and stop-runner when a newer CLI binary is already on disk.

Fixes #1084

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web,hub): make runner skew banner dismissible; gate auto-upgrade

Compact the out-of-date banner (minimize + 1h snooze + per-host Restart)
so it no longer blocks the session list. Auto stop-runner on skew stays
opt-in via HAPI_AUTO_UPGRADE_RUNNERS / autoUpgradeRunners (default off).

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(web): tolerate full sessionStorage on skew banner minimize

QuotaExceededError from setItem aborted minimize before React state
updated, leaving the banner stuck over the session list. Persist to
memory when storage fails; only enable Restart when a newer CLI is
already on disk; clarify opt-in is stop-runner only, not package push.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub): drop redundant autoUpgradeRunners; runners already self-restart

CLI version handoff already reloads the runner when the on-disk binary
mtime changes. Hub-driven stop-runner on skew duplicated that. Keep the
skew banner and manual Restart only as a stuck/disabled-handoff escape.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(cli,hub,web): runner-only caps ads; gate Restart on supervisor

Address #1108 bot Majors on the thin tip: terminal/lazy bootstraps no
longer merge CURRENT_MACHINE_CAPABILITIES into the machine row (only
asRunner registration does). Banner Restart refuses unsupervised hosts
so stop-runner cannot leave a detached laptop offline; supervised
runners advertise supervisedRestart via HAPI_RUNNER_SUPERVISED=1.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(hub,cli,web): clear sticky runner ads; docs SUPERVISED; i18n skew label

Omit-means-clear on runner registration so rollback cannot leave
supervisedRestart/capabilities sticky; always advertise boolean
supervisedRestart from asRunner. Document HAPI_RUNNER_SUPERVISED=1
and localize MachineSelector UPDATE REQUIRED.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Debian <heavygee@oos-linux.in.lockhouse>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-11 22:24:39 +08:00
24e0c76717 feat(cursor): bump hub thinking on ACP harness wake (#1487)
* 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>
2026-08-11 10:03:42 +08:00
SSU-WEI HUANGandGitHub 2548eaf3ed fix(cli): raise flaky claudeRemote first-test timeout to 15s under CI load (#1493)
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
2026-08-11 10:03:27 +08:00
SSU-WEI HUANGandGitHub b572c35e34 fix(pi): surface mid-turn LLM errors in web chat (#1479)
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
2026-08-10 11:47:56 +08:00
Junmo KimandGitHub 495fa53465 fix(opencode): surface upstream errors and retries (#1433)
* 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.
2026-08-10 10:48:48 +08:00
AnanovoandGitHub 044d72fdc0 fix(web): show file metadata in preview header (#1450) 2026-08-10 10:47:58 +08:00
SSU-WEI HUANGandGitHub 427ac1ff95 fix(pi): sync native session name (#1454)
* 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.
2026-08-10 10:46:16 +08:00
SSU-WEI HUANGandGitHub 2a98b4425f fix(agy): sync native Anti-Gravity conversation titles (#1476)
* 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.
2026-08-10 10:46:04 +08:00
SSU-WEI HUANGandGitHub bb40a4e8d0 fix(agy): preserve PTY running status (#1456)
* 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).
2026-08-10 10:45:52 +08:00
SSU-WEI HUANGandGitHub e6e229c068 fix(codex): preserve plan approval in yolo (#1420) 2026-08-10 10:44:41 +08:00
SSU-WEI HUANGandGitHub b744414241 fix(cli): skip invalid set_mode for interactive Copilot sessions (#1463)
* 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
2026-08-10 10:44:24 +08:00
weishu c2cc73159c fix(codex): preserve transcript final answer ordering 2026-08-10 10:36:34 +08:00
fe4d51043c fix(cli): remap bracketed Cursor wires onto bare/SKU catalogs (#1430)
* 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>
2026-08-09 20:49:42 +01:00
weishu cde0507bad fix(codex): harden model discovery fallback 2026-08-09 09:04:28 +08:00
b7f52f58ca feat(media): add audio and file display (#1405)
* 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>
2026-08-08 13:46:59 +08:00
Junmo KimandGitHub 64a85ad923 fix(agy): move carrier sweep off the startup path, enable on macOS (#1406)
* 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.
2026-08-08 13:46:33 +08:00
weishu e3ed80676a fix(codex): restore transcript messages from Codex 0.147 2026-08-08 13:45:51 +08:00
28df974edd feat(settings): onboard hub provider credentials for dictation and voice (#1392)
* 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>
2026-08-07 13:20:03 +08:00
988f8f183f feat: settings toggle for AGENT_NOTIFY_SUMMARY contract injection (#1376)
* 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>
2026-08-06 18:51:35 +08:00
KorenKritaandGitHub 256ad98ece fix: normalize cache token usage semantics (#1390)
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
2026-08-06 18:50:49 +08:00
weishu 97c7412434 fix(codex): forward lifecycle hooks without allow decision 2026-08-05 23:04:10 +08:00
c0b30bf916 feat(cli): MCP list_peers + runner hub auth for peer discovery (#1372)
* 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>
2026-08-05 22:16:04 +08:00
KorenKritaandGitHub 3aff832246 fix(pi): advertise runner capabilities at registration and on connect (#1386)
* 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.
2026-08-05 22:12:04 +08:00
KorenKritaandGitHub 0201b9f6d4 feat(pi): import and reconcile local sessions (#1365)
* 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
2026-08-05 16:08:08 +08:00
c7e38e872c feat(a2a): steer session citations toward inspect_peer (#1373)
* 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>
2026-08-05 15:05:38 +08:00
KorenKritaandGitHub e50099e4a4 fix(pi): keep running state through active RPC turns (#1379)
* fix(pi): keep running state through active RPC turns

* test(pi): cover pre-settlement state snapshots
2026-08-05 15:03:57 +08:00
Junmo KimandGitHub 229766dd21 fix(agy): make conversation discovery deterministic at session start (#1369)
* 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.
2026-08-05 07:56:40 +08:00
807fa72aaa fix(opencode): surface stall errors and clear thinking spinner (#869)
* 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>
2026-08-04 11:19:02 +08:00
Junmo KimandGitHub c3bed919b8 fix(opencode): verify persisted compaction results (#1357) 2026-08-04 11:15:42 +08:00
KorenKritaandGitHub 021b5c194b feat(pi): complete RPC parity, native steer, and history controls (#1353)
* 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.
2026-08-04 11:01:00 +08:00
3c83fe58c9 fix(web+cli): Cursor model picker empty on bare ACP ids + nested variant drill-down (#947)
* 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>
2026-08-04 10:59:06 +08:00
00e8fc3a47 fix(codex): recover ready after stale terminal event (#997)
* 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>
2026-08-04 10:58:49 +08:00
79f91e4b45 fix(acp/runner): Cursor worktree banner + skip nested --worktree hang (#1087)
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>
2026-08-04 10:58:24 +08:00