Skip to content

Commit 6cf00ec

Browse files
author
linyuan.yang
committed
整理 shell 代码
1 parent 2950083 commit 6cf00ec

18 files changed

Lines changed: 473 additions & 433 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Reads new output from a background process started by shell or a script tool with mode="background".
2+
3+
Pass the exact numeric processId returned by the tool. The result contains only output produced since the previous read. If the process is still running, call read_process again later with the same processId. If the process has exited, the result includes the final exit status.

‎packages/sbot/prompts/tools/command/read_task.txt‎

Lines changed: 0 additions & 3 deletions
This file was deleted.

‎packages/sbot/prompts/tools/command/shell.txt‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
Executes a shell command or multi-line shell script in a given working directory. Returns stdout and stderr separately. Default timeout 60 s.
1+
Executes shell code in a given working directory. Put the command or multi-line shell script in code. Returns stdout and stderr separately. Use mode="sync" for normal commands; default timeout is 60 s.
22

3-
Set background=true for commands that may take longer than a normal tool call, such as builds, test suites, servers, or long scripts. In background mode, the tool waits briefly for completion; if the process is still running, it returns current output plus a taskid. Use read_task with that taskid to read later output.
3+
Use mode="background" for commands that may take longer than a normal tool call, such as builds, test suites, servers, or long scripts. In background mode, the tool waits briefly for completion; if the process is still running, it returns current output plus a numeric processId. Use read_process with that processId to read later output.
44

5-
Supports all forms:
5+
The code field supports all forms:
66
- Single command: "git status"
77
- Chained commands: "npm install && npm run build"
88
- Multi-line script: "for f in *.log; do rm \"$f\"; done"

‎packages/sbot/src/Tools/Command/index.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import { type StructuredToolInterface } from '@langchain/core/tools';
22

3-
export { createShellTool, createReadTaskTool } from './shell';
3+
export { createShellTool, createReadProcessTool } from './shell';
44
export { createPythonCodeTool } from './python';
55
export { createPsCodeTool } from './powershell';
66

7-
import { createShellTool, createReadTaskTool } from './shell';
7+
import { createShellTool, createReadProcessTool } from './shell';
88
import { createPythonCodeTool } from './python';
99
import { createPsCodeTool } from './powershell';
1010

