merge: hapi upstream main 2026-10-19 (34 commits past v0.30.7)

Bring in the post-0.30.7 upstream work while keeping local team, macaron,
requirement, DSH and deployment features:

- runner/hub: cross-platform orphan reap on archive and tracking loss,
  machine-spawn preallocated stubs, keepalive-only sessions reconcile to idle
- hub: prepared-statement cache, stale/canceled permission request handling
- cli: Codex compaction announcements, dynamic Kimi models, MCP bridge reap
- web: session toolbar icon shedding, mark-all-read, unread/active sections,
  Russian locale, external-link preference, 48px search chrome
- ios/android: locale and font-size updates

Conflict resolution keeps local-only behavior (agent team spawns, macaron
skins, collapsible sidebar, workspace markdown images) layered on the new
upstream toolbar and session lifecycle plumbing.

Test infrastructure: skip the Docker-only pwsh integration test quickly when
Docker is unavailable, and exclude the Bun-only usageScan test from vitest.

via [HAPI](https://hapi.run)

Co-Authored-By: HAPI <noreply@hapi.run>
Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
2026-10-23 12:44:05 +08:00
co-authored by HAPI Claude Code
279 changed files with 23126 additions and 1620 deletions
@@ -30,7 +30,8 @@ export async function runCursorAcpModelProbe(cwd?: string): Promise<ListCursorMo
const response: ListCursorModelsResponse = {
success: true,
availableModels: snapshot.availableModels,
currentModelId: snapshot.currentModelId
currentModelId: snapshot.currentModelId,
...(snapshot.parameterized ? { parameterized: true } : {})
};
if (!hasAcpWireCatalog(response)) {
return { success: false, error: 'Cursor ACP catalog has no wire model ids' };
@@ -273,6 +273,50 @@ describe('listCursorModels', () => {
expect(spawnMock).not.toHaveBeenCalled()
})
test('attaches variant cliModelSkus to parameterized bare base catalogs (#1818)', async () => {
vi.mocked(isAgentAcpTransportActive).mockReturnValue(true)
const bareCatalog = [
{ modelId: 'composer-2.5', name: 'Composer 2.5' },
{ modelId: 'claude-opus-4-8', name: 'Claude Opus 4.8' },
{ modelId: 'grok-4.6', name: 'Cursor Grok 4.6' }
]
setCursorAcpModelsSnapshot({
availableModels: bareCatalog,
currentModelId: 'composer-2.5',
parameterized: true
})
writeSharedCursorModelsCache({
success: true,
parameterized: true,
availableModels: bareCatalog,
currentModelId: 'composer-2.5',
cliModelSkus: [
{ modelId: 'composer-2.5', name: 'Composer 2.5' },
{ modelId: 'composer-2.5-fast', name: 'Composer 2.5 Fast' },
{ modelId: 'claude-opus-4-8-low', name: 'Claude Opus 4.8 Low' },
{ modelId: 'cursor-grok-4.6-high', name: 'Cursor Grok 4.6' }
]
})
const result = await listCursorModels()
expect(result.availableModels?.map((row) => row.modelId)).toEqual([
'composer-2.5',
'claude-opus-4-8',
'grok-4.6'
])
// Parameterized ACP sessions apply fast/effort over config options, so the
// spawn-safe variant skus stay attached to their bare base rows — including
// CLI skus that keep Cursor's legacy `cursor-` family prefix.
expect(result.cliModelSkus?.map((row) => row.modelId)).toEqual([
'composer-2.5',
'composer-2.5-fast',
'claude-opus-4-8-low',
'cursor-grok-4.6-high'
])
expect(spawnMock).not.toHaveBeenCalled()
})
test('enriches live ACP snapshot with fuller shared cliModelSkus while lock is active', async () => {
vi.mocked(isAgentAcpTransportActive).mockReturnValue(true)
setCursorAcpModelsSnapshot({
+18 -12
View File
@@ -18,6 +18,7 @@ import {
import {
cursorCliSkuBaseId,
cursorModelBaseId,
cursorModelBaseMatches,
isCursorAcpCatalogModelId,
isCursorAcpWireModelId
} from '@hapi/protocol';
@@ -31,6 +32,7 @@ export function buildCursorModelsSeedPayload(
availableModels: CursorModelSummary[];
currentModelId: string | null;
cliModelSkus?: readonly CursorModelSummary[];
parameterized?: boolean;
},
shared?: CursorModelsResponse | null
): ListCursorModelsResponse {
@@ -42,6 +44,7 @@ export function buildCursorModelsSeedPayload(
success: true,
availableModels: snapshot.availableModels,
currentModelId: snapshot.currentModelId,
...(snapshot.parameterized ? { parameterized: true } : {}),
...(cliModelSkus.length > 0 ? { cliModelSkus } : {})
};
}
@@ -68,9 +71,9 @@ function filterCliSkusForWireBases(
cliSkus: CursorModelSummary[],
wires: CursorModelSummary[]
): CursorModelSummary[] {
const wireBases = new Set(
wires.map((entry) => cursorModelBaseId(entry.modelId)).filter((base) => base.length > 0)
);
const wireBases = wires
.map((entry) => cursorModelBaseId(entry.modelId))
.filter((base) => base.length > 0);
return cliSkus.filter((entry) => {
const modelId = entry.modelId.trim();
@@ -78,7 +81,8 @@ function filterCliSkusForWireBases(
if (!modelId || modelId === 'auto' || isCursorAcpWireModelId(modelId)) {
return false;
}
return wireBases.has(cursorCliSkuBaseId(modelId));
const skuBase = cursorCliSkuBaseId(modelId);
return wireBases.some((base) => cursorModelBaseMatches(skuBase, base));
});
}
@@ -87,22 +91,24 @@ function attachCliSkusToResponse(
cliSkus: readonly CursorModelSummary[]
): ListCursorModelsResponse {
const wires = (response.availableModels ?? []).filter((entry) => isCursorAcpCatalogModelId(entry.modelId));
// Suffixed CLI variants (effort/speed) only apply when ACP exposes parameterized
// wires for that base. Bare-only catalogs cannot express those variants
// (apply path is model + fast at most), so attaching them creates dead picker rows.
const parameterizedBases = new Set(
wires
// Variant skus are only usable when the ACP apply path can express them:
// parameterized pickers apply model + fast + thought_level over config options,
// and wire catalogs already pair each variant with a base wire. Bare-only
// catalogs without the parameterized picker keep base rows only.
const applyableBases = (response.parameterized === true
? wires.map((entry) => cursorModelBaseId(entry.modelId))
: wires
.filter((entry) => isCursorAcpWireModelId(entry.modelId))
.map((entry) => cursorModelBaseId(entry.modelId))
.filter((base) => base.length > 0)
);
).filter((base) => base.length > 0);
const filtered = filterCliSkusForWireBases(
mergeCliModelSkus(response.cliModelSkus ?? [], [...cliSkus]),
wires
).filter((entry) => {
const modelId = entry.modelId.trim();
const base = cursorCliSkuBaseId(modelId);
return modelId === base || parameterizedBases.has(base);
return modelId === base
|| applyableBases.some((candidate) => cursorModelBaseMatches(base, candidate));
});
if (filtered.length === 0) {
return response.cliModelSkus?.length
@@ -1,5 +1,5 @@
import { afterAll, afterEach, describe, expect, test } from 'vitest';
import { mkdtempSync, rmSync } from 'node:fs';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
@@ -59,4 +59,21 @@ describe('cursorModelsSharedCache', () => {
expect(readSharedCursorModelsCache()?.cliModelSkus).toEqual(payload.cliModelSkus);
});
test('ignores pre-versioned cache files that carry synthesized wire ids', () => {
// v1 files carried `[fast=…]` wires Cursor rejects; a runner must re-probe
// instead of serving them forever (listCursorModels trusts the cache).
mkdirSync(join(testHapiHome, 'cache'), { recursive: true });
writeFileSync(
join(testHapiHome, 'cache', 'cursor-models.json'),
JSON.stringify({
success: true,
availableModels: [{ modelId: 'grok-4.6[fast=false]', name: 'Cursor Grok 4.6' }],
currentModelId: 'grok-4.6[fast=false]'
}),
'utf8'
);
expect(readSharedCursorModelsCache()).toBeNull();
});
});
@@ -18,6 +18,18 @@ function isUsableModelsResponse(response: CursorModelsResponse | null): response
);
}
/**
* Bumped when a cached catalog can no longer be trusted. v1 carried synthesized
* `[fast=…]` wire ids that Cursor rejects at `session/new`; `listCursorModels`
* serves the on-disk cache without re-probing, so stale entries must not be read.
*/
const SHARED_CACHE_VERSION = 2;
type SharedCacheEnvelope = {
version: number;
response: CursorModelsResponse;
};
/** Cross-process catalog for New Session while an ACP lock blocks `agent --list-models`. */
export function readSharedCursorModelsCache(): CursorModelsResponse | null {
const path = getSharedCachePath();
@@ -26,8 +38,12 @@ export function readSharedCursorModelsCache(): CursorModelsResponse | null {
}
try {
const parsed = JSON.parse(readFileSync(path, 'utf8')) as CursorModelsResponse;
return isUsableModelsResponse(parsed) ? parsed : null;
const parsed = JSON.parse(readFileSync(path, 'utf8')) as Partial<SharedCacheEnvelope> | null;
if (!parsed || parsed.version !== SHARED_CACHE_VERSION) {
return null;
}
const response = parsed.response ?? null;
return isUsableModelsResponse(response) ? response : null;
} catch {
return null;
}
@@ -41,7 +57,8 @@ export function writeSharedCursorModelsCache(response: CursorModelsResponse): vo
const path = getSharedCachePath();
try {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, JSON.stringify(response), 'utf8');
const envelope: SharedCacheEnvelope = { version: SHARED_CACHE_VERSION, response };
writeFileSync(path, JSON.stringify(envelope), 'utf8');
} catch {
// Best effort — in-process cache still works in the session child.
}
@@ -0,0 +1,135 @@
import { EventEmitter } from 'node:events'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
const { spawnMock } = vi.hoisted(() => ({ spawnMock: vi.fn() }))
vi.mock('node:child_process', () => ({ spawn: spawnMock }))
vi.mock('@/ui/logger', () => ({
logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() }
}))
vi.mock('@/kimi/utils/config', () => ({
readKimiLocalConfig: () => ({ model: 'GLM-5.3-flash' })
}))
import { _resetKimiModelsCacheForTests } from '../kimiModels'
import { registerKimiSessionModelHandlers } from './kimiModels'
class FakeChild extends EventEmitter {
stdout = new EventEmitter()
stderr = new EventEmitter()
kill = vi.fn()
}
/** Real `kimi provider list --json` shape, including fields HAPI must strip. */
const PROVIDER_PAYLOAD = JSON.stringify({
providers: {
thehive: {
baseUrl: 'https://api.thehive.example/v1',
type: 'openai',
apiKey: 'sk-secret-thehive-key'
}
},
models: {
'GLM-5.3-flash': {
provider: 'thehive',
model: 'zai-org/glm-5.3-flash',
displayName: 'thehive / GLM-5.3-flash',
capabilities: ['tool_use']
}
}
})
function registerSessionHandlers(cwd: string): (params: unknown) => Promise<unknown> {
const handlers = new Map<string, (params: unknown) => Promise<unknown>>()
const rpcHandlerManager = {
registerHandler: (method: string, handler: (params: unknown) => Promise<unknown>) => {
handlers.set(method, handler)
}
} as unknown as RpcHandlerManager
registerKimiSessionModelHandlers(rpcHandlerManager, () => cwd)
const handler = handlers.get(RPC_METHODS.ListKimiModels)
if (!handler) {
throw new Error(`session handler ${RPC_METHODS.ListKimiModels} was not registered`)
}
return handler
}
beforeEach(() => {
spawnMock.mockReset()
_resetKimiModelsCacheForTests()
})
describe('registerKimiSessionModelHandlers', () => {
it('answers the catalog over the session connection without a runner', async () => {
const handler = registerSessionHandlers('/work/project')
const child = new FakeChild()
spawnMock.mockImplementation(() => child)
const pending = handler(undefined)
child.stdout.emit('data', PROVIDER_PAYLOAD)
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: true,
availableModels: [{
modelId: 'GLM-5.3-flash',
name: 'thehive / GLM-5.3-flash',
provider: 'thehive'
}],
currentModelId: 'GLM-5.3-flash'
})
expect(spawnMock).toHaveBeenCalledWith(
'kimi',
['provider', 'list', '--json'],
expect.any(Object)
)
})
it('returns only modelId, name and provider — never provider credentials', async () => {
const handler = registerSessionHandlers('/work/project')
const child = new FakeChild()
spawnMock.mockImplementation(() => child)
const pending = handler(undefined)
child.stdout.emit('data', PROVIDER_PAYLOAD)
child.emit('close', 0, null)
const response = await pending
const serialized = JSON.stringify(response)
expect(serialized).not.toContain('sk-secret-thehive-key')
expect(serialized).not.toContain('api.thehive.example')
expect(serialized).not.toContain('baseUrl')
expect(serialized).not.toContain('capabilities')
expect(serialized).not.toContain('zai-org/glm-5.3-flash')
expect(Object.keys((response as { availableModels: Array<object> }).availableModels[0]!).sort())
.toEqual(['modelId', 'name', 'provider'])
})
it('reports a malformed probe as a failed response instead of throwing', async () => {
const handler = registerSessionHandlers('/work/project')
const child = new FakeChild()
spawnMock.mockImplementation(() => child)
const pending = handler(undefined)
child.stdout.emit('data', '{"models":')
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'kimi provider list produced invalid JSON output'
})
})
it('scopes the probe to the session cwd and ignores cwd sent by the caller', async () => {
const handler = registerSessionHandlers('')
await expect(handler({ cwd: '/etc' })).resolves.toEqual({
success: false,
error: 'cwd is required'
})
expect(spawnMock).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,46 @@
import { logger } from '@/ui/logger'
import { RPC_METHODS } from '@hapi/protocol/rpcMethods'
import type { ListKimiModelsResponse } from '@hapi/protocol/apiTypes'
import type { RpcHandlerManager } from '@/api/rpc/RpcHandlerManager'
import {
listKimiModelsForCwd,
type ListKimiModelsForCwdRequest,
type ListKimiModelsForCwdResponse
} from '../kimiModels'
import { getErrorMessage, rpcError } from '../rpcResponses'
export function registerKimiModelHandlers(rpcHandlerManager: RpcHandlerManager): void {
rpcHandlerManager.registerHandler<ListKimiModelsForCwdRequest, ListKimiModelsForCwdResponse>(
RPC_METHODS.ListKimiModelsForCwd,
async (data) => {
try {
return await listKimiModelsForCwd(typeof data?.cwd === 'string' ? data.cwd : '')
} catch (error) {
logger.debug('Failed to list Kimi models:', error)
return rpcError(getErrorMessage(error, 'Failed to list Kimi models'))
}
}
)
}
/**
* Session-scoped discovery for a running Kimi session. The probe cwd is the
* session's own metadata, never an RPC argument, so this cannot be pointed at
* an arbitrary directory.
*/
export function registerKimiSessionModelHandlers(
rpcHandlerManager: RpcHandlerManager,
getCwd: () => string
): void {
rpcHandlerManager.registerHandler<unknown, ListKimiModelsResponse>(
RPC_METHODS.ListKimiModels,
async () => {
try {
return await listKimiModelsForCwd(getCwd())
} catch (error) {
logger.debug('Failed to list Kimi models:', error)
return rpcError(getErrorMessage(error, 'Failed to list Kimi models'))
}
}
)
}
+168
View File
@@ -0,0 +1,168 @@
import { describe, expect, it } from 'vitest'
import { buildKimiProviderListArgs, parseKimiProviderListOutput } from './kimiModels'
const PROVIDER_LIST_OUTPUT = JSON.stringify({
providers: {
thehive: {
baseUrl: 'https://api.thehive.example/v1',
type: 'openai',
apiKey: 'sk-secret-thehive-key'
},
'charm-hyper': {
baseUrl: 'https://api.charm-hyper.example',
type: 'openai',
apiKey: 'sk-secret-charm-key'
},
openrouter: {
baseUrl: 'https://openrouter.example/api',
type: 'openai',
apiKey: 'sk-secret-openrouter-key'
}
},
models: {
'GLM-5.3-flash': {
provider: 'thehive',
model: 'zai-org/glm-5.3-flash',
displayName: 'thehive / GLM-5.3-flash',
capabilities: ['tool_use', 'image_in']
},
'deepseek-v4.1-flash': {
provider: 'thehive',
model: 'deepseek-ai/deepseek-v4.1-flash',
displayName: 'thehive / hive-deepseek'
},
'hyper-glm-5.3-flash': {
provider: 'charm-hyper',
model: 'glm-5.3-flash',
displayName: 'charm-hyper / Hyper · GLM-5.3-Flash'
},
'openrouter-union-alpha': {
provider: 'openrouter',
model: 'stealth/union-alpha',
displayName: 'openrouter / Union Alpha'
}
}
})
describe('buildKimiProviderListArgs', () => {
it('uses the provider list command in json mode', () => {
expect(buildKimiProviderListArgs()).toEqual(['provider', 'list', '--json'])
})
})
describe('parseKimiProviderListOutput', () => {
it('parses the real provider list format with multiple providers', () => {
const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT)
expect(parsed.availableModels.map((model) => model.modelId)).toEqual([
'hyper-glm-5.3-flash',
'openrouter-union-alpha',
'deepseek-v4.1-flash',
'GLM-5.3-flash'
])
expect(parsed.currentModelId).toBeNull()
})
it('keeps several models of the same provider distinct', () => {
const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT)
const thehiveModels = parsed.availableModels.filter((model) => model.provider === 'thehive')
expect(thehiveModels.map((model) => model.modelId).sort()).toEqual([
'GLM-5.3-flash',
'deepseek-v4.1-flash'
])
})
it('carries provider and display name for UI labels', () => {
const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT)
const hyper = parsed.availableModels.find((model) => model.modelId === 'hyper-glm-5.3-flash')
expect(hyper).toEqual({
modelId: 'hyper-glm-5.3-flash',
name: 'charm-hyper / Hyper · GLM-5.3-Flash',
provider: 'charm-hyper'
})
})
it('never transmits secrets from the provider payload', () => {
const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT)
const serialized = JSON.stringify(parsed)
expect(serialized).not.toContain('sk-secret-thehive-key')
expect(serialized).not.toContain('sk-secret-charm-key')
expect(serialized).not.toContain('sk-secret-openrouter-key')
expect(serialized).not.toContain('api.thehive.example')
expect(serialized).not.toContain('openrouter.example')
for (const model of parsed.availableModels) {
expect(Object.keys(model).sort()).toEqual(['modelId', 'name', 'provider'].sort())
}
})
it('reports the local default model as current', () => {
const parsed = parseKimiProviderListOutput(PROVIDER_LIST_OUTPUT, 'GLM-5.3-flash')
expect(parsed.currentModelId).toBe('GLM-5.3-flash')
})
it('parses a bare models map', () => {
const output = JSON.stringify({
models: {
'alias-a': { provider: 'p1', displayName: 'Model A' },
'alias-b': { provider: 'p2' }
}
})
const parsed = parseKimiProviderListOutput(output)
expect(parsed.availableModels.map((model) => model.modelId).sort()).toEqual(['alias-a', 'alias-b'])
})
it('parses an array of model entries', () => {
const output = JSON.stringify([
{ alias: 'alias-a', displayName: 'Model A', provider: 'p1', apiKey: 'should-not-leak' },
{ modelId: 'alias-b', name: 'Model B' }
])
const parsed = parseKimiProviderListOutput(output)
expect(parsed.availableModels).toEqual([
{ modelId: 'alias-b', name: 'Model B' },
{ modelId: 'alias-a', name: 'Model A', provider: 'p1' }
])
expect(JSON.stringify(parsed)).not.toContain('should-not-leak')
})
it('parses providers with nested models', () => {
const output = JSON.stringify({
providers: {
p1: { apiKey: 'secret', models: { 'alias-a': { displayName: 'Model A' } } }
}
})
const parsed = parseKimiProviderListOutput(output)
expect(parsed.availableModels).toEqual([
{ modelId: 'alias-a', name: 'Model A', provider: undefined }
])
expect(JSON.stringify(parsed)).not.toContain('secret')
})
it('tolerates leading non-JSON output', () => {
const parsed = parseKimiProviderListOutput(`some banner\n${PROVIDER_LIST_OUTPUT}`)
expect(parsed.availableModels).toHaveLength(4)
})
it('falls back to the object key when no alias field exists', () => {
const output = JSON.stringify({ models: { 'key-alias': { model: 'upstream/id' } } })
const parsed = parseKimiProviderListOutput(output)
expect(parsed.availableModels[0]?.modelId).toBe('key-alias')
// The upstream provider model id is not the alias and must not be used as value.
expect(parsed.availableModels[0]).not.toHaveProperty('modelId', 'upstream/id')
})
it('throws on output without JSON', () => {
expect(() => parseKimiProviderListOutput('no json here')).toThrow('no JSON output')
})
it('throws on invalid JSON', () => {
expect(() => parseKimiProviderListOutput('{"models":')).toThrow('invalid JSON output')
})
it('deduplicates models across shapes', () => {
const output = JSON.stringify({
models: { 'alias-a': { provider: 'p1' } },
providers: { p1: { models: { 'alias-a': { displayName: 'dup' } } } }
})
const parsed = parseKimiProviderListOutput(output)
expect(parsed.availableModels).toHaveLength(1)
})
})
+223
View File
@@ -0,0 +1,223 @@
import { spawn } from 'node:child_process'
import { getAgentLaunchCommand } from '@/agent/agentLaunchCommand'
import { asString, isObject } from '@hapi/protocol'
import type { KimiModelSummary, KimiModelsResponse } from '@hapi/protocol/apiTypes'
import { readKimiLocalConfig } from '@/kimi/utils/config'
import { logger } from '@/ui/logger'
import { getErrorMessage } from './rpcResponses'
export interface ListKimiModelsForCwdRequest {
cwd?: string
}
export type ListKimiModelsForCwdResponse = KimiModelsResponse
interface CacheEntry {
expiresAt: number
response: ListKimiModelsForCwdResponse
}
const CACHE_TTL_MS = 60_000
const PROBE_TIMEOUT_MS = 15_000
const cache = new Map<string, CacheEntry>()
const inflight = new Map<string, Promise<ListKimiModelsForCwdResponse>>()
export function buildKimiProviderListArgs(): string[] {
return ['provider', 'list', '--json']
}
/**
* Extract only the fields HAPI is allowed to transmit. Everything else in the
* `kimi provider list --json` output (api keys, base urls, upstream model ids,
* context sizes) stays on the machine.
*/
function normalizeModelEntry(entry: Record<string, unknown>, keyAlias: string | null): KimiModelSummary | null {
const modelId = asString(entry.modelId)
?? asString(entry.alias)
?? asString(entry.id)
?? keyAlias
if (!modelId) return null
const name = asString(entry.displayName) ?? asString(entry.name) ?? undefined
const provider = asString(entry.provider) ?? undefined
return {
modelId,
...(name ? { name } : {}),
...(provider ? { provider } : {})
}
}
/**
* Parse `kimi provider list --json`. Handles the real shape
* `{ providers: {...}, models: { "<alias>": { provider, displayName, ... } } }`
* plus tolerant variants: a bare `models` map, an array of model entries, and
* a `providers` map whose entries carry nested `models`. Only whitelisted
* fields are returned, so secrets in the payload can never leak through.
*/
export function parseKimiProviderListOutput(
output: string,
defaultModel?: string
): {
availableModels: KimiModelSummary[]
currentModelId: string | null
} {
const availableModels: KimiModelSummary[] = []
const seen = new Set<string>()
const push = (entry: Record<string, unknown>, keyAlias: string | null) => {
const model = normalizeModelEntry(entry, keyAlias)
if (!model || seen.has(model.modelId)) return
seen.add(model.modelId)
availableModels.push(model)
}
const jsonStart = output.indexOf('{')
const arrayStart = output.indexOf('[')
const start = jsonStart === -1
? arrayStart
: arrayStart !== -1 && arrayStart < jsonStart ? arrayStart : jsonStart
if (start === -1) {
throw new Error('kimi provider list produced no JSON output')
}
let data: unknown
try {
data = JSON.parse(output.slice(start))
} catch {
throw new Error('kimi provider list produced invalid JSON output')
}
const collectModelMap = (value: unknown) => {
if (!isObject(value)) return
for (const [alias, entry] of Object.entries(value)) {
if (isObject(entry)) push(entry, alias)
}
}
if (Array.isArray(data)) {
for (const entry of data) {
if (isObject(entry)) push(entry, null)
}
} else if (isObject(data)) {
collectModelMap(data.models)
if (availableModels.length === 0 && isObject(data.providers)) {
for (const providerEntry of Object.values(data.providers)) {
if (!isObject(providerEntry)) continue
if (isObject(providerEntry.models)) {
collectModelMap(providerEntry.models)
} else {
push(providerEntry, null)
}
}
}
}
availableModels.sort((a, b) => {
const providerOrder = (a.provider ?? '').localeCompare(b.provider ?? '')
return providerOrder !== 0 ? providerOrder : a.modelId.localeCompare(b.modelId)
})
const currentModelId = defaultModel?.trim() || null
return { availableModels, currentModelId }
}
function describeProbeExit(code: number | null, signal: NodeJS.Signals | null): string {
if (signal) return `kimi provider list was terminated by ${signal}`
return `kimi provider list exited with code ${code}`
}
async function runKimiProviderListProbe(): Promise<ListKimiModelsForCwdResponse> {
return await new Promise((resolve, reject) => {
const child = spawn(getAgentLaunchCommand('kimi'), buildKimiProviderListArgs(), {
env: process.env,
stdio: ['ignore', 'pipe', 'pipe'],
shell: process.platform === 'win32',
windowsHide: process.platform === 'win32'
})
let stdout = ''
let stderr = ''
let settled = false
// Exactly one of timeout / spawn error / close settles the probe, and
// the settling work is wrapped: a throw from an event callback would
// otherwise escape this promise and reach the runner's
// uncaughtException shutdown handler instead of the caller's catch.
const settle = (outcome: () => void) => {
if (settled) return
settled = true
clearTimeout(timeout)
try {
outcome()
} catch (error) {
reject(error)
}
}
const timeout = setTimeout(() => {
settle(() => {
try {
child.kill('SIGTERM')
} catch (error) {
logger.debug('Failed to kill the Kimi model discovery probe:', error)
}
reject(new Error('Kimi model discovery timed out'))
})
}, PROBE_TIMEOUT_MS)
child.stdout?.on('data', (chunk) => {
stdout += chunk.toString()
})
child.stderr?.on('data', (chunk) => {
stderr += chunk.toString()
})
child.on('error', (error) => {
settle(() => reject(error))
})
// Parse on 'close', not 'exit': stdio must be drained first, and the
// parser runs inside settle() so malformed output rejects the probe.
child.on('close', (code, signal) => {
settle(() => {
if (code !== 0) {
reject(new Error(stderr.trim() || describeProbeExit(code, signal)))
return
}
const defaultModel = readKimiLocalConfig().model
resolve({ success: true, ...parseKimiProviderListOutput(stdout, defaultModel) })
})
})
})
}
export async function listKimiModelsForCwd(cwd: string): Promise<ListKimiModelsForCwdResponse> {
const trimmed = cwd?.trim()
if (!trimmed) return { success: false, error: 'cwd is required' }
const cached = cache.get(trimmed)
if (cached && cached.expiresAt > Date.now()) return cached.response
const running = inflight.get(trimmed)
if (running) return running
const promise = (async () => {
try {
const response = await runKimiProviderListProbe()
if (response.success) {
cache.set(trimmed, { expiresAt: Date.now() + CACHE_TTL_MS, response })
}
return response
} catch (error) {
return {
success: false,
error: getErrorMessage(error, 'Failed to discover Kimi models')
}
} finally {
inflight.delete(trimmed)
}
})()
inflight.set(trimmed, promise)
return promise
}
export function _resetKimiModelsCacheForTests(): void {
cache.clear()
inflight.clear()
}
@@ -0,0 +1,175 @@
import { EventEmitter } from 'node:events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { spawnMock, configState } = vi.hoisted(() => ({
spawnMock: vi.fn(),
configState: { read: (() => ({ model: 'GLM-5.3-flash' })) as () => { model?: string } }
}))
vi.mock('node:child_process', () => ({ spawn: spawnMock }))
vi.mock('@/ui/logger', () => ({
logger: { debug: vi.fn(), warn: vi.fn(), info: vi.fn() }
}))
vi.mock('@/kimi/utils/config', () => ({
readKimiLocalConfig: () => configState.read()
}))
import { _resetKimiModelsCacheForTests, listKimiModelsForCwd } from './kimiModels'
class FakeChild extends EventEmitter {
stdout = new EventEmitter()
stderr = new EventEmitter()
kill = vi.fn()
}
const MALFORMED_OUTPUT = '{"models":'
function startProbe(cwd: string) {
const child = new FakeChild()
spawnMock.mockImplementation(() => child)
return { child, pending: listKimiModelsForCwd(cwd) }
}
beforeEach(() => {
spawnMock.mockReset()
configState.read = () => ({ model: 'GLM-5.3-flash' })
_resetKimiModelsCacheForTests()
})
afterEach(() => {
vi.useRealTimers()
})
describe('Kimi provider list probe settlement', () => {
it('reports malformed JSON at exit code 0 as a failure instead of throwing out of the callback', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-malformed')
child.stdout.emit('data', MALFORMED_OUTPUT)
child.emit('exit', 0, null)
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'kimi provider list produced invalid JSON output'
})
})
it('reports missing JSON output as a failure', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-no-json')
child.stdout.emit('data', 'no json here')
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'kimi provider list produced no JSON output'
})
})
it('contains a throwing local-config read inside the probe promise', async () => {
configState.read = () => {
throw new Error('kimi config unreadable')
}
const { child, pending } = startProbe('/tmp/kimi-probe-config-throws')
child.stdout.emit('data', JSON.stringify({ models: { 'alias-a': {} } }))
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'kimi config unreadable'
})
})
it('parses stdout that arrives after exit but before close', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-late-stdout')
child.emit('exit', 0, null)
child.stdout.emit('data', JSON.stringify({
models: {
'late-alias': { provider: 'p1', displayName: 'Late Model' }
}
}))
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: true,
availableModels: [{ modelId: 'late-alias', name: 'Late Model', provider: 'p1' }],
currentModelId: 'GLM-5.3-flash'
})
})
it('keeps a non-zero exit a failure and prefers stderr', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-exit-1')
child.stderr.emit('data', 'provider list unavailable\n')
child.emit('close', 1, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'provider list unavailable'
})
})
it('keeps a non-zero exit a failure when stderr is empty', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-exit-2')
child.emit('close', 2, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'kimi provider list exited with code 2'
})
})
it('names the terminating signal when the probe dies without an exit code', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-signaled')
child.emit('close', null, 'SIGKILL')
await expect(pending).resolves.toEqual({
success: false,
error: 'kimi provider list was terminated by SIGKILL'
})
})
it('times the probe out and kills the child', async () => {
vi.useFakeTimers()
const { child, pending } = startProbe('/tmp/kimi-probe-timeout')
await vi.advanceTimersByTimeAsync(15_000)
await expect(pending).resolves.toEqual({
success: false,
error: 'Kimi model discovery timed out'
})
expect(child.kill).toHaveBeenCalledWith('SIGTERM')
})
it('lets the first settlement win when an error is followed by a successful close', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-error-then-close')
child.emit('error', new Error('spawn kimi ENOENT'))
child.stdout.emit('data', JSON.stringify({ models: { 'alias-a': {} } }))
child.emit('close', 0, null)
await expect(pending).resolves.toEqual({
success: false,
error: 'spawn kimi ENOENT'
})
})
it('ignores a second close after the probe already settled', async () => {
const { child, pending } = startProbe('/tmp/kimi-probe-double-close')
child.stdout.emit('data', JSON.stringify({ models: { 'alias-a': { displayName: 'A' } } }))
child.emit('close', 0, null)
child.emit('close', 1, null)
await expect(pending).resolves.toEqual({
success: true,
availableModels: [{ modelId: 'alias-a', name: 'A' }],
currentModelId: 'GLM-5.3-flash'
})
})
})
@@ -8,6 +8,7 @@ import { registerOpencodeModelVariantsHandlers } from './handlers/opencodeModelV
import { registerPiModelHandlers } from './handlers/piModels'
import { registerGrokModelHandlers } from './handlers/grokModels'
import { registerCopilotModelHandlers } from './handlers/copilotModels'
import { registerKimiModelHandlers } from './handlers/kimiModels'
import { registerDirectoryHandlers } from './handlers/directories'
import { registerDifftasticHandlers } from './handlers/difftastic'
import { registerFileHandlers } from './handlers/files'
@@ -27,6 +28,7 @@ export function registerCommonHandlers(rpcHandlerManager: RpcHandlerManager, wor
registerPiModelHandlers(rpcHandlerManager)
registerGrokModelHandlers(rpcHandlerManager)
registerCopilotModelHandlers(rpcHandlerManager)
registerKimiModelHandlers(rpcHandlerManager)
registerFileHandlers(rpcHandlerManager, workingDirectory)
registerDirectoryHandlers(rpcHandlerManager, workingDirectory)
registerRipgrepHandlers(rpcHandlerManager, workingDirectory)
+11 -5
View File
@@ -5,11 +5,11 @@ export interface SpawnSessionOptions {
machineId?: string
directory: string
sessionId?: string
// Existing hub session id to reuse (reopen/resume). Distinct from the legacy
// `sessionId` field above (reserved/unused by spawn): when set, the CLI boots
// with `--hapi-session-id` so the child reuses the existing hub row (stable
// id) instead of minting a new one. Set only by the hub reopen/resume path.
// Live hub row id for reopen/resume. Runner stamps `--existing-session-id`.
existingSessionId?: string
// Hub-preallocated machine-spawn stub. Runner stamps `--hapi-session-id`
// (adopt-stub create/getOrCreate) — must NOT take the reopen path.
reservedSessionId?: string
resumeSessionId?: string
approvedNewDirectoryCreation?: boolean
agent?: AgentFlavor
@@ -40,10 +40,16 @@ export interface SpawnSessionOptions {
export type SpawnSessionResult =
| { type: 'success'; sessionId: string }
| { type: 'requestToApproveDirectoryCreation'; directory: string }
| { type: 'requestToApproveDirectoryCreation'; directory: string; childStarted: false }
| {
type: 'error'
errorMessage: string
code?: 'agent_unavailable' | 'outside_workspace_roots'
agent?: AgentFlavor
/**
* Explicit false = runner rejected before exec (no OS child). Hub may
* delete a preallocated stub. Omitted/true = child may exist — keep stub
* until StopSession confirms gone (#1911 B3).
*/
childStarted?: boolean
}
@@ -9,16 +9,6 @@ import {
withSessionSummaryInstruction
} from './sessionSummaryInstruction'
const PREVIOUS_SESSION_SUMMARY_INSTRUCTION = [
'Session status summary:',
'End every response with a single machine-readable status line (no backticks)',
'so this workspace\'s session tracking can record progress. Put it on its own',
'final line after all other content:',
'AGENT_NOTIFY_SUMMARY {"version":1,"agent":"<agent-id>","project":"<project>","status":"done|blocked|needs_review|needs_decision|failed|stalled","action":"<=12 words","summary":"one-line triage"}',
'Use status "blocked" if unsure. Keep action to 12 words or fewer when status',
'is "done" and follow-up remains.'
].join('\n')
const USER_LANGUAGE_INSTRUCTION = [
'Use the language used by the user in the current conversation for the',
'human-readable "action" and "summary" values.'
@@ -66,17 +56,14 @@ describe('sessionSummaryInstruction', () => {
expect(body.toLowerCase()).not.toContain('surveillance')
})
it('adds user-language guidance without changing the existing prompt contract', () => {
it('limits summaries to the final answer while preserving language and footer guidance', () => {
applyHubSessionSummaryContract(true)
const body = sessionSummaryInstructionOrEmpty({})
const previousLines = PREVIOUS_SESSION_SUMMARY_INSTRUCTION.split('\n')
const expected = [
...previousLines.slice(0, 5),
USER_LANGUAGE_INSTRUCTION,
...previousLines.slice(5)
].join('\n')
expect(body).toBe(expected)
expect(body).toContain('At the end of each turn, append exactly one')
expect(body).toContain('final answer only')
expect(body).toContain('Do not emit this line in commentary, progress updates, or before tool calls.')
expect(body).toContain(USER_LANGUAGE_INSTRUCTION)
expect(body).not.toContain('End every response')
})
it('preserves the exact machine-readable footer format', () => {
@@ -49,9 +49,10 @@ export const SESSION_SUMMARY_CONTRACT_LINE =
export function buildSessionSummaryInstruction(): string {
return [
'Session status summary:',
'End every response with a single machine-readable status line (no backticks)',
'so this workspace\'s session tracking can record progress. Put it on its own',
'final line after all other content:',
'At the end of each turn, append exactly one machine-readable status line',
'(no backticks) to the final answer only, so this workspace\'s session tracking',
'can record progress. Do not emit this line in commentary, progress updates, or before tool calls.',
'Put it on its own final line after all other content:',
SESSION_SUMMARY_CONTRACT_LINE,
'Use the language used by the user in the current conversation for the',
'human-readable "action" and "summary" values.',