Skip to content

🤖 Code Audit: 10 potential issue(s) found #837

@asmit25805

Description

@asmit25805

Code Audit Report

All findings are reviewed for confidence before posting.
Please verify each finding before acting on it.

Repository: MoonshotAI/kimi-code
Findings: 10 issue(s) found — 🟠 4 high · 🟡 6 medium


1. 🐛 import.meta.dirname is not a standard property and may be undefined

Field Details
Severity 🟠 High
Type Bug
File apps/kimi-code/tsdown.native.config.ts
Location const appRoot = import.meta.dirname;
Confidence 96%

Problem:
The code assigns appRoot from import.meta.dirname, but Node.js does not provide a dirname property on import.meta (only url). When appRoot is undefined, the subsequent resolve(appRoot, 'src') call throws a TypeError, causing the configuration script to fail at runtime.

Suggested Fix:
Replace the usage with a reliable method to obtain the directory, e.g., const appRoot = new URL('.', import.meta.url).pathname; or import { fileURLToPath } from 'node:url'; const appRoot = fileURLToPath(new URL('.', import.meta.url));.


2. 🐛 Missing null/undefined handling for optional headers and env arrays

Field Details
Severity 🟠 High
Type Bug
File packages/acp-adapter/src/mcp.ts
Location function acpMcpServerToConfig
Confidence 98%

Problem:
The code unconditionally passes server.headers and stdio.env to headersArrayToRecord and envArrayToRecord. If either property is undefined (which is allowed by the MCP schema), the helper functions will attempt to iterate over undefined, throwing a TypeError at runtime and breaking the conversion process.

Suggested Fix:
Add default empty-array handling before calling the helpers, e.g., headersArrayToRecord(server.headers ?? []) and envArrayToRecord(stdio.env ?? []). Also update the helper functions to accept undefined gracefully or add guards.


3. 🐛 Potential TypeError when negotiated version is undefined

Field Details
Severity 🟠 High
Type Bug
File packages/acp-adapter/src/server.ts
Location initialize method
Confidence 95%

Problem:
The initialize method assigns this.negotiated = negotiateVersion(params.protocolVersion). If negotiateVersion returns undefined for an unsupported protocol version, the subsequent line protocolVersion: this.negotiated.protocolVersion will attempt to access .protocolVersion on undefined, causing a runtime TypeError and preventing the server from responding to the client.

Suggested Fix:
Validate the result of negotiateVersion before accessing its properties. For example:

const negotiated = negotiateVersion(params.protocolVersion);
if (!negotiated) {
  throw RequestError.invalidParams('Unsupported protocol version');
}
this.negotiated = negotiated;

Then use negotiated.protocolVersion in the response.


4. 🐛 ReferenceError: THINKING_ON_LEVEL is undefined

Field Details
Severity 🟠 High
Type Bug
File packages/acp-adapter/src/session.ts
Location setModel method
Confidence 99%

Problem:
The setModel method references a constant THINKING_ON_LEVEL that is not imported or defined in this module. At runtime this will throw a ReferenceError, preventing the method from completing and breaking model setting with the ,thinking suffix.

Suggested Fix:
Import the appropriate constant or replace the reference with the correct string value, e.g., await this.session.setThinking('high'); or add import { THINKING_ON_LEVEL } from './constants'; at the top of the file.


5. 🐛 Potential TypeError when resource_link name is undefined

Field Details
Severity 🟡 Medium
Type Bug
File packages/acp-adapter/src/convert.ts
Location acpBlocksToPromptParts → resource_link handling
Confidence 96%

Problem:
The code constructs an XML string for a resource_link block using escapeXmlAttr(block.name). If block.name is undefined (optional), escapeXmlAttr receives a non‑string argument, leading to a runtime TypeError (replace is not a function). This can crash the conversion process for valid inputs.

Suggested Fix:
Guard against undefined values before calling escapeXmlAttr, e.g., const nameAttr = block.name !== undefined ? escapeXmlAttr(block.name) : ''; then include the attribute only when present, or provide a default empty string.


6. 🐛 Missing default case may return undefined

Field Details
Severity 🟡 Medium
Type Bug
File packages/acp-adapter/src/events-map.ts
Location turnEndReasonToStopReason
Confidence 96%

Problem:
The function turnEndReasonToStopReason switches on reason but does not handle values outside the known TurnEndReason union. If a new reason is introduced or an unexpected value is passed, the function returns undefined, violating the expected AcpStopReason type and potentially causing runtime errors downstream.

Suggested Fix:
Add a default case that returns a sensible fallback (e.g., 'end_turn') or throws a clear error. Example:

export function turnEndReasonToStopReason(reason: TurnEndReason): AcpStopReason {
  switch (reason) {
    case 'completed':
      return 'end_turn';
    case 'cancelled':
      return 'cancelled';
    case 'failed':
      return 'end_turn';
    default:
      // Fallback for unknown reasons
      return 'end_turn';
  }
}

7. 🐛 Case‑sensitive check against toggleable model set

Field Details
Severity 🟡 Medium
Type Bug
File packages/acp-adapter/src/model-catalog.ts
Location deriveThinkingSupported(alias: ModelAlias)
Confidence 96%

Problem:
The function checks TOGGLEABLE_THINKING_MODELS.has(alias.model) using the original alias.model value. The set contains lower‑case strings, so if the model name is provided with different casing (e.g., "Kimi-For-Coding"), the check will incorrectly return false, causing thinkingSupported to be missed for toggleable models.

Suggested Fix:
Normalize the model name before the set lookup, e.g., if (TOGGLEABLE_THINKING_MODELS.has(lower)) return true;


8. 🐛 Potential TypeError when config.models is null or non‑object

Field Details
Severity 🟡 Medium
Type Bug
File packages/acp-adapter/src/model-catalog.ts
Location listModelsFromHarness
Confidence 95%

Problem:
The code assigns models = config.models without verifying that it is a plain object. If config.models is null or another non‑object value, Object.entries(models) will throw at runtime, breaking the adapter.

Suggested Fix:
Add a guard after retrieving models, e.g., if (!models || typeof models !== 'object') return []; before iterating.


9. 🐛 Hardcoded question index prevents correct handling of multi-question responses

Field Details
Severity 🟡 Medium
Type Bug
File packages/acp-adapter/src/question.ts
Location outcomeToQuestionAnswer
Confidence 96%

Problem:
The outcomeToQuestionAnswer function assumes the question index is always 0. It calls skipOptionId(0) and uses a regex /^q0_opt_(\d+)$/ to parse option IDs. If future multi‑question support introduces a non‑zero index, skip options and selected options will not be recognized correctly, leading to incorrect null results or mis‑mapped answers.

Suggested Fix:
Add a questionIndex parameter (or derive it from the response) and use it when generating the skip ID and regex, e.g., if (optionId === skipOptionId(questionIndex)) return null; const match = new RegExp(^q${questionIndex}opt(\d+)$).exec(optionId);


10. 🐛 Duplicate re-exports cause name collisions

Field Details
Severity 🟡 Medium
Type Bug
File packages/agent-core/src/index.ts
Location export * from './session';
export * from './session/export';
Confidence 95%

Problem:
The file re-exports everything from both './session' and './session/export'. If these two modules share any exported identifiers, TypeScript will emit duplicate identifier errors for consumers, breaking compilation and runtime imports.

Suggested Fix:
Remove one of the duplicate re-exports or explicitly re-export only the needed symbols to avoid overlapping names, e.g., replace one line with a selective export list or eliminate the redundant export.


About this report

This report was generated using Advanced AI models.
Only findings with ≥90% confidence are included.
False positives are possible — use your own judgment.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions