mirror of
https://github.com/MoonshotAI/kimi-code.git
synced 2026-07-31 12:05:17 +00:00
* refactor(oauth): make X-Msh-Platform an explicit host identity field X-Msh-Platform was hardcoded to kimi_code_cli in createKimiDeviceHeaders, so non-CLI hosts could not state their own platform and the desktop had to patch the header after the fact. KimiHostIdentity now carries a required platform (every host declares its own value; the CLI constant stays the fallback only for direct createKimiDeviceHeaders callers), and userAgentProduct is renamed to productName so the transport identity uses one name everywhere. All in-repo identity constructions pass platform explicitly; the wire value for CLI and VS Code hosts is unchanged (kimi_code_cli). * feat(agent-core-v2): carry the host identity in the bootstrap snapshot Replace the flat clientVersion field with a required clientIdentity (KimiHostIdentity) so every consumer reads the same host identity object: OAuthToolkitService now passes it to the OAuth toolkit, which means the OAuth device-flow endpoints (device authorization, token polling, refresh) on the kap-server path finally send the full X-Msh-* device headers instead of none, and the telemetry cloud appender reads client_version from the same source. A built-in CLI fallback keeps bare bootstrap() calls in tests working; composition roots must pass their own identity. The session export manifest grows an optional desktopVersion field (payload plumbed through; filled by kap-server in a follow-up). * feat(agent-core): thread the host identity into the managed auth facades The v1 managed auth facade constructed its OAuth toolkit without an identity, so token refreshes from inside the core went out without any X-Msh-* device headers. createManagedAuthFacade now takes an optional KimiHostIdentity and every call site supplies one: CoreProcessService._defaultOAuthTokenResolver forwards the core process's options.identity (the same source _defaultKimiRequestHeaders uses), and the DI-held services (oauth / auth summary / model catalog) read it from a new optional identity field on IEnvironmentService. The library-level "no identity, no device headers" contract is unchanged. * feat(kap-server)!: require the host identity and derive request headers from it ServerStartOptions.hostIdentity is now a required ServerHostIdentity (KimiHostIdentity + optional prompt display fields), replacing both the old optional HostIdentityOverrides (renamed to PromptIdentityOverrides, its productName field now displayName) and the version option (renamed to serverVersion — it is the engine version reported as server_version, while the host product version travels in hostIdentity.version). The server now feeds bootstrap's clientIdentity from hostIdentity and derives the default outbound headers (User-Agent + X-Msh-*) from it via createKimiDefaultHeaders, so kap-server-hosted OAuth flows and model / WebSearch requests carry the real host identity instead of a hardcoded kimi-code-cli fallback UA. Explicit header seeds still win as an escape hatch. Session export manifests record the host product version: kimiCodeVersion now carries hostIdentity.version (the engine version no longer appears), and desktop exports (desktop: true) are additionally stamped with a desktopVersion field. The instance registry keeps its host_version wire field for compatibility (kimi-inspect reads it); only the in-memory name changed to serverVersion. * feat(cli): wire the CLI host identity into the kimi web server kimi web now passes createKimiCodeHostIdentity(version) as the server's hostIdentity, so web-UI OAuth flows and the engine's outbound requests carry the explicit CLI identity (productName + version + platform). The explicit hostRequestHeadersSeed is dropped — kap-server derives the same headers from hostIdentity — and buildKimiDefaultHeaders goes away with its only consumer. * test(klient): drop clientVersion from the bootstrap contract parity list * chore: add changesets for the host identity unification * feat(cli): tag kimi web requests with a (web) User-Agent suffix kimi web shares the CLI product token and platform, so its outbound requests were indistinguishable from direct CLI runs upstream. Its host identity now carries userAgentSuffix 'web', putting web-UI traffic at kimi-code-cli/<version> (web) while X-Msh-Platform stays kimi_code_cli. * fix(klient): keep the env() clientVersion wire field after the bootstrap identity switch The bootstrap snapshot replaced the flat clientVersion scalar with clientIdentity, which broke klient's env() fan-out (RPCError: method not found). The wire surface keeps clientVersion — now sourced from clientIdentity.version — and bootstrapService gains a clientIdentity read (registered in envContract with an object schema) for consumers that want the full identity. * feat(oauth): send the product User-Agent on OAuth requests The OAuth endpoints used to receive only the X-Msh-* device headers (undici's default UA otherwise), which left the OAuth host unable to distinguish runtime surfaces — notably kimi web, whose platform matches the CLI and whose only distinguishing mark is the (web) UA suffix. The toolkit now feeds the full identity headers (User-Agent + X-Msh-*) into every device authorization, token polling, and refresh request; the request-header type widens from DeviceHeaders to OAuthRequestHeaders. * feat(vscode): report kimi_code_vscode as the extension's platform The VS Code extension inherited the CLI's hardcoded X-Msh-Platform value; with platform now an explicit identity field it declares its own, so the managed endpoints and OAuth host can tell extension traffic apart from CLI runs. * refactor(agent-core-v2)!: require the client identity at the composition root The bootstrap fallback identity fabricated a kimi-code-cli/unknown host for any caller that forgot to pass one — the same silent-misreport pattern this series set out to remove, and it made "required" a lie. BootstrapInput.clientIdentity is now required, so a missing identity fails at compile time instead of being papered over. Test and example callers pass a shared fixture (klient examples and test engines get one each); the node-sdk v2 client asserts its host identity with the oauth helper. Also folds DeviceHeaders from an interface into a type alias so it stays assignable to the widened OAuthRequestHeaders record. * feat(oauth)!: require and validate the platform in device headers Drops the quiet CLI fallback in createKimiDeviceHeaders (the same silent-misreport pattern removed from the bootstrap identity): platform is now a required option, validated with the same required-ASCII rule as the version — empty or all-non-ASCII values throw instead of emitting a blank X-Msh-Platform, and header-unsafe characters are stripped rather than sent raw. * fix(node-sdk): seed the host request headers on the v2 client path The interactive v2 engine path (experimental flag) bootstrapped without a hostRequestHeaders seed, so managed vendor calls went out with the SDK's default User-Agent (OpenAI/JS) and no X-Msh-* at all — v1 passes the full identity headers on the same requests. The v2 client now seeds the headers from its asserted host identity, and a test pins the seed. * chore: simplify the CLI changeset wording
91 lines
3.2 KiB
TypeScript
91 lines
3.2 KiB
TypeScript
import { mkdtemp, rm } from 'node:fs/promises';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { Writable } from 'node:stream';
|
|
|
|
import { pino, type Logger } from 'pino';
|
|
import { afterEach, assert, describe, expect, it } from 'vitest';
|
|
|
|
import { extractEnvelopeCode } from '../src/requestLogging';
|
|
import { type RunningServer, startServer } from '../src/start';
|
|
import { TEST_HOST_IDENTITY } from './helpers/hostIdentity';
|
|
|
|
function captureLogger(): { logger: Logger; lines: string[] } {
|
|
const lines: string[] = [];
|
|
const stream = new Writable({
|
|
write(chunk, _enc, cb) {
|
|
lines.push(chunk.toString());
|
|
cb();
|
|
},
|
|
});
|
|
return { logger: pino({ level: 'info' }, stream), lines };
|
|
}
|
|
|
|
function parseEntries(lines: string[]): Record<string, unknown>[] {
|
|
return lines
|
|
.map((line) => {
|
|
try {
|
|
return JSON.parse(line) as Record<string, unknown>;
|
|
} catch {
|
|
return null;
|
|
}
|
|
})
|
|
.filter((entry): entry is Record<string, unknown> => entry !== null);
|
|
}
|
|
|
|
describe('requestLogging', () => {
|
|
let server: RunningServer | undefined;
|
|
let home: string | undefined;
|
|
|
|
afterEach(async () => {
|
|
if (server !== undefined) {
|
|
await server.close();
|
|
server = undefined;
|
|
}
|
|
if (home !== undefined) {
|
|
await rm(home, { recursive: true, force: true });
|
|
home = undefined;
|
|
}
|
|
});
|
|
|
|
it('logs the envelope code instead of the HTTP status code', async () => {
|
|
home = await mkdtemp(join(tmpdir(), 'kimi-server-v2-request-log-'));
|
|
const { logger, lines } = captureLogger();
|
|
server = await startServer({ hostIdentity: TEST_HOST_IDENTITY, host: '127.0.0.1', port: 0, homeDir: home, logger });
|
|
|
|
const res = await fetch(`http://127.0.0.1:${String(server.port)}/api/v1/healthz`);
|
|
expect(res.status).toBe(200);
|
|
expect(((await res.json()) as { code: number }).code).toBe(0);
|
|
|
|
// Let the post-response `onResponse` hook flush its log line.
|
|
await new Promise((resolve) => setImmediate(resolve));
|
|
|
|
const completed = parseEntries(lines).filter((entry) => entry['msg'] === 'request completed');
|
|
expect(completed.length).toBeGreaterThanOrEqual(1);
|
|
const entry = completed[completed.length - 1];
|
|
assert(entry !== undefined);
|
|
|
|
// The access line carries the envelope `code`, not the HTTP status code.
|
|
expect(entry['code']).toBe(0);
|
|
expect(entry).not.toHaveProperty('statusCode');
|
|
expect(entry['res']).toBeUndefined();
|
|
expect(entry['req']).toMatchObject({ method: 'GET', url: '/api/v1/healthz' });
|
|
expect(typeof entry['responseTime']).toBe('number');
|
|
});
|
|
});
|
|
|
|
describe('extractEnvelopeCode', () => {
|
|
it('extracts a leading code from an envelope body', () => {
|
|
expect(extractEnvelopeCode('{"code":0,"msg":"success","data":null,"request_id":"r"}')).toBe(0);
|
|
expect(
|
|
extractEnvelopeCode('{"code":40001,"msg":"validation.failed","data":null,"request_id":"r"}'),
|
|
).toBe(40001);
|
|
});
|
|
|
|
it('returns undefined for non-envelope or non-string payloads', () => {
|
|
expect(extractEnvelopeCode(undefined)).toBeUndefined();
|
|
expect(extractEnvelopeCode(Buffer.from('{"code":1}'))).toBeUndefined();
|
|
expect(extractEnvelopeCode('<html/>')).toBeUndefined();
|
|
expect(extractEnvelopeCode('{"msg":"no code"}')).toBeUndefined();
|
|
});
|
|
});
|