mirror of
https://github.com/QwenLM/qwen-code.git
synced 2025-12-20 16:57:46 +00:00
Fix Gemini Code's (GC) smarts.
- The tl;dr; is that GC couldn't see what the user was saying when tool call events happened in response. The rason why this was happening was because we were instantly invoking tools that the model told us to invoke and then instantly re-requesting. This resulted in the bug because the genai APIs can't update the chat history before a full response has been completed (doesn't know how to update if it's incomplete). - To address the above issue I had to do quite the large refactor. The gist is that now turns truly drive everything on the server (vs. a server client split). This ensured that when we got tool invocations we could control when/how re-requesting would happen and then also ensure that history was updated. This change also meant that the server would act as an event publisher to enable the client to react to events rather than try and weave in complex logic between the events. - A BIG change that this changeset incudes is the removal of all of the CLI tools in favor of the server tools. - Removed some dead code as part of this - **NOTE: Confirmations are still broken (they were broken prior to this); however, I've set them up to be able to work in the future, I'll dot hat in a follow up to be less breaking to others.** Fixes https://b.corp.google.com/issues/412320087
This commit is contained in:
committed by
N. Taylor Mullen
parent
e351baf10f
commit
81f0f618f7
@@ -1,241 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { Part } from '@google/genai';
|
||||
import { toolRegistry } from '../tools/tool-registry.js';
|
||||
import {
|
||||
HistoryItem,
|
||||
IndividualToolCallDisplay,
|
||||
ToolCallEvent,
|
||||
ToolCallStatus,
|
||||
ToolConfirmationOutcome,
|
||||
ToolEditConfirmationDetails,
|
||||
ToolExecuteConfirmationDetails,
|
||||
} from '../ui/types.js';
|
||||
import { ToolResultDisplay } from '../tools/tools.js';
|
||||
|
||||
/**
|
||||
* Processes a tool call chunk and updates the history state accordingly.
|
||||
* Manages adding new tool groups or updating existing ones.
|
||||
* Resides here as its primary effect is updating history based on tool events.
|
||||
*/
|
||||
export const handleToolCallChunk = (
|
||||
chunk: ToolCallEvent,
|
||||
setHistory: React.Dispatch<React.SetStateAction<HistoryItem[]>>,
|
||||
submitQuery: (query: Part) => Promise<void>,
|
||||
getNextMessageId: () => number,
|
||||
currentToolGroupIdRef: React.MutableRefObject<number | null>,
|
||||
): void => {
|
||||
const toolDefinition = toolRegistry.getTool(chunk.name);
|
||||
const description = toolDefinition?.getDescription
|
||||
? toolDefinition.getDescription(chunk.args)
|
||||
: '';
|
||||
const toolDisplayName = toolDefinition?.displayName ?? chunk.name;
|
||||
let confirmationDetails = chunk.confirmationDetails;
|
||||
if (confirmationDetails) {
|
||||
const originalConfirmationDetails = confirmationDetails;
|
||||
const historyUpdatingConfirm = async (outcome: ToolConfirmationOutcome) => {
|
||||
originalConfirmationDetails.onConfirm(outcome);
|
||||
|
||||
if (outcome === ToolConfirmationOutcome.Cancel) {
|
||||
let resultDisplay: ToolResultDisplay | undefined;
|
||||
if ('fileDiff' in originalConfirmationDetails) {
|
||||
resultDisplay = {
|
||||
fileDiff: (
|
||||
originalConfirmationDetails as ToolEditConfirmationDetails
|
||||
).fileDiff,
|
||||
};
|
||||
} else {
|
||||
resultDisplay = `~~${(originalConfirmationDetails as ToolExecuteConfirmationDetails).command}~~`;
|
||||
}
|
||||
handleToolCallChunk(
|
||||
{
|
||||
...chunk,
|
||||
status: ToolCallStatus.Error,
|
||||
confirmationDetails: undefined,
|
||||
resultDisplay: resultDisplay ?? 'Canceled by user.',
|
||||
},
|
||||
setHistory,
|
||||
submitQuery,
|
||||
getNextMessageId,
|
||||
currentToolGroupIdRef,
|
||||
);
|
||||
const functionResponse: Part = {
|
||||
functionResponse: {
|
||||
name: chunk.name,
|
||||
response: { error: 'User rejected function call.' },
|
||||
},
|
||||
};
|
||||
await submitQuery(functionResponse);
|
||||
} else {
|
||||
const tool = toolRegistry.getTool(chunk.name);
|
||||
if (!tool) {
|
||||
throw new Error(
|
||||
`Tool "${chunk.name}" not found or is not registered.`,
|
||||
);
|
||||
}
|
||||
handleToolCallChunk(
|
||||
{
|
||||
...chunk,
|
||||
status: ToolCallStatus.Invoked,
|
||||
resultDisplay: 'Executing...',
|
||||
confirmationDetails: undefined,
|
||||
},
|
||||
setHistory,
|
||||
submitQuery,
|
||||
getNextMessageId,
|
||||
currentToolGroupIdRef,
|
||||
);
|
||||
const result = await tool.execute(chunk.args);
|
||||
handleToolCallChunk(
|
||||
{
|
||||
...chunk,
|
||||
status: ToolCallStatus.Invoked,
|
||||
resultDisplay: result.returnDisplay,
|
||||
confirmationDetails: undefined,
|
||||
},
|
||||
setHistory,
|
||||
submitQuery,
|
||||
getNextMessageId,
|
||||
currentToolGroupIdRef,
|
||||
);
|
||||
const functionResponse: Part = {
|
||||
functionResponse: {
|
||||
name: chunk.name,
|
||||
id: chunk.callId,
|
||||
response: { output: result.llmContent },
|
||||
},
|
||||
};
|
||||
await submitQuery(functionResponse);
|
||||
}
|
||||
};
|
||||
|
||||
confirmationDetails = {
|
||||
...originalConfirmationDetails,
|
||||
onConfirm: historyUpdatingConfirm,
|
||||
};
|
||||
}
|
||||
const toolDetail: IndividualToolCallDisplay = {
|
||||
callId: chunk.callId,
|
||||
name: toolDisplayName,
|
||||
description,
|
||||
resultDisplay: chunk.resultDisplay,
|
||||
status: chunk.status,
|
||||
confirmationDetails,
|
||||
};
|
||||
|
||||
const activeGroupId = currentToolGroupIdRef.current;
|
||||
setHistory((prev) => {
|
||||
if (chunk.status === ToolCallStatus.Pending) {
|
||||
if (activeGroupId === null) {
|
||||
// Start a new tool group
|
||||
const newGroupId = getNextMessageId();
|
||||
currentToolGroupIdRef.current = newGroupId;
|
||||
return [
|
||||
...prev,
|
||||
{
|
||||
id: newGroupId,
|
||||
type: 'tool_group',
|
||||
tools: [toolDetail],
|
||||
} as HistoryItem,
|
||||
];
|
||||
}
|
||||
|
||||
// Add to existing tool group
|
||||
return prev.map((item) =>
|
||||
item.id === activeGroupId && item.type === 'tool_group'
|
||||
? item.tools.some((t) => t.callId === toolDetail.callId)
|
||||
? item // Tool already listed as pending
|
||||
: { ...item, tools: [...item.tools, toolDetail] }
|
||||
: item,
|
||||
);
|
||||
}
|
||||
|
||||
// Update the status of a pending tool within the active group
|
||||
if (activeGroupId === null) {
|
||||
// Log if an invoked tool arrives without an active group context
|
||||
console.warn(
|
||||
'Received invoked tool status without an active tool group ID:',
|
||||
chunk,
|
||||
);
|
||||
return prev;
|
||||
}
|
||||
|
||||
return prev.map((item) =>
|
||||
item.id === activeGroupId && item.type === 'tool_group'
|
||||
? {
|
||||
...item,
|
||||
tools: item.tools.map((t) =>
|
||||
t.callId === toolDetail.callId
|
||||
? { ...t, ...toolDetail, status: chunk.status } // Update details & status
|
||||
: t,
|
||||
),
|
||||
}
|
||||
: item,
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Appends an error or informational message to the history, attempting to attach
|
||||
* it to the last non-user message or creating a new entry.
|
||||
*/
|
||||
export const addErrorMessageToHistory = (
|
||||
error: DOMException | Error,
|
||||
setHistory: React.Dispatch<React.SetStateAction<HistoryItem[]>>,
|
||||
getNextMessageId: () => number,
|
||||
): void => {
|
||||
const isAbort = error.name === 'AbortError';
|
||||
const errorType = isAbort ? 'info' : 'error';
|
||||
const errorText = isAbort
|
||||
? '[Request cancelled by user]'
|
||||
: `[Error: ${error.message || 'Unknown error'}]`;
|
||||
|
||||
setHistory((prev) => {
|
||||
const reversedHistory = [...prev].reverse();
|
||||
// Find the last message that isn't from the user to append the error/info to
|
||||
const lastBotMessageIndex = reversedHistory.findIndex(
|
||||
(item) => item.type !== 'user',
|
||||
);
|
||||
const originalIndex =
|
||||
lastBotMessageIndex !== -1 ? prev.length - 1 - lastBotMessageIndex : -1;
|
||||
|
||||
if (originalIndex !== -1) {
|
||||
// Append error to the last relevant message
|
||||
return prev.map((item, index) => {
|
||||
if (index === originalIndex) {
|
||||
let baseText = '';
|
||||
// Determine base text based on item type
|
||||
if (item.type === 'gemini') baseText = item.text ?? '';
|
||||
else if (item.type === 'tool_group')
|
||||
baseText = `Tool execution (${item.tools.length} calls)`;
|
||||
else if (item.type === 'error' || item.type === 'info')
|
||||
baseText = item.text ?? '';
|
||||
// Safely handle potential undefined text
|
||||
|
||||
const updatedText = (
|
||||
baseText +
|
||||
(baseText && !baseText.endsWith('\n') ? '\n' : '') +
|
||||
errorText
|
||||
).trim();
|
||||
// Reuse existing ID, update type and text
|
||||
return { ...item, type: errorType, text: updatedText };
|
||||
}
|
||||
return item;
|
||||
});
|
||||
} else {
|
||||
// No previous message to append to, add a new error item
|
||||
return [
|
||||
...prev,
|
||||
{
|
||||
id: getNextMessageId(),
|
||||
type: errorType,
|
||||
text: errorText,
|
||||
} as HistoryItem,
|
||||
];
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -8,15 +8,17 @@ import React from 'react';
|
||||
import { render } from 'ink';
|
||||
import { App } from './ui/App.js';
|
||||
import { toolRegistry } from './tools/tool-registry.js';
|
||||
import { LSTool } from './tools/ls.tool.js';
|
||||
import { ReadFileTool } from './tools/read-file.tool.js';
|
||||
import { GrepTool } from './tools/grep.tool.js';
|
||||
import { GlobTool } from './tools/glob.tool.js';
|
||||
import { EditTool } from './tools/edit.tool.js';
|
||||
import { TerminalTool } from './tools/terminal.tool.js';
|
||||
import { WriteFileTool } from './tools/write-file.tool.js';
|
||||
import { WebFetchTool } from './tools/web-fetch.tool.js';
|
||||
import { loadCliConfig } from './config/config.js';
|
||||
import {
|
||||
LSTool,
|
||||
ReadFileTool,
|
||||
GrepTool,
|
||||
GlobTool,
|
||||
EditTool,
|
||||
TerminalTool,
|
||||
WriteFileTool,
|
||||
WebFetchTool,
|
||||
} from '@gemini-code/server';
|
||||
|
||||
async function main() {
|
||||
// Load configuration
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import {
|
||||
EditLogic,
|
||||
EditToolParams,
|
||||
ToolResult,
|
||||
makeRelative,
|
||||
shortenPath,
|
||||
isNodeError,
|
||||
} from '@gemini-code/server';
|
||||
import { BaseTool } from './tools.js';
|
||||
import {
|
||||
ToolCallConfirmationDetails,
|
||||
ToolConfirmationOutcome,
|
||||
ToolEditConfirmationDetails,
|
||||
} from '../ui/types.js';
|
||||
import * as Diff from 'diff';
|
||||
|
||||
/**
|
||||
* CLI wrapper for the Edit tool.
|
||||
* Handles confirmation prompts and potentially UI-specific state like 'Always Edit'.
|
||||
*/
|
||||
export class EditTool extends BaseTool<EditToolParams, ToolResult> {
|
||||
static readonly Name: string = EditLogic.Name;
|
||||
private coreLogic: EditLogic;
|
||||
private shouldAlwaysEdit = false;
|
||||
|
||||
/**
|
||||
* Creates a new instance of the EditTool CLI wrapper
|
||||
* @param rootDirectory Root directory to ground this tool in.
|
||||
*/
|
||||
constructor(rootDirectory: string) {
|
||||
const coreLogicInstance = new EditLogic(rootDirectory);
|
||||
super(
|
||||
EditTool.Name,
|
||||
'Edit',
|
||||
`Replaces a SINGLE, UNIQUE occurrence of text within a file. Requires providing significant context around the change to ensure uniqueness. For moving/renaming files, use the Bash tool with \`mv\`. For replacing entire file contents or creating new files use the WriteFile tool. Always use the ReadFile tool to examine the file before using this tool.`,
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates validation to the core logic
|
||||
*/
|
||||
validateToolParams(params: EditToolParams): string | null {
|
||||
return this.coreLogic.validateParams(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates getting description to the core logic
|
||||
*/
|
||||
getDescription(params: EditToolParams): string {
|
||||
return this.coreLogic.getDescription(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the confirmation prompt for the Edit tool in the CLI.
|
||||
* It needs to calculate the diff to show the user.
|
||||
*/
|
||||
async shouldConfirmExecute(
|
||||
params: EditToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
if (this.shouldAlwaysEdit) {
|
||||
return false;
|
||||
}
|
||||
const validationError = this.validateToolParams(params);
|
||||
if (validationError) {
|
||||
console.error(
|
||||
`[EditTool Wrapper] Attempted confirmation with invalid parameters: ${validationError}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
let currentContent: string | null = null;
|
||||
let fileExists = false;
|
||||
let newContent = '';
|
||||
try {
|
||||
currentContent = fs.readFileSync(params.file_path, 'utf8');
|
||||
fileExists = true;
|
||||
} catch (err: unknown) {
|
||||
if (isNodeError(err) && err.code === 'ENOENT') {
|
||||
fileExists = false;
|
||||
} else {
|
||||
console.error(`Error reading file for confirmation diff: ${err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (params.old_string === '' && !fileExists) {
|
||||
newContent = params.new_string;
|
||||
} else if (!fileExists) {
|
||||
return false;
|
||||
} else if (currentContent !== null) {
|
||||
const occurrences = this.coreLogic['countOccurrences'](
|
||||
currentContent,
|
||||
params.old_string,
|
||||
);
|
||||
const expectedReplacements =
|
||||
params.expected_replacements === undefined
|
||||
? 1
|
||||
: params.expected_replacements;
|
||||
if (occurrences === 0 || occurrences !== expectedReplacements) {
|
||||
return false;
|
||||
}
|
||||
newContent = this.coreLogic['replaceAll'](
|
||||
currentContent,
|
||||
params.old_string,
|
||||
params.new_string,
|
||||
);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
const fileName = path.basename(params.file_path);
|
||||
const fileDiff = Diff.createPatch(
|
||||
fileName,
|
||||
currentContent ?? '',
|
||||
newContent,
|
||||
'Current',
|
||||
'Proposed',
|
||||
{ context: 3 },
|
||||
);
|
||||
const confirmationDetails: ToolEditConfirmationDetails = {
|
||||
title: `Confirm Edit: ${shortenPath(makeRelative(params.file_path, this.coreLogic['rootDirectory']))}`,
|
||||
fileName,
|
||||
fileDiff,
|
||||
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
||||
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
||||
this.shouldAlwaysEdit = true;
|
||||
}
|
||||
},
|
||||
};
|
||||
return confirmationDetails;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic
|
||||
*/
|
||||
async execute(params: EditToolParams): Promise<ToolResult> {
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// Import core logic and types from the server package
|
||||
import { GlobLogic, GlobToolParams, ToolResult } from '@gemini-code/server';
|
||||
|
||||
// Import CLI-specific base class and types
|
||||
import { BaseTool } from './tools.js';
|
||||
import { ToolCallConfirmationDetails } from '../ui/types.js';
|
||||
|
||||
/**
|
||||
* CLI wrapper for the Glob tool
|
||||
*/
|
||||
export class GlobTool extends BaseTool<GlobToolParams, ToolResult> {
|
||||
static readonly Name: string = GlobLogic.Name; // Use name from logic
|
||||
|
||||
// Core logic instance from the server package
|
||||
private coreLogic: GlobLogic;
|
||||
|
||||
/**
|
||||
* Creates a new instance of the GlobTool CLI wrapper
|
||||
* @param rootDirectory Root directory to ground this tool in.
|
||||
*/
|
||||
constructor(rootDirectory: string) {
|
||||
// Instantiate the core logic from the server package
|
||||
const coreLogicInstance = new GlobLogic(rootDirectory);
|
||||
|
||||
// Initialize the CLI BaseTool
|
||||
super(
|
||||
GlobTool.Name,
|
||||
'FindFiles', // Define display name here
|
||||
'Efficiently finds files matching specific glob patterns (e.g., `src/**/*.ts`, `**/*.md`), returning absolute paths sorted by modification time (newest first). Ideal for quickly locating files based on their name or path structure, especially in large codebases.', // Define description here
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates validation to the core logic
|
||||
*/
|
||||
validateToolParams(params: GlobToolParams): string | null {
|
||||
return this.coreLogic.validateToolParams(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates getting description to the core logic
|
||||
*/
|
||||
getDescription(params: GlobToolParams): string {
|
||||
return this.coreLogic.getDescription(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define confirmation behavior (Glob likely doesn't need confirmation)
|
||||
*/
|
||||
shouldConfirmExecute(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
params: GlobToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic
|
||||
*/
|
||||
async execute(params: GlobToolParams): Promise<ToolResult> {
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
|
||||
// Removed private methods (isWithinRoot)
|
||||
// as they are now part of GlobLogic in the server package.
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// Import core logic and types from the server package
|
||||
import { GrepLogic, GrepToolParams, ToolResult } from '@gemini-code/server';
|
||||
|
||||
// Import CLI-specific base class and types
|
||||
import { BaseTool } from './tools.js';
|
||||
import { ToolCallConfirmationDetails } from '../ui/types.js';
|
||||
|
||||
// --- Interfaces (Params defined in server package) ---
|
||||
|
||||
// --- GrepTool CLI Wrapper Class ---
|
||||
|
||||
/**
|
||||
* CLI wrapper for the Grep tool
|
||||
*/
|
||||
export class GrepTool extends BaseTool<GrepToolParams, ToolResult> {
|
||||
static readonly Name: string = GrepLogic.Name; // Use name from logic
|
||||
|
||||
// Core logic instance from the server package
|
||||
private coreLogic: GrepLogic;
|
||||
|
||||
/**
|
||||
* Creates a new instance of the GrepTool CLI wrapper
|
||||
* @param rootDirectory Root directory to ground this tool in.
|
||||
*/
|
||||
constructor(rootDirectory: string) {
|
||||
// Instantiate the core logic from the server package
|
||||
const coreLogicInstance = new GrepLogic(rootDirectory);
|
||||
|
||||
// Initialize the CLI BaseTool
|
||||
super(
|
||||
GrepTool.Name,
|
||||
'SearchText', // Define display name here
|
||||
'Searches for a regular expression pattern within the content of files in a specified directory (or current working directory). Can filter files by a glob pattern. Returns the lines containing matches, along with their file paths and line numbers.', // Define description here
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates validation to the core logic
|
||||
*/
|
||||
validateToolParams(params: GrepToolParams): string | null {
|
||||
return this.coreLogic.validateToolParams(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates getting description to the core logic
|
||||
*/
|
||||
getDescription(params: GrepToolParams): string {
|
||||
return this.coreLogic.getDescription(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define confirmation behavior (Grep likely doesn't need confirmation)
|
||||
*/
|
||||
shouldConfirmExecute(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
params: GrepToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic
|
||||
*/
|
||||
async execute(params: GrepToolParams): Promise<ToolResult> {
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
|
||||
// Removed private methods (resolveAndValidatePath, performGrepSearch, etc.)
|
||||
// as they are now part of GrepLogic in the server package.
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// Import core logic and types from the server package
|
||||
import { LSLogic, LSToolParams, ToolResult } from '@gemini-code/server';
|
||||
|
||||
// Import CLI-specific base class and types
|
||||
import { BaseTool } from './tools.js';
|
||||
import { ToolCallConfirmationDetails } from '../ui/types.js';
|
||||
|
||||
/**
|
||||
* CLI wrapper for the LS tool
|
||||
*/
|
||||
export class LSTool extends BaseTool<LSToolParams, ToolResult> {
|
||||
static readonly Name: string = LSLogic.Name; // Use name from logic
|
||||
|
||||
// Core logic instance from the server package
|
||||
private coreLogic: LSLogic;
|
||||
|
||||
/**
|
||||
* Creates a new instance of the LSTool CLI wrapper
|
||||
* @param rootDirectory Root directory to ground this tool in.
|
||||
*/
|
||||
constructor(rootDirectory: string) {
|
||||
// Instantiate the core logic from the server package
|
||||
const coreLogicInstance = new LSLogic(rootDirectory);
|
||||
|
||||
// Initialize the CLI BaseTool
|
||||
super(
|
||||
LSTool.Name,
|
||||
'ReadFolder', // Define display name here
|
||||
'Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.', // Define description here
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates validation to the core logic
|
||||
*/
|
||||
validateToolParams(params: LSToolParams): string | null {
|
||||
return this.coreLogic.validateToolParams(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates getting description to the core logic
|
||||
*/
|
||||
getDescription(params: LSToolParams): string {
|
||||
return this.coreLogic.getDescription(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define confirmation behavior (LS likely doesn't need confirmation)
|
||||
*/
|
||||
shouldConfirmExecute(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
params: LSToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic
|
||||
*/
|
||||
async execute(params: LSToolParams): Promise<ToolResult> {
|
||||
// The CLI wrapper could potentially modify the returnDisplay
|
||||
// from the core logic if needed, but for LS, the core logic's
|
||||
// display might be sufficient.
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
|
||||
// Removed private methods (isWithinRoot, shouldIgnore, errorResult)
|
||||
// as they are now part of LSLogic in the server package.
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import {
|
||||
ReadFileLogic,
|
||||
ReadFileToolParams,
|
||||
ToolResult,
|
||||
} from '@gemini-code/server';
|
||||
import { BaseTool } from './tools.js';
|
||||
import { ToolCallConfirmationDetails } from '../ui/types.js';
|
||||
|
||||
/**
|
||||
* CLI wrapper for the ReadFile tool
|
||||
*/
|
||||
export class ReadFileTool extends BaseTool<ReadFileToolParams, ToolResult> {
|
||||
static readonly Name: string = ReadFileLogic.Name;
|
||||
private coreLogic: ReadFileLogic;
|
||||
|
||||
/**
|
||||
* Creates a new instance of the ReadFileTool CLI wrapper
|
||||
* @param rootDirectory Root directory to ground this tool in.
|
||||
*/
|
||||
constructor(rootDirectory: string) {
|
||||
const coreLogicInstance = new ReadFileLogic(rootDirectory);
|
||||
super(
|
||||
ReadFileTool.Name,
|
||||
'ReadFile',
|
||||
'Reads and returns the content of a specified file from the local filesystem. Handles large files by allowing reading specific line ranges.',
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates validation to the core logic
|
||||
*/
|
||||
validateToolParams(_params: ReadFileToolParams): string | null {
|
||||
return this.coreLogic.validateToolParams(_params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates getting description to the core logic
|
||||
*/
|
||||
getDescription(_params: ReadFileToolParams): string {
|
||||
return this.coreLogic.getDescription(_params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define confirmation behavior here in the CLI wrapper if needed
|
||||
* For ReadFile, we likely don't need confirmation.
|
||||
*/
|
||||
shouldConfirmExecute(
|
||||
_params: ReadFileToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic
|
||||
*/
|
||||
execute(params: ReadFileToolParams): Promise<ToolResult> {
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,8 +4,8 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { FunctionDeclaration, Schema } from '@google/genai';
|
||||
import { ToolCallConfirmationDetails } from '../ui/types.js';
|
||||
import { ToolCallConfirmationDetails } from '@gemini-code/server';
|
||||
import { FunctionDeclaration } from '@google/genai';
|
||||
|
||||
/**
|
||||
* Interface representing the base Tool functionality
|
||||
@@ -66,83 +66,6 @@ export interface Tool<
|
||||
execute(params: TParams): Promise<TResult>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Base implementation for tools with common functionality
|
||||
*/
|
||||
export abstract class BaseTool<
|
||||
TParams = unknown,
|
||||
TResult extends ToolResult = ToolResult,
|
||||
> implements Tool<TParams, TResult>
|
||||
{
|
||||
/**
|
||||
* Creates a new instance of BaseTool
|
||||
* @param name Internal name of the tool (used for API calls)
|
||||
* @param displayName User-friendly display name of the tool
|
||||
* @param description Description of what the tool does
|
||||
* @param parameterSchema JSON Schema defining the parameters
|
||||
*/
|
||||
constructor(
|
||||
readonly name: string,
|
||||
readonly displayName: string,
|
||||
readonly description: string,
|
||||
readonly parameterSchema: Record<string, unknown>,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Function declaration schema computed from name, description, and parameterSchema
|
||||
*/
|
||||
get schema(): FunctionDeclaration {
|
||||
return {
|
||||
name: this.name,
|
||||
description: this.description,
|
||||
parameters: this.parameterSchema as Schema,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the parameters for the tool
|
||||
* This is a placeholder implementation and should be overridden
|
||||
* @param params Parameters to validate
|
||||
* @returns An error message string if invalid, null otherwise
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
validateToolParams(params: TParams): string | null {
|
||||
// Implementation would typically use a JSON Schema validator
|
||||
// This is a placeholder that should be implemented by derived classes
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a pre-execution description of the tool operation
|
||||
* Default implementation that should be overridden by derived classes
|
||||
* @param params Parameters for the tool execution
|
||||
* @returns A markdown string describing what the tool will do
|
||||
*/
|
||||
getDescription(params: TParams): string {
|
||||
return JSON.stringify(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if the tool should prompt for confirmation before execution
|
||||
* @param params Parameters for the tool execution
|
||||
* @returns Whether or not execute should be confirmed by the user.
|
||||
*/
|
||||
shouldConfirmExecute(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
params: TParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract method to execute the tool with the given parameters
|
||||
* Must be implemented by derived classes
|
||||
* @param params Parameters for the tool execution
|
||||
* @returns Result of the tool execution
|
||||
*/
|
||||
abstract execute(params: TParams): Promise<TResult>;
|
||||
}
|
||||
|
||||
export interface ToolResult {
|
||||
/**
|
||||
* Content meant to be included in LLM history.
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
// Import core logic and types from the server package
|
||||
import {
|
||||
WebFetchLogic,
|
||||
WebFetchToolParams,
|
||||
ToolResult,
|
||||
} from '@gemini-code/server';
|
||||
|
||||
// Import CLI-specific base class and UI types
|
||||
import { BaseTool } from './tools.js';
|
||||
import { ToolCallConfirmationDetails } from '../ui/types.js';
|
||||
|
||||
/**
|
||||
* CLI wrapper for the WebFetch tool.
|
||||
*/
|
||||
export class WebFetchTool extends BaseTool<WebFetchToolParams, ToolResult> {
|
||||
static readonly Name: string = WebFetchLogic.Name; // Use name from logic
|
||||
|
||||
// Core logic instance from the server package
|
||||
private coreLogic: WebFetchLogic;
|
||||
|
||||
constructor() {
|
||||
const coreLogicInstance = new WebFetchLogic();
|
||||
super(
|
||||
WebFetchTool.Name,
|
||||
'WebFetch', // Define display name here
|
||||
'Fetches text content from a given URL. Handles potential network errors and non-success HTTP status codes.', // Define description here
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
validateToolParams(params: WebFetchToolParams): string | null {
|
||||
// Delegate validation to core logic
|
||||
return this.coreLogic.validateParams(params);
|
||||
}
|
||||
|
||||
getDescription(params: WebFetchToolParams): string {
|
||||
// Delegate description generation to core logic
|
||||
return this.coreLogic.getDescription(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Define confirmation behavior (WebFetch likely doesn't need confirmation)
|
||||
*/
|
||||
async shouldConfirmExecute(
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
params: WebFetchToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic.
|
||||
*/
|
||||
async execute(params: WebFetchToolParams): Promise<ToolResult> {
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import * as Diff from 'diff';
|
||||
import {
|
||||
WriteFileLogic,
|
||||
WriteFileToolParams,
|
||||
ToolResult,
|
||||
makeRelative,
|
||||
shortenPath,
|
||||
} from '@gemini-code/server';
|
||||
import { BaseTool } from './tools.js';
|
||||
import {
|
||||
ToolCallConfirmationDetails,
|
||||
ToolConfirmationOutcome,
|
||||
ToolEditConfirmationDetails,
|
||||
} from '../ui/types.js';
|
||||
|
||||
/**
|
||||
* CLI wrapper for the WriteFile tool.
|
||||
*/
|
||||
export class WriteFileTool extends BaseTool<WriteFileToolParams, ToolResult> {
|
||||
static readonly Name: string = WriteFileLogic.Name;
|
||||
private shouldAlwaysWrite = false;
|
||||
|
||||
private coreLogic: WriteFileLogic;
|
||||
|
||||
constructor(rootDirectory: string) {
|
||||
const coreLogicInstance = new WriteFileLogic(rootDirectory);
|
||||
super(
|
||||
WriteFileTool.Name,
|
||||
'WriteFile',
|
||||
'Writes content to a specified file in the local filesystem.',
|
||||
(coreLogicInstance.schema.parameters as Record<string, unknown>) ?? {},
|
||||
);
|
||||
this.coreLogic = coreLogicInstance;
|
||||
}
|
||||
|
||||
validateToolParams(params: WriteFileToolParams): string | null {
|
||||
return this.coreLogic.validateParams(params);
|
||||
}
|
||||
|
||||
getDescription(params: WriteFileToolParams): string {
|
||||
return this.coreLogic.getDescription(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the confirmation prompt for the WriteFile tool in the CLI.
|
||||
*/
|
||||
async shouldConfirmExecute(
|
||||
params: WriteFileToolParams,
|
||||
): Promise<ToolCallConfirmationDetails | false> {
|
||||
if (this.shouldAlwaysWrite) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const validationError = this.validateToolParams(params);
|
||||
if (validationError) {
|
||||
console.error(
|
||||
`[WriteFile Wrapper] Attempted confirmation with invalid parameters: ${validationError}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
const relativePath = makeRelative(
|
||||
params.file_path,
|
||||
this.coreLogic['rootDirectory'],
|
||||
);
|
||||
const fileName = path.basename(params.file_path);
|
||||
|
||||
let currentContent = '';
|
||||
try {
|
||||
currentContent = fs.readFileSync(params.file_path, 'utf8');
|
||||
} catch {
|
||||
// File might not exist, that's okay for write/create
|
||||
}
|
||||
|
||||
const fileDiff = Diff.createPatch(
|
||||
fileName,
|
||||
currentContent,
|
||||
params.content,
|
||||
'Current',
|
||||
'Proposed',
|
||||
{ context: 3 },
|
||||
);
|
||||
|
||||
const confirmationDetails: ToolEditConfirmationDetails = {
|
||||
title: `Confirm Write: ${shortenPath(relativePath)}`,
|
||||
fileName,
|
||||
fileDiff,
|
||||
onConfirm: async (outcome: ToolConfirmationOutcome) => {
|
||||
if (outcome === ToolConfirmationOutcome.ProceedAlways) {
|
||||
this.shouldAlwaysWrite = true;
|
||||
}
|
||||
},
|
||||
};
|
||||
return confirmationDetails;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delegates execution to the core logic.
|
||||
*/
|
||||
async execute(params: WriteFileToolParams): Promise<ToolResult> {
|
||||
return this.coreLogic.execute(params);
|
||||
}
|
||||
}
|
||||
@@ -7,16 +7,16 @@
|
||||
import React from 'react';
|
||||
import { Box, Text, useInput } from 'ink';
|
||||
import SelectInput from 'ink-select-input';
|
||||
import { PartListUnion } from '@google/genai';
|
||||
import { DiffRenderer } from './DiffRenderer.js';
|
||||
import { UI_WIDTH } from '../../constants.js';
|
||||
import { Colors } from '../../colors.js';
|
||||
import {
|
||||
ToolCallConfirmationDetails,
|
||||
ToolEditConfirmationDetails,
|
||||
ToolConfirmationOutcome,
|
||||
ToolExecuteConfirmationDetails,
|
||||
} from '../../types.js';
|
||||
import { PartListUnion } from '@google/genai';
|
||||
import { DiffRenderer } from './DiffRenderer.js';
|
||||
import { UI_WIDTH } from '../../constants.js';
|
||||
import { Colors } from '../../colors.js';
|
||||
} from '@gemini-code/server';
|
||||
|
||||
export interface ToolConfirmationMessageProps {
|
||||
confirmationDetails: ToolCallConfirmationDetails;
|
||||
|
||||
@@ -7,16 +7,15 @@
|
||||
import React from 'react';
|
||||
import { Box, Text } from 'ink';
|
||||
import Spinner from 'ink-spinner';
|
||||
import {
|
||||
IndividualToolCallDisplay,
|
||||
ToolCallStatus,
|
||||
ToolCallConfirmationDetails,
|
||||
ToolEditConfirmationDetails,
|
||||
ToolExecuteConfirmationDetails,
|
||||
} from '../../types.js';
|
||||
import { IndividualToolCallDisplay, ToolCallStatus } from '../../types.js';
|
||||
import { DiffRenderer } from './DiffRenderer.js';
|
||||
import { FileDiff, ToolResultDisplay } from '../../../tools/tools.js';
|
||||
import { Colors } from '../../colors.js';
|
||||
import {
|
||||
ToolCallConfirmationDetails,
|
||||
ToolEditConfirmationDetails,
|
||||
ToolExecuteConfirmationDetails,
|
||||
} from '@gemini-code/server';
|
||||
|
||||
export const ToolMessage: React.FC<IndividualToolCallDisplay> = ({
|
||||
callId,
|
||||
|
||||
@@ -15,17 +15,16 @@ import {
|
||||
isNodeError,
|
||||
ToolResult,
|
||||
Config,
|
||||
ToolCallConfirmationDetails,
|
||||
ToolCallResponseInfo,
|
||||
} from '@gemini-code/server';
|
||||
import type { Chat, PartListUnion, FunctionDeclaration } from '@google/genai';
|
||||
// Import CLI types
|
||||
import {
|
||||
HistoryItem,
|
||||
IndividualToolCallDisplay,
|
||||
ToolCallStatus,
|
||||
} from '../types.js';
|
||||
import { Tool } from '../../tools/tools.js'; // CLI Tool definition
|
||||
import { StreamingState } from '../../core/gemini-stream.js';
|
||||
// Import CLI tool registry
|
||||
import { toolRegistry } from '../../tools/tool-registry.js';
|
||||
|
||||
const addHistoryItem = (
|
||||
@@ -112,7 +111,7 @@ export const useGeminiStream = (
|
||||
// This just clears the *UI* history, not the model history.
|
||||
// TODO: add a slash command for that.
|
||||
setDebugMessage('Clearing terminal.');
|
||||
setHistory((prevHistory) => []);
|
||||
setHistory((_) => []);
|
||||
return;
|
||||
} else if (config.getPassthroughCommands().includes(maybeCommand)) {
|
||||
// Execute and capture output
|
||||
@@ -188,14 +187,7 @@ export const useGeminiStream = (
|
||||
const signal = abortControllerRef.current.signal;
|
||||
|
||||
// Get ServerTool descriptions for the server call
|
||||
const serverTools: ServerTool[] = toolRegistry
|
||||
.getAllTools()
|
||||
.map((cliTool: Tool) => ({
|
||||
name: cliTool.name,
|
||||
schema: cliTool.schema,
|
||||
execute: (args: Record<string, unknown>) =>
|
||||
cliTool.execute(args as ToolArgs), // Pass execution
|
||||
}));
|
||||
const serverTools: ServerTool[] = toolRegistry.getAllTools();
|
||||
|
||||
const stream = client.sendMessageStream(
|
||||
chat,
|
||||
@@ -257,11 +249,18 @@ export const useGeminiStream = (
|
||||
);
|
||||
}
|
||||
|
||||
let description: string;
|
||||
try {
|
||||
description = cliTool.getDescription(args);
|
||||
} catch (e) {
|
||||
description = `Error: Unable to get description: ${getErrorMessage(e)}`;
|
||||
}
|
||||
|
||||
// Create the UI display object matching IndividualToolCallDisplay
|
||||
const toolCallDisplay: IndividualToolCallDisplay = {
|
||||
callId,
|
||||
name,
|
||||
description: cliTool.getDescription(args as ToolArgs),
|
||||
description,
|
||||
status: ToolCallStatus.Pending,
|
||||
resultDisplay: undefined,
|
||||
confirmationDetails: undefined,
|
||||
@@ -286,143 +285,35 @@ export const useGeminiStream = (
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
|
||||
// --- Tool Execution & Confirmation Logic ---
|
||||
const confirmationDetails = await cliTool.shouldConfirmExecute(
|
||||
args as ToolArgs,
|
||||
} else if (event.type === ServerGeminiEventType.ToolCallResponse) {
|
||||
updateFunctionResponseUI(event.value);
|
||||
} else if (
|
||||
event.type === ServerGeminiEventType.ToolCallConfirmation
|
||||
) {
|
||||
setHistory((prevHistory) =>
|
||||
prevHistory.map((item) => {
|
||||
if (
|
||||
item.id === currentToolGroupId &&
|
||||
item.type === 'tool_group'
|
||||
) {
|
||||
return {
|
||||
...item,
|
||||
tools: item.tools.map((tool) =>
|
||||
tool.callId === event.value.request.callId
|
||||
? {
|
||||
...tool,
|
||||
status: ToolCallStatus.Confirming,
|
||||
confirmationDetails: event.value.details,
|
||||
}
|
||||
: tool,
|
||||
),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
|
||||
if (confirmationDetails) {
|
||||
setHistory((prevHistory) =>
|
||||
prevHistory.map((item) => {
|
||||
if (
|
||||
item.id === currentToolGroupId &&
|
||||
item.type === 'tool_group'
|
||||
) {
|
||||
return {
|
||||
...item,
|
||||
tools: item.tools.map((tool) =>
|
||||
tool.callId === callId
|
||||
? {
|
||||
...tool,
|
||||
status: ToolCallStatus.Confirming,
|
||||
confirmationDetails,
|
||||
}
|
||||
: tool,
|
||||
),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
setStreamingState(StreamingState.WaitingForConfirmation);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setHistory((prevHistory) =>
|
||||
prevHistory.map((item) => {
|
||||
if (
|
||||
item.id === currentToolGroupId &&
|
||||
item.type === 'tool_group'
|
||||
) {
|
||||
return {
|
||||
...item,
|
||||
tools: item.tools.map((tool) =>
|
||||
tool.callId === callId
|
||||
? {
|
||||
...tool,
|
||||
status:
|
||||
tool.status === ToolCallStatus.Error
|
||||
? ToolCallStatus.Error
|
||||
: ToolCallStatus.Invoked,
|
||||
}
|
||||
: tool,
|
||||
),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
|
||||
const result: ToolResult = await cliTool.execute(
|
||||
args as ToolArgs,
|
||||
);
|
||||
const resultPart = {
|
||||
functionResponse: {
|
||||
name,
|
||||
id: callId,
|
||||
response: { output: result.llmContent },
|
||||
},
|
||||
};
|
||||
|
||||
setHistory((prevHistory) =>
|
||||
prevHistory.map((item) => {
|
||||
if (
|
||||
item.id === currentToolGroupId &&
|
||||
item.type === 'tool_group'
|
||||
) {
|
||||
return {
|
||||
...item,
|
||||
tools: item.tools.map((tool) =>
|
||||
tool.callId === callId
|
||||
? {
|
||||
...tool,
|
||||
status:
|
||||
tool.status === ToolCallStatus.Error
|
||||
? ToolCallStatus.Error
|
||||
: ToolCallStatus.Success,
|
||||
resultDisplay: result.returnDisplay,
|
||||
}
|
||||
: tool,
|
||||
),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
|
||||
// Execute the function and continue the stream
|
||||
await submitQuery(resultPart);
|
||||
return;
|
||||
} catch (execError: unknown) {
|
||||
const error = new Error(
|
||||
`Tool execution failed: ${execError instanceof Error ? execError.message : String(execError)}`,
|
||||
);
|
||||
const errorPart = {
|
||||
functionResponse: {
|
||||
name,
|
||||
id: callId,
|
||||
response: {
|
||||
error: `Tool execution failed: ${error.message}`,
|
||||
},
|
||||
},
|
||||
};
|
||||
setHistory((prevHistory) =>
|
||||
prevHistory.map((item) => {
|
||||
if (
|
||||
item.id === currentToolGroupId &&
|
||||
item.type === 'tool_group'
|
||||
) {
|
||||
return {
|
||||
...item,
|
||||
tools: item.tools.map((tool) =>
|
||||
tool.callId === callId
|
||||
? {
|
||||
...tool,
|
||||
status: ToolCallStatus.Error,
|
||||
resultDisplay: `Error: ${error.message}`,
|
||||
}
|
||||
: tool,
|
||||
),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
await submitQuery(errorPart);
|
||||
return;
|
||||
}
|
||||
setStreamingState(StreamingState.WaitingForConfirmation);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
@@ -445,6 +336,33 @@ export const useGeminiStream = (
|
||||
setStreamingState(StreamingState.Idle);
|
||||
}
|
||||
}
|
||||
|
||||
function updateFunctionResponseUI(toolResponse: ToolCallResponseInfo) {
|
||||
setHistory((prevHistory) =>
|
||||
prevHistory.map((item) => {
|
||||
if (item.id === currentToolGroupId && item.type === 'tool_group') {
|
||||
return {
|
||||
...item,
|
||||
tools: item.tools.map((tool) => {
|
||||
if (tool.callId === toolResponse.callId) {
|
||||
return {
|
||||
...tool,
|
||||
// TODO: Do we surface the error here?
|
||||
status: toolResponse.error
|
||||
? ToolCallStatus.Error
|
||||
: ToolCallStatus.Success,
|
||||
resultDisplay: toolResponse.resultDisplay,
|
||||
};
|
||||
} else {
|
||||
return tool;
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
// Dependencies need careful review - including updateGeminiMessage
|
||||
[
|
||||
@@ -464,8 +382,8 @@ export const useGeminiStream = (
|
||||
interface ServerTool {
|
||||
name: string;
|
||||
schema: FunctionDeclaration;
|
||||
shouldConfirmExecute(
|
||||
params: Record<string, unknown>,
|
||||
): Promise<ToolCallConfirmationDetails | false>;
|
||||
execute(params: Record<string, unknown>): Promise<ToolResult>;
|
||||
}
|
||||
|
||||
// Define a more specific type for tool arguments to replace 'any'
|
||||
type ToolArgs = Record<string, unknown>;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { ToolCallConfirmationDetails } from '@gemini-code/server';
|
||||
import { ToolResultDisplay } from '../tools/tools.js';
|
||||
|
||||
export enum ToolCallStatus {
|
||||
@@ -46,27 +47,3 @@ export type HistoryItem = HistoryItemBase &
|
||||
| { type: 'error'; text: string }
|
||||
| { type: 'tool_group'; tools: IndividualToolCallDisplay[] }
|
||||
);
|
||||
|
||||
export interface ToolCallConfirmationDetails {
|
||||
title: string;
|
||||
onConfirm: (outcome: ToolConfirmationOutcome) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface ToolEditConfirmationDetails
|
||||
extends ToolCallConfirmationDetails {
|
||||
fileName: string;
|
||||
fileDiff: string;
|
||||
}
|
||||
|
||||
export interface ToolExecuteConfirmationDetails
|
||||
extends ToolCallConfirmationDetails {
|
||||
command: string;
|
||||
rootCommand: string;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export enum ToolConfirmationOutcome {
|
||||
ProceedOnce,
|
||||
ProceedAlways,
|
||||
Cancel,
|
||||
}
|
||||
|
||||
@@ -1,473 +0,0 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright 2025 Google LLC
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
import { Content, SchemaUnion, Type } from '@google/genai';
|
||||
import {
|
||||
Config,
|
||||
getErrorMessage,
|
||||
isNodeError,
|
||||
GeminiClient,
|
||||
} from '@gemini-code/server';
|
||||
import { promises as fs } from 'fs';
|
||||
import { exec as _exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
// Define the AnalysisStatus type alias
|
||||
type AnalysisStatus =
|
||||
| 'Running'
|
||||
| 'SuccessReported'
|
||||
| 'ErrorReported'
|
||||
| 'Unknown'
|
||||
| 'AnalysisFailed';
|
||||
|
||||
// Promisify child_process.exec for easier async/await usage
|
||||
const execAsync = promisify(_exec);
|
||||
|
||||
// Define the expected interface for the AI client dependency
|
||||
export interface AiClient {
|
||||
generateJson(
|
||||
prompt: Content[], // Keep flexible or define a stricter prompt structure type
|
||||
schema: SchemaUnion,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
): Promise<any>; // Ideally, specify the expected JSON structure TAnalysisResult | TAnalysisFailure
|
||||
}
|
||||
|
||||
// Identifier for the background process (e.g., PID)
|
||||
// Using `unknown` allows more flexibility than `object` while still being type-safe
|
||||
export type ProcessHandle = number | string | unknown;
|
||||
|
||||
// Represents the structure expected from a successful LLM analysis call
|
||||
export interface AnalysisResult {
|
||||
summary: string;
|
||||
inferredStatus: 'Running' | 'SuccessReported' | 'ErrorReported' | 'Unknown';
|
||||
}
|
||||
|
||||
// Represents the structure returned when the LLM analysis itself fails
|
||||
export interface AnalysisFailure {
|
||||
error: string;
|
||||
inferredStatus: 'AnalysisFailed';
|
||||
}
|
||||
|
||||
// Type guard to check if the result is a failure object
|
||||
function isAnalysisFailure(
|
||||
result: AnalysisResult | AnalysisFailure,
|
||||
): result is AnalysisFailure {
|
||||
return (result as AnalysisFailure).inferredStatus === 'AnalysisFailed';
|
||||
}
|
||||
|
||||
// Represents the final outcome after polling is complete (or failed/timed out)
|
||||
export interface FinalAnalysisOutcome {
|
||||
status: string; // e.g., 'Completed_SuccessReported', 'TimedOut_Running', 'AnalysisFailed'
|
||||
summary: string; // Final summary or error message
|
||||
}
|
||||
|
||||
export class BackgroundTerminalAnalyzer {
|
||||
private geminiClient: GeminiClient | null = null;
|
||||
private readonly maxOutputAnalysisLength = 20000;
|
||||
private pollIntervalMs: number;
|
||||
private maxAttempts: number;
|
||||
private initialDelayMs: number;
|
||||
|
||||
constructor(
|
||||
config: Config, // Accept Config object
|
||||
options: {
|
||||
pollIntervalMs?: number;
|
||||
maxAttempts?: number;
|
||||
initialDelayMs?: number;
|
||||
} = {},
|
||||
) {
|
||||
try {
|
||||
// Initialize Gemini client using config
|
||||
this.geminiClient = new GeminiClient(
|
||||
config.getApiKey(),
|
||||
config.getModel(),
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Failed to initialize GeminiClient in BackgroundTerminalAnalyzer:',
|
||||
error,
|
||||
);
|
||||
// Set client to null so analyzeOutput handles it
|
||||
this.geminiClient = null;
|
||||
}
|
||||
this.pollIntervalMs = options.pollIntervalMs ?? 5000; // Default 5 seconds
|
||||
this.maxAttempts = options.maxAttempts ?? 6; // Default 6 attempts (approx 30s total)
|
||||
this.initialDelayMs = options.initialDelayMs ?? 500; // Default 0.5s initial delay
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls the output of a background process using an LLM
|
||||
* until a conclusive status is determined or timeout occurs.
|
||||
* @param pid The handle/identifier of the background process (typically PID number).
|
||||
* @param tempStdoutFilePath Path to the temporary file capturing stdout.
|
||||
* @param tempStderrFilePath Path to the temporary file capturing stderr.
|
||||
* @param command The command string that was executed (for context in prompts).
|
||||
* @returns A promise resolving to the final analysis outcome.
|
||||
*/
|
||||
async analyze(
|
||||
pid: ProcessHandle,
|
||||
tempStdoutFilePath: string,
|
||||
tempStderrFilePath: string,
|
||||
command: string,
|
||||
): Promise<FinalAnalysisOutcome> {
|
||||
// --- Validate PID ---
|
||||
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
|
||||
console.error(
|
||||
`BackgroundTerminalAnalyzer: Invalid or non-numeric PID provided (${pid}). Analysis cannot proceed.`,
|
||||
);
|
||||
return {
|
||||
status: 'AnalysisFailed',
|
||||
summary: 'Invalid PID provided for analysis.',
|
||||
};
|
||||
}
|
||||
|
||||
// --- Initial Delay ---
|
||||
// Wait briefly before the first check to allow the process to initialize
|
||||
// and potentially write initial output.
|
||||
await new Promise((resolve) => setTimeout(resolve, this.initialDelayMs));
|
||||
|
||||
let attempts = 0;
|
||||
let lastAnalysisResult: AnalysisResult | AnalysisFailure | null = null;
|
||||
|
||||
while (attempts < this.maxAttempts) {
|
||||
attempts++;
|
||||
let currentStdout = '';
|
||||
let currentStderr = '';
|
||||
|
||||
// --- Robust File Reading ---
|
||||
try {
|
||||
currentStdout = await fs.readFile(tempStdoutFilePath, 'utf-8');
|
||||
} catch (error: unknown) {
|
||||
// If file doesn't exist yet or isn't readable, treat as empty, but log warning
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
console.warn(
|
||||
`Attempt ${attempts}: Failed to read stdout file ${tempStdoutFilePath}: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
try {
|
||||
currentStderr = await fs.readFile(tempStderrFilePath, 'utf-8');
|
||||
} catch (error: unknown) {
|
||||
if (!isNodeError(error) || error.code !== 'ENOENT') {
|
||||
console.warn(
|
||||
`Attempt ${attempts}: Failed to read stderr file ${tempStderrFilePath}: ${getErrorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Process Status Check ---
|
||||
let isRunning = false;
|
||||
try {
|
||||
// Check if process is running *before* the final analysis if it seems to have ended
|
||||
isRunning = await this.isProcessRunning(pid);
|
||||
if (!isRunning) {
|
||||
// Reread files one last time in case output was written just before exit
|
||||
try {
|
||||
currentStdout = await fs.readFile(tempStdoutFilePath, 'utf-8');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
try {
|
||||
currentStderr = await fs.readFile(tempStderrFilePath, 'utf-8');
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
|
||||
lastAnalysisResult = await this.performLlmAnalysis(
|
||||
currentStdout,
|
||||
currentStderr,
|
||||
command,
|
||||
pid,
|
||||
);
|
||||
|
||||
if (isAnalysisFailure(lastAnalysisResult)) {
|
||||
return {
|
||||
status: 'Completed_AnalysisFailed',
|
||||
summary: `Process ended. Final analysis failed: ${lastAnalysisResult.error}`,
|
||||
};
|
||||
}
|
||||
// Append ProcessEnded to the status determined by the final analysis
|
||||
return {
|
||||
status: 'Completed_' + lastAnalysisResult.inferredStatus,
|
||||
summary: `Process ended. Final analysis summary: ${lastAnalysisResult.summary}`,
|
||||
};
|
||||
}
|
||||
} catch (procCheckError: unknown) {
|
||||
// Log the error but allow polling to continue, as log analysis might still be useful
|
||||
console.warn(
|
||||
`Could not check process status for PID ${pid} on attempt ${attempts}: ${getErrorMessage(procCheckError)}`,
|
||||
);
|
||||
// Decide if you want to bail out here or continue analysis based on logs only
|
||||
// For now, we continue.
|
||||
}
|
||||
|
||||
// --- LLM Analysis ---
|
||||
lastAnalysisResult = await this.performLlmAnalysis(
|
||||
currentStdout,
|
||||
currentStderr,
|
||||
command,
|
||||
pid,
|
||||
);
|
||||
|
||||
if (isAnalysisFailure(lastAnalysisResult)) {
|
||||
console.error(
|
||||
`LLM Analysis failed for PID ${pid} on attempt ${attempts}:`,
|
||||
lastAnalysisResult.error,
|
||||
);
|
||||
// Stop polling on analysis failure, returning the specific failure status
|
||||
return {
|
||||
status: lastAnalysisResult.inferredStatus,
|
||||
summary: lastAnalysisResult.error,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Exit Conditions ---
|
||||
if (
|
||||
lastAnalysisResult.inferredStatus === 'SuccessReported' ||
|
||||
lastAnalysisResult.inferredStatus === 'ErrorReported'
|
||||
) {
|
||||
return {
|
||||
status: lastAnalysisResult.inferredStatus,
|
||||
summary: lastAnalysisResult.summary,
|
||||
};
|
||||
}
|
||||
|
||||
// Heuristic: If the process seems stable and 'Running' after several checks,
|
||||
// return that status without waiting for the full timeout. Adjust threshold as needed.
|
||||
const runningExitThreshold = Math.floor(this.maxAttempts / 3) + 1; // e.g., exit after attempt 4 if maxAttempts is 6
|
||||
if (
|
||||
attempts >= runningExitThreshold &&
|
||||
lastAnalysisResult.inferredStatus === 'Running'
|
||||
) {
|
||||
return {
|
||||
status: lastAnalysisResult.inferredStatus,
|
||||
summary: lastAnalysisResult.summary,
|
||||
};
|
||||
}
|
||||
|
||||
// --- Wait before next poll ---
|
||||
if (attempts < this.maxAttempts) {
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, this.pollIntervalMs),
|
||||
);
|
||||
}
|
||||
} // End while loop
|
||||
|
||||
// --- Timeout Condition ---
|
||||
console.warn(
|
||||
`Polling timed out for PID ${pid} after ${this.maxAttempts} attempts.`,
|
||||
);
|
||||
|
||||
// Determine final status based on the last successful analysis (if any)
|
||||
const finalStatus =
|
||||
lastAnalysisResult && !isAnalysisFailure(lastAnalysisResult)
|
||||
? `TimedOut_${lastAnalysisResult.inferredStatus}` // e.g., TimedOut_Running
|
||||
: 'TimedOut_AnalysisFailed'; // If last attempt failed or no analysis succeeded
|
||||
|
||||
const finalSummary =
|
||||
lastAnalysisResult && !isAnalysisFailure(lastAnalysisResult)
|
||||
? `Polling timed out after ${this.maxAttempts} attempts. Last known summary: ${lastAnalysisResult.summary}`
|
||||
: lastAnalysisResult && isAnalysisFailure(lastAnalysisResult)
|
||||
? `Polling timed out; last analysis attempt failed: ${lastAnalysisResult}`
|
||||
: `Polling timed out after ${this.maxAttempts} attempts without any successful analysis.`;
|
||||
|
||||
return { status: finalStatus, summary: finalSummary };
|
||||
}
|
||||
|
||||
// --- Actual Implementation of isProcessRunning ---
|
||||
/**
|
||||
* Checks if the background process is still running using OS-specific methods.
|
||||
* @param pid Process handle/identifier (expects a number for standard checks).
|
||||
* @returns True if running, false otherwise.
|
||||
* @throws Error if the check itself fails critically (e.g., command not found, permissions).
|
||||
*/
|
||||
private async isProcessRunning(pid: ProcessHandle): Promise<boolean> {
|
||||
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
|
||||
console.warn(
|
||||
`isProcessRunning: Invalid PID provided (${pid}). Assuming not running.`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
// Windows: Use tasklist command
|
||||
const command = `tasklist /FI "PID eq ${pid}" /NH`; // /NH for no header
|
||||
const { stdout } = await execAsync(command);
|
||||
// Check if the output contains the process information (it will have the image name if found)
|
||||
return stdout.toLowerCase().includes('.exe'); // A simple check, adjust if needed
|
||||
} else {
|
||||
// Linux/macOS/Unix-like: Use kill -0 signal
|
||||
// process.kill sends signal 0 to check existence without killing
|
||||
process.kill(pid, 0);
|
||||
return true; // If no error is thrown, process exists
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
if (isNodeError(error) && error.code === 'ESRCH') {
|
||||
// ESRCH: Standard error code for "No such process" on Unix-like systems
|
||||
return false;
|
||||
} else if (
|
||||
process.platform === 'win32' &&
|
||||
getErrorMessage(error).includes('No tasks are running')
|
||||
) {
|
||||
// tasklist specific error when PID doesn't exist
|
||||
return false;
|
||||
} else {
|
||||
// Other errors (e.g., EPERM - permission denied) mean we couldn't determine status.
|
||||
// Re-throwing might be appropriate depending on desired behavior.
|
||||
// Here, we log it and cautiously return true, assuming it *might* still be running.
|
||||
console.warn(
|
||||
`isProcessRunning(${pid}) encountered error: ${getErrorMessage(error)}. Assuming process might still exist.`,
|
||||
);
|
||||
// Or you could throw the error: throw new Error(`Failed to check process status for PID ${pid}: ${error.message}`);
|
||||
return true; // Cautious assumption
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- LLM Analysis Method (largely unchanged but added validation robustness) ---
|
||||
private async performLlmAnalysis(
|
||||
stdoutContent: string,
|
||||
stderrContent: string,
|
||||
command: string,
|
||||
pid: number,
|
||||
): Promise<AnalysisResult | AnalysisFailure> {
|
||||
if (!this.geminiClient) {
|
||||
return {
|
||||
error: '[Analysis unavailable: Gemini client not initialized]',
|
||||
inferredStatus: 'AnalysisFailed',
|
||||
};
|
||||
}
|
||||
|
||||
const truncatedStdout =
|
||||
stdoutContent.substring(0, this.maxOutputAnalysisLength) +
|
||||
(stdoutContent.length > this.maxOutputAnalysisLength
|
||||
? '... [truncated]'
|
||||
: '');
|
||||
const truncatedStderr =
|
||||
stderrContent.substring(0, this.maxOutputAnalysisLength) +
|
||||
(stderrContent.length > this.maxOutputAnalysisLength
|
||||
? '... [truncated]'
|
||||
: '');
|
||||
|
||||
const analysisPrompt = `**Analyze Background Process Logs**
|
||||
|
||||
**Context:** A command (\`${command}\`) was executed in the background. You are analyzing the standard output (stdout) and standard error (stderr) collected so far to understand its progress and outcome. This analysis will be used to inform a user about what the command did.
|
||||
|
||||
**Input:**
|
||||
* **Command:** \`${command}\`
|
||||
* **Stdout:**
|
||||
\`\`\`
|
||||
${truncatedStdout}
|
||||
\`\`\`
|
||||
* **Stderr:**
|
||||
\`\`\`
|
||||
${truncatedStderr}
|
||||
\`\`\`
|
||||
|
||||
**Task:**
|
||||
|
||||
Based *only* on the provided stdout and stderr:
|
||||
|
||||
1. **Interpret and Summarize:** Do *not* simply repeat the logs. Analyze the content and provide a concise summary describing the significant actions, results, progress, or errors reported by the command. If logs are empty, state that no output was captured. Summaries should be formatted as markdown. Focus on the most recent or conclusive information if logs are long.
|
||||
2. **Infer Current Status:** Based *only* on the log content, infer the likely status of the command's execution as reflected *in the logs*. Choose the most appropriate status from the options defined in the schema (\`Running\`, \`SuccessReported\`, \`ErrorReported\`, \`Unknown\`). For example:
|
||||
* If logs show ongoing activity or progress messages without clear completion or error signals, use \`Running\`.
|
||||
* If logs contain explicit messages indicating successful completion or the final expected output of a successful run, use \`SuccessReported\`.
|
||||
* If logs contain error messages, stack traces, or failure indications, use \`ErrorReported\`.
|
||||
* If the logs provide insufficient information to determine a clear status (e.g., empty logs, vague messages), use \`Unknown\`.
|
||||
* If dealing with a node server, the second the port has been shown the server is considered booted, use \`SuccessReported\`.
|
||||
* *Note: This status reflects the log content, not necessarily the absolute real-time state of the OS process.*
|
||||
3. **Format Output:** Return the results as a JSON object adhering strictly to the following schema:
|
||||
|
||||
\`\`\`json
|
||||
${JSON.stringify(
|
||||
{
|
||||
// Generate the schema JSON string for the prompt context
|
||||
type: 'object',
|
||||
properties: {
|
||||
summary: {
|
||||
type: 'string',
|
||||
description:
|
||||
'Concise markdown summary (1-3 sentences) of log interpretation.',
|
||||
},
|
||||
inferredStatus: {
|
||||
type: 'string',
|
||||
enum: ['Running', 'SuccessReported', 'ErrorReported', 'Unknown'],
|
||||
description:
|
||||
'Status inferred from logs: Running, SuccessReported, ErrorReported, Unknown',
|
||||
},
|
||||
},
|
||||
required: ['summary', 'inferredStatus'],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}
|
||||
\`\`\`
|
||||
|
||||
**Instructions:**
|
||||
* The \`summary\` must be an interpretation of the logs, focusing on key outcomes or activities. Prioritize recent events if logs are extensive.
|
||||
* The \`inferredStatus\` should reflect the most likely state *deduced purely from the log text provided*. Ensure it is one of the specified enum values.`;
|
||||
|
||||
const schema: SchemaUnion = {
|
||||
type: Type.OBJECT,
|
||||
properties: {
|
||||
summary: {
|
||||
type: Type.STRING,
|
||||
description:
|
||||
'Concise markdown summary (1-3 sentences) of log interpretation.',
|
||||
},
|
||||
inferredStatus: {
|
||||
type: Type.STRING,
|
||||
description:
|
||||
'Status inferred from logs: Running, SuccessReported, ErrorReported, Unknown',
|
||||
enum: ['Running', 'SuccessReported', 'ErrorReported', 'Unknown'],
|
||||
},
|
||||
},
|
||||
required: ['summary', 'inferredStatus'],
|
||||
};
|
||||
|
||||
try {
|
||||
const resultJson = await this.geminiClient.generateJson(
|
||||
[{ role: 'user', parts: [{ text: analysisPrompt }] }],
|
||||
schema,
|
||||
);
|
||||
|
||||
// Validate and construct the AnalysisResult object
|
||||
const summary =
|
||||
typeof resultJson?.summary === 'string'
|
||||
? resultJson.summary
|
||||
: '[Summary unavailable]';
|
||||
|
||||
// Define valid statuses using the AnalysisStatus type (ensure it's defined above)
|
||||
const validStatuses: Array<Exclude<AnalysisStatus, 'AnalysisFailed'>> = [
|
||||
'Running',
|
||||
'SuccessReported',
|
||||
'ErrorReported',
|
||||
'Unknown',
|
||||
];
|
||||
|
||||
// Cast the unknown value to string before checking with includes
|
||||
const statusString = resultJson?.inferredStatus as string;
|
||||
const inferredStatus = validStatuses.includes(
|
||||
statusString as Exclude<AnalysisStatus, 'AnalysisFailed'>,
|
||||
)
|
||||
? (statusString as Exclude<AnalysisStatus, 'AnalysisFailed'>)
|
||||
: 'Unknown';
|
||||
|
||||
// Explicitly construct the object matching AnalysisResult type
|
||||
const analysisResult: AnalysisResult = { summary, inferredStatus };
|
||||
return analysisResult;
|
||||
} catch (error: unknown) {
|
||||
console.error(`LLM Analysis Request Failed for PID ${pid}:`, error);
|
||||
// Return the AnalysisFailure type
|
||||
const analysisFailure: AnalysisFailure = {
|
||||
error: `[Analysis failed: ${getErrorMessage(error)}]`,
|
||||
inferredStatus: 'AnalysisFailed', // This matches the AnalysisStatus type
|
||||
};
|
||||
return analysisFailure;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user