Skip to content

feat(gateway): add pinned-session mode and relay client requests in both modes - #363

Open
danielkov wants to merge 19 commits into
mainfrom
feat/gateway-pinned-session
Open

danielkov wants to merge 19 commits into
mainfrom
feat/gateway-pinned-session

Conversation

@danielkov

@danielkov danielkov commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds kit gateway --pinned-session <id>: one gateway process serves one session to many ACP-over-HTTP clients at the same time. The gateway now also relays agent-to-client requests and supports replay cursors in both modes, so pinned mode differs from the default mode only in what many attachments require.

Motivation

A gateway session has one controller: a second attach replaces the first and withdraws its held prompts, and updates reach one client. Hosting one Kit process per conversation needs several clients on one session: a UI, a short-lived deliverer that submits a prompt and leaves, and an operator, with an authenticating proxy in front.

The default mode also refused agent-to-client requests such as ask_user and offered replay only from the start. Neither limit had a protocol reason. Lifting them for both modes keeps the pinned-only surface small.

Impact

Both modes:

  • Agent-to-client requests are relayed. Ask-user (elicitation/create) is offered to attached clients whose own initialize declared capabilities.elicitation.form; permission requests go to every attached client. The first well-formed answer wins and the other clients receive a cancellation. With no eligible client attached, the child gets -32601 at once, as before.
  • A pending request survives a reconnect. It is re-offered to a client that attaches later, and expires after --client-request-timeout (default 5m). Form content is validated by the child, not the gateway.
  • Capabilities are forwarded, not blanked. Default mode forwards the connecting client's declared elicitation.form and nothing else. A client that declares {} sees no change and is never sent a request.
  • Replay cursors. {"type":"_kit_current_turn"} and {"type":"_kit_message", ...} join {"type":"start"}. A current-turn replay that no longer fits is trimmed and flagged with _meta["kit/gateway"].replayTruncated.
  • kit/subagent/steer is accepted as a session-scoped passthrough.
  • SSE keep-alive. Streams carry a comment every 15 seconds while idle, so a proxy that closes silent streams does not cut a quiet turn.

Pinned mode only:

  • One session. session/new and session/resume both attach to the pinned session; any other session id is rejected. session/close detaches the caller and does not end the session. The session is bound to the approved project that already holds its transcript.
  • Many attachments. A new attachment never replaces another. Every attachment receives every session/update through its own bounded queue; one that overflows is dropped alone. Replies go to the sender.
  • Held prompts survive a detach. A deliverer may disconnect before insertion. A retry with the same idempotencyKey takes over the orphaned entry and is not forwarded to the child again. An explicit $/cancel_request withdraws every held attempt that shares the key.
  • Defaults and limits. No replayFrom means no history. elicitation.form is always advertised to the child, because the first client to attach may be a headless one. 32 pending requests per attachment, 128 shared.

Technical details

  • Both modes use one attachment map, one send path and one relay implementation. Default mode holds at most one attachment and keeps its replace, lease and withdrawal policy.
  • Withdrawing one waiter in agentkit-acp cancels its whole idempotency group, so pinned mode keeps orphaned prompts and re-parents them on retry instead of withdrawing them.
  • All attachments in pinned mode share the session, including its configuration and MCP servers. The proxy in front decides who may attach. A client or the proxy must send DELETE when a client disconnects; the gateway does not detect a dropped connection.
  • Two default-mode error details changed: an unsupported replayFrom type now returns -32602, and a response-shaped frame from a client is no longer answered with an error.

Not covered

  • session/fork and session/delete through the gateway. They need coordination with the gateway's session registry.
  • The TUI through the gateway with a relayed ask_user, and the TUI against a pinned gateway, were not exercised end to end.
  • Transport-level resume with Last-Event-ID. It needs per-stream event ids and a bounded replay buffer in agentkit-acp-http.
  • After a truncated replay the first assistant message may be a partial tail; the result flags truncation but not which message.

…handling

Addresses review defects and simplifies pinned-session gateway implementation:
- Default absent/null replayFrom to ReplayMode::None for both session/new and session/resume in pinned mode (including cold restore over large transcripts).
- Isolate orphaned held prompts from the shared 128 active pending cap (bounded separately at 256) and enforce a 32 per-attachment cap after verifying agentkit-acp withdrawal cancels the entire idempotency group.
- Truncate _kit_current_turn gracefully when the turn start is evicted, marking result._meta["kit/gateway"].replayTruncated = true.
- Reap expired pinned attachments and leaked startup drivers on the actor deadline timer and bound parked cold-startup joiners.
- Restrict unsupported-method target declines to -32601 only, buffer winning relayed client replies across child-stdin backpressure, and cancel pending relayed requests on child exit.
- Fix session/list cwd filtering and foreign sessionId checks, update docs, deduplicate gateway actor paths, and add regression and real-child integration tests.
… reaping

Addresses second review of pinned-session gateway mode:
- Budget pending relayed requests and existing queued events/bytes inside _kit_current_turn replay trimming so joining with a full journal and pending relay succeeds.
- Record idempotencyKey on Pending and re-parent matching orphaned held session/prompt entries in place without forwarding duplicate attempts to the child.
- Run pinned attachment reaping only on the actor deadline timer arm after draining ready commands so a paused process does not reap an attachment with a queued Poll.
- Track detached relay targets so a -32601 from the last present target does not prematurely decline a request while another target is mid-reload.
- Deduplicate Attachment::poll, resident MCP-server conflict checks, supported ACP method checks, and startup driver/waiter delivery in output().
- Restore default-mode sentence in docs/user/gateway.md verbatim to main and clarify group cancellation, reaper semantics, child PendingPrompts caps, re-parenting, and mid-message truncation in docs/reference/gateway-protocol.md.
…hans, and deflake eviction test

Addresses final review items for pinned-session gateway mode:
- Deflake pinned_session_new_without_replay_from_defaults_to_none_and_survives_eviction by filling the journal across 6 client-acknowledged 1.6 MiB rounds instead of a single 10 MiB burst that could overflow c1 before polling.
- Guard re-parenting against cancelled orphans (both withdrawal_pending and already-enqueued cancellations by clearing idempotency_key on cancel).
- Reserve startup headroom for bounded pending relayed requests in start replay so a complete full journal with a pending relay succeeds and replay_unavailable is returned only when the history itself cannot be replayed in full.
- Update docs/reference/gateway-protocol.md to document mandatory DELETE on client disconnect (no TCP-drop reaping) and that re-parented retries reuse the original held prompt body.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 8 files

Shadow auto-approve: would not auto-approve because issues were found.
This PR changes concurrency-sensitive code such as locks, queues, or retries. Ultrareviews find 2.4x more serious bugs than standard reviews. Comment @cubic-dev-ai ultrareview to run one.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread tests/gateway.rs Resolved
Comment thread docs/user/gateway.md Resolved

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pinned mode can create a second transcript under the pinned ID and reattach a retry to a cancelled prompt. Relay handling can accept answers after the deadline, discard supported extension replies, commit invalid results, or stop the shared child on writer saturation. Pending relays can also consume the queue headroom needed to deliver a full replay.

Took 26 min

Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 7 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/gateway/http_server.rs Resolved
Comment thread src/gateway/pinned_tests.rs Resolved
Comment thread docs/reference/gateway-protocol.md Resolved

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default-mode relay IDs can collide across sessions on one connection, routing an answer to the wrong session. Default mode also discards the response route before validation, so a rejected answer prevents the same controller from submitting a correction. Current-turn replay can reject startup when an oversized update precedes an otherwise replayable tail. All seven prior findings remain active.

Took 17 min

Comment thread src/gateway/http_server.rs Resolved
Comment thread src/gateway/http_server.rs Resolved
Comment thread src/gateway.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 5 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/gateway/pinned_tests.rs Resolved

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A child exit can drop a queued relay cancellation. Pinned-session startup can falsely report conflicting owners for a legacy transcript or create a new session in the first approved project when cwd is omitted. Three prior findings remain active: invalid form choices can win relay arbitration, relay IDs can collide across actors on a multiplexed connection, and an oversized interior replay frame can block reconnection.

Took 24 min

Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway/http_server.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 6 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread docs/reference/gateway-protocol.md Resolved
Comment thread src/gateway/tests.rs Resolved
@danielkov danielkov changed the title feat(gateway): add pinned-session mode with many attachments feat(gateway): add pinned-session mode and relay client requests in both modes Nov 29, 2026

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three new findings: an oversized relay can close the entire HTTP connection, a null relay result is mistaken for a request, and a capable controller cannot enable forms in a resident session started by a headless controller. Four prior findings still apply: oversized interior updates can block current-turn replay, queued relay cancellations can be lost on child exit, a single legacy transcript can be counted as multiple workspace owners, and first pinned startup can choose a workspace without an explicit cwd.

Took 12 min

Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would not auto-approve. Auto-approval blocked by 6 unresolved issues from previous reviews.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default controller replacement drops outstanding agent-to-client requests from the old HTTP connection without cancelling them there. Seven existing findings remain active: replay truncation, child-exit cancellation draining, legacy transcript ownership, implicit workspace selection on first pinned creation, oversized relay frames, null response routing, and form capability after takeover.

Took 17 min

Comment thread src/gateway/http_server.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 6 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/gateway/pinned_tests.rs Resolved

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oversized live updates can terminate multiplexed HTTP connections, startup relay reservations can hold roughly 64 MiB of copied payload per joining attachment outside its live queue budget, and the protocol reference promises a warning for client-reported errors that the gateway does not log. Two existing findings remain active: a capable controller cannot enable forms on a resident child initialized by a headless client, and a displaced controller does not receive cancellation for its unanswered relays.

Took 11 min