1111
export function createCommandTools(): StructuredToolInterface[] {
1212
return [
1313
createShellTool(),
14-
createReadTaskTool(),
14+
createReadProcessTool(),
1515
createPythonCodeTool(),
1616
createPsCodeTool(),
1717
].filter((t): t is StructuredToolInterface => t !== null);

‎packages/sbot/src/Tools/Command/powershell.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { type StructuredToolInterface } from '@langchain/core/tools';
22
import { loadPrompt } from '../../Core/PromptLoader';
3-
import { createScriptCodeTool, isCommandAvailable } from './utils';
3+
import { CodeRuntime, createScriptCodeTool, isCommandAvailable } from './utils';
44

55
interface PsInterpreter {
66
interpreter: string;
@@ -24,6 +24,7 @@ export function createPsCodeTool(): StructuredToolInterface | null {
2424
return createScriptCodeTool({
2525
name: 'execute_ps_code',
2626
description: loadPrompt(`tools/command/ps_code_${ps.interpreter}.txt`),
27+
runtime: CodeRuntime.PowerShell,
2728
interpreter: ps.interpreter,
2829
preArgs: ps.preArgs,
2930
ext: '.ps1',

‎packages/sbot/src/Tools/Command/python.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { type StructuredToolInterface } from '@langchain/core/tools';
22
import { loadPrompt } from '../../Core/PromptLoader';
3-
import { createScriptCodeTool, isCommandAvailable } from './utils';
3+
import { CodeRuntime, createScriptCodeTool, isCommandAvailable } from './utils';
44

55
// 现代 Linux/macOS 默认只有 python3,Windows 通常是 python;都试一遍。
66
let _pythonInterpreter: string | null | undefined;
@@ -18,6 +18,7 @@ export function createPythonCodeTool(): StructuredToolInterface | null {
1818
return createScriptCodeTool({
1919
name: 'execute_python_code',
2020
description: loadPrompt('tools/command/python_code.txt'),
21+
runtime: CodeRuntime.Python,
2122
interpreter,
2223
ext: '.py',
2324
});
Lines changed: 7 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,18 @@
1-
import { DynamicStructuredTool, type StructuredToolInterface } from '@langchain/core/tools';
2-
import { z } from 'zod';
31
import {
4-
ShellManager,
5-
createErrorResult,
6-
formatBackgroundResult,
7-
type MCPToolResult,
2+
createShellTool as createCoreShellTool,
3+
createReadProcessTool as createCoreReadProcessTool,
84
} from 'scorpio.ai';
5+
import { type StructuredToolInterface } from '@langchain/core/tools';
96
import { loadPrompt } from '../../Core/PromptLoader';
10-
import { resolveWorkingDir, runShellCommand } from './utils';
117

128
export function createShellTool(): StructuredToolInterface {
13-
return new DynamicStructuredTool({
14-
name: 'shell',
9+
return createCoreShellTool({
1510
description: loadPrompt('tools/command/shell.txt'),
16-
schema: z.object({
17-
command: z.string().min(1).describe('Command or multi-line shell script to run, e.g. "git status", "npm install && npm run build", or a newline-separated script'),
18-
workingDir: z.string().describe('Absolute path of the working directory'),
19-
stdin: z.any().optional().describe('Data to pipe into the command via stdin. Prefer a string; objects/arrays are auto-serialized to JSON.'),
20-
timeout: z.number().optional().default(60000).describe('Timeout in milliseconds, default 60000 (60 s)'),
21-
background: z.boolean().optional().default(false).describe('Run as a background task. If still running after yieldMs, returns existing output plus a taskid for read_task.'),
22-
yieldMs: z.number().optional().default(1000).describe('Background mode only: how long to wait for immediate completion before returning a taskid, default 1000 ms'),
23-
}) as any,
24-
func: async ({ command, workingDir, stdin, timeout = 60000, background = false, yieldMs = 1000 }: any) => {
25-
// schema 用 z.any() 是为了同时满足两点:(1) Zod v4 的 toJSONSchema 不接受 transform/preprocess;
26-
// (2) 模型偶尔不遵守 string 约束、直接塞 object/array。这里在 func 入口统一序列化兜底。
27-
if (stdin != null && typeof stdin !== 'string') stdin = JSON.stringify(stdin);
28-
const { cwd, error } = await resolveWorkingDir(workingDir);
29-
if (error) return createErrorResult(error);
30-
if (background) {
31-
const result = await ShellManager.exec(command, cwd!, yieldMs, `background command "${command}"`, stdin);
32-
return formatBackgroundResult(result);
33-
}
34-
return runShellCommand(command, cwd!, timeout, `command "${command}"`, stdin);
35-
},
3611
});
3712
}
3813

39-
export function createReadTaskTool(): StructuredToolInterface {
40-
return new DynamicStructuredTool({
41-
name: 'read_task',
42-
description: loadPrompt('tools/command/read_task.txt'),
43-
schema: z.object({
44-
taskid: z.string().min(1).describe('The taskid returned by shell background=true or script mode=background'),
45-
yieldMs: z.number().optional().default(1000).describe('How long to wait for new output, default 1000 ms'),
46-
}) as any,
47-
func: async ({ taskid, yieldMs = 1000 }: any): Promise<MCPToolResult> => {
48-
const result = await ShellManager.readTask(taskid, yieldMs);
49-
return formatBackgroundResult(result);
50-
},
14+
export function createReadProcessTool(): StructuredToolInterface {
15+
return createCoreReadProcessTool({
16+
description: loadPrompt('tools/command/read_process.txt'),
5117
});
5218
}

‎packages/sbot/src/Tools/Command/utils.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,14 @@
33
export {
44
runProgram,
55
runShellCommand,
6-
resolveShell,
6+
getCurrentShell,
77
isCommandAvailable,
88
validatePath,
99
resolveWorkingDir,
1010
createScriptCodeTool,
1111
scriptCodeSchema,
12+
CodeRuntime,
13+
CodeToolMode,
1214
MAX_OUTPUT_BYTES,
1315
} from 'scorpio.ai';
1416
export type { ScriptCodeToolOptions } from 'scorpio.ai';
Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
import fs from 'fs';
2+
import os from 'os';
3+
import path from 'path';
4+
import crypto from 'crypto';
5+
import { z } from 'zod';
6+
import { DynamicStructuredTool, type StructuredToolInterface } from '@langchain/core/tools';
7+
import { createErrorResult, type MCPToolResult } from '../Core';
8+
import { runProgram, runShellCommand } from './runtime/foreground';
9+
import { resolveWorkingDir } from './runtime/workingDir';
10+
import { isCommandAvailable } from './runtime/process';
11+
import { processManager, formatProcessResult } from './runtime/processManager';
12+
13+
export enum CodeRuntime {
14+
Shell = 'shell',
15+
PowerShell = 'powershell',
16+
Python = 'python',
17+
NodeJs = 'nodejs',
18+
}
19+
20+
export enum CodeToolMode {
21+
Sync = 'sync',
22+
Background = 'background',
23+
}
24+
25+
export { CodeToolMode as ShellToolMode, CodeToolMode as ScriptCodeMode };
26+
27+
function normalizeStdin(stdin: unknown): string | undefined {
28+
if (stdin == null) return undefined;
29+
return typeof stdin === 'string' ? stdin : JSON.stringify(stdin);
30+
}
31+
32+
function withExecutionMode<T extends z.ZodRawShape>(base: z.ZodObject<T>) {
33+
return z.discriminatedUnion('mode', [
34+
base.extend({
35+
mode: z.literal(CodeToolMode.Sync).describe('Run synchronously and return the final output in this tool call'),
36+
timeout: z.number().optional().default(60000).describe('Timeout in milliseconds, default 60000 (60 s)'),
37+
}),
38+
base.extend({
39+
mode: z.literal(CodeToolMode.Background).describe('Run in the background and use read_process for later output'),
40+
yieldMs: z.number().optional().default(1000).describe('How long to wait for immediate completion before returning a processid, default 1000 ms'),
41+
}),
42+
]);
43+
}
44+
45+
const shellCodeBaseSchema = z.object({
46+
code: z.string().min(1).describe('Command or multi-line shell script to run, e.g. "git status", "npm install && npm run build", or a newline-separated script'),
47+
workingDir: z.string().describe('Absolute path of the working directory'),
48+
stdin: z.any().optional().describe('Data to pipe into the command via stdin. Prefer a string; objects/arrays are auto-serialized to JSON.'),
49+
});
50+
51+
const scriptCodeBaseSchema = z.object({
52+
code: z.string().min(1).describe('Script source code to execute; written to a temp file automatically'),
53+
workingDir: z.string().describe('Absolute path of the working directory for the script'),
54+
stdin: z.any().optional().describe('Data to pipe into the script via stdin. Prefer a string; objects/arrays are auto-serialized to JSON.'),
55+
});
56+
57+
export const shellToolSchema = withExecutionMode(shellCodeBaseSchema);
58+
export const scriptCodeSchema = withExecutionMode(scriptCodeBaseSchema);
59+
60+
export const readProcessToolSchema = z.object({
61+
processId: z.number().int().positive().describe('The numeric processId returned by shell/script mode="background"'),
62+
yieldMs: z.number().optional().default(1000).describe('How long to wait for new output, default 1000 ms'),
63+
});
64+
65+
type ShellToolInput = z.infer<typeof shellToolSchema>;
66+
type ScriptCodeInput = z.infer<typeof scriptCodeSchema>;
67+
type ReadProcessToolInput = z.infer<typeof readProcessToolSchema>;
68+
type CodeToolInput = ShellToolInput | ScriptCodeInput;
69+
70+
export interface ShellToolOptions {
71+
name?: string;
72+
description: string;
73+
}
74+
75+
export interface ReadProcessToolOptions {
76+
name?: string;
77+
description: string;
78+
}
79+
80+
export interface ScriptCodeToolOptions {
81+
name: string;
82+
description: string;
83+
runtime: CodeRuntime;
84+
interpreter: string;
85+
preArgs?: string[];
86+
ext: string;
87+
}
88+
89+
interface ExecuteCodeOptions {
90+
runtime: CodeRuntime;
91+
label: string;
92+
interpreter?: string;
93+
preArgs?: string[];
94+
ext?: string;
95+
}
96+
97+
async function executeCode(input: CodeToolInput, opts: ExecuteCodeOptions): Promise<MCPToolResult> {
98+
const { cwd, error: cwdError } = await resolveWorkingDir(input.workingDir);
99+
if (cwdError) return createErrorResult(cwdError);
100+
101+
const stdin = normalizeStdin(input.stdin);
102+
if (opts.runtime === CodeRuntime.Shell) {
103+
if (input.mode === CodeToolMode.Background) {
104+
const result = await processManager.exec(input.code, cwd!, input.yieldMs ?? 1000, stdin);
105+
return formatProcessResult(result);
106+
}
107+
return runShellCommand(input.code, cwd!, input.timeout ?? 60000, `command "${input.code}"`, stdin);
108+
}
109+
110+
if (!opts.interpreter || !opts.ext) {
111+
return createErrorResult(`Missing interpreter configuration for ${opts.runtime}`);
112+
}
113+
114+
const tmpFile = path.join(os.tmpdir(), `sbot_script_${Date.now()}_${crypto.randomBytes(6).toString('hex')}${opts.ext}`);
115+
try {
116+
await fs.promises.writeFile(tmpFile, input.code, 'utf8');
117+
} catch (e: any) {
118+
return createErrorResult(`Failed to write temp script: ${e?.message ?? e}`);
119+
}
120+
121+
let cleanupByBackgroundManager = false;
122+
const cleanupTempFile = async () => {
123+
try { await fs.promises.unlink(tmpFile); } catch { /* ignore */ }
124+
};
125+
126+
try {
127+
const runArgs = [...(opts.preArgs ?? []), tmpFile];
128+
if (input.mode === CodeToolMode.Background) {
129+
cleanupByBackgroundManager = true;
130+
const result = await processManager.runProgram(
131+
opts.interpreter,
132+
runArgs,
133+
cwd!,
134+
input.yieldMs ?? 1000,
135+
stdin,
136+
cleanupTempFile,
137+
);
138+
return formatProcessResult(result);
139+
}
140+
return runProgram(opts.interpreter, runArgs, cwd!, input.timeout ?? 60000, opts.label, stdin);
141+
} finally {
142+
if (!cleanupByBackgroundManager) await cleanupTempFile();
143+
}
144+
}
145+
146+
export function createShellTool({ name = 'shell', description }: ShellToolOptions): StructuredToolInterface {
147+
return new DynamicStructuredTool({
148+
name,
149+
description,
150+
schema: shellToolSchema as any,
151+
func: async (input: ShellToolInput): Promise<MCPToolResult> => executeCode(input, {
152+
runtime: CodeRuntime.Shell,
153+
label: name,
154+
}),
155+
});
156+
}
157+
158+
export function createScriptCodeTool({ name, description, runtime, interpreter, preArgs = [], ext }: ScriptCodeToolOptions): StructuredToolInterface | null {
159+
if (!isCommandAvailable(interpreter)) return null;
160+
return new DynamicStructuredTool({
161+
name,
162+
description,
163+
schema: scriptCodeSchema as any,
164+
func: async (input: ScriptCodeInput): Promise<MCPToolResult> => executeCode(input, {
165+
runtime,
166+
label: name,
167+
interpreter,
168+
preArgs,
169+
ext,
170+
}),
171+
});
172+
}
173+
174+
export function createReadProcessTool({ name = 'read_process', description }: ReadProcessToolOptions): StructuredToolInterface {
175+
return new DynamicStructuredTool({
176+
name,
177+
description,
178+
schema: readProcessToolSchema as any,
179+
func: async ({ processId, yieldMs = 1000 }: ReadProcessToolInput): Promise<MCPToolResult> => {
180+
const result = await processManager.readProcess(processId, yieldMs);
181+
return formatProcessResult(result);
182+
},
183+
});
184+
}
Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,24 @@
1-
export { runProgram, runShellCommand, MAX_OUTPUT_BYTES } from './runner';
2-
export { resolveShell, isCommandAvailable } from './shell';
3-
export { validatePath, resolveWorkingDir } from './paths';
4-
export { createScriptCodeTool, scriptCodeSchema, ScriptCodeMode, type ScriptCodeToolOptions } from './scriptTool';
1+
export { runProgram, runShellCommand, MAX_OUTPUT_BYTES } from './runtime/foreground';
2+
export { getCurrentShell, isCommandAvailable } from './runtime/process';
3+
export { validatePath, resolveWorkingDir } from './runtime/workingDir';
54
export {
6-
ShellManager,
7-
formatBackgroundResult,
8-
} from './ShellManager';
5+
createShellTool,
6+
createReadProcessTool,
7+
shellToolSchema,
8+
readProcessToolSchema,
9+
scriptCodeSchema,
10+
CodeRuntime,
11+
CodeToolMode,
12+
ShellToolMode,
13+
ScriptCodeMode,
14+
type ShellToolOptions,
15+
type ReadProcessToolOptions,
16+
createScriptCodeTool,
17+
type ScriptCodeToolOptions,
18+
} from './codeTool';
19+
export {
20+
ProcessManager,
21+
processManager,
22+
formatProcessResult,
23+
type ManagedProcessResult,
24+
} from './runtime/processManager';

0 commit comments

Comments
 (0)