Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion core/src/code_executors/code_execution_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import {cloneDeep} from 'lodash-es';

import {base64Encode, isBase64Encoded} from '../utils/env_aware_utils.js';

export enum FileContentEncoding {
UTF8 = 'utf-8',
BASE64 = 'base64',
}

/**
* A structure that contains a file name and its content
*/
Expand All @@ -18,10 +23,15 @@ export interface File {
name: string;

/**
* The base64 - encoded bytes of the file content.
* The encoded bytes of the file content.
* */
content: string;

/**
* The encoding of the file content.
*/
contentEncoding?: FileContentEncoding;

/**
* The mime type of the file (e.g., ' image / png')
* */
Expand Down Expand Up @@ -67,6 +77,11 @@ export interface CodeExecutionInput {
* The execution ID for the stateful code execution.
* */
executionId?: string;

/**
* Optional arguments to pass to the executed code/script.
*/
args?: string[] | Record<string, string | number | boolean>;
}

/**
Expand Down
78 changes: 72 additions & 6 deletions core/src/code_executors/unsafe_local_code_executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,14 @@ import {spawn} from 'child_process';
import * as fs from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import {getMimeTypeAndEncoding} from '../utils/file_extension_utils.js';
import {materializeFiles} from '../utils/file_utils.js';
import {logger} from '../utils/logger.js';
import {BaseCodeExecutor, ExecuteCodeParams} from './base_code_executor.js';
import {
CodeExecutionLanguage,
CodeExecutionResult,
File,
} from './code_execution_utils.js';

const IS_WINDOWS = os.platform() === 'win32';
Expand Down Expand Up @@ -157,6 +160,10 @@ export class UnsafeLocalCodeExecutor extends BaseCodeExecutor {
const filePath = res.filePath;
tempDir = res.tempDir;

if (params.codeExecutionInput.inputFiles) {
await materializeFiles(params.codeExecutionInput.inputFiles, tempDir);
}

let command = this.nodeCommandPath;
let args = [filePath];

Expand All @@ -177,7 +184,21 @@ export class UnsafeLocalCodeExecutor extends BaseCodeExecutor {
args = ['/c', filePath];
}

return await new Promise<CodeExecutionResult>((resolve) => {
if (params.codeExecutionInput.args) {
if (Array.isArray(params.codeExecutionInput.args)) {
args.push(...params.codeExecutionInput.args);
} else {
for (const [k, v] of Object.entries(params.codeExecutionInput.args)) {
args.push(`--${k}`, String(v));
Comment thread
kalenkevich marked this conversation as resolved.
}
}
}

const executionResult = await new Promise<{
stdout: string;
stderr: string;
exitCode: number | null;
}>((resolve) => {
const child = spawn(command, args, {
timeout: this.timeoutSeconds * 1000,
killSignal: 'SIGKILL',
Expand Down Expand Up @@ -206,14 +227,59 @@ export class UnsafeLocalCodeExecutor extends BaseCodeExecutor {
child.on('close', (exitCode, signal) => {
if (signal === 'SIGKILL' || signal === 'SIGTERM') {
stderr += `\nCode execution timed out after ${this.timeoutSeconds} seconds.`;
} else if (exitCode !== 0 && exitCode !== null) {
if (!stderr) {
stderr = `Exit code ${exitCode}`;
}
}
resolve({
stdout,
stderr,
outputFiles: [],
});
resolve({stdout, stderr, exitCode});
});
});

const outputFiles: File[] = [];
try {
const allFiles = await fs.readdir(tempDir, {recursive: true});
Comment thread
ScottMansfield marked this conversation as resolved.
for (const relativeFilePath of allFiles) {
const fullPath = path.join(tempDir, relativeFilePath);
const stat = await fs.lstat(fullPath);

if (!stat.isFile()) {
continue;
}

// Skip the script file
if (relativeFilePath === path.basename(filePath)) {
continue;
}

// Skip input files
const isInputFile = params.codeExecutionInput.inputFiles?.some(
(f) => f.name === relativeFilePath,
);
if (isInputFile) {
continue;
}

const fileContent = await fs.readFile(fullPath);
const {mimeType, encoding} = getMimeTypeAndEncoding(
path.extname(relativeFilePath),
);
outputFiles.push({
name: relativeFilePath,
content: fileContent.toString(encoding),
contentEncoding: encoding,
mimeType: mimeType,
});
}
} catch (e) {
logger.error(`Error scanning output files: ${e}`);
}

return {
stdout: executionResult.stdout,
stderr: executionResult.stderr,
outputFiles,
};
} finally {
if (tempDir) {
await fs.rm(tempDir, {recursive: true, force: true});
Expand Down
1 change: 1 addition & 0 deletions core/src/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export type {ExecuteCodeParams} from './code_executors/base_code_executor.js';
export {BuiltInCodeExecutor} from './code_executors/built_in_code_executor.js';
export {
CodeExecutionLanguage,
FileContentEncoding,
type CodeExecutionInput,
type CodeExecutionResult,
type File,
Expand Down
3 changes: 3 additions & 0 deletions core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export {
loadSkillFromDir,
validateSkillDir,
} from './skills/loader.js';
export {RunSkillInlineScriptTool} from './tools/skill/run_skill_inline_script_tool.js';
export {RunSkillScriptTool} from './tools/skill/run_skill_script_tool.js';

export * from './telemetry/google_cloud.js';
export * from './telemetry/setup.js';
export * from './tools/mcp/mcp_session_manager.js';
Expand Down
118 changes: 118 additions & 0 deletions core/src/tools/skill/run_skill_inline_script_tool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/**
* @license
* Copyright 2026 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/

import {FunctionDeclaration, Type} from '@google/genai';
import {isLlmAgent} from '../../agents/llm_agent.js';
import {CodeExecutionLanguage} from '../../code_executors/code_execution_utils.js';
import {experimental} from '../../utils/experimental.js';
import {materializeFiles} from '../../utils/file_utils.js';
import {BaseTool, RunAsyncToolRequest} from '../base_tool.js';
import {SkillToolset} from './skill_toolset.js';

@experimental
export class RunSkillInlineScriptTool extends BaseTool {
constructor(private toolset: SkillToolset) {
super({
name: 'run_skill_inline_script',
description:
'Executes an inline script provided directly in the request.',
});
}

override _getDeclaration(): FunctionDeclaration {
return {
name: this.name,
description: this.description,
parameters: {
type: Type.OBJECT,
properties: {
script_content: {
type: Type.STRING,
description: 'The content of the script to execute.',
},
language: {
type: Type.STRING,
description: 'The language/type of the script.',
enum: Object.values(CodeExecutionLanguage).filter(
(l) => l !== CodeExecutionLanguage.UNSPECIFIED,
),
},
args: {
anyOf: [
{type: Type.OBJECT},
{type: Type.ARRAY, items: {type: Type.STRING}},
],
description:
'Optional arguments to pass to the script as key-value pairs or an array of strings.',
},
},
required: ['script_content', 'language'],
},
};
}

override async runAsync({
args,
toolContext,
}: RunAsyncToolRequest): Promise<unknown> {
const inlineScriptContent = args['script_content'] as string;
const language = args['language'] as string;
const scriptArgs = args['args'] as
| string[]
| Record<string, string | number | boolean>
| undefined;

if (!inlineScriptContent) {
return {
error: 'Script content is required.',
errorCode: 'MISSING_SCRIPT_CONTENT',
};
}
if (!language) {
return {
error: 'Language is required.',
errorCode: 'MISSING_LANGUAGE',
};
}

let codeExecutor = this.toolset?.codeExecutor;
if (!codeExecutor) {
const agent = toolContext.invocationContext.agent;
if (isLlmAgent(agent)) {
codeExecutor = agent.codeExecutor;
}
}

if (!codeExecutor) {
return {
error: 'No code executor configured.',
errorCode: 'NO_CODE_EXECUTOR',
};
}

try {
const result = await codeExecutor.executeCode({
invocationContext: toolContext.invocationContext,
codeExecutionInput: {
code: inlineScriptContent,
inputFiles: [],
language: language as CodeExecutionLanguage,
args: scriptArgs,
},
});

// Final filename could be different if there was a collision, so update the result.
result.outputFiles = await materializeFiles(result.outputFiles);

return result;
} catch (e: unknown) {
return {
error: `Failed to execute inline script: ${(e as Error).message}`,
errorCode: 'EXECUTION_ERROR',
};
}
}
}
Loading
Loading