mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-25 05:07:05 +00:00
37446bcf5fda945a40df2a398849ed86115a5265
651
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
37446bcf5f |
feat(agy): negotiate ACP slash commands and support native /swarm (#2454)
* feat(agy): negotiate ACP slash commands and support native /swarm * fix(agy): clear cached ACP commands when available_commands_update is empty * fix(agy): recognize backgrounded commands in swarm_wait turn boundaries |
||
|
|
dff2d99fd6 |
fix: align Stop with the official agent TUIs (#1992)
* fix(cli): preserve queued user input on plain Stop across flavors Plain Stop must abort only the active runtime turn and keep unconsumed queued messages (localIds/order/isolate/mode) for the next drain. Previously the per-flavor Abort handlers unconditionally called queue.reset(), dropping pending messages, and an idle loop could collect/ACK a batch that arrived during abort teardown. - MessageQueue2.waitForMessagesAndGetAsString checks the abort signal before both batch collections, so an in-flight Abort can never collect/ACK (and therefore never replay) a pending batch. - Add a serialized Abort barrier in RemoteLauncherBase with an optional synchronous entry callback: onAbortEntry aborts the current signal so an idle waiter fails closed, and waitForAbortBarrier holds the loop's next dequeue until teardown completes. A rejection during teardown no longer spins the loop with a stale aborted signal; it is boxed and propagated to the Abort RPC caller, the run loop, and clearAbortHandlers lifecycle. - Launcher handleAbort resets the queue only on terminal cleanup (shouldExit/leavingRemote). BaseLocalLauncher Abort (switch to remote) preserves the shared queue. Cursor ACP soft-steer drain handles an already aborted signal without deadlock. - Codex shared root Abort stays a pure turn/interrupt; native queue retained (control regression only, no resume-policy change). Tests: Launcher-level Abort preservation (active/idle/concurrent/rejection), enqueue-during-cancel, MessageQueue2 idle wake-then-abort and post-await guard, base-local queue preservation, Codex abort/native-queue control. Verified with Node22 (.sbx/node22) - full cli suite green; see .sbx/REPORT.md. * fix(web): settle Stop state with the abort request * test(web): cover Stop request settlement without an idle render * feat(cli): batch compatible Codex queued input * fix(codex): preserve batch recovery and fork boundaries * test(cli): cover idle and overlapping Stop teardown Keep queued input unacknowledged while an idle Stop or a later Stop is still tearing down. Gate cancellation acknowledgements independently from prompt completion to exercise both ordering races. * fix(codex): keep queue preflight failures retryable Persist a retryable state during the read-only tail lookup, then journal uncertainty with the native mutation. Preserve released native edits and avoid replay when acceptance arrives during preflight. * fix(cli): honor exit requests after abort teardown * test(cli): cover terminal handoff during overlapping stops * fix(codex): retain uncertain batch append ownership * fix(dsh): stop queued dispatch during process cleanup * fix(dsh): stop idle queue waits before process cleanup * fix(codex): preserve removal intents across native edits * test(codex): resolve native batch inputs in full-stack checks * test(copilot): stub session metadata on the abort test client The ACP session title sync now reads client.getMetadata() when a launcher is created, so the abort test client needs a getMetadata stub next to its existing updateMetadata stub. Without it every case built on createAbortSession fails with "client.getMetadata is not a function". * fix(opencode): keep the dequeue signal usable after a Stop that only abandons round metadata The abort barrier aborts the dequeue signal when a Stop arrives so an idle wait wakes up. A plain Stop during the post-prompt round-summary settle phase only abandons metadata and returns before performAbort, which is what replaces the controller. The loop then re-read the aborted signal in a tight microtask loop and never reached the queued input, pinning a CPU. Recycle the controller on that early return so the queued input is dequeued on the next iteration. * fix(cli): keep launchers running when a native cancel is rejected The abort barrier aborts the dequeue signal when a Stop arrives and, when the teardown rejected, boxed the failure so the run loop threw it at the next dequeue. Every launcher that uses the barrier therefore stopped surviving a rejected native cancel, which it did before the barrier: a rejected cancel left the controller untouched and only the Abort caller saw the error. setupAbortHandlers now takes an onAbortRejected callback next to onAbortEntry. On a teardown rejection the base restores the dequeue signal through it and rethrows to the Abort RPC caller only; the boxed failure is gone. Each launcher passes a one-line callback that replaces the controller only when it was aborted. Queue preservation and the barrier's ordering are unchanged. * fix(codex): restore the applied batch version after definite rejections A definite native rejection left the rejected proposal in versions and rolled batch.current back positionally (length - 2), so a second consecutive rejection selected the earlier rejected proposal instead of the applied version; the stale current survived reconciliation and a later member cancel could submit rejected content for execution. Capture batch.current before each append and restore that saved index on definite rejection across nativeUpdate, extendBatch, cancelBatchMember and steerBatchMember. Covered by failing-first regression tests: consecutive rejected appends followed by a member cancel, and consecutive rejected native edits. See tiann/hapi#1992 review discussion. * fix(hub): align archive cleanup status assertion with the 503 mapping tiann/hapi#2423 changed ArchiveCleanupError to return 503 instead of 504 (Cloudflare Tunnel replaces 502/504 bodies; the code field distinguishes timeouts) and updated one assertion, but the overlapping-archive singleflight test still expected 504, which the 409 | 503 status union can never produce. * fix(opencode): preserve queued input on a plain Stop tiann/hapi#1992 promises pending input survives a plain Abort on the queue-backed launchers. Upstream #2424's performAbort reset the queue unconditionally, dropping not-yet-dispatched input on a plain Stop. Reset only when leaving the session (switch/exit), and let a terminal request joining an in-flight plain Stop promote its cleanup intent onto the operation so the reset still lands exactly once, after the shared cancellation restore drain. * fix(opencode): terminal drain ordering, dequeue fence, teardown escalation Hydrogen pre-review of the preserve-on-plain-Stop round surfaced six defects in the Stop/terminal paths, all adjudicated valid, and its re-review surfaced three more: - A direct switch/exit reset the queue before the v2 cancellation drain, so a proven-cancelled steer restored back into the queue after the reset and a switch bounced straight back into remote mode. Run the terminal reset after the drain, where a terminal joining a plain Stop already applied its promoted reset. - The dequeue loop could dequeue, ACK, and then drop a preserved row on the prompt-prep aborted-continue while a plain Stop was still awaiting its native cancellation. Park the dequeue on the runtime gate's cancellation-idle fence and refuse beforeDequeue while a cancellation drain is in flight. - restoreQueuedReservation ignored shouldExit, re-admitting a steer parked before its v2Steers entry after the terminal reset. Leaving remote never re-admits. - performAbort's finally escalated every steer to 'teardown' when the teardown threw, stranding a proven-cancelled steer indeterminate on a plain Stop that keeps running. Escalate only when leaving remote. - A terminal joining a plain Stop lost its promoted cleanup intent when the owner's performAbort rejected: the queue kept its rows and an idle dequeue waiter was never woken. Run the reset and the abort in the rejection handler. - dispatchV2Steer removed its entry only after awaiting the restore, so a Stop landing mid-restore ran a second concurrent restore whose failed restoreReservation falsely reported the row indeterminate. Detach the entry before the restore. - A plain Stop landing between the dequeue and the prompt (model/effort setup, round snapshot, or the native history read) still dropped the already-dequeued, hub-ACKed batch on the pre-dispatch bail-outs. Requeue the batch there in its original order with each localId intact, and echo it at the dispatch commit point so the retry does not double-echo; compact keeps its early echo. - restoreQueuedReservation's leaving-remote path returned false without undoing its work: the steer stayed stuck 'dispatching' in the shared queue (Cancel answered 'in-flight' forever) and the hub stamp never reverted. Persist 'queued' and release the held reservation instead. - The v1 terminal path had no rejection cleanup: a performAbort(true) that threw left the queue unreset and the dequeue signal un-aborted, parking the idle loop forever. Mirror the v2 rejection cleanup. * fix(cli): preserve queued input across pre-prompt Stops in every queue-backed launcher The whole-PR review surfaced the OpenCode preserve class defect in every other queue-backed launcher, plus teardown and batching gaps: - dsh, cursor ACP, copilot, grok and kimi dequeued and hub-ACKed a batch and then dropped or dispatched it when a plain Stop landed during the pre-prompt setup awaits. Requeue the batch at every pre-dispatch bail-out (requeue never fires for terminal switch/exit, whose reset already cleared the queue) and defer the cursor ACP hub ACK and user echo to the dispatch commit point so a retry never double-ACKs or double-echoes. The shared requeue lives in MessageQueue2.unshiftBatch; OpenCode's helper delegates to it. - cursor ACP requeued into the shared queue without a shouldExit check, bouncing a switch straight back into remote mode, and its soft-steer restoreQueuedReservation re-admitted a 'dispatching' steer after the terminal reset. Guard the requeues and release the steer the same way OpenCode does: persist 'queued' and release the held reservation. - A rejected handleAbort(true) skipped the queue reset everywhere and the dequeue-signal abort outside DSH, parking an idle runMainLoop forever. requestExit now invokes an onTerminalTeardownRejected hook on rejection; copilot, grok, kimi and cursor ACP override it with their reset+abort, OpenCode and DSH are no-ops (their teardowns guarantee the cleanup on every path), and DSH moves its reset into a finally so a rejected cancel cannot skip it. - runAbortUnderBarrier overwrote an in-flight abort barrier instead of chaining onto it, letting dsh kill() unblock the loop's dequeue while an earlier plain-Stop teardown was still running. The release now chains onto the prior barrier. - codex/shared/root captured the message batch key from this.settings at callback arrival, merging queued messages across a settings-changing slash command and splitting around cold-start hydration. The key is now computed inside the work continuation, after bound and after earlier queued commands ran. * fix(cli): keep origin-indeterminate steers resolvable and skip dead prep on Stop The round-4 confirm review surfaced three residual steer/teardown gaps: - restoreQueuedReservation's terminal-exit branch deleted an origin-indeterminate reservation and left the hub steerDeliveryState stuck at 'dispatching'. An origin-indeterminate row cannot be honestly reverted to 'queued': stamp 'indeterminate', emit it, and keep the reservation for explicit Cancel/Retry in local mode (opencode and the same newly added cursor ACP branch). - restoreQueuedReservation now returns 'restored' | 'dropped' | 'indeterminate' so dispatchV2Steer can tell a clean terminal drop from an unknown outcome: the rejected-admission branch reports 'Active turn changed' instead of a false 'Steer state is indeterminate', and the stop-cancellation path treats the drop as definitive removal. - A plain Stop landing during the inline setModel/setConfigOption awaits no longer runs captureOpencodeRoundSnapshot or toggles thinking/steeringActive for a prompt that never starts; the already- dequeued batch requeues before the round-snapshot setup. * test(cursor): cover legacy queue preservation across Stop and terminal exits The PR changed cursorLegacyRemoteLauncher's abort handling (+10: the leavingRemote queue reset and the rejected-cancel signal restore) without any behavioral test. Mirror the Cursor ACP coverage: a plain Stop during an in-flight turn keeps the queued row and drains it after the Stop settles, a terminal switch/exit resets the queue exactly once with no further dispatch, and a Stop landing during the dequeue wait preserves the not-yet-dequeued row. The launcher already behaved correctly on all three paths; the tests guard them. * fix(launchers): close abort-window races across teardown and pre-dispatch setup Four launcher loops (cursorAcp, copilot, grok, kimi) plus dsh and opencode kept a live dequeue signal and a dequeue-time hub ACK across their pre-prompt setup awaits, so a batch arriving behind a terminal switch/exit teardown was dequeued, stamped invoked at the hub, run through ACP model/mode mutations, and dropped unprompted; and an abort that landed mid-setup could be erased by a later state reset and still dispatch the canceled turn. cursorAcp - single userAbortRequested reset per turn window: an abort that lands during model/mode setup survives to the pre-dispatch gates - hub ACK moved to the dispatch commit point, after every pre-dispatch bail-out: an aborted batch is never stamped invoked nor dropped with a false ready - new requeueAbortedBatch helper: abort-path requeues carry only user content, so a Stop-canceled model-error-bridge item is dropped instead of resurrecting after the Stop settles - durable Bridge mutations (user-turn supersede, replay-gate persist) deferred to the dispatch commit point with post-persist abort/exit guards; guard added after the harness-resume buffer discard - soft-steer restoreQueuedReservation re-checks shouldExit after the 'queued' persist and releases the held reservation instead of restoring it into the queue, which would bounce a terminal switch straight back into remote mode; 'Active turn changed' when the turn changed during the restore - handleAbort aborts and replaces the dequeue signal at entry when leavingRemote, unparking the wait before the teardown's own awaits - lastUserMessage recorded at the dispatch commit point copilot/grok/kimi - handleAbort entry abort-and-replace when leavingRemote - shouldExit break right after the dequeue resolves, before any state mutation - hub ACK deferred to the dispatch commit point - intermediate shouldExit/aborted checks after each setup await; isClosed guards on every unshiftBatch - grok: thinking deferred to the commit point, history busy kept early dsh - hub ACK deferred to the dispatch commit point - a failed top-of-loop reconnect requeues the un-ACKed batch when a plain Stop landed inside it; isClosed guards on every unshiftBatch - generation checks after the model/effort switch awaits; thinking deferred to the commit point - kill() batch drop emits the sibling idle 'ready' signal opencode - display-mode state applied below the pre-snapshot Stop/exit check Each loop change is covered by a behavioral regression test that fails against the pre-fix dequeue-time ACK / live-signal teardown behavior. * fix(launchers): close bridge supersede, cancel-window, and teardown races - cursorAcp: markModelErrorSupersededByUserTurn now drops the pending bridge row, and the replay gate fails closed once superseded, so a manual Bridge enqueued mid-setup can no longer replay after the user turn that superseded it - cursorAcp/dsh: a batch resolved while the terminal teardown flips shouldExit breaks before reconnect or mode/model setup instead of mutating ACP state on a closing backend - MessageQueue2: cancelByLocalId answers 'in-flight' for dequeued-but- uncommitted localIds, closing the deferred-ACK window where a cancel could double-deliver a message or deliver one after an explicit cancel - MessageQueue2: unshift forwards internal provenance; unshiftBatch and the cursorAcp requeue helper keep it on non-isolated requeues - dsh: a plain Stop racing a failed acpSessionEnded restart requeues the dequeued batch instead of dropping it in the recovery catch, and the null-model switch path gains the same abort-generation guard as its sibling branch - copilot/kimi: the switched model's effort baseline is captured before the plain-Stop bail so the requeued turn takes the new baseline - tests: failing-first regression tests for each sequence; grok/kimi requeue tests drop unused spies, fix stale deferred-ACK comments, and assert the commit-time ACK exactly once * fix(cli): scope in-flight cancel tracking to deferred-ACK launchers * fix(opencode): commit hub consumption only when the prompt is dispatched * fix(codex): persist batch uncertainty after an unconfirmed shrink * fix(codex): journal batch uncertainty before dispatching a shrink * fix(codex): journal batch uncertainty before every native batch write Every native RPC that can change the content or existence of a batch's queued submission now persists the batch as unknown, together with the proposal that motivated it, before it is dispatched. Only a confirmed response or a definite rejection settles the batch back, and that transition is persisted. Previously the whole native edit (nativeUpdate), the append edit (extendBatch), the restoration after a rejected steer and the suspend delete left the batch queued while an unconfirmed proposal was current. A crash before the edit applied, followed by canceling a member, could then delete or rewrite the native submission from a version it never held and silently drop sibling input. --------- Co-authored-by: sbx <sbx@agent-sandbox.invalid> |
||
|
|
d01acf994b | feat(cli): read Claude plan quota on demand via get_usage (#2451) | ||
|
|
6cd6d375c0 |
fix(jobs): stop waking busy agents and gate session jobs to long work
Job wakes interrupted running turns: `deliverJobTerminalWake` only special-cased inactive sessions, so an opted-in terminal job posted a user message into whatever the agent was doing. Drop the wake when a turn is running and settle the claim so a later idle flip cannot re-fire. Those wakes also impersonated operator input — `sentFrom: 'webapp'`, a bare user message with a "Verify the outcome and continue" imperative. Tag them `hapi-system` and render them as a quiet status line in the web chat instead of a user bubble with fork/retry actions. Drop the default imperative; a prescription now has to come from `--wake-prompt`. Agents attached jobs to short work (tests, builds, typechecks) because the injected prompt was 2.1k chars of REQUIRED / MUST / FORBIDDEN. Replace it with a decision rule: default is not to attach, never for work that finishes in this turn, and run `hapi job --help` for the mechanics. Co-Authored-By: HAPI <noreply@hapi.run> |
||
|
|
8aebb908bf |
feat(codex): attach HAPI to external desktop runtimes
Add explicit macOS attach/detach workers independent of owned runtimes. Preserve external engine lifetime, native queues and settings, and fence history rewrites with durable projection checkpoints. Guard owned resume and deduplication paths, add protocol and CLI-to-Hub regression coverage, and document the isolated ChatGPT desktop GUI acceptance results. Refs #2427 |
||
|
|
6237e90b37 | feat: import local sessions through one registry (Pi, OpenCode, Codex, Claude) (#2435) | ||
|
|
2d0c8a7695 |
fix(opencode): show each OpenCode v2 model's real effort options, with one Default (#2439)
* fix(web): drop provider-default entry from dynamic reasoning effort options * fix(cli): support OpenCode v2 /api/model variant lookup and Basic auth |
||
|
|
30835911fb | feat(uploads): stream large session attachments via chunked uploads (#2429) | ||
|
|
6a19189cd8 | fix(claude): deny pending permission requests when steering (#2432) | ||
|
|
80a5b94f8f |
feat(runner): add safe agent quota query infrastructure (#1787)
* feat: add runner-side quota query infrastructure * test: cover usage query protocol contract * fix: close quota query redirect and in-flight races * fix: harden quota query cache and timestamps * fix: restrict quota templates to read-only requests * fix: harden quota credential and request boundaries * fix: bind quota cache to credentials * fix: retry quota failures after cooldown * fix: require an active Codex provider * fix: harden quota value parsing and redaction * fix: close quota provider selection boundaries * fix: resolve qualified Kimi provider defaults * fix: continue Kimi config fallback when current is incomplete * fix: isolate explicit Kimi profile fallback * fix: bind provider credentials and URL safety * fix: isolate Codex profiles and abort quota responses * fix(usage-query): preserve case-sensitive Codex providers |
||
|
|
f0ab4ba79d |
feat(cursor): detect inline model errors, surface, notify, and bridge (#878) (#987)
Cursor ACP sessions can fail mid-turn with a transient model error that the agent reports inline rather than as an RPC rejection. HAPI treated those turns as successful, so the session went quiet with no banner, no push, and no way to resume without retyping the prompt. This adds the full path: - detect: classify inline/stderr model errors from the Cursor ACP stream, requiring strong signatures before typing a failure as a model error - surface: persist `lastModelError` on session metadata; render a chat banner and a session-list indicator, with the prompt text kept out of list/SSE summaries so they never ship up to 32 KB of user prompt - notify: deliver a push for an unacknowledged error, watermarked on the hub copy so a restart does not re-page the same eventId - bridge & retry: offer a one-shot recovery prompt that replays the failed turn, bound to the originating eventId and gated so a real user turn always supersedes it. Auto-bridge is opt-in and defaults to OFF, persisted in hub settings and fanned out to live Cursor CLIs. Re-cut onto current upstream/main. The branch had accumulated 108 iterative hardening commits against a 289-commit-older base; replaying them individually would have re-resolved the same conflicts ~100 times. The pre-re-cut tip was 2c28a1365 if the granular history is ever needed. Absorbing upstream required adapting to three refactors that landed meanwhile: - `MessageQueue2` grew an `internal?: boolean` control-message flag upstream while this branch added richer `internal` provenance. Unified on a tagged `QueueItemInternal` union (`control` | `model-error-bridge`) so one field carries one concept. `hasPendingNonBridgeTurn()` now treats *any* internal item as non-user: otherwise a queued `/auto-review` control slash would have counted as a user turn and wrongly superseded a live bridge. - `AcpSdkBackend.prompt()` gained a `timing` callback upstream; merged it with this branch's `shouldSend` gate into a single options object. - The hub settings route moved to a unified `updateSettings` transaction. `autoBridgeTransientModelErrors` is applied outside that transaction because SyncEngine owns its CLI fan-out and rollback under its own lock. via [HAPI](https://hapi.run) Co-authored-by: HAPI <noreply@hapi.run> |
||
|
|
a7e472bb39 |
refactor(cli): move media guidance into tools and infer job countdowns (#2416)
* feat(cli): render local Markdown links as attachments * fix(prompt): auto-infer sleep durations and deduplicate MCP media guidance * fix(prompt): rely on tools and attachment fallback instead of injecting media guidance into system prompt * fix(attachments): gate fallback by session permission mode and track denied paths * fix(pr-review): track permission denials, exclude sidechains, and support multi-arg sleep * fix(attachments): canonicalize denied paths, track local Claude & Codex approvals, exclude sidechain * fix(attachments): canonicalize symlinks, hook Cursor PermissionAdapter, process Pi/ACP terminal snapshots * fix(attachments): recognize ACP display titles, block file-read denials, document relative countdowns * fix(attachments): normalize ACP read permissions, track native Claude denials, align sleep instruction * fix(attachments): normalize AcpPermissionHandler read denials without rawInput * fix(attachments): preserve SharedCodexPermissions file read/display denials * fix(attachments): recognize qualified MCP read tools and preserve terminal-resolved Codex denials * fix(attachments): support multi-file path extraction, avoid duplicate web markdown images, guard terminal resolution * fix(attachments): multi-file denial tracking, guard terminal Codex approvals, conditionally suppress web cards * fix(attachments): nested multi-file denial extraction, resolve terminal Codex approvals, parent-relative image card retention * fix(attachments): recursive multi-file path extraction, native Codex approval reconciliation, decode percent-encoded targets * fix(codex): reconcile native execution in root.ts, track webApproval vs terminal denial * fix(codex): verify thread ownership and successful execution before clearing denials in root.ts * fix(codex): validate MCP result error envelopes and retain web cards for non-image targets * fix(cli): support underscored MCP server names, accept null error on Codex success, and deduplicate across cold resumes * refactor(cli): keep media delivery in tool contracts and remove link fallback * test(cli): avoid assuming a typed MCP config description * fix(cli): anchor inferred sleep countdowns to child launch |
||
|
|
bb97a6512f |
fix(runner): verified exit must confirm stop despite unrelated protected wrapper (#2346)
* fix(runner): let verified exit confirm stop when only unrelated wrappers are protected * test(runner): verified exit confirms stop despite unrelated protected wrapper |
||
|
|
acddadf194 |
fix(agy): keep empty edit/write strings and the question card's free-text limit (#2331)
* fix(agy): keep empty strings in edit and write tool card inputs A deletion edit (empty Replacement) or an empty-file write was mapped without new_string/content, so the web Edit and Write views rendered nothing. Keep '' for old_string, new_string and content. * fix(web): take the question card's free-text flag from the pending request agy's ask_question tool call is shown before its form arrives, so its input cannot say whether free text is allowed, and the card kept offering Other on forms without qN_other. Fill allowFreeText on the tool call input from the pending request's input for questions that carry none. Inputs and requests without the flag keep showing Other. |
||
|
|
90fbb417ca |
fix(agy): concatenate ACP text chunks as deltas (#2332)
agy streams agent_message_chunk as pure deltas, but the backend used the default overlap-dedupe mode, which dropped a repeated character at a chunk boundary (73-8 + 800 was shown as 73-800). Set textChunkMode to delta, as the OpenCode and Grok backends do. |
||
|
|
bebda45006 | fix(dsh): respawn dead ACP children, recover closed sessions, sandbox modes, inline images, reasoning effort (#2386) | ||
|
|
04032d704e | fix(cli): isolate claude.test.ts resume-identity tests from HAPI_INVOKED_CWD (#2396) | ||
|
|
ebd4ac2105 | fix(agy): handle stale errors and missing session titles (#2401) | ||
|
|
083aaca779 | fix(web): distinguish and navigate pending requests (#2402) | ||
|
|
d391324e81 | fix(cli): handle ACP stdin stream errors (#2403) | ||
|
|
72b341fde1 | perf(cli): load command modules on demand (#2404) | ||
|
|
e24ccf5e50 | feat(agy): show the round turn count and running background commands (#2405) | ||
|
|
f1339d3ee5 | docs(cli): note that worktree spawn-peer needs a git repository (#2410) | ||
|
|
cca38a4acc | fix(cli,hub): clear stale permission required when request is inactive (#2415) | ||
|
|
b3219357eb | fix(pi): register peer tools directly when registerMcpServer is absent (#2418) | ||
|
|
cad21ec6d0 | feat(opencode): fork and rewind OpenCode v2 conversations (#2424) | ||
|
|
31cb262ee0 |
feat(usage): display CLI account quotas and rate limits in Settings -> Usage (#2389)
* feat(usage): display CLI account quotas and rate limits across Codex, Antigravity, and Claude * fix(usage): persist live quota state across processes and normalize agy usage * fix(cli): isolate Claude quota observations by account and bound probe deadlines * fix(usage): bind Claude quota events to producing session account and surface quota fetch errors * fix(usage): preserve OAuth token isolation without email and surface Codex read failures * fix(usage): skip host claude path lookup when test probe override is active |
||
|
|
0bea8967b4 | fix(agy): wake session and stream reactive background turns over agy acp (#2387) | ||
|
|
446cf2351c | feat(cli): diagnose Bun pre-init fatal crashes in webhook failure messages (#2365) | ||
|
|
2e8b2a108b | fix(codex): preserve completed-fork availability across stale refreshes (#2370) | ||
|
|
20878e317a | fix(claude): mark only the compaction turn result, not pending-compaction rounds (#2374) | ||
|
|
926eac7023 |
fix: keep one stable HAPI session id per Claude conversation (#2388)
* fix: keep one stable HAPI session id per Claude conversation Every terminal `hapi claude -r` minted a new HAPI session id for the same Claude conversation; the hub then merged the duplicates after the fact and deleted the older row, so links and peer references to it broke, and two live duplicates hid one row in the web sidebar. CLI: resolve identity before Claude starts (HAPI_SESSION_ID is fixed at bootstrap). `--resume <id>` / `--continue` look up the owning HAPI session and reopen it with the same id, handing an active remote session over and refusing one controlled by another terminal; bare `--resume` uses the `hapi resume` picker filtered to Claude. Rotated Claude ids are kept in `claudeSessionIdHistory` so older ids still match. Hub: schema v35 adds `session_redirects`; every merge that deletes a row records old -> survivor, and client-facing lookups follow it (sockets and job ownership stay strict). New `GET /cli/sessions/resume-target-by-agent`. Web: a merged-away URL moves to the survivor instead of bouncing home, and live Claude duplicates stay visible in the sidebar. * fix: keep job-key remaps and hub-archived resumes working after redirects Review follow-up for the stable session identity change. - Job routes: the session lookup now follows a merged-away id to the survivor, so `requestedSessionId` must stay the raw URL id. Otherwise a colliding `<old id>/<key>` remap was bypassed and PATCH/DELETE/late PUT through the old id hit the survivor's own job. - Terminal resume of an inactive session now asks the hub to clear a hub-authored archive first (`POST /cli/sessions/:id/prepare-local-resume`, same clear as hub reopen), so `hapi claude --resume/--continue` (and `hapi resume`) no longer exit on the #1911 existing-session guard. * fix(cli): refuse an explicit Claude resume whose transcript is gone Reopening the owning HAPI session drops --resume and hands the id to the local launcher, which silently starts a fresh conversation when the transcript is missing — under the existing HAPI id, title and history. Check the transcript before any handoff or archive change and fail explicitly instead. * fix: follow merged-session redirects on /api only for clients that rebind Native clients store a session detail under the requested id and drop SSE events for any other id, so a merged-away id that resolved to the survivor loaded history but never showed live messages. `SyncEngine.resolveSessionAccess` is strict again by default; `/api` routes follow redirects only with `x-hapi-follow-session-redirects: 1`, which the web client (that rebinds to the returned id) sends. Native clients keep the previous 404. CLI REST always follows. Job routes still keep the raw URL id for key remaps under both modes. |
||
|
|
7ac33a70c3 |
feat: show generation rate (tok/s) for Codex rounds (#2379)
* feat(codex): fill the round footer tok/s from app-server timing Measure each Codex round's generation window the way agy rounds do: the live turn span minus tool-execution and wait-for-the-user windows, over the thread-cumulative output-token delta, emitted on the turn's turn_duration so the round footer shows tok/s. Tool windows prefer the app-server's own item timing (startedAtMs/completedAtMs/durationMs). The token baseline is the last reported cumulative total: the CLI seeds a thread it created in this process (thread/start) to zero, while resumed and forked threads receive the app-server's attach-time usage replay and stay unseeded, so inherited history is never counted as a turn's output. Only the live root-turn feed reaches the ledger: history replays re-project old items and must not settle a round. Permission hooks keep timing waits for the user. * fix(codex): seed gateway-created threads for the first-turn tok/s baseline Native /new and /clear create threads through the gateway before/after hooks, whose after() binds the fresh root without the zero usage seed the runtime create path applies - so the new thread's first turn captured a null baseline and never showed tok/s. Seed it there too, same as create(): thread/start only, since forked threads receive the app-server's attach-time usage replay instead (tiann/hapi#2379). * fix(codex): keep the active generation ledger across a hub-only reconnect SharedCodexRoot's session.onReconnect reset the whole projection, but a hub reconnect only replays final history: the native turn keeps running without a new turn/started, so dropping the ledger identity, baseline and windows made generation.settle() return null at completion and the round permanently lost its tok/s. Add projection.resetAfterHubReconnect which replays without touching the ledger; the app-server reconnect path keeps the full reset, because the resumed turn re-announces itself and must re-measure from its own start (tiann/hapi#2379). * fix(codex): seed fresh usage before session-ready releases queued input The gateway thread/start seed ran in the after() hook, after the bind wrapper had already activated the root: registerControls and emitSessionReady open the input gates, so a queued Web prompt (or one submitted on session-ready while the runner notification is delayed) could start the thread's first turn before the zero baseline existed, and seeding afterward could not repair that captured-null turn. Move the seed into the bind wrapper right after root.bind, guarded by a freshThread flag the create and gateway paths set for thread/start only - forks keep their app-server attach-time replay baseline (tiann/hapi#2379). |
||
|
|
eff515e2e0 |
feat(cli): rotate hub entries after repeated connect failures (#2383)
Self-hosted hubs are commonly reachable through several origins (an edge-proxied domain and a direct one); cross-border interference can randomly break TLS on either for hours. A runner pinned to a single HAPI_API_URL sat dead through those windows. When HAPI_API_FALLBACK_URLS is set, the machine client keeps a rotation ring (primary + fallbacks) and, after HAPI_API_FAILOVER_AFTER (default 5) consecutive connect failures, tears the socket down and reconnects through the next entry. A successful connection on a fallback schedules a return-to-primary attempt after 30 minutes. Without the env, behavior is byte-for-byte unchanged. |
||
|
|
5e76af5615 | feat(codex): fork running sessions through the last completed turn (#2369) | ||
|
|
f11f7097ef | fix(cli): respect workspace image delivery preferences (#2368) | ||
|
|
ac82d2d8d6 |
feat: show generation rate (tok/s) for Claude rounds (#2367)
* refactor(agent): extract agy's generation-time clock into a shared helper agy computes generation time as the round minus tool-run and user-wait windows. Move the window math and the event-fed bookkeeping into cli/src/agent/generationClock.ts (GenerationClock + generationTimeMs) so other ACP launchers can time their rounds the same way, and feed agy's clock the same session updates and permission waits it always did. Numbers are identical: the moved pure function is agyGenerationMs verbatim and the agy tok/s integration tests pass unchanged. * feat(claude): fill the round footer tok/s from the SDK result Claude Code reports duration_api_ms on every result: the API-active time of the round, with tool execution and permission waits already outside it. Pair it with the round's usage.output_tokens and send both in the existing turn_duration resultSummary, so the web's generic round-summary normalizer picks them up and the footer renders tok/s — no new wire types, and the renderer already knew how to format the pair. Errored rounds and the manual /compact turn carry no meaningful generation rate, so they emit nothing: claudeRemote marks the compact turn result in-process (hapi_compact_turn) before it reaches the log converter. Values that cannot produce a rate (zero, negative, fractional, missing) are omitted rather than guessed. |
||
|
|
7ac95e0e2e | fix(cursor): fresh-spawn resume when ACP thread never persisted a store (#2184) (#2343) | ||
|
|
bfec91b5e1 | fix(codex): start a new goal after the previous one completes (#2338) | ||
|
|
39da0be557 |
feat(cli): Cursor emits AGENT_NOTIFY_SUMMARY when status-summary toggle is on (#2354)
* feat(cli): Cursor emits AGENT_NOTIFY_SUMMARY via rules overlay When Emit status summaries is on, install a transient workspace .cursor/rules overlay for Cursor ACP sessions and clean it up on teardown, closing the flavor hole left after #1376. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): harden Cursor notify-rule overlay ownership and exclude Address review on the emit overlay: clear ownership state under lock, refresh crash-recovery snapshots after user replacement, fall back to an alternate rule filename when the primary path is tracked, and lease .git/info/exclude so git add -A cannot stage the transient rule. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): path-scope notify overlay ownership and reap excludes Refresh restore snapshots on live user replacements, key ownership by selected rule path, and prune dead PID-stamped .git/info/exclude leases left by crashed Cursor sessions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): harden Cursor notify overlay against symlink and path traps Refuse rule writes through symlinks, canonicalize workspace paths for ownership, escape literal Git exclude patterns, and qualify settings copy as Cursor ACP. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve unreadable rules and file modes in notify overlay Skip install when an existing rule cannot be backed up, restore original permission bits on cleanup, and stop retrying ownership-lock callback failures as lock contention. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): keep notify overlay restore snapshot on unreadable cleanup When teardown cannot read the generated rule, leave the file alone but retain the private ownership snapshot so a later session can restore the user's original content; write state.json as 0600. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): restore notify overlay snapshot even if install never wrote Last-owner cleanup now restores from the shared snapshot whenever the on-disk rule is still HAPI-owned, including handles that registered then failed before writing the generated rule. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): write notify overlay ownership state atomically Replace in-place state.json writes with temp+rename so a partial failure cannot destroy the only backup of a user rule, and harden the failed- install recovery test to actually chmod the exclude file. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): fail closed on abandoned notify overlay locks Publish pid+token via link(2) like the MCP overlay so a crashed holder leaves an identifiable lock, and surface an actionable rm path instead of silently spinning for five seconds. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): retry notify overlay lock when holder already released After link EEXIST, a missing lock means the contender freed it before our owner read - retry acquire instead of misreporting the path as abandoned. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): treat notify lock ENOENT during owner read as retry Distinguish missing vs invalid lock contents so a holder that releases between existsSync and readFile is not misclassified as abandoned. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): recreate notify overlay stateDir under the ownership lock Last-owner cleanup no longer rmdirs stateDir, and install mkdir+write runs inside the lock so a waiting installer cannot hit ENOENT on state.json. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
ce6d074a54 |
fix(session): deactivate a session as soon as its runner child dies (#2351)
* feat(shared): add session-child-exited CLI socket event * feat(cli): report unexpected runner child exits to the hub * feat(hub): mark a session inactive when its owning runner child exits * fix(hub): respawn resume when the active session has no live CLI socket * fix(hub): fail safe owner guard when the session row has no start marker A session row can carry no hostStartMarker (the CLI's start-marker probe fails at spawn). The child-exit owner guard then matched on pid alone, so a late notice from an old process whose pid the OS reused deactivated the current owner instead of being ignored. Require an exact marker match whenever either side carries a marker, and when both sides lack one, accept only a notice that is not older than the current owner's registration (metadata.lifecycleStateSince, written by the CLI together with hostPid on every spawn). Anything else falls back to the keep-alive grace. * fix(cli): release intentional-stop pid markers that no exit event will consume intentionallyStoppedPids entries were only consumed by onChildExited. A stop that ended already_gone, still_alive or unknown never produced that exit event for pids without a runner-spawned child handle, so the entry stayed forever and suppressed the real unexpected exit of a later child that reused the pid. markIntentionalStop now returns the pids it marked plus the subset with a child 'exit' listener; the stop wrapper releases the rest once the stop attempt settles, so only exits that a spawned child will still report through onChildExited keep their suppression. * fix(hub): only respawn an active row without a live socket when it is runner-spawned An empty session socket room also happens during a transport reconnect while the CLI process still runs. Resuming a terminal-started session in that window fell through to spawning a second CLI: the runner's spawn dedupe only covers sessions it spawned itself, so the replacement could overwrite ownership metadata and compete with the original process when its socket returns. Keep the legacy no-op success for active rows the hub cannot prove are runner-spawned; runner-spawned rows keep the respawn shortcut, where the runner deduplicates spawns per existing session while its child lives. * fix(cli): keep intentional-stop suppression only for the pids a stop terminated A stop that preserved a shared Codex wrapper for sibling roots returned stopped while its PID stayed marked intentional; because the wrapper has an exit listener, the marker survived until the wrapper's own exit. A wrapper that later crashed on its own consumed that stale marker and suppressed the death notifications for every sibling root, leaving them active until the keep-alive grace. Failed stops that leave a tracked child alive leaked the same way. Record the PIDs each stop attempt actually terminated and retain their suppression only while the child's own exit event is still pending; release the rest (preserved wrappers, children left alive, already-gone outcomes) so a later real death is reported. * revert(hub): keep the active-session resume shortcut Revert the ghost-active respawn from resume: an empty socket room also happens during a transport reconnect, runner dedupe can return the live child while the resume path waits for a fresh ready the session never re-emits (Pi readiness emits once), and a ghost-active Codex row refuses cold resume while the row is still active. Upstream's original behavior returns success for any active row; dead owners there are recovered by the child-exit notice, the owner guard, and the keep-alive grace. |
||
|
|
b7b1da40eb |
feat(copilot): reasoning effort selection for remote sessions (#2348)
* feat(copilot): reasoning effort selection for remote sessions Copilot's ACP session advertises the active model's reasoning levels as a thought_level config option. Expose it like Grok's: a session RPC + hub route for the options, the composer effort picker, and per-turn session/set_config_option in the remote launcher. The runner forwards --effort so resumed sessions keep the selection. * fix(copilot): keep effort options in step with model switches Copilot answers session/set_model with no config options and pushes the new model's thought_level via config_option_update; capture it (opt-in in the ACP backend), re-baseline the launcher's effort after a switch, report 'switch pending' until the next turn applies it, and have the web poll until discovery succeeds instead of giving up on the first failure. * test(acp): flavor-neutral config_option_update test * fix(copilot): gate effort discovery on the model the backend applied Compare the model the next queued turn carries with the backend's model instead of session state, so an older queued batch or a failed switch keeps discovery pending; forward the saved effort on terminal resume. |
||
|
|
42a00d5dcf | fix(cli): name the failed phase and delivery state in ping_peer errors (#2345) | ||
|
|
72ecf885d6 |
fix(codex): resolve developer instructions after session bootstrap (#2344)
Fixes #2305 |
||
|
|
ee73f3a848 |
feat: show progress bar on session for hours-long jobs (#1424)
* feat: session-attached long-running jobs (#1404) Hub-persisted jobs that outlive the agent process: register/update/clear via REST + `hapi job`, surface primary running progress on the session list even when active=false. Opt-in registration only — not thinking progress. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(jobs): agent guidance + wall-clock elapsed on list chrome Document the session-job contract for agents and always show startedAt elapsed next to remaining/fraction/running so indeterminate drains still read as wall time without inventing an ETA. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): address Opus cold-review Majors for #1404 Add hapi job run supervisor (auto-heartbeat + exit status), follow post-merge job-owner redirects so $HAPI_SESSION_ID heartbeats keep working, cover the CLI parser/resolve/run paths with tests, and steer agents toward the supervisor instead of an idle-agent heartbeat myth. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): honor explicit startedAt on PUT; document late-attach clock Beets dogfood: PATCH rejects startedAt; sticky PUT clock made elapsed lie after late attach. Explicit upsert startedAt now corrects; CLI --started-at; clear+set recipe kept for older hubs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): keep merge redirect keys in MetadataSchema (#1404) SessionCache.refreshSession stripped jobsAcceptedFromSessionIds / jobsTransferredToSessionId as unknown keys, so resolveAttachedJobSessionId could not follow post-merge heartbeats. Declare the fields, add a real SessionCache integration test, and pass full UUIDs through the CLI when the merge source is missing from GET /sessions. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(jobs): MCP session_job tool for catalog-level discoverability Expose session-attached jobs in the same HAPI MCP catalog as ping_peer / inspect_peer so Cursor/ACP and steered flavors see outliving-work meters as first-class tooling, not docs-only. Auto-approve own-session calls; steer prefers MCP set/update or CLI job run for supervised children. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(web): tri-state pin — default long-running jobs with #1404 Replace boolean pin-in-progress with off / jobs / all. Unset preference defaults to jobs so outliving attached-job sessions float to In progress by default; legacy true→all, false→off. Settings Display gets a 3-way control. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): cold-review pass 3 Blocker + Majors (#1404) CI: bump migration tip expects to SCHEMA 22; stub list attachedJobs mocks; align Codex/OpenCode/ACP fixtures with job steer + session_job tool list. Merge: write jobsAccepted/Transferred redirects after metadata merge so a name/summary copy cannot clobber the post-merge job owner map. MCP: session_job is own-session only (drop sessionId from schema) so auto-approve cannot silently write peer meters. Prefer hapi job run in steer. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): close pass-3 minors — stable primary, own-client heartbeats Resolve JWT/session once for job run heartbeats; order primary job by started_at ASC; cover job redirect 404 + invalid key/body; idle jobs get a Jobs bucket (not Running); treat attachedJob.startedAt as render-relevant. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): refresh JWT for long job-run heartbeats (#1404) Cache sessionId once but re-exchange JWT before hub's 4h expiry and on 401 retry so days-long supervised jobs keep heartbeating and can still mark completed/failed. Log the first heartbeat failure to stderr. Co-authored-by: Cursor <cursoragent@cursor.com> * test(jobs): cover proactive JWT refresh; map 401 to auth_failed Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stamp fresh startedAt on job run; prefer supervisor Re-running the same job key was sticky-reusing a prior row's startedAt, so elapsed lied. Drain in-flight heartbeats before terminal status. Align AGENTS/guide: CLI supervisor first, MCP as manual path. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): typecheck-safe assertion for run startedAt Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): type put mock args so startedAt assertion typechecks Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): address Codex Majors — redirect ancestry, heartbeat status, ACP allowlist Inherit jobsAcceptedFromSessionIds across A→B→C merges; heartbeat PATCH omits status so late ticks cannot resurrect running; drop session_job from global name-only auto-approve (bridge/--allowedTools remain the trust path). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): type from-session metadata when inheriting job redirects Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): version attachedJob SSE; keep live job on merge collision Gate list cache on versioned attachedJob patches so dual EventSources cannot resurrect a cleared meter. On transfer key collision, prefer a running source over a terminal target (heartbeats no longer rewrite status). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): monotonic attachedJob emit watermark (not primary.updatedAt) Primary switches can go backwards in updatedAt and strand the list cache. Emit versions are Math.max(Date.now(), prev+1); REST list stamps a fresh wall-clock watermark so null jobs do not reset the client gate to 0. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): one attachedJob watermark allocator for REST and SSE GET /sessions and emitAttachedJobChanged share allocateAttachedJobVersion so equal-ms terminal patches are not rejected after a list refetch. Also preserve real Unix signal exit codes in hapi job run. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stub allocateAttachedJobVersion in sessions route mocks Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): always record merge redirects even with zero jobs transferred Agents may attach the first outliving job after merge while still holding the pre-merge HAPI_SESSION_ID; redirects must exist before that first set. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): install source redirect before merge awaits; allow empty update Point jobsTransferredToSession immediately after transfer so mid-merge heartbeats follow the new owner during scratchlist I/O. Empty CLI/MCP update bodies are heartbeat-only (hub stamps heartbeatAt). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): expect empty MCP update as heartbeat Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): treat merge redirect metadata as hub-owned CLI update-metadata must not forge or erase jobsAcceptedFromSessionIds / jobsTransferredToSessionId — same strip/restore as supersede/clear links. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): reconcile REST list against attachedJob watermark Slow /api/sessions can finish after SSE clear/progress and resurrect a stale attachedJob. Also prefer newer terminal results on merge key collisions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): retry terminal status write; reject startedAt on update Supervisor exit is the only running→terminal transition — retry transient hub failures. --started-at / startedAt only apply to set, not update/run. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): keep both live jobs on same-key merge Dual-running collisions remap the source key and record jobKeyRedirects so pre-merge supervisors cannot terminal-mark the winner. Also raise the flaky claudeRemote first-result test timeout under CI load. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): hard-refuse MCP set; louder stale heartbeat chrome Process-shaped work must use Shell hapi job run. MCP set is refused with the run recipe (wardrobe freeze). Stale rows show "no heartbeat · age". Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): preserve jobKeyRedirects across metadata merge + A→B→C Recompute merge metadata from latest target so early key remaps are not clobbered; compose inherited redirects through the current remaps. Localize stale/progress chip strings (en + zh-CN). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): keep running-job stubs in sidebar; align bar precedence Empty idle stubs with a live attachedJob must survive prepareSidebarSessions before title metadata lands. Match fraction to remaining-first label order. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): block delete while job running; keep jobful dedup losers CASCADE would erase outliving meters on inactive delete. Sidebar dedup must not hide a running attachedJob behind a jobless duplicate winner. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): guard store delete for running jobs; transfer on Codex merge Route-only 409 still left Codex duplicate consolidation and other callers cascading live meters. Refuse in DELETE SQL, clear watermarks, and transfer+redirect before Codex hard-deletes duplicates. Co-authored-by: Cursor <cursoragent@cursor.com> * test(jobs): stub transferAttachedJobs in Codex duplicate-merge mock Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fence supervisor PATCH with expectedStartedAt Stale hapi job run processes must not heartbeat or terminal-write a newer run that reused the same job key. Treat startedAt as the run generation: supervisors send expectedStartedAt; hub rejects mismatches with 409 (CAS in SQL too). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): CAS supervisor writes with UUID runId (schema V24) Date.now()/startedAt is not unique across concurrent job-run processes. Persist run_id, mint UUID on PUT (client or hub), and reject PATCH when expectedRunId does not match. Replaces the interim expectedStartedAt fence. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): heartbeat PATCH must not re-send launch --detail Supervisor timer only needs expectedRunId so MCP/CLI progress detail updates are not clobbered by the next heartbeat. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stamp heartbeatAt on the hub only Drop heartbeatAt from upsert/patch schemas and always persist Date.now() on the hub so a skewed/future client clock cannot keep a dead job green. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(jobs): note schema tip V25 after A2A V23 collision Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): clear stale jobsTransferred redirect on reclaim When A→B then B→A makes A canonical again, drop A's outgoing jobsTransferredToSessionId so resolve(A) no longer hops to deleted B. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): transfer attached jobs on OpenCode /clear finishOpenCodeClear already wrote supersededBySessionId (which job APIs follow) without moving session_jobs. Transfer first so heartbeats on the retained source id reach the replacement row. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): follow job redirects with cycle detection Replace the five-hop cap so supervisors that retain the original HAPI_SESSION_ID across many OpenCode /clear replacements still resolve to the canonical owner. Visited-set stops redirect cycles. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): defer no-engine Codex merge; pending outranks Jobs Refuse duplicate merge when SyncEngine is unavailable and the source still has attached jobs (redirects cannot be persisted). Sidebar: put operator-pending ahead of the Jobs bucket when both apply. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): allocate list watermark before reading jobs GET /api/sessions was labeling snapshots with a version allocated after the job read, so a concurrent SSE emit could lose to a stale REST value. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): stamp supervised startedAt on the hub clock hapi job run omits startedAt; hub uses now when runId starts a new generation so runner/hub skew cannot zero or inflate elapsed time. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve -- for hapi job run under normalizeCliArgs Runtime-wrapper handoff was dropping everything before `--` (or stripping `--` itself), so `job run … -- <cmd>` fell through to Claude. Keep `--` when a HAPI command already precedes it; only treat bare `bun entry -- <cli>` as a wrapper handoff. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): allow PATCH null clears from CLI and MCP Hub already accepts null to drop stale remaining/done/total so done+total can take over. Expose that via MCP nullable fields and hapi job update --clear-remaining (and siblings). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): scope -- keep to job run; expose runId fence on CLI Only preserve the child `--` separator for `job run`. Re-inserting it for `hapi -- auth` / `codex --` broke resolveCommand. Manual wrappers can now stamp `--run-id` / `--expected-run-id` to match hub CAS. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fence DELETE/clear with expectedRunId Stale manual wrappers must not clear a newer run after key reuse; hub DELETE and CLI/MCP clear now honor the same run fence as PATCH. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): include runId on listSessionJobs for fence recovery Safe PATCH/DELETE need expectedRunId; list/MCP/CLI must return the generation so reconnecting wrappers can fence without guessing. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): stamp attachedJob on new SessionSummary test helpers Upstream share-picker / row-summary fixtures landed without #1404 fields; restore typecheck after rebase onto main. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fail job run when terminal status never persists Child exit 0 with a frozen running meter lied to wrappers; surface hub write failure as exit 1 (run-mismatch still non-fatal). Clarify Active-sessions-only copy for attached jobs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor,web): stop attached-job sessions bouncing Running/Jobs (#1553) Rebase onto upstream/main (#1503). Ignore ambient ACP thinking bumps while the message queue is idle and prompt() is not in flight. Prefer the Jobs in-progress bucket and suppress the thinking spinner when a running attached job is the honest outliving signal. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): do not mask foreground thinking when attached job runs (#1553) Keep the CLI queue-idle ACP guard; web now trusts hub thinking during real prompts instead of treating every attached job as ambient chatter. Co-authored-by: Cursor <cursoragent@cursor.com> * fix: rebase onto upstream/main — resolve test mock conflicts Merge upstream title/summary stubs with attached-job mocks; drop duplicate showSessionSummaryInChat key introduced during rebase. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): preserve child exit 0 when meter cleared during job run Treat terminal PATCH not_found as detached (operator cleared via session_job) instead of a supervision failure. Retry transient 404s; accept absence on the last attempt. Regression test covers successful child after external clear. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): filter only debounced running chatter while queue-idle (#1553) Tag agent-activity listener callbacks with source in AcpSdkBackend so the Cursor launcher can ignore queue-idle state_update:running without hiding harness resume (requires_action, permission). Regression test updated. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(#1424): trust ACP foreground signals; preflight merge job check Drop queue-idle running suppression in Cursor launcher — it hid autonomous harness work. Attached-job Running/Jobs flicker stays in web/sessionInProgress. Refuse no-engine Codex merge before copying history when sources have jobs. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): steer agents away from sleep-stub jobs and remaining=0 traps MCP update-before-create and hapi job run -- sleep while real work runs elsewhere can leave a misleading running meter. Return job-run recipe on not_found, warn when remaining hits zero without completion, and tighten session_job agent instructions. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): steer MCP session_job not_found even when instanceof breaks MCP HTTP server bundles can load duplicate SessionJobError identities so update-before-create fell through to bare "job not found". Detect not_found by code and message, not instanceof alone. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): idempotent MCP clear-not-found; reject --heartbeat-sec off run Clear on an already-absent job returns success without steering to hapi job run. Parser rejects --heartbeat-sec on set/update/clear/list. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): reject mutation flags on job list/clear and status on run Parser now fails fast when list/clear receive label/status/progress fields, or when run receives --status, instead of silently discarding them. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): reject stray MCP fields and non-run command suffix MCP list/clear reject incompatible fields; CLI rejects -- <cmd> unless action is run so clear/set cannot silently drop a trailing command. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): preserve runId on corrective job PUT without runId Started-at corrections via job set must not mint a new generation and break an in-flight supervisor's expectedRunId fence. Docs heartbeat recipe now shows run-id + expected-run-id. Co-authored-by: Cursor <cursoragent@cursor.com> * docs: mark ALL_DONE late-attach example as completed status job set defaults to running; remaining=0 alone does not finish the meter. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web,cli): finish #1424 rebase onto upstream pin buckets Keep Jobs in the In progress section after upstream split Active/Running. Preserve Cursor ACP retry fields and Codex prompt test names from main. Quiet connected sessions stay in directories (#1404 stand). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): rename All activity — quiet connected is not in-progress Connected-but-idle sessions stay in project folders in every pin mode. UI mode label is now Working & pending; drop the unreachable Active pin bucket and the copy that claimed quiet actives floated under All. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(guide): session-id contract and remaining vs bar fill Document hub-row vs worker HAPI_SESSION_ID bug and that --remaining alone does not move the progress bar without total. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): bind isNewerVersionedPatch after sessionPatch extract `export … from` does not put the helper in module scope, so attachedJob list patches failed typecheck after the rebase onto upstream's extract. Guide copy now matches Working & pending; quiet connected stays in folders. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): commit job-row move and owner redirects together A failed metadata write after sessionJobs.transfer left the old session id pointing at an emptied source, so heartbeats 404ed. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): fail-closed session id for remote Cursor job run AGENTS and recipe copy no longer treat \$HAPI_SESSION_ID as always safe; remote Cursor may export a worker row. Cursor resume bootstrap test asserts the requested existingSessionId is exported into the child env. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): refresh job redirects before scratchlist merge await persistAttachedJobRedirects wrote SQLite while resolveAttachedJobSessionId still read stale cache; heartbeats via the old id could 404 during attachment I/O. Refresh both sessions immediately after persist. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): ignore ambient ACP running without a prompt in flight state_update_running chatter while the queue is idle was setting hub thinking and floating quiet sessions (with jobs) into Working. Permission and requires_action still bump; prompt-owned running still bumps. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cursor): drop leftover rebase conflict markers in ACP launcher Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): sanitize job text before terminal stdout Strip VT/ANSI and remaining C0 controls from job key/label/unit/detail/runId in formatJobLine so list/set/update cannot emit OSC escapes from persisted fields. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): sanitize MCP session_job output via shared formatter Move terminalText/formatJobLine into modules so CLI stdout and MCP tool results both strip VT/ANSI/C0 before agents render job fields. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): scrub C1 controls in shared job-output sanitizer Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): fix C1 sanitizer assertion (content may remain) Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): remap late job PUT when merge left no key redirect When a merged-away session registers a new runId for a key the target already owns as a different running generation, allocate a remapped key and persist jobKeyRedirects so the target's live meter is not overwritten. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): also remap redirected job set without runId on collision Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): tree-kill supervised job children on SIGINT/SIGTERM Bare process.kill only hit the immediate child; a shell grandchild could keep running after the wrapper marked the job terminal. Use killProcessByChildProcess. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): preserve SIGINT on job tree-kill and await teardown Forward the received signal through killProcessByChildProcess so Ctrl-C stays exit 130, and wait for verified tree termination before writing the terminal job meter. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): type the tree-kill teardown patch mock for typecheck Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): supply attachedJob fields in upstream session fixtures After rebasing onto main, mark-all-read and app-badge helpers need attachedJob / attachedJobUpdatedAt for SessionSummary typecheck. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): record identity jobKeyRedirects on no-collision transfer A→B transfers that keep the original key must still map A/key→key so a later B→C remap can compose A through to the remapped key instead of resolving onto C's unrelated live same-key job. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): resolve job owner after PUT/PATCH body parse A merge/clear during the JSON await must not leave mutations targeting the pre-merge session id. Validate the body first, then resolve owner and key synchronously before upsert/patch. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): honor identity jobKeyRedirects on corrective PUT Explicit A/key→key maps from no-collision transfers must short-circuit late-registration remapping so job set without runId updates the same row instead of allocating a second key and orphaning the supervisor. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): persist identity redirects on late free-key job PUT Empty A→B then late register left no A/batch map, so B→C remaps could not compose and A targeted C's live meter. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): skip redirect inheritance on late job-key PUT Recording a free-key identity via retained B was reimporting B's stale A/batch map onto C and undoing composed A→B→C remaps. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): supply attachedJob on new upstream search fixtures Rebase onto main brought search-rank helpers that omit SessionSummary.attachedJob fields required by #1424. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): pass XDG_CACHE_HOME through vitest hub globalSetup Estate bun installs pin the cache via XDG_CACHE_HOME; the test hub whitelist omitted it and `bun run hub` hung before ready. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): retarget bucketRunningSessions for jobs pin modes Upstream #1820 idle/active boolean buckets no longer exist after the quiet-connected never-floats contract; cover jobs/working/pending instead. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): add Russian strings for session jobs pin modes Upstream shipped ru locale after the jobs pin UI; fill attachedJob and tri-state pin copy so Display settings are not missing keys. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(cli): steer agents to list session jobs before done/archive MCP session_job description and always-on SESSION_JOB_INSTRUCTION now require list on resume and before done; clear zombie running meters without asking the operator. No hub auto-clear. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): keep ACP MCP tool list without video/media after rebase Co-authored-by: Cursor <cursoragent@cursor.com> * docs(jobs): forbid frozen 0/N job run for display meters Split alive-only vs fraction bars in the guide and always-on steer: heartbeats do not advance launch --done/--total; name hapi-job-run-metered and the continuous-update portable path; note exit≠semantic failure. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): expect Codex autoReview in set-mode allowed lists Upstream #2090 added autoReview after #2095 set-mode tests; update the allowed-mode strings so CI matches the catalog. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): use SessionSpinner for foreground thinking after merge Keep isAgentForegroundThinking gate; match upstream SessionSpinner markup so background/thinking spinner equality tests pass. Co-authored-by: Cursor <cursoragent@cursor.com> * test(hub): expect schema tip v29 in migration-v26 after jobs remap Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): expect fixed-order + jobs pin after merge with upstream display Upstream asserted Fixed session order was gone; #1424 keeps it with the tri-state pin choice group. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): honor Fixed session order with creation-time sort Tip Minor: the setting only paused pin float while directories still sorted by lastUserMessageAt. Use createdAt comparators for rows, groups, and global pins when fixed mode is on. Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): cover Fixed session order vs activity list promotion Upstream order test forced obsolete fixed-order=true and expected activity promotion; with #1424 keeping the setting, split default vs fixed cases. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): preserve composed jobKeyRedirects on cleanup re-merge A second B→C merge with empty remaps was reimporting retained B's stale A/batch→batch and clobbering C's composed A/batch→batch.<B> mapping. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): survive hub-down after job run child exit Terminal completed/failed PATCH now retries connection/502–504 failures for up to ~10m so a brief hub restart cannot leave a zombie running meter. Refuse wrapping hapi-restart-hub / stack-switch argv in job run; document the hard rule in the guide and CLI help. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): classify HTTP 502–504 via SessionJobError.httpStatus Structured hub outage bodies (e.g. 503 "Not connected") no longer drop the status code, so terminal PATCH keeps the hub-down retry window instead of exiting after three short attempts. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: nudge GitHub PR head sync for #1424 Fork tip already includes the upstream/main merge; empty commit to re-fire the cross-repo PR head webhook (API still showed prior SHA). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): honor jobs exception and fixed order under list view Active status filter keeps idle running attachedJob rows (and keeps them out of archived). Fixed session order forces created sort with activeFirst off, not only pin-off. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): ignore obsolete fixed-order key under SessionListView Upstream #2263 made hapi-fixed-session-order obsolete; reading it overrode last-message promotion. Keep jobs-aware status filtering; list sort stays on SessionListView. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): include attachedJob on content-search summaries Content-search replaces live list rows; omitting jobs dropped meters and the active-filter exception for matching idle sessions (#1424). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): remove obsolete fixed session order setting SessionListView owns list order (#2263); the switch only wrote a dead localStorage key and kept recycling tip Findings on #1424. Co-authored-by: Cursor <cursoragent@cursor.com> * chore: nudge GitHub PR head sync for #1424 Co-authored-by: Cursor <cursoragent@cursor.com> * test(web): drop Fixed session order assertion from display settings Matches removal of the obsolete switch under SessionListView (#2263). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): drop fake 1/3 fill for indeterminate attached jobs Remaining-only jobs have no fraction; the old pulse bar painted a constant w-1/3 that looked like progress. Keep honest text; show a bar only when done/remaining+total yields a real fraction. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(jobs): wake owning session on terminal status (#1489) Fold opt-in wakeOnTerminal into the #1424 tip for dogfood-lane ship. Schema v33→v34 additive wake columns + runId one-shot claim. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): release terminal wake claim on delivery failure Provisional wake_emitted claims must clear when resume/send fails so a reconnect retry can reclaim; schedule capped backoff and use a run-scoped localId for send dedupe (#1489 tip Finding). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): requeue wakes after retry budget and follow ownership Keep undelivered terminal wakes eligible after rapid-retry exhaustion and rescan on hub start / machine offline→online. Resolve job-owner and key redirects before claim, release, and deferred retry so merges cannot strand a provisional wake_emitted claim. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): provisional pending wake claims + run fence Persist wake delivery as pending:<runId> until send succeeds so hub restart can clearAbandoned and reclaim. Before send, fence the live row to the claimed run/terminal/opt-in so key reuse mid-resume cannot mis-prompt. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): classic indeterminate marquee for unknown attached jobs Session list claimed an "indeterminate bar" but only rendered the pulse dot when fraction was null. Show a track with a sliding segment (no %) in the same slot as determinate fill, with unit coverage and docs/help aligned to shapes A/B. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): quiet striped indeterminate job bar Replace the loud sliding-chunk marquee with CSS-Tricks-style diagonal stripes that drift slowly at low contrast — still reads as moving, not carnival mode. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(web): seamless loop for indeterminate job stripes Animate background-position by exactly one 8px tile on both axes so the diagonal stripe phase matches at the loop boundary (was -12px → jump). Co-authored-by: Cursor <cursoragent@cursor.com> * fix(jobs): requeue wakes on machine-update-state online Connect marks active via runner-state update before the first heartbeat, so heartbeat offline→online never fired. Requeue pending terminal wakes when machine-updated refreshes an offline machine to active. Co-authored-by: Cursor <cursoragent@cursor.com> * test(hub): cast private machineCache in wake reconnect coverage CI typecheck failed on private SyncEngine.machineCache access from the machine-updated requeue test. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): monotonic machine active_at on runner-state online refreshMachine only adopts store activity when storedActiveAt is strictly newer than the cache. Same-ms create→updateMachineRunnerState left the cache stuck inactive and skipped #1489 wake requeue. Bump active_at past the activity floor; align the reconnect test with memory-only expiry. Co-authored-by: Cursor <cursoragent@cursor.com> * feat(cli): require --progress mode on job run/set Forces an explicit affordance (unknown|fraction|until) so known-duration countdowns cannot silently fall into indeterminate stripes. until stamps remaining/total and job-run heartbeats re-stamp remaining from the deadline. Co-authored-by: Cursor <cursoragent@cursor.com> * docs(session-jobs): require --progress in create examples Bot Minor: wake/set/heartbeat/CLI recipes and AGENTS.md omitted the now-mandatory progress mode, so copy-paste creates would fail parse. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(cli): refuse numeric sleep without until; honor --started-at on countdown Closes the dogfood footgun: sleep N under unknown/fraction is rejected. Until-mode job run accepts --started-at so mid-window re-attach keeps the original window total; heartbeats stamp against that start. Docs demote estate-only hapi-job-run-metered as non-upstream. Co-authored-by: Cursor <cursoragent@cursor.com> * test(cli): type heartbeat mock args in until startedAt coverage Fixes CI TS2493 on patch.mock.calls[0][1] from an untyped vi.fn. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(hub): exempt job-wake prompts from session-end sweep Session-end was synthetically consuming unacked hapi-job-wake: rows, so a completion wake queued behind an active turn could be lost when the CLI disconnected before messages-consumed. Mirror the ping-peer- exemption so wakes stay replayable until a real runtime ACK. Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
2d400a2abd |
feat(kimi): thinking level selection for remote sessions (#2349)
* feat(kimi): thinking level selection for remote sessions Kimi Code's ACP session advertises the active model's thinking levels as a thought_level config option (`thinking`: off/on or off plus declared efforts). Expose it like Grok's effort: a session RPC + hub route for the options, the composer effort picker, and per-turn session/set_config_option in the remote launcher. The runner forwards --effort so resumed sessions keep the selection. * fix(kimi): keep thinking options in step with model switches Kimi Code answers session/set_model with no config options and pushes the new model's thought_level via config_option_update; capture it (opt-in in the ACP backend, same hunk as #2348), re-baseline the launcher's level after a switch, report 'switch pending' until the next turn applies it, and have the web poll until discovery succeeds. * fix(kimi): gate thinking discovery on the model the backend applied Compare the model the next queued turn carries with the backend's model instead of session state, so an older queued batch or a failed switch keeps discovery pending; forward the saved effort on terminal resume. |
||
|
|
f34ff13fce |
feat(peer): forward peer replies back to the caller with waitForReply (#2167)
* feat(peer): spawn_peer and reply forwarding for peer sessions Peer sessions could only fire messages at each other: the caller had to poll inspect_peer to learn that a peer finished, and nothing woke it once it ended its turn. There was also no way to start a peer for new work. - spawn_peer starts a session on the caller's machine (directory and agent default to the caller's) and sends it a task. - ping_peer gains waitForReply. - In both cases the caller's CLI watches the peer and, when its turn ends, posts the peer's latest reply into the caller session, which starts the caller's next turn. spawn_peer needs manual approval like ping_peer. No hub changes. * refactor(peer): drop own spawn_peer; add waitForReply to upstream spawn_peer Upstream #1922 ships spawn_peer (spawn, rename, remit delivery, fresh-child wait, manual approval). Remove this PR's duplicate spawnPeer and keep only reply forwarding: spawnPeer now returns the remit's ping-peer localId and resolved flavor, and MCP spawn_peer/ping_peer share one waitForReply hook. Add a steered-task attribution test. Co-Authored-By: Claude <noreply@anthropic.com> * fix(peer): keep waiting for a task an offline peer has not read The hub keeps unconsumed peer tasks for replay, so a peer that goes offline before reading the task can still run it after a resume. Only a stop after consumption ends the reply watch. Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
7de3fdc405 |
feat(acp): show OpenCode and Antigravity questions in HAPI and return the answer (#2309)
* feat(acp): opt-in form elicitation capability advertisement * feat(acp): route elicitation/create forms to a registered handler * feat(opencode): map question forms to AskUserQuestion input and back * feat(opencode): queue question forms as AskUserQuestion requests without auto-answering * feat(opencode): advertise form elicitation for OpenCode v2 * feat(opencode): present the question tool call as AskUserQuestion * feat(opencode): cancel pending question forms on abort, turn end, archive and exit * test(opencode): cover the unshown question result surfacing * feat(acp): let a form elicitation be declined A form elicitation could only be accepted or cancelled. ACP also has decline, the user refusing to answer, and agents may record it differently from a cancel: Antigravity records a declined question as "User Skipped". FormElicitationResponse now includes it, and the backend passes it back to the agent unchanged. * feat(acp): let the ACP permission handler ask the user a question An agent's question (Antigravity's ask_question) is not a permission request: it needs the user's answers, and it must never be answered automatically. askUser() shows it as a pending request with the given tool name and input, whatever the permission mode, and resolves with the user's decision and answers. cancelAll() resolves an open question as aborted, and an open question counts as a pending request, so callers that wait for approvals also wait for it. onUserWait now covers these waits too and no longer takes the request. isUsed() tells whether an id is open or was already shown, since clients hide a pending request whose id was completed before. * feat(agy): answer agy's questions in the question card On agy acp, agy's ask_question used to arrive as a generic tool card and plain text. The turn ended, and whatever the user typed next became the answer. agy now gets form elicitation advertised, so it asks through elicitation/create and keeps the turn open. The launcher takes these forms through the backend's shared form elicitation handler, the same one OpenCode uses. - The question is shown as the AskUserQuestion card on agy's own tool call, with the options as choices, multi-select and an Other field. - The user's choice goes back as agy's answer: the chosen option values, plus free text under qN_other only when the user typed some, so agy records exactly the chosen label. - Denying declines the question, which agy records as "User Skipped". Stop and session end cancel it. - No permission mode answers a question, always-proceed included. - Steer is refused while a question is open. - An approval that carries no usable answer declines instead of sending an empty answer. - A question that arrives after Stop is cancelled. * fix(opencode): decline question forms that arrive after Stop cancelAll only swept requests that already existed, so a form delivered afterwards was queued as a card whose promise never settled. Close the gate synchronously in cancelAll and reopen it when the next prompt begins, matching the aborted-turn guard of the agy handler. * feat(web): let the question card be skipped Add a Skip button, also bound to Esc inside the card, that denies the pending question through the existing deny API and clears the draft like Submit does. A deny already becomes a decline for agy and a cancel for OpenCode, so the backend is unchanged. * fix(agy): decline questions that arrive after the turn has ended * fix(web): keep typed text when Esc is pressed in the question card's text field * fix(question): hide Other on question forms that do not allow free text Forms without qN_custom (OpenCode) or qN_other (agy) take no typed answer, yet the card always offered Other, and a typed answer was dropped so the result became a cancel. Carry an allowFreeText flag through the tool-call input and the synthesized question input, and hide Other on the card when it is false. Inputs without the flag keep showing Other. |
||
|
|
1feac0a1be | feat(pi): expose peer session MCP tools (#2312) | ||
|
|
38b6540bed |
feat(agy): show Antigravity's tool calls as the canonical tool cards (#2330)
* docs(agy): say request-review follows agy's toolPermission setting On agy acp, HAPI's request-review is agy's default mode, which asks only as agy's own toolPermission setting says. With toolPermission set to always-proceed, agy runs commands and edits without asking, so HAPI shows no approval prompts, and HAPI cannot override that per session. The guide now says so, and says what acceptEdits and plan do on agy. It also notes that always-proceed approves a request a PreToolUse hook marks force_ask: agy sends it as an ordinary approval request, with nothing that says it came from a hook. * feat(acp): carry the agent's own tool name and args on tool calls Some ACP agents send their own tool name and args next to the standard title, kind and rawInput (agy: name, args). Pass them through as nativeName and nativeArgs so a launcher can pick a card by the real tool instead of a free-text title. Agents that send no name are unaffected. * feat(agy): show agy ACP tool calls as the canonical tool cards Map agy's own tool names to the cards the other flavors use: run_command to Bash (with a clean stdout result), read_file to Read, edit_file to an Edit diff, write_file to Write, search_web to WebSearch, invoke_subagent to Task and call_mcp_tool to the mcp card. A write_file artifact (plan or task list) is shown as a plan instead of a hidden brain-directory path. A command agy moves to the background gets no further update after end_turn, so its card spun until the next message. Show it as running in the background at end_turn; the real result replaces that when agy reports it in a later prompt's stream. |