Comment thread src/gateway.rs Resolved
Comment thread src/gateway.rs Resolved
Comment thread docs/reference/gateway-protocol.md Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds a major gateway feature: pinned multi-client sessions, relayed agent-to-client requests, new replay cursors, and SSE keep-alives. It changes session access and the public protocol contract, so it needs human sign-off.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Three existing findings remain valid: oversized live updates can terminate a multiplexed HTTP connection; startup relay copies can retain roughly 64 MiB of serialized payload per joining attachment outside its live queue budget; and the protocol reference incorrectly promises an HTTP warning for non--32601 client error responses. No new findings.

Took 5 min 56 sec

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds pinned-session multi-client mode, relayed agent-to-client requests, new replay cursors, and SSE keep-alives, plus session-ownership changes. This changes the gateway trust boundary and public protocol contract, so it needs human sign-off.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new per-frame guard can report an oversized default-mode response as a controller takeover, causing the bundled client to stop instead of recovering. In pinned mode, one oversized update can disconnect every live attachment even when none of their queues is full; the reference does not describe that case.

Took 7 min 16 sec

Comment thread src/gateway.rs Resolved
Comment thread docs/reference/gateway-protocol.md Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 6 files (changes from recent commits).

Confidence score: 3/5

  • In src/gateway.rs, the oversized-response fallback can still exceed MAX_HTTP_FRAME when the request ID is unbounded, causing push_to_attachment to retire the attachment instead of returning the bounded error. Bound the request ID in the fallback.
  • In src/gateway.rs, queue admission can mask an oversized update as queue_overflow when the attachment is full. Check the frame limit before queue admission so callers get frame_too_large.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/gateway.rs">

<violation number="1">
P2: Queue admission runs before frame-size admission, so an oversized update on a full attachment is reported as `queue_overflow` instead of `frame_too_large`. Check the frame limit first to preserve the independent per-frame contract.</violation>

<violation number="2">
P2: The oversized-response fallback copies an unbounded request ID, so it can exceed `MAX_HTTP_FRAME` itself. `push_to_attachment` then retires the attachment instead of returning the documented bounded error; enforce an ID budget before accepting the request or handle this impossible-to-fit response before enqueueing it.</violation>
</file>

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An oversized live update can still masquerade as a controller takeover when the attachment has little queue headroom. When the gateway does report frame_too_large, the bundled client's full-replay recovery can hit the same frame again and lose the original failure reason.

Took 7 min 57 sec

Comment thread src/gateway.rs Resolved
Comment thread src/gateway/http_client/recovery.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 5 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds pinned-session multi-client mode, relayed agent-to-client requests, new replay cursors, and SSE keep-alives. The gateway trust boundary and public protocol contract are the decisive factors.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The oversized-response fallback can itself exceed the frame limit and retire the originating attachment, discarding queued events instead of failing only the request.

Took 6 min 10 sec

Comment thread src/gateway.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds pinned-session multi-client mode, relayed agent-to-client requests, new replay cursors, and SSE keep-alives; the shared trust boundary and new public protocol contract are the decisive factors.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new request-ID guard closes the entire ACP HTTP connection even when a correlated rejection would fit, disrupting unrelated session attachments and pending replies.

Took 14 min

Comment thread src/gateway/http_server.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 3 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds pinned-session multi-client mode, relayed agent-to-client requests, new replay cursors, and SSE keep-alives; the new shared trust boundary, expanded interactive-request exposure, and public protocol changes are the decisive factors.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A request-ID rejection that the HTTP server can deliver without closing the connection still shuts down the bundled stdio bridge and marks unrelated in-flight calls as outcome_unknown.

Took 5 min 25 sec

Comment thread src/gateway.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 4 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds pinned-session multi-client gateway mode, relays agent-to-client requests in both modes, and adds replay cursors/SSE keep-alives plus recovery/error changes; the new shared trust boundary and expanded interactive-request exposure require human sign-off.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An over-budget request ID can wedge initialization or terminate the first explicit attachment even after the gateway returns a non-terminal rejection.

Took 5 min 37 sec

Comment thread src/gateway.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 4 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

During reconnect backoff the bundled bridge bypasses request-ID validation, making the rejection depend on when the request is read.

Took 6 min 6 sec

Comment thread src/gateway/http_client/recovery.rs Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Shadow auto-approve: would not auto-approve because issues were found.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread src/gateway/http_client/recovery.rs Resolved
kit-code-agent[bot]
kit-code-agent Bot previously approved these changes Nov 29, 2026

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found. The changes look good to merge.

Took 7 min 2 sec

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Shadow auto-approve: would require human review. Adds pinned-session multi-client gateway mode and relays agent-to-client requests in both modes, plus new replay cursors, steer passthrough, and SSE keep-alives; the expanded shared trust boundary and interactive-request exposure need human sign-off.

View guided diff | Turn on auto-fix | Re-trigger cubic

@kit-code-agent kit-code-agent Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found. The changes look good to merge.

Took 6 min 48 sec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant