Skip to content

feat(client-py): cover the gateway chat, approval and ws surface - #14866

Merged
buluoray merged 2 commits into
mainfrom
feat/client-py-port
Sep 29, 2026
Merged

buluoray merged 2 commits into
mainfrom
feat/client-py-port

Conversation

@buluoray

@buluoray buluoray commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Python code outside the gateway can drive chat, approvals, models, config, STT and live events through kirocrew-client instead of hand-rolling HTTP and WebSocket calls.

packages/kirocrew-client-py covers only part of the Gateway API, and the API reference already lists each gap as "call the endpoint directly". Several of the wrappers it does ship are wrong:

  • Auth never reaches the Gateway. The token goes out as a bare mc_token cookie. The Gateway reads only mc_token_<port> (token_auth._cookie_port_from_host), so a token-authenticated request carries no credential.
  • A 401 refresh spends a retry. With max_retries=0, a successful refresh ends in Request failed.
  • Wrong shapes or routes. list_subagents / list_crons / list_lessons expect bare lists where the Gateway returns {agents} / {jobs} / {lessons}. update_cron sends PUT to a PATCH route. list_mcp_servers calls an unregistered path. memory_search sends top_k where the route reads limit.
  • No WebSocket client and no streaming. Any consumer that needs live events or a streamed turn has to write its own.

Why it matters

A second in-repo consumer is about to need exactly this surface: the ACP server in #7415 carries its own hand-rolled HTTP/WS/SSE client inside acp_server/http_backend.py. A client that authenticates correctly and covers chat, approvals and events lets that code, and any app backend, depend on one tested client instead of each writing its own.

Not a goal

  • Publishing kirocrew-client to PyPI, or making the main kirocrew package depend on it.
  • Porting GatewayManager, AppLifecycle, manifest or proxy-auth helpers.
  • Wrappers that write into the data home directly (agent configs, skills, mcp.json). Those bypass the Gateway, so they stay "call the endpoint".
  • Any Gateway-side change. Every wrapper targets a route that already exists on main.
  • Adding the endpoints feat(acp): add gateway-backed ACP server #7415 introduces (question cards, per-session MCP, turn-origin header).

What changed (motivation → approach → change)

  • Approach. Each wrapper was written against the route it calls on main: the method, path, query and body keys the handler reads, and the shape it returns. It was not written from the old wrapper or from memory. Where a route accepts a narrower vocabulary than the wrapper exposes, the client validates before sending anything. Examples: the four /api/config/<key> routes (GATEWAY_CONFIG_KEYS) and the approval actions.
  • Fixes in client.py. Cookie keyed by the dialled port (_auth_cookie_name). The gateway keys that cookie by the Host port it receives, falling back to its own listen port, so a deployment whose proxy strips or rewrites Host sets cookie_port to the gateway's listen port (used for HTTP and the WebSocket). The refresh no longer consumes an attempt. _request retries a 5xx or transport error only for GET / PUT / DELETE; POST and PATCH are retried only on 429 and after the single auth refresh, both of which mean the request was refused rather than applied (a blind re-send of edit-resend would truncate and regenerate history again). The backoff saturates instead of overflowing after a very long outage. Wrapped-list reads go through _list_field, which raises SERVER_ERROR when the envelope key is missing instead of returning []. update_cron uses PATCH. list_mcp_servers calls GET /api/mcp. memory_search sends limit and reads results.
  • New wrappers. get_slot_history, stop_slot, edit_resend, stream_chat (an async iterator over the SSE frames that ends at [DONE]), list_notifications / ack_notification(ts) / ack_all_notifications, list_approvals / resolve_approval / set_approval_mode, list_models / set_slot_model, get_gateway_config / set_gateway_config, and transcribe (multipart audio field, the only one the route reads).
    • resolve_approval sends approve / reject as approved / rejected on the slot route, because that route turns any action it does not recognise into a rejection. It checks the action against the route's vocabulary (approved, rejected, trust, trust_reads, trust_command, trust_base, yolo) before sending, and takes the pending card's pattern that trust_command / trust_base require. set_approval_mode likewise accepts only normal, trust_reads, trust, yolo, and refuses a slot_id with yolo, which the gateway applies to every slot.
    • stream_chat and transcribe refresh the token and re-send once after a 401/403. Nothing else is retried: a re-send of stream_chat could start a second turn. Transport failures on both raise NETWORK_ERROR, like every other method, and so does a stream that ends before [DONE]. When the slot is busy, /api/chat answers with a JSON receipt ({ok, queued} / {ok, steered}) instead of a stream; stream_chat yields that receipt once and ends normally, so a caller does not re-send an already queued turn.
  • ws_client.py. WsClient for /api/ws with typed, slot-scoped and raw listeners (each returns an unsubscribe function) and a saturating backoff reconnect loop. KiroCrewClient.create_ws() wires in the auth cookie and the Origin header /api/ws requires, and refreshes the token before each reconnect when a refresher exists. Caller options (origin, get_headers, on_reconnect) override those defaults. Slot listeners also receive slot_title and session_summary, the two frame types that carry the slot as data["key"] (every other slot-bound frame uses data["slot"]).
  • Path escaping. Every caller-supplied path parameter (slot, request, agent, cron job, task, MCP server, app) is path-escaped.
  • Route-contract test (main suite). test/test_client_py_route_contract.py derives every (method, path) the client calls from its source and asserts that set equals an explicit inventory, so the extraction cannot silently return nothing. It then checks each route against the real router that register_all builds. A gateway route rename turns the main suite red, not just the stub. It also checks that the handlers still carry the envelope keys the client reads (agents, jobs, lessons, results) and every value in the client's approval-action and approval-mode vocabularies, and that every request-making client method yields an extractable route, so a wrapper cannot slip past the router check.
  • CI (second commit). .github/workflows/client-py.yml runs the package tests on Python 3.9 (the package floor) and 3.12. It is path-scoped to the package and removes setup-python's problem matcher before pytest. Until now nothing ran these tests: check_testpaths_coverage.py exempts nested distributions on the understanding that they run on their own.
  • Docs. The method table in docs/app-kit/api-reference.md and the note in getting-started.md are updated to match.

Backwards compatibility

Compatible for anything that works today, with one deliberate narrowing: POST and PATCH are no longer retried after a 5xx or a transport error, because the change may already have been applied. A caller that relied on that retry now gets the error and decides for itself. list_subagents, list_crons, list_lessons, list_mcp_servers and memory_search returned [] against the real Gateway, and update_cron got a 405. They now return the Gateway's data. The auth cookie change only affects requests that carried a token, and those were not authenticated before. _list_field still accepts a bare list. It raises only for a dict without the expected key, a shape no current handler returns (checked: api_spawn_list, api_crons, api_lessons, api_memory_episodic_search, and every branch of api_models). resolve_approval without a slot_id is new behavior and has no existing callers.

Tests

packages/kirocrew-client-py/tests/test_gateway_contract.py runs every wrapper against a stub aiohttp Gateway that records method, raw path, query, body and cookie. It answers with the real routes' shapes, and its /api/ws rejects a missing or wrong Origin the way origin.py does. It pins:

  • The cookie name per port and scheme, and that the token actually goes out under it.
  • A refresh with max_retries=0 returns the refreshed answer. stream_chat and transcribe each recover from one 401.
  • Envelope unwrapping, and SERVER_ERROR for a dict missing its key. PATCH for update_cron, and limit / results for memory_search.
  • History, stop (with force), edit-resend bodies, and that an id containing / and ? is escaped.
  • stream_chat yields chunks until [DONE], raises on an error status before yielding, and raises NETWORK_ERROR for a refused connection or a mid-stream drop. transcribe does the same for a refused connection.
  • POST answered 503 is sent once; GET 503 then 200 is retried; POST 429 then 200 is retried. Backoff at attempt 5000 returns the cap. A stream closing without [DONE] raises NETWORK_ERROR, while a JSON queued or steered receipt is yielded once. yolo with a slot raises and sends nothing. A newly escaped id containing / stays one path segment.
  • Notification ack routes. Approval actions on both routes (approve → approved on the slot route), and the pattern requirement for trust_command / trust_base. Rejected actions and config keys send no request.
  • The multipart field name for transcribe.
  • WsClient connects with the auth cookie and Origin, dispatches typed and slot events, and derives ws:// / wss:// from the base URL.

test/test_client_py_route_contract.py (main suite) is described under What changed.

Mutation-checked: reverting the cookie name, the refresh fix, the envelope unwrap or the missing-key raise, the path escaping, the WebSocket Origin, the 401 replays, the slot action mapping, the pattern check, or the network-error translation each turns at least one test red. Renaming a real gateway route turns the route-contract test red. The package suite passes on Python 3.9 and 3.12 (55 each). The route-contract, CI-annotation and workflow-lint suites pass.

