rird 1.0.200
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 +18 -0
- package/README.md +15 -0
- package/bin/opencode +336 -0
- package/bin/pty-wrapper.js +285 -0
- package/bunfig.toml +4 -0
- package/facebook_ads_library.png +0 -0
- package/nul`nif +0 -0
- package/package.json +111 -0
- package/parsers-config.ts +239 -0
- package/rird-1.0.199.tgz +0 -0
- package/script/build-windows.ts +54 -0
- package/script/build.ts +167 -0
- package/script/postinstall.mjs +544 -0
- package/script/publish-registries.ts +187 -0
- package/script/publish.ts +72 -0
- package/script/schema.ts +47 -0
- package/src/acp/README.md +164 -0
- package/src/acp/agent.ts +1063 -0
- package/src/acp/session.ts +101 -0
- package/src/acp/types.ts +22 -0
- package/src/agent/agent.ts +367 -0
- package/src/agent/generate.txt +75 -0
- package/src/agent/prompt/compaction.txt +12 -0
- package/src/agent/prompt/explore.txt +18 -0
- package/src/agent/prompt/summary.txt +10 -0
- package/src/agent/prompt/title.txt +36 -0
- package/src/auth/index.ts +70 -0
- package/src/bun/index.ts +114 -0
- package/src/bus/bus-event.ts +43 -0
- package/src/bus/global.ts +10 -0
- package/src/bus/index.ts +105 -0
- package/src/cli/bootstrap.ts +17 -0
- package/src/cli/cmd/acp.ts +88 -0
- package/src/cli/cmd/agent.ts +256 -0
- package/src/cli/cmd/auth.ts +391 -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 +48 -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 +15 -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 +1400 -0
- package/src/cli/cmd/import.ts +98 -0
- package/src/cli/cmd/mcp.ts +654 -0
- package/src/cli/cmd/models.ts +77 -0
- package/src/cli/cmd/pr.ts +112 -0
- package/src/cli/cmd/run.ts +368 -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 +696 -0
- package/src/cli/cmd/tui/attach.ts +30 -0
- package/src/cli/cmd/tui/component/border.tsx +21 -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-mcp.tsx +86 -0
- package/src/cli/cmd/tui/component/dialog-model.tsx +245 -0
- package/src/cli/cmd/tui/component/dialog-provider.tsx +224 -0
- package/src/cli/cmd/tui/component/dialog-session-list.tsx +102 -0
- package/src/cli/cmd/tui/component/dialog-session-rename.tsx +31 -0
- package/src/cli/cmd/tui/component/dialog-stash.tsx +86 -0
- package/src/cli/cmd/tui/component/dialog-status.tsx +162 -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/did-you-know.tsx +85 -0
- package/src/cli/cmd/tui/component/logo.tsx +35 -0
- package/src/cli/cmd/tui/component/prompt/autocomplete.tsx +574 -0
- package/src/cli/cmd/tui/component/prompt/history.tsx +108 -0
- package/src/cli/cmd/tui/component/prompt/index.tsx +1090 -0
- package/src/cli/cmd/tui/component/prompt/stash.tsx +101 -0
- package/src/cli/cmd/tui/component/tips.ts +27 -0
- package/src/cli/cmd/tui/component/todo-item.tsx +32 -0
- package/src/cli/cmd/tui/context/args.tsx +14 -0
- package/src/cli/cmd/tui/context/directory.ts +13 -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 +101 -0
- package/src/cli/cmd/tui/context/kv.tsx +49 -0
- package/src/cli/cmd/tui/context/local.tsx +354 -0
- package/src/cli/cmd/tui/context/prompt.tsx +18 -0
- package/src/cli/cmd/tui/context/route.tsx +46 -0
- package/src/cli/cmd/tui/context/sdk.tsx +74 -0
- package/src/cli/cmd/tui/context/sync.tsx +372 -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-frappe.json +233 -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/cursor.json +249 -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/lucent-orng.json +227 -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/rird.json +245 -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 +1109 -0
- package/src/cli/cmd/tui/event.ts +40 -0
- package/src/cli/cmd/tui/routes/home.tsx +138 -0
- package/src/cli/cmd/tui/routes/session/dialog-fork-from-timeline.tsx +64 -0
- package/src/cli/cmd/tui/routes/session/dialog-message.tsx +109 -0
- package/src/cli/cmd/tui/routes/session/dialog-subagent.tsx +26 -0
- package/src/cli/cmd/tui/routes/session/dialog-timeline.tsx +47 -0
- package/src/cli/cmd/tui/routes/session/footer.tsx +88 -0
- package/src/cli/cmd/tui/routes/session/header.tsx +125 -0
- package/src/cli/cmd/tui/routes/session/index.tsx +1864 -0
- package/src/cli/cmd/tui/routes/session/sidebar.tsx +318 -0
- package/src/cli/cmd/tui/spawn.ts +60 -0
- package/src/cli/cmd/tui/thread.ts +142 -0
- package/src/cli/cmd/tui/ui/dialog-alert.tsx +57 -0
- package/src/cli/cmd/tui/ui/dialog-confirm.tsx +83 -0
- package/src/cli/cmd/tui/ui/dialog-help.tsx +38 -0
- package/src/cli/cmd/tui/ui/dialog-prompt.tsx +77 -0
- package/src/cli/cmd/tui/ui/dialog-select.tsx +332 -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 +100 -0
- package/src/cli/cmd/web.ts +84 -0
- package/src/cli/error.ts +56 -0
- package/src/cli/ui.ts +84 -0
- package/src/cli/upgrade.ts +25 -0
- package/src/command/index.ts +80 -0
- package/src/command/template/initialize.txt +10 -0
- package/src/command/template/review.txt +97 -0
- package/src/config/config.ts +995 -0
- package/src/config/markdown.ts +41 -0
- package/src/env/index.ts +26 -0
- package/src/file/ignore.ts +83 -0
- package/src/file/index.ts +328 -0
- package/src/file/ripgrep.ts +393 -0
- package/src/file/time.ts +64 -0
- package/src/file/watcher.ts +103 -0
- package/src/flag/flag.ts +46 -0
- package/src/format/formatter.ts +315 -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 +76 -0
- package/src/index.ts +240 -0
- package/src/installation/index.ts +239 -0
- package/src/lsp/client.ts +229 -0
- package/src/lsp/index.ts +485 -0
- package/src/lsp/language.ts +116 -0
- package/src/lsp/server.ts +1895 -0
- package/src/mcp/auth.ts +135 -0
- package/src/mcp/index.ts +690 -0
- package/src/mcp/oauth-callback.ts +200 -0
- package/src/mcp/oauth-provider.ts +154 -0
- package/src/patch/index.ts +622 -0
- package/src/permission/index.ts +199 -0
- package/src/plugin/index.ts +91 -0
- package/src/project/bootstrap.ts +31 -0
- package/src/project/instance.ts +78 -0
- package/src/project/project.ts +221 -0
- package/src/project/state.ts +65 -0
- package/src/project/vcs.ts +76 -0
- package/src/provider/auth.ts +143 -0
- package/src/provider/models-macro.ts +11 -0
- package/src/provider/models.ts +106 -0
- package/src/provider/provider.ts +1071 -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 +22 -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 +455 -0
- package/src/pty/index.ts +231 -0
- package/src/security/guardrails.test.ts +341 -0
- package/src/security/guardrails.ts +558 -0
- package/src/security/index.ts +19 -0
- package/src/server/error.ts +36 -0
- package/src/server/project.ts +79 -0
- package/src/server/server.ts +2642 -0
- package/src/server/tui.ts +71 -0
- package/src/session/compaction.ts +223 -0
- package/src/session/index.ts +461 -0
- package/src/session/llm.ts +201 -0
- package/src/session/message-v2.ts +690 -0
- package/src/session/message.ts +189 -0
- package/src/session/processor.ts +409 -0
- package/src/session/prompt/act-switch.txt +5 -0
- package/src/session/prompt/anthropic-20250930.txt +166 -0
- package/src/session/prompt/anthropic.txt +85 -0
- package/src/session/prompt/anthropic_spoof.txt +1 -0
- package/src/session/prompt/beast.txt +103 -0
- package/src/session/prompt/codex.txt +304 -0
- package/src/session/prompt/copilot-gpt-5.txt +138 -0
- package/src/session/prompt/gemini.txt +85 -0
- package/src/session/prompt/max-steps.txt +16 -0
- package/src/session/prompt/plan-reminder-anthropic.txt +35 -0
- package/src/session/prompt/plan.txt +24 -0
- package/src/session/prompt/polaris.txt +84 -0
- package/src/session/prompt/qwen.txt +106 -0
- package/src/session/prompt.ts +1509 -0
- package/src/session/retry.ts +86 -0
- package/src/session/revert.ts +108 -0
- package/src/session/sensitive-filter.test.ts +327 -0
- package/src/session/sensitive-filter.ts +466 -0
- package/src/session/status.ts +76 -0
- package/src/session/summary.ts +194 -0
- package/src/session/system.ts +120 -0
- package/src/session/todo.ts +37 -0
- package/src/share/share-next.ts +194 -0
- package/src/share/share.ts +87 -0
- package/src/shell/shell.ts +67 -0
- package/src/skill/index.ts +1 -0
- package/src/skill/skill.ts +83 -0
- package/src/snapshot/index.ts +197 -0
- package/src/storage/storage.ts +226 -0
- package/src/tests/agent.test.ts +308 -0
- package/src/tests/build-guards.test.ts +267 -0
- package/src/tests/config.test.ts +664 -0
- package/src/tests/tool-registry.test.ts +589 -0
- package/src/tool/bash.ts +317 -0
- package/src/tool/bash.txt +158 -0
- package/src/tool/batch.ts +175 -0
- package/src/tool/batch.txt +24 -0
- package/src/tool/codesearch.ts +168 -0
- package/src/tool/codesearch.txt +12 -0
- package/src/tool/edit.ts +675 -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 +121 -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/lsp.ts +87 -0
- package/src/tool/lsp.txt +19 -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 +219 -0
- package/src/tool/read.txt +12 -0
- package/src/tool/registry.ts +162 -0
- package/src/tool/skill.ts +100 -0
- package/src/tool/task.ts +136 -0
- package/src/tool/task.txt +51 -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 +71 -0
- package/src/tool/webfetch.ts +198 -0
- package/src/tool/webfetch.txt +13 -0
- package/src/tool/websearch.ts +180 -0
- package/src/tool/websearch.txt +11 -0
- package/src/tool/write.ts +110 -0
- package/src/tool/write.txt +8 -0
- package/src/util/archive.ts +16 -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 +83 -0
- package/src/util/fn.ts +11 -0
- package/src/util/iife.ts +3 -0
- package/src/util/keybind.ts +102 -0
- package/src/util/lazy.ts +11 -0
- package/src/util/license.ts +325 -0
- package/src/util/locale.ts +81 -0
- package/src/util/lock.ts +98 -0
- package/src/util/log.ts +180 -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/agent/agent.test.ts +146 -0
- package/test/bun.test.ts +53 -0
- package/test/cli/github-remote.test.ts +80 -0
- package/test/config/agent-color.test.ts +66 -0
- package/test/config/config.test.ts +535 -0
- package/test/config/markdown.test.ts +89 -0
- package/test/file/ignore.test.ts +10 -0
- package/test/fixture/fixture.ts +36 -0
- package/test/fixture/lsp/fake-lsp-server.js +77 -0
- package/test/ide/ide.test.ts +82 -0
- package/test/keybind.test.ts +421 -0
- package/test/lsp/client.test.ts +95 -0
- package/test/mcp/headers.test.ts +153 -0
- package/test/patch/patch.test.ts +348 -0
- package/test/preload.ts +57 -0
- package/test/project/project.test.ts +72 -0
- package/test/provider/provider.test.ts +1809 -0
- package/test/provider/transform.test.ts +411 -0
- package/test/session/retry.test.ts +111 -0
- package/test/session/session.test.ts +71 -0
- package/test/skill/skill.test.ts +131 -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 +434 -0
- package/test/tool/grep.test.ts +108 -0
- package/test/tool/patch.test.ts +259 -0
- package/test/tool/read.test.ts +42 -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 +16 -0
|
@@ -0,0 +1,1509 @@
|
|
|
1
|
+
import path from "path"
|
|
2
|
+
import os from "os"
|
|
3
|
+
import fs from "fs/promises"
|
|
4
|
+
import z from "zod"
|
|
5
|
+
import { Identifier } from "../id/id"
|
|
6
|
+
import { MessageV2 } from "./message-v2"
|
|
7
|
+
import { Log } from "../util/log"
|
|
8
|
+
import { SessionRevert } from "./revert"
|
|
9
|
+
import { Session } from "."
|
|
10
|
+
import { Agent } from "../agent/agent"
|
|
11
|
+
import { Provider } from "../provider/provider"
|
|
12
|
+
import { type Tool as AITool, tool, jsonSchema } from "ai"
|
|
13
|
+
import { SessionCompaction } from "./compaction"
|
|
14
|
+
import { Instance } from "../project/instance"
|
|
15
|
+
import { Bus } from "../bus"
|
|
16
|
+
import { ProviderTransform } from "../provider/transform"
|
|
17
|
+
import { SystemPrompt } from "./system"
|
|
18
|
+
import { Plugin } from "../plugin"
|
|
19
|
+
import PROMPT_PLAN from "../session/prompt/plan.txt"
|
|
20
|
+
import ACT_SWITCH from "../session/prompt/act-switch.txt"
|
|
21
|
+
import MAX_STEPS from "../session/prompt/max-steps.txt"
|
|
22
|
+
import { defer } from "../util/defer"
|
|
23
|
+
import { clone, mergeDeep, pipe } from "remeda"
|
|
24
|
+
import { ToolRegistry } from "../tool/registry"
|
|
25
|
+
import { Wildcard } from "../util/wildcard"
|
|
26
|
+
import { MCP } from "../mcp"
|
|
27
|
+
import { LSP } from "../lsp"
|
|
28
|
+
import { ReadTool } from "../tool/read"
|
|
29
|
+
import { ListTool } from "../tool/ls"
|
|
30
|
+
import { FileTime } from "../file/time"
|
|
31
|
+
import { Flag } from "../flag/flag"
|
|
32
|
+
import { ulid } from "ulid"
|
|
33
|
+
import { spawn } from "child_process"
|
|
34
|
+
import { Command } from "../command"
|
|
35
|
+
import { $, fileURLToPath } from "bun"
|
|
36
|
+
import { ConfigMarkdown } from "../config/markdown"
|
|
37
|
+
import { SessionSummary } from "./summary"
|
|
38
|
+
import { NamedError } from "@opencode-ai/util/error"
|
|
39
|
+
import { fn } from "@/util/fn"
|
|
40
|
+
import { SessionProcessor } from "./processor"
|
|
41
|
+
import { TaskTool } from "@/tool/task"
|
|
42
|
+
import { SessionStatus } from "./status"
|
|
43
|
+
import { LLM } from "./llm"
|
|
44
|
+
import { iife } from "@/util/iife"
|
|
45
|
+
import { Shell } from "@/shell/shell"
|
|
46
|
+
import { SensitiveFilter } from "./sensitive-filter"
|
|
47
|
+
|
|
48
|
+
// @ts-ignore
|
|
49
|
+
globalThis.AI_SDK_LOG_WARNINGS = false
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Recursively restore sensitive data placeholders in tool arguments.
|
|
53
|
+
* This allows the LLM to plan using placeholders while actual execution
|
|
54
|
+
* uses the real values - keeping sensitive data local and never sent to API.
|
|
55
|
+
*/
|
|
56
|
+
function restoreSensitiveInArgs(args: unknown, sessionID: string): unknown {
|
|
57
|
+
if (typeof args === "string") {
|
|
58
|
+
return SensitiveFilter.restore(args, sessionID)
|
|
59
|
+
}
|
|
60
|
+
if (Array.isArray(args)) {
|
|
61
|
+
return args.map((item) => restoreSensitiveInArgs(item, sessionID))
|
|
62
|
+
}
|
|
63
|
+
if (args !== null && typeof args === "object") {
|
|
64
|
+
const restored: Record<string, unknown> = {}
|
|
65
|
+
for (const [key, value] of Object.entries(args)) {
|
|
66
|
+
restored[key] = restoreSensitiveInArgs(value, sessionID)
|
|
67
|
+
}
|
|
68
|
+
return restored
|
|
69
|
+
}
|
|
70
|
+
return args
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export namespace SessionPrompt {
|
|
74
|
+
const log = Log.create({ service: "session.prompt" })
|
|
75
|
+
export const OUTPUT_TOKEN_MAX = Flag.RIRD_EXPERIMENTAL_OUTPUT_TOKEN_MAX || 32_000
|
|
76
|
+
|
|
77
|
+
const state = Instance.state(
|
|
78
|
+
() => {
|
|
79
|
+
const data: Record<
|
|
80
|
+
string,
|
|
81
|
+
{
|
|
82
|
+
abort: AbortController
|
|
83
|
+
callbacks: {
|
|
84
|
+
resolve(input: MessageV2.WithParts): void
|
|
85
|
+
reject(): void
|
|
86
|
+
}[]
|
|
87
|
+
}
|
|
88
|
+
> = {}
|
|
89
|
+
return data
|
|
90
|
+
},
|
|
91
|
+
async (current) => {
|
|
92
|
+
for (const item of Object.values(current)) {
|
|
93
|
+
item.abort.abort()
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
export function assertNotBusy(sessionID: string) {
|
|
99
|
+
const match = state()[sessionID]
|
|
100
|
+
if (match) throw new Session.BusyError(sessionID)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export const PromptInput = z.object({
|
|
104
|
+
sessionID: Identifier.schema("session"),
|
|
105
|
+
messageID: Identifier.schema("message").optional(),
|
|
106
|
+
model: z
|
|
107
|
+
.object({
|
|
108
|
+
providerID: z.string(),
|
|
109
|
+
modelID: z.string(),
|
|
110
|
+
})
|
|
111
|
+
.optional(),
|
|
112
|
+
agent: z.string().optional(),
|
|
113
|
+
noReply: z.boolean().optional(),
|
|
114
|
+
tools: z.record(z.string(), z.boolean()).optional(),
|
|
115
|
+
system: z.string().optional(),
|
|
116
|
+
parts: z.array(
|
|
117
|
+
z.discriminatedUnion("type", [
|
|
118
|
+
MessageV2.TextPart.omit({
|
|
119
|
+
messageID: true,
|
|
120
|
+
sessionID: true,
|
|
121
|
+
})
|
|
122
|
+
.partial({
|
|
123
|
+
id: true,
|
|
124
|
+
})
|
|
125
|
+
.meta({
|
|
126
|
+
ref: "TextPartInput",
|
|
127
|
+
}),
|
|
128
|
+
MessageV2.FilePart.omit({
|
|
129
|
+
messageID: true,
|
|
130
|
+
sessionID: true,
|
|
131
|
+
})
|
|
132
|
+
.partial({
|
|
133
|
+
id: true,
|
|
134
|
+
})
|
|
135
|
+
.meta({
|
|
136
|
+
ref: "FilePartInput",
|
|
137
|
+
}),
|
|
138
|
+
MessageV2.AgentPart.omit({
|
|
139
|
+
messageID: true,
|
|
140
|
+
sessionID: true,
|
|
141
|
+
})
|
|
142
|
+
.partial({
|
|
143
|
+
id: true,
|
|
144
|
+
})
|
|
145
|
+
.meta({
|
|
146
|
+
ref: "AgentPartInput",
|
|
147
|
+
}),
|
|
148
|
+
MessageV2.SubtaskPart.omit({
|
|
149
|
+
messageID: true,
|
|
150
|
+
sessionID: true,
|
|
151
|
+
})
|
|
152
|
+
.partial({
|
|
153
|
+
id: true,
|
|
154
|
+
})
|
|
155
|
+
.meta({
|
|
156
|
+
ref: "SubtaskPartInput",
|
|
157
|
+
}),
|
|
158
|
+
]),
|
|
159
|
+
),
|
|
160
|
+
})
|
|
161
|
+
export type PromptInput = z.infer<typeof PromptInput>
|
|
162
|
+
|
|
163
|
+
export const prompt = fn(PromptInput, async (input) => {
|
|
164
|
+
const session = await Session.get(input.sessionID)
|
|
165
|
+
await SessionRevert.cleanup(session)
|
|
166
|
+
|
|
167
|
+
const message = await createUserMessage(input)
|
|
168
|
+
await Session.touch(input.sessionID)
|
|
169
|
+
|
|
170
|
+
if (input.noReply === true) {
|
|
171
|
+
return message
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return loop(input.sessionID)
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
export async function resolvePromptParts(template: string): Promise<PromptInput["parts"]> {
|
|
178
|
+
const parts: PromptInput["parts"] = [
|
|
179
|
+
{
|
|
180
|
+
type: "text",
|
|
181
|
+
text: template,
|
|
182
|
+
},
|
|
183
|
+
]
|
|
184
|
+
const files = ConfigMarkdown.files(template)
|
|
185
|
+
const seen = new Set<string>()
|
|
186
|
+
await Promise.all(
|
|
187
|
+
files.map(async (match) => {
|
|
188
|
+
const name = match[1]
|
|
189
|
+
if (seen.has(name)) return
|
|
190
|
+
seen.add(name)
|
|
191
|
+
const filepath = name.startsWith("~/")
|
|
192
|
+
? path.join(os.homedir(), name.slice(2))
|
|
193
|
+
: path.resolve(Instance.worktree, name)
|
|
194
|
+
|
|
195
|
+
const stats = await fs.stat(filepath).catch(() => undefined)
|
|
196
|
+
if (!stats) {
|
|
197
|
+
const agent = await Agent.get(name)
|
|
198
|
+
if (agent) {
|
|
199
|
+
parts.push({
|
|
200
|
+
type: "agent",
|
|
201
|
+
name: agent.name,
|
|
202
|
+
})
|
|
203
|
+
}
|
|
204
|
+
return
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (stats.isDirectory()) {
|
|
208
|
+
parts.push({
|
|
209
|
+
type: "file",
|
|
210
|
+
url: `file://${filepath}`,
|
|
211
|
+
filename: name,
|
|
212
|
+
mime: "application/x-directory",
|
|
213
|
+
})
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
parts.push({
|
|
218
|
+
type: "file",
|
|
219
|
+
url: `file://${filepath}`,
|
|
220
|
+
filename: name,
|
|
221
|
+
mime: "text/plain",
|
|
222
|
+
})
|
|
223
|
+
}),
|
|
224
|
+
)
|
|
225
|
+
return parts
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function start(sessionID: string) {
|
|
229
|
+
const s = state()
|
|
230
|
+
if (s[sessionID]) return
|
|
231
|
+
const controller = new AbortController()
|
|
232
|
+
s[sessionID] = {
|
|
233
|
+
abort: controller,
|
|
234
|
+
callbacks: [],
|
|
235
|
+
}
|
|
236
|
+
return controller.signal
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
export function cancel(sessionID: string) {
|
|
240
|
+
log.info("cancel", { sessionID })
|
|
241
|
+
const s = state()
|
|
242
|
+
const match = s[sessionID]
|
|
243
|
+
if (!match) return
|
|
244
|
+
match.abort.abort()
|
|
245
|
+
for (const item of match.callbacks) {
|
|
246
|
+
item.reject()
|
|
247
|
+
}
|
|
248
|
+
delete s[sessionID]
|
|
249
|
+
SessionStatus.set(sessionID, { type: "idle" })
|
|
250
|
+
return
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export const loop = fn(Identifier.schema("session"), async (sessionID) => {
|
|
254
|
+
const abort = start(sessionID)
|
|
255
|
+
if (!abort) {
|
|
256
|
+
return new Promise<MessageV2.WithParts>((resolve, reject) => {
|
|
257
|
+
const callbacks = state()[sessionID].callbacks
|
|
258
|
+
callbacks.push({ resolve, reject })
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
using _ = defer(() => cancel(sessionID))
|
|
263
|
+
|
|
264
|
+
let step = 0
|
|
265
|
+
while (true) {
|
|
266
|
+
SessionStatus.set(sessionID, { type: "busy" })
|
|
267
|
+
log.info("loop", { step, sessionID })
|
|
268
|
+
if (abort.aborted) break
|
|
269
|
+
let msgs = await MessageV2.filterCompacted(MessageV2.stream(sessionID))
|
|
270
|
+
|
|
271
|
+
let lastUser: MessageV2.User | undefined
|
|
272
|
+
let lastAssistant: MessageV2.Assistant | undefined
|
|
273
|
+
let lastFinished: MessageV2.Assistant | undefined
|
|
274
|
+
let tasks: (MessageV2.CompactionPart | MessageV2.SubtaskPart)[] = []
|
|
275
|
+
for (let i = msgs.length - 1; i >= 0; i--) {
|
|
276
|
+
const msg = msgs[i]
|
|
277
|
+
if (!lastUser && msg.info.role === "user") lastUser = msg.info as MessageV2.User
|
|
278
|
+
if (!lastAssistant && msg.info.role === "assistant") lastAssistant = msg.info as MessageV2.Assistant
|
|
279
|
+
if (!lastFinished && msg.info.role === "assistant" && msg.info.finish)
|
|
280
|
+
lastFinished = msg.info as MessageV2.Assistant
|
|
281
|
+
if (lastUser && lastFinished) break
|
|
282
|
+
const task = msg.parts.filter((part) => part.type === "compaction" || part.type === "subtask")
|
|
283
|
+
if (task && !lastFinished) {
|
|
284
|
+
tasks.push(...task)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (!lastUser) throw new Error("No user message found in stream. This should never happen.")
|
|
289
|
+
if (
|
|
290
|
+
lastAssistant?.finish &&
|
|
291
|
+
!["tool-calls", "unknown"].includes(lastAssistant.finish) &&
|
|
292
|
+
lastUser.id < lastAssistant.id
|
|
293
|
+
) {
|
|
294
|
+
log.info("exiting loop", { sessionID })
|
|
295
|
+
break
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
step++
|
|
299
|
+
if (step === 1)
|
|
300
|
+
ensureTitle({
|
|
301
|
+
session: await Session.get(sessionID),
|
|
302
|
+
modelID: lastUser.model.modelID,
|
|
303
|
+
providerID: lastUser.model.providerID,
|
|
304
|
+
message: msgs.find((m) => m.info.role === "user")!,
|
|
305
|
+
history: msgs,
|
|
306
|
+
})
|
|
307
|
+
|
|
308
|
+
const model = await Provider.getModel(lastUser.model.providerID, lastUser.model.modelID)
|
|
309
|
+
// Get action model (small/cheap model) for tool call continuation steps
|
|
310
|
+
let actionModel: Provider.Model | undefined
|
|
311
|
+
try {
|
|
312
|
+
actionModel = await Provider.getSmallModel(lastUser.model.providerID)
|
|
313
|
+
} catch (e) {
|
|
314
|
+
// Silently fall back to main model if small model unavailable
|
|
315
|
+
}
|
|
316
|
+
// Get vision model for image processing
|
|
317
|
+
let visionModel: Provider.Model | undefined
|
|
318
|
+
try {
|
|
319
|
+
visionModel = await Provider.getVisionModel(lastUser.model.providerID)
|
|
320
|
+
} catch (e) {
|
|
321
|
+
// Silently fall back to main model if vision model unavailable
|
|
322
|
+
}
|
|
323
|
+
// Check if messages contain images (need vision model)
|
|
324
|
+
const hasImages = msgs.some((msg) =>
|
|
325
|
+
msg.parts.some((part) => part.type === "file" && part.mime?.startsWith("image/"))
|
|
326
|
+
)
|
|
327
|
+
// Check if there are pending tool calls to execute (last assistant ended with tool-calls)
|
|
328
|
+
const hasPendingToolCalls = lastAssistant?.finish === "tool-calls"
|
|
329
|
+
// Model selection priority:
|
|
330
|
+
// 1. Vision model when images present
|
|
331
|
+
// 2. Action model ONLY for tool call execution (when lastAssistant has pending tool-calls)
|
|
332
|
+
// 3. Main model for planning (step 1), output, and retries
|
|
333
|
+
let effectiveModel = model
|
|
334
|
+
if (hasImages && visionModel) {
|
|
335
|
+
effectiveModel = visionModel
|
|
336
|
+
} else if (hasPendingToolCalls && actionModel) {
|
|
337
|
+
effectiveModel = actionModel
|
|
338
|
+
}
|
|
339
|
+
const task = tasks.pop()
|
|
340
|
+
|
|
341
|
+
// pending subtask
|
|
342
|
+
// TODO: centralize "invoke tool" logic
|
|
343
|
+
if (task?.type === "subtask") {
|
|
344
|
+
const taskTool = await TaskTool.init()
|
|
345
|
+
const assistantMessage = (await Session.updateMessage({
|
|
346
|
+
id: Identifier.ascending("message"),
|
|
347
|
+
role: "assistant",
|
|
348
|
+
parentID: lastUser.id,
|
|
349
|
+
sessionID,
|
|
350
|
+
mode: task.agent,
|
|
351
|
+
agent: task.agent,
|
|
352
|
+
path: {
|
|
353
|
+
cwd: Instance.directory,
|
|
354
|
+
root: Instance.worktree,
|
|
355
|
+
},
|
|
356
|
+
cost: 0,
|
|
357
|
+
tokens: {
|
|
358
|
+
input: 0,
|
|
359
|
+
output: 0,
|
|
360
|
+
reasoning: 0,
|
|
361
|
+
cache: { read: 0, write: 0 },
|
|
362
|
+
},
|
|
363
|
+
modelID: model.id,
|
|
364
|
+
providerID: model.providerID,
|
|
365
|
+
time: {
|
|
366
|
+
created: Date.now(),
|
|
367
|
+
},
|
|
368
|
+
})) as MessageV2.Assistant
|
|
369
|
+
let part = (await Session.updatePart({
|
|
370
|
+
id: Identifier.ascending("part"),
|
|
371
|
+
messageID: assistantMessage.id,
|
|
372
|
+
sessionID: assistantMessage.sessionID,
|
|
373
|
+
type: "tool",
|
|
374
|
+
callID: ulid(),
|
|
375
|
+
tool: TaskTool.id,
|
|
376
|
+
state: {
|
|
377
|
+
status: "running",
|
|
378
|
+
input: {
|
|
379
|
+
prompt: task.prompt,
|
|
380
|
+
description: task.description,
|
|
381
|
+
subagent_type: task.agent,
|
|
382
|
+
command: task.command,
|
|
383
|
+
},
|
|
384
|
+
time: {
|
|
385
|
+
start: Date.now(),
|
|
386
|
+
},
|
|
387
|
+
},
|
|
388
|
+
})) as MessageV2.ToolPart
|
|
389
|
+
const taskArgs = {
|
|
390
|
+
prompt: task.prompt,
|
|
391
|
+
description: task.description,
|
|
392
|
+
subagent_type: task.agent,
|
|
393
|
+
command: task.command,
|
|
394
|
+
}
|
|
395
|
+
await Plugin.trigger(
|
|
396
|
+
"tool.execute.before",
|
|
397
|
+
{
|
|
398
|
+
tool: "task",
|
|
399
|
+
sessionID,
|
|
400
|
+
callID: part.id,
|
|
401
|
+
},
|
|
402
|
+
{ args: taskArgs },
|
|
403
|
+
)
|
|
404
|
+
let executionError: Error | undefined
|
|
405
|
+
const result = await taskTool
|
|
406
|
+
.execute(taskArgs, {
|
|
407
|
+
agent: task.agent,
|
|
408
|
+
messageID: assistantMessage.id,
|
|
409
|
+
sessionID: sessionID,
|
|
410
|
+
abort,
|
|
411
|
+
async metadata(input) {
|
|
412
|
+
await Session.updatePart({
|
|
413
|
+
...part,
|
|
414
|
+
type: "tool",
|
|
415
|
+
state: {
|
|
416
|
+
...part.state,
|
|
417
|
+
...input,
|
|
418
|
+
},
|
|
419
|
+
} satisfies MessageV2.ToolPart)
|
|
420
|
+
},
|
|
421
|
+
})
|
|
422
|
+
.catch((error) => {
|
|
423
|
+
executionError = error
|
|
424
|
+
log.error("subtask execution failed", { error, agent: task.agent, description: task.description })
|
|
425
|
+
return undefined
|
|
426
|
+
})
|
|
427
|
+
await Plugin.trigger(
|
|
428
|
+
"tool.execute.after",
|
|
429
|
+
{
|
|
430
|
+
tool: "task",
|
|
431
|
+
sessionID,
|
|
432
|
+
callID: part.id,
|
|
433
|
+
},
|
|
434
|
+
result,
|
|
435
|
+
)
|
|
436
|
+
assistantMessage.finish = "tool-calls"
|
|
437
|
+
assistantMessage.time.completed = Date.now()
|
|
438
|
+
await Session.updateMessage(assistantMessage)
|
|
439
|
+
if (result && part.state.status === "running") {
|
|
440
|
+
await Session.updatePart({
|
|
441
|
+
...part,
|
|
442
|
+
state: {
|
|
443
|
+
status: "completed",
|
|
444
|
+
input: part.state.input,
|
|
445
|
+
title: result.title,
|
|
446
|
+
metadata: result.metadata,
|
|
447
|
+
output: result.output,
|
|
448
|
+
attachments: result.attachments,
|
|
449
|
+
time: {
|
|
450
|
+
...part.state.time,
|
|
451
|
+
end: Date.now(),
|
|
452
|
+
},
|
|
453
|
+
},
|
|
454
|
+
} satisfies MessageV2.ToolPart)
|
|
455
|
+
}
|
|
456
|
+
if (!result) {
|
|
457
|
+
await Session.updatePart({
|
|
458
|
+
...part,
|
|
459
|
+
state: {
|
|
460
|
+
status: "error",
|
|
461
|
+
error: executionError ? `Tool execution failed: ${executionError.message}` : "Tool execution failed",
|
|
462
|
+
time: {
|
|
463
|
+
start: part.state.status === "running" ? part.state.time.start : Date.now(),
|
|
464
|
+
end: Date.now(),
|
|
465
|
+
},
|
|
466
|
+
metadata: part.metadata,
|
|
467
|
+
input: part.state.input,
|
|
468
|
+
},
|
|
469
|
+
} satisfies MessageV2.ToolPart)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// Add synthetic user message to prevent certain reasoning models from erroring
|
|
473
|
+
// If we create assistant messages w/ out user ones following mid loop thinking signatures
|
|
474
|
+
// will be missing and it can cause errors for models like gemini for example
|
|
475
|
+
const summaryUserMsg: MessageV2.User = {
|
|
476
|
+
id: Identifier.ascending("message"),
|
|
477
|
+
sessionID,
|
|
478
|
+
role: "user",
|
|
479
|
+
time: {
|
|
480
|
+
created: Date.now(),
|
|
481
|
+
},
|
|
482
|
+
agent: lastUser.agent,
|
|
483
|
+
model: lastUser.model,
|
|
484
|
+
}
|
|
485
|
+
await Session.updateMessage(summaryUserMsg)
|
|
486
|
+
await Session.updatePart({
|
|
487
|
+
id: Identifier.ascending("part"),
|
|
488
|
+
messageID: summaryUserMsg.id,
|
|
489
|
+
sessionID,
|
|
490
|
+
type: "text",
|
|
491
|
+
text: "Summarize the task tool output above and continue with your task.",
|
|
492
|
+
synthetic: true,
|
|
493
|
+
} satisfies MessageV2.TextPart)
|
|
494
|
+
|
|
495
|
+
continue
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
// pending compaction
|
|
499
|
+
if (task?.type === "compaction") {
|
|
500
|
+
const result = await SessionCompaction.process({
|
|
501
|
+
messages: msgs,
|
|
502
|
+
parentID: lastUser.id,
|
|
503
|
+
abort,
|
|
504
|
+
sessionID,
|
|
505
|
+
auto: task.auto,
|
|
506
|
+
})
|
|
507
|
+
if (result === "stop") break
|
|
508
|
+
continue
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// context overflow, needs compaction
|
|
512
|
+
if (
|
|
513
|
+
lastFinished &&
|
|
514
|
+
lastFinished.summary !== true &&
|
|
515
|
+
SessionCompaction.isOverflow({ tokens: lastFinished.tokens, model })
|
|
516
|
+
) {
|
|
517
|
+
await SessionCompaction.create({
|
|
518
|
+
sessionID,
|
|
519
|
+
agent: lastUser.agent,
|
|
520
|
+
model: lastUser.model,
|
|
521
|
+
auto: true,
|
|
522
|
+
})
|
|
523
|
+
continue
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// normal processing
|
|
527
|
+
const agent = await Agent.get(lastUser.agent)
|
|
528
|
+
const maxSteps = agent.maxSteps ?? Infinity
|
|
529
|
+
const isLastStep = step >= maxSteps
|
|
530
|
+
msgs = insertReminders({
|
|
531
|
+
messages: msgs,
|
|
532
|
+
agent,
|
|
533
|
+
})
|
|
534
|
+
|
|
535
|
+
const processor = SessionProcessor.create({
|
|
536
|
+
assistantMessage: (await Session.updateMessage({
|
|
537
|
+
id: Identifier.ascending("message"),
|
|
538
|
+
parentID: lastUser.id,
|
|
539
|
+
role: "assistant",
|
|
540
|
+
mode: agent.name,
|
|
541
|
+
agent: agent.name,
|
|
542
|
+
path: {
|
|
543
|
+
cwd: Instance.directory,
|
|
544
|
+
root: Instance.worktree,
|
|
545
|
+
},
|
|
546
|
+
cost: 0,
|
|
547
|
+
tokens: {
|
|
548
|
+
input: 0,
|
|
549
|
+
output: 0,
|
|
550
|
+
reasoning: 0,
|
|
551
|
+
cache: { read: 0, write: 0 },
|
|
552
|
+
},
|
|
553
|
+
modelID: effectiveModel.id,
|
|
554
|
+
providerID: effectiveModel.providerID,
|
|
555
|
+
time: {
|
|
556
|
+
created: Date.now(),
|
|
557
|
+
},
|
|
558
|
+
sessionID,
|
|
559
|
+
})) as MessageV2.Assistant,
|
|
560
|
+
sessionID: sessionID,
|
|
561
|
+
model: effectiveModel,
|
|
562
|
+
abort,
|
|
563
|
+
})
|
|
564
|
+
const tools = await resolveTools({
|
|
565
|
+
agent,
|
|
566
|
+
sessionID,
|
|
567
|
+
model,
|
|
568
|
+
tools: lastUser.tools,
|
|
569
|
+
processor,
|
|
570
|
+
})
|
|
571
|
+
|
|
572
|
+
if (step === 1) {
|
|
573
|
+
SessionSummary.summarize({
|
|
574
|
+
sessionID: sessionID,
|
|
575
|
+
messageID: lastUser.id,
|
|
576
|
+
})
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const sessionMessages = clone(msgs)
|
|
580
|
+
|
|
581
|
+
await Plugin.trigger("experimental.chat.messages.transform", {}, { messages: sessionMessages })
|
|
582
|
+
|
|
583
|
+
const result = await processor.process({
|
|
584
|
+
user: lastUser,
|
|
585
|
+
agent,
|
|
586
|
+
abort,
|
|
587
|
+
sessionID,
|
|
588
|
+
system: [...(await SystemPrompt.environment()), ...(await SystemPrompt.custom())],
|
|
589
|
+
messages: [
|
|
590
|
+
...MessageV2.toModelMessage(sessionMessages, { sessionID }),
|
|
591
|
+
...(isLastStep
|
|
592
|
+
? [
|
|
593
|
+
{
|
|
594
|
+
role: "assistant" as const,
|
|
595
|
+
content: MAX_STEPS,
|
|
596
|
+
},
|
|
597
|
+
]
|
|
598
|
+
: []),
|
|
599
|
+
],
|
|
600
|
+
tools,
|
|
601
|
+
model: effectiveModel,
|
|
602
|
+
})
|
|
603
|
+
if (result === "stop") break
|
|
604
|
+
continue
|
|
605
|
+
}
|
|
606
|
+
SessionCompaction.prune({ sessionID })
|
|
607
|
+
for await (const item of MessageV2.stream(sessionID)) {
|
|
608
|
+
if (item.info.role === "user") continue
|
|
609
|
+
const queued = state()[sessionID]?.callbacks ?? []
|
|
610
|
+
for (const q of queued) {
|
|
611
|
+
q.resolve(item)
|
|
612
|
+
}
|
|
613
|
+
return item
|
|
614
|
+
}
|
|
615
|
+
throw new Error("Impossible")
|
|
616
|
+
})
|
|
617
|
+
|
|
618
|
+
async function lastModel(sessionID: string) {
|
|
619
|
+
for await (const item of MessageV2.stream(sessionID)) {
|
|
620
|
+
if (item.info.role === "user" && item.info.model) return item.info.model
|
|
621
|
+
}
|
|
622
|
+
return Provider.defaultModel()
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
async function resolveTools(input: {
|
|
626
|
+
agent: Agent.Info
|
|
627
|
+
model: Provider.Model
|
|
628
|
+
sessionID: string
|
|
629
|
+
tools?: Record<string, boolean>
|
|
630
|
+
processor: SessionProcessor.Info
|
|
631
|
+
}) {
|
|
632
|
+
using _ = log.time("resolveTools")
|
|
633
|
+
const tools: Record<string, AITool> = {}
|
|
634
|
+
const enabledTools = pipe(
|
|
635
|
+
input.agent.tools,
|
|
636
|
+
mergeDeep(await ToolRegistry.enabled(input.agent)),
|
|
637
|
+
mergeDeep(input.tools ?? {}),
|
|
638
|
+
)
|
|
639
|
+
for (const item of await ToolRegistry.tools(input.model.providerID, input.agent)) {
|
|
640
|
+
if (Wildcard.all(item.id, enabledTools) === false) continue
|
|
641
|
+
const schema = ProviderTransform.schema(input.model, z.toJSONSchema(item.parameters))
|
|
642
|
+
tools[item.id] = tool({
|
|
643
|
+
id: item.id as any,
|
|
644
|
+
description: item.description,
|
|
645
|
+
inputSchema: jsonSchema(schema as any),
|
|
646
|
+
async execute(args, options) {
|
|
647
|
+
await Plugin.trigger(
|
|
648
|
+
"tool.execute.before",
|
|
649
|
+
{
|
|
650
|
+
tool: item.id,
|
|
651
|
+
sessionID: input.sessionID,
|
|
652
|
+
callID: options.toolCallId,
|
|
653
|
+
},
|
|
654
|
+
{
|
|
655
|
+
args,
|
|
656
|
+
},
|
|
657
|
+
)
|
|
658
|
+
// Restore sensitive data placeholders to real values for actual execution
|
|
659
|
+
// LLM sees: "type [REDACTED-PASSWORD] in field" but tool types the real password
|
|
660
|
+
const restoredArgs = restoreSensitiveInArgs(args, input.sessionID)
|
|
661
|
+
const result = await item.execute(restoredArgs as typeof args, {
|
|
662
|
+
sessionID: input.sessionID,
|
|
663
|
+
abort: options.abortSignal!,
|
|
664
|
+
messageID: input.processor.message.id,
|
|
665
|
+
callID: options.toolCallId,
|
|
666
|
+
extra: { model: input.model },
|
|
667
|
+
agent: input.agent.name,
|
|
668
|
+
metadata: async (val) => {
|
|
669
|
+
const match = input.processor.partFromToolCall(options.toolCallId)
|
|
670
|
+
if (match && match.state.status === "running") {
|
|
671
|
+
await Session.updatePart({
|
|
672
|
+
...match,
|
|
673
|
+
state: {
|
|
674
|
+
title: val.title,
|
|
675
|
+
metadata: val.metadata,
|
|
676
|
+
status: "running",
|
|
677
|
+
input: args,
|
|
678
|
+
time: {
|
|
679
|
+
start: Date.now(),
|
|
680
|
+
},
|
|
681
|
+
},
|
|
682
|
+
})
|
|
683
|
+
}
|
|
684
|
+
},
|
|
685
|
+
})
|
|
686
|
+
await Plugin.trigger(
|
|
687
|
+
"tool.execute.after",
|
|
688
|
+
{
|
|
689
|
+
tool: item.id,
|
|
690
|
+
sessionID: input.sessionID,
|
|
691
|
+
callID: options.toolCallId,
|
|
692
|
+
},
|
|
693
|
+
result,
|
|
694
|
+
)
|
|
695
|
+
return result
|
|
696
|
+
},
|
|
697
|
+
toModelOutput(result) {
|
|
698
|
+
return {
|
|
699
|
+
type: "text",
|
|
700
|
+
value: result.output,
|
|
701
|
+
}
|
|
702
|
+
},
|
|
703
|
+
})
|
|
704
|
+
}
|
|
705
|
+
for (const [key, item] of Object.entries(await MCP.tools())) {
|
|
706
|
+
if (Wildcard.all(key, enabledTools) === false) continue
|
|
707
|
+
const execute = item.execute
|
|
708
|
+
if (!execute) continue
|
|
709
|
+
|
|
710
|
+
// Wrap execute to add plugin hooks and format output
|
|
711
|
+
item.execute = async (args, opts) => {
|
|
712
|
+
await Plugin.trigger(
|
|
713
|
+
"tool.execute.before",
|
|
714
|
+
{
|
|
715
|
+
tool: key,
|
|
716
|
+
sessionID: input.sessionID,
|
|
717
|
+
callID: opts.toolCallId,
|
|
718
|
+
},
|
|
719
|
+
{
|
|
720
|
+
args,
|
|
721
|
+
},
|
|
722
|
+
)
|
|
723
|
+
const result = await execute(args, opts)
|
|
724
|
+
|
|
725
|
+
await Plugin.trigger(
|
|
726
|
+
"tool.execute.after",
|
|
727
|
+
{
|
|
728
|
+
tool: key,
|
|
729
|
+
sessionID: input.sessionID,
|
|
730
|
+
callID: opts.toolCallId,
|
|
731
|
+
},
|
|
732
|
+
result,
|
|
733
|
+
)
|
|
734
|
+
|
|
735
|
+
const textParts: string[] = []
|
|
736
|
+
const attachments: MessageV2.FilePart[] = []
|
|
737
|
+
|
|
738
|
+
for (const contentItem of result.content) {
|
|
739
|
+
if (contentItem.type === "text") {
|
|
740
|
+
textParts.push(contentItem.text)
|
|
741
|
+
} else if (contentItem.type === "image") {
|
|
742
|
+
attachments.push({
|
|
743
|
+
id: Identifier.ascending("part"),
|
|
744
|
+
sessionID: input.sessionID,
|
|
745
|
+
messageID: input.processor.message.id,
|
|
746
|
+
type: "file",
|
|
747
|
+
mime: contentItem.mimeType,
|
|
748
|
+
url: `data:${contentItem.mimeType};base64,${contentItem.data}`,
|
|
749
|
+
})
|
|
750
|
+
}
|
|
751
|
+
// Add support for other types if needed
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
return {
|
|
755
|
+
title: "",
|
|
756
|
+
metadata: result.metadata ?? {},
|
|
757
|
+
output: textParts.join("\n\n"),
|
|
758
|
+
attachments,
|
|
759
|
+
content: result.content, // directly return content to preserve ordering when outputting to model
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
item.toModelOutput = (result) => {
|
|
763
|
+
return {
|
|
764
|
+
type: "text",
|
|
765
|
+
value: result.output,
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
tools[key] = item
|
|
769
|
+
}
|
|
770
|
+
return tools
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
async function createUserMessage(input: PromptInput) {
|
|
774
|
+
const agent = await Agent.get(input.agent ?? (await Agent.defaultAgent()))
|
|
775
|
+
const info: MessageV2.Info = {
|
|
776
|
+
id: input.messageID ?? Identifier.ascending("message"),
|
|
777
|
+
role: "user",
|
|
778
|
+
sessionID: input.sessionID,
|
|
779
|
+
time: {
|
|
780
|
+
created: Date.now(),
|
|
781
|
+
},
|
|
782
|
+
tools: input.tools,
|
|
783
|
+
agent: agent.name,
|
|
784
|
+
model: input.model ?? agent.model ?? (await lastModel(input.sessionID)),
|
|
785
|
+
system: input.system,
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
const parts = await Promise.all(
|
|
789
|
+
input.parts.map(async (part): Promise<MessageV2.Part[]> => {
|
|
790
|
+
if (part.type === "file") {
|
|
791
|
+
const url = new URL(part.url)
|
|
792
|
+
switch (url.protocol) {
|
|
793
|
+
case "data:":
|
|
794
|
+
if (part.mime === "text/plain") {
|
|
795
|
+
return [
|
|
796
|
+
{
|
|
797
|
+
id: Identifier.ascending("part"),
|
|
798
|
+
messageID: info.id,
|
|
799
|
+
sessionID: input.sessionID,
|
|
800
|
+
type: "text",
|
|
801
|
+
synthetic: true,
|
|
802
|
+
text: `Called the Read tool with the following input: ${JSON.stringify({ filePath: part.filename })}`,
|
|
803
|
+
},
|
|
804
|
+
{
|
|
805
|
+
id: Identifier.ascending("part"),
|
|
806
|
+
messageID: info.id,
|
|
807
|
+
sessionID: input.sessionID,
|
|
808
|
+
type: "text",
|
|
809
|
+
synthetic: true,
|
|
810
|
+
text: Buffer.from(part.url, "base64url").toString(),
|
|
811
|
+
},
|
|
812
|
+
{
|
|
813
|
+
...part,
|
|
814
|
+
id: part.id ?? Identifier.ascending("part"),
|
|
815
|
+
messageID: info.id,
|
|
816
|
+
sessionID: input.sessionID,
|
|
817
|
+
},
|
|
818
|
+
]
|
|
819
|
+
}
|
|
820
|
+
break
|
|
821
|
+
case "file:":
|
|
822
|
+
log.info("file", { mime: part.mime })
|
|
823
|
+
// have to normalize, symbol search returns absolute paths
|
|
824
|
+
// Decode the pathname since URL constructor doesn't automatically decode it
|
|
825
|
+
const filepath = fileURLToPath(part.url)
|
|
826
|
+
const stat = await Bun.file(filepath).stat()
|
|
827
|
+
|
|
828
|
+
if (stat.isDirectory()) {
|
|
829
|
+
part.mime = "application/x-directory"
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
if (part.mime === "text/plain") {
|
|
833
|
+
let offset: number | undefined = undefined
|
|
834
|
+
let limit: number | undefined = undefined
|
|
835
|
+
const range = {
|
|
836
|
+
start: url.searchParams.get("start"),
|
|
837
|
+
end: url.searchParams.get("end"),
|
|
838
|
+
}
|
|
839
|
+
if (range.start != null) {
|
|
840
|
+
const filePathURI = part.url.split("?")[0]
|
|
841
|
+
let start = parseInt(range.start)
|
|
842
|
+
let end = range.end ? parseInt(range.end) : undefined
|
|
843
|
+
// some LSP servers (eg, gopls) don't give full range in
|
|
844
|
+
// workspace/symbol searches, so we'll try to find the
|
|
845
|
+
// symbol in the document to get the full range
|
|
846
|
+
if (start === end) {
|
|
847
|
+
const symbols = await LSP.documentSymbol(filePathURI)
|
|
848
|
+
for (const symbol of symbols) {
|
|
849
|
+
let range: LSP.Range | undefined
|
|
850
|
+
if ("range" in symbol) {
|
|
851
|
+
range = symbol.range
|
|
852
|
+
} else if ("location" in symbol) {
|
|
853
|
+
range = symbol.location.range
|
|
854
|
+
}
|
|
855
|
+
if (range?.start?.line && range?.start?.line === start) {
|
|
856
|
+
start = range.start.line
|
|
857
|
+
end = range?.end?.line ?? start
|
|
858
|
+
break
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
offset = Math.max(start - 1, 0)
|
|
863
|
+
if (end) {
|
|
864
|
+
limit = end - offset
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
const args = { filePath: filepath, offset, limit }
|
|
868
|
+
|
|
869
|
+
const pieces: MessageV2.Part[] = [
|
|
870
|
+
{
|
|
871
|
+
id: Identifier.ascending("part"),
|
|
872
|
+
messageID: info.id,
|
|
873
|
+
sessionID: input.sessionID,
|
|
874
|
+
type: "text",
|
|
875
|
+
synthetic: true,
|
|
876
|
+
text: `Called the Read tool with the following input: ${JSON.stringify(args)}`,
|
|
877
|
+
},
|
|
878
|
+
]
|
|
879
|
+
|
|
880
|
+
await ReadTool.init()
|
|
881
|
+
.then(async (t) => {
|
|
882
|
+
const model = await Provider.getModel(info.model.providerID, info.model.modelID)
|
|
883
|
+
const result = await t.execute(args, {
|
|
884
|
+
sessionID: input.sessionID,
|
|
885
|
+
abort: new AbortController().signal,
|
|
886
|
+
agent: input.agent!,
|
|
887
|
+
messageID: info.id,
|
|
888
|
+
extra: { bypassCwdCheck: true, model },
|
|
889
|
+
metadata: async () => {},
|
|
890
|
+
})
|
|
891
|
+
pieces.push({
|
|
892
|
+
id: Identifier.ascending("part"),
|
|
893
|
+
messageID: info.id,
|
|
894
|
+
sessionID: input.sessionID,
|
|
895
|
+
type: "text",
|
|
896
|
+
synthetic: true,
|
|
897
|
+
text: result.output,
|
|
898
|
+
})
|
|
899
|
+
if (result.attachments?.length) {
|
|
900
|
+
pieces.push(
|
|
901
|
+
...result.attachments.map((attachment) => ({
|
|
902
|
+
...attachment,
|
|
903
|
+
synthetic: true,
|
|
904
|
+
filename: attachment.filename ?? part.filename,
|
|
905
|
+
messageID: info.id,
|
|
906
|
+
sessionID: input.sessionID,
|
|
907
|
+
})),
|
|
908
|
+
)
|
|
909
|
+
} else {
|
|
910
|
+
pieces.push({
|
|
911
|
+
...part,
|
|
912
|
+
id: part.id ?? Identifier.ascending("part"),
|
|
913
|
+
messageID: info.id,
|
|
914
|
+
sessionID: input.sessionID,
|
|
915
|
+
})
|
|
916
|
+
}
|
|
917
|
+
})
|
|
918
|
+
.catch((error) => {
|
|
919
|
+
log.error("failed to read file", { error })
|
|
920
|
+
const message = error instanceof Error ? error.message : error.toString()
|
|
921
|
+
Bus.publish(Session.Event.Error, {
|
|
922
|
+
sessionID: input.sessionID,
|
|
923
|
+
error: new NamedError.Unknown({
|
|
924
|
+
message,
|
|
925
|
+
}).toObject(),
|
|
926
|
+
})
|
|
927
|
+
pieces.push({
|
|
928
|
+
id: Identifier.ascending("part"),
|
|
929
|
+
messageID: info.id,
|
|
930
|
+
sessionID: input.sessionID,
|
|
931
|
+
type: "text",
|
|
932
|
+
synthetic: true,
|
|
933
|
+
text: `Read tool failed to read ${filepath} with the following error: ${message}`,
|
|
934
|
+
})
|
|
935
|
+
})
|
|
936
|
+
|
|
937
|
+
return pieces
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
if (part.mime === "application/x-directory") {
|
|
941
|
+
const args = { path: filepath }
|
|
942
|
+
const result = await ListTool.init().then((t) =>
|
|
943
|
+
t.execute(args, {
|
|
944
|
+
sessionID: input.sessionID,
|
|
945
|
+
abort: new AbortController().signal,
|
|
946
|
+
agent: input.agent!,
|
|
947
|
+
messageID: info.id,
|
|
948
|
+
extra: { bypassCwdCheck: true },
|
|
949
|
+
metadata: async () => {},
|
|
950
|
+
}),
|
|
951
|
+
)
|
|
952
|
+
return [
|
|
953
|
+
{
|
|
954
|
+
id: Identifier.ascending("part"),
|
|
955
|
+
messageID: info.id,
|
|
956
|
+
sessionID: input.sessionID,
|
|
957
|
+
type: "text",
|
|
958
|
+
synthetic: true,
|
|
959
|
+
text: `Called the list tool with the following input: ${JSON.stringify(args)}`,
|
|
960
|
+
},
|
|
961
|
+
{
|
|
962
|
+
id: Identifier.ascending("part"),
|
|
963
|
+
messageID: info.id,
|
|
964
|
+
sessionID: input.sessionID,
|
|
965
|
+
type: "text",
|
|
966
|
+
synthetic: true,
|
|
967
|
+
text: result.output,
|
|
968
|
+
},
|
|
969
|
+
{
|
|
970
|
+
...part,
|
|
971
|
+
id: part.id ?? Identifier.ascending("part"),
|
|
972
|
+
messageID: info.id,
|
|
973
|
+
sessionID: input.sessionID,
|
|
974
|
+
},
|
|
975
|
+
]
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
const file = Bun.file(filepath)
|
|
979
|
+
FileTime.read(input.sessionID, filepath)
|
|
980
|
+
return [
|
|
981
|
+
{
|
|
982
|
+
id: Identifier.ascending("part"),
|
|
983
|
+
messageID: info.id,
|
|
984
|
+
sessionID: input.sessionID,
|
|
985
|
+
type: "text",
|
|
986
|
+
text: `Called the Read tool with the following input: {\"filePath\":\"${filepath}\"}`,
|
|
987
|
+
synthetic: true,
|
|
988
|
+
},
|
|
989
|
+
{
|
|
990
|
+
id: part.id ?? Identifier.ascending("part"),
|
|
991
|
+
messageID: info.id,
|
|
992
|
+
sessionID: input.sessionID,
|
|
993
|
+
type: "file",
|
|
994
|
+
url: `data:${part.mime};base64,` + Buffer.from(await file.bytes()).toString("base64"),
|
|
995
|
+
mime: part.mime,
|
|
996
|
+
filename: part.filename!,
|
|
997
|
+
source: part.source,
|
|
998
|
+
},
|
|
999
|
+
]
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
if (part.type === "agent") {
|
|
1004
|
+
return [
|
|
1005
|
+
{
|
|
1006
|
+
id: Identifier.ascending("part"),
|
|
1007
|
+
...part,
|
|
1008
|
+
messageID: info.id,
|
|
1009
|
+
sessionID: input.sessionID,
|
|
1010
|
+
},
|
|
1011
|
+
{
|
|
1012
|
+
id: Identifier.ascending("part"),
|
|
1013
|
+
messageID: info.id,
|
|
1014
|
+
sessionID: input.sessionID,
|
|
1015
|
+
type: "text",
|
|
1016
|
+
synthetic: true,
|
|
1017
|
+
text:
|
|
1018
|
+
"Use the above message and context to generate a prompt and call the task tool with subagent: " +
|
|
1019
|
+
part.name,
|
|
1020
|
+
},
|
|
1021
|
+
]
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
return [
|
|
1025
|
+
{
|
|
1026
|
+
id: Identifier.ascending("part"),
|
|
1027
|
+
...part,
|
|
1028
|
+
messageID: info.id,
|
|
1029
|
+
sessionID: input.sessionID,
|
|
1030
|
+
},
|
|
1031
|
+
]
|
|
1032
|
+
}),
|
|
1033
|
+
).then((x) => x.flat())
|
|
1034
|
+
|
|
1035
|
+
await Plugin.trigger(
|
|
1036
|
+
"chat.message",
|
|
1037
|
+
{
|
|
1038
|
+
sessionID: input.sessionID,
|
|
1039
|
+
agent: input.agent,
|
|
1040
|
+
model: input.model,
|
|
1041
|
+
messageID: input.messageID,
|
|
1042
|
+
},
|
|
1043
|
+
{
|
|
1044
|
+
message: info,
|
|
1045
|
+
parts,
|
|
1046
|
+
},
|
|
1047
|
+
)
|
|
1048
|
+
|
|
1049
|
+
await Session.updateMessage(info)
|
|
1050
|
+
for (const part of parts) {
|
|
1051
|
+
await Session.updatePart(part)
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
return {
|
|
1055
|
+
info,
|
|
1056
|
+
parts,
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
function insertReminders(input: { messages: MessageV2.WithParts[]; agent: Agent.Info }) {
|
|
1061
|
+
const userMessage = input.messages.findLast((msg) => msg.info.role === "user")
|
|
1062
|
+
if (!userMessage) return input.messages
|
|
1063
|
+
if (input.agent.name === "plan") {
|
|
1064
|
+
userMessage.parts.push({
|
|
1065
|
+
id: Identifier.ascending("part"),
|
|
1066
|
+
messageID: userMessage.info.id,
|
|
1067
|
+
sessionID: userMessage.info.sessionID,
|
|
1068
|
+
type: "text",
|
|
1069
|
+
// TODO (for mr dax): update to use the anthropic full fledged one (see plan-reminder-anthropic.txt)
|
|
1070
|
+
text: PROMPT_PLAN,
|
|
1071
|
+
synthetic: true,
|
|
1072
|
+
})
|
|
1073
|
+
}
|
|
1074
|
+
const wasPlan = input.messages.some((msg) => msg.info.role === "assistant" && msg.info.agent === "plan")
|
|
1075
|
+
if (wasPlan && input.agent.name === "act") {
|
|
1076
|
+
userMessage.parts.push({
|
|
1077
|
+
id: Identifier.ascending("part"),
|
|
1078
|
+
messageID: userMessage.info.id,
|
|
1079
|
+
sessionID: userMessage.info.sessionID,
|
|
1080
|
+
type: "text",
|
|
1081
|
+
text: ACT_SWITCH,
|
|
1082
|
+
synthetic: true,
|
|
1083
|
+
})
|
|
1084
|
+
}
|
|
1085
|
+
return input.messages
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
export const ShellInput = z.object({
|
|
1089
|
+
sessionID: Identifier.schema("session"),
|
|
1090
|
+
agent: z.string(),
|
|
1091
|
+
model: z
|
|
1092
|
+
.object({
|
|
1093
|
+
providerID: z.string(),
|
|
1094
|
+
modelID: z.string(),
|
|
1095
|
+
})
|
|
1096
|
+
.optional(),
|
|
1097
|
+
command: z.string(),
|
|
1098
|
+
})
|
|
1099
|
+
export type ShellInput = z.infer<typeof ShellInput>
|
|
1100
|
+
export async function shell(input: ShellInput) {
|
|
1101
|
+
const abort = start(input.sessionID)
|
|
1102
|
+
if (!abort) {
|
|
1103
|
+
throw new Session.BusyError(input.sessionID)
|
|
1104
|
+
}
|
|
1105
|
+
using _ = defer(() => cancel(input.sessionID))
|
|
1106
|
+
|
|
1107
|
+
const session = await Session.get(input.sessionID)
|
|
1108
|
+
if (session.revert) {
|
|
1109
|
+
SessionRevert.cleanup(session)
|
|
1110
|
+
}
|
|
1111
|
+
const agent = await Agent.get(input.agent)
|
|
1112
|
+
const model = input.model ?? agent.model ?? (await lastModel(input.sessionID))
|
|
1113
|
+
const userMsg: MessageV2.User = {
|
|
1114
|
+
id: Identifier.ascending("message"),
|
|
1115
|
+
sessionID: input.sessionID,
|
|
1116
|
+
time: {
|
|
1117
|
+
created: Date.now(),
|
|
1118
|
+
},
|
|
1119
|
+
role: "user",
|
|
1120
|
+
agent: input.agent,
|
|
1121
|
+
model: {
|
|
1122
|
+
providerID: model.providerID,
|
|
1123
|
+
modelID: model.modelID,
|
|
1124
|
+
},
|
|
1125
|
+
}
|
|
1126
|
+
await Session.updateMessage(userMsg)
|
|
1127
|
+
const userPart: MessageV2.Part = {
|
|
1128
|
+
type: "text",
|
|
1129
|
+
id: Identifier.ascending("part"),
|
|
1130
|
+
messageID: userMsg.id,
|
|
1131
|
+
sessionID: input.sessionID,
|
|
1132
|
+
text: "The following tool was executed by the user",
|
|
1133
|
+
synthetic: true,
|
|
1134
|
+
}
|
|
1135
|
+
await Session.updatePart(userPart)
|
|
1136
|
+
|
|
1137
|
+
const msg: MessageV2.Assistant = {
|
|
1138
|
+
id: Identifier.ascending("message"),
|
|
1139
|
+
sessionID: input.sessionID,
|
|
1140
|
+
parentID: userMsg.id,
|
|
1141
|
+
mode: input.agent,
|
|
1142
|
+
agent: input.agent,
|
|
1143
|
+
cost: 0,
|
|
1144
|
+
path: {
|
|
1145
|
+
cwd: Instance.directory,
|
|
1146
|
+
root: Instance.worktree,
|
|
1147
|
+
},
|
|
1148
|
+
time: {
|
|
1149
|
+
created: Date.now(),
|
|
1150
|
+
},
|
|
1151
|
+
role: "assistant",
|
|
1152
|
+
tokens: {
|
|
1153
|
+
input: 0,
|
|
1154
|
+
output: 0,
|
|
1155
|
+
reasoning: 0,
|
|
1156
|
+
cache: { read: 0, write: 0 },
|
|
1157
|
+
},
|
|
1158
|
+
modelID: model.modelID,
|
|
1159
|
+
providerID: model.providerID,
|
|
1160
|
+
}
|
|
1161
|
+
await Session.updateMessage(msg)
|
|
1162
|
+
const part: MessageV2.Part = {
|
|
1163
|
+
type: "tool",
|
|
1164
|
+
id: Identifier.ascending("part"),
|
|
1165
|
+
messageID: msg.id,
|
|
1166
|
+
sessionID: input.sessionID,
|
|
1167
|
+
tool: "bash",
|
|
1168
|
+
callID: ulid(),
|
|
1169
|
+
state: {
|
|
1170
|
+
status: "running",
|
|
1171
|
+
time: {
|
|
1172
|
+
start: Date.now(),
|
|
1173
|
+
},
|
|
1174
|
+
input: {
|
|
1175
|
+
command: input.command,
|
|
1176
|
+
},
|
|
1177
|
+
},
|
|
1178
|
+
}
|
|
1179
|
+
await Session.updatePart(part)
|
|
1180
|
+
const shell = Shell.preferred()
|
|
1181
|
+
const shellName = (
|
|
1182
|
+
process.platform === "win32" ? path.win32.basename(shell, ".exe") : path.basename(shell)
|
|
1183
|
+
).toLowerCase()
|
|
1184
|
+
|
|
1185
|
+
const invocations: Record<string, { args: string[] }> = {
|
|
1186
|
+
nu: {
|
|
1187
|
+
args: ["-c", input.command],
|
|
1188
|
+
},
|
|
1189
|
+
fish: {
|
|
1190
|
+
args: ["-c", input.command],
|
|
1191
|
+
},
|
|
1192
|
+
zsh: {
|
|
1193
|
+
args: [
|
|
1194
|
+
"-c",
|
|
1195
|
+
"-l",
|
|
1196
|
+
`
|
|
1197
|
+
[[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
|
|
1198
|
+
[[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
|
|
1199
|
+
eval ${JSON.stringify(input.command)}
|
|
1200
|
+
`,
|
|
1201
|
+
],
|
|
1202
|
+
},
|
|
1203
|
+
bash: {
|
|
1204
|
+
args: [
|
|
1205
|
+
"-c",
|
|
1206
|
+
"-l",
|
|
1207
|
+
`
|
|
1208
|
+
shopt -s expand_aliases
|
|
1209
|
+
[[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
|
|
1210
|
+
eval ${JSON.stringify(input.command)}
|
|
1211
|
+
`,
|
|
1212
|
+
],
|
|
1213
|
+
},
|
|
1214
|
+
// Windows cmd
|
|
1215
|
+
cmd: {
|
|
1216
|
+
args: ["/c", input.command],
|
|
1217
|
+
},
|
|
1218
|
+
// Windows PowerShell
|
|
1219
|
+
powershell: {
|
|
1220
|
+
args: ["-NoProfile", "-Command", input.command],
|
|
1221
|
+
},
|
|
1222
|
+
pwsh: {
|
|
1223
|
+
args: ["-NoProfile", "-Command", input.command],
|
|
1224
|
+
},
|
|
1225
|
+
// Fallback: any shell that doesn't match those above
|
|
1226
|
+
// - No -l, for max compatibility
|
|
1227
|
+
"": {
|
|
1228
|
+
args: ["-c", `${input.command}`],
|
|
1229
|
+
},
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
const matchingInvocation = invocations[shellName] ?? invocations[""]
|
|
1233
|
+
const args = matchingInvocation?.args
|
|
1234
|
+
|
|
1235
|
+
const proc = spawn(shell, args, {
|
|
1236
|
+
cwd: Instance.directory,
|
|
1237
|
+
detached: process.platform !== "win32",
|
|
1238
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1239
|
+
env: {
|
|
1240
|
+
...process.env,
|
|
1241
|
+
TERM: "dumb",
|
|
1242
|
+
},
|
|
1243
|
+
})
|
|
1244
|
+
|
|
1245
|
+
let output = ""
|
|
1246
|
+
|
|
1247
|
+
proc.stdout?.on("data", (chunk) => {
|
|
1248
|
+
output += chunk.toString()
|
|
1249
|
+
if (part.state.status === "running") {
|
|
1250
|
+
part.state.metadata = {
|
|
1251
|
+
output: output,
|
|
1252
|
+
description: "",
|
|
1253
|
+
}
|
|
1254
|
+
Session.updatePart(part)
|
|
1255
|
+
}
|
|
1256
|
+
})
|
|
1257
|
+
|
|
1258
|
+
proc.stderr?.on("data", (chunk) => {
|
|
1259
|
+
output += chunk.toString()
|
|
1260
|
+
if (part.state.status === "running") {
|
|
1261
|
+
part.state.metadata = {
|
|
1262
|
+
output: output,
|
|
1263
|
+
description: "",
|
|
1264
|
+
}
|
|
1265
|
+
Session.updatePart(part)
|
|
1266
|
+
}
|
|
1267
|
+
})
|
|
1268
|
+
|
|
1269
|
+
let aborted = false
|
|
1270
|
+
let exited = false
|
|
1271
|
+
|
|
1272
|
+
const kill = () => Shell.killTree(proc, { exited: () => exited })
|
|
1273
|
+
|
|
1274
|
+
if (abort.aborted) {
|
|
1275
|
+
aborted = true
|
|
1276
|
+
await kill()
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
const abortHandler = () => {
|
|
1280
|
+
aborted = true
|
|
1281
|
+
void kill()
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
abort.addEventListener("abort", abortHandler, { once: true })
|
|
1285
|
+
|
|
1286
|
+
await new Promise<void>((resolve) => {
|
|
1287
|
+
proc.on("close", () => {
|
|
1288
|
+
exited = true
|
|
1289
|
+
abort.removeEventListener("abort", abortHandler)
|
|
1290
|
+
resolve()
|
|
1291
|
+
})
|
|
1292
|
+
})
|
|
1293
|
+
|
|
1294
|
+
if (aborted) {
|
|
1295
|
+
output += "\n\n" + ["<metadata>", "User aborted the command", "</metadata>"].join("\n")
|
|
1296
|
+
}
|
|
1297
|
+
msg.time.completed = Date.now()
|
|
1298
|
+
await Session.updateMessage(msg)
|
|
1299
|
+
if (part.state.status === "running") {
|
|
1300
|
+
part.state = {
|
|
1301
|
+
status: "completed",
|
|
1302
|
+
time: {
|
|
1303
|
+
...part.state.time,
|
|
1304
|
+
end: Date.now(),
|
|
1305
|
+
},
|
|
1306
|
+
input: part.state.input,
|
|
1307
|
+
title: "",
|
|
1308
|
+
metadata: {
|
|
1309
|
+
output,
|
|
1310
|
+
description: "",
|
|
1311
|
+
},
|
|
1312
|
+
output,
|
|
1313
|
+
}
|
|
1314
|
+
await Session.updatePart(part)
|
|
1315
|
+
}
|
|
1316
|
+
return { info: msg, parts: [part] }
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
export const CommandInput = z.object({
|
|
1320
|
+
messageID: Identifier.schema("message").optional(),
|
|
1321
|
+
sessionID: Identifier.schema("session"),
|
|
1322
|
+
agent: z.string().optional(),
|
|
1323
|
+
model: z.string().optional(),
|
|
1324
|
+
arguments: z.string(),
|
|
1325
|
+
command: z.string(),
|
|
1326
|
+
})
|
|
1327
|
+
export type CommandInput = z.infer<typeof CommandInput>
|
|
1328
|
+
const bashRegex = /!`([^`]+)`/g
|
|
1329
|
+
const argsRegex = /(?:[^\s"']+|"[^"]*"|'[^']*')+/g
|
|
1330
|
+
const placeholderRegex = /\$(\d+)/g
|
|
1331
|
+
const quoteTrimRegex = /^["']|["']$/g
|
|
1332
|
+
/**
|
|
1333
|
+
* Regular expression to match @ file references in text
|
|
1334
|
+
* Matches @ followed by file paths, excluding commas, periods at end of sentences, and backticks
|
|
1335
|
+
* Does not match when preceded by word characters or backticks (to avoid email addresses and quoted references)
|
|
1336
|
+
*/
|
|
1337
|
+
|
|
1338
|
+
export async function command(input: CommandInput) {
|
|
1339
|
+
log.info("command", input)
|
|
1340
|
+
const command = await Command.get(input.command)
|
|
1341
|
+
const agentName = command.agent ?? input.agent ?? (await Agent.defaultAgent())
|
|
1342
|
+
|
|
1343
|
+
const raw = input.arguments.match(argsRegex) ?? []
|
|
1344
|
+
const args = raw.map((arg) => arg.replace(quoteTrimRegex, ""))
|
|
1345
|
+
|
|
1346
|
+
const placeholders = command.template.match(placeholderRegex) ?? []
|
|
1347
|
+
let last = 0
|
|
1348
|
+
for (const item of placeholders) {
|
|
1349
|
+
const value = Number(item.slice(1))
|
|
1350
|
+
if (value > last) last = value
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
// Let the final placeholder swallow any extra arguments so prompts read naturally
|
|
1354
|
+
const withArgs = command.template.replaceAll(placeholderRegex, (_, index) => {
|
|
1355
|
+
const position = Number(index)
|
|
1356
|
+
const argIndex = position - 1
|
|
1357
|
+
if (argIndex >= args.length) return ""
|
|
1358
|
+
if (position === last) return args.slice(argIndex).join(" ")
|
|
1359
|
+
return args[argIndex]
|
|
1360
|
+
})
|
|
1361
|
+
let template = withArgs.replaceAll("$ARGUMENTS", input.arguments)
|
|
1362
|
+
|
|
1363
|
+
const shell = ConfigMarkdown.shell(template)
|
|
1364
|
+
if (shell.length > 0) {
|
|
1365
|
+
const results = await Promise.all(
|
|
1366
|
+
shell.map(async ([, cmd]) => {
|
|
1367
|
+
try {
|
|
1368
|
+
return await $`${{ raw: cmd }}`.quiet().nothrow().text()
|
|
1369
|
+
} catch (error) {
|
|
1370
|
+
return `Error executing command: ${error instanceof Error ? error.message : String(error)}`
|
|
1371
|
+
}
|
|
1372
|
+
}),
|
|
1373
|
+
)
|
|
1374
|
+
let index = 0
|
|
1375
|
+
template = template.replace(bashRegex, () => results[index++])
|
|
1376
|
+
}
|
|
1377
|
+
template = template.trim()
|
|
1378
|
+
|
|
1379
|
+
const model = await (async () => {
|
|
1380
|
+
if (command.model) {
|
|
1381
|
+
return Provider.parseModel(command.model)
|
|
1382
|
+
}
|
|
1383
|
+
if (command.agent) {
|
|
1384
|
+
const cmdAgent = await Agent.get(command.agent)
|
|
1385
|
+
if (cmdAgent.model) {
|
|
1386
|
+
return cmdAgent.model
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
if (input.model) return Provider.parseModel(input.model)
|
|
1390
|
+
return await lastModel(input.sessionID)
|
|
1391
|
+
})()
|
|
1392
|
+
|
|
1393
|
+
try {
|
|
1394
|
+
await Provider.getModel(model.providerID, model.modelID)
|
|
1395
|
+
} catch (e) {
|
|
1396
|
+
if (Provider.ModelNotFoundError.isInstance(e)) {
|
|
1397
|
+
const { providerID, modelID, suggestions } = e.data
|
|
1398
|
+
const hint = suggestions?.length ? ` Did you mean: ${suggestions.join(", ")}?` : ""
|
|
1399
|
+
Bus.publish(Session.Event.Error, {
|
|
1400
|
+
sessionID: input.sessionID,
|
|
1401
|
+
error: new NamedError.Unknown({ message: `Model not found: ${providerID}/${modelID}.${hint}` }).toObject(),
|
|
1402
|
+
})
|
|
1403
|
+
}
|
|
1404
|
+
throw e
|
|
1405
|
+
}
|
|
1406
|
+
const agent = await Agent.get(agentName)
|
|
1407
|
+
|
|
1408
|
+
const parts =
|
|
1409
|
+
(agent.mode === "subagent" && command.subtask !== false) || command.subtask === true
|
|
1410
|
+
? [
|
|
1411
|
+
{
|
|
1412
|
+
type: "subtask" as const,
|
|
1413
|
+
agent: agent.name,
|
|
1414
|
+
description: command.description ?? "",
|
|
1415
|
+
command: input.command,
|
|
1416
|
+
// TODO: how can we make task tool accept a more complex input?
|
|
1417
|
+
prompt: await resolvePromptParts(template).then((x) => x.find((y) => y.type === "text")?.text ?? ""),
|
|
1418
|
+
},
|
|
1419
|
+
]
|
|
1420
|
+
: await resolvePromptParts(template)
|
|
1421
|
+
|
|
1422
|
+
const result = (await prompt({
|
|
1423
|
+
sessionID: input.sessionID,
|
|
1424
|
+
messageID: input.messageID,
|
|
1425
|
+
model,
|
|
1426
|
+
agent: agentName,
|
|
1427
|
+
parts,
|
|
1428
|
+
})) as MessageV2.WithParts
|
|
1429
|
+
|
|
1430
|
+
Bus.publish(Command.Event.Executed, {
|
|
1431
|
+
name: input.command,
|
|
1432
|
+
sessionID: input.sessionID,
|
|
1433
|
+
arguments: input.arguments,
|
|
1434
|
+
messageID: result.info.id,
|
|
1435
|
+
})
|
|
1436
|
+
|
|
1437
|
+
return result
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
async function ensureTitle(input: {
|
|
1441
|
+
session: Session.Info
|
|
1442
|
+
message: MessageV2.WithParts
|
|
1443
|
+
history: MessageV2.WithParts[]
|
|
1444
|
+
providerID: string
|
|
1445
|
+
modelID: string
|
|
1446
|
+
}) {
|
|
1447
|
+
if (input.session.parentID) return
|
|
1448
|
+
if (!Session.isDefaultTitle(input.session.title)) return
|
|
1449
|
+
const isFirst =
|
|
1450
|
+
input.history.filter((m) => m.info.role === "user" && !m.parts.every((p) => "synthetic" in p && p.synthetic))
|
|
1451
|
+
.length === 1
|
|
1452
|
+
if (!isFirst) return
|
|
1453
|
+
const agent = await Agent.get("title")
|
|
1454
|
+
if (!agent) return
|
|
1455
|
+
const result = await LLM.stream({
|
|
1456
|
+
agent,
|
|
1457
|
+
user: input.message.info as MessageV2.User,
|
|
1458
|
+
system: [],
|
|
1459
|
+
small: true,
|
|
1460
|
+
tools: {},
|
|
1461
|
+
model: await iife(async () => {
|
|
1462
|
+
if (agent.model) return await Provider.getModel(agent.model.providerID, agent.model.modelID)
|
|
1463
|
+
return (
|
|
1464
|
+
(await Provider.getSmallModel(input.providerID)) ?? (await Provider.getModel(input.providerID, input.modelID))
|
|
1465
|
+
)
|
|
1466
|
+
}),
|
|
1467
|
+
abort: new AbortController().signal,
|
|
1468
|
+
sessionID: input.session.id,
|
|
1469
|
+
retries: 2,
|
|
1470
|
+
messages: [
|
|
1471
|
+
{
|
|
1472
|
+
role: "user",
|
|
1473
|
+
content: "Generate a title for this conversation:\n",
|
|
1474
|
+
},
|
|
1475
|
+
...MessageV2.toModelMessage([
|
|
1476
|
+
{
|
|
1477
|
+
info: {
|
|
1478
|
+
id: Identifier.ascending("message"),
|
|
1479
|
+
role: "user",
|
|
1480
|
+
sessionID: input.session.id,
|
|
1481
|
+
time: {
|
|
1482
|
+
created: Date.now(),
|
|
1483
|
+
},
|
|
1484
|
+
agent: input.message.info.role === "user" ? input.message.info.agent : await Agent.defaultAgent(),
|
|
1485
|
+
model: {
|
|
1486
|
+
providerID: input.providerID,
|
|
1487
|
+
modelID: input.modelID,
|
|
1488
|
+
},
|
|
1489
|
+
},
|
|
1490
|
+
parts: input.message.parts,
|
|
1491
|
+
},
|
|
1492
|
+
], { sessionID: input.session.id }),
|
|
1493
|
+
],
|
|
1494
|
+
})
|
|
1495
|
+
const text = await result.text.catch((err) => log.error("failed to generate title", { error: err }))
|
|
1496
|
+
if (text)
|
|
1497
|
+
return Session.update(input.session.id, (draft) => {
|
|
1498
|
+
const cleaned = text
|
|
1499
|
+
.replace(/<think>[\s\S]*?<\/think>\s*/g, "")
|
|
1500
|
+
.split("\n")
|
|
1501
|
+
.map((line) => line.trim())
|
|
1502
|
+
.find((line) => line.length > 0)
|
|
1503
|
+
if (!cleaned) return
|
|
1504
|
+
|
|
1505
|
+
const title = cleaned.length > 100 ? cleaned.substring(0, 97) + "..." : cleaned
|
|
1506
|
+
draft.title = title
|
|
1507
|
+
})
|
|
1508
|
+
}
|
|
1509
|
+
}
|