File size: 6,699 Bytes
7421850
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
import {
  BaseDeclarativeTool,
  BaseToolInvocation,
  type ToolResult,
  type ToolInvocation,
  type ExecuteOptions,
  Kind,
  type MessageBus,
} from '@google/gemini-cli-core';
import type { SessionContext } from './types.js';

export { z };

/**
 * An error that, when thrown from a tool's action, will be visible to the
 * Gemini model in the conversation. Useful for providing feedback to the
 * model about why a tool failed so it can retry or adjust its approach.
 */
export class ModelVisibleError extends Error {
  constructor(message: string | Error) {
    super(message instanceof Error ? message.message : message);
    this.name = 'ModelVisibleError';
  }
}

/**
 * The declarative definition of a tool, including its name, description,
 * Zod input schema, and optional error-handling behavior.
 *
 * @typeParam T - The Zod schema type that validates the tool's input parameters.
 */
export interface ToolDefinition<T extends z.ZodTypeAny> {
  /**
   * A unique name for the tool, used by the model to invoke it.
   */
  name: string;

  /**
   * A human-readable description of what the tool does.
   * This is sent to the model to help it decide when to use the tool.
   */
  description: string;

  /**
   * A Zod schema that validates and type-checks the tool's input parameters.
   */
  inputSchema: T;

  /**
   * When `true`, any errors thrown by the tool's action will be sent back
   * to the model as part of the conversation. Defaults to `false`.
   */
  sendErrorsToModel?: boolean;
}

/**
 * A complete tool definition that combines a {@link ToolDefinition} with
 * an executable action function.
 *
 * The action receives validated parameters (inferred from the Zod schema)
 * and an optional {@link SessionContext}, and returns an arbitrary result
 * that will be serialized and sent back to the model.
 *
 * @typeParam T - The Zod schema type that validates the tool's input parameters.
 */
export interface Tool<T extends z.ZodTypeAny> extends ToolDefinition<T> {
  /**
   * The function executed when the model invokes this tool.
   *
   * @param params - The validated input parameters, typed from the Zod schema.
   * @param context - Optional session context providing access to filesystem,
   *   shell, and other session state.
   * @returns A promise resolving to the tool's output, which will be
   *   serialized (to JSON if not already a string) and sent to the model.
   */
  action: (params: z.infer<T>, context?: SessionContext) => Promise<unknown>;
}

class SdkToolInvocation<T extends z.ZodTypeAny> extends BaseToolInvocation<
  z.infer<T>,
  ToolResult
> {
  constructor(
    params: z.infer<T>,
    messageBus: MessageBus,
    private readonly action: (
      params: z.infer<T>,
      context?: SessionContext,
    ) => Promise<unknown>,
    private readonly context: SessionContext | undefined,
    toolName: string,
    private readonly sendErrorsToModel: boolean = false,
  ) {
    super(params, messageBus, toolName);
  }

  getDescription(): string {
    return `Executing ${this._toolName}...`;
  }

  async execute({
    abortSignal: _abortSignal,
    updateOutput: _updateOutput,
  }: ExecuteOptions): Promise<ToolResult> {
    try {
      const result = await this.action(this.params, this.context);
      const output =
        typeof result === 'string' ? result : JSON.stringify(result, null, 2);
      return {
        llmContent: output,
        returnDisplay: output,
      };
    } catch (error) {
      if (this.sendErrorsToModel || error instanceof ModelVisibleError) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        return {
          llmContent: `Error: ${errorMessage}`,
          returnDisplay: `Error: ${errorMessage}`,
          error: {
            message: errorMessage,
          },
        };
      }
      throw error;
    }
  }
}

/**
 * A wrapper that integrates an SDK {@link Tool} into the core tool registry.
 *
 * Handles parameter validation, execution, error handling (including
 * {@link ModelVisibleError}), and context binding for tool invocations.
 *
 * @typeParam T - The Zod schema type that validates the tool's input parameters.
 */
export class SdkTool<T extends z.ZodTypeAny> extends BaseDeclarativeTool<
  z.infer<T>,
  ToolResult
> {
  constructor(
    private readonly definition: Tool<T>,
    messageBus: MessageBus,
    _agent?: unknown,
    private readonly context?: SessionContext,
  ) {
    super(
      definition.name,
      definition.name,
      definition.description,
      Kind.Other,
      zodToJsonSchema(definition.inputSchema),
      messageBus,
    );
  }

  bindContext(context: SessionContext): SdkTool<T> {
    return new SdkTool(this.definition, this.messageBus, undefined, context);
  }

  createInvocationWithContext(
    params: z.infer<T>,
    messageBus: MessageBus,
    context: SessionContext | undefined,
    toolName?: string,
  ): ToolInvocation<z.infer<T>, ToolResult> {
    return new SdkToolInvocation(
      params,
      messageBus,
      this.definition.action,
      context || this.context,
      toolName || this.name,
      this.definition.sendErrorsToModel,
    );
  }

  protected createInvocation(
    params: z.infer<T>,
    messageBus: MessageBus,
    toolName?: string,
  ): ToolInvocation<z.infer<T>, ToolResult> {
    return new SdkToolInvocation(
      params,
      messageBus,
      this.definition.action,
      this.context,
      toolName || this.name,
      this.definition.sendErrorsToModel,
    );
  }
}

/**
 * Helper function to create a {@link Tool} by combining a definition and an action.
 *
 * @typeParam T - The Zod schema type for the tool's input parameters.
 * @param definition - The tool's name, description, and input schema.
 * @param action - The async function to execute when the tool is invoked.
 * @returns A complete {@link Tool} object ready to be passed to
 *   {@link GeminiCliAgentOptions.tools}.
 *
 * @example
 * ```typescript
 * import { z, tool } from '@google/gemini-cli-sdk';
 *
 * const myTool = tool(
 *   {
 *     name: 'get_weather',
 *     description: 'Get the current weather for a location',
 *     inputSchema: z.object({ city: z.string() }),
 *   },
 *   async (params) => {
 *     return `Weather in ${params.city}: Sunny, 25°C`;
 *   },
 * );
 * ```
 */
export function tool<T extends z.ZodTypeAny>(
  definition: ToolDefinition<T>,
  action: (params: z.infer<T>, context?: SessionContext) => Promise<unknown>,
): Tool<T> {
  return {
    ...definition,
    action,
  };
}