Manual verification

N/A. The wire contract is covered by the stub-Gateway tests, whose route shapes were read from the handlers on main, and route existence is checked against the real router. A live smoke against a running gateway is not included.

Related Issues

Groundwork for the split proposed on #7415.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

@buluoray
buluoray requested a review from a team as a code owner September 28, 2026 23:38
@buluoray
buluoray requested a review from kyleseaman September 28, 2026 23:38
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 28, 2026
@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — ✅ PASS

Design-level review of 7577e277e4e19c26c1c8b7bb1333117181a8f855 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: PASS

Verify the new path-filtered client-py.yml is not marked a required check — path-scoped required checks hang PRs that never trigger them.

Suggestions

[DESIGN-REVIEWED] 7577e27

Description read

[DESCRIPTION-READ] 565fe513f720ef5aed551b2e2258d52f154113761964e29cbdc0ef710b8c6370

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 7577e277e4e19c26c1c8b7bb1333117181a8f855 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 7577e27

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 7577e277e4e19c26c1c8b7bb1333117181a8f855: <one-sentence reason>

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — ✅ PASS

Premise-level review of 7577e277e4e19c26c1c8b7bb1333117181a8f855 — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: PASS

The addition's only named consumer, #7415, is prospective — nothing in-repo calls any new wrapper yet; confirm that PR actually adopts this client.

What this change ships

Inventory (10 items) — 10 justified

Intent: make the existing (unpublished) Python client actually work against the Gateway and cover chat/approvals/events, ahead of #7415 adopting it — an ADDITION carrying real fixes.

  1. Token auth now reaches the Gateway (port-scoped mc_token_<port> cookie) — justified
  2. A 401 refresh no longer consumes the only retry attempt — justified
  3. Broken wrappers return real data: list envelopes, PATCH cron, GET /api/mcp, memory limit — justified
  4. POST/PATCH no longer replayed after 5xx/transport errors (declared narrowing) — justified
  5. New chat surface: stream_chat, get_slot_history, stop_slot, edit_resend — justified
  6. New notifications, approvals, models, config and transcribe wrappers with pre-send vocabulary validation — justified
  7. WsClient / create_ws() live-event client with reconnect and token refresh — justified
  8. cookie_port constructor option for proxy deployments that rewrite Host — justified
  9. Main-suite route-contract test pins client calls to the real router — justified
  10. CI workflow now runs the package's tests (nothing did before) — justified

[FIRST-PRINCIPLES-REVIEWED] 7577e27

Description read

[DESCRIPTION-READ] 08e9a77402f345cb9f441c1bfdd2c8235cb6d4e267769bababa6d84e39cde259

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5 Review — ✅ no blocking findings

Reviewed 7577e277e4e19c26c1c8b7bb1333117181a8f855 — this comment is updated in place on each push.

Review details

Nothing blocks; a server-supplied Retry-After is slept on with no ceiling.

FINDING — packages/kirocrew-client-py/kirocrew_client/client.py:318 — a 429 carrying Retry-After: 3600 from the gateway or any intermediary reaches delay = float(retry_after) uncapped and parks the caller's coroutine for an hour inside a single await client.get_status(), while the sibling branch one line below is bounded by _MAX_BACKOFF; the constructor's timeout bounds each request but not this sleep → Fix: delay = min(max(float(retry_after), 0.0), _MAX_BACKOFF) in the same expression.

[OPUS-REVIEWED] 7577e27

Verdict parsed from the review's SHA-scoped output markers for commit 7577e277e4e19c26c1c8b7bb1333117181a8f855.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 7577e277e4e19c26c1c8b7bb1333117181a8f855: <one-sentence reason>

@buluoray

Copy link
Copy Markdown
Contributor Author

Review dispositions for 94b54d1071 (supersedes 24425ec386 and 81307b7aac).

GPT 5.6 — all four findings fixed. Each mechanism was checked against the gateway source before any change.

  • BLOCKING, slot approval with the default action silently rejects. api_chat_slot_approve turns any action other than approved / approved_trust_reads into rejected and still returns {"ok": true}. On the slot path, resolve_approval now sends approve as approved and reject as rejected; the global path keeps its opposite mapping. There is a stub test for each spelling, and reverting the mapping turns 3 tests red.
  • WebSocket sends no Origin. Real, and broader than reported: _check_ws_origin calls check_origin(require=True), so a handshake without Origin is refused from any non-loopback peer. create_ws now sends the HTTP(S) origin of base_url. The stub's /api/ws rejects a missing or wrong Origin the same way origin.py does.
  • stream_chat / transcribe skip the token refresh. Both now refresh once and re-send once after a 401/403. For stream_chat this is safe because a refused request never started a turn. No other stream failure is retried.
  • trust_command / trust_base need a pattern. The handler requires body["pattern"] to match the pending card. There is a new keyword-only pattern=, and a missing one is refused before any request goes out.

Design Review — watch cleared. test/test_client_py_route_contract.py (main suite) extracts every (method, path) the client calls from its source. It asserts that set equals an explicit inventory, so extraction cannot silently return nothing, then checks each route against the real router built by register_all. Renaming /api/status turns it red. client-py.yml also triggers on src/kiro_crew/dashboard/routes/**.

First Principles — kept as shipped, with reasoning. It is true that the new wrappers have no in-repo caller yet. They are what this PR is for: the Goal is Python code driving chat, approvals and events through one client, and #7415's adapter already hand-rolls exactly this surface. The package is source-only and unpublished, so nothing here is a one-way door. The new route-contract test also answers the "kept in sync with routes by hand" cost: drift now fails CI instead of rotting silently.

test_pid_reader_ratchet (Backend Tests 3.12 shard 4, Windows shard 4): inherited from main. The test scans only src/kiro_crew, and this PR's diff has no file under src/, so it cannot add or remove a site the ratchet counts. It fails the same way locally. The Coverage Gate red on 81307b7aac is its fail-closed follow-on (backend-test=failure), not a coverage drop. I'll rebase once main fixes it.

Also fixed on the way, from CI: client-py.yml now removes setup-python's python problem matcher before pytest, which test_ci_failure_annotations requires of every pytest job.

Repair provenance: the four earlier GPT findings and the drift guard were repaired by a GPT 5.6 delegate. The slot-approval finding was repaired by a follow-up that ran on Claude Opus 5.5 rather than the GPT family. I (the parent) verified every change: the package suite passes on Python 3.9 and 3.12 (51 each), the route-contract, annotation and checkout-credential tests pass, flake8 and black are clean, and each fix was mutation-checked red, then green.

@buluoray

Copy link
Copy Markdown
Contributor Author

Review dispositions for df30956ea4 (round 3, supersedes the comment for 94b54d1071).

GPT 5.6 — BLOCKING finding fixed. The finding: stream_chat and transcribe let raw aiohttp / asyncio.TimeoutError escape. Both now raise KiroCrewError(NETWORK_ERROR) (chained from exc), including for a drop mid-stream, and no replay was added beyond the existing single auth refresh. Tests cover a refused connection for each and a mid-stream disconnect. Swapping the caught exception types for an unrelated one turns 3 tests red.

Design Review — watch fixed. _list_field now raises SERVER_ERROR when a dict response lacks the expected envelope key, so a renamed key surfaces as an error instead of []. Before the change I checked every success shape it reads: api_spawn_list returns {agents}, api_crons returns {jobs, server_tz}, api_lessons returns {lessons, …} and api_memory_episodic_search returns {results}; api_models returns a bare list on the Kiro, Claude and Codex branches. None of these now raise.

First Principles:

  • routes/** path filter: agreed and removed. The package tests hit a stub, and route drift is the job of the main-suite test/test_client_py_route_contract.py.
  • Route-contract test undeclared: the description's What changed and Tests sections now describe it.
  • Zero consumers for the new wrappers: same answer as last round, and left as-is pending the author's scope call. The wrappers are the PR's stated Goal, the package is source-only and unpublished, and the route-contract test is what keeps them from rotting.

Still red and inherited from main: test_pid_reader_ratchet (Backend Tests 3.12 shard 4, Windows shard 4), plus Coverage Gate failing closed on it. This PR's diff touches nothing under src/.

Repair provenance: a GPT 5.6 delegate (served model gpt-5.6-sol) made the fixes. I removed one extra test it added, which pinned the absence of the path filter in workflow YAML and was not asked for. Parent verification: the package suite passes on Python 3.9 and 3.12 (55 each), the route-contract and CI-annotation tests pass, flake8 is clean, and I re-ran the network-error mutation myself.

@buluoray

Copy link
Copy Markdown
Contributor Author

Review dispositions for 5ab597a1ac (round 4, supersedes the comment for df30956ea4).

This round's GPT findings were the fourth in a row on these paths. So instead of patching the four quoted lines, every instance of each class was fixed in one pass:

  • Backoff overflow. Both compute_reconnect_delay and _compute_backoff now return the cap before the exponent can overflow. Tested at attempt 5000.
  • Retried non-idempotent requests (edit-resend and the rest). The fix is in _request itself. A 5xx or transport error is retried only for GET / PUT / DELETE. POST and PATCH are retried only on 429 and after the single auth refresh, since both mean the request was refused rather than applied. This is a deliberate narrowing and is now stated under Backwards compatibility. Tests: POST 503 is sent once, GET 503→200 is retried, POST 429→200 is retried. Removing the guard turns 2 tests red.
  • Unvalidated enum values. Slot approval actions are checked against the branches api_chat_slot_approve handles (approved, rejected, trust, trust_reads, trust_command, trust_base, yolo). Anything else resolves to rejected and consumes the approval. Approval modes are checked against api_chat_mode's (normal, trust_reads, trust, yolo). An invalid value sends nothing.
  • Stream EOF read as completion. stream_chat tracks [DONE] and raises NETWORK_ERROR if the body ends first.

First Principles:

  • Unescaped ids: every caller-supplied path parameter is now escaped, not only slot and request ids. The route-contract test's inventory is unchanged.
  • on_raw_message: removed, together with its callback type and the docs row. The docs-lint baseline entry that flagged it as a dead identifier is gone too.
  • Zero consumers: unchanged, as before. This is a scope call for the author and is not being absorbed here.

GPT's non-blocking note (the portless-Host cookie name behind a reverse proxy) is deferred. It is the edge case where the proxy preserves a Host with no port while the gateway listens on a non-default one. Fixing it means choosing how the client learns the gateway's listen port, which is new surface outside this PR's goal.

CI: test_history_index_worker::test_a_contended_write_waits_instead_of_failing (Windows shard 1, "the write did not actually contend") is a timing test in a module this PR does not touch; I'll re-run it. test_pid_reader_ratchet is still inherited from main.

Repair provenance: a GPT 5.6 delegate (gpt-5.6-sol) made the changes but hit its turn limit before it could report, so I verified the result directly. The package suite passes on 3.9 and 3.12 (65 each), the route-contract and CI-annotation tests pass, flake8 and docs-lint are clean, I mutation-checked the retry guard, and I compared both vocabularies against the handler source.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Sep 29, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 29, 2026
@buluoray

Copy link
Copy Markdown
Contributor Author

Review dispositions for e4b9ceb5e8 (round 5, supersedes the comment for 5ab597a1ac). Scope is kept as-is by the author's decision.

GPT 5.6 — both blocking findings fixed. Both were checked against chat_handlers.py before the change.

  • Queued chat reported as a network failure. api_chat answers a busy slot with a JSON 200 instead of an SSE stream:

    • {ok, steered} (:929)
    • {ok, queued} (:933)
    • {ok, queued, queue_id} (:1008, :1072)
    • the orchestrator receipts (:1326, :1353)

    stream_chat now yields a JSON 2xx receipt once and ends normally. [DONE] is still required, and still raises NETWORK_ERROR when missing, but only for text/event-stream answers. There are tests for the queued receipt, the steered receipt, and the existing truncated-SSE case. Reverting the JSON branch turns both receipt tests red.

  • Slot-scoped YOLO is global. Only trust / trust_reads are slot-scoped (_SLOT_SCOPED_TRUST_MODES, :262), so yolo activates the process-wide override. set_approval_mode("yolo", slot_id=...) now raises VALIDATION_ERROR and sends nothing. normal keeps accepting a slot, because its branch revokes trust per slot (:12739-12761). Note that it also clears a global YOLO override (:12628-12638), since that override cannot be revoked for one slot only. Removing the guard turns the regression red.

First Principles (zero consumers): kept by the author's decision. The rebuttal is unchanged.

Still red and inherited from main: test_pid_reader_ratchet, plus Coverage Gate failing closed on it.

Repair provenance: GPT 5.6 delegate (served gpt-5.6-sol). Parent verification: the package suite passes on Python 3.9 and 3.12 (69 each), the route-contract test and flake8 pass, and I re-ran the YOLO-guard mutation myself.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 29, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 29, 2026
@buluoray

Copy link
Copy Markdown
Contributor Author

Review dispositions for 948401c6c8 (round 6, supersedes the comment for e4b9ceb5e8).

GPT 5.6 (blocking): fixed. create_ws now builds its defaults first (origin, get_headers, and the refresh on_reconnect), lets the caller's options override them, and expands once. Before this, passing origin= or get_headers= raised a duplicate-keyword TypeError. Tests cover both overrides. Restoring the double expansion turns 2 tests red.

Design Review, both watch items addressed:

  • Drift beyond (method, path). test/test_client_py_route_contract.py now also checks the real handlers:

    • The envelope keys the client reads are still returned: agents (api_spawn_list), jobs (api_crons), lessons (api_lessons) and results (api_memory_episodic_search).
    • Every value in the client's _SLOT_APPROVAL_ACTIONS and _APPROVAL_MODES still appears in api_chat_slot_approve / api_chat_mode.

    The check reads executable string literals from each handler's source (docstrings excluded). Renaming jobs in api_crons turns it red.

  • Port-less base URL. The docstring overclaimed and is now corrected. The gateway keys the cookie by the Host port, or by its own listen port when Host has none (token_auth._cookie_port_from_host). The client cannot know that port, so a port-less URL is keyed by the scheme default. The docstring and API reference now say that directly: behind a proxy that strips the port, name the port in the base URL. I did not switch to the ?token= credential. The main auth path treats a query token differently from a cookie (from_cookie / use_session_exp), so it is not an equivalent substitute.

First Principles (zero consumers): kept by the author's scope decision.

Inherited from main, not touched by this PR: test_pid_reader_ratchet, plus Coverage Gate failing closed on it.

Repair provenance: GPT 5.6 delegate (served gpt-5.6-sol). I dropped one assertion it added that pinned docstring wording. Parent verification: the package suite passes on Python 3.9 and 3.12 (71 each), the route-contract test passes (7), flake8 and black are clean, and I mutation-checked the kwarg merge and the envelope check.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 29, 2026
The standalone kirocrew-client covered only part of the Gateway API,
and several of the wrappers it did ship called it wrong. The API
reference already documented each gap as "call the endpoint directly".

Auth: the client sent its token as a bare mc_token cookie, which the
Gateway never reads (it reads mc_token_<port>, keyed by the Host port),
so a token-authenticated request carried no credential. A 401 refresh
also spent a retry attempt, so max_retries=0 turned a successful
refresh into "Request failed".

Wrong shapes: list_subagents, list_crons and list_lessons expected a
bare list where the Gateway wraps it in {agents} / {jobs} / {lessons};
update_cron sent PUT to a PATCH route; list_mcp_servers called an
unregistered path; memory_search sent top_k where the route reads
limit, and expected a list where it returns {results}.

New wrappers, each checked against the route it calls: slot history,
stop and edit-resend; stream_chat as an async iterator over the SSE
frames; notifications list / ack / ack-all; approvals list and resolve
(global and slot-scoped); approval mode; models; the four config keys
the Gateway serves; STT transcribe; and a WsClient for /api/ws with
typed and slot-scoped listeners and backoff reconnect.

Slot and request ids are now path-escaped in the new wrappers and in
delete_slot. The API reference and getting-started note are updated to
match.

The WebSocket handshake sends the base URL's Origin, which /api/ws
requires. stream_chat and transcribe refresh and replay once after a
401/403, as _request does. On the slot-scoped approval route
resolve_approval sends approved/rejected (the route turns anything it
does not recognise into a rejection) and takes the pending card's
pattern that trust_command and trust_base require. Transport failures
on those two direct paths raise KiroCrewError(NETWORK_ERROR) like every
other method, and a list wrapper whose envelope key is missing raises
SERVER_ERROR instead of reading as an empty list.

_request no longer retries POST or PATCH on a 5xx or a transport
error, since the change may already have been applied (edit-resend
truncates and regenerates history); those are retried only on 429 and
after the single auth refresh, both refusals. stream_chat raises
NETWORK_ERROR when the stream ends before [DONE]. Slot approval actions
and approval modes are checked against the vocabularies the handlers
accept, because both routes coerce an unknown value. Every
caller-supplied path parameter is escaped, both backoff helpers
saturate instead of overflowing, and the unused WsClient.on_raw_message
is removed.

stream_chat also accepts the JSON receipts /api/chat returns instead
of a stream (a busy slot queues or steers the message), yielding the
receipt once rather than raising, and set_approval_mode refuses a slot
for yolo, which the gateway applies to every slot. create_ws lets a
caller override its origin and header defaults, the port-less base URL
limit of cookie auth is documented, and the route-contract test also
checks the envelope keys and approval vocabularies against the
handlers, and that every request-making method yields an extractable
route. WsClient dispatches slot_title and session_summary, which carry
the slot as data["key"], to slot listeners, and a cookie_port option
names the cookie for deployments whose proxy strips or rewrites Host.

test/test_client_py_route_contract.py derives every (method, path) the
client calls from its source and fails when the real gateway router no
longer registers one, so a gateway-side route change turns the main
suite red instead of only drifting the stub.
The package is a nested distribution, so the repo-wide backend suite
never collects it, and check_testpaths_coverage.py exempts it on the
understanding that it runs on its own. Nothing did. Add a workflow that
runs its tests on the package's Python floor (3.9) and on 3.12.

It removes setup-python's problem matcher before pytest like every
other pytest job here. Gateway route drift is caught by the main suite's
route-contract test, not here: these tests run against a stub.
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 29, 2026
@buluoray

Copy link
Copy Markdown
Contributor Author

Review dispositions for 7577e277e4 (round 7, supersedes the comment for 948401c6c8). First Principles now passes.

GPT 5.6 (blocking), fixed. Slot listeners dropped slot_title and session_summary, because both frames carry the slot as data["key"] (state.py:9323, :9350). I audited every WS frame the dashboard emits: all other slot-bound frames use data["slot"]. member_projection also has a key, but that key names a member, not a slot (websocket_hub.py:570). So the fallback applies only to those two frame types, not to any frame that happens to carry key. New tests: a slot_title frame reaches the matching slot listener and does not reach a listener on another slot. Removing the fallback turns the test red.

Design Review:

  • Proxy that strips or rewrites Host: agreed. The earlier "name the port in the base URL" remedy cannot help, because the gateway keys the cookie by the Host it receives, or by its own listen port when that Host has no port. I added a keyword-only cookie_port option. When set, it names the cookie on both HTTP and the WebSocket handshake. The docstring and API reference now tell proxied deployments to set it to the gateway's listen port. Ignoring the option turns its HTTP/WS test red.
  • Suggestion (unextractable paths): adopted. The route-contract test now also asserts that every request-making KiroCrewClient method yields at least one extracted route. Giving get_system_info a dynamic path turns it red.

Inherited from main, unchanged: test_pid_reader_ratchet, and Coverage Gate fails closed because of it.

Repair provenance: the fix was made by a GPT 5.6 delegate (served gpt-5.6-sol). I verified it separately: the package suite passes on Python 3.9 and 3.12 (73 each), the route-contract test passes (8), and flake8, black and docs-lint are clean. I also mutation-checked the key fallback myself.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Sep 29, 2026
@buluoray
buluoray enabled auto-merge (squash) September 29, 2026 05:31
@buluoray buluoray mentioned this pull request Sep 29, 2026
5 tasks done

@iamwhatever iamwhatever 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.

Reviewed. Token travels only in the Cookie header, never in URLs or error text; the new workflow is contents:read only, no secrets, persist-credentials false, SHA-pinned, pull_request not pull_request_target. Route contract test checks the client's method/path set against the real router. Behaviour matches the description (no POST/PATCH retry after 5xx, refresh does not consume a retry, yolo with slot refused before any request).

Non-blocking notes:

  • client.py:464: an SSE line over aiohttp's buffer limit raises a raw ValueError that _network_errors does not translate; multi-line data: frames are not joined.
  • ws_client.py:108,232: listener keys are f'{slot_id}:{event_type}', so a slot id containing ':' could collide.
  • client.py:741: create_ws skips _check_auth(), so a tokenless remote gateway reconnects forever instead of raising AUTH_REQUIRED.

@buluoray
buluoray merged commit 80f19a8 into main Sep 29, 2026
101 of 107 checks passed
@buluoray
buluoray deleted the feat/client-py-port branch September 29, 2026 06:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

readiness: passed Eligible automated validation passed for the current revision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants