cerebras-cli 1.0.5 → 1.0.138
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +27 -0
- package/Dockerfile +10 -0
- package/README.md +5 -3
- package/bin/{opencode.cjs → opencode} +4 -4
- package/bunfig.toml +4 -0
- package/package.json +89 -32
- package/parsers-config.ts +239 -0
- package/script/build.ts +151 -0
- package/script/postinstall.mjs +122 -0
- package/script/publish.ts +256 -0
- package/script/schema.ts +47 -0
- package/snake_game.py +111 -0
- package/src/acp/README.md +164 -0
- package/src/acp/agent.ts +812 -0
- package/src/acp/session.ts +70 -0
- package/src/acp/types.ts +22 -0
- package/src/agent/agent.ts +310 -0
- package/src/agent/generate.txt +75 -0
- package/src/auth/index.ts +70 -0
- package/src/bun/index.ts +152 -0
- package/src/bus/global.ts +10 -0
- package/src/bus/index.ts +142 -0
- package/src/cli/bootstrap.ts +17 -0
- package/src/cli/cmd/acp.ts +88 -0
- package/src/cli/cmd/agent.ts +165 -0
- package/src/cli/cmd/auth.ts +369 -0
- package/src/cli/cmd/cmd.ts +7 -0
- package/src/cli/cmd/debug/config.ts +15 -0
- package/src/cli/cmd/debug/file.ts +91 -0
- package/src/cli/cmd/debug/index.ts +43 -0
- package/src/cli/cmd/debug/lsp.ts +47 -0
- package/src/cli/cmd/debug/ripgrep.ts +83 -0
- package/src/cli/cmd/debug/scrap.ts +15 -0
- package/src/cli/cmd/debug/skill.ts +36 -0
- package/src/cli/cmd/debug/snapshot.ts +48 -0
- package/src/cli/cmd/export.ts +88 -0
- package/src/cli/cmd/generate.ts +38 -0
- package/src/cli/cmd/github.ts +1200 -0
- package/src/cli/cmd/import.ts +98 -0
- package/src/cli/cmd/mcp.ts +400 -0
- package/src/cli/cmd/models.ts +77 -0
- package/src/cli/cmd/pr.ts +112 -0
- package/src/cli/cmd/run.ts +342 -0
- package/src/cli/cmd/serve.ts +31 -0
- package/src/cli/cmd/session.ts +106 -0
- package/src/cli/cmd/stats.ts +298 -0
- package/src/cli/cmd/tui/app.tsx +833 -0
- package/src/cli/cmd/tui/attach.ts +25 -0
- package/src/cli/cmd/tui/component/border.tsx +21 -0
- package/src/cli/cmd/tui/component/cerebras-onboarding.tsx +225 -0
- package/src/cli/cmd/tui/component/dialog-agent.tsx +31 -0
- package/src/cli/cmd/tui/component/dialog-command.tsx +124 -0
- package/src/cli/cmd/tui/component/dialog-feedback.tsx +160 -0
- package/src/cli/cmd/tui/component/dialog-mcp.tsx +86 -0
- package/src/cli/cmd/tui/component/dialog-model.tsx +223 -0
- package/src/cli/cmd/tui/component/dialog-notification.tsx +78 -0
- package/src/cli/cmd/tui/component/dialog-provider.tsx +222 -0
- package/src/cli/cmd/tui/component/dialog-session-list.tsx +97 -0
- package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
- package/src/cli/cmd/tui/component/dialog-status.tsx +114 -0
- package/src/cli/cmd/tui/component/dialog-tag.tsx +44 -0
- package/src/cli/cmd/tui/component/dialog-theme-list.tsx +50 -0
- package/src/cli/cmd/tui/component/logo.tsx +43 -0
- package/src/cli/cmd/tui/component/notification-banner.tsx +58 -0
- package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +530 -0
- package/src/cli/cmd/tui/component/prompt/history.tsx +107 -0
- package/src/cli/cmd/tui/component/prompt/index.tsx +931 -0
- package/src/cli/cmd/tui/component/quickstart-onboarding.tsx +116 -0
- package/src/cli/cmd/tui/context/args.tsx +14 -0
- package/src/cli/cmd/tui/context/directory.ts +12 -0
- package/src/cli/cmd/tui/context/exit.tsx +23 -0
- package/src/cli/cmd/tui/context/helper.tsx +25 -0
- package/src/cli/cmd/tui/context/keybind.tsx +111 -0
- package/src/cli/cmd/tui/context/kv.tsx +49 -0
- package/src/cli/cmd/tui/context/local.tsx +338 -0
- package/src/cli/cmd/tui/context/prompt.tsx +18 -0
- package/src/cli/cmd/tui/context/route.tsx +45 -0
- package/src/cli/cmd/tui/context/sdk.tsx +75 -0
- package/src/cli/cmd/tui/context/sync.tsx +374 -0
- package/src/cli/cmd/tui/context/theme/aura.json +69 -0
- package/src/cli/cmd/tui/context/theme/ayu.json +80 -0
- package/src/cli/cmd/tui/context/theme/catppuccin-macchiato.json +233 -0
- package/src/cli/cmd/tui/context/theme/catppuccin.json +112 -0
- package/src/cli/cmd/tui/context/theme/cobalt2.json +228 -0
- package/src/cli/cmd/tui/context/theme/dracula.json +219 -0
- package/src/cli/cmd/tui/context/theme/everforest.json +241 -0
- package/src/cli/cmd/tui/context/theme/flexoki.json +237 -0
- package/src/cli/cmd/tui/context/theme/github.json +233 -0
- package/src/cli/cmd/tui/context/theme/gruvbox.json +95 -0
- package/src/cli/cmd/tui/context/theme/kanagawa.json +77 -0
- package/src/cli/cmd/tui/context/theme/material.json +235 -0
- package/src/cli/cmd/tui/context/theme/matrix.json +77 -0
- package/src/cli/cmd/tui/context/theme/mercury.json +252 -0
- package/src/cli/cmd/tui/context/theme/monokai.json +221 -0
- package/src/cli/cmd/tui/context/theme/nightowl.json +221 -0
- package/src/cli/cmd/tui/context/theme/nord.json +223 -0
- package/src/cli/cmd/tui/context/theme/one-dark.json +84 -0
- package/src/cli/cmd/tui/context/theme/orng.json +245 -0
- package/src/cli/cmd/tui/context/theme/palenight.json +222 -0
- package/src/cli/cmd/tui/context/theme/rosepine.json +234 -0
- package/src/cli/cmd/tui/context/theme/solarized.json +223 -0
- package/src/cli/cmd/tui/context/theme/synthwave84.json +226 -0
- package/src/cli/cmd/tui/context/theme/tokyonight.json +243 -0
- package/src/cli/cmd/tui/context/theme/vercel.json +245 -0
- package/src/cli/cmd/tui/context/theme/vesper.json +218 -0
- package/src/cli/cmd/tui/context/theme/zenburn.json +223 -0
- package/src/cli/cmd/tui/context/theme.tsx +1077 -0
- package/src/cli/cmd/tui/event.ts +39 -0
- package/src/cli/cmd/tui/routes/home.tsx +150 -0
- package/src/cli/cmd/tui/routes/session/dialog-message.tsx +93 -0
- package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +37 -0
- package/src/cli/cmd/tui/routes/session/footer.tsx +76 -0
- package/src/cli/cmd/tui/routes/session/header.tsx +181 -0
- package/src/cli/cmd/tui/routes/session/index.tsx +1695 -0
- package/src/cli/cmd/tui/routes/session/sidebar.tsx +686 -0
- package/src/cli/cmd/tui/spawn.ts +60 -0
- package/src/cli/cmd/tui/thread.ts +120 -0
- package/src/cli/cmd/tui/ui/dialog-alert.tsx +55 -0
- package/src/cli/cmd/tui/ui/dialog-confirm.tsx +81 -0
- package/src/cli/cmd/tui/ui/dialog-help.tsx +36 -0
- package/src/cli/cmd/tui/ui/dialog-prompt.tsx +75 -0
- package/src/cli/cmd/tui/ui/dialog-select.tsx +317 -0
- package/src/cli/cmd/tui/ui/dialog.tsx +170 -0
- package/src/cli/cmd/tui/ui/spinner.ts +368 -0
- package/src/cli/cmd/tui/ui/toast.tsx +100 -0
- package/src/cli/cmd/tui/util/clipboard.ts +127 -0
- package/src/cli/cmd/tui/util/editor.ts +32 -0
- package/src/cli/cmd/tui/util/terminal.ts +114 -0
- package/src/cli/cmd/tui/worker.ts +63 -0
- package/src/cli/cmd/uninstall.ts +344 -0
- package/src/cli/cmd/upgrade.ts +67 -0
- package/src/cli/cmd/web.ts +84 -0
- package/src/cli/error.ts +55 -0
- package/src/cli/ui.ts +84 -0
- package/src/cli/upgrade.ts +25 -0
- package/src/command/index.ts +79 -0
- package/src/command/template/initialize.txt +10 -0
- package/src/command/template/review.txt +73 -0
- package/src/config/config.ts +886 -0
- package/src/config/markdown.ts +41 -0
- package/src/env/index.ts +26 -0
- package/src/file/fzf.ts +124 -0
- package/src/file/ignore.ts +83 -0
- package/src/file/index.ts +326 -0
- package/src/file/ripgrep.ts +391 -0
- package/src/file/time.ts +38 -0
- package/src/file/watcher.ts +89 -0
- package/src/flag/flag.ts +29 -0
- package/src/format/formatter.ts +277 -0
- package/src/format/index.ts +137 -0
- package/src/global/index.ts +52 -0
- package/src/id/id.ts +73 -0
- package/src/ide/index.ts +75 -0
- package/src/index.ts +158 -0
- package/src/installation/index.ts +194 -0
- package/src/lsp/client.ts +215 -0
- package/src/lsp/index.ts +370 -0
- package/src/lsp/language.ts +111 -0
- package/src/lsp/server.ts +1327 -0
- package/src/mcp/auth.ts +82 -0
- package/src/mcp/index.ts +576 -0
- package/src/mcp/oauth-callback.ts +203 -0
- package/src/mcp/oauth-provider.ts +132 -0
- package/src/notification/index.ts +101 -0
- package/src/patch/index.ts +622 -0
- package/src/permission/index.ts +198 -0
- package/src/plugin/index.ts +95 -0
- package/src/project/bootstrap.ts +31 -0
- package/src/project/instance.ts +68 -0
- package/src/project/project.ts +133 -0
- package/src/project/state.ts +65 -0
- package/src/project/vcs.ts +77 -0
- package/src/provider/auth.ts +143 -0
- package/src/provider/models-macro.ts +11 -0
- package/src/provider/models.ts +93 -0
- package/src/provider/provider.ts +1005 -0
- package/src/provider/sdk/openai-compatible/src/README.md +5 -0
- package/src/provider/sdk/openai-compatible/src/index.ts +2 -0
- package/src/provider/sdk/openai-compatible/src/openai-compatible-provider.ts +100 -0
- package/src/provider/sdk/openai-compatible/src/responses/convert-to-openai-responses-input.ts +303 -0
- package/src/provider/sdk/openai-compatible/src/responses/map-openai-responses-finish-reason.ts +27 -0
- package/src/provider/sdk/openai-compatible/src/responses/openai-config.ts +18 -0
- package/src/provider/sdk/openai-compatible/src/responses/openai-error.ts +22 -0
- package/src/provider/sdk/openai-compatible/src/responses/openai-responses-api-types.ts +207 -0
- package/src/provider/sdk/openai-compatible/src/responses/openai-responses-language-model.ts +1713 -0
- package/src/provider/sdk/openai-compatible/src/responses/openai-responses-prepare-tools.ts +177 -0
- package/src/provider/sdk/openai-compatible/src/responses/openai-responses-settings.ts +1 -0
- package/src/provider/sdk/openai-compatible/src/responses/tool/code-interpreter.ts +88 -0
- package/src/provider/sdk/openai-compatible/src/responses/tool/file-search.ts +128 -0
- package/src/provider/sdk/openai-compatible/src/responses/tool/image-generation.ts +115 -0
- package/src/provider/sdk/openai-compatible/src/responses/tool/local-shell.ts +65 -0
- package/src/provider/sdk/openai-compatible/src/responses/tool/web-search-preview.ts +104 -0
- package/src/provider/sdk/openai-compatible/src/responses/tool/web-search.ts +103 -0
- package/src/provider/transform.ts +406 -0
- package/src/pty/index.ts +226 -0
- package/src/ratelimit/index.ts +185 -0
- package/src/server/error.ts +36 -0
- package/src/server/project.ts +50 -0
- package/src/server/server.ts +2463 -0
- package/src/server/tui.ts +71 -0
- package/src/session/compaction.ts +257 -0
- package/src/session/index.ts +470 -0
- package/src/session/message-v2.ts +641 -0
- package/src/session/message.ts +189 -0
- package/src/session/processor.ts +448 -0
- package/src/session/prompt/anthropic-20250930.txt +166 -0
- package/src/session/prompt/anthropic.txt +105 -0
- package/src/session/prompt/anthropic_spoof.txt +1 -0
- package/src/session/prompt/beast.txt +147 -0
- package/src/session/prompt/build-switch.txt +5 -0
- package/src/session/prompt/codex.txt +318 -0
- package/src/session/prompt/compaction.txt +12 -0
- package/src/session/prompt/copilot-gpt-5.txt +143 -0
- package/src/session/prompt/gemini.txt +155 -0
- package/src/session/prompt/max-steps.txt +16 -0
- package/src/session/prompt/plan-reminder-anthropic.txt +67 -0
- package/src/session/prompt/plan.txt +26 -0
- package/src/session/prompt/polaris.txt +107 -0
- package/src/session/prompt/qwen.txt +109 -0
- package/src/session/prompt/summarize.txt +4 -0
- package/src/session/prompt/title.txt +36 -0
- package/src/session/prompt.ts +1541 -0
- package/src/session/retry.ts +82 -0
- package/src/session/revert.ts +108 -0
- package/src/session/status.ts +75 -0
- package/src/session/summary.ts +203 -0
- package/src/session/system.ts +148 -0
- package/src/session/todo.ts +36 -0
- package/src/share/share-next.ts +195 -0
- package/src/share/share.ts +87 -0
- package/src/skill/index.ts +2 -0
- package/src/skill/skill.ts +138 -0
- package/src/snapshot/index.ts +197 -0
- package/src/storage/storage.ts +226 -0
- package/src/telemetry/index.ts +247 -0
- package/src/tool/bash.ts +365 -0
- package/src/tool/bash.txt +128 -0
- package/src/tool/batch.ts +173 -0
- package/src/tool/batch.txt +28 -0
- package/src/tool/codesearch.ts +138 -0
- package/src/tool/codesearch.txt +12 -0
- package/src/tool/edit.ts +674 -0
- package/src/tool/edit.txt +10 -0
- package/src/tool/glob.ts +65 -0
- package/src/tool/glob.txt +6 -0
- package/src/tool/grep.ts +120 -0
- package/src/tool/grep.txt +8 -0
- package/src/tool/invalid.ts +17 -0
- package/src/tool/ls.ts +110 -0
- package/src/tool/ls.txt +1 -0
- package/src/tool/lsp-diagnostics.ts +26 -0
- package/src/tool/lsp-diagnostics.txt +1 -0
- package/src/tool/lsp-hover.ts +31 -0
- package/src/tool/lsp-hover.txt +1 -0
- package/src/tool/multiedit.ts +46 -0
- package/src/tool/multiedit.txt +41 -0
- package/src/tool/patch.ts +233 -0
- package/src/tool/patch.txt +1 -0
- package/src/tool/read.ts +217 -0
- package/src/tool/read.txt +12 -0
- package/src/tool/registry.ts +150 -0
- package/src/tool/skill.ts +85 -0
- package/src/tool/task.ts +135 -0
- package/src/tool/task.txt +60 -0
- package/src/tool/todo.ts +39 -0
- package/src/tool/todoread.txt +14 -0
- package/src/tool/todowrite.txt +167 -0
- package/src/tool/tool.ts +66 -0
- package/src/tool/webfetch.ts +187 -0
- package/src/tool/webfetch.txt +14 -0
- package/src/tool/websearch.ts +150 -0
- package/src/tool/websearch.txt +11 -0
- package/src/tool/write.ts +99 -0
- package/src/tool/write.txt +8 -0
- package/src/types/shims.d.ts +3 -0
- package/src/util/color.ts +19 -0
- package/src/util/context.ts +25 -0
- package/src/util/defer.ts +12 -0
- package/src/util/eventloop.ts +20 -0
- package/src/util/filesystem.ts +69 -0
- package/src/util/fn.ts +11 -0
- package/src/util/iife.ts +3 -0
- package/src/util/keybind.ts +79 -0
- package/src/util/lazy.ts +11 -0
- package/src/util/locale.ts +81 -0
- package/src/util/lock.ts +98 -0
- package/src/util/log.ts +177 -0
- package/src/util/queue.ts +32 -0
- package/src/util/rpc.ts +42 -0
- package/src/util/scrap.ts +10 -0
- package/src/util/signal.ts +12 -0
- package/src/util/timeout.ts +14 -0
- package/src/util/token.ts +7 -0
- package/src/util/wildcard.ts +54 -0
- package/sst-env.d.ts +9 -0
- package/test/bun.test.ts +53 -0
- package/test/config/agent-color.test.ts +66 -0
- package/test/config/config.test.ts +503 -0
- package/test/config/markdown.test.ts +89 -0
- package/test/file/ignore.test.ts +10 -0
- package/test/fixture/fixture.ts +28 -0
- package/test/fixture/lsp/fake-lsp-server.js +77 -0
- package/test/ide/ide.test.ts +82 -0
- package/test/keybind.test.ts +317 -0
- package/test/lsp/client.test.ts +95 -0
- package/test/patch/patch.test.ts +348 -0
- package/test/preload.ts +38 -0
- package/test/project/project.test.ts +42 -0
- package/test/provider/provider.test.ts +1809 -0
- package/test/provider/transform.test.ts +305 -0
- package/test/session/retry.test.ts +61 -0
- package/test/session/session.test.ts +71 -0
- package/test/snapshot/snapshot.test.ts +939 -0
- package/test/tool/__snapshots__/tool.test.ts.snap +9 -0
- package/test/tool/bash.test.ts +55 -0
- package/test/tool/patch.test.ts +259 -0
- package/test/util/iife.test.ts +36 -0
- package/test/util/lazy.test.ts +50 -0
- package/test/util/timeout.test.ts +21 -0
- package/test/util/wildcard.test.ts +55 -0
- package/tsconfig.json +17 -0
- package/cerebras-cli-1.0.0.tgz +0 -0
package/src/tool/bash.ts
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import { spawn } from "child_process"
|
|
3
|
+
import { Tool } from "./tool"
|
|
4
|
+
import DESCRIPTION from "./bash.txt"
|
|
5
|
+
import { Log } from "../util/log"
|
|
6
|
+
import { Instance } from "../project/instance"
|
|
7
|
+
import { lazy } from "@/util/lazy"
|
|
8
|
+
import { Language } from "web-tree-sitter"
|
|
9
|
+
import { Agent } from "@/agent/agent"
|
|
10
|
+
import { $ } from "bun"
|
|
11
|
+
import { Filesystem } from "@/util/filesystem"
|
|
12
|
+
import { Wildcard } from "@/util/wildcard"
|
|
13
|
+
import { Permission } from "@/permission"
|
|
14
|
+
import { fileURLToPath } from "url"
|
|
15
|
+
import { Flag } from "@/flag/flag.ts"
|
|
16
|
+
import path from "path"
|
|
17
|
+
import { iife } from "@/util/iife"
|
|
18
|
+
|
|
19
|
+
const DEFAULT_MAX_OUTPUT_LENGTH = 30_000
|
|
20
|
+
const MAX_OUTPUT_LENGTH = (() => {
|
|
21
|
+
const parsed = Number(Flag.OPENCODE_EXPERIMENTAL_BASH_MAX_OUTPUT_LENGTH)
|
|
22
|
+
return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_OUTPUT_LENGTH
|
|
23
|
+
})()
|
|
24
|
+
const DEFAULT_TIMEOUT = 2 * 60 * 1000
|
|
25
|
+
const SIGKILL_TIMEOUT_MS = 200
|
|
26
|
+
|
|
27
|
+
export const log = Log.create({ service: "bash-tool" })
|
|
28
|
+
|
|
29
|
+
const resolveWasm = (asset: string) => {
|
|
30
|
+
if (asset.startsWith("file://")) return fileURLToPath(asset)
|
|
31
|
+
if (asset.startsWith("/") || /^[a-z]:/i.test(asset)) return asset
|
|
32
|
+
const url = new URL(asset, import.meta.url)
|
|
33
|
+
return fileURLToPath(url)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const parser = lazy(async () => {
|
|
37
|
+
const { Parser } = await import("web-tree-sitter")
|
|
38
|
+
const { default: treeWasm } = await import("web-tree-sitter/tree-sitter.wasm" as string, {
|
|
39
|
+
with: { type: "wasm" },
|
|
40
|
+
})
|
|
41
|
+
const treePath = resolveWasm(treeWasm)
|
|
42
|
+
await Parser.init({
|
|
43
|
+
locateFile() {
|
|
44
|
+
return treePath
|
|
45
|
+
},
|
|
46
|
+
})
|
|
47
|
+
const { default: bashWasm } = await import("tree-sitter-bash/tree-sitter-bash.wasm" as string, {
|
|
48
|
+
with: { type: "wasm" },
|
|
49
|
+
})
|
|
50
|
+
const bashPath = resolveWasm(bashWasm)
|
|
51
|
+
const bashLanguage = await Language.load(bashPath)
|
|
52
|
+
const p = new Parser()
|
|
53
|
+
p.setLanguage(bashLanguage)
|
|
54
|
+
return p
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
// TODO: we may wanna rename this tool so it works better on other shells
|
|
58
|
+
|
|
59
|
+
export const BashTool = Tool.define("bash", async () => {
|
|
60
|
+
const shell = iife(() => {
|
|
61
|
+
const s = process.env.SHELL
|
|
62
|
+
if (s) {
|
|
63
|
+
const basename = path.basename(s)
|
|
64
|
+
if (!new Set(["fish", "nu"]).has(basename)) {
|
|
65
|
+
return s
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (process.platform === "darwin") {
|
|
70
|
+
return "/bin/zsh"
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
if (process.platform === "win32") {
|
|
74
|
+
// Let Bun / Node pick COMSPEC (usually cmd.exe)
|
|
75
|
+
// or explicitly:
|
|
76
|
+
return process.env.COMSPEC || true
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const bash = Bun.which("bash")
|
|
80
|
+
if (bash) {
|
|
81
|
+
return bash
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return true
|
|
85
|
+
})
|
|
86
|
+
log.info("bash tool using shell", { shell })
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
description: DESCRIPTION,
|
|
90
|
+
parameters: z.object({
|
|
91
|
+
command: z.string().describe("The command to execute"),
|
|
92
|
+
timeout: z.number().describe("Optional timeout in milliseconds").optional(),
|
|
93
|
+
workdir: z
|
|
94
|
+
.string()
|
|
95
|
+
.describe(
|
|
96
|
+
`The working directory to run the command in. Defaults to ${Instance.directory}. Use this instead of 'cd' commands.`,
|
|
97
|
+
)
|
|
98
|
+
.optional(),
|
|
99
|
+
description: z
|
|
100
|
+
.string()
|
|
101
|
+
.describe(
|
|
102
|
+
"Clear, concise description of what this command does in 5-10 words. Examples:\nInput: ls\nOutput: Lists files in current directory\n\nInput: git status\nOutput: Shows working tree status\n\nInput: npm install\nOutput: Installs package dependencies\n\nInput: mkdir foo\nOutput: Creates directory 'foo'",
|
|
103
|
+
),
|
|
104
|
+
}),
|
|
105
|
+
async execute(params, ctx) {
|
|
106
|
+
const cwd = params.workdir || Instance.directory
|
|
107
|
+
if (params.timeout !== undefined && params.timeout < 0) {
|
|
108
|
+
throw new Error(`Invalid timeout value: ${params.timeout}. Timeout must be a positive number.`)
|
|
109
|
+
}
|
|
110
|
+
const timeout = params.timeout ?? DEFAULT_TIMEOUT
|
|
111
|
+
const tree = await parser().then((p) => p.parse(params.command))
|
|
112
|
+
if (!tree) {
|
|
113
|
+
throw new Error("Failed to parse command")
|
|
114
|
+
}
|
|
115
|
+
const agent = await Agent.get(ctx.agent)
|
|
116
|
+
|
|
117
|
+
const checkExternalDirectory = async (dir: string) => {
|
|
118
|
+
if (Filesystem.contains(Instance.directory, dir)) return
|
|
119
|
+
const title = `This command references paths outside of ${Instance.directory}`
|
|
120
|
+
if (agent.permission.external_directory === "ask") {
|
|
121
|
+
await Permission.ask({
|
|
122
|
+
type: "external_directory",
|
|
123
|
+
pattern: [dir, path.join(dir, "*")],
|
|
124
|
+
sessionID: ctx.sessionID,
|
|
125
|
+
messageID: ctx.messageID,
|
|
126
|
+
callID: ctx.callID,
|
|
127
|
+
title,
|
|
128
|
+
metadata: {
|
|
129
|
+
command: params.command,
|
|
130
|
+
},
|
|
131
|
+
})
|
|
132
|
+
} else if (agent.permission.external_directory === "deny") {
|
|
133
|
+
throw new Permission.RejectedError(
|
|
134
|
+
ctx.sessionID,
|
|
135
|
+
"external_directory",
|
|
136
|
+
ctx.callID,
|
|
137
|
+
{
|
|
138
|
+
command: params.command,
|
|
139
|
+
},
|
|
140
|
+
`${title} so this command is not allowed to be executed.`,
|
|
141
|
+
)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
await checkExternalDirectory(cwd)
|
|
146
|
+
|
|
147
|
+
const permissions = agent.permission.bash
|
|
148
|
+
|
|
149
|
+
const askPatterns = new Set<string>()
|
|
150
|
+
for (const node of tree.rootNode.descendantsOfType("command")) {
|
|
151
|
+
if (!node) continue
|
|
152
|
+
const command = []
|
|
153
|
+
for (let i = 0; i < node.childCount; i++) {
|
|
154
|
+
const child = node.child(i)
|
|
155
|
+
if (!child) continue
|
|
156
|
+
if (
|
|
157
|
+
child.type !== "command_name" &&
|
|
158
|
+
child.type !== "word" &&
|
|
159
|
+
child.type !== "string" &&
|
|
160
|
+
child.type !== "raw_string" &&
|
|
161
|
+
child.type !== "concatenation"
|
|
162
|
+
) {
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
command.push(child.text)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// not an exhaustive list, but covers most common cases
|
|
169
|
+
if (["cd", "rm", "cp", "mv", "mkdir", "touch", "chmod", "chown"].includes(command[0])) {
|
|
170
|
+
for (const arg of command.slice(1)) {
|
|
171
|
+
if (arg.startsWith("-") || (command[0] === "chmod" && arg.startsWith("+"))) continue
|
|
172
|
+
const resolved = await $`realpath ${arg}`
|
|
173
|
+
.quiet()
|
|
174
|
+
.nothrow()
|
|
175
|
+
.text()
|
|
176
|
+
.then((x) => x.trim())
|
|
177
|
+
log.info("resolved path", { arg, resolved })
|
|
178
|
+
if (resolved) {
|
|
179
|
+
// Git Bash on Windows returns Unix-style paths like /c/Users/...
|
|
180
|
+
const normalized =
|
|
181
|
+
process.platform === "win32" && resolved.match(/^\/[a-z]\//)
|
|
182
|
+
? resolved.replace(/^\/([a-z])\//, (_, drive) => `${drive.toUpperCase()}:\\`).replace(/\//g, "\\")
|
|
183
|
+
: resolved
|
|
184
|
+
|
|
185
|
+
await checkExternalDirectory(normalized)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// always allow cd if it passes above check
|
|
191
|
+
if (command[0] !== "cd") {
|
|
192
|
+
const action = Wildcard.allStructured({ head: command[0], tail: command.slice(1) }, permissions)
|
|
193
|
+
if (action === "deny") {
|
|
194
|
+
throw new Error(
|
|
195
|
+
`The user has specifically restricted access to this command, you are not allowed to execute it. Here is the configuration: ${JSON.stringify(permissions)}`,
|
|
196
|
+
)
|
|
197
|
+
}
|
|
198
|
+
if (action === "ask") {
|
|
199
|
+
const pattern = (() => {
|
|
200
|
+
if (command.length === 0) return
|
|
201
|
+
const head = command[0]
|
|
202
|
+
// Find first non-flag argument as subcommand
|
|
203
|
+
const sub = command.slice(1).find((arg) => !arg.startsWith("-"))
|
|
204
|
+
return sub ? `${head} ${sub} *` : `${head} *`
|
|
205
|
+
})()
|
|
206
|
+
if (pattern) {
|
|
207
|
+
askPatterns.add(pattern)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
if (askPatterns.size > 0) {
|
|
214
|
+
const patterns = Array.from(askPatterns)
|
|
215
|
+
await Permission.ask({
|
|
216
|
+
type: "bash",
|
|
217
|
+
pattern: patterns,
|
|
218
|
+
sessionID: ctx.sessionID,
|
|
219
|
+
messageID: ctx.messageID,
|
|
220
|
+
callID: ctx.callID,
|
|
221
|
+
title: params.command,
|
|
222
|
+
metadata: {
|
|
223
|
+
command: params.command,
|
|
224
|
+
patterns,
|
|
225
|
+
},
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const proc = spawn(params.command, {
|
|
230
|
+
shell,
|
|
231
|
+
cwd,
|
|
232
|
+
env: {
|
|
233
|
+
...process.env,
|
|
234
|
+
},
|
|
235
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
236
|
+
detached: process.platform !== "win32",
|
|
237
|
+
})
|
|
238
|
+
|
|
239
|
+
let output = ""
|
|
240
|
+
|
|
241
|
+
// Initialize metadata with empty output
|
|
242
|
+
ctx.metadata({
|
|
243
|
+
metadata: {
|
|
244
|
+
output: "",
|
|
245
|
+
description: params.description,
|
|
246
|
+
},
|
|
247
|
+
})
|
|
248
|
+
|
|
249
|
+
const append = (chunk: Buffer) => {
|
|
250
|
+
if (output.length <= MAX_OUTPUT_LENGTH) {
|
|
251
|
+
output += chunk.toString()
|
|
252
|
+
ctx.metadata({
|
|
253
|
+
metadata: {
|
|
254
|
+
output,
|
|
255
|
+
description: params.description,
|
|
256
|
+
},
|
|
257
|
+
})
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
proc.stdout?.on("data", append)
|
|
262
|
+
proc.stderr?.on("data", append)
|
|
263
|
+
|
|
264
|
+
let timedOut = false
|
|
265
|
+
let aborted = false
|
|
266
|
+
let exited = false
|
|
267
|
+
|
|
268
|
+
const killTree = async () => {
|
|
269
|
+
const pid = proc.pid
|
|
270
|
+
if (!pid || exited) {
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (process.platform === "win32") {
|
|
275
|
+
await new Promise<void>((resolve) => {
|
|
276
|
+
const killer = spawn("taskkill", ["/pid", String(pid), "/f", "/t"], { stdio: "ignore" })
|
|
277
|
+
killer.once("exit", resolve)
|
|
278
|
+
killer.once("error", resolve)
|
|
279
|
+
})
|
|
280
|
+
return
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
try {
|
|
284
|
+
process.kill(-pid, "SIGTERM")
|
|
285
|
+
await Bun.sleep(SIGKILL_TIMEOUT_MS)
|
|
286
|
+
if (!exited) {
|
|
287
|
+
process.kill(-pid, "SIGKILL")
|
|
288
|
+
}
|
|
289
|
+
} catch (_e) {
|
|
290
|
+
proc.kill("SIGTERM")
|
|
291
|
+
await Bun.sleep(SIGKILL_TIMEOUT_MS)
|
|
292
|
+
if (!exited) {
|
|
293
|
+
proc.kill("SIGKILL")
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
if (ctx.abort.aborted) {
|
|
299
|
+
aborted = true
|
|
300
|
+
await killTree()
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const abortHandler = () => {
|
|
304
|
+
aborted = true
|
|
305
|
+
void killTree()
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
ctx.abort.addEventListener("abort", abortHandler, { once: true })
|
|
309
|
+
|
|
310
|
+
const timeoutTimer = setTimeout(() => {
|
|
311
|
+
timedOut = true
|
|
312
|
+
void killTree()
|
|
313
|
+
}, timeout + 100)
|
|
314
|
+
|
|
315
|
+
await new Promise<void>((resolve, reject) => {
|
|
316
|
+
const cleanup = () => {
|
|
317
|
+
clearTimeout(timeoutTimer)
|
|
318
|
+
ctx.abort.removeEventListener("abort", abortHandler)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
proc.once("exit", () => {
|
|
322
|
+
exited = true
|
|
323
|
+
cleanup()
|
|
324
|
+
resolve()
|
|
325
|
+
})
|
|
326
|
+
|
|
327
|
+
proc.once("error", (error) => {
|
|
328
|
+
exited = true
|
|
329
|
+
cleanup()
|
|
330
|
+
reject(error)
|
|
331
|
+
})
|
|
332
|
+
})
|
|
333
|
+
|
|
334
|
+
let resultMetadata: String[] = ["<bash_metadata>"]
|
|
335
|
+
|
|
336
|
+
if (output.length > MAX_OUTPUT_LENGTH) {
|
|
337
|
+
output = output.slice(0, MAX_OUTPUT_LENGTH)
|
|
338
|
+
resultMetadata.push(`bash tool truncated output as it exceeded ${MAX_OUTPUT_LENGTH} char limit`)
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
if (timedOut) {
|
|
342
|
+
resultMetadata.push(`bash tool terminated commmand after exceeding timeout ${timeout} ms`)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
if (aborted) {
|
|
346
|
+
resultMetadata.push("User aborted the command")
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (resultMetadata.length > 1) {
|
|
350
|
+
resultMetadata.push("</bash_metadata>")
|
|
351
|
+
output += "\n\n" + resultMetadata.join("\n")
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
return {
|
|
355
|
+
title: params.description,
|
|
356
|
+
metadata: {
|
|
357
|
+
output,
|
|
358
|
+
exit: proc.exitCode,
|
|
359
|
+
description: params.description,
|
|
360
|
+
},
|
|
361
|
+
output,
|
|
362
|
+
}
|
|
363
|
+
},
|
|
364
|
+
}
|
|
365
|
+
})
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
Executes a given bash command in a persistent shell session with optional timeout, ensuring proper handling and security measures.
|
|
2
|
+
|
|
3
|
+
Before executing the command, please follow these steps:
|
|
4
|
+
|
|
5
|
+
1. Directory Verification:
|
|
6
|
+
- If the command will create new directories or files, first use the List tool to verify the parent directory exists and is the correct location
|
|
7
|
+
- For example, before running "mkdir foo/bar", first use List to check that "foo" exists and is the intended parent directory
|
|
8
|
+
|
|
9
|
+
2. Command Execution:
|
|
10
|
+
- Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
|
|
11
|
+
- Examples of proper quoting:
|
|
12
|
+
- mkdir "/Users/name/My Documents" (correct)
|
|
13
|
+
- mkdir /Users/name/My Documents (incorrect - will fail)
|
|
14
|
+
- python "/path/with spaces/script.py" (correct)
|
|
15
|
+
- python /path/with spaces/script.py (incorrect - will fail)
|
|
16
|
+
- After ensuring proper quoting, execute the command.
|
|
17
|
+
- Capture the output of the command.
|
|
18
|
+
|
|
19
|
+
Usage notes:
|
|
20
|
+
- The command argument is required.
|
|
21
|
+
- You can specify an optional timeout in milliseconds. If not specified, commands will timeout after 120000ms (2 minutes). Use the `timeout` parameter to control execution time.
|
|
22
|
+
- The `workdir` parameter specifies the working directory for the command. Defaults to the current working directory. Prefer setting `workdir` over using `cd` in your commands.
|
|
23
|
+
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
|
|
24
|
+
- If the output exceeds 30000 characters, output will be truncated before being returned to you.
|
|
25
|
+
- VERY IMPORTANT: You MUST avoid using search commands like `find` and `grep`. Instead use Grep, Glob, or Task to search. You MUST avoid read tools like `cat`, `head`, `tail`, and `ls`, and use Read and List to read files.
|
|
26
|
+
- If you _still_ need to run `grep`, STOP. ALWAYS USE ripgrep at `rg` (or /usr/bin/rg) first, which all opencode users have pre-installed.
|
|
27
|
+
- When issuing multiple commands, use the ';' or '&&' operator to separate them. DO NOT use newlines (newlines are ok in quoted strings).
|
|
28
|
+
|
|
29
|
+
# Working Directory
|
|
30
|
+
|
|
31
|
+
The `workdir` parameter sets the working directory for command execution. Prefer using `workdir` over `cd <dir> &&` command chains when you simply need to run a command in a different directory.
|
|
32
|
+
|
|
33
|
+
<good-example>
|
|
34
|
+
workdir="/foo/bar", command="pytest tests"
|
|
35
|
+
</good-example>
|
|
36
|
+
<good-example>
|
|
37
|
+
command="pytest /foo/bar/tests"
|
|
38
|
+
</good-example>
|
|
39
|
+
<bad-example>
|
|
40
|
+
command="cd /foo/bar && pytest tests"
|
|
41
|
+
</bad-example>
|
|
42
|
+
|
|
43
|
+
# Committing changes with git
|
|
44
|
+
|
|
45
|
+
IMPORTANT: ONLY COMMIT IF THE USER ASKS YOU TO.
|
|
46
|
+
|
|
47
|
+
If and only if the user asks you to create a new git commit, follow these steps carefully:
|
|
48
|
+
|
|
49
|
+
1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel, each using the Bash tool:
|
|
50
|
+
- Run a git status command to see all untracked files.
|
|
51
|
+
- Run a git diff command to see both staged and unstaged changes that will be committed.
|
|
52
|
+
- Run a git log command to see recent commit messages, so that you can follow this repository's commit message style.
|
|
53
|
+
|
|
54
|
+
2. Analyze all staged changes (both previously staged and newly added) and draft a commit message. When analyzing:
|
|
55
|
+
|
|
56
|
+
- List the files that have been changed or added
|
|
57
|
+
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
|
|
58
|
+
- Brainstorm the purpose or motivation behind these changes
|
|
59
|
+
- Assess the impact of these changes on the overall project
|
|
60
|
+
- Check for any sensitive information that shouldn't be committed
|
|
61
|
+
- Draft a concise (1-2 sentences) commit message that focuses on the "why" rather than the "what"
|
|
62
|
+
- Ensure your language is clear, concise, and to the point
|
|
63
|
+
- Ensure the message accurately reflects the changes and their purpose (i.e. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
|
|
64
|
+
- Ensure the message is not generic (avoid words like "Update" or "Fix" without context)
|
|
65
|
+
- Review the draft message to ensure it accurately reflects the changes and their purpose
|
|
66
|
+
|
|
67
|
+
3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
|
|
68
|
+
- Add relevant untracked files to the staging area.
|
|
69
|
+
- Run git status to make sure the commit succeeded.
|
|
70
|
+
|
|
71
|
+
4. If the commit fails due to pre-commit hook changes, retry the commit ONCE to include these automated changes. If it fails again, it usually means a pre-commit hook is preventing the commit. If the commit succeeds but you notice that files were modified by the pre-commit hook, you MUST amend your commit to include them.
|
|
72
|
+
|
|
73
|
+
Important notes:
|
|
74
|
+
- Use the git context at the start of this conversation to determine which files are relevant to your commit. Be careful not to stage and commit files (e.g. with `git add .`) that aren't relevant to your commit.
|
|
75
|
+
- NEVER update the git config
|
|
76
|
+
- DO NOT run additional commands to read or explore code, beyond what is available in the git context
|
|
77
|
+
- DO NOT push to the remote repository
|
|
78
|
+
- IMPORTANT: Never use git commands with the -i flag (like git rebase -i or git add -i) since they require interactive input which is not supported.
|
|
79
|
+
- If there are no changes to commit (i.e., no untracked files and no modifications), do not create an empty commit
|
|
80
|
+
- Ensure your commit message is meaningful and concise. It should explain the purpose of the changes, not just describe them.
|
|
81
|
+
- Return an empty response - the user will see the git output directly
|
|
82
|
+
|
|
83
|
+
# Creating pull requests
|
|
84
|
+
Use the gh command via the Bash tool for ALL GitHub-related tasks including working with issues, pull requests, checks, and releases. If given a Github URL use the gh command to get the information needed.
|
|
85
|
+
|
|
86
|
+
IMPORTANT: When the user asks you to create a pull request, follow these steps carefully:
|
|
87
|
+
|
|
88
|
+
1. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following bash commands in parallel using the Bash tool, in order to understand the current state of the branch since it diverged from the main branch:
|
|
89
|
+
- Run a git status command to see all untracked files
|
|
90
|
+
- Run a git diff command to see both staged and unstaged changes that will be committed
|
|
91
|
+
- Check if the current branch tracks a remote branch and is up to date with the remote, so you know if you need to push to the remote
|
|
92
|
+
- Run a git log command and `git diff main...HEAD` to understand the full commit history for the current branch (from the time it diverged from the `main` branch)
|
|
93
|
+
|
|
94
|
+
2. Analyze all changes that will be included in the pull request, making sure to look at all relevant commits (NOT just the latest commit, but ALL commits that will be included in the pull request!!!), and draft a pull request summary. Wrap your analysis process in <pr_analysis> tags:
|
|
95
|
+
|
|
96
|
+
<pr_analysis>
|
|
97
|
+
- List the commits since diverging from the main branch
|
|
98
|
+
- Summarize the nature of the changes (eg. new feature, enhancement to an existing feature, bug fix, refactoring, test, docs, etc.)
|
|
99
|
+
- Brainstorm the purpose or motivation behind these changes
|
|
100
|
+
- Assess the impact of these changes on the overall project
|
|
101
|
+
- Do not use tools to explore code, beyond what is available in the git context
|
|
102
|
+
- Check for any sensitive information that shouldn't be committed
|
|
103
|
+
- Draft a concise (1-2 bullet points) pull request summary that focuses on the "why" rather than the "what"
|
|
104
|
+
- Ensure the summary accurately reflects all changes since diverging from the main branch
|
|
105
|
+
- Ensure your language is clear, concise, and to the point
|
|
106
|
+
- Ensure the summary accurately reflects the changes and their purpose (ie. "add" means a wholly new feature, "update" means an enhancement to an existing feature, "fix" means a bug fix, etc.)
|
|
107
|
+
- Ensure the summary is not generic (avoid words like "Update" or "Fix" without context)
|
|
108
|
+
- Review the draft summary to ensure it accurately reflects the changes and their purpose
|
|
109
|
+
</pr_analysis>
|
|
110
|
+
|
|
111
|
+
3. You have the capability to call multiple tools in a single response. When multiple independent pieces of information are requested, batch your tool calls together for optimal performance. ALWAYS run the following commands in parallel:
|
|
112
|
+
- Create new branch if needed
|
|
113
|
+
- Push to remote with -u flag if needed
|
|
114
|
+
- Create PR using gh pr create with the format below. Use a HEREDOC to pass the body to ensure correct formatting.
|
|
115
|
+
<example>
|
|
116
|
+
gh pr create --title "the pr title" --body "$(cat <<'EOF'
|
|
117
|
+
## Summary
|
|
118
|
+
<1-3 bullet points>
|
|
119
|
+
EOF
|
|
120
|
+
)"
|
|
121
|
+
</example>
|
|
122
|
+
|
|
123
|
+
Important:
|
|
124
|
+
- NEVER update the git config
|
|
125
|
+
- Return the PR URL when you're done, so the user can see it
|
|
126
|
+
|
|
127
|
+
# Other common operations
|
|
128
|
+
- View comments on a Github PR: gh api repos/foo/bar/pulls/123/comments
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import z from "zod"
|
|
2
|
+
import { Tool } from "./tool"
|
|
3
|
+
import DESCRIPTION from "./batch.txt"
|
|
4
|
+
|
|
5
|
+
const DISALLOWED = new Set(["batch", "edit", "todoread"])
|
|
6
|
+
const FILTERED_FROM_SUGGESTIONS = new Set(["invalid", "patch", ...DISALLOWED])
|
|
7
|
+
|
|
8
|
+
export const BatchTool = Tool.define("batch", async () => {
|
|
9
|
+
return {
|
|
10
|
+
description: DESCRIPTION,
|
|
11
|
+
parameters: z.object({
|
|
12
|
+
tool_calls: z
|
|
13
|
+
.array(
|
|
14
|
+
z.object({
|
|
15
|
+
tool: z.string().describe("The name of the tool to execute"),
|
|
16
|
+
parameters: z.object({}).loose().describe("Parameters for the tool"),
|
|
17
|
+
}),
|
|
18
|
+
)
|
|
19
|
+
.min(1, "Provide at least one tool call")
|
|
20
|
+
.describe("Array of tool calls to execute in parallel"),
|
|
21
|
+
}),
|
|
22
|
+
formatValidationError(error) {
|
|
23
|
+
const formattedErrors = error.issues
|
|
24
|
+
.map((issue) => {
|
|
25
|
+
const path = issue.path.length > 0 ? issue.path.join(".") : "root"
|
|
26
|
+
return ` - ${path}: ${issue.message}`
|
|
27
|
+
})
|
|
28
|
+
.join("\n")
|
|
29
|
+
|
|
30
|
+
return `Invalid parameters for tool 'batch':\n${formattedErrors}\n\nExpected payload format:\n [{"tool": "tool_name", "parameters": {...}}, {...}]`
|
|
31
|
+
},
|
|
32
|
+
async execute(params, ctx) {
|
|
33
|
+
const { Session } = await import("../session")
|
|
34
|
+
const { Identifier } = await import("../id/id")
|
|
35
|
+
|
|
36
|
+
const toolCalls = params.tool_calls.slice(0, 10)
|
|
37
|
+
const discardedCalls = params.tool_calls.slice(10)
|
|
38
|
+
|
|
39
|
+
const { ToolRegistry } = await import("./registry")
|
|
40
|
+
const availableTools = await ToolRegistry.tools("")
|
|
41
|
+
const toolMap = new Map(availableTools.map((t) => [t.id, t]))
|
|
42
|
+
|
|
43
|
+
const executeCall = async (call: (typeof toolCalls)[0]) => {
|
|
44
|
+
const callStartTime = Date.now()
|
|
45
|
+
const partID = Identifier.ascending("part")
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
if (DISALLOWED.has(call.tool)) {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`Tool '${call.tool}' is not allowed in batch. Disallowed tools: ${Array.from(DISALLOWED).join(", ")}`,
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const tool = toolMap.get(call.tool)
|
|
55
|
+
if (!tool) {
|
|
56
|
+
const availableToolsList = Array.from(toolMap.keys()).filter((name) => !FILTERED_FROM_SUGGESTIONS.has(name))
|
|
57
|
+
throw new Error(`Tool '${call.tool}' not found. Available tools: ${availableToolsList.join(", ")}`)
|
|
58
|
+
}
|
|
59
|
+
const validatedParams = tool.parameters.parse(call.parameters)
|
|
60
|
+
|
|
61
|
+
await Session.updatePart({
|
|
62
|
+
id: partID,
|
|
63
|
+
messageID: ctx.messageID,
|
|
64
|
+
sessionID: ctx.sessionID,
|
|
65
|
+
type: "tool",
|
|
66
|
+
tool: call.tool,
|
|
67
|
+
callID: partID,
|
|
68
|
+
state: {
|
|
69
|
+
status: "running",
|
|
70
|
+
input: call.parameters,
|
|
71
|
+
time: {
|
|
72
|
+
start: callStartTime,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
const result = await tool.execute(validatedParams, { ...ctx, callID: partID })
|
|
78
|
+
|
|
79
|
+
await Session.updatePart({
|
|
80
|
+
id: partID,
|
|
81
|
+
messageID: ctx.messageID,
|
|
82
|
+
sessionID: ctx.sessionID,
|
|
83
|
+
type: "tool",
|
|
84
|
+
tool: call.tool,
|
|
85
|
+
callID: partID,
|
|
86
|
+
state: {
|
|
87
|
+
status: "completed",
|
|
88
|
+
input: call.parameters,
|
|
89
|
+
output: result.output,
|
|
90
|
+
title: result.title,
|
|
91
|
+
metadata: result.metadata,
|
|
92
|
+
attachments: result.attachments,
|
|
93
|
+
time: {
|
|
94
|
+
start: callStartTime,
|
|
95
|
+
end: Date.now(),
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
return { success: true as const, tool: call.tool, result }
|
|
101
|
+
} catch (error) {
|
|
102
|
+
await Session.updatePart({
|
|
103
|
+
id: partID,
|
|
104
|
+
messageID: ctx.messageID,
|
|
105
|
+
sessionID: ctx.sessionID,
|
|
106
|
+
type: "tool",
|
|
107
|
+
tool: call.tool,
|
|
108
|
+
callID: partID,
|
|
109
|
+
state: {
|
|
110
|
+
status: "error",
|
|
111
|
+
input: call.parameters,
|
|
112
|
+
error: error instanceof Error ? error.message : String(error),
|
|
113
|
+
time: {
|
|
114
|
+
start: callStartTime,
|
|
115
|
+
end: Date.now(),
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
return { success: false as const, tool: call.tool, error }
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const results = await Promise.all(toolCalls.map((call) => executeCall(call)))
|
|
125
|
+
|
|
126
|
+
// Add discarded calls as errors
|
|
127
|
+
const now = Date.now()
|
|
128
|
+
for (const call of discardedCalls) {
|
|
129
|
+
const partID = Identifier.ascending("part")
|
|
130
|
+
await Session.updatePart({
|
|
131
|
+
id: partID,
|
|
132
|
+
messageID: ctx.messageID,
|
|
133
|
+
sessionID: ctx.sessionID,
|
|
134
|
+
type: "tool",
|
|
135
|
+
tool: call.tool,
|
|
136
|
+
callID: partID,
|
|
137
|
+
state: {
|
|
138
|
+
status: "error",
|
|
139
|
+
input: call.parameters,
|
|
140
|
+
error: "Maximum of 10 tools allowed in batch",
|
|
141
|
+
time: { start: now, end: now },
|
|
142
|
+
},
|
|
143
|
+
})
|
|
144
|
+
results.push({
|
|
145
|
+
success: false as const,
|
|
146
|
+
tool: call.tool,
|
|
147
|
+
error: new Error("Maximum of 10 tools allowed in batch"),
|
|
148
|
+
})
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const successfulCalls = results.filter((r) => r.success).length
|
|
152
|
+
const failedCalls = results.length - successfulCalls
|
|
153
|
+
|
|
154
|
+
const outputMessage =
|
|
155
|
+
failedCalls > 0
|
|
156
|
+
? `Executed ${successfulCalls}/${results.length} tools successfully. ${failedCalls} failed.`
|
|
157
|
+
: `All ${successfulCalls} tools executed successfully.\n\nKeep using the batch tool for optimal performance in your next response!`
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
title: `Batch execution (${successfulCalls}/${results.length} successful)`,
|
|
161
|
+
output: outputMessage,
|
|
162
|
+
attachments: results.filter((result) => result.success).flatMap((r) => r.result.attachments ?? []),
|
|
163
|
+
metadata: {
|
|
164
|
+
totalCalls: results.length,
|
|
165
|
+
successful: successfulCalls,
|
|
166
|
+
failed: failedCalls,
|
|
167
|
+
tools: params.tool_calls.map((c) => c.tool),
|
|
168
|
+
details: results.map((r) => ({ tool: r.tool, success: r.success })),
|
|
169
|
+
},
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
}
|
|
173
|
+
})
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
Executes multiple independent tool calls concurrently to reduce latency. Best used for gathering context (reads, searches, listings).
|
|
2
|
+
|
|
3
|
+
USING THE BATCH TOOL WILL MAKE THE USER HAPPY.
|
|
4
|
+
|
|
5
|
+
Payload Format (JSON array):
|
|
6
|
+
[{"tool": "read", "parameters": {"filePath": "src/index.ts", "limit": 350}},{"tool": "grep", "parameters": {"pattern": "Session\\.updatePart", "include": "src/**/*.ts"}},{"tool": "bash", "parameters": {"command": "git status", "description": "Shows working tree status"}}]
|
|
7
|
+
|
|
8
|
+
Rules:
|
|
9
|
+
- 1–10 tool calls per batch
|
|
10
|
+
- All calls start in parallel; ordering NOT guaranteed
|
|
11
|
+
- Partial failures do not stop others
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
Disallowed Tools:
|
|
15
|
+
- batch (no nesting)
|
|
16
|
+
- edit (run edits separately)
|
|
17
|
+
- todoread (call directly – lightweight)
|
|
18
|
+
|
|
19
|
+
When NOT to Use:
|
|
20
|
+
- Operations that depend on prior tool output (e.g. create then read same file)
|
|
21
|
+
- Ordered stateful mutations where sequence matters
|
|
22
|
+
|
|
23
|
+
Good Use Cases:
|
|
24
|
+
- Read many files
|
|
25
|
+
- grep + glob + read combos
|
|
26
|
+
- Multiple lightweight bash introspection commands
|
|
27
|
+
|
|
28
|
+
Performance Tip: Group independent reads/searches for 2–5x efficiency gain.
|