Commit graph

55 commits

Author SHA1 Message Date
_Kerman
bec0b085f2 Merge remote-tracking branch 'origin/kimi-code-v2' into xtr/context-ops-wire
# Conflicts:
#	packages/agent-core-v2/src/agent/contextMemory/contextMemory.ts
#	packages/agent-core-v2/src/agent/goal/goalService.ts
#	packages/agent-core-v2/src/agent/prompt/promptService.ts
#	packages/agent-core-v2/src/agent/systemReminder/systemReminder.ts
2026-07-04 18:14:31 +08:00
_Kerman
c0c9f155da fix: restore prompt id in server-v2 snapshots 2026-07-04 17:14:50 +08:00
_Kerman
3665c7da37 Merge remote-tracking branch 'origin/kimi-code-v2' into xtr/context-ops-wire
# Conflicts:
#	packages/agent-core-v2/src/agent/contextMemory/messageId.ts
#	packages/agent-core-v2/src/agent/goal/goalService.ts
2026-07-04 16:29:30 +08:00
_Kerman
0d8b9f96ef refactor: remove promptMessageId from turn lifecycle
Turn no longer carries or emits the triggering message id; prompt and goal
callers keep message identity in context memory instead.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-04 16:24:17 +08:00
_Kerman
0491b06339 refactor: route v2 context changes through context ops 2026-07-04 16:14:30 +08:00
haozhe.yang
bcc9bc095f refactor(agent-core-v2): drop ISessionAgentFileSystem, use os layer
- remove the ISessionAgentFileSystem service and its node implementation
- extend IHostFileSystem with readText decode options and stat mtimeMs/ino
- route SessionFsService, profile context, media, and plan through IHostFileSystem
- drop the unused agentFs:* session REST endpoints from server-v2/server-e2e
2026-07-03 21:08:00 +08:00
haozhe.yang
33fbbcb451 Merge remote-tracking branch 'origin/kimi-code-v2' into kimi-code-v2 2026-07-03 17:54:05 +08:00
_Kerman
030cf793d5 refactor: task instead of background task 2026-07-03 16:57:46 +08:00
haozhe.yang
b05c30e705 refactor(cron): consolidate cron domain into app/cron
- add app/cron barrel re-exporting the cron task record, persistence contract/service, and dependency-free algorithm lib (cron-expr, jitter, clock, format)
- move cronTask persistence files from app/cronPersistence into app/cron and drop the old cronPersistence barrel
- register the cron config section (KIMI_CRON_* env bindings) via configSection
- repoint cron tests from #/agent/cron and #/app/cronPersistence to #/app/cron
2026-07-03 16:53:54 +08:00
haozhe.yang
6c0527cb6a refactor(agent-core-v2,server-v2): merge terminal backend into HostTerminalService
- Remove ITerminalBackend abstraction and NotImplementedTerminalBackend
- Move node-pty spawn logic into IHostTerminalService implementation
- Drop server-v2 direct node-pty dependency (now via agent-core-v2)
- Update tests and server-v2 wiring to use IHostTerminalService directly
- Rewrite server-v2 terminal test model seed after model resolver refactor
2026-07-03 13:37:46 +08:00
haozhe.yang
b2cb0c7ede refactor: rename store services to domain-specific terms
- rename ToolStore to ToolState
- rename CronTaskStore to CronTaskPersistence
- rename SkillCatalogStore to SkillDiscovery
- rename WorkspaceStore to WorkspacePersistence
- rename IFileStore to IFileService and update server call sites
2026-07-03 13:27:32 +08:00
haozhe.yang
d3bf5646ea refactor(agent-core-v2): remove SessionService facade and move lifecycle to App scope
- remove Session-scoped ISessionService/SessionService facade
- move archive, fork, and scope addressing into App-scoped ISessionLifecycleService
- add scope() helper to ISessionContext and bootstrap sessionScope/sessionDir helpers
- update agent-core-dev skill docs and AGENTS.md examples
- add events.example.ts for IEventService soft coupling
- update server-v2 action map and server-e2e session resource for archive path
2026-07-02 21:36:00 +08:00
haozhe.yang
61ef35b302 feat(server-e2e): add typed v2 ServerClient SDK with drift test
- add ServerClient under src/v2: typed /api/v2 resource tree over HTTP
  plus events over WebSocket, with core/session/agent scopes and a v1
  escape hatch for the legacy REST surface
- add resource modules (core/session/agent/events), a manifest mirroring
  the server-v2 actionMap, shared types, and transport (HttpRpc,
  rpcProxy, V2Socket)
- expose @moonshot-ai/server-v2/contract (actionMap + channel helpers)
  so the SDK drift test stays in lockstep with the server surface
- add an in-process smoke test and the vitest raw-text/hash-imports
  plugins needed to import server-v2 source from the e2e tests
- add optional bearer token support to the legacy HttpClient and document
  the two-client package layout
2026-07-02 01:06:16 +08:00
haozhe.yang
6633fcdd04 Merge remote-tracking branch 'origin/kimi-code-v2' into kimi-code-v2 2026-07-01 23:21:14 +08:00
haozhe.yang
4571edf90a refactor(agent-core-v2): extract SessionBtwService for btw
- add Session-scoped ISessionBtwService/SessionBtwService that forks the
  main agent into a side-question child agent (tools disabled,
  side-channel reminder) via IAgentLifecycleService.fork('main')
- remove startBtw from AgentAPI (core-api) and ISessionLegacyService;
  the server-v2 POST /sessions/{id}/btw route now resolves
  ISessionBtwService directly
- add a unit test for SessionBtwService
2026-07-01 22:54:24 +08:00
haozhe.yang
d4a6a20db8 feat(agent-core-v2): add scope-typed IScopeHandle aliases
- make IScopeHandle generic over LifecycleScope and add IAppScopeHandle /
  ISessionScopeHandle / IAgentScopeHandle so session and agent handles cannot
  be passed to each other's parameters at compile time
- thread the aliases through IAgentLifecycleService / ISessionLifecycleService
  and their consumers (sessionLegacy, messageLegacy, server-v2 mainAgent and
  skills), narrowing at the lifecycle boundary
- dep-graph viewer: render scope-mismatch (token registered at a scope the
  caller cannot see) distinctly from a genuinely missing implementation
2026-07-01 22:45:48 +08:00
haozhe.yang
fff2babe42 refactor(agent-core-v2): merge event sink into IAgentRecordService
- add IAgentRecordService: append(record) fans out to durable persistence,
  live broadcast, and replay capture via per-type facets
  (toLive/toReplay/resume/blobs); signal(event) emits live-only events
- remove IAgentEventSinkService; fold live emission into IAgentRecordService
- migrate all agent domains to record.append/signal/define
- server-v2 subscribes to agent events via IAgentRecordService
- delete dead createLoopEventDispatcher
- AgentRecordMap extends WireRecordMap so record types stay on WireRecordMap
2026-07-01 22:38:25 +08:00
_Kerman
186ed6eaa5 feat: implement goal core workflow 2026-07-01 21:29:51 +08:00
haozhe.yang
760808abd9 feat(server-v2): add model catalog auto-refresh and remaining wiring
- add config-driven model catalog refresh scheduler (interval / on-start)
- refresh all providers and add the single-provider refresh endpoint
- broadcast model_catalog.changed to session subscribers
- finish wiring route handlers, middleware, and auth services
- align route and websocket tests with the authenticated server model
2026-07-01 13:02:26 +08:00
haozhe.yang
4d103c5d76 feat(server-v2): add auth and request security hardening
- add persistent bearer-token auth (token store, credentials, password hashing)
- gate HTTP and WebSocket (bearer subprotocol) upgrades behind auth
- classify loopback vs non-loopback binds and validate hostnames/origin
- add rate limiting and security headers middleware
- add GUI store service and routes
- add process file locking
2026-07-01 11:44:20 +08:00
haozhe.yang
cd47ef4aff refactor(agent-core-v2): rename scoped services to encode scope
- rename service interfaces and implementations to carry the Session/Agent
  scope prefix and Service suffix (e.g. IApprovalService ->
  ISessionApprovalService, ApprovalService -> SessionApprovalService)
- rename LifecycleScope.Core to App in the DI base
- update DI createDecorator keys to match the new identifiers
- propagate the renames through server-v2 routes/transport, examples, docs,
  and the agent-core-dev skill
2026-07-01 01:05:53 +08:00
haozhe.yang
6219fa6866 feat(agent-core-v2): give ContextMessage a stable id
- stamp `msg_<ulid>` on every message entering IContextMemory and persist it
  in the context.splice wire record, so ids survive restore
- carry the provider response id as `providerMessageId` on assistant messages
- thread `promptMessageId` from prompt -> turn -> turn.started ->
  InFlightTurnTracker, so snapshot `current_prompt_id` comes from the native
  path instead of post-hoc enrichment
- project real ids on the wire and look up messages by id; drop the positional
  parseMessageId
- make the v1 prompt_id equal its user message id
2026-06-30 21:25:01 +08:00
haozhe.yang
db3a7c4f43 fix(server-v2): serve cold session messages from wire transcript
- add MessageLegacyService (agent-core-v2 L7 edge adapter) implementing the
  v1 GET /sessions/{sid}/messages contract on top of the native services
- cold sessions: load + restore the main agent wire log and read the full
  transcript from IReplayBuilderService; live sessions keep reading
  IContextMemory
- rewrite the messages route as a thin adapter over the legacy service
- register the message.not_found (40403) error code in protocol and
  agent-core-v2
2026-06-30 21:02:23 +08:00
haozhe.yang
37d3953368 fix(server-v2): align /sessions/:tail actions with v1
- forward undo and archive results from ISessionLegacyService instead of
  re-paginating undo in the route and hardcoding the archive response
- drop the AUTH_TOKEN_MISSING error mapping that v1 does not declare
- move the ContextMessage -> Message projection into agent-core-v2 so
  the session legacy service owns the undo response shape
2026-06-30 20:11:42 +08:00
haozhe.yang
05053ee845 fix(server-v2): align GET /api/v1/auth with v1 readiness summary
The v2 readiness probe returned a simplified snapshot: default_model was
hardcoded to null, providers_count counted only oauth providers, and
managed_provider was synthesized from any authenticated provider. Mirror
v1's AuthSummaryService.get() through a new L7 edge adapter.

- add IAuthLegacyService projecting provider/config/oauth state into the
  v1 AuthSummary wire shape; the native IAuthSummaryService keeps serving
  /api/v2 untouched
- default_model reads the configured defaultModel
- providers_count counts every configured provider
- managed_provider reflects managed:kimi-code cached-token state and is
  null when that provider is absent
- ready matches v1 (providers >= 1, default model set, not revoked)
- register authLegacy at L7 in the domain-layer map
2026-06-30 19:54:43 +08:00
haozhe.yang
2fc1fbc648 fix(server-v2): resolve workspace branch from .git/HEAD
- read .git/HEAD and peel ref: refs/heads/<branch> to populate branch
- resolve the real git dir through a .git worktree/submodule file
- keep detached HEAD and unreadable files as branch: null
- add branch-resolution tests for slash branches, detached HEAD, and worktrees
2026-06-30 19:30:17 +08:00
haozhe.yang
c43177019c feat(server-v2): add session children and warnings endpoints
- surface custom metadata in session index summaries so child sessions can be filtered without per-session document reads
- add ISessionLegacyService.createChild/listChildren: children are forks tagged with parent_session_id + child_session_kind, listed by those markers
- wire GET/POST /sessions/{id}/children and GET /sessions/{id}/warnings, reusing the protocol schemas and mapping session.not_found / session.fork_active_turn
- register the sessionLegacy domain at L7 in the domain-layer check
2026-06-30 18:47:01 +08:00
haozhe.yang
b94c60d50a feat(server-v2): add /api/v1/ws with seq/epoch watermark and resync
Bring the v1 WebSocket protocol to server-v2 so web clients get gap-free
sync across reconnects instead of silently losing events.

- per-session durable event journal with monotonic seq + epoch, recovered
  across restarts
- SessionEventBroadcaster: single per-session fan-out, durable/volatile
  classification, and cursor-based replay (buffer_overflow / epoch_changed)
- WsConnectionV1: client_hello / subscribe with cursors, replay or
  resync_required, and ack carrying authoritative server cursors
- GET /sessions/:id/snapshot: atomic-at-a-watermark state and in-flight turn
- IAgentLifecycleService: onDidCreate / onDidDispose for agent discovery
- GET /connections: list live WebSocket clients
2026-06-30 18:47:01 +08:00
haozhe.yang
d210009877 feat(server-v2): port v1 /sessions/{tail} action routes
- implement SessionLifecycleService.fork (active-turn guard, per-agent
  wire-log copy, metadata rewrite, forked marker, closed-session fork)
- add SessionLegacyService edge adapter for compact/undo/abort/btw over
  the native v2 services
- persist agent transcripts via per-agent homedir and extend SessionMeta
  (isCustomTitle/lastPrompt/agents/custom) for fork parity
- add aborted session status and IWireRecord.getRecords()
- register session.undo_unavailable error code
- dispatch all six /sessions/{tail} actions with v1 error mapping and
  emit session.created on create/fork
2026-06-30 18:47:01 +08:00
haozhe.yang
ce0e4f2589 feat(server-v2): expose /openapi.json via @fastify/swagger
- register @fastify/swagger before routes and serve GET /openapi.json
- add v2-specific openapi transform for multipart upload, binary downloads, and the fs-action/question oneOf dispatchers
- project the session-action dispatcher into archive only (v2 registers a subset of v1 routes)
- reuse protocol wire schemas, no inline re-declaration
2026-06-30 18:47:01 +08:00
haozhe.yang
83b93eca64 feat(server-v2): port v1 terminals REST routes
- add /sessions/{session_id}/terminals routes (list/create/get/close)
  mirroring packages/server, backed by the Session-scoped ITerminalService
- add node-pty ITerminalBackend overriding the agent-core-v2 stub
- map session/terminal not-found and cwd-escape to protocol error codes
2026-06-30 14:55:05 +08:00
haozhe.yang
adaa4de0a8 feat(server-v2): port v1 /sessions/:sid/skills routes
- add GET /sessions/{session_id}/skills and POST .../{name}:activate, mirroring the v1 wire contract and protocol schemas
- gate both endpoints on activated (live) sessions via ISessionLifecycleService; when persisted but not live, return 40401 with a "you need to activate it first" hint
- resolve ISkillCatalog for listing and the main agent's IAgentSkillService for activation; map skill.not_found to 40415 and skill.type_unsupported to 40912
- export IAgentSkillService and ISkillCatalog from agent-core-v2
2026-06-30 14:30:53 +08:00
haozhe.yang
f3ebc1e2a7 feat(server-v2): port v1 session fs routes
- expose /api/v1/sessions/{sid}/fs:* mirror routes backed by the
  Session-scoped IFsService (list, read, list_many, stat, stat_many,
  mkdir, search, grep, git_status, diff, open, open-in, reveal) plus the
  fs/{path}:download stream
- extend agent-core-v2 IFsService with list/read/stat/mkdir/resolve
  methods and add fs.is_directory/is_binary/too_large/already_exists
  error codes (protocol KimiErrorCode + FsErrors)
- seed IWorkspaceContext with the session work dir in session-lifecycle
  so workspace-relative services resolve paths against the session root
- port fileLaunch lib for open/reveal/open-in
2026-06-30 14:19:18 +08:00
haozhe.yang
69084ab683 refactor(agent-core-v2): move managed OAuth model refresh into OAuthService
- IOAuthService/OAuthService now owns refreshOAuthProviderModels: the managed
  OAuth provider's credential provisioning and server-side model refresh live
  together in the auth domain.
- modelCatalog is back to a read-only catalog projection (listModels,
  listProviders, getProvider, setDefaultModel); the OAuth refresh method and
  its helpers are removed.
- server-v2 /providers:refresh_oauth route and the oauth example resolve
  IOAuthService for the refresh.
- Move the refresh tests into test/auth and add the auth --> config edge to
  the DI scope diagram.
2026-06-30 14:12:22 +08:00
haozhe.yang
9076f55643 refactor(agent-core-v2): add kaos domain for execution environment
- Add `kaos` domain (`IKaos` per session + `IKaosFactory`) wrapping
  `@moonshot-ai/kaos`, so business code imports `#/kaos` instead of the
  package directly.
- Back `agentFs` and `process` with `IKaos`; drop the per-domain
  `IFileSystemBackend` / `IProcessBackend` interfaces and their
  local/ssh stubs.
- Migrate `read-media`, `path-access`, `background/process-task`, and
  `bootstrap` off direct kaos-package imports.
- Seed `IKaos` per session in `SessionLifecycleService` and expose
  `agentFs` / `fs` on the server-v2 action map.
- Create the server-v2 main agent on demand (`ensureMainAgent`)
  instead of failing requests when it is missing.
2026-06-30 12:17:09 +08:00
haozhe.yang
d4f9933b92 fix(server-v2): serve v1 fs browse/home on distinct routes
- replace the `/fs:action` parametric dispatcher with two routes that
  mirror v1 (`/fs::browse`, `/fs::home`), so the wire path is the
  single-colon `/api/v1/fs:browse` and `/api/v1/fs:home` that v1 serves
- update the folder-picker test to hit the single-colon URLs and assert
  the double-colon form 404s, guarding against reintroducing the
  parametric dispatcher
2026-06-30 12:11:31 +08:00
haozhe.yang
01509910a7 refactor(storage): give each storage role token its own FileStorageService
- bootstrap: storageSeed() now returns a per-token SyncDescriptor so
  IStorageService / IAppendLogStorage / IAtomicDocumentStorage / IBlobStorage
  each resolve to a distinct FileStorageService rooted at homeDir, instead of
  sharing one instance. Keeps the roles independently routable.
- server-v2: drop the now-redundant durableStorageSeeds and rely on bootstrap()
  for file-backed storage.
- add a regression test asserting the four tokens are distinct instances.
2026-06-30 11:06:57 +08:00
haozhe.yang
053ee9a150 feat(server-v2): add sessions tasks api/v1 endpoints
Port the v1 server's `/sessions/{sid}/tasks*` REST surface onto
agent-core-v2:

- GET /sessions/{sid}/tasks — list with optional `status` filter
- GET /sessions/{sid}/tasks/{tid} — get by id with optional
  `with_output` / `output_bytes` preview
- POST /sessions/{sid}/tasks/{tid}:cancel — cancel with the
  idempotent 40904 `{cancelled:false}` shape

The routes resolve the main agent's `IBackgroundService` through the
core -> session -> agent scope chain and project `BackgroundTaskInfo`
onto the protocol `BackgroundTask`, matching the v1 wire contract
(schemas, error codes, and messages). The `:cancel` suffix is parsed
via the shared `parseActionSuffix` helper.
2026-06-30 10:26:12 +08:00
haozhe.yang
b0c8aa8821 feat(server-v2): return turn ids for prompt actions
Return turn_id from agent prompt and steer RPC/gateway methods, route
prompt submit/steer/undo/clear/cancel through IAgentRPCService in the
server-v2 action map, and cover prompt submission and missing-agent errors.
2026-06-29 21:23:53 +08:00
haozhe.yang
96cb9c4dc8 feat(agent-core-v2): track recently resolved interactions
Add createdAt to parked interactions and keep a bounded recently-resolved
ledger so edge transports can distinguish duplicate resolves from unknown
ids. Cover the server-v2 approval duplicate-resolve path.
2026-06-29 21:22:55 +08:00
haozhe.yang
3e4d92fc6d refactor(agent-core-v2): split model runtime from kosong domain
Replace the kosong domain with chatProvider, model, and modelRuntime
services, move model alias config and env overlay into model, and update
profile and LLM requester to resolve providers through IModelResolver and
IChatProviderFactory.
2026-06-29 21:22:41 +08:00
haozhe.yang
7d04f4f7dd feat(server-v2): add fs::browse and fs::home folder picker routes
- implement GET /api/v1/fs::browse and /api/v1/fs::home, matching the
  packages/server v1 wire contract (directory-only entries, git metadata,
  dot-last sorting, parent resolution, $HOME + recent workspace roots)
- complete IHostFolderBrowser in agent-core-v2: realpath resolution, git
  detection, recent_roots from IWorkspaceRegistry, and HostFolder* domain
  errors mapped to protocol codes 40001/40409/40411
- register the routes behind a /fs:action semi-static path because
  find-my-way cannot register the literal /fs::browse / /fs::home paths
2026-06-29 21:17:43 +08:00
haozhe.yang
e083b923e5 feat(server-v2): add /api/v1 tools and MCP server routes
- GET /tools, GET /mcp/servers, POST /mcp/servers/{id}:restart
- resolve IToolRegistry / IMcpService from the most-recent session's
  main agent; empty list / 40408 when no session is live
- project v2 models to the protocol wire shapes, matching
  packages/server (source/status mapping, mcp_server_id, null input_schema)
2026-06-29 21:15:29 +08:00
haozhe.yang
55060e3942 feat(server-v2): port v1 /files routes
- add agent-core-v2 filestore domain (IFileStore) streaming blobs through IBlobStorage
- expose POST/GET/DELETE /api/v1/files (multipart upload, binary download, delete)
- map file errors to 40407/41301 envelopes; add unit + e2e coverage
2026-06-29 21:06:59 +08:00
haozhe.yang
a7a2708aee feat(server-v2): port v1 /sessions/:sid/prompts routes
- add PromptLegacyService (per-agent v1 scheduler: prompt_id, FIFO queue, steer/abort, auto-start-next) on top of IPromptService
- register prompt.not_found / session.busy / prompt.already_completed error codes in protocol and agent-core-v2
- expose GET/POST /api/v1/sessions/:sid/prompts, prompts::steer, prompts/:pid:abort|:steer
2026-06-29 20:59:02 +08:00
haozhe.yang
7c91ffc876 feat(server-v2): port v1 /sessions/:sid/questions routes
- add GET /sessions/:sid/questions (list pending) and POST
  /sessions/:sid/questions/:tail (resolve + :dismiss) on top of
  IQuestionService / IInteractionService
- enrich the agent-core-v2 question domain with the rich in-process
  model (QuestionItem / QuestionResult) and dismiss() so the v1 wire
  can be projected faithfully
- reimplement the protocol <-> in-process adapter at the edge (no v1
  agent-core import): synthesized item/option ids, allow_other,
  expires_at, and the 5-kind answer flattening
2026-06-29 20:44:28 +08:00
haozhe.yang
bca247b463 feat(server-v2): port v1 /sessions/:sid/messages routes
- add GET /sessions/{sid}/messages (paginated, role-filtered) and GET /sessions/{sid}/messages/{message_id}
- thin wrapper over the main agent's IContextMemory, already exposed in the v2 action map
- port v1 id derivation, content mapping, pagination and role-filter semantics
- register the routes under /api/v1 and cover with tests
2026-06-29 20:36:09 +08:00
haozhe.yang
420cefbc02 feat(server-v2): add model and provider catalog endpoints
- add Core-scoped IModelCatalogService in agent-core-v2 covering
  listModels, listProviders, getProvider, setDefaultModel, and
  refreshOAuthProviderModels
- expose the v1-compatible /api/v1 models and providers catalog routes
  in server-v2, mapping provider.not_found / model.not_found to the
  numeric protocol error codes
- add IOAuthService.getCachedAccessToken for provider status detection
- register provider.not_found and model.not_found protocol error codes
2026-06-29 20:10:12 +08:00
haozhe.yang
fc801c9ea0 feat(server-v2): port v1 approvals and workspaces routes
- add `/sessions/{sid}/approvals` GET (list pending) and POST (resolve)
  routes, backed by IApprovalService and IInteractionService; duplicate
  resolves return 40902 via the kernel's recently-resolved window
- add `/workspaces` GET / POST / PATCH / DELETE routes, backed by
  IWorkspaceRegistry, projecting v2 workspace records onto the v1 wire shape
- register both route groups in registerApiV1Routes
- add an agent-core-v2 interaction example that resolves the Session-scoped
  kernel and approval/question facades through the scope tree
2026-06-29 19:26:30 +08:00
haozhe.yang
f08840f4ca feat(server-v2): expose workspaces update action on v2 RPC
- map `workspaces:update` to IWorkspaceRegistry.update in the core actionMap
- cover the rename round-trip in rpc.test.ts
- sync the edge-exposure cheatsheet
2026-06-29 19:02:30 +08:00