Repository navigation
feat(tui): run interactive shell on agent-core-v2 with deferred session creation - #1543
liruifengv wants to merge 615 commits into
Conversation
- remove unused imports and variables - add void to floating promises - drop redundant return-await - bind unbound method references - replace == null with strict null/undefined checks - add explicit sort comparators and Array.from helpers - rename background_tasks capability to tasks - migrate event sink to event bus in tests
- add a per-connection outbound send buffer in WsConnectionV1; sendFrame enqueues and a flush drains on a 16ms interval or once 64 frames queue - coalesce adjacent volatile assistant/thinking deltas for the same session/agent/turn into one frame, keeping the first offset/seq so client alignment is unchanged - defer flushing while socket.bufferedAmount exceeds a 1MiB high-water mark, merging new deltas into the queued frame instead of growing it - flush remaining frames on close to avoid truncating the tail of a stream - expose flushIntervalMs / maxBatchSize / highWaterMarkBytes via registerWsV1
- bridge split v2 status slices into one combined `agent.status.updated` event via a LegacyStatus derived model at the kap-server edge, so a usage-only event no longer overwrites the live context window with a stale zero - fall back to the configured default model's context window when the agent has no model bound yet, so fresh sessions don't show "0/0" - use `size` (measured + estimated) for the live context token count to mirror v1's `context.tokenCount` - export `defineDerivedModel` / `DerivedModelDef` from agent-core-v2
- add custom onSend/onResponse access logging that records the envelope code - disable Fastify built-in request logging (every response is HTTP 200) - drop pino-pretty; logger always emits newline-delimited JSON - rename dev:server-v2 script to dev:kap-server
The v2 server package is @moonshot-ai/kap-server, but three changesets still referenced the old @moonshot-ai/server-v2 name, which no longer exists in the workspace.
Subagents created via the Agent tool or AgentSwarm fell back to the default `manual` permission mode because CreateAgentOptions offered no way to seed one, so write/execute tool calls inside a subagent prompted for approval even when the parent ran in auto/yolo. Add an optional permissionMode to CreateAgentOptions and have the Agent tool and AgentSwarm pass the caller's current mode when creating a child.
- add reduceContextTranscript in agent-core-v2: keeps the full history across context.apply_compaction (summary marker instead of dropping the prefix) and stops context.undo at compaction summaries, matching v1's transcript view - SnapshotReader: reduce the wire with the transcript reducer instead of the folded live context, so a later undo no longer hides the pre-compaction assistant reply - MessageLegacyService: read the main agent wire log and merge the unflushed live tail instead of the folded IAgentContextMemoryService.get()
- v1 session route handlers and the sessionLegacy adapter resolved the target via ISessionLifecycleService.get, which only sees live (in-memory) sessions. A freshly-opened session is persisted (index + disk) but not live until the first prompt, so commands such as undo / fs:* / skills / :btw / warnings / terminals / profile / questions / approvals / archive reported `session does not exist` (40401). - Resolve via ISessionLifecycleService.resume instead, which cold-loads a persisted session from disk (matches v1's resumeSession); a genuinely missing session still 404s. - Add a cold-load regression for `:undo` and update the skills test for the new cold-load behaviour.
- add an Agent-scope runtime domain that holds the whole live phase as one discriminated-union field (idle, running, streaming, tool_call, retrying, awaiting_approval, interrupted, ended) - drive it from existing turn, step, delta, tool, retry, interrupt and approval events, edge-triggered with reference-equality dedup so delta bursts do not flood the wire log - carry the phase on the existing agent.status.updated channel and add the AgentPhase type/schema to the protocol (backward compatible)
- write `kimi version <version>` to stderr first in text mode - emit a `system.version` meta line first in stream-json mode - gate behind isKimiV2Enabled() so the default v1 path is unchanged
…cap to 3000px (#1460) * fix(agent-core): report EXIF-rotated image dimensions and raise edge cap to 3000px Image compression now reports original dimensions in the decoded (EXIF-rotated) space, matching the coordinate system of the sent image and of ReadMediaFile region readback; previously portrait JPEGs (orientation 5-8) got swapped width/height in captions. The longest-edge downscale cap rises from 2000px to 3000px, and the default jimp resize path is documented as the anti-aliased area-average one so it is not accidentally switched to a point-sampled interpolation mode. * test: shrink oversized image fixtures to fit CI timeouts The 3600x3600 fixtures introduced for the 3000px edge cap nearly doubled the pixel area jimp has to decode and deflate, pushing the slowest compression tests past the 5s vitest timeout on CI runners. 3600x1800 keeps every fixture over the cap while restoring roughly the workload of the old 2600x2600 fixtures that CI handled comfortably. * test: pin anti-aliased downscale quality with executable guards A 1px checkerboard probe pins the compressor to full-coverage averaging at integer and fractional ratios, with jimp's point-sampled BILINEAR mode kept as the executable aliasing counter-example (it collapses the 50%-gray pattern to solid black at 4:1). Also guards the other classic downscale bugs: transparent-pixel color bleed, mean-brightness drift, iterative recompression degradation, and zero-size collapse on extreme aspect ratios. * fix(agent-core): report decoded EXIF-rotated dimensions in ReadMediaFile notes The media note derived its original-dimensions line from the header sniff, which reports pre-rotation values for EXIF orientation 5-8 JPEGs. The sent image and region readback both live in the decoded (rotated) space, so portrait photos got axis-swapped coordinate guidance. Once a decode has happened — compression or crop — its dimensions now overwrite the sniffed ones. * fix(agent-core): improve handling of EXIF orientation in image dimensions and metadata * fix(agent-core): sniff EXIF orientation and step budget fallback through 2000px Two follow-ups to the EXIF and 3000px-cap changes: sniffImageDimensions now reads the JPEG EXIF Orientation tag (pure header parse, both byte orders) and reports display-space dimensions for orientations 5-8. Passthrough images — never decoded — previously kept the pre-rotation header size in compression results and media read notes, disagreeing with the decoded space that region readback uses. encodeWithinBudget steps the over-budget fallback through 2000px before the 1000px last resort. Raising the cap to 3000px had left a regression window: an image whose 2000px encode fits the byte budget was sent at 1000px where the old 2000px cap used to send it at 2000px. * fix(kimi-code): record pasted image dimensions in display space The TUI paste path recorded attachment and original dimensions from its raw header parser, which ignores EXIF orientation. For a portrait JPEG the submit-time caption then contradicted the sent image's aspect and region readback coordinates were axis-swapped. Dimensions now come from the compression result, which reports display space on both the compressed and passthrough paths; parseImageMeta remains only the format/mime gate. * feat(agent-core): add image compression and crop telemetry Every image ingestion path now reports an image_compress event — outcome (compressed / passthrough fast, guard, unsupported, unhelpful, error), input/output formats, byte and pixel sizes, EXIF transposition, and duration — and region readback reports an image_crop event with a failure classification and the region's share of the original area. Wiring is per call site via a new CompressImageOptions.telemetry option, so the outcome split and timing are measured inside the compressor while each caller only names its source: ReadMediaFile (tool construction, like GrepTool), MCP tool results (McpOutputOptions), server prompt ingestion (ICoreProcessService now exposes the host telemetry client), ACP prompts (session track adapter), and TUI paste (host.track adapter). Properties are numeric/enum only — never paths or content — and a throwing client can never affect the compression result. * fix(agent-core): run the full JPEG quality ladder at fallback sizes The fallback rescales encoded only at quality 20, so a JPEG whose ladder failed at the fitted size collapsed straight to the lowest quality even when the smaller size left budget headroom for a higher rung (the realistic window is the 1000px step, where the 4x pixel drop pays for q80/q60). Each fallback edge now walks the same q80-to-q20 ladder as the fitted size. * test: shrink heavy JPEG fixtures and add explicit timeouts The fallback-ladder test runs ~11 pure-JS JPEG encodes and the EXIF paste test decodes, rotates, and re-encodes a 6.5MP frame; both sat at the edge of the 5s vitest timeout on CI runners. Narrower fixtures cut the pixel area (the ladder test keeps its width above 2000px so the full fallback chain still runs) and explicit 15s timeouts absorb runner variance. * fix(server): scope prompt image compression telemetry to the session The prompt-ingestion image_compress events were emitted with the bare host telemetry client, while every agent-side source inherits a session-scoped client — so prompt_inline/prompt_file events could not be correlated with their session. The route now wraps the client with withTelemetryContext({ sessionId }) like rpc/core-impl does for session telemetry. * chore(changeset): consolidate image compression changesets One entry covering the cap raise and the EXIF dimension fix, listed for both the CLI and the SDK so the SDK changelog's compression description (previously pinned at 2000px) stays accurate.
Align progressive tool disclosure with the discard-on-compaction model: compaction no longer rebuilds loaded dynamic tool schemas. The boundary announcement re-lists every loadable name, the model re-selects what it still needs, and a from-memory call to a no-longer-loaded tool is rejected by preflight with select guidance. This removes the keep-all rebuild and its half-trigger budget heuristics entirely: the post-compaction floor is back to users + summary, which is structurally outside the auto-compaction trigger band, and the guard baseline degenerates to summary + reinjected reminders. Every downstream mechanism already treated the empty loaded set as its consistent base state (ledger scan, pending clear at the compaction boundary, deferred extras, preflight wording), so this is a strict simplification. Co-authored-by: fengchenchen <[email protected]>
Headless (`kimi -p`) failures could exit with code 0 when the event loop drained during the shutdown cleanup (e.g. telemetry's unref'd retry backoff when the network is blocked), because the rejection never reached the process.exit(1) call. Set the failure exit code before any await in both the run-prompt catch and the main catch, and keep the cleanup timeout ref'd so the loop stays alive long enough for the rejection to propagate.
Fast catch-up merge; no conflicts. Brings in tool-args JSON Schema format validation (adds ajv/ajv-formats deps), cron tool-source cleanup, and test file tidy. No overlap with the goal-parity work.
It round-tripped restore over a hardcoded local dataset (kimi-code-mini-bench/.vitest-results) that is not in the repo, so it vacuously passed everywhere else. Removed at the original author's request.
…test The fuzz-style invariant test now drives the full v1 fallback ladder ([2000, 1000, 768, 512, 384, 256]) for over-budget inputs, which takes longer than the default 5s boundary in this environment. Give it 30s.
- agent/task/manager.test.ts -> taskManager.test.ts (no manager.ts in agent/task; disambiguate from taskService.test.ts). - app/cron/persist.test.ts -> cronTaskPersistenceService.test.ts (mirrors the module it covers; agent/task/persist.test.ts mirrors agent/task/persist.ts, so it is left as-is). - agent/contextMemory/message.test.ts -> message-history.test.ts (its describe is 'message history (IAgentContextMemoryService)'; the dir already names the domain).
…into tui-v2 # Conflicts: # packages/agent-core-v2/src/index.ts
Fresh TUI startup no longer creates an empty session. The initial render reads config-level defaults (model, context window, permission/plan mode, thinking effort) from the new App-scope-only CoreHarness.getStartupState(), which resolves through IConfigService + IModelResolver without touching the session lifecycle. The session is created lazily on the first user message (sendAfterLazySessionStart), with OAuth failures entering the login-required state instead of failing startup. Model switches without a live session (activateModelSelection, formerly activateModelAfterLogin) now only record the choice in appState instead of creating a session.
|
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 99fe170204
ℹ️ 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".
| if (session === undefined) { | ||
| this.showError(LLM_NOT_SET_MESSAGE); | ||
| // Session-less startup: create the session lazily, then deliver this | ||
| // input as its first turn. | ||
| void this.sendAfterLazySessionStart(text, extraction); | ||
| return; |
There was a problem hiding this comment.
Serialize lazy startup session creation
When a fresh TUI has not created a session yet, every submitted prompt reaches this branch while this.session is still undefined; because the async sendAfterLazySessionStart() is fire-and-forget and no pending-start flag/busy state is set until after createSessionFromCurrentState() resolves, two quick Enter presses can start two independent session creations. The later one will setSession() and close/unload the earlier session while its first prompt may already be sent, dropping the first turn or leaving it in a different session. Please gate this path with a shared pending promise or mark input as busy before awaiting session creation.
Useful? React with 👍 / 👎.
The v2 engine now records `!`-command input/output with the `shell_command` prompt origin and compaction summaries with the `compaction_summary` origin, but the replay renderer had no branches for them and dumped both as plain user messages (raw <bash-*> XML and the full summary text). Restore the v1 render paths in session-replay: - shell_command input replays as the `$ cmd` echo (shellMode color, suppressed bullet); output is unwrapped from the XML tags and formatted through formatBashOutputForDisplay. - compaction_summary replays as the collapsible "Compaction complete" card (compactionData) instead of a plain message; the COMPACTION_SUMMARY_PREFIX marker is stripped via a core re-export. Token counts stay absent until replay reads wire records (G-1).
Resume replay no longer reads the compacted context view. New module src/core/transcript.ts declares a TranscriptModel via v2's public defineDerivedModel and folds it manually over IAgentWireRecordService records (the facade cannot wire.attach — replay runs inside v2 before the facade sees the session, and replay is read once per resume). The fold recovers the full pre-compaction history (user/assistant/tool messages through loop-event folding), emits compaction card entries with summary + token counts from context.apply_compaction records, and maps goal/plan/permission/approval/config ops to their replay records. The display-side TranscriptMessage type mirrors but does not alias ContextMessage, so transcript content can never be fed to the model by accident. Blob references are rehydrated through IAgentBlobService. Entry times stay 0 (wire recordToPayload drops the envelope timestamp); TUI renders by position, so this is safe.
main landed agent-core-v2 + kap-server with breaking changes; this merge rebases the TUI-v2 facade onto them. Resolution: - Shared packages (agent-core-v2, kap-server, minidb, protocol, server-e2e, kimi-web, .agents) take origin/main verbatim; dropped v1 server files and stale old-branch leftovers (old v2 layout files, hash-imports loaders, tsdown plugin wiring) follow main. - apps/kimi-code keeps the tui-v2 migration; main's TUI deltas (media steer items, paste-time [image] max_edge_px, skill/plugin-command placeholder rewrite, userAgent on provider refresh) re-applied onto the v2 surface. Facade adaptations to the new v2 API: - prompt/steer moved off the removed IAgentPromptLegacyService onto IAgentPromptService.enqueue/inject, with wire-shaped parts converted to v2-native ContentParts at the boundary (mirrors kap-server contentToCoreParts). - Approval/MCP payload types derived from the barrel-exported service interfaces; KimiError -> Error2; transcript reducer fold indexes through a string-keyed view of ModelReducers. - CoreHarness gains a sync imageLimits view over the [image] config section for paste-time compression. - ensureMainAgent now goes through IAgentLifecycleService.whenReady; test fixtures updated accordingly. Verified: apps/kimi-code typecheck clean, 2401 unit tests pass (core/tui/cli/feedback/helpers/migration/scripts/utils/native), oxlint clean on changed files, pnpm build OK, CLI boots (0.23.6).
Startup defers session creation to the first message, but command guards still assumed a live session and rejected input with misleading "LLM not set / No active session" errors. - KimiTUI.ensureSession() lazily creates the deferred session (same init path as the first message: runtime activation, dynamic command refresh, event subscription) and hands OAuth failures to the login flow; sendAfterLazySessionStart now builds on it. - State-only commands work without a session by recording the choice in appState, which the lazy creation already reads: /plan (on/off/toggle), /yolo, /auto, and the Shift-Tab plan shortcut. /plan clear stays session-scoped with a plain notice. - Session-bound commands ensure the session on demand instead of erroring: skill and plugin-command activation, /swarm, /btw, /web, /undo, /goal create+resume, /compact, /title, /fork, /export-md, /export-debug, /add-dir. - Ctrl-S with queued/editor input but no session routes the items through the normal send path (fresh input, not steers). - Tests: fake hosts gain ensureSession; tests that relied on synchronous picker mounting flush the async ensure first; the no-session plan/goal cases pin the new appState/abort behavior.
agent-core-v2 now ships SessionInitService.generateAgentsMd (ported from v1: spawns an init-profile child agent and mirrors its run), so the facade forwards instead of throwing NOT_IMPLEMENTED. Closes gap G-6.
CoreSession.cancel() now also calls sessionInit.cancelInit() (a no-op while idle): /init runs outside the main agent's loop turns, so the RPC turn cancel alone could not reach it. Builds on the engine support that landed in #1667.
Slash autocomplete had no skills until the first message created the session, because the catalog is Session-scoped. The v2 engine already exports the App-level pieces for exactly this composition (skillRoots is documented as "exported so the edge can compose a workspace's skills without a Session"): CoreHarness.listStartupSkills merges the builtin and user App-scope sources with projectRoots + skillDiscovery over the startup workDir, honoring the explicitDirs and merge-all-skills config. The full session catalog (plugin skills, explicit/extra dirs) replaces the list as soon as ensureSession lands.
/web (and kimi web) re-execs the CLI entry as the daemon. In dev sessions (pnpm dev:cli) that entry is a TypeScript file previously run under tsx, but spawnDaemonChild dropped the parent's execArgv, so the daemon fell back to Node's strip-only mode and died on the first parameter property (ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX). Forward process.execArgv on the script-entry path only; it is empty for the bundled CLI and must not reach a SEA binary, so prod is unchanged. Verified end to end: with the tsx loader forwarded, server run --daemon from source reaches "daemon ready" and serves /api/v1.
The facade passed a bare randomUUID() for every new session, overriding the lifecycle's canonical session_-prefixed ids (v1 parity). When the caller does not supply an id, create() now receives none and the facade reads the minted id back off the session scope.
|
hope this lazy creation pr will be merged soon ..... so annoyed that so many blank sessions in the list |
Related Issue
No related issue — this lands the
tui-v2work branch ontokimi-code-v2.Problem
The interactive TUI still reached the agent engine through the legacy v1 SDK (
@moonshot-ai/kimi-code-sdk). To move the TUI ontoagent-core-v2, a dedicated facade (apps/kimi-code/src/core/) was introduced.A follow-up problem with the initial migration: fresh TUI startup eagerly created an empty session just to read initial state (default model, context window, modes). That polluted the session list and forced every startup through the full session bootstrap.
What changed
Two commits:
250bd460feat(tui): migrate interactive shell to agent-core-v2apps/kimi-code/src/core/(CoreHarnessat App scope,CoreSessionat session scope); the interactive TUI reaches the engine only through this facade. Print (kimi -p), ACP and other subcommands still consume the v1 SDK.TODO(v2-gap), documented insrc/core/README.md.99fe1702feat(tui): defer session creation to the first message on fresh startupCoreHarness.getStartupState()(IConfigService+IModelResolver, plus the profile service's own thinking resolution).sendAfterLazySessionStart); OAuth login-required errors now surface at first message instead of failing startup.activateModelSelection, formerlyactivateModelAfterLogin) only record the choice in appState — used by both post-login activation and/model.Tests: new
getStartupStateunit tests intest/core/harness.test.ts; TUI startup / message-flow / replay suites adapted to the deferred-creation flow. Full suite: 2365 passed (6 failures intest/cli/telemetryandtest/cli/update/preflightare pre-existing on the base branch, verified by stash comparison).Checklist
gen-changesetsskill, or this PR needs no changeset. — no changeset per the author's call (internal migration branch, not user-facing release content).gen-docsskill, or this PR needs no doc update. — no user-doc impact:/new, resume and startup flags behave identically; only the eagerly-created empty session is gone.