Repository navigation
feat(client-py): cover the gateway chat, approval and ws surface - #14866
Conversation
Design Review (Fable 5) — ✅ PASSDesign-level review of Design-Verdict: PASS Verify the new path-filtered 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 |
GPT 5.6 Review — ✅ no blocking findingsGPT 5.6 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
24425ec to
81307b7
Compare
First Principles Review (Fable 5) — ✅ PASSPremise-level review of 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 shipsInventory (10 items) — 10 justifiedIntent: 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.
[FIRST-PRINCIPLES-REVIEWED] 7577e27 Description read[DESCRIPTION-READ] 08e9a77402f345cb9f441c1bfdd2c8235cb6d4e267769bababa6d84e39cde259 That sha256 names the PR description this verdict read. Recompute it with |
81307b7 to
94b54d1
Compare
Opus 5 Review — ✅ no blocking findingsReviewed Review detailsNothing blocks; a server-supplied FINDING — packages/kirocrew-client-py/kirocrew_client/client.py:318 — a 429 carrying [OPUS-REVIEWED] 7577e27 Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
|
Review dispositions for GPT 5.6 — all four findings fixed. Each mechanism was checked against the gateway source before any change.
Design Review — watch cleared. 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.
Also fixed on the way, from CI: 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. |
94b54d1 to
df30956
Compare
|
Review dispositions for GPT 5.6 — BLOCKING finding fixed. The finding: Design Review — watch fixed. First Principles:
Still red and inherited from Repair provenance: a GPT 5.6 delegate (served model |
df30956 to
5ab597a
Compare
|
Review dispositions for 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:
First Principles:
GPT's non-blocking note (the portless- CI: Repair provenance: a GPT 5.6 delegate ( |
5ab597a to
e4b9ceb
Compare
|
Review dispositions for GPT 5.6 — both blocking findings fixed. Both were checked against
First Principles (zero consumers): kept by the author's decision. The rebuttal is unchanged. Still red and inherited from Repair provenance: GPT 5.6 delegate (served |
e4b9ceb to
948401c
Compare
|
Review dispositions for GPT 5.6 (blocking): fixed. Design Review, both watch items addressed:
First Principles (zero consumers): kept by the author's scope decision. Inherited from Repair provenance: GPT 5.6 delegate (served |
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.
948401c to
7577e27
Compare
|
Review dispositions for GPT 5.6 (blocking), fixed. Slot listeners dropped Design Review:
Inherited from Repair provenance: the fix was made by a GPT 5.6 delegate (served |
iamwhatever
left a comment
There was a problem hiding this comment.
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.
Problem / Motivation
Goal: Python code outside the gateway can drive chat, approvals, models, config, STT and live events through
kirocrew-clientinstead of hand-rolling HTTP and WebSocket calls.packages/kirocrew-client-pycovers 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:mc_tokencookie. The Gateway reads onlymc_token_<port>(token_auth._cookie_port_from_host), so a token-authenticated request carries no credential.max_retries=0, a successful refresh ends inRequest failed.list_subagents/list_crons/list_lessonsexpect bare lists where the Gateway returns{agents}/{jobs}/{lessons}.update_cronsendsPUTto aPATCHroute.list_mcp_serverscalls an unregistered path.memory_searchsendstop_kwhere the route readslimit.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
kirocrew-clientto PyPI, or making the mainkirocrewpackage depend on it.GatewayManager,AppLifecycle, manifest or proxy-auth helpers.mcp.json). Those bypass the Gateway, so they stay "call the endpoint".main.What changed (motivation → approach → change)
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.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 setscookie_portto the gateway's listen port (used for HTTP and the WebSocket). The refresh no longer consumes an attempt._requestretries 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 ofedit-resendwould truncate and regenerate history again). The backoff saturates instead of overflowing after a very long outage. Wrapped-list reads go through_list_field, which raisesSERVER_ERRORwhen the envelope key is missing instead of returning[].update_cronusesPATCH.list_mcp_serverscallsGET /api/mcp.memory_searchsendslimitand readsresults.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, andtranscribe(multipartaudiofield, the only one the route reads).resolve_approvalsendsapprove/rejectasapproved/rejectedon 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'spatternthattrust_command/trust_baserequire.set_approval_modelikewise accepts onlynormal,trust_reads,trust,yolo, and refuses aslot_idwithyolo, which the gateway applies to every slot.stream_chatandtranscriberefresh the token and re-send once after a 401/403. Nothing else is retried: a re-send ofstream_chatcould start a second turn. Transport failures on both raiseNETWORK_ERROR, like every other method, and so does a stream that ends before[DONE]. When the slot is busy,/api/chatanswers with a JSON receipt ({ok, queued}/{ok, steered}) instead of a stream;stream_chatyields that receipt once and ends normally, so a caller does not re-send an already queued turn.ws_client.py.WsClientfor/api/wswith 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 theOriginheader/api/wsrequires, and refreshes the token before each reconnect when a refresher exists. Caller options (origin,get_headers,on_reconnect) override those defaults. Slot listeners also receiveslot_titleandsession_summary, the two frame types that carry the slot asdata["key"](every other slot-bound frame usesdata["slot"]).test/test_client_py_route_contract.pyderives 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 thatregister_allbuilds. 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..github/workflows/client-py.ymlruns 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.pyexempts nested distributions on the understanding that they run on their own.docs/app-kit/api-reference.mdand the note ingetting-started.mdare 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_serversandmemory_searchreturned[]against the real Gateway, andupdate_crongot 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_fieldstill 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 ofapi_models).resolve_approvalwithout aslot_idis new behavior and has no existing callers.Tests
packages/kirocrew-client-py/tests/test_gateway_contract.pyruns 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/wsrejects a missing or wrongOriginthe wayorigin.pydoes. It pins:max_retries=0returns the refreshed answer.stream_chatandtranscribeeach recover from one 401.SERVER_ERRORfor a dict missing its key.PATCHforupdate_cron, andlimit/resultsformemory_search.force), edit-resend bodies, and that an id containing/and?is escaped.stream_chatyields chunks until[DONE], raises on an error status before yielding, and raisesNETWORK_ERRORfor a refused connection or a mid-stream drop.transcribedoes the same for a refused connection.[DONE]raisesNETWORK_ERROR, while a JSON queued or steered receipt is yielded once.yolowith a slot raises and sends nothing. A newly escaped id containing/stays one path segment.approve→approvedon the slot route), and thepatternrequirement fortrust_command/trust_base. Rejected actions and config keys send no request.transcribe.WsClientconnects with the auth cookie andOrigin, dispatches typed and slot events, and derivesws:///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, thepatterncheck, 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
feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)Contribution License Agreement