Repository navigation
feat(kap): add agent-to-agent HTTP wait/interactions/kap.md, web --json, and KAP guide - #4966
Conversation
🦋 Changeset detectedLatest commit: 4929e0d The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b3b0b1c2fc
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
fe73091 to
ec9f213
Compare
b3b0b1c to
bc4e726
Compare
There was a problem hiding this comment.
💡 Codex Review
When a caller supplies the newly documented top-level cwd without workspace_id or metadata.cwd—including the request shown in this PR's quick start—the route accepts it because callerCwd is body.cwd ?? metadata.cwd. This error list instead says that exact combination returns 40001, and similarly attributes workspace-root mismatches only to metadata.cwd; describe the conditions in terms of cwd or metadata.cwd so client implementations do not reject a valid request form.
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
ec9f213 to
7ee166d
Compare
bc4e726 to
edd8c4b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: edd8c4b349
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 14b0c2e832
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f8165efe10
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 599dcca617
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
7ee166d to
d88c389
Compare
8b9fec2 to
4efeafd
Compare
d88c389 to
70c8de2
Compare
4efeafd to
f593c5b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f593c5ba81
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
bd822ab to
6da716a
Compare
f593c5b to
a861d86
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a861d86278
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0d42b3aa08
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11354c1836
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const refDir = resolve(outDir, locale, 'reference') | ||
| mkdirSync(refDir, { recursive: true }) | ||
| for (const slug of legacyPages) { | ||
| const html = `<!DOCTYPE html><html lang="${locale}"><head><meta charset="utf-8"><title>Redirecting…</title><link rel="canonical" href="${guideTarget}"><meta http-equiv="refresh" content="0; url=${guideTarget}"><script>(function(){var raw=location.hash||'';var h=raw;try{h=decodeURIComponent(raw);}catch(_){}h=h.toLowerCase();var p=${JSON.stringify(slug)};var g=${JSON.stringify(guideTarget)};var s=${JSON.stringify(specTarget)};var u=g;if(p==='server-api-conversation'){if(/^#(turns|items|user_message|assistant_message|tool_call|notification|system|agent-state|轮次|条目|agent-状态)/.test(h))u=s+'#core-domain-shapes';else if(h.length>1)u=s+'#websocket-and-conversation-reduction-constitution';}else if(/^#(auth|authentication|connection-and-authentication|connecting-and-authenticating|鉴权|连接与鉴权)(?:$|[-_])/.test(h))u=g+${JSON.stringify(authHash)};else if(/^#(quick-start|drive-a-session|快速开始|用-api-驱动)/.test(h))u=g+${JSON.stringify(quickStartHash)};else if(/^#(conventions|online-schemas|address|response-envelope|error-codes|when-several-clients|pagination|action-paths|common-rules|binary-and-streaming|基础约定|在线-schema|地址|响应信封|错误码|多个客户端|分页|动作路径|共同规则|二进制与流式)/.test(h))u=s+'#protocol-conventions-and-evolution';else if(/^#(the-session-object|session-object|session-对象|会话对象)/.test(h))u=s+'#core-domain-shapes';else if(/^#(the-workspace-object|workspace-object|entry-object|workspace-对象|工作区对象|条目对象)/.test(h))u=s+'#files-uploads-workspaces-search';else if(/^#(capability-status-object|plugin-summary|能力状态对象|插件摘要)/.test(h))u=s+'#models-providers-config-tools-capabilities-plugins-mcp-oauth';else if(/^#(websocket-protocol|connect|control-frames|events|reconnect-and-recovery|transcript-protocol|conversation|websocket-协议|建立连接|控制帧|事件|断线恢复|转录协议|对话)(?:$|[-_])/.test(h))u=s+'#websocket-and-conversation-reduction-constitution';else if(h.length>1)u=s+'#complete-endpoint-and-websocket-catalog';location.replace(u);})()</script></head><body><p>Redirecting to <a href="${guideTarget}">${guideTarget}</a>…</p></body></html>\n` |
There was a problem hiding this comment.
Preserve endpoint-specific legacy anchors
When readers follow a published endpoint bookmark such as /en/reference/server-api-service.html#get-api-v1-meta or #post-api-v1-oauth-login, none of these endpoint hashes match the replacement regexes, so they all fall through to #complete-endpoint-and-websocket-catalog; that section has only grouped tables and no corresponding endpoint anchors. The deleted legacy-anchor map covered 282 get-/post-/put-/patch-/delete- hashes, so preserve those mappings or generate endpoint-specific targets instead of discarding every endpoint bookmark.
AGENTS.md reference: AGENTS.md:L111-L113
Useful? React with 👍 / 👎.
| | `POST /api/v1/sessions/{session_id}:wait` | `session_wait` | Block until `activity !== "turn"`, a pending interaction appears, or `timeout_ms` (`0..60000`, default `15000`); returns `{ session, pending_interactions, timed_out }` | | ||
| | `POST /api/v1/sessions/{session_id}:cancel` | `baseline` | Cancel running turn (`agent_id?`, `include_background?`) | | ||
| | `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Fork session (`turn_index?`), undo from `turn_id`, compact context (`instruction?`), or spawn side-chat (`{ agent_id }`) | | ||
| | `POST /api/v1/sessions/{session_id}:archive` / `:restore` / `:delete` / `:reload` / `:takeover` | `baseline` | Lifecycle actions on one session (also batch `POST /api/v1/sessions:archive` & `:restore` by `ids`) | |
There was a problem hiding this comment.
Restore the stale-lock warning for session takeover
When the process currently holding the session lock is still alive, :takeover unlinks that lock without stopping the holder, allowing both processes to write the same session until one goes idle and potentially interleave its history. Grouping this operation with ordinary lifecycle actions removes the deleted reference's stale-lock-only warning, so an HTTP supervisor may call it as routine conflict recovery; document that callers must first establish that the holder exited, or require an explicit confirmation before exposing this action.
AGENTS.md reference: AGENTS.md:L127-L129
Useful? React with 👍 / 👎.
| | `GET /api/v1/sessions` / `GET /api/v1/sessions/{session_id}` | `baseline` | List/filter/group sessions (`flat` or `by_workspace`, pagination) or read one session | | ||
| | `POST /api/v1/sessions/{session_id}:wait` | `session_wait` | Block until `activity !== "turn"`, a pending interaction appears, or `timeout_ms` (`0..60000`, default `15000`); returns `{ session, pending_interactions, timed_out }` | | ||
| | `POST /api/v1/sessions/{session_id}:cancel` | `baseline` | Cancel running turn (`agent_id?`, `include_background?`) | | ||
| | `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Fork session (`turn_index?`), undo from `turn_id`, compact context (`instruction?`), or spawn side-chat (`{ agent_id }`) | |
There was a problem hiding this comment.
State that undo leaves working-tree changes intact
When a turn has edited files, POST ...:undo removes the selected conversation turns and reconciles derived session state, but it does not restore any files changed by those turns. The replacement catalog now says only “undo from turn_id,” so an HTTP automation client can report a rollback as complete while the edits remain in the repository; retain the explicit warning that callers must revert working-tree changes separately.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| | `GET /api/v1/sessions` / `GET /api/v1/sessions/{session_id}` | `baseline` | List/filter/group sessions (`flat` or `by_workspace`, pagination) or read one session | | ||
| | `POST /api/v1/sessions/{session_id}:wait` | `session_wait` | Block until `activity !== "turn"`, a pending interaction appears, or `timeout_ms` (`0..60000`, default `15000`); returns `{ session, pending_interactions, timed_out }` | | ||
| | `POST /api/v1/sessions/{session_id}:cancel` | `baseline` | Cancel running turn (`agent_id?`, `include_background?`) | | ||
| | `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Fork session (`turn_index?`), undo from `turn_id`, compact context (`instruction?`), or spawn side-chat (`{ agent_id }`) | |
There was a problem hiding this comment.
Explain how forking truncates an active turn
When :fork is called while the main agent is running, the fork keeps only the last completed boundary and represents the active turn as its original user prompt followed by a synthetic cancelled end; partial assistant output, tool activity, queued prompts, and later events are absent from the child. The catalog presents this as an ordinary session fork, so automation using it as a live snapshot can silently continue from an incomplete history; restore the active-turn truncation warning or direct callers to wait for the turn to settle first.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| | `GET /api/v1/sessions` / `GET /api/v1/sessions/{session_id}` | `baseline` | List/filter/group sessions (`flat` or `by_workspace`, pagination) or read one session | | ||
| | `POST /api/v1/sessions/{session_id}:wait` | `session_wait` | Block until `activity !== "turn"`, a pending interaction appears, or `timeout_ms` (`0..60000`, default `15000`); returns `{ session, pending_interactions, timed_out }` | | ||
| | `POST /api/v1/sessions/{session_id}:cancel` | `baseline` | Cancel running turn (`agent_id?`, `include_background?`) | | ||
| | `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Fork session (`turn_index?`), undo from `turn_id`, compact context (`instruction?`), or spawn side-chat (`{ agent_id }`) | |
There was a problem hiding this comment.
Document that manual compaction returns before completion
When a client calls :compact, the endpoint starts compaction and returns immediately rather than waiting for the summary to finish; subsequent prompts are held until that background operation settles, and :wait is not a completion primitive because it returns immediately whenever the main turn is inactive. Describing the action only as “compact context” lets pure-HTTP clients treat the successful POST as completion and miss a still-running or cancelled compaction, so document the asynchronous contract and the state clients must poll before proceeding.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
b61e875 to
d735b2d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d735b2dde5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| curl -sf -X POST "${ORIGIN}/api/v1/sessions/${SID}/interactions/${IID}" \ | ||
| -H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" \ | ||
| -d '{"kind":"approval","decision":"approved"}' >/dev/null |
There was a problem hiding this comment.
Branch on interaction kind in the shell loop
When the pending item is a question, this loop always submits an approval response, so the interaction endpoint returns 40001 for the kind mismatch and leaves the question pending. Because the script ignores that response and immediately continues, the next :wait returns the same question at once and the example enters a tight infinite loop. Inspect kind and answer or dismiss questions instead of unconditionally approving the first item.
AGENTS.md reference: packages/kap-server/AGENTS.md:L14-L15
Useful? React with 👍 / 👎.
| Run the local Kimi server in the foreground of the current terminal — a single process that exposes the REST + WebSocket API and serves the web UI from the same origin — and open the web UI in the default browser once it is ready. The command stays attached to the terminal and shuts down cleanly on `SIGINT` / `SIGTERM` (e.g. `Ctrl-C`). | ||
|
|
||
| When the server is running, `GET /openapi.json` returns the REST OpenAPI document and `GET /asyncapi.json` returns the local WebSocket AsyncAPI document. For an end-to-end walkthrough of driving sessions over the API, see [Server API: Drive a session over the API](./server-api.md#drive-a-session-over-the-api); for the protocol details, see the [Server API](./server-api.md) reference. | ||
| When the server is running, `GET /openapi.json` returns the REST OpenAPI document and `GET /asyncapi.json` returns the local WebSocket AsyncAPI document. For an end-to-end walkthrough of driving sessions over the API, see [Kimi Agent Protocol: Quick start](../guides/kap.md#quick-start); for the protocol details, see [Kimi Agent Protocol (KAP)](../guides/kap.md). |
There was a problem hiding this comment.
Point the quick-start link at an existing section
Neither docs/en/guides/kap.md nor its Chinese mirror defines a Quick start / 快速开始 heading, so this newly added link—and the corresponding Chinese link—lands on a nonexistent anchor instead of the promised walkthrough. Link to the existing dynamic-bootstrap section or add the referenced heading.
AGENTS.md reference: docs/AGENTS.md:L234-L237
Useful? React with 👍 / 👎.
| 1. **Prefer attaching to a running Desktop / `kimi web` instance** so the newly created session appears immediately in the user's open Kimi Code Desktop sidebar. | ||
| 2. Create the session: `POST /api/v1/sessions` with `{ "cwd": "<absolute workspace path>", "title": "<concise handoff title>" }`. | ||
| 3. Submit a clean handoff brief via `POST /api/v1/sessions/{session_id}/prompts` covering: **Goal**, **Completed changes & relevant files**, **Key decisions / constraints**, and **Next steps** (omit noisy raw logs and secrets). | ||
| 4. **Server lifetime rule**: If attached to the user's running server, you can either return `session_id` immediately for user takeover in Kimi Code or supervise via `:wait`. If you spawned a private `kimi web --port 0 --json` subprocess, **do not kill that subprocess while `activity === "turn"`** — wait via `:wait` until the turn settles so history persists cleanly to disk, then stop the subprocess and give the user `kimi -S <session_id>`. |
There was a problem hiding this comment.
Keep private servers alive while background work is active
When the main turn ends while a detached Bash or subagent task is still running, the returned session has activity: "background", not "turn"; following this rule therefore stops the private server even though work remains active. That shutdown abandons the live task (restored running tasks are subsequently marked lost), so HTTP-driven handoffs can silently terminate work after receiving the main reply. Require activity === "idle", or explicitly inspect and settle/cancel background tasks, before stopping the subprocess.
AGENTS.md reference: packages/kap-server/AGENTS.md:L14-L15
Useful? React with 👍 / 👎.
d735b2d to
70f3c0b
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 70f3c0be0e
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| ## 1. Request conventions | ||
|
|
||
| - **Auth & headers**: Send `Authorization: Bearer <token>` on all `/api/v1/*` and `/openapi.json` requests (`GET /api/v1/healthz` is unauthenticated). Send `Content-Type: application/json` when passing a JSON body. | ||
| *(If you have not connected yet: attach to a live instance via `${KIMI_CODE_HOME:-~/.kimi-code}/server/instances/*.json` + `server.token`, or spawn `kimi web --port 0 --json` and read `{ origin, token }` from line 1 of `stdout`.)* |
There was a problem hiding this comment.
Expand HOME outside the fallback expression
When KIMI_CODE_HOME is unset, Bash evaluates ${KIMI_CODE_HOME:-~/.kimi-code} to the literal path ~/.kimi-code; tilde expansion is not performed inside this parameter-expansion fallback. An agent following the built-in bootstrap guide therefore fails to find server.token and the instance registry on the default installation. Use ${KIMI_CODE_HOME:-$HOME/.kimi-code}, as the installed skill already does.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| ```sh | ||
| SID=$(curl -sf -X POST "${ORIGIN}/api/v1/sessions" \ | ||
| -H "Authorization: Bearer ${TOKEN}" -H "Content-Type: application/json" \ | ||
| -d "{\"cwd\":\"$PWD\",\"agent_config\":{\"permission_mode\":\"manual\"}}" | jq -r '.data.id') |
There was a problem hiding this comment.
Encode the workspace path before embedding it in JSON
When the workspace path contains a JSON-sensitive character such as ", \, or a newline, interpolating $PWD directly into this string either produces invalid JSON or changes the requested path through JSON escape processing. The copy-paste loop then fails to create the session, or creates it for the wrong directory; construct the body with jq -n --arg cwd "$PWD" (or equivalent JSON encoding) instead.
Useful? React with 👍 / 👎.
70f3c0b to
7703ee6
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7703ee6aee
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
|
|
||
| 1. **Attach to a running Desktop app or `kimi web` server first** (so new or updated sessions appear live in the user's open Kimi Code window): | ||
| - Read `KIMI_HOME="${KIMI_CODE_HOME:-$HOME/.kimi-code}"` and `TOKEN="$(tr -d '[:space:]' < "$KIMI_HOME/server.token")"`. | ||
| - Scan `"$KIMI_HOME"/server/instances/*.json` (preferring `product === "kimi-code-desktop"` when present, then newest `started_at`), verify `kill -0 <pid>`, map `host` `"0.0.0.0"` to `"127.0.0.1"` (or `"::"` / `"::1"` to `"[::1]"`), and probe `GET http://<host>:<port>/api/v1/meta` with `Authorization: Bearer ${TOKEN}`. Pick the first instance returning HTTP `200` (`code: 0`). |
There was a problem hiding this comment.
Persist the product before preferring Desktop
When Desktop and kimi web are both running, this preference cannot work: the instance registry encoder writes only server_id, pid, host, port, started_at, heartbeat_at, and host_version, so no generated instance has a product field. An external agent following this bootstrap therefore falls back to the newest process and may attach to another CLI/web server instead of the open Desktop instance, defeating the stated guarantee that changes appear live in the user's window. Persist the host product in each registry record or describe a selection signal that actually exists.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| 1. **Resolve model (when the user names a specific model)** & **create a session**: | ||
| - Query `GET /api/v1/models` (`data.items[]` has `{ provider, model, display_name, support_efforts }`) to map a human model name to `"${provider}/${model}"` instead of guessing model IDs. | ||
| - Create a session via `POST /api/v1/sessions` with `{ "cwd": "/abs/path/to/project", "title"?: "...", "agent_config"?: { "permission_mode": "manual" | "auto" | "yolo", "model"?: "${provider}/${model}", "thinking"?: "high", "plan_mode"?: false } }` (for pure design/plan discussions, `"plan_mode": true` or `"permission_mode": "auto"` works well). | ||
| 2. **Submit a round prompt**: `POST /api/v1/sessions/{session_id}/prompts` with a unique `prompt_id` (`"round-1"`, `"round-2"`, ...) and `{ "content": [{ "type": "text", "text": "..." }] }`. Verify `code === 0` and `data.status` is `"running"` or `"queued"`. |
There was a problem hiding this comment.
Reuse prompt IDs when retrying submissions
When the POST response is lost after the server has accepted a prompt, treating prompt_id as merely unique and generating a new round ID for the retry submits the prompt a second time, potentially repeating edits or commands. The implementation explicitly deduplicates an unchanged request with the same ID (and returns 40927 if that ID is reused with a different request), but this replacement workflow removed the retry contract from the deleted reference; tell HTTP agents to resend the identical endpoint and body with the same prompt_id after a timeout rather than allocate a new one.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| | `POST /api/v1/sessions/{session_id}:archive` / `:restore` / `:delete` / `:reload` / `:takeover` | `baseline` | Single-session lifecycle actions (plus batch `POST /api/v1/sessions:archive` & `:restore` by `ids`) | | ||
| | `POST /api/v1/sessions/{session_id}/profile` & `/title/generate` | `baseline` | Update `title`, `metadata`, or `agent_config`, or generate a session title | | ||
| | `GET /api/v1/sessions/{session_id}/agents/{agent_id}/turns` | `baseline` | Read turns (`before_ordinal?`, `page_size` ≤ 200; flushes live streaming items on read) | | ||
| | `GET` / `POST /api/v1/sessions/{session_id}/prompts` | `baseline` | Read active/queued prompts or submit a prompt (`prompt_id`, `content`, setting overrides, `skills?`) | |
There was a problem hiding this comment.
Warn that prompt plan and goal fields are ignored
When an HTTP client builds a prompt from the live OpenAPI schema, plan_mode, goal_objective, and goal_control are accepted request fields, but the prompt handler applies only model, thinking, permission, swarm, and disabled-tool overrides and silently ignores those three fields while still returning success. Replacing the detailed reference with the generic “setting overrides” wording removes the only warning about this behavior, so an agent can believe it entered Plan mode or updated Goal mode and proceed under the wrong safety assumptions; identify the ignored fields and direct callers to the session profile/goal endpoints instead.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7703ee6aee
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| 1. **Resolve model (when the user names a specific model)** & **create a session**: | ||
| - Query `GET /api/v1/models` (`data.items[]` has `{ provider, model, display_name, support_efforts }`) to map a human model name to `"${provider}/${model}"` instead of guessing model IDs. | ||
| - Create a session via `POST /api/v1/sessions` with `{ "cwd": "/abs/path/to/project", "title"?: "...", "agent_config"?: { "permission_mode": "manual" | "auto" | "yolo", "model"?: "${provider}/${model}", "thinking"?: "high", "plan_mode"?: false } }` (for pure design/plan discussions, `"plan_mode": true` or `"permission_mode": "auto"` works well). | ||
| 2. **Submit a round prompt**: `POST /api/v1/sessions/{session_id}/prompts` with a unique `prompt_id` (`"round-1"`, `"round-2"`, ...) and `{ "content": [{ "type": "text", "text": "..." }] }`. Verify `code === 0` and `data.status` is `"running"` or `"queued"`. |
There was a problem hiding this comment.
Reuse prompt IDs when retrying submissions
When a prompt request times out after the server accepted it, callers must resend the unchanged request with the same prompt_id: beginPromptAttempt returns the original result only for that exact ID and body, while a new or omitted ID submits another prompt (routes/prompts.ts:582-596). Saying only that every round needs a “unique” ID leaves HTTP agents likely to mint a new ID for a retry, which can repeat edits or commands; document the retry contract and its process-local/256-entry limit.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| | `POST /api/v1/sessions/{session_id}:wait` | `session_wait` | Wait until `activity !== "turn"`, a pending interaction appears, or `timeout_ms` (`0..60000`, default `15000`) | | ||
| | `POST /api/v1/sessions/{session_id}:cancel` | `baseline` | Cancel active turn (`agent_id?`, `include_background?`) | | ||
| | `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Branch session (`turn_index?`), undo from `turn_id`, compact context, or spawn read-only side-chat (`{ agent_id }`) | | ||
| | `POST /api/v1/sessions/{session_id}:archive` / `:restore` / `:delete` / `:reload` / `:takeover` | `baseline` | Single-session lifecycle actions (plus batch `POST /api/v1/sessions:archive` & `:restore` by `ids`) | |
There was a problem hiding this comment.
Warn that session deletion is irreversible
When an HTTP agent uses :delete, deleteSessionAction immediately invokes ISessionManager.delete, removing the session's persisted data before returning { deleted: true } (routes/sessions.ts:1003-1007). Grouping deletion with reversible lifecycle actions such as archive and restore removes the prior warning that deletion is permanent and cannot be undone, so an agent organizing session history can treat it as routine cleanup and destroy user data; call out the irreversible behavior and direct ordinary cleanup to :archive.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
| | `POST /api/v1/sessions/{session_id}:archive` / `:restore` / `:delete` / `:reload` / `:takeover` | `baseline` | Single-session lifecycle actions (plus batch `POST /api/v1/sessions:archive` & `:restore` by `ids`) | | ||
| | `POST /api/v1/sessions/{session_id}/profile` & `/title/generate` | `baseline` | Update `title`, `metadata`, or `agent_config`, or generate a session title | | ||
| | `GET /api/v1/sessions/{session_id}/agents/{agent_id}/turns` | `baseline` | Read turns (`before_ordinal?`, `page_size` ≤ 200; flushes live streaming items on read) | | ||
| | `GET` / `POST /api/v1/sessions/{session_id}/prompts` | `baseline` | Read active/queued prompts or submit a prompt (`prompt_id`, `content`, setting overrides, `skills?`) | |
There was a problem hiding this comment.
State that prompt setting overrides persist
When a KAP caller includes model, thinking, permission_mode, swarm_mode, or disabled_tools in a prompt request, the handler writes those values into the target agent before enqueuing the input and never restores the previous values (routes/prompts.ts:272-287), even when the prompt is only queued. Calling these fields merely “setting overrides” makes them look request-scoped, so an automation round can silently leave the user's subsequent Desktop/Web turns on a different model or permission policy; document that these settings persist and must be explicitly reset.
AGENTS.md reference: packages/kap-server/AGENTS.md:L15-L15
Useful? React with 👍 / 👎.
7703ee6 to
1bea34d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1bea34d0b3
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| | `POST /api/v1/sessions/{session_id}:fork` / `:undo` / `:compact` / `:btw` | `baseline` | Branch session (`turn_index?`), undo from `turn_id`, compact context, or spawn read-only side-chat (`{ agent_id }`) | | ||
| | `POST /api/v1/sessions/{session_id}:archive` / `:restore` / `:delete` / `:reload` / `:takeover` | `baseline` | Single-session lifecycle actions (plus batch `POST /api/v1/sessions:archive` & `:restore` by `ids`) | |
There was a problem hiding this comment.
Project every documented session action into OpenAPI
When an HTTP agent follows the new instruction to obtain exact schemas from /openapi.json, the documented :fork, :undo, :compact, :btw, and :restore paths are absent: patchSessionAction projects only cancel/wait/archive/delete/reload/takeover and then deletes the generic /sessions/{tail} operation. Because this change also removes the detailed server API pages that previously described these actions, callers can no longer discover their request and response contracts from either canonical source; project all listed actions before deleting the generic path or retain their field-level documentation.
AGENTS.md reference: packages/kap-server/AGENTS.md:L12-L15
Useful? React with 👍 / 👎.
| - **Exit codes**: | ||
| - `0`: Completed normally; | ||
| - `1`: Invalid CLI options, missing model credentials, or turn execution error; | ||
| - `4`: The target session (`-S` / `-c`) is currently in use by another process (`stream-json` also writes `{"type":"error",...}` to `stdout`). |
There was a problem hiding this comment.
Document the non-error Goal exit statuses
When -p is used with a supported Goal prompt such as kimi -p "/goal ...", a blocked goal exits with 3 and a paused goal exits with 6 (GOAL_EXIT_CODES), but this new purported exit-code list mentions only 0, 1, and 4. CI wrappers following this guide can therefore classify a normal blocked or paused Goal outcome as an unknown execution failure instead of inspecting the emitted goal.summary; include codes 3 and 6 and their meanings.
Useful? React with 👍 / 👎.
| pendingInteractions: PendingInteraction[]; | ||
| settled: boolean; | ||
| live: ISessionScopeHandle | undefined; | ||
| }> { |
There was a problem hiding this comment.
Read pending interactions after asynchronous session metadata
When another client answers an approval or question while readWaitSnapshot is awaiting ISessionMetadata.read(), this early snapshot remains in pendingInteractions even though resolveSessionFacts subsequently observes that it ended. The :wait response then reports the ended interaction as pending, and an HTTP supervisor following it receives 40902 when it tries to respond; collect pending interactions after the asynchronous metadata/workspace reads so the interaction list and session facts describe the same point in time.
Useful? React with 👍 / 👎.
| const raw = interactions.findAll({ | ||
| resolved: false, | ||
| tags: { [INTERACTION_TAG_SESSION_ID]: sessionId }, | ||
| }); |
There was a problem hiding this comment.
Exclude expired approvals from the pending interaction list
When an approval has remained unanswered for more than the advertised 24-hour lifetime, this query still returns it because it filters only on resolved: false; the response route likewise performs no expiry check. The newly added HTTP polling workflow therefore lets a reconnecting supervisor discover and approve a stale file or shell action after its expires_at, even though the protocol advertises 41001 for expired approvals. Expire or reject these records before exposing them as pending.
Useful? React with 👍 / 👎.
| - **Attach to a running local instance first** (preferred so new or updated sessions appear live in an open Kimi Code Desktop or Web window): set `KIMI_HOME="${KIMI_CODE_HOME:-$HOME/.kimi-code}"`, read `TOKEN="$(tr -d '[:space:]' < "$KIMI_HOME/server.token")"`, scan `"$KIMI_HOME"/server/instances/*.json` where `kill -0 <pid>` succeeds (preferring `product === "kimi-code-desktop"` when present, then newest `started_at`), map `host` `"0.0.0.0"` to `"127.0.0.1"` (or `"::"` / `"::1"` to `"[::1]"`), and pick the first `http://<host>:<port>` where `GET /api/v1/meta` (`Authorization: Bearer ${TOKEN}`) returns HTTP `200`. | ||
| - **Fallback -- start an on-demand server**: if no live instance responds, spawn `kimi web --port 0 --json` in the background, parse `{ origin, token }` from line 1 of `stdout`, keep that process running until active work finishes, and stop it (`SIGTERM`) afterward. |
There was a problem hiding this comment.
Provide a Windows-compatible KAP bootstrap path
When this public skill is installed on Windows, its required discovery path cannot be followed as written: the shell substitutions, tr, kill -0, Unix-style $HOME path, and later SIGTERM shutdown are not available in PowerShell or cmd.exe. A Windows external agent therefore falls through or fails before it can attach to Desktop or launch the JSON fallback; specify platform-neutral process/file operations or include PowerShell equivalents for discovery and shutdown.
Useful? React with 👍 / 👎.
2aaf4f5 to
2202f65
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2202f65967
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const after = await readWaitSnapshot(core, id); | ||
| reply.send( | ||
| okEnvelope( | ||
| { | ||
| session: after.session, |
There was a problem hiding this comment.
Continue waiting if queued work restarts the turn
When another prompt is already queued, onDidChange resolves this wait as soon as the current TurnEnded briefly makes mainTurnActive false, but the loop can start the queued turn while the asynchronous readWaitSnapshot is reading metadata. This then returns timed_out: false with session.activity === "turn", a state excluded by the documented result branches, so an HTTP supervisor can treat the session as having reached a stopping point while the next prompt is actively making changes. Re-check after the snapshot and keep waiting when the turn has restarted and no interaction is pending.
AGENTS.md reference: packages/kap-server/AGENTS.md:L12-L15
Useful? React with 👍 / 👎.
…on, and KAP guide
2202f65 to
4929e0d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4929e0d2aa
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| - **`kimi rc`** (alias `kimi remote`): start Remote Control directly; | ||
| - **`kimi web --remote-control`**: equivalent to `kimi rc`; | ||
| - **`/remote-control`** (alias `/rc`): hand your active CLI session directly to the remote web UI. |
There was a problem hiding this comment.
Restore the Remote Control launch constraints
When users try to combine kimi web --remote-control with LAN sharing or disabled authentication, handleWebCommand rejects the invocation because Remote Control requires a loopback host and cannot be combined with --dangerous-bypass-auth. The deleted Remote Control guide documented both constraints, but this replacement calls the commands equivalent without preserving them, and the generic security note can imply that bypass auth remains available in this mode; restore these restrictions beside the launch instructions in both locales.
AGENTS.md reference: docs/AGENTS.md:L271-L285
Useful? React with 👍 / 👎.
| Each line written to `stdout` is a standalone JSON object (JSONL): | ||
|
|
||
| ```json | ||
| {"role":"assistant","content":"","tool_calls":[{"type":"function","id":"call_1","function":{"name":"Grep","arguments":"{\"pattern\":\"export function\"}"}}]} |
There was a problem hiding this comment.
Include the initial version record in the JSONL contract
When a script models stream-json from this example and the following record list, its first input is an undocumented {"role":"meta","type":"system.version","version":"..."} record because runV2Print calls writeExperimentalVersion before starting the session. A strict headless parser can therefore reject every run before reaching the documented Assistant record; add system.version to the example and the role: "meta" type list in both locales.
AGENTS.md reference: AGENTS.md:L127-L129
Useful? React with 👍 / 👎.
The interactions routes, web --json, KAP 1.0.0 and the interactions_list/session_wait capabilities were already present; add the missing built-in guide route serving docs/kap.md as text/markdown, with the refreshed contract/openapi goldens and the reviewed apiSurface snapshot (MoonshotAI#4966). meta suite 10 pass.
Requirement or Bug
整理并发布 Kimi Agent Protocol(KAP,
0.xBeta)面向「另一个活的 AI Agent 在运行时通过纯 HTTP 交互式驾驭 Kimi Code(作为可监工的 subagent、双向 hand off 交接会话、跨工作区批量整理会话)」的极简闭环能力、kimi-code跨 Agent Skill 与文档:kimi web --json:子进程启动模式(隐含--no-open,生成仅随进程存活的内存随机 Bearer Token,跳过全局instances/注册,日志走stderr,就绪后在stdout首行输出单行 JSON{ origin, ws_url, token, kimi_agent_protocol_version })。GET /api/v1/sessions/{session_id}/interactions:纯 HTTP 读取当前会话未决approval/question列表{ items }(复用现有 wire 投影)。POST /api/v1/sessions/{session_id}:wait+ConversationFeed.page()刷缓冲:同步等待下一个停顿点(activity !== "turn"或出现未决approval/question时 0ms 立即返回,否则挂起至状态变化、timeout_ms或客户端断连自动清理监听器),一次返回{ session, pending_interactions, timed_out };同时在GET .../turns读取前调用flushPending()确保纯 HTTP 能实时读到运行中轮次与流式半截条目,并在GET /api/v1/meta的capabilities暴露session_wait: true、interactions_list: true。GET /api/v1/kap.md:运行中实例直接返回内置的packages/kap-server/docs/kap.md(需 Bearer 鉴权,text/markdown; charset=utf-8),并统一instances/*.json与/api/v1/meta的server_id。guides/other-agents.md→skills/use-kimi-code/SKILL.md→ 动态GET /api/v1/kap.md):skills/use-kimi-code/SKILL.md(支持npx skills add https://code.kimi.com/kimi-code/skills/use-kimi-code.md -g):极薄引导桩,不暴露内部协议术语也不写死易变接口路径,触发后自动连接本机实例并动态拉取GET /api/v1/kap.md。packages/kap-server/docs/kap.md(~160 行纯 HTTP 运行时操作手册):去掉冗余自指与 WebSocket 客户端归并噪音,聚焦 subagent 监工闭环、双向hand off会话交接与跨工作区会话整理。docs/{zh,en}/guides/other-agents.md:合并替换旧reference/server-api*.md5 页,围绕「安装一次 Skill → 自然语言驱动 subagent / 双向 hand off / 会话整理」组织学习路线。packages/kap-server/AGENTS.md、AGENTS.md、.agents/skills/*):明确0.xBeta 仅对核心会话与对话流接口保持向后兼容,宿主管理接口随第一方产品自由演进。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
API、CLI 与文件
+/-清单(运行时协议面纯增量)Behavior Changes and Affected Users
kimi web新增--json启动标志--json--no-open,使用进程内随机 Bearer Token 并在stdout首行输出单行 JSON{ origin, ws_url, token, kimi_agent_protocol_version }--json保持原有交互横幅与server.token行为GET /api/v1/sessions/{id}/interactions、POST /api/v1/sessions/{id}:wait、GET /api/v1/kap.md及meta.capabilities布尔位GET .../turns读取前自动刷缓冲返回最新运行态条目packages/kap-server(meta.test.ts、approvals.test.ts、sessions.test.ts、apiSurface.snapshot.test.ts)与apps/kimi-code(options.test.ts、web.test.ts)全绿,typecheck、oxlint、check-comments、tsdown构建及docs build全部通过。manual会话、:wait捕获并代批两次Bash审批、sleep 4期间/steer跨轮纠偏及最终结果回收。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.