Skip to content

feat(kap-server): add POST /sessions/{id}:continue for interrupted turns - #5048

Open
wbxl2000 wants to merge 2 commits into
mainfrom
feat/kap-session-continue
Open

wbxl2000 wants to merge 2 commits into
mainfrom
feat/kap-session-continue

Conversation

@wbxl2000

Copy link
Copy Markdown
Collaborator

Requirement or Bug

用户在取消(:cancel)或因模型错误中断当前轮次、或进程异常退出留下未完结轮次后,需要一种无需伪造 "继续" 用户消息即可从中断点接着执行的会话动作。本 PR(Stacked on #4967)新增 POST /api/v1/sessions/{session_id}:continue。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

flowchart TD
    Req["POST /api/v1/sessions/{id}:continue"] --> Resume["resumeSessionById + ensureMainAgent + loop.start()"]
    Resume --> Busy{"running / paused / compacting?"}
    Busy -- yes --> E40901["40901 SESSION_BUSY"]
    Busy -- no --> Check{"hasUnfinishedTurn || lastTurn in (cancelled, failed)?"}
    Check -- no --> E40940["40940 TURN_NOT_CONTINUABLE"]
    Check -- yes --> Remind{"hasUnfinishedTurn?"}
    Remind -- no --> Inject["loop.remind(<system-reminder>No new user message was sent. Continue...)</system-reminder>"]
    Remind -- yes --> Cont["loop.continueTurn() (loop.continue({ force: true }))"]
    Inject --> Cont
    Cont --> Resp["200 { continued: true } (非阻塞,事件走 WS)"]
Loading
  • packages/agent-core-v2:
    • LoopSnapshot:修正 state 判定为 loop?.state.status === 'running' || active !== undefined ? 'running' : 'idle',避免冷恢复后携带崩溃未结轮次(loop.state.status === 'interrupted')时被误判为 running;同时暴露 hasUnfinishedTurn?: boolean。
    • IAgentLoopService.continueTurn():非阻塞排空 pendingReminders 并调用 loop.continue({ force: true })(崩溃未结轮次走 turn.resumed 续跑原轮次;已结束的 cancelled/failed 轮次开启 trigger: 'continue' 新轮次,不在对话流中生成 user_message 条目)。
    • LoopErrors:新增 TURN_NOT_CONTINUABLE(turn.not_continuable)。
  • packages/kap-server:
    • routes/sessions.ts:新增动作 continue(映射 40940 TURN_NOT_CONTINUABLE),对已结 cancelled/failed 轮次在续跑前注入 origin: { kind: 'injection', variant: 'turn_continue' } 的系统提醒,引导模型直接从中断处继续而不重复已完成步骤;在 openapi/transforms.ts 投影 POST /api/v1/sessions/{session_id}:continue 并更新 apiSurface 快照。
  • docs/{zh,en}/reference/server-api*.md:增量补充 POST /api/v1/sessions/{session_id}:continue 与 40940 错误码说明。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
POST /api/v1/sessions/{session_id}:continue 路由动作不存在(返回 40001 unsupported action) 非阻塞继续 main 的未结、cancelled 或 failed 轮次并返回 { continued: true };运行中返回 40901,新会话或已 completed 轮次返回 40940 无既有调用方(纯新增会话动作;apiSurface.snapshot.test.ts.snap 新增 /api/v1/sessions/{session_id}:continue) 不调用 :continue 时所有既有提交路径不变
:continue 续跑已结 cancelled/failed 轮次时的提醒注入 无此入口(此前 :cancel 仅注入 "The user's next message continues the conversation.") 仅在显式调用 POST /sessions/{id}:continue 且非崩溃 unfinished 恢复时,追加一句提醒:"No new user message was sent. Continue the interrupted work from where it stopped; do not repeat steps that already completed."(origin.kind: "injection",UI 隐藏) 仅显式调用 POST /api/v1/sessions/{id}:continue 的客户端会话接收该提醒;普通 /prompts 提交完全不触发 改用 POST /sessions/{id}/prompts 发送显式用户消息
LoopSnapshot.state 在冷恢复存在崩溃 unfinished 轮次时的值 因 loop.state.turn 非空曾返回 'running'(尽管 loop.state.status === 'interrupted' 且无活跃执行) 返回 'idle' 并置 hasUnfinishedTurn: true 仅崩溃未结会话冷加载后在尚未触发恢复前的快照查询;真实运行轮次 loop.state.status === 'running' 不变 N/A
  • 受影响模块:packages/agent-core-v2(agent/loop)、packages/kap-server(routes/sessions.ts、openapi/transforms.ts、错误码与快照)、docs/。
  • 验证结论:conversationContract.e2e.test.ts 新增 S13 覆盖新建空会话拒绝(40940)、运行中拒绝(40901)、:cancel 后 :continue 无 user_message 正常续跑完成、正常完成后拒绝(40940)、上游报错 failed 后 :continue 续跑恢复;typecheck、oxlint 与 VitePress 构建全绿。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@changeset-bot

changeset-bot Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: edda32a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-18T15:38:18.674311Z edda32a New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@edda32a
npx https://pkg.pr.new/@moonshot-ai/kimi-code@edda32a

commit: edda32a

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5c9de4207d

ℹ️ 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 assertIdle = (): void => {
const snap = loop.snapshot();
const compacting = agent.accessor.get(IAgentFullCompactionService).compacting !== null;
if (snap.state === 'running' || snap.paused || snap.hasPendingRequests || compacting) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Allow crash-interrupted loops through the busy checks

When a session is cold-restored after a process crash, the core loop has state.status === 'interrupted'; hasPendingRequests() consequently returns true for that non-idle status. This condition therefore returns 40901 SESSION_BUSY before checking whether the orphaned turn is continuable, and AgentLoopService.continueTurn() repeats the same check even if this guard is bypassed. As a result, the advertised crash-recovery case can never reach loop.continue({ force: true }); distinguish an interrupted unfinished loop from genuinely active pending work in both gates.

Useful? React with 👍 / 👎.

switch (record.type) {
case 'turn.prompt':
case 'turn.prompt': {
if (typeof record['trigger'] === 'string') state.recordsTurnEnds = true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reopen the orphaned turn when resuming it

Once a cold-restored crash continuation passes the busy checks, this new classification makes settleOrphanTurns() mark the orphan as ended/interrupted, but it does not add the turn to implicitlyEnded. When the core resumes the same turn number, the next step.begin therefore cannot reopen the known turn in turnForNumber() and instead creates a second conversation turn with the same turn_number; KAP clients retain the original as interrupted and receive the resumed output in a separate, user-message-less turn. Mark crash-settled turns as implicitly ended (or otherwise explicitly reopen them) so the WS/REST projection matches the core's same-turn resume.

Useful? React with 👍 / 👎.

undo: { body: undoSessionRequestSchema, handle: undoSessionAction },
cancel: { body: cancelSessionRequestSchema, handle: cancelSessionAction },
wait: { body: waitSessionRequestSchema, handle: waitSessionAction },
continue: { handle: continueSessionAction },

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Add a changeset for the public continue action

This adds an externally advertised core KAP capability and endpoint, but the commit contains no .changeset entry. The repository's changeset rules explicitly require public KAP conversation/session capabilities to produce a user-facing CLI changeset, so otherwise this new action will be absent from the generated release versioning and changelog; add a minor changeset for @moonshot-ai/kimi-code.

AGENTS.md reference: AGENTS.md:L109-L109

Useful? React with 👍 / 👎.

@wbxl2000
wbxl2000 force-pushed the feat/kap-session-continue branch from 5c9de42 to 7acf8db Compare November 18, 2026 10:10
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from f8dc1f6 to 93ceab0 Compare November 18, 2026 10:10
@wbxl2000
wbxl2000 force-pushed the feat/kap-session-continue branch from 7acf8db to 4ac723d Compare November 18, 2026 12:16
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from 93ceab0 to e3eaf6d Compare November 18, 2026 12:16

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4ac723df68

ℹ️ 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 retry = active?.retry;
return {
state: loop?.state.turn === undefined && active === undefined ? 'idle' : 'running',
state: loop?.state.status === 'running' || active !== undefined ? 'running' : 'idle',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep interrupted turns unavailable to cron scheduling

When a cron-enabled session is cold-restored with durable.unfinished, the loop has status === 'interrupted' and no active projection, so this change reports it as idle. tickCron() skips delivery only when snapshot().state === 'running'; a due persisted job can therefore call notify(), whose core scheduler invokes closeUnfinished() before starting the cron turn. This silently discards the resumable foreground turn before the user can call :continue, whereas the previous snapshot kept cron delivery blocked while that unfinished turn existed. Treat interrupted work as non-idle to existing schedulers, or update those schedulers to honor hasPendingRequests.

AGENTS.md reference: AGENTS.md:L115-L117

Useful? React with 👍 / 👎.

@wbxl2000
wbxl2000 force-pushed the feat/kap-session-continue branch from 4ac723d to 24a1422 Compare November 18, 2026 12:47
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from e3eaf6d to 7ea55aa Compare November 18, 2026 12:47
@wbxl2000
wbxl2000 force-pushed the feat/kap-session-continue branch from 24a1422 to 69c7eab Compare November 18, 2026 14:16
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch from 7ea55aa to eae5840 Compare November 18, 2026 14:16
@wbxl2000
wbxl2000 force-pushed the feat/kap-session-continue branch from 69c7eab to edda32a Compare November 18, 2026 15:33
@wbxl2000
wbxl2000 force-pushed the feat/kap-agent-close branch 2 times, most recently from 1c858f4 to 030a71d Compare November 19, 2026 14:01
Base automatically changed from feat/kap-agent-close to main November 20, 2026 04:55

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant