diff --git a/.changeset/cruel-jobs-hunt.md b/.changeset/cruel-jobs-hunt.md new file mode 100644 index 000000000..aa84538dd --- /dev/null +++ b/.changeset/cruel-jobs-hunt.md @@ -0,0 +1,61 @@ +--- +"@voltagent/sandbox-daytona": patch +"@voltagent/serverless-hono": patch +"@voltagent/server-elysia": patch +"@voltagent/sandbox-e2b": patch +"@voltagent/server-core": patch +"@voltagent/server-hono": patch +"@voltagent/core": patch +--- + +feat: introduce experimental Workspace support with filesystem, sandbox execution, search indexing, and skill discovery; add global workspace defaults and optional sandbox providers (E2B/Daytona). - #1008 + +Example: + +```ts +import { Agent, Workspace, LocalSandbox, NodeFilesystemBackend } from "@voltagent/core"; + +const workspace = new Workspace({ + id: "support-workspace", + operationTimeoutMs: 30_000, + filesystem: { + backend: new NodeFilesystemBackend({ + rootDir: "./.workspace", + }), + }, + sandbox: new LocalSandbox({ + rootDir: "./.sandbox", + isolation: { provider: "detect" }, + cleanupOnDestroy: true, + }), + search: { + autoIndexPaths: ["/notes", "/tickets"], + }, + skills: { + rootPaths: ["/skills"], + }, +}); + +const agent = new Agent({ + name: "support-agent", + model, + instructions: "Use workspace tools to review tickets and summarize findings.", + workspace, + workspaceToolkits: { + filesystem: { + toolPolicies: { + tools: { write_file: { needsApproval: true } }, + }, + }, + }, +}); + +const { text } = await agent.generateText( + [ + "Scan /tickets and /notes.", + "Use workspace_search to find urgent issues from the last week.", + "Summarize the top 3 risks and include file paths as citations.", + ].join("\n"), + { maxSteps: 40 } +); +``` diff --git a/.gitignore b/.gitignore index 41cd90d48..fe0d10b5d 100644 --- a/.gitignore +++ b/.gitignore @@ -166,6 +166,8 @@ vitest.config.*.timestamp* # claude .claude skills +!packages/core/src/workspace/skills +!packages/core/src/workspace/skills/** dev-debug.log node_modules/ @@ -179,3 +181,7 @@ node_modules/ # serena .serena + + +# example skills +!examples/with-workspace/workspace/skills diff --git a/examples/README.md b/examples/README.md index ca1244ccd..1857294d7 100644 --- a/examples/README.md +++ b/examples/README.md @@ -83,6 +83,7 @@ Create a multi-agent research workflow where different AI agents collaborate to ## All Examples - [Base Starter](./base) — Minimal VoltAgent starter with a single agent, memory, and dev server. +- [Workspace](./with-workspace) — Workspace filesystem, sandbox execution, search, and skills. - [Summarization](./with-summarization) — Agent summarization with a low trigger window for easy testing. - [Retries and Fallbacks](./with-retries-fallback) — Model fallback list with per-model retries and agent-level defaults. - [Middleware](./with-middleware) — Input/output middleware with retry feedback. diff --git a/examples/with-workspace/.env.example b/examples/with-workspace/.env.example new file mode 100644 index 000000000..121e76c45 --- /dev/null +++ b/examples/with-workspace/.env.example @@ -0,0 +1 @@ +OPENAI_API_KEY=your_openai_api_key_here \ No newline at end of file diff --git a/examples/with-workspace/.gitignore b/examples/with-workspace/.gitignore new file mode 100644 index 000000000..0ca39c007 --- /dev/null +++ b/examples/with-workspace/.gitignore @@ -0,0 +1,3 @@ +node_modules +dist +.DS_Store diff --git a/examples/with-workspace/README.md b/examples/with-workspace/README.md new file mode 100644 index 000000000..23201665f --- /dev/null +++ b/examples/with-workspace/README.md @@ -0,0 +1,61 @@ +
+ +435380213-b6253409-8741-462b-a346-834cd18565a9 + + +
+
+ +
+ Home Page | + Documentation | + Examples | + Discord | + Blog +
+
+ +
+ +
+ VoltAgent is an open source TypeScript framework for building and orchestrating AI agents.
+Escape the limitations of no-code builders and the complexity of starting from scratch. +
+
+
+ +
+ +[![npm version](https://img.shields.io/npm/v/@voltagent/core.svg)](https://www.npmjs.com/package/@voltagent/core) +[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](CODE_OF_CONDUCT.md) +[![Discord](https://img.shields.io/discord/1361559153780195478.svg?label=&logo=discord&logoColor=ffffff&color=7389D8&labelColor=6A7EC2)](https://s.voltagent.dev/discord) +[![Twitter Follow](https://img.shields.io/twitter/follow/voltagent_dev?style=social)](https://twitter.com/voltagent_dev) + +
+ +
+ +
+ +VoltAgent Schema + + +
+ +## VoltAgent: Workspace Example + +This example shows how to attach a Workspace to an agent, giving it a persistent filesystem, sandboxed command execution, file search (BM25 + vector), and reusable skills loaded from `SKILL.md` files. + +## Try Example + +```bash +npm create voltagent-app@latest -- --example with-workspace +``` + +## Highlights + +- Workspace filesystem rooted at `./workspace` +- Sandbox execution with `execute_command` +- Workspace search via `workspace_index` and `workspace_search` +- Skills loaded from `/skills` with `workspace_list_skills` and `workspace_read_skill` +- Filesystem extras: `stat`, `mkdir`, and `list_tree` diff --git a/examples/with-workspace/package.json b/examples/with-workspace/package.json new file mode 100644 index 000000000..422e10a9a --- /dev/null +++ b/examples/with-workspace/package.json @@ -0,0 +1,38 @@ +{ + "name": "voltagent-example-with-workspace", + "author": "", + "dependencies": { + "@ai-sdk/openai": "^3.0.0", + "@voltagent/cli": "^0.1.21", + "@voltagent/core": "^2.3.3", + "@voltagent/libsql": "^2.1.0", + "@voltagent/logger": "^2.0.2", + "@voltagent/server-hono": "^2.0.4", + "ai": "^6.0.0", + "zod": "^3.25.76" + }, + "devDependencies": { + "@types/node": "^24.2.1", + "tsx": "^4.19.3", + "typescript": "^5.8.2" + }, + "keywords": [ + "agent", + "ai", + "voltagent" + ], + "license": "MIT", + "private": true, + "repository": { + "type": "git", + "url": "https://github.com/VoltAgent/voltagent.git", + "directory": "examples/with-workspace" + }, + "scripts": { + "build": "tsc", + "dev": "tsx watch --env-file=.env ./src", + "start": "node dist/index.js", + "volt": "volt" + }, + "type": "module" +} diff --git a/examples/with-workspace/src/index.ts b/examples/with-workspace/src/index.ts new file mode 100644 index 000000000..287d1d0d2 --- /dev/null +++ b/examples/with-workspace/src/index.ts @@ -0,0 +1,83 @@ +import path from "node:path"; +import { + Agent, + InMemoryVectorAdapter, + LocalSandbox, + Memory, + NodeFilesystemBackend, + VoltAgent, + Workspace, +} from "@voltagent/core"; +import { LibSQLMemoryAdapter, LibSQLVectorAdapter } from "@voltagent/libsql"; +import { createPinoLogger } from "@voltagent/logger"; +import { honoServer } from "@voltagent/server-hono"; + +// Create logger +const logger = createPinoLogger({ + name: "with-workspace", + level: "info", +}); + +// Create Memory instance with vector support for semantic search and working memory +const memory = new Memory({ + storage: new LibSQLMemoryAdapter(), + embedding: "openai/text-embedding-3-small", + vector: new LibSQLVectorAdapter(), + generateTitle: true, +}); + +const workspaceRoot = path.resolve(process.cwd(), "workspace"); + +const workspace = new Workspace({ + id: "workspace-example", + name: "Workspace Example", + filesystem: { + backend: new NodeFilesystemBackend({ + rootDir: workspaceRoot, + virtualMode: true, + }), + }, + sandbox: new LocalSandbox({ + rootDir: workspaceRoot, + }), + search: { + autoIndexPaths: [{ path: "/", glob: "**/*.{md,txt,csv}" }], + embedding: "openai/text-embedding-3-small", + vector: new InMemoryVectorAdapter(), + }, + skills: { + rootPaths: ["/skills"], + }, +}); + +const skillsHook = workspace.createSkillsPromptHook({ + includeAvailable: true, + includeActivated: true, +}); + +const agent = new Agent({ + name: "Workspace Agent", + instructions: [ + "You are a helpful assistant.", + "Use the workspace filesystem for notes under /notes and data under /data.", + "Use workspace_search to find relevant files before answering.", + "Skills live under /skills; activate them when a task matches the description.", + ].join(" "), + model: "openai/gpt-4o-mini", + memory, + workspace, + hooks: skillsHook, + workspaceToolkits: { + filesystem: { + toolPolicies: { + tools: { write_file: { needsApproval: true } }, + }, + }, + }, +}); + +new VoltAgent({ + agents: { agent }, + server: honoServer(), + logger, +}); diff --git a/examples/with-workspace/tsconfig.json b/examples/with-workspace/tsconfig.json new file mode 100644 index 000000000..cee90c6f3 --- /dev/null +++ b/examples/with-workspace/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "strict": true, + "outDir": "dist", + "skipLibCheck": true + }, + "include": ["src"], + "exclude": ["node_modules", "dist"] +} diff --git a/examples/with-workspace/workspace/data/customers.csv b/examples/with-workspace/workspace/data/customers.csv new file mode 100644 index 000000000..8efe17681 --- /dev/null +++ b/examples/with-workspace/workspace/data/customers.csv @@ -0,0 +1,6 @@ +customer_id,segment,mrr,region,plan +C-001,mid-market,1200,NA,Pro +C-002,enterprise,9000,EU,Enterprise +C-003,smb,300,NA,Starter +C-004,mid-market,1800,APAC,Pro +C-005,enterprise,15000,NA,Enterprise diff --git a/examples/with-workspace/workspace/notes/meeting-notes.md b/examples/with-workspace/workspace/notes/meeting-notes.md new file mode 100644 index 000000000..f6c92c96c --- /dev/null +++ b/examples/with-workspace/workspace/notes/meeting-notes.md @@ -0,0 +1,6 @@ +# Meeting Notes (2026-02-01) + +- Prioritize CSV import for accounts, contacts, and deals. +- Add summary dashboard with KPIs: MRR, churn, new logos. +- Keep UI minimal for beta: timeline + tasks + pipeline. +- Use feature flags for beta customers. diff --git a/examples/with-workspace/workspace/notes/project-brief.md b/examples/with-workspace/workspace/notes/project-brief.md new file mode 100644 index 000000000..5564a6794 --- /dev/null +++ b/examples/with-workspace/workspace/notes/project-brief.md @@ -0,0 +1,10 @@ +# Project Brief: Atlas CRM + +Owner: Acme Sales Ops +Goal: unify customer notes, tasks, and pipeline in one dashboard. +Constraints: ship MVP by 2026-03-15, keep infra simple (Postgres + Next.js). +Open questions: + +- Import path from legacy CSVs +- Define role-based permissions +- Decide on weekly KPI report format diff --git a/examples/with-workspace/workspace/skills/data-analysis/SKILL.md b/examples/with-workspace/workspace/skills/data-analysis/SKILL.md new file mode 100644 index 000000000..1f6085466 --- /dev/null +++ b/examples/with-workspace/workspace/skills/data-analysis/SKILL.md @@ -0,0 +1,19 @@ +--- +name: Workspace Data Analyst +description: Analyze CSV files in the workspace and summarize insights. +version: "1.0.0" +tags: + - data + - csv + - analysis +references: + - references/schema.md +assets: + - assets/sample.csv +--- + +When analyzing CSV data: + +1. Load the file and inspect headers. +2. Summarize totals, averages, and outliers. +3. Provide a short insight summary and recommended next steps. diff --git a/examples/with-workspace/workspace/skills/data-analysis/assets/sample.csv b/examples/with-workspace/workspace/skills/data-analysis/assets/sample.csv new file mode 100644 index 000000000..eaffb5ef7 --- /dev/null +++ b/examples/with-workspace/workspace/skills/data-analysis/assets/sample.csv @@ -0,0 +1,6 @@ +customer_id,segment,mrr,region,plan +S-100,smb,220,NA,Starter +S-101,mid-market,1400,EU,Pro +S-102,enterprise,12000,NA,Enterprise +S-103,mid-market,2100,APAC,Pro +S-104,smb,180,EU,Starter diff --git a/examples/with-workspace/workspace/skills/data-analysis/references/schema.md b/examples/with-workspace/workspace/skills/data-analysis/references/schema.md new file mode 100644 index 000000000..af6ad43d9 --- /dev/null +++ b/examples/with-workspace/workspace/skills/data-analysis/references/schema.md @@ -0,0 +1,9 @@ +# CSV Schema + +Expected columns: + +- customer_id: unique identifier +- segment: smb | mid-market | enterprise +- mrr: monthly recurring revenue (number) +- region: NA | EU | APAC +- plan: Starter | Pro | Enterprise diff --git a/packages/core/src/agent/agent.ts b/packages/core/src/agent/agent.ts index 86ec0a7dc..3170ca350 100644 --- a/packages/core/src/agent/agent.ts +++ b/packages/core/src/agent/agent.ts @@ -87,6 +87,7 @@ import type { Voice } from "../voice"; import { VoltOpsClient as VoltOpsClientClass } from "../voltops/client"; import type { VoltOpsClient } from "../voltops/client"; import type { PromptContent, PromptHelper } from "../voltops/types"; +import { Workspace } from "../workspace"; import { buildToolErrorResult } from "./error-utils"; import { ToolDeniedError, @@ -275,6 +276,60 @@ const filterResponseMessages = (messages: unknown): ModelMessage[] | undefined = return filtered.length > 0 ? filtered : undefined; }; +const resolveWorkspace = (workspace: AgentOptions["workspace"]): Workspace | undefined => { + if (!workspace) { + return undefined; + } + + if (workspace instanceof Workspace) { + return workspace; + } + + return new Workspace(workspace); +}; + +const buildWorkspaceToolkits = ( + workspace: Workspace | undefined, + options: AgentOptions["workspaceToolkits"], +): Toolkit[] => { + if (!workspace || options === false) { + return []; + } + + const includeDefaults = options === undefined; + const toolkits: Toolkit[] = []; + + const filesystemOptions = includeDefaults ? {} : options?.filesystem; + if (includeDefaults || filesystemOptions !== undefined) { + if (filesystemOptions !== false) { + toolkits.push(workspace.createFilesystemToolkit(filesystemOptions || {})); + } + } + + const sandboxOptions = includeDefaults ? {} : options?.sandbox; + if (includeDefaults || sandboxOptions !== undefined) { + if (sandboxOptions !== false) { + toolkits.push(workspace.createSandboxToolkit(sandboxOptions || {})); + } + } + + const searchOptions = includeDefaults ? {} : options?.search; + if (includeDefaults || searchOptions !== undefined) { + if (searchOptions !== false) { + toolkits.push(workspace.createSearchToolkit(searchOptions || {})); + } + } + + const skillsOptions = includeDefaults ? {} : options?.skills; + if (includeDefaults || skillsOptions !== undefined) { + if (skillsOptions !== false) { + toolkits.push(workspace.createSkillsToolkit(skillsOptions || {})); + } + } + + return toolkits; +}; + const searchToolsParameters = z.object({ query: z.string().describe("User request or query to search tools for."), topK: z.number().int().positive().optional().describe("Maximum number of tools to return."), @@ -533,7 +588,8 @@ function isAsyncIterable(value: unknown): value is AsyncIterable { * Base options for all generation methods * Extends AI SDK's CallSettings for full compatibility */ -export interface BaseGenerationOptions extends Partial { +export interface BaseGenerationOptions + extends Partial { // === VoltAgent Specific === // Context userId?: string; @@ -589,7 +645,7 @@ export interface BaseGenerationOptions extends Partial { maxMiddlewareRetries?: number; // Provider-specific options - providerOptions?: ProviderOptions; + providerOptions?: TProviderOptions; // Structured output (for schema-guided generation) output?: OutputSpec; @@ -610,24 +666,27 @@ export interface BaseGenerationOptions extends Partial { toolChoice?: ToolChoice>; } -export type GenerateTextOptions = Omit< - BaseGenerationOptions, - "output" -> & { +export type GenerateTextOptions< + OUTPUT extends OutputSpec = OutputSpec, + TProviderOptions extends ProviderOptions = ProviderOptions, +> = Omit, "output"> & { output?: OUTPUT; }; -export type StreamTextOptions = BaseGenerationOptions & { - onFinish?: (result: any) => void | Promise; - /** - * When true, avoids wiring the HTTP abort signal into the stream so clients can resume later. - * Use with a resumable stream store to prevent orphaned streams. - */ - resumableStream?: boolean; -}; -export type GenerateObjectOptions = BaseGenerationOptions; -export type StreamObjectOptions = BaseGenerationOptions & { - onFinish?: (result: any) => void | Promise; -}; +export type StreamTextOptions = + BaseGenerationOptions & { + onFinish?: (result: any) => void | Promise; + /** + * When true, avoids wiring the HTTP abort signal into the stream so clients can resume later. + * Use with a resumable stream store to prevent orphaned streams. + */ + resumableStream?: boolean; + }; +export type GenerateObjectOptions = + BaseGenerationOptions; +export type StreamObjectOptions = + BaseGenerationOptions & { + onFinish?: (result: any) => void | Promise; + }; // ============================================================================ // Agent Implementation @@ -658,6 +717,7 @@ export class Agent { private readonly memory?: Memory | false; private readonly memoryConfigured: boolean; private readonly summarization?: AgentSummarizationOptions | false; + private readonly workspace?: Workspace; private defaultObservability?: VoltAgentObservability; private readonly toolManager: ToolManager; private readonly toolPoolManager: ToolManager; @@ -690,7 +750,11 @@ export class Agent { this.hooks = options.hooks || {}; this.temperature = options.temperature; this.maxOutputTokens = options.maxOutputTokens; - this.maxSteps = options.maxSteps || 5; + const globalWorkspace = AgentRegistry.getInstance().getGlobalWorkspace(); + const workspaceOption = options.workspace === undefined ? globalWorkspace : options.workspace; + this.workspace = resolveWorkspace(workspaceOption); + const defaultMaxSteps = this.workspace ? 100 : 5; + this.maxSteps = options.maxSteps ?? defaultMaxSteps; this.maxRetries = options.maxRetries ?? DEFAULT_LLM_MAX_RETRIES; this.stopWhen = options.stopWhen; this.markdown = options.markdown ?? false; @@ -735,6 +799,7 @@ export class Agent { this.memoryConfigured = options.memory !== undefined; this.memory = options.memory; this.summarization = options.summarization; + // workspace resolved above to set default maxSteps // Initialize memory manager const resolvedMemory = this.memoryConfigured @@ -751,12 +816,17 @@ export class Agent { titleGenerator, ); + const workspaceToolkits = buildWorkspaceToolkits(this.workspace, options.workspaceToolkits); + // Initialize tool manager with static tools const staticTools = typeof options.tools === "function" ? [] : options.tools; this.toolManager = new ToolManager(staticTools, this.logger); if (options.toolkits) { this.toolManager.addItems(options.toolkits); } + if (workspaceToolkits.length > 0) { + this.toolManager.addItems(workspaceToolkits); + } this.toolPoolManager = new ToolManager([], this.logger); this.applyToolRoutingConfig(this.toolRouting); @@ -778,9 +848,12 @@ export class Agent { /** * Generate text response */ - async generateText( + async generateText< + OUTPUT extends OutputSpec = OutputSpec, + TProviderOptions extends ProviderOptions = ProviderOptions, + >( input: string | UIMessage[] | BaseMessage[], - options?: GenerateTextOptions, + options?: GenerateTextOptions, ): Promise> { const startTime = Date.now(); const oc = this.createOperationContext(input, options); @@ -1250,9 +1323,9 @@ export class Agent { /** * Stream text response */ - async streamText( + async streamText( input: string | UIMessage[] | BaseMessage[], - options?: StreamTextOptions, + options?: StreamTextOptions, ): Promise { const startTime = Date.now(); const oc = this.createOperationContext(input, options); @@ -2212,10 +2285,13 @@ export class Agent { * Generate structured object * @deprecated — Use generateText with an output setting instead. */ - async generateObject( + async generateObject< + T extends z.ZodType, + TProviderOptions extends ProviderOptions = ProviderOptions, + >( input: string | UIMessage[] | BaseMessage[], schema: T, - options?: GenerateObjectOptions, + options?: GenerateObjectOptions, ): Promise>> { const startTime = Date.now(); const oc = this.createOperationContext(input, options); @@ -2533,10 +2609,13 @@ export class Agent { * Stream structured object * @deprecated — Use streamText with an output setting instead. */ - async streamObject( + async streamObject< + T extends z.ZodType, + TProviderOptions extends ProviderOptions = ProviderOptions, + >( input: string | UIMessage[] | BaseMessage[], schema: T, - options?: StreamObjectOptions, + options?: StreamObjectOptions, ): Promise>> { const startTime = Date.now(); const oc = this.createOperationContext(input, options); @@ -6826,6 +6905,13 @@ export class Agent { return this.toolManager; } + /** + * Get Workspace instance if configured + */ + public getWorkspace(): Workspace | undefined { + return this.workspace; + } + /** * Get Memory instance if available */ diff --git a/packages/core/src/agent/types.ts b/packages/core/src/agent/types.ts index 57fc58aa3..2db170443 100644 --- a/packages/core/src/agent/types.ts +++ b/packages/core/src/agent/types.ts @@ -41,6 +41,14 @@ import type { VoltOpsFeedbackCreateInput, VoltOpsFeedbackExpiresIn, } from "../voltops/types"; +import type { + Workspace, + WorkspaceConfig, + WorkspaceFilesystemToolkitOptions, + WorkspaceSandboxToolkitOptions, + WorkspaceSearchToolkitOptions, + WorkspaceSkillsToolkitOptions, +} from "../workspace"; import type { ContextInput } from "./agent"; import type { AgentHooks } from "./hooks"; import type { AgentTraceContext } from "./open-telemetry/trace-context"; @@ -89,6 +97,13 @@ export type ToolWithNodeId = (BaseTool | ProviderTool) & { node_id: string; }; +export type WorkspaceToolkitOptions = { + filesystem?: WorkspaceFilesystemToolkitOptions | false; + sandbox?: WorkspaceSandboxToolkitOptions | false; + search?: WorkspaceSearchToolkitOptions | false; + skills?: WorkspaceSkillsToolkitOptions | false; +}; + export interface AgentScorerState { key: string; id: string; @@ -576,6 +591,8 @@ export type AgentOptions = { tools?: (Tool | Toolkit | VercelTool)[] | DynamicValue<(Tool | Toolkit)[]>; toolkits?: Toolkit[]; toolRouting?: ToolRoutingConfig | false; + workspace?: Workspace | WorkspaceConfig | false; + workspaceToolkits?: WorkspaceToolkitOptions | false; memory?: Memory | false; summarization?: AgentSummarizationOptions | false; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 1a7591f2e..b6c55802a 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -51,6 +51,7 @@ export { type StreamObjectResultWithContext, } from "./agent/agent"; export * from "./planagent"; +export * from "./workspace"; export * from "./agent/hooks"; export { createSubagent } from "./agent/subagent/types"; export type { @@ -180,6 +181,7 @@ export type { AgentModelValue, AgentFeedbackOptions, AgentFeedbackMetadata, + WorkspaceToolkitOptions, AgentResponse, AgentFullState, ApiToolInfo, diff --git a/packages/core/src/observability/types.ts b/packages/core/src/observability/types.ts index bf4387789..0f6ea9d35 100644 --- a/packages/core/src/observability/types.ts +++ b/packages/core/src/observability/types.ts @@ -166,6 +166,29 @@ export interface SpanAttributes { // Tool-specific attributes "tool.name"?: string; + // Workspace attributes + "workspace.id"?: string; + "workspace.name"?: string; + "workspace.scope"?: "agent" | "conversation"; + "workspace.operation"?: string; + "workspace.fs.path"?: string; + "workspace.fs.pattern"?: string; + "workspace.fs.bytes"?: number; + "workspace.fs.offset"?: number; + "workspace.fs.limit"?: number; + "workspace.fs.occurrences"?: number; + "workspace.search.query"?: string; + "workspace.search.mode"?: string; + "workspace.search.top_k"?: number; + "workspace.search.results"?: number; + "workspace.sandbox.command"?: string; + "workspace.sandbox.args"?: string[] | string; + "workspace.sandbox.cwd"?: string; + "workspace.sandbox.timeout_ms"?: number; + "workspace.sandbox.exit_code"?: number; + "workspace.skills.name"?: string; + "workspace.skills.source"?: string; + // Common attributes "user.id"?: string; "conversation.id"?: string; diff --git a/packages/core/src/planagent/filesystem/backends/backend.ts b/packages/core/src/planagent/filesystem/backends/backend.ts index 93b3b1be9..61528bebb 100644 --- a/packages/core/src/planagent/filesystem/backends/backend.ts +++ b/packages/core/src/planagent/filesystem/backends/backend.ts @@ -1,64 +1 @@ -import type { Agent } from "../../../agent/agent"; -import type { OperationContext } from "../../../agent/types"; -import type { PlanAgentFileData } from "../../types"; - -export type MaybePromise = T | Promise; - -export interface FileInfo { - path: string; - is_dir?: boolean; - size?: number; - modified_at?: string; -} - -export interface GrepMatch { - path: string; - line: number; - text: string; -} - -export type FileData = PlanAgentFileData; - -export interface WriteResult { - error?: string; - path?: string; - filesUpdate?: Record | null; - metadata?: Record; -} - -export interface EditResult { - error?: string; - path?: string; - filesUpdate?: Record | null; - occurrences?: number; - metadata?: Record; -} - -export interface FilesystemBackend { - lsInfo(path: string): MaybePromise; - read(filePath: string, offset?: number, limit?: number): MaybePromise; - readRaw(filePath: string): MaybePromise; - grepRaw( - pattern: string, - path?: string | null, - glob?: string | null, - ): MaybePromise; - globInfo(pattern: string, path?: string): MaybePromise; - write(filePath: string, content: string): MaybePromise; - edit( - filePath: string, - oldString: string, - newString: string, - replaceAll?: boolean, - ): MaybePromise; -} - -export type FilesystemBackendContext = { - agent: Agent; - operationContext: OperationContext; - state: { - files?: Record; - }; -}; - -export type FilesystemBackendFactory = (context: FilesystemBackendContext) => FilesystemBackend; +export * from "../../../workspace/filesystem/backends/backend"; diff --git a/packages/core/src/planagent/filesystem/backends/composite.ts b/packages/core/src/planagent/filesystem/backends/composite.ts index 22c719fd9..816d7b594 100644 --- a/packages/core/src/planagent/filesystem/backends/composite.ts +++ b/packages/core/src/planagent/filesystem/backends/composite.ts @@ -1,173 +1 @@ -import type { - EditResult, - FileData, - FileInfo, - FilesystemBackend, - GrepMatch, - WriteResult, -} from "./backend"; - -export class CompositeFilesystemBackend implements FilesystemBackend { - private defaultBackend: FilesystemBackend; - private routes: Record; - private sortedRoutes: Array<[string, FilesystemBackend]>; - - constructor(defaultBackend: FilesystemBackend, routes: Record) { - this.defaultBackend = defaultBackend; - this.routes = routes; - - this.sortedRoutes = Object.entries(routes).sort((a, b) => b[0].length - a[0].length); - } - - private getBackendAndKey(key: string): [FilesystemBackend, string] { - for (const [prefix, backend] of this.sortedRoutes) { - if (key.startsWith(prefix)) { - const suffix = key.substring(prefix.length); - const strippedKey = suffix ? `/${suffix}` : "/"; - return [backend, strippedKey]; - } - } - - return [this.defaultBackend, key]; - } - - async lsInfo(path: string): Promise { - for (const [routePrefix, backend] of this.sortedRoutes) { - if (path.startsWith(routePrefix.replace(/\/$/, ""))) { - const suffix = path.substring(routePrefix.length); - const searchPath = suffix ? `/${suffix}` : "/"; - const infos = await backend.lsInfo(searchPath); - - return infos.map((info) => ({ - ...info, - path: routePrefix.slice(0, -1) + info.path, - })); - } - } - - if (path === "/") { - const results: FileInfo[] = []; - const defaultInfos = await this.defaultBackend.lsInfo(path); - results.push(...defaultInfos); - - for (const [routePrefix] of this.sortedRoutes) { - results.push({ - path: routePrefix, - is_dir: true, - size: 0, - modified_at: "", - }); - } - - results.sort((a, b) => a.path.localeCompare(b.path)); - return results; - } - - return await this.defaultBackend.lsInfo(path); - } - - async read(filePath: string, offset = 0, limit = 2000): Promise { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.read(strippedKey, offset, limit); - } - - async readRaw(filePath: string): Promise { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.readRaw(strippedKey); - } - - async grepRaw( - pattern: string, - path = "/", - glob: string | null = null, - ): Promise { - for (const [routePrefix, backend] of this.sortedRoutes) { - if (path.startsWith(routePrefix.replace(/\/$/, ""))) { - const searchPath = path.substring(routePrefix.length - 1); - const raw = await backend.grepRaw(pattern, searchPath || "/", glob); - - if (typeof raw === "string") { - return raw; - } - - return raw.map((match) => ({ - ...match, - path: routePrefix.slice(0, -1) + match.path, - })); - } - } - - const allMatches: GrepMatch[] = []; - const rawDefault = await this.defaultBackend.grepRaw(pattern, path, glob); - - if (typeof rawDefault === "string") { - return rawDefault; - } - - allMatches.push(...rawDefault); - - for (const [routePrefix, backend] of Object.entries(this.routes)) { - const raw = await backend.grepRaw(pattern, "/", glob); - - if (typeof raw === "string") { - return raw; - } - - allMatches.push( - ...raw.map((match) => ({ - ...match, - path: routePrefix.slice(0, -1) + match.path, - })), - ); - } - - return allMatches; - } - - async globInfo(pattern: string, path = "/"): Promise { - const results: FileInfo[] = []; - - for (const [routePrefix, backend] of this.sortedRoutes) { - if (path.startsWith(routePrefix.replace(/\/$/, ""))) { - const searchPath = path.substring(routePrefix.length - 1); - const infos = await backend.globInfo(pattern, searchPath || "/"); - - return infos.map((info) => ({ - ...info, - path: routePrefix.slice(0, -1) + info.path, - })); - } - } - - const defaultInfos = await this.defaultBackend.globInfo(pattern, path); - results.push(...defaultInfos); - - for (const [routePrefix, backend] of Object.entries(this.routes)) { - const infos = await backend.globInfo(pattern, "/"); - results.push( - ...infos.map((info) => ({ - ...info, - path: routePrefix.slice(0, -1) + info.path, - })), - ); - } - - results.sort((a, b) => a.path.localeCompare(b.path)); - return results; - } - - async write(filePath: string, content: string): Promise { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.write(strippedKey, content); - } - - async edit( - filePath: string, - oldString: string, - newString: string, - replaceAll = false, - ): Promise { - const [backend, strippedKey] = this.getBackendAndKey(filePath); - return await backend.edit(strippedKey, oldString, newString, replaceAll); - } -} +export * from "../../../workspace/filesystem/backends/composite"; diff --git a/packages/core/src/planagent/filesystem/backends/filesystem.ts b/packages/core/src/planagent/filesystem/backends/filesystem.ts index b7390f731..c02842357 100644 --- a/packages/core/src/planagent/filesystem/backends/filesystem.ts +++ b/packages/core/src/planagent/filesystem/backends/filesystem.ts @@ -1,607 +1 @@ -import { spawn } from "node:child_process"; -import * as fsSync from "node:fs"; -import * as fs from "node:fs/promises"; -import * as path from "node:path"; -import micromatch from "micromatch"; -import { - checkEmptyContent, - formatContentWithLineNumbers, - performStringReplacement, -} from "../utils"; -import type { - EditResult, - FileData, - FileInfo, - FilesystemBackend as FilesystemBackendProtocol, - GrepMatch, - WriteResult, -} from "./backend"; - -const SUPPORTS_NOFOLLOW = fsSync.constants.O_NOFOLLOW !== undefined; -type FastGlobFn = typeof import("fast-glob"); -let fastGlobPromise: Promise | undefined; - -async function loadFastGlob(): Promise { - if (!fastGlobPromise) { - fastGlobPromise = import("fast-glob").then((mod) => { - const resolved = - (mod as unknown as { default?: FastGlobFn }).default ?? (mod as unknown as FastGlobFn); - return resolved; - }); - } - return fastGlobPromise; -} - -export class NodeFilesystemBackend implements FilesystemBackendProtocol { - private cwd: string; - private virtualMode: boolean; - private maxFileSizeBytes: number; - - constructor( - options: { - rootDir?: string; - virtualMode?: boolean; - maxFileSizeMb?: number; - } = {}, - ) { - const { rootDir, virtualMode = false, maxFileSizeMb = 10 } = options; - this.cwd = rootDir ? path.resolve(rootDir) : process.cwd(); - this.virtualMode = virtualMode; - this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024; - } - - private resolvePath(key: string): string { - if (this.virtualMode) { - const vpath = key.startsWith("/") ? key : `/${key}`; - if (vpath.includes("..") || vpath.startsWith("~")) { - throw new Error("Path traversal not allowed"); - } - const full = path.resolve(this.cwd, vpath.substring(1)); - const relative = path.relative(this.cwd, full); - if (relative.startsWith("..") || path.isAbsolute(relative)) { - throw new Error(`Path: ${full} outside root directory: ${this.cwd}`); - } - return full; - } - - if (path.isAbsolute(key)) { - return key; - } - return path.resolve(this.cwd, key); - } - - async lsInfo(dirPath: string): Promise { - try { - const resolvedPath = this.resolvePath(dirPath); - const stat = await fs.stat(resolvedPath); - - if (!stat.isDirectory()) { - return []; - } - - const entries = await fs.readdir(resolvedPath, { withFileTypes: true }); - const results: FileInfo[] = []; - - const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; - - for (const entry of entries) { - const fullPath = path.join(resolvedPath, entry.name); - - try { - const entryStat = await fs.stat(fullPath); - const isFile = entryStat.isFile(); - const isDir = entryStat.isDirectory(); - - if (!this.virtualMode) { - if (isFile) { - results.push({ - path: fullPath, - is_dir: false, - size: entryStat.size, - modified_at: entryStat.mtime.toISOString(), - }); - } else if (isDir) { - results.push({ - path: fullPath + path.sep, - is_dir: true, - size: 0, - modified_at: entryStat.mtime.toISOString(), - }); - } - } else { - let relativePath: string; - if (fullPath.startsWith(cwdStr)) { - relativePath = fullPath.substring(cwdStr.length); - } else if (fullPath.startsWith(this.cwd)) { - relativePath = fullPath.substring(this.cwd.length).replace(/^[/\\]/, ""); - } else { - relativePath = fullPath; - } - - relativePath = relativePath.split(path.sep).join("/"); - const virtPath = `/${relativePath}`; - - if (isFile) { - results.push({ - path: virtPath, - is_dir: false, - size: entryStat.size, - modified_at: entryStat.mtime.toISOString(), - }); - } else if (isDir) { - results.push({ - path: `${virtPath}/`, - is_dir: true, - size: 0, - modified_at: entryStat.mtime.toISOString(), - }); - } - } - } catch { - // ignore entry errors - } - } - - results.sort((a, b) => a.path.localeCompare(b.path)); - return results; - } catch { - return []; - } - } - - async read(filePath: string, offset = 0, limit = 2000): Promise { - try { - const resolvedPath = this.resolvePath(filePath); - - let content: string; - - if (SUPPORTS_NOFOLLOW) { - const stat = await fs.stat(resolvedPath); - if (!stat.isFile()) { - return `Error: File '${filePath}' not found`; - } - const fd = await fs.open( - resolvedPath, - fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW, - ); - try { - content = await fd.readFile({ encoding: "utf-8" }); - } finally { - await fd.close(); - } - } else { - const stat = await fs.lstat(resolvedPath); - if (stat.isSymbolicLink()) { - return `Error: Symlinks are not allowed: ${filePath}`; - } - if (!stat.isFile()) { - return `Error: File '${filePath}' not found`; - } - content = await fs.readFile(resolvedPath, "utf-8"); - } - - const emptyMsg = checkEmptyContent(content); - if (emptyMsg) { - return emptyMsg; - } - - const lines = content.split("\n"); - const startIdx = offset; - const endIdx = Math.min(startIdx + limit, lines.length); - - if (startIdx >= lines.length) { - return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`; - } - - const selectedLines = lines.slice(startIdx, endIdx); - return formatContentWithLineNumbers(selectedLines, startIdx + 1); - } catch (e: any) { - return `Error reading file '${filePath}': ${e.message}`; - } - } - - async readRaw(filePath: string): Promise { - const resolvedPath = this.resolvePath(filePath); - - let content: string; - let stat: fsSync.Stats; - - if (SUPPORTS_NOFOLLOW) { - stat = await fs.stat(resolvedPath); - if (!stat.isFile()) throw new Error(`File '${filePath}' not found`); - const fd = await fs.open( - resolvedPath, - fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW, - ); - try { - content = await fd.readFile({ encoding: "utf-8" }); - } finally { - await fd.close(); - } - } else { - stat = await fs.lstat(resolvedPath); - if (stat.isSymbolicLink()) { - throw new Error(`Symlinks are not allowed: ${filePath}`); - } - if (!stat.isFile()) throw new Error(`File '${filePath}' not found`); - content = await fs.readFile(resolvedPath, "utf-8"); - } - - return { - content: content.split("\n"), - created_at: stat.ctime.toISOString(), - modified_at: stat.mtime.toISOString(), - }; - } - - async write(filePath: string, content: string): Promise { - try { - const resolvedPath = this.resolvePath(filePath); - - try { - const stat = await fs.lstat(resolvedPath); - if (stat.isSymbolicLink()) { - return { - error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`, - }; - } - return { - error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`, - }; - } catch { - // File does not exist - } - - await fs.mkdir(path.dirname(resolvedPath), { recursive: true }); - - if (SUPPORTS_NOFOLLOW) { - const flags = - fsSync.constants.O_WRONLY | - fsSync.constants.O_CREAT | - fsSync.constants.O_TRUNC | - fsSync.constants.O_NOFOLLOW; - - const fd = await fs.open(resolvedPath, flags, 0o644); - try { - await fd.writeFile(content, "utf-8"); - } finally { - await fd.close(); - } - } else { - await fs.writeFile(resolvedPath, content, "utf-8"); - } - - return { path: filePath, filesUpdate: null }; - } catch (e: any) { - return { error: `Error writing file '${filePath}': ${e.message}` }; - } - } - - async edit( - filePath: string, - oldString: string, - newString: string, - replaceAll = false, - ): Promise { - try { - const resolvedPath = this.resolvePath(filePath); - - let content: string; - - if (SUPPORTS_NOFOLLOW) { - const stat = await fs.stat(resolvedPath); - if (!stat.isFile()) { - return { error: `Error: File '${filePath}' not found` }; - } - - const fd = await fs.open( - resolvedPath, - fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW, - ); - try { - content = await fd.readFile({ encoding: "utf-8" }); - } finally { - await fd.close(); - } - } else { - const stat = await fs.lstat(resolvedPath); - if (stat.isSymbolicLink()) { - return { error: `Error: Symlinks are not allowed: ${filePath}` }; - } - if (!stat.isFile()) { - return { error: `Error: File '${filePath}' not found` }; - } - content = await fs.readFile(resolvedPath, "utf-8"); - } - - const result = performStringReplacement(content, oldString, newString, replaceAll); - - if (typeof result === "string") { - return { error: result }; - } - - const [newContent, occurrences] = result; - - if (SUPPORTS_NOFOLLOW) { - const flags = - fsSync.constants.O_WRONLY | fsSync.constants.O_TRUNC | fsSync.constants.O_NOFOLLOW; - - const fd = await fs.open(resolvedPath, flags); - try { - await fd.writeFile(newContent, "utf-8"); - } finally { - await fd.close(); - } - } else { - await fs.writeFile(resolvedPath, newContent, "utf-8"); - } - - return { path: filePath, filesUpdate: null, occurrences: occurrences }; - } catch (e: any) { - return { error: `Error editing file '${filePath}': ${e.message}` }; - } - } - - async grepRaw( - pattern: string, - dirPath = "/", - glob: string | null = null, - ): Promise { - try { - new RegExp(pattern); - } catch (e: any) { - return `Invalid regex pattern: ${e.message}`; - } - - let baseFull: string; - try { - baseFull = this.resolvePath(dirPath || "."); - } catch { - return []; - } - - try { - await fs.stat(baseFull); - } catch { - return []; - } - - let results = await this.ripgrepSearch(pattern, baseFull, glob); - if (results === null) { - results = await this.fallbackSearch(pattern, baseFull, glob); - } - - const matches: GrepMatch[] = []; - for (const [filePath, items] of Object.entries(results)) { - for (const [lineNum, lineText] of items) { - matches.push({ path: filePath, line: lineNum, text: lineText }); - } - } - return matches; - } - - private async ripgrepSearch( - pattern: string, - baseFull: string, - includeGlob: string | null, - ): Promise> | null> { - return new Promise((resolve) => { - const args = ["--json"]; - if (includeGlob) { - args.push("--glob", includeGlob); - } - args.push("--", pattern, baseFull); - - const proc = spawn("rg", args, { timeout: 30000 }); - const results: Record> = {}; - let output = ""; - - proc.stdout.on("data", (data) => { - output += data.toString(); - }); - - proc.on("close", (code) => { - if (code !== 0 && code !== 1) { - resolve(null); - return; - } - - for (const line of output.split("\n")) { - if (!line.trim()) continue; - try { - const data = JSON.parse(line); - if (data.type !== "match") continue; - - const pdata = data.data || {}; - const ftext = pdata.path?.text; - if (!ftext) continue; - - let virtPath: string | undefined; - if (this.virtualMode) { - try { - const resolved = path.resolve(ftext); - const relative = path.relative(this.cwd, resolved); - if (relative.startsWith("..")) continue; - const normalizedRelative = relative.split(path.sep).join("/"); - virtPath = `/${normalizedRelative}`; - } catch { - // ignore path errors - } - } else { - virtPath = ftext; - } - - if (!virtPath) { - continue; - } - - const ln = pdata.line_number; - const lt = pdata.lines?.text?.replace(/\n$/, "") || ""; - if (ln === undefined) continue; - - if (!results[virtPath]) { - results[virtPath] = []; - } - results[virtPath].push([ln, lt]); - } catch { - // ignore parse errors - } - } - - resolve(results); - }); - - proc.on("error", () => { - resolve(null); - }); - }); - } - - private async fallbackSearch( - pattern: string, - baseFull: string, - includeGlob: string | null, - ): Promise>> { - let regex: RegExp; - try { - regex = new RegExp(pattern); - } catch { - return {}; - } - - const results: Record> = {}; - const stat = await fs.stat(baseFull); - const root = stat.isDirectory() ? baseFull : path.dirname(baseFull); - - const fg = await loadFastGlob(); - const files = await fg("**/*", { - cwd: root, - absolute: true, - onlyFiles: true, - dot: true, - }); - - for (const fp of files) { - try { - if (includeGlob && !micromatch.isMatch(path.basename(fp), includeGlob)) { - continue; - } - - const stat = await fs.stat(fp); - if (stat.size > this.maxFileSizeBytes) { - continue; - } - - const content = await fs.readFile(fp, "utf-8"); - const lines = content.split("\n"); - - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - if (regex.test(line)) { - let virtPath: string | undefined; - if (this.virtualMode) { - try { - const relative = path.relative(this.cwd, fp); - if (relative.startsWith("..")) continue; - const normalizedRelative = relative.split(path.sep).join("/"); - virtPath = `/${normalizedRelative}`; - } catch { - // ignore path errors - } - } else { - virtPath = fp; - } - - if (!virtPath) { - continue; - } - - if (!results[virtPath]) { - results[virtPath] = []; - } - results[virtPath].push([i + 1, line]); - } - } - } catch { - // ignore file errors - } - } - - return results; - } - - async globInfo(pattern: string, searchPath = "/"): Promise { - let effectivePattern = pattern; - if (effectivePattern.startsWith("/")) { - effectivePattern = effectivePattern.substring(1); - } - - const resolvedSearchPath = searchPath === "/" ? this.cwd : this.resolvePath(searchPath); - - try { - const stat = await fs.stat(resolvedSearchPath); - if (!stat.isDirectory()) { - return []; - } - } catch { - return []; - } - - const results: FileInfo[] = []; - - try { - const fg = await loadFastGlob(); - const matches = await fg(effectivePattern, { - cwd: resolvedSearchPath, - absolute: true, - onlyFiles: true, - dot: true, - }); - - for (const matchedPath of matches) { - try { - const stat = await fs.stat(matchedPath); - if (!stat.isFile()) continue; - - const normalizedPath = matchedPath.split("/").join(path.sep); - - if (!this.virtualMode) { - results.push({ - path: normalizedPath, - is_dir: false, - size: stat.size, - modified_at: stat.mtime.toISOString(), - }); - } else { - const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; - let relativePath: string; - - if (normalizedPath.startsWith(cwdStr)) { - relativePath = normalizedPath.substring(cwdStr.length); - } else if (normalizedPath.startsWith(this.cwd)) { - relativePath = normalizedPath.substring(this.cwd.length).replace(/^[/\\]/, ""); - } else { - relativePath = normalizedPath; - } - - relativePath = relativePath.split(path.sep).join("/"); - const virt = `/${relativePath}`; - results.push({ - path: virt, - is_dir: false, - size: stat.size, - modified_at: stat.mtime.toISOString(), - }); - } - } catch { - // ignore file errors - } - } - } catch { - // ignore - } - - results.sort((a, b) => a.path.localeCompare(b.path)); - return results; - } -} +export * from "../../../workspace/filesystem/backends/filesystem"; diff --git a/packages/core/src/planagent/filesystem/backends/in-memory.ts b/packages/core/src/planagent/filesystem/backends/in-memory.ts index 1bb5d578a..aafa5355b 100644 --- a/packages/core/src/planagent/filesystem/backends/in-memory.ts +++ b/packages/core/src/planagent/filesystem/backends/in-memory.ts @@ -1,157 +1 @@ -import { - createFileData, - fileDataToString, - formatReadResponse, - globSearchFiles, - grepMatchesFromFiles, - performStringReplacement, - updateFileData, -} from "../utils"; -import type { - EditResult, - FileData, - FileInfo, - FilesystemBackend, - GrepMatch, - WriteResult, -} from "./backend"; - -export class InMemoryFilesystemBackend implements FilesystemBackend { - private files: Record; - - constructor(files: Record = {}) { - this.files = files; - } - - private getFiles(): Record { - return this.files; - } - - lsInfo(path: string): FileInfo[] { - const files = this.getFiles(); - const infos: FileInfo[] = []; - const subdirs = new Set(); - - const normalizedPath = path.endsWith("/") ? path : `${path}/`; - - for (const [filePath, fd] of Object.entries(files)) { - if (!filePath.startsWith(normalizedPath)) { - continue; - } - - const relative = filePath.substring(normalizedPath.length); - if (relative.includes("/")) { - const subdirName = relative.split("/")[0]; - subdirs.add(`${normalizedPath}${subdirName}/`); - continue; - } - - const size = fd.content.join("\n").length; - infos.push({ - path: filePath, - is_dir: false, - size: size, - modified_at: fd.modified_at, - }); - } - - for (const subdir of Array.from(subdirs).sort()) { - infos.push({ - path: subdir, - is_dir: true, - size: 0, - modified_at: "", - }); - } - - infos.sort((a, b) => a.path.localeCompare(b.path)); - return infos; - } - - read(filePath: string, offset = 0, limit = 2000): string { - const files = this.getFiles(); - const fileData = files[filePath]; - - if (!fileData) { - return `Error: File '${filePath}' not found`; - } - - return formatReadResponse(fileData, offset, limit); - } - - readRaw(filePath: string): FileData { - const files = this.getFiles(); - const fileData = files[filePath]; - - if (!fileData) throw new Error(`File '${filePath}' not found`); - return fileData; - } - - write(filePath: string, content: string): WriteResult { - const files = this.getFiles(); - - if (filePath in files) { - return { - error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`, - }; - } - - const newFileData = createFileData(content); - return { - path: filePath, - filesUpdate: { [filePath]: newFileData }, - }; - } - - edit(filePath: string, oldString: string, newString: string, replaceAll = false): EditResult { - const files = this.getFiles(); - const fileData = files[filePath]; - - if (!fileData) { - return { error: `Error: File '${filePath}' not found` }; - } - - const content = fileDataToString(fileData); - const result = performStringReplacement(content, oldString, newString, replaceAll); - - if (typeof result === "string") { - return { error: result }; - } - - const [newContent, occurrences] = result; - const newFileData = updateFileData(fileData, newContent); - return { - path: filePath, - filesUpdate: { [filePath]: newFileData }, - occurrences: occurrences, - }; - } - - grepRaw(pattern: string, path = "/", glob: string | null = null): GrepMatch[] | string { - const files = this.getFiles(); - return grepMatchesFromFiles(files, pattern, path, glob); - } - - globInfo(pattern: string, path = "/"): FileInfo[] { - const files = this.getFiles(); - const result = globSearchFiles(files, pattern, path); - - if (result === "No files found") { - return []; - } - - const paths = result.split("\n"); - const infos: FileInfo[] = []; - for (const filePath of paths) { - const fd = files[filePath]; - const size = fd ? fd.content.join("\n").length : 0; - infos.push({ - path: filePath, - is_dir: false, - size: size, - modified_at: fd?.modified_at || "", - }); - } - return infos; - } -} +export * from "../../../workspace/filesystem/backends/in-memory"; diff --git a/packages/core/src/planagent/filesystem/index.ts b/packages/core/src/planagent/filesystem/index.ts index a409d2f2e..c8dbb57d0 100644 --- a/packages/core/src/planagent/filesystem/index.ts +++ b/packages/core/src/planagent/filesystem/index.ts @@ -1,3 +1,5 @@ +import type { AttributeValue, Span } from "@opentelemetry/api"; +import { safeStringify } from "@voltagent/internal"; import { z } from "zod"; import type { Agent } from "../../agent/agent"; import type { OperationContext } from "../../agent/types"; @@ -41,6 +43,7 @@ export const FILESYSTEM_SYSTEM_PROMPT = `You have access to a virtual filesystem - read_file: read a file from the filesystem - write_file: write to a file in the filesystem - edit_file: edit a file in the filesystem +- delete_file: delete a file from the filesystem - glob: find files matching a pattern (e.g., "**/*.ts") - grep: search for text within files`; @@ -50,6 +53,7 @@ export const WRITE_FILE_TOOL_DESCRIPTION = "Write content to a new file. Returns an error if the file already exists"; export const EDIT_FILE_TOOL_DESCRIPTION = "Edit a file by replacing a specific string with a new string"; +export const DELETE_FILE_TOOL_DESCRIPTION = "Delete a file from the filesystem"; export const GLOB_TOOL_DESCRIPTION = "Find files matching a glob pattern (e.g., '**/*.ts' for all TypeScript files)"; export const GREP_TOOL_DESCRIPTION = @@ -89,10 +93,54 @@ function mergeFileUpdates( return result; } +function setWorkspaceSpanAttributes( + operationContext: OperationContext, + attributes: Record, +): void { + const toolSpan = operationContext.systemContext.get("parentToolSpan") as Span | undefined; + if (!toolSpan) { + return; + } + + for (const [key, value] of Object.entries(attributes)) { + const normalized = normalizeAttributeValue(value); + if (normalized !== undefined) { + toolSpan.setAttribute(key, normalized); + } + } +} + +function normalizeAttributeValue(value: unknown): AttributeValue | undefined { + if (value === undefined) { + return undefined; + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + return value; + } + if (typeof value === "bigint" || typeof value === "symbol") { + return String(value); + } + if (Array.isArray(value)) { + const allPrimitive = value.every( + (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean", + ); + if (allPrimitive) { + return value as AttributeValue; + } + const serialized = safeStringify(value); + return typeof serialized === "string" ? serialized : undefined; + } + if (typeof value === "object" || typeof value === "function") { + const serialized = safeStringify(value); + return typeof serialized === "string" ? serialized : undefined; + } + return undefined; +} + async function applyFilesUpdate( agent: Agent, operationContext: OperationContext, - filesUpdate: Record | null | undefined, + filesUpdate: FilesUpdate | null | undefined, ): Promise { if (!filesUpdate) { return; @@ -155,6 +203,10 @@ function createLsTool( }), execute: async (input, executeOptions) => { const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.list", + "workspace.fs.path": input.path || "/", + }); const state = await loadPlanAgentState(agent, operationContext); const resolvedBackend = resolveBackend(backend, { agent, @@ -177,19 +229,21 @@ function createReadFileTool( description: options.customDescription || READ_FILE_TOOL_DESCRIPTION, parameters: z.object({ file_path: z.string().describe("Absolute path to the file to read"), - offset: z - .number({ coerce: true }) + offset: z.coerce + .number() .optional() .default(0) .describe("Line offset to start reading from (0-indexed)"), - limit: z - .number({ coerce: true }) - .optional() - .default(2000) - .describe("Maximum number of lines to read"), + limit: z.coerce.number().optional().default(2000).describe("Maximum number of lines to read"), }), execute: async (input, executeOptions) => { const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.read", + "workspace.fs.path": input.file_path, + "workspace.fs.offset": input.offset, + "workspace.fs.limit": input.limit, + }); const state = await loadPlanAgentState(agent, operationContext); const resolvedBackend = resolveBackend(backend, { agent, @@ -215,6 +269,11 @@ function createWriteFileTool( }), execute: async (input, executeOptions) => { const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.write", + "workspace.fs.path": input.file_path, + "workspace.fs.bytes": input.content.length, + }); const state = await loadPlanAgentState(agent, operationContext); const resolvedBackend = resolveBackend(backend, { agent, @@ -253,6 +312,10 @@ function createEditFileTool( }), execute: async (input, executeOptions) => { const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.edit", + "workspace.fs.path": input.file_path, + }); const state = await loadPlanAgentState(agent, operationContext); const resolvedBackend = resolveBackend(backend, { agent, @@ -271,12 +334,54 @@ function createEditFileTool( return result.error; } + setWorkspaceSpanAttributes(operationContext, { + "workspace.fs.occurrences": result.occurrences, + }); await applyFilesUpdate(agent, operationContext, result.filesUpdate || undefined); return `Successfully replaced ${result.occurrences ?? 0} occurrence(s) in '${input.file_path}'`; }, }); } +function createDeleteFileTool( + agent: Agent, + backend: FilesystemBackend | FilesystemBackendFactory, + options: { customDescription: string | undefined }, +) { + return createTool({ + name: "delete_file", + description: options.customDescription || DELETE_FILE_TOOL_DESCRIPTION, + parameters: z.object({ + file_path: z.string().describe("Absolute path to the file to delete"), + }), + execute: async (input, executeOptions) => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.delete", + "workspace.fs.path": input.file_path, + }); + const state = await loadPlanAgentState(agent, operationContext); + const resolvedBackend = resolveBackend(backend, { + agent, + operationContext, + state, + }); + + if (!resolvedBackend.delete) { + return "Delete operation is not supported by the configured filesystem backend."; + } + + const result = await resolvedBackend.delete(input.file_path); + if (result.error) { + return result.error; + } + + await applyFilesUpdate(agent, operationContext, result.filesUpdate || undefined); + return `Successfully deleted '${input.file_path}'`; + }, + }); +} + function createGlobTool( agent: Agent, backend: FilesystemBackend | FilesystemBackendFactory, @@ -291,6 +396,11 @@ function createGlobTool( }), execute: async (input, executeOptions) => { const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.glob", + "workspace.fs.path": input.path || "/", + "workspace.fs.pattern": input.pattern, + }); const state = await loadPlanAgentState(agent, operationContext); const resolvedBackend = resolveBackend(backend, { agent, @@ -323,6 +433,12 @@ function createGrepTool( }), execute: async (input, executeOptions) => { const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + "workspace.operation": "filesystem.grep", + "workspace.fs.path": input.path || "/", + "workspace.search.query": input.pattern, + "workspace.fs.pattern": input.glob ?? undefined, + }); const state = await loadPlanAgentState(agent, operationContext); const resolvedBackend = resolveBackend(backend, { agent, @@ -358,6 +474,9 @@ export function createFilesystemToolkit( createEditFileTool(agent, backend, { customDescription: options.customToolDescriptions?.edit_file, }), + createDeleteFileTool(agent, backend, { + customDescription: options.customToolDescriptions?.delete_file, + }), createGlobTool(agent, backend, { customDescription: options.customToolDescriptions?.glob }), createGrepTool(agent, backend, { customDescription: options.customToolDescriptions?.grep }), ]; diff --git a/packages/core/src/planagent/filesystem/utils.ts b/packages/core/src/planagent/filesystem/utils.ts index 73503be04..923a1b601 100644 --- a/packages/core/src/planagent/filesystem/utils.ts +++ b/packages/core/src/planagent/filesystem/utils.ts @@ -1,289 +1 @@ -import micromatch from "micromatch"; -import type { FileData, GrepMatch } from "./backends/backend"; - -export const EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents"; -export const MAX_LINE_LENGTH = 10000; -export const LINE_NUMBER_WIDTH = 6; -export const TOOL_RESULT_TOKEN_LIMIT = 20000; -export const TRUNCATION_GUIDANCE = - "... [results truncated, try being more specific with your parameters]"; - -export function sanitizeToolCallId(toolCallId: string): string { - return toolCallId.replace(/\./g, "_").replace(/\//g, "_").replace(/\\/g, "_"); -} - -export function formatContentWithLineNumbers(content: string | string[], startLine = 1): string { - let lines: string[]; - if (typeof content === "string") { - lines = content.split("\n"); - if (lines.length > 0 && lines[lines.length - 1] === "") { - lines = lines.slice(0, -1); - } - } else { - lines = content; - } - - const resultLines: string[] = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - const lineNum = i + startLine; - - if (line.length <= MAX_LINE_LENGTH) { - resultLines.push(`${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\t${line}`); - } else { - const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH); - for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) { - const start = chunkIdx * MAX_LINE_LENGTH; - const end = Math.min(start + MAX_LINE_LENGTH, line.length); - const chunk = line.substring(start, end); - if (chunkIdx === 0) { - resultLines.push(`${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\t${chunk}`); - } else { - const continuationMarker = `${lineNum}.${chunkIdx}`; - resultLines.push(`${continuationMarker.padStart(LINE_NUMBER_WIDTH)}\t${chunk}`); - } - } - } - } - - return resultLines.join("\n"); -} - -export function checkEmptyContent(content: string): string | null { - if (!content || content.trim() === "") { - return EMPTY_CONTENT_WARNING; - } - return null; -} - -export function fileDataToString(fileData: FileData): string { - return fileData.content.join("\n"); -} - -export function createFileData(content: string, createdAt?: string): FileData { - const lines = typeof content === "string" ? content.split("\n") : content; - const now = new Date().toISOString(); - - return { - content: lines, - created_at: createdAt || now, - modified_at: now, - }; -} - -export function updateFileData(fileData: FileData, content: string): FileData { - const lines = typeof content === "string" ? content.split("\n") : content; - const now = new Date().toISOString(); - - return { - content: lines, - created_at: fileData.created_at, - modified_at: now, - }; -} - -export function formatReadResponse(fileData: FileData, offset: number, limit: number): string { - const content = fileDataToString(fileData); - const emptyMsg = checkEmptyContent(content); - if (emptyMsg) { - return emptyMsg; - } - - const lines = content.split("\n"); - const startIdx = offset; - const endIdx = Math.min(startIdx + limit, lines.length); - - if (startIdx >= lines.length) { - return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`; - } - - const selectedLines = lines.slice(startIdx, endIdx); - return formatContentWithLineNumbers(selectedLines, startIdx + 1); -} - -export function performStringReplacement( - content: string, - oldString: string, - newString: string, - replaceAll: boolean, -): [string, number] | string { - const occurrences = content.split(oldString).length - 1; - - if (occurrences === 0) { - return `Error: String not found in file: '${oldString}'`; - } - - if (occurrences > 1 && !replaceAll) { - return `Error: String '${oldString}' appears ${occurrences} times in file. Use replace_all=true to replace all instances, or provide a more specific string with surrounding context.`; - } - - const newContent = content.split(oldString).join(newString); - - return [newContent, occurrences]; -} - -export function truncateIfTooLong(result: string[] | string): string[] | string { - if (Array.isArray(result)) { - const totalChars = result.reduce((sum, item) => sum + item.length, 0); - if (totalChars > TOOL_RESULT_TOKEN_LIMIT * 4) { - const truncateAt = Math.floor((result.length * TOOL_RESULT_TOKEN_LIMIT * 4) / totalChars); - return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE]; - } - return result; - } - - if (result.length > TOOL_RESULT_TOKEN_LIMIT * 4) { - return `${result.substring(0, TOOL_RESULT_TOKEN_LIMIT * 4)}\n${TRUNCATION_GUIDANCE}`; - } - return result; -} - -export function validatePath(path: string | null | undefined): string { - const pathStr = path || "/"; - if (!pathStr || pathStr.trim() === "") { - throw new Error("Path cannot be empty"); - } - - let normalized = pathStr.startsWith("/") ? pathStr : `/${pathStr}`; - - if (!normalized.endsWith("/")) { - normalized += "/"; - } - - return normalized; -} - -function basename(filePath: string): string { - const normalized = filePath.replace(/\\/g, "/"); - const parts = normalized.split("/"); - return parts[parts.length - 1] || ""; -} - -export function globSearchFiles( - files: Record, - pattern: string, - path = "/", -): string { - let normalizedPath: string; - try { - normalizedPath = validatePath(path); - } catch { - return "No files found"; - } - - const filtered = Object.fromEntries( - Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)), - ); - - const matches: Array<[string, string]> = []; - for (const [filePath, fileData] of Object.entries(filtered)) { - let relative = filePath.substring(normalizedPath.length); - if (relative.startsWith("/")) { - relative = relative.substring(1); - } - if (!relative) { - relative = basename(filePath); - } - - if ( - micromatch.isMatch(relative, pattern, { - dot: true, - nobrace: false, - }) - ) { - matches.push([filePath, fileData.modified_at]); - } - } - - matches.sort((a, b) => b[1].localeCompare(a[1])); - - if (matches.length === 0) { - return "No files found"; - } - - return matches.map(([fp]) => fp).join("\n"); -} - -export function grepMatchesFromFiles( - files: Record, - pattern: string, - path: string | null = null, - glob: string | null = null, -): GrepMatch[] | string { - let regex: RegExp; - try { - regex = new RegExp(pattern); - } catch (e: any) { - return `Invalid regex pattern: ${e.message}`; - } - - let normalizedPath: string; - try { - normalizedPath = validatePath(path); - } catch { - return []; - } - - let filtered = Object.fromEntries( - Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)), - ); - - if (glob) { - filtered = Object.fromEntries( - Object.entries(filtered).filter(([fp]) => - micromatch.isMatch(basename(fp), glob, { dot: true, nobrace: false }), - ), - ); - } - - const matches: GrepMatch[] = []; - for (const [filePath, fileData] of Object.entries(filtered)) { - for (let i = 0; i < fileData.content.length; i++) { - const line = fileData.content[i]; - const lineNum = i + 1; - if (regex.test(line)) { - matches.push({ path: filePath, line: lineNum, text: line }); - } - } - } - - return matches; -} - -export function formatGrepMatches( - matches: GrepMatch[], - outputMode: "files_with_matches" | "content" | "count", -): string { - if (matches.length === 0) { - return "No matches found"; - } - - const grouped: Record> = {}; - for (const match of matches) { - if (!grouped[match.path]) { - grouped[match.path] = []; - } - grouped[match.path].push([match.line, match.text]); - } - - if (outputMode === "files_with_matches") { - return Object.keys(grouped).sort().join("\n"); - } - - if (outputMode === "count") { - const lines: string[] = []; - for (const filePath of Object.keys(grouped).sort()) { - lines.push(`${filePath}: ${grouped[filePath].length}`); - } - return lines.join("\n"); - } - - const lines: string[] = []; - for (const filePath of Object.keys(grouped).sort()) { - lines.push(`${filePath}:`); - for (const [lineNum, line] of grouped[filePath]) { - lines.push(` ${lineNum}: ${line}`); - } - } - return lines.join("\n"); -} +export * from "../../workspace/filesystem/utils"; diff --git a/packages/core/src/planagent/index.ts b/packages/core/src/planagent/index.ts index b6a2a87b4..26c90101b 100644 --- a/packages/core/src/planagent/index.ts +++ b/packages/core/src/planagent/index.ts @@ -33,6 +33,7 @@ export { READ_FILE_TOOL_DESCRIPTION, WRITE_FILE_TOOL_DESCRIPTION, EDIT_FILE_TOOL_DESCRIPTION, + DELETE_FILE_TOOL_DESCRIPTION, GLOB_TOOL_DESCRIPTION, GREP_TOOL_DESCRIPTION, } from "./filesystem"; diff --git a/packages/core/src/planagent/plan-agent.ts b/packages/core/src/planagent/plan-agent.ts index 2e9bedd3f..5b7d90b42 100644 --- a/packages/core/src/planagent/plan-agent.ts +++ b/packages/core/src/planagent/plan-agent.ts @@ -125,7 +125,13 @@ export type TaskToolOptions = { export type PlanAgentOptions = Omit< AgentOptions, - "instructions" | "tools" | "toolkits" | "subAgents" | "supervisorConfig" + | "instructions" + | "tools" + | "toolkits" + | "subAgents" + | "supervisorConfig" + | "workspace" + | "workspaceToolkits" > & { systemPrompt?: InstructionsDynamicValue; tools?: (Tool | Toolkit | VercelTool)[]; @@ -1016,8 +1022,12 @@ export class PlanAgent extends Agent { onError: [...extensionHooks.map((hook) => hook.onError), hooks?.onError], }); + const sanitizedAgentOptions = { ...(agentOptions as AgentOptions) }; + (sanitizedAgentOptions as Record).workspace = undefined; + (sanitizedAgentOptions as Record).workspaceToolkits = undefined; + super({ - ...agentOptions, + ...sanitizedAgentOptions, name: name || "plan-agent", instructions, summarization, diff --git a/packages/core/src/planagent/types.ts b/packages/core/src/planagent/types.ts index bfd2ca5a3..af25f825f 100644 --- a/packages/core/src/planagent/types.ts +++ b/packages/core/src/planagent/types.ts @@ -1,3 +1,5 @@ +import type { FileData } from "../workspace/filesystem"; + export type PlanAgentTodoStatus = "pending" | "in_progress" | "done"; export type PlanAgentTodoItem = { @@ -8,11 +10,7 @@ export type PlanAgentTodoItem = { updatedAt?: string; }; -export type PlanAgentFileData = { - content: string[]; - created_at: string; - modified_at: string; -}; +export type PlanAgentFileData = FileData; export type PlanAgentState = { todos?: PlanAgentTodoItem[]; diff --git a/packages/core/src/registries/agent-registry.ts b/packages/core/src/registries/agent-registry.ts index bb24e6d80..1da299193 100644 --- a/packages/core/src/registries/agent-registry.ts +++ b/packages/core/src/registries/agent-registry.ts @@ -4,6 +4,7 @@ import type { Memory } from "../memory"; import type { VoltAgentObservability } from "../observability"; import type { ToolRoutingConfig } from "../tool/routing/types"; import type { VoltOpsClient } from "../voltops/client"; +import type { Workspace } from "../workspace"; /** * Registry to manage and track agents @@ -27,6 +28,7 @@ export class AgentRegistry { private globalAgentMemory?: Memory; private globalWorkflowMemory?: Memory; private globalToolRouting?: ToolRoutingConfig; + private globalWorkspace?: Workspace; /** * Track parent-child relationships between agents (child -> parents) @@ -292,4 +294,18 @@ export class AgentRegistry { public getGlobalToolRouting(): ToolRoutingConfig | undefined { return this.globalToolRouting; } + + /** + * Set the global Workspace instance. + */ + public setGlobalWorkspace(workspace: Workspace | undefined): void { + this.globalWorkspace = workspace; + } + + /** + * Get the global Workspace instance. + */ + public getGlobalWorkspace(): Workspace | undefined { + return this.globalWorkspace; + } } diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 0130d3fbf..d1fc4d0e3 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -20,6 +20,7 @@ import type { VoltOpsClient } from "./voltops/client"; import type { WorkflowChain } from "./workflow/chain"; import type { RegisteredWorkflow } from "./workflow/registry"; import type { Workflow, WorkflowSuspendController } from "./workflow/types"; +import type { Workspace, WorkspaceConfig } from "./workspace"; export interface MCPLoggingAdapter { setLevel?(level: string): Promise | void; @@ -233,6 +234,11 @@ export type VoltAgentOptions = { * When enabled, agents expose searchTools/callTool and hide pool tools from the model. */ toolRouting?: ToolRoutingConfig; + /** + * Optional global workspace instance or configuration. + * Agents inherit this workspace unless they explicitly provide their own workspace or set it to false. + */ + workspace?: Workspace | WorkspaceConfig; /** Optional VoltOps trigger handlers */ triggers?: VoltAgentTriggersConfig; /** diff --git a/packages/core/src/voltagent.ts b/packages/core/src/voltagent.ts index 97584c8c5..381b1b50f 100644 --- a/packages/core/src/voltagent.ts +++ b/packages/core/src/voltagent.ts @@ -22,6 +22,7 @@ import { VoltOpsClient } from "./voltops/client"; import type { Workflow } from "./workflow"; import type { WorkflowChain } from "./workflow/chain"; import { WorkflowRegistry } from "./workflow/registry"; +import { Workspace } from "./workspace"; /** * Main VoltAgent class for managing agents and server @@ -42,6 +43,9 @@ export class VoltAgent { private readonly ensureEnvironmentBinding: (env?: Record) => void; private readonly triggerRegistry: TriggerRegistry; private readonly agentRefs: Record; + public readonly ready: Promise; + public initError?: unknown; + public degraded = false; constructor(options: VoltAgentOptions) { this.registry = AgentRegistry.getInstance(); this.workflowRegistry = WorkflowRegistry.getInstance(); @@ -64,9 +68,19 @@ export class VoltAgent { if (options.toolRouting) { this.registry.setGlobalToolRouting(options.toolRouting); } + let workspaceInitPromise: Promise | undefined; + if (options.workspace) { + const workspaceInstance = + options.workspace instanceof Workspace + ? options.workspace + : new Workspace(options.workspace); + this.registry.setGlobalWorkspace(workspaceInstance); + workspaceInitPromise = workspaceInstance.init(); + } // Initialize logger - this.logger = (options.logger || getGlobalLogger()).child({ component: "voltagent" }); + const logger = (options.logger || getGlobalLogger()).child({ component: "voltagent" }); + this.logger = logger; // Handle unified VoltOps client before observability so factories can reuse it if (options.voltOpsClient) { @@ -104,83 +118,148 @@ export class VoltAgent { // Setup graceful shutdown handlers this.setupShutdownHandlers(); - // ✅ NOW register agents - they can access global telemetry exporter - this.registerAgents(options.agents); - this.registerTriggers(options.triggers); - - // Register workflows if provided - if (options.workflows) { - this.registerWorkflows(options.workflows); - } - - // Handle server provider if provided - if (options.server) { - this.serverInstance = options.server({ - agentRegistry: this.registry, - workflowRegistry: this.workflowRegistry, - logger: this.logger, - voltOpsClient: this.registry.getGlobalVoltOpsClient(), - observability: this.observability, - mcp: { - registry: this.mcpServerRegistry, - }, - a2a: { - registry: this.a2aServerRegistry, - }, - triggerRegistry: this.triggerRegistry, - ensureEnvironment: this.ensureEnvironmentBinding, - }); - } + const finalizeInit = () => { + // ✅ NOW register agents - they can access global telemetry exporter + this.registerAgents(options.agents); + this.registerTriggers(options.triggers); - if (options.serverless) { - this.serverlessProvider = options.serverless({ - agentRegistry: this.registry, - workflowRegistry: this.workflowRegistry, - logger: this.logger, - voltOpsClient: this.registry.getGlobalVoltOpsClient(), - observability: this.observability, - mcp: { - registry: this.mcpServerRegistry, - }, - a2a: { - registry: this.a2aServerRegistry, - }, - triggerRegistry: this.triggerRegistry, - ensureEnvironment: this.ensureEnvironmentBinding, - }); - } + // Register workflows if provided + if (options.workflows) { + this.registerWorkflows(options.workflows); + } - if (options.mcpServers) { - for (const entry of Object.values(options.mcpServers)) { - this.initializeMCPServer(entry); + // Handle server provider if provided + if (options.server) { + this.serverInstance = options.server({ + agentRegistry: this.registry, + workflowRegistry: this.workflowRegistry, + logger: this.logger, + voltOpsClient: this.registry.getGlobalVoltOpsClient(), + observability: this.observability, + mcp: { + registry: this.mcpServerRegistry, + }, + a2a: { + registry: this.a2aServerRegistry, + }, + triggerRegistry: this.triggerRegistry, + ensureEnvironment: this.ensureEnvironmentBinding, + }); } - } - if (options.a2aServers) { - for (const entry of Object.values(options.a2aServers)) { - this.initializeA2AServer(entry); + if (options.serverless) { + this.serverlessProvider = options.serverless({ + agentRegistry: this.registry, + workflowRegistry: this.workflowRegistry, + logger: this.logger, + voltOpsClient: this.registry.getGlobalVoltOpsClient(), + observability: this.observability, + mcp: { + registry: this.mcpServerRegistry, + }, + a2a: { + registry: this.a2aServerRegistry, + }, + triggerRegistry: this.triggerRegistry, + ensureEnvironment: this.ensureEnvironmentBinding, + }); } - } - // Check dependencies if enabled (run in background) - if (options.checkDependencies !== false) { - // Run dependency check in background to not block startup - Promise.resolve().then(() => { - this.checkDependencies().catch(() => { - // Silently ignore errors + if (options.mcpServers) { + for (const entry of Object.values(options.mcpServers)) { + this.initializeMCPServer(entry); + } + } + + if (options.a2aServers) { + for (const entry of Object.values(options.a2aServers)) { + this.initializeA2AServer(entry); + } + } + + // Check dependencies if enabled (run in background) + if (options.checkDependencies !== false) { + // Run dependency check in background to not block startup + Promise.resolve().then(() => { + this.checkDependencies().catch(() => { + // Silently ignore errors + }); }); - }); - } + } - // Auto-start server if provided - if (this.serverInstance) { - this.startServer().catch((err) => { - this.logger.error("Failed to start server:", err); - if (typeof process !== "undefined" && typeof process.exit === "function") { - process.exit(1); + // Auto-start server if provided + if (this.serverInstance) { + this.startServer().catch((err) => { + this.logger.error("Failed to start server:", err); + if (typeof process !== "undefined" && typeof process.exit === "function") { + process.exit(1); + } + }); + } + }; + + this.ready = (async () => { + let workspaceError: unknown; + let finalizeError: unknown; + if (workspaceInitPromise) { + try { + await workspaceInitPromise; + } catch (error) { + workspaceError = error; + logger.error("Workspace initialization failed:", { error }); } - }); - } + } + try { + finalizeInit(); + } catch (error) { + finalizeError = error; + logger.error("finalizeInit failed:", { error }); + } + + if (workspaceError || finalizeError) { + this.degraded = true; + if (workspaceError && finalizeError) { + this.initError = new AggregateError( + [workspaceError, finalizeError], + "Workspace and finalizeInit failed", + ); + logger.error("Agent initialization encountered multiple failures:", { + workspaceError, + finalizeError, + }); + } else { + this.initError = workspaceError ?? finalizeError; + logger.error("Agent initialization failed:", { + error: this.initError, + }); + } + } + + if (finalizeError) { + throw finalizeError; + } + })().catch((error) => { + this.degraded = true; + if (this.initError) { + if (this.initError instanceof AggregateError) { + const aggregated = (this.initError as AggregateError).errors; + if (!aggregated.includes(error)) { + this.initError = new AggregateError( + [...aggregated, error], + "Agent initialization failed", + ); + } + } else if (this.initError !== error) { + this.initError = new AggregateError( + [this.initError, error], + "Agent initialization failed", + ); + } + } else { + this.initError = error; + } + logger.error("Agent initialization failed:", { error }); + }); } serverless(): IServerlessProvider { @@ -561,6 +640,12 @@ export class VoltAgent { this.logger.info("[VoltAgent] Suspending active workflows..."); await this.workflowRegistry.suspendAllActiveWorkflows(); + const globalWorkspace = this.registry.getGlobalWorkspace(); + if (globalWorkspace) { + this.logger.info("[VoltAgent] Destroying global workspace..."); + await globalWorkspace.destroy(); + } + // Shutdown telemetry if (this.observability) { this.logger.info("[VoltAgent] Shutting down telemetry..."); diff --git a/packages/core/src/workspace/filesystem/backends/backend.ts b/packages/core/src/workspace/filesystem/backends/backend.ts new file mode 100644 index 000000000..2222d082d --- /dev/null +++ b/packages/core/src/workspace/filesystem/backends/backend.ts @@ -0,0 +1,102 @@ +import type { Agent } from "../../../agent/agent"; +import type { OperationContext } from "../../../agent/types"; + +export type MaybePromise = T | Promise; + +export interface FileInfo { + path: string; + is_dir?: boolean; + size?: number; + modified_at?: string; + created_at?: string; +} + +export interface GrepMatch { + path: string; + line: number; + text: string; +} + +export interface FileData { + content: string[]; + created_at: string; + modified_at: string; +} + +export interface WriteResult { + error?: string; + path?: string; + filesUpdate?: Record | null; + metadata?: Record; +} + +export interface WriteOptions { + overwrite?: boolean; +} + +export interface EditResult { + error?: string; + path?: string; + filesUpdate?: Record | null; + occurrences?: number; + metadata?: Record; +} + +export interface DeleteResult { + error?: string; + path?: string; + filesUpdate?: Record | null; + metadata?: Record; +} + +export interface DeleteOptions { + recursive?: boolean; +} + +export interface MkdirResult { + error?: string; + path?: string; + metadata?: Record; +} + +export interface RmdirResult { + error?: string; + path?: string; + filesUpdate?: Record | null; + metadata?: Record; +} + +export interface FilesystemBackend { + lsInfo(path: string): MaybePromise; + read(filePath: string, offset?: number, limit?: number): MaybePromise; + readRaw(filePath: string): MaybePromise; + stat?(filePath: string): MaybePromise; + exists?(filePath: string): MaybePromise; + grepRaw( + pattern: string, + path?: string | null, + glob?: string | null, + ): MaybePromise; + globInfo(pattern: string, path?: string): MaybePromise; + write(filePath: string, content: string, options?: WriteOptions): MaybePromise; + edit( + filePath: string, + oldString: string, + newString: string, + replaceAll?: boolean, + ): MaybePromise; + delete?(filePath: string, options?: DeleteOptions): MaybePromise; + mkdir?(path: string, recursive?: boolean): MaybePromise; + rmdir?(path: string, recursive?: boolean): MaybePromise; +} + +export type FilesystemBackendContext = { + agent?: Agent; + operationContext?: OperationContext; + state: { + files?: Record; + directories?: Set; + }; +}; + +export type FilesystemBackendFactory = (context: FilesystemBackendContext) => FilesystemBackend; diff --git a/packages/core/src/workspace/filesystem/backends/composite.ts b/packages/core/src/workspace/filesystem/backends/composite.ts new file mode 100644 index 000000000..eacc98cee --- /dev/null +++ b/packages/core/src/workspace/filesystem/backends/composite.ts @@ -0,0 +1,368 @@ +import { posix as posixPath } from "node:path"; +import type { + DeleteOptions, + DeleteResult, + EditResult, + FileData, + FileInfo, + FilesystemBackend, + GrepMatch, + MkdirResult, + RmdirResult, + WriteOptions, + WriteResult, +} from "./backend"; + +export class CompositeFilesystemBackend implements FilesystemBackend { + private defaultBackend: FilesystemBackend; + private routes: Record; + private sortedRoutes: Array<[string, FilesystemBackend]>; + + constructor(defaultBackend: FilesystemBackend, routes: Record) { + this.defaultBackend = defaultBackend; + this.routes = routes; + + this.sortedRoutes = Object.entries(routes).sort((a, b) => b[0].length - a[0].length); + } + + private getBackendAndKey(key: string): [FilesystemBackend, string] { + for (const [prefix, backend] of this.sortedRoutes) { + if (key.startsWith(prefix)) { + const suffix = key.substring(prefix.length); + const strippedKey = suffix ? `/${suffix}` : "/"; + return [backend, strippedKey]; + } + } + + return [this.defaultBackend, key]; + } + + private getMountPrefix(key: string): string | null { + for (const [prefix] of this.sortedRoutes) { + if (key.startsWith(prefix)) { + return prefix; + } + } + return null; + } + + private remapFilesUpdate( + filesUpdate: Record, + mountPrefix: string, + ): Record { + const prefix = mountPrefix.endsWith("/") ? mountPrefix.slice(0, -1) : mountPrefix; + const remapped: Record = {}; + for (const [key, value] of Object.entries(filesUpdate)) { + const normalizedKey = key.startsWith("/") ? key : `/${key}`; + const mappedPath = posixPath.normalize(`${prefix}${normalizedKey}`); + remapped[mappedPath] = value; + } + return remapped; + } + + private remapFilesUpdateResult< + T extends { filesUpdate?: Record | null }, + >(result: T, mountPrefix: string | null): T { + if (!mountPrefix || !result.filesUpdate) { + return result; + } + return { + ...result, + filesUpdate: this.remapFilesUpdate(result.filesUpdate, mountPrefix), + }; + } + + async lsInfo(path: string): Promise { + for (const [routePrefix, backend] of this.sortedRoutes) { + const normalizedPrefix = routePrefix.endsWith("/") ? routePrefix : `${routePrefix}/`; + const prefixRoot = normalizedPrefix.slice(0, -1); + if (path === prefixRoot || path.startsWith(normalizedPrefix)) { + const suffix = path === prefixRoot ? "" : path.substring(normalizedPrefix.length); + const searchPath = suffix ? `/${suffix}` : "/"; + const infos = await backend.lsInfo(searchPath); + + return infos.map((info) => ({ + ...info, + path: routePrefix.slice(0, -1) + info.path, + })); + } + } + + if (path === "/") { + const results: FileInfo[] = []; + const defaultInfos = await this.defaultBackend.lsInfo(path); + results.push(...defaultInfos); + + for (const [routePrefix] of this.sortedRoutes) { + results.push({ + path: routePrefix, + is_dir: true, + size: 0, + modified_at: "", + }); + } + + results.sort((a, b) => a.path.localeCompare(b.path)); + return results; + } + + return await this.defaultBackend.lsInfo(path); + } + + async read(filePath: string, offset = 0, limit = 2000): Promise { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.read(strippedKey, offset, limit); + } + + async readRaw(filePath: string): Promise { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + return await backend.readRaw(strippedKey); + } + + async stat(filePath: string): Promise { + for (const [routePrefix, backend] of this.sortedRoutes) { + const normalizedPrefix = routePrefix.endsWith("/") ? routePrefix : `${routePrefix}/`; + if (filePath === routePrefix || filePath === normalizedPrefix) { + return { + path: normalizedPrefix, + is_dir: true, + size: 0, + modified_at: "", + }; + } + if (filePath.startsWith(normalizedPrefix)) { + if (!backend.stat) { + return null; + } + const suffix = filePath.substring(routePrefix.length); + const strippedPath = suffix ? `/${suffix}` : "/"; + const info = await backend.stat(strippedPath); + if (!info) { + return null; + } + return { + ...info, + path: routePrefix.slice(0, -1) + info.path, + }; + } + } + + if (!this.defaultBackend.stat) { + return null; + } + return await this.defaultBackend.stat(filePath); + } + + async exists(filePath: string): Promise { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + if (backend.exists) { + return await backend.exists(strippedKey); + } + if (backend.stat) { + const info = await backend.stat(strippedKey); + return Boolean(info); + } + try { + await backend.readRaw(strippedKey); + return true; + } catch { + return false; + } + } + + async grepRaw( + pattern: string, + path = "/", + glob: string | null = null, + ): Promise { + const errors: string[] = []; + for (const [routePrefix, backend] of this.sortedRoutes) { + const prefix = routePrefix.replace(/\/$/, ""); + if (path.startsWith(prefix)) { + const searchPath = path.substring(prefix.length) || "/"; + const raw = await backend.grepRaw(pattern, searchPath, glob); + + if (typeof raw === "string") { + errors.push(raw); + continue; + } + + return raw.map((match) => ({ + ...match, + path: routePrefix.slice(0, -1) + match.path, + })); + } + } + + const allMatches: GrepMatch[] = []; + const rawDefault = await this.defaultBackend.grepRaw(pattern, path, glob); + + if (typeof rawDefault === "string") { + errors.push(rawDefault); + } else { + allMatches.push(...rawDefault); + } + + for (const [routePrefix, backend] of Object.entries(this.routes)) { + const raw = await backend.grepRaw(pattern, "/", glob); + + if (typeof raw === "string") { + errors.push(raw); + continue; + } + + allMatches.push( + ...raw.map((match) => ({ + ...match, + path: routePrefix.slice(0, -1) + match.path, + })), + ); + } + + if (allMatches.length > 0) { + return allMatches; + } + if (errors.length > 0) { + return errors[0]; + } + return allMatches; + } + + async globInfo(pattern: string, path = "/"): Promise { + const results: FileInfo[] = []; + + for (const [routePrefix, backend] of this.sortedRoutes) { + const normalizedPrefix = routePrefix.endsWith("/") ? routePrefix : `${routePrefix}/`; + const prefixRoot = normalizedPrefix.slice(0, -1); + if (path === prefixRoot || path.startsWith(normalizedPrefix)) { + const suffix = path === prefixRoot ? "" : path.substring(normalizedPrefix.length); + const searchPath = suffix ? `/${suffix}` : "/"; + const infos = await backend.globInfo(pattern, searchPath); + + return infos.map((info) => ({ + ...info, + path: routePrefix.slice(0, -1) + info.path, + })); + } + } + + const defaultInfos = await this.defaultBackend.globInfo(pattern, path); + results.push(...defaultInfos); + + for (const [routePrefix, backend] of Object.entries(this.routes)) { + const infos = await backend.globInfo(pattern, "/"); + results.push( + ...infos.map((info) => ({ + ...info, + path: routePrefix.slice(0, -1) + info.path, + })), + ); + } + + results.sort((a, b) => a.path.localeCompare(b.path)); + return results; + } + + async write(filePath: string, content: string, options?: WriteOptions): Promise { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + const result = await backend.write(strippedKey, content, options); + const matchedPrefix = this.getMountPrefix(filePath); + const remapped = this.remapFilesUpdateResult(result, matchedPrefix); + if (!remapped.path || !matchedPrefix || backend === this.defaultBackend) { + return remapped; + } + return { + ...remapped, + path: matchedPrefix.slice(0, -1) + remapped.path, + }; + } + + async edit( + filePath: string, + oldString: string, + newString: string, + replaceAll = false, + ): Promise { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + const result = await backend.edit(strippedKey, oldString, newString, replaceAll); + const matchedPrefix = this.getMountPrefix(filePath); + const remapped = this.remapFilesUpdateResult(result, matchedPrefix); + if (!remapped.path || !matchedPrefix || backend === this.defaultBackend) { + return remapped; + } + return { + ...remapped, + path: matchedPrefix.slice(0, -1) + remapped.path, + }; + } + + async delete(filePath: string, options?: DeleteOptions): Promise { + const [backend, strippedKey] = this.getBackendAndKey(filePath); + if (!backend.delete) { + return { error: "Delete operation is not supported by this filesystem backend." }; + } + const result = await backend.delete(strippedKey, options); + const matchedPrefix = this.getMountPrefix(filePath); + const remapped = this.remapFilesUpdateResult(result, matchedPrefix); + if (!remapped.path || !matchedPrefix || backend === this.defaultBackend) { + return remapped; + } + return { + ...remapped, + path: matchedPrefix.slice(0, -1) + remapped.path, + }; + } + + async mkdir(path: string, recursive = true): Promise { + const matchedPrefix = this.getMountPrefix(path); + + const [backend, strippedKey] = this.getBackendAndKey(path); + if (!backend.mkdir) { + return { error: "Mkdir operation is not supported by this filesystem backend." }; + } + const result = await backend.mkdir(strippedKey, recursive); + if (result.error || !result.path) { + return result; + } + if (!matchedPrefix || backend === this.defaultBackend) { + return result; + } + + return { + ...result, + path: matchedPrefix.slice(0, -1) + result.path, + }; + } + + async rmdir(path: string, recursive = false): Promise { + let matchedPrefix: string | undefined; + for (const [routePrefix] of this.sortedRoutes) { + if (path.startsWith(routePrefix)) { + matchedPrefix = routePrefix; + break; + } + } + + const [backend, strippedKey] = this.getBackendAndKey(path); + if (!backend.rmdir) { + return { error: "Rmdir operation is not supported by this filesystem backend." }; + } + const result = await backend.rmdir(strippedKey, recursive); + if (result.error) { + return result; + } + if (!matchedPrefix || backend === this.defaultBackend) { + return result; + } + + const remapped = this.remapFilesUpdateResult(result, matchedPrefix); + if (!remapped.path) { + return remapped; + } + + return { + ...remapped, + path: matchedPrefix.slice(0, -1) + remapped.path, + }; + } +} diff --git a/packages/core/src/workspace/filesystem/backends/filesystem.ts b/packages/core/src/workspace/filesystem/backends/filesystem.ts new file mode 100644 index 000000000..84e05a784 --- /dev/null +++ b/packages/core/src/workspace/filesystem/backends/filesystem.ts @@ -0,0 +1,980 @@ +import { spawn } from "node:child_process"; +import * as fsSync from "node:fs"; +import * as fs from "node:fs/promises"; +import * as path from "node:path"; +import micromatch from "micromatch"; +import { + MAX_GREP_LINE_LENGTH, + MAX_GREP_MATCHES, + assessRegexPattern, + checkEmptyContent, + formatContentWithLineNumbers, + performStringReplacement, +} from "../utils"; +import type { + DeleteOptions, + DeleteResult, + EditResult, + FileData, + FileInfo, + FilesystemBackend as FilesystemBackendProtocol, + GrepMatch, + MkdirResult, + RmdirResult, + WriteOptions, + WriteResult, +} from "./backend"; + +const SUPPORTS_NOFOLLOW = fsSync.constants.O_NOFOLLOW !== undefined; +type FastGlobFn = typeof import("fast-glob"); +let fastGlobPromise: Promise | undefined; + +async function loadFastGlob(): Promise { + if (!fastGlobPromise) { + fastGlobPromise = import("fast-glob").then((mod) => { + const resolved = + (mod as unknown as { default?: FastGlobFn }).default ?? (mod as unknown as FastGlobFn); + return resolved; + }); + } + return fastGlobPromise; +} + +export class NodeFilesystemBackend implements FilesystemBackendProtocol { + private cwd: string; + private virtualMode: boolean; + private readonly contained: boolean; + private maxFileSizeBytes: number; + + constructor( + options: { + rootDir?: string; + virtualMode?: boolean; + contained?: boolean; + maxFileSizeMb?: number; + } = {}, + ) { + const { rootDir, virtualMode = true, contained = true, maxFileSizeMb = 10 } = options; + this.cwd = rootDir ? path.resolve(rootDir) : process.cwd(); + this.virtualMode = virtualMode; + this.contained = contained; + this.maxFileSizeBytes = maxFileSizeMb * 1024 * 1024; + } + + private resolvePath(key: string): string { + const trimmed = key.trim(); + if (!trimmed) { + throw new Error("Path cannot be empty"); + } + + const normalized = trimmed.replace(/\\/g, "/"); + const cleaned = normalized.replace(/^\/+/, ""); + const normalizedInput = path.normalize(cleaned); + + if (this.virtualMode || this.contained) { + const full = path.resolve(this.cwd, normalizedInput); + if (this.contained) { + const relative = path.relative(this.cwd, full); + if (relative.startsWith("..") || path.isAbsolute(relative)) { + throw new Error(`Path: ${full} outside root directory: ${this.cwd}`); + } + } + return full; + } + + if (path.isAbsolute(normalized)) { + return path.resolve(normalized); + } + return path.resolve(this.cwd, normalized); + } + + private isEnoentError(error: unknown): boolean { + if (!error || typeof error !== "object") { + return false; + } + return "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT"; + } + + private async assertPathContained(absolutePath: string): Promise { + if (!this.contained) { + return; + } + + let baseReal: string; + try { + baseReal = await fs.realpath(this.cwd); + } catch (error: unknown) { + if (this.isEnoentError(error)) { + throw new Error(`Root directory not found: ${this.cwd}`); + } + throw error; + } + + let targetReal: string | undefined; + try { + targetReal = await fs.realpath(absolutePath); + } catch (error: unknown) { + if (this.isEnoentError(error)) { + let parentPath = absolutePath; + while (true) { + const nextParent = path.dirname(parentPath); + if (nextParent === parentPath) { + throw new Error(`Path: ${absolutePath} outside root directory: ${this.cwd}`); + } + parentPath = nextParent; + try { + targetReal = await fs.realpath(parentPath); + break; + } catch (parentError: unknown) { + if (!this.isEnoentError(parentError)) { + throw parentError; + } + } + } + } else { + throw error; + } + } + + if (!targetReal) { + throw new Error(`Path: ${absolutePath} outside root directory: ${this.cwd}`); + } + + if (targetReal !== baseReal && !targetReal.startsWith(`${baseReal}${path.sep}`)) { + throw new Error(`Path: ${absolutePath} outside root directory: ${this.cwd}`); + } + } + + private toVirtualPath(fullPath: string, isDir: boolean): string { + const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; + let relativePath: string; + + if (fullPath.startsWith(cwdStr)) { + relativePath = fullPath.substring(cwdStr.length); + } else if (fullPath.startsWith(this.cwd)) { + relativePath = fullPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + } else { + relativePath = fullPath; + } + + relativePath = relativePath.split(path.sep).join("/"); + const virt = `/${relativePath}`; + if (!isDir) { + return virt; + } + return virt.endsWith("/") ? virt : `${virt}/`; + } + + async lsInfo(dirPath: string): Promise { + try { + const resolvedPath = this.resolvePath(dirPath); + await this.assertPathContained(resolvedPath); + const stat = await fs.lstat(resolvedPath); + + if (stat.isSymbolicLink() || !stat.isDirectory()) { + return []; + } + + const entries = await fs.readdir(resolvedPath, { withFileTypes: true }); + const results: FileInfo[] = []; + + const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; + + for (const entry of entries) { + const fullPath = path.join(resolvedPath, entry.name); + + try { + await this.assertPathContained(fullPath); + const entryStat = await fs.lstat(fullPath); + if (entryStat.isSymbolicLink()) { + continue; + } + const isFile = entryStat.isFile(); + const isDir = entryStat.isDirectory(); + + if (!this.virtualMode) { + if (isFile) { + results.push({ + path: fullPath, + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString(), + }); + } else if (isDir) { + results.push({ + path: fullPath + path.sep, + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString(), + }); + } + } else { + let relativePath: string; + if (fullPath.startsWith(cwdStr)) { + relativePath = fullPath.substring(cwdStr.length); + } else if (fullPath.startsWith(this.cwd)) { + relativePath = fullPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + } else { + relativePath = fullPath; + } + + relativePath = relativePath.split(path.sep).join("/"); + const virtPath = `/${relativePath}`; + + if (isFile) { + results.push({ + path: virtPath, + is_dir: false, + size: entryStat.size, + modified_at: entryStat.mtime.toISOString(), + }); + } else if (isDir) { + results.push({ + path: `${virtPath}/`, + is_dir: true, + size: 0, + modified_at: entryStat.mtime.toISOString(), + }); + } + } + } catch { + // ignore entry errors + } + } + + results.sort((a, b) => a.path.localeCompare(b.path)); + return results; + } catch { + return []; + } + } + + async read(filePath: string, offset = 0, limit = 2000): Promise { + try { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + + let content: string; + + if (SUPPORTS_NOFOLLOW) { + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return `Error: Symlinks are not allowed: ${filePath}`; + } + if (!stat.isFile()) { + return `Error: File '${filePath}' not found`; + } + const fd = await fs.open( + resolvedPath, + fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW, + ); + try { + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return `Error: Symlinks are not allowed: ${filePath}`; + } + if (!stat.isFile()) { + return `Error: File '${filePath}' not found`; + } + content = await fs.readFile(resolvedPath, "utf-8"); + } + + const emptyMsg = checkEmptyContent(content); + if (emptyMsg) { + return emptyMsg; + } + + const lines = content.split("\n"); + const startIdx = offset; + const endIdx = Math.min(startIdx + limit, lines.length); + + if (startIdx >= lines.length) { + return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`; + } + + const selectedLines = lines.slice(startIdx, endIdx); + return formatContentWithLineNumbers(selectedLines, startIdx + 1); + } catch (e: any) { + return `Error reading file '${filePath}': ${e.message}`; + } + } + + async readRaw(filePath: string): Promise { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + + let content: string; + let stat: fsSync.Stats; + + if (SUPPORTS_NOFOLLOW) { + stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + throw new Error(`Symlinks are not allowed: ${filePath}`); + } + if (!stat.isFile()) throw new Error(`File '${filePath}' not found`); + const fd = await fs.open( + resolvedPath, + fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW, + ); + try { + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + throw new Error(`Symlinks are not allowed: ${filePath}`); + } + if (!stat.isFile()) throw new Error(`File '${filePath}' not found`); + content = await fs.readFile(resolvedPath, "utf-8"); + } + + return { + content: content.split("\n"), + created_at: stat.ctime.toISOString(), + modified_at: stat.mtime.toISOString(), + }; + } + + async stat(filePath: string): Promise { + try { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + const stat = await fs.lstat(resolvedPath); + + if (stat.isSymbolicLink()) { + throw new Error(`Symlinks are not allowed: ${filePath}`); + } + + const isDir = stat.isDirectory(); + const pathValue = this.virtualMode + ? this.toVirtualPath(resolvedPath, isDir) + : isDir + ? resolvedPath.endsWith(path.sep) + ? resolvedPath + : `${resolvedPath}${path.sep}` + : resolvedPath; + + return { + path: pathValue, + is_dir: isDir, + size: isDir ? 0 : stat.size, + modified_at: stat.mtime.toISOString(), + created_at: stat.ctime.toISOString(), + }; + } catch { + return null; + } + } + + async exists(filePath: string): Promise { + try { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return false; + } + return stat.isFile() || stat.isDirectory(); + } catch { + return false; + } + } + + async write(filePath: string, content: string, options?: WriteOptions): Promise { + try { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + const overwrite = options?.overwrite ?? false; + + try { + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return { + error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`, + }; + } + if (!stat.isFile()) { + return { + error: `Cannot write to ${filePath} because it is not a file.`, + }; + } + if (!overwrite) { + return { + error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`, + }; + } + } catch { + // File does not exist + } + + await fs.mkdir(path.dirname(resolvedPath), { recursive: true }); + + if (SUPPORTS_NOFOLLOW) { + const flags = + fsSync.constants.O_WRONLY | + fsSync.constants.O_CREAT | + fsSync.constants.O_TRUNC | + fsSync.constants.O_NOFOLLOW; + + const fd = await fs.open(resolvedPath, flags, 0o644); + try { + await fd.writeFile(content, "utf-8"); + } finally { + await fd.close(); + } + } else { + try { + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return { + error: `Cannot write to ${filePath} because it is a symlink. Symlinks are not allowed.`, + }; + } + if (!stat.isFile()) { + return { + error: `Cannot write to ${filePath} because it is not a file.`, + }; + } + if (!overwrite) { + return { + error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`, + }; + } + } catch { + // File does not exist + } + await fs.writeFile(resolvedPath, content, "utf-8"); + } + + return { path: filePath, filesUpdate: null }; + } catch (e: any) { + return { error: `Error writing file '${filePath}': ${e.message}` }; + } + } + + async mkdir(dirPath: string, recursive = true): Promise { + try { + const resolvedPath = this.resolvePath(dirPath); + await this.assertPathContained(resolvedPath); + try { + const existing = await fs.lstat(resolvedPath); + if (existing.isSymbolicLink()) { + return { error: `Cannot create directory '${dirPath}' because it is a symlink.` }; + } + if (existing.isDirectory()) { + const pathValue = this.virtualMode + ? this.toVirtualPath(resolvedPath, true) + : resolvedPath.endsWith(path.sep) + ? resolvedPath + : `${resolvedPath}${path.sep}`; + return { path: pathValue }; + } + return { + error: `Cannot create directory '${dirPath}' because a file exists at that path.`, + }; + } catch { + // does not exist + } + + await fs.mkdir(resolvedPath, { recursive }); + const pathValue = this.virtualMode + ? this.toVirtualPath(resolvedPath, true) + : resolvedPath.endsWith(path.sep) + ? resolvedPath + : `${resolvedPath}${path.sep}`; + return { path: pathValue }; + } catch (error: any) { + return { + error: `Error creating directory '${dirPath}': ${error?.message ? String(error.message) : "unknown error"}`, + }; + } + } + + async edit( + filePath: string, + oldString: string, + newString: string, + replaceAll = false, + ): Promise { + try { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + + let content: string; + + if (SUPPORTS_NOFOLLOW) { + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return { error: `Error: Symlinks are not allowed: ${filePath}` }; + } + if (!stat.isFile()) { + return { error: `Error: File '${filePath}' not found` }; + } + + const fd = await fs.open( + resolvedPath, + fsSync.constants.O_RDONLY | fsSync.constants.O_NOFOLLOW, + ); + try { + content = await fd.readFile({ encoding: "utf-8" }); + } finally { + await fd.close(); + } + } else { + const stat = await fs.lstat(resolvedPath); + if (stat.isSymbolicLink()) { + return { error: `Error: Symlinks are not allowed: ${filePath}` }; + } + if (!stat.isFile()) { + return { error: `Error: File '${filePath}' not found` }; + } + content = await fs.readFile(resolvedPath, "utf-8"); + } + + const result = performStringReplacement(content, oldString, newString, replaceAll); + + if (typeof result === "string") { + return { error: result }; + } + + const [newContent, occurrences] = result; + + if (SUPPORTS_NOFOLLOW) { + const flags = + fsSync.constants.O_WRONLY | fsSync.constants.O_TRUNC | fsSync.constants.O_NOFOLLOW; + + const fd = await fs.open(resolvedPath, flags); + try { + await fd.writeFile(newContent, "utf-8"); + } finally { + await fd.close(); + } + } else { + await fs.writeFile(resolvedPath, newContent, "utf-8"); + } + + return { path: filePath, filesUpdate: null, occurrences: occurrences }; + } catch (e: any) { + return { error: `Error editing file '${filePath}': ${e.message}` }; + } + } + + async delete(filePath: string, options?: DeleteOptions): Promise { + try { + const resolvedPath = this.resolvePath(filePath); + await this.assertPathContained(resolvedPath); + const stat = await fs.lstat(resolvedPath); + + if (stat.isSymbolicLink()) { + return { error: `Error: Symlinks are not allowed: ${filePath}` }; + } + + if (stat.isDirectory()) { + if (!options?.recursive) { + return { error: `Error: '${filePath}' is a directory` }; + } + await fs.rm(resolvedPath, { recursive: true, force: false }); + return { path: filePath, filesUpdate: null }; + } + + if (!stat.isFile()) { + return { error: `Error: File '${filePath}' not found` }; + } + + await fs.unlink(resolvedPath); + return { path: filePath, filesUpdate: null }; + } catch (e: any) { + return { error: `Error deleting file '${filePath}': ${e.message}` }; + } + } + + async rmdir(dirPath: string, recursive = false): Promise { + try { + const resolvedPath = this.resolvePath(dirPath); + await this.assertPathContained(resolvedPath); + const stat = await fs.lstat(resolvedPath); + + if (stat.isSymbolicLink()) { + return { error: `Error: Symlinks are not allowed: ${dirPath}` }; + } + + if (!stat.isDirectory()) { + return { error: `Error: Directory '${dirPath}' not found` }; + } + + if (recursive) { + await fs.rm(resolvedPath, { recursive: true, force: false }); + } else { + await fs.rmdir(resolvedPath); + } + + return { path: dirPath }; + } catch (e: any) { + return { error: `Error removing directory '${dirPath}': ${e.message}` }; + } + } + + async grepRaw( + pattern: string, + dirPath = "/", + glob: string | null = null, + ): Promise { + const safety = assessRegexPattern(pattern); + const useLiteral = !safety.safe; + if (!useLiteral) { + try { + new RegExp(pattern); + } catch (e: any) { + return `Invalid regex pattern: ${e.message}`; + } + } + + let baseFull: string; + try { + baseFull = this.resolvePath(dirPath || "."); + await this.assertPathContained(baseFull); + } catch { + return []; + } + + try { + await fs.lstat(baseFull); + } catch { + return []; + } + + let results = await this.ripgrepSearch(pattern, baseFull, glob, useLiteral); + if (results === null) { + results = await this.fallbackSearch(pattern, baseFull, glob, useLiteral); + } + + const matches: GrepMatch[] = []; + for (const [filePath, items] of Object.entries(results)) { + for (const [lineNum, lineText] of items) { + matches.push({ path: filePath, line: lineNum, text: lineText }); + } + } + return matches; + } + + private async ripgrepSearch( + pattern: string, + baseFull: string, + includeGlob: string | null, + literal = false, + ): Promise> | null> { + return new Promise((resolve) => { + const args = ["--json"]; + if (literal) { + args.push("-F"); + } + if (includeGlob) { + args.push("--glob", includeGlob); + } + args.push("--", pattern, baseFull); + + const proc = spawn("rg", args, { timeout: 30000 }); + const results: Record> = {}; + let buffer = ""; + let matchCount = 0; + let resolved = false; + + const finish = (value: Record> | null) => { + if (resolved) { + return; + } + resolved = true; + resolve(value); + }; + + const handleLine = (line: string) => { + if (!line.trim()) { + return; + } + try { + const data = JSON.parse(line); + if (data.type !== "match") { + return; + } + + const pdata = data.data || {}; + const ftext = pdata.path?.text; + if (!ftext) { + return; + } + + let virtPath: string | undefined; + if (this.virtualMode) { + try { + const resolvedPath = path.resolve(ftext); + const relative = path.relative(this.cwd, resolvedPath); + if (relative.startsWith("..")) { + return; + } + const normalizedRelative = relative.split(path.sep).join("/"); + virtPath = `/${normalizedRelative}`; + } catch { + return; + } + } else { + virtPath = ftext; + } + + if (!virtPath) { + return; + } + + const ln = pdata.line_number; + const lt = pdata.lines?.text?.replace(/\n$/, "") || ""; + if (ln === undefined) { + return; + } + + if (!results[virtPath]) { + results[virtPath] = []; + } + results[virtPath].push([ln, lt]); + matchCount += 1; + if (matchCount >= MAX_GREP_MATCHES) { + try { + proc.kill(); + } catch { + // ignore kill failures + } + finish(results); + } + } catch { + // ignore parse errors + } + }; + + proc.stdout.on("data", (data) => { + if (resolved) { + return; + } + buffer += data.toString(); + const lines = buffer.split("\n"); + buffer = lines.pop() || ""; + for (const line of lines) { + handleLine(line); + if (resolved) { + return; + } + } + }); + + proc.on("close", (code) => { + if (resolved) { + return; + } + if (code !== 0 && code !== 1) { + finish(null); + return; + } + + if (buffer.trim()) { + handleLine(buffer); + } + finish(results); + }); + + proc.on("error", () => { + finish(null); + }); + }); + } + + private async fallbackSearch( + pattern: string, + baseFull: string, + includeGlob: string | null, + forceLiteral = false, + ): Promise>> { + const safety = assessRegexPattern(pattern); + const useLiteral = forceLiteral || !safety.safe; + + let regex: RegExp | null = null; + if (!useLiteral) { + try { + regex = new RegExp(pattern); + } catch { + return {}; + } + } + + const results: Record> = {}; + const stat = await fs.lstat(baseFull); + const root = stat.isDirectory() ? baseFull : path.dirname(baseFull); + + const fg = await loadFastGlob(); + const files = await fg("**/*", { + cwd: root, + absolute: true, + onlyFiles: true, + dot: true, + followSymbolicLinks: false, + }); + + let matchCount = 0; + for (const fp of files) { + try { + if (includeGlob) { + const relativePath = path.relative(root, fp); + const normalizedRelative = relativePath.split(path.sep).join("/"); + if (!micromatch.isMatch(normalizedRelative, includeGlob)) { + continue; + } + } + + const stat = await fs.lstat(fp); + if (stat.isSymbolicLink()) { + continue; + } + await this.assertPathContained(fp); + if (stat.size > this.maxFileSizeBytes) { + continue; + } + + const content = await fs.readFile(fp, "utf-8"); + const lines = content.split("\n"); + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + if (matchCount >= MAX_GREP_MATCHES) { + return results; + } + const candidate = + line.length > MAX_GREP_LINE_LENGTH ? line.slice(0, MAX_GREP_LINE_LENGTH) : line; + let matched = false; + if (useLiteral) { + matched = candidate.includes(pattern); + } else if (regex) { + try { + matched = regex.test(candidate); + } catch { + matched = false; + } + } + if (matched) { + let virtPath: string | undefined; + if (this.virtualMode) { + try { + const relative = path.relative(this.cwd, fp); + if (relative.startsWith("..")) continue; + const normalizedRelative = relative.split(path.sep).join("/"); + virtPath = `/${normalizedRelative}`; + } catch { + // ignore path errors + } + } else { + virtPath = fp; + } + + if (!virtPath) { + continue; + } + + if (!results[virtPath]) { + results[virtPath] = []; + } + results[virtPath].push([i + 1, line]); + matchCount++; + if (matchCount >= MAX_GREP_MATCHES) { + return results; + } + } + } + } catch { + // ignore file errors + } + } + + return results; + } + + async globInfo(pattern: string, searchPath = "/"): Promise { + let effectivePattern = pattern; + if (effectivePattern.startsWith("/")) { + effectivePattern = effectivePattern.substring(1); + } + + const resolvedSearchPath = searchPath === "/" ? this.cwd : this.resolvePath(searchPath); + + try { + await this.assertPathContained(resolvedSearchPath); + const stat = await fs.lstat(resolvedSearchPath); + if (stat.isSymbolicLink() || !stat.isDirectory()) { + return []; + } + } catch { + return []; + } + + const results: FileInfo[] = []; + + try { + const fg = await loadFastGlob(); + const matches = await fg(effectivePattern, { + cwd: resolvedSearchPath, + absolute: true, + onlyFiles: true, + dot: true, + followSymbolicLinks: false, + }); + + for (const matchedPath of matches) { + try { + await this.assertPathContained(matchedPath); + const stat = await fs.lstat(matchedPath); + if (stat.isSymbolicLink()) continue; + if (!stat.isFile()) continue; + + const normalizedPath = matchedPath.split("/").join(path.sep); + + if (!this.virtualMode) { + results.push({ + path: normalizedPath, + is_dir: false, + size: stat.size, + modified_at: stat.mtime.toISOString(), + }); + } else { + const cwdStr = this.cwd.endsWith(path.sep) ? this.cwd : this.cwd + path.sep; + let relativePath: string; + + if (normalizedPath.startsWith(cwdStr)) { + relativePath = normalizedPath.substring(cwdStr.length); + } else if (normalizedPath.startsWith(this.cwd)) { + relativePath = normalizedPath.substring(this.cwd.length).replace(/^[/\\]/, ""); + } else { + relativePath = normalizedPath; + } + + relativePath = relativePath.split(path.sep).join("/"); + const virt = `/${relativePath}`; + results.push({ + path: virt, + is_dir: false, + size: stat.size, + modified_at: stat.mtime.toISOString(), + }); + } + } catch { + // ignore file errors + } + } + } catch { + // ignore + } + + results.sort((a, b) => a.path.localeCompare(b.path)); + return results; + } +} diff --git a/packages/core/src/workspace/filesystem/backends/in-memory.ts b/packages/core/src/workspace/filesystem/backends/in-memory.ts new file mode 100644 index 000000000..b0a88406c --- /dev/null +++ b/packages/core/src/workspace/filesystem/backends/in-memory.ts @@ -0,0 +1,372 @@ +import { + createFileData, + fileDataToString, + formatReadResponse, + globSearchFiles, + grepMatchesFromFiles, + performStringReplacement, + updateFileData, +} from "../utils"; +import type { + DeleteOptions, + DeleteResult, + EditResult, + FileData, + FileInfo, + FilesystemBackend, + GrepMatch, + MkdirResult, + RmdirResult, + WriteOptions, + WriteResult, +} from "./backend"; + +export class InMemoryFilesystemBackend implements FilesystemBackend { + private files: Record; + private directories: Set; + + constructor(files: Record = {}, directories: Set = new Set()) { + this.files = files; + this.directories = directories; + } + + private getFiles(): Record { + return this.files; + } + + private getDirectories(): Set { + return this.directories; + } + + private normalizeDirPath(path: string): string { + const trimmed = path.trim(); + if (!trimmed) { + return "/"; + } + const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`; + return withSlash.endsWith("/") ? withSlash : `${withSlash}/`; + } + + private hasDirectory(path: string): boolean { + const dirPath = this.normalizeDirPath(path); + if (dirPath === "/") { + return true; + } + + if (this.directories.has(dirPath)) { + return true; + } + + const files = this.getFiles(); + return Object.keys(files).some((filePath) => filePath.startsWith(dirPath)); + } + + lsInfo(path: string): FileInfo[] { + const files = this.getFiles(); + const directories = this.getDirectories(); + const infos: FileInfo[] = []; + const subdirs = new Set(); + + const normalizedPath = path.endsWith("/") ? path : `${path}/`; + + for (const [filePath, fd] of Object.entries(files)) { + if (!filePath.startsWith(normalizedPath)) { + continue; + } + + const relative = filePath.substring(normalizedPath.length); + if (relative.includes("/")) { + const subdirName = relative.split("/")[0]; + subdirs.add(`${normalizedPath}${subdirName}/`); + continue; + } + + const size = fd.content.join("\n").length; + infos.push({ + path: filePath, + is_dir: false, + size: size, + modified_at: fd.modified_at, + }); + } + + for (const dirPath of directories) { + if (!dirPath.startsWith(normalizedPath) || dirPath === normalizedPath) { + continue; + } + + const relative = dirPath.substring(normalizedPath.length); + if (!relative) { + continue; + } + + if (relative.includes("/")) { + const subdirName = relative.split("/")[0]; + subdirs.add(`${normalizedPath}${subdirName}/`); + } else { + subdirs.add(dirPath); + } + } + + for (const subdir of Array.from(subdirs).sort()) { + infos.push({ + path: subdir, + is_dir: true, + size: 0, + modified_at: "", + }); + } + + infos.sort((a, b) => a.path.localeCompare(b.path)); + return infos; + } + + read(filePath: string, offset = 0, limit = 2000): string { + const files = this.getFiles(); + const fileData = files[filePath]; + + if (!fileData) { + if (this.hasDirectory(filePath)) { + return `Error: '${filePath}' is a directory`; + } + return `Error: File '${filePath}' not found`; + } + + return formatReadResponse(fileData, offset, limit); + } + + readRaw(filePath: string): FileData { + const files = this.getFiles(); + const fileData = files[filePath]; + + if (!fileData) { + if (this.hasDirectory(filePath)) { + throw new Error(`'${filePath}' is a directory`); + } + throw new Error(`File '${filePath}' not found`); + } + return fileData; + } + + stat(filePath: string): FileInfo | null { + const files = this.getFiles(); + const fileData = files[filePath]; + + if (fileData) { + const size = fileData.content.join("\n").length; + return { + path: filePath, + is_dir: false, + size, + modified_at: fileData.modified_at, + created_at: fileData.created_at, + }; + } + + if (this.hasDirectory(filePath)) { + return { + path: this.normalizeDirPath(filePath), + is_dir: true, + size: 0, + modified_at: "", + }; + } + + return null; + } + + exists(filePath: string): boolean { + const files = this.getFiles(); + return Boolean(files[filePath]) || this.hasDirectory(filePath); + } + + write(filePath: string, content: string, options?: WriteOptions): WriteResult { + const files = this.getFiles(); + const overwrite = options?.overwrite ?? false; + + if (this.hasDirectory(filePath) || filePath.endsWith("/")) { + return { + error: `Cannot write to ${filePath} because it is a directory.`, + }; + } + + if (filePath in files && !overwrite) { + return { + error: `Cannot write to ${filePath} because it already exists. Read and then make an edit, or write to a new path.`, + }; + } + + const newFileData = + filePath in files ? updateFileData(files[filePath], content) : createFileData(content); + return { + path: filePath, + filesUpdate: { [filePath]: newFileData }, + }; + } + + edit(filePath: string, oldString: string, newString: string, replaceAll = false): EditResult { + const files = this.getFiles(); + const fileData = files[filePath]; + + if (!fileData) { + if (this.hasDirectory(filePath)) { + return { error: `Error: '${filePath}' is a directory` }; + } + return { error: `Error: File '${filePath}' not found` }; + } + + const content = fileDataToString(fileData); + const result = performStringReplacement(content, oldString, newString, replaceAll); + + if (typeof result === "string") { + return { error: result }; + } + + const [newContent, occurrences] = result; + const newFileData = updateFileData(fileData, newContent); + return { + path: filePath, + filesUpdate: { [filePath]: newFileData }, + occurrences: occurrences, + }; + } + + delete(filePath: string, options?: DeleteOptions): DeleteResult { + const files = this.getFiles(); + const recursive = options?.recursive ?? false; + + if (!(filePath in files)) { + if (this.hasDirectory(filePath)) { + if (!recursive) { + return { error: `Error: '${filePath}' is a directory` }; + } + + const dirPath = this.normalizeDirPath(filePath); + const updates: Record = {}; + for (const key of Object.keys(files)) { + if (key.startsWith(dirPath)) { + updates[key] = null; + } + } + for (const dir of Array.from(this.directories)) { + if (dir.startsWith(dirPath)) { + this.directories.delete(dir); + } + } + + return { + path: dirPath, + filesUpdate: updates, + }; + } + return { error: `Error: File '${filePath}' not found` }; + } + + return { + path: filePath, + filesUpdate: { [filePath]: null }, + }; + } + + grepRaw(pattern: string, path = "/", glob: string | null = null): GrepMatch[] | string { + const files = this.getFiles(); + return grepMatchesFromFiles(files, pattern, path, glob); + } + + globInfo(pattern: string, path = "/"): FileInfo[] { + const files = this.getFiles(); + const result = globSearchFiles(files, pattern, path); + + if (result === "No files found") { + return []; + } + + const paths = result.split("\n"); + const infos: FileInfo[] = []; + for (const filePath of paths) { + const fd = files[filePath]; + const size = fd ? fd.content.join("\n").length : 0; + infos.push({ + path: filePath, + is_dir: false, + size: size, + modified_at: fd?.modified_at || "", + }); + } + return infos; + } + + mkdir(path: string, recursive = true): MkdirResult { + const files = this.getFiles(); + const dirPath = this.normalizeDirPath(path); + + if (dirPath === "/") { + return { path: dirPath }; + } + + const fileCollision = files[dirPath.slice(0, -1)]; + if (fileCollision) { + return { error: `Cannot create directory ${dirPath} because a file exists at that path.` }; + } + + if (this.hasDirectory(dirPath)) { + return { path: dirPath }; + } + + if (!recursive) { + const trimmed = dirPath.slice(0, -1); + const lastSlash = trimmed.lastIndexOf("/"); + const parent = lastSlash <= 0 ? "/" : `${trimmed.slice(0, lastSlash)}/`; + if (!this.hasDirectory(parent)) { + return { + error: `Parent directory '${parent}' does not exist. Use recursive=true to create it.`, + }; + } + } + + this.directories.add(dirPath); + return { path: dirPath }; + } + + rmdir(path: string, recursive = false): RmdirResult { + const dirPath = this.normalizeDirPath(path); + + if (dirPath === "/") { + return { error: "Cannot remove root directory '/'." }; + } + + if (!this.hasDirectory(dirPath)) { + return { error: `Directory '${dirPath}' not found.` }; + } + + const files = this.getFiles(); + const hasChildren = Object.keys(files).some((filePath) => filePath.startsWith(dirPath)); + const hasSubdirs = Array.from(this.directories).some( + (child) => child !== dirPath && child.startsWith(dirPath), + ); + + if ((hasChildren || hasSubdirs) && !recursive) { + return { + error: `Directory '${dirPath}' is not empty. Use recursive=true to remove it.`, + }; + } + + const updates: Record = {}; + if (recursive) { + for (const key of Object.keys(files)) { + if (key.startsWith(dirPath)) { + updates[key] = null; + } + } + for (const dir of Array.from(this.directories)) { + if (dir.startsWith(dirPath)) { + this.directories.delete(dir); + } + } + } else { + this.directories.delete(dirPath); + } + + return { path: dirPath, filesUpdate: Object.keys(updates).length > 0 ? updates : null }; + } +} diff --git a/packages/core/src/workspace/filesystem/index.spec.ts b/packages/core/src/workspace/filesystem/index.spec.ts new file mode 100644 index 000000000..173949219 --- /dev/null +++ b/packages/core/src/workspace/filesystem/index.spec.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { WorkspaceFilesystem } from "./index"; + +describe("WorkspaceFilesystem", () => { + it("writes, reads, edits, and deletes files", async () => { + const filesystem = new WorkspaceFilesystem(); + + const writeResult = await filesystem.write("/notes/summary.md", "hello", { + ensureDirs: true, + }); + expect(writeResult.error).toBeUndefined(); + + const readResult = await filesystem.read("/notes/summary.md"); + expect(readResult).toContain("hello"); + + const editResult = await filesystem.edit("/notes/summary.md", "hello", "hi"); + expect(editResult.error).toBeUndefined(); + + const updated = await filesystem.read("/notes/summary.md"); + expect(updated).toContain("hi"); + + const deleteResult = await filesystem.delete("/notes/summary.md"); + expect(deleteResult.error).toBeUndefined(); + + const list = await filesystem.lsInfo("/notes"); + const fileNames = list.map((entry) => entry.path); + expect(fileNames).not.toContain("/notes/summary.md"); + }); + + it("blocks write operations when read-only", async () => { + const filesystem = new WorkspaceFilesystem({ + readOnly: true, + files: { "/notes/a.txt": "hello" }, + }); + + const writeResult = await filesystem.write("/notes/b.txt", "blocked"); + expect(writeResult.error).toContain("read-only"); + }); +}); diff --git a/packages/core/src/workspace/filesystem/index.ts b/packages/core/src/workspace/filesystem/index.ts new file mode 100644 index 000000000..5ffd424e9 --- /dev/null +++ b/packages/core/src/workspace/filesystem/index.ts @@ -0,0 +1,1251 @@ +import type { Span } from "@opentelemetry/api"; +import { z } from "zod"; +import type { Agent } from "../../agent/agent"; +import type { OperationContext } from "../../agent/types"; +import { createTool } from "../../tool"; +import { createToolkit } from "../../tool/toolkit"; +import type { Toolkit } from "../../tool/toolkit"; +import { withOperationTimeout } from "../timeout"; +import type { + WorkspaceFilesystemToolPolicy, + WorkspaceToolPolicies, + WorkspaceToolPolicyGroup, +} from "../tool-policy"; +import type { WorkspaceComponentStatus, WorkspaceIdentity } from "../types"; +import type { + DeleteResult, + EditResult, + FileData, + FileInfo, + FilesystemBackend, + FilesystemBackendContext, + FilesystemBackendFactory, + GrepMatch, + MkdirResult, + RmdirResult, + WriteResult, +} from "./backends/backend"; +import { CompositeFilesystemBackend } from "./backends/composite"; +import { NodeFilesystemBackend } from "./backends/filesystem"; +import { InMemoryFilesystemBackend } from "./backends/in-memory"; +import { formatGrepMatches, truncateIfTooLong } from "./utils"; + +export type { + DeleteOptions, + DeleteResult, + EditResult, + FileData, + FileInfo, + FilesystemBackend, + FilesystemBackendContext, + FilesystemBackendFactory, + GrepMatch, + MkdirResult, + RmdirResult, + WriteOptions, + WriteResult, +} from "./backends/backend"; +export { InMemoryFilesystemBackend, CompositeFilesystemBackend, NodeFilesystemBackend }; + +const WORKSPACE_FILESYSTEM_SYSTEM_PROMPT = `You have access to a workspace filesystem. All file paths must start with a /. + +- ls: list files in a directory (requires absolute path) +- read_file: read a file from the filesystem +- write_file: write to a file in the filesystem +- edit_file: edit a file in the filesystem +- delete_file: delete a file from the filesystem +- stat: get file or directory metadata +- mkdir: create a directory +- rmdir: remove a directory +- list_tree: list files and directories with depth control +- list_files: list files and directories with depth control (alias) +- glob: find files matching a pattern (e.g., "**/*.ts") +- grep: search for text within files`; + +const LS_TOOL_DESCRIPTION = "List files and directories in a directory"; +const READ_FILE_TOOL_DESCRIPTION = "Read the contents of a file"; +const WRITE_FILE_TOOL_DESCRIPTION = + "Write content to a file. Returns an error if the file already exists unless overwrite=true; can create parent directories"; +const EDIT_FILE_TOOL_DESCRIPTION = "Edit a file by replacing a specific string with a new string"; +const DELETE_FILE_TOOL_DESCRIPTION = + "Delete a file from the filesystem. Use recursive=true to remove a directory"; +const STAT_TOOL_DESCRIPTION = "Get file or directory metadata"; +const MKDIR_TOOL_DESCRIPTION = "Create a directory in the filesystem"; +const RMDIR_TOOL_DESCRIPTION = "Remove a directory from the filesystem"; +const LIST_TREE_TOOL_DESCRIPTION = + "List files and directories recursively with optional depth control"; +const LIST_FILES_TOOL_DESCRIPTION = + "List files and directories recursively with optional depth control"; +const GLOB_TOOL_DESCRIPTION = + "Find files matching a glob pattern (e.g., '**/*.ts' for all TypeScript files)"; +const GREP_TOOL_DESCRIPTION = + "Search for a regex pattern in files. Returns matching files and line numbers"; +const WORKSPACE_FILESYSTEM_TAGS = ["workspace", "filesystem"] as const; +const WORKSPACE_FS_READ_PATHS_KEY = Symbol("workspace.fs.readPaths"); +const READ_ONLY_BLOCKED_TOOLS = new Set([ + "write_file", + "edit_file", + "delete_file", + "mkdir", + "rmdir", +]); + +export type WorkspaceFilesystemToolName = + | "ls" + | "read_file" + | "write_file" + | "edit_file" + | "delete_file" + | "stat" + | "mkdir" + | "rmdir" + | "list_tree" + | "list_files" + | "glob" + | "grep"; + +export type WorkspaceFilesystemToolkitOptions = { + systemPrompt?: string | null; + operationTimeoutMs?: number; + customToolDescriptions?: Partial> | null; + toolPolicies?: WorkspaceToolPolicies< + WorkspaceFilesystemToolName, + WorkspaceFilesystemToolPolicy + > | null; +}; + +export type WorkspaceFilesystemOptions = { + backend?: FilesystemBackend | FilesystemBackendFactory; + files?: Record; + directories?: string[]; + readOnly?: boolean; +}; + +export type WorkspaceFilesystemCallContext = { + agent?: Agent; + operationContext?: OperationContext; +}; + +export type WorkspaceFilesystemReadOptions = { + offset?: number; + limit?: number; + context?: WorkspaceFilesystemCallContext; +}; + +export type WorkspaceFilesystemWriteOptions = { + overwrite?: boolean; + ensureDirs?: boolean; + context?: WorkspaceFilesystemCallContext; +}; + +export type WorkspaceFilesystemSearchOptions = { + path?: string; + glob?: string | null; + context?: WorkspaceFilesystemCallContext; +}; + +export type WorkspaceFilesystemOperationOptions = { + context?: WorkspaceFilesystemCallContext; +}; + +export type WorkspaceFilesystemDeleteOptions = { + recursive?: boolean; + context?: WorkspaceFilesystemCallContext; +}; + +export type WorkspaceFilesystemRmdirOptions = { + recursive?: boolean; + context?: WorkspaceFilesystemCallContext; +}; + +export type WorkspaceFilesystemToolkitContext = { + filesystem: WorkspaceFilesystem; + workspace?: WorkspaceIdentity; + agent?: Agent; +}; + +const resolveBackend = ( + backend: FilesystemBackend | FilesystemBackendFactory, + context: FilesystemBackendContext, +): FilesystemBackend => { + if (typeof backend === "function") { + return backend(context); + } + return backend; +}; + +const applyFilesUpdate = ( + current: Record, + update?: Record | null, +): Record => { + if (!update) { + return current; + } + + const result: Record = { ...current }; + for (const [key, value] of Object.entries(update)) { + if (value === null) { + delete result[key]; + } else { + result[key] = value; + } + } + return result; +}; + +export class WorkspaceFilesystem { + private backend: FilesystemBackend | FilesystemBackendFactory; + private files: Record; + private directories: Set; + readonly readOnly: boolean; + status: WorkspaceComponentStatus = "idle"; + + constructor(options: WorkspaceFilesystemOptions = {}) { + this.backend = + options.backend || + ((context: FilesystemBackendContext) => + new InMemoryFilesystemBackend( + context.state.files || {}, + context.state.directories || new Set(), + )); + this.files = options.files ?? {}; + this.directories = new Set( + (options.directories ?? []).map((dir) => this.normalizeDirectoryPath(dir)), + ); + this.readOnly = options.readOnly ?? false; + } + + private normalizeDirectoryPath(path: string): string { + const trimmed = path.trim(); + if (!trimmed) { + return "/"; + } + const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`; + return withSlash.endsWith("/") ? withSlash : `${withSlash}/`; + } + + private buildBackendContext(context?: WorkspaceFilesystemCallContext): FilesystemBackendContext { + return { + agent: context?.agent, + operationContext: context?.operationContext, + state: { + files: this.files, + directories: this.directories, + }, + }; + } + + private updateFiles(update?: Record | null): void { + this.files = applyFilesUpdate(this.files, update); + } + + init(): void { + if (this.status === "destroyed") { + throw new Error("Workspace filesystem has been destroyed."); + } + this.status = "ready"; + } + + destroy(): void { + this.status = "destroyed"; + } + + getInfo(): Record { + const backendName = + typeof this.backend === "function" + ? "factory" + : (this.backend?.constructor?.name ?? "unknown"); + return { + backend: backendName, + readOnly: this.readOnly, + fileCount: Object.keys(this.files).length, + directoryCount: this.directories.size, + }; + } + + getInstructions(): string { + return WORKSPACE_FILESYSTEM_SYSTEM_PROMPT; + } + + async lsInfo(path = "/", options?: WorkspaceFilesystemOperationOptions): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + return await backend.lsInfo(path); + } + + async read(filePath: string, options?: WorkspaceFilesystemReadOptions): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + return await backend.read(filePath, options?.offset ?? 0, options?.limit ?? 2000); + } + + async readRaw( + filePath: string, + options?: WorkspaceFilesystemOperationOptions, + ): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + return await backend.readRaw(filePath); + } + + async write( + filePath: string, + content: string, + options?: WorkspaceFilesystemWriteOptions, + ): Promise { + if (this.readOnly) { + return { error: "Workspace filesystem is read-only." }; + } + if (options?.ensureDirs) { + const normalized = filePath.replace(/\\/g, "/"); + const lastSlash = normalized.lastIndexOf("/"); + const parent = lastSlash <= 0 ? "/" : normalized.slice(0, lastSlash) || "/"; + await this.mkdir(parent, true, { context: options.context }); + } + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + const result = await backend.write(filePath, content, { overwrite: options?.overwrite }); + if (!result.error) { + this.updateFiles(result.filesUpdate ?? undefined); + } + return result; + } + + async edit( + filePath: string, + oldString: string, + newString: string, + replaceAll = false, + options?: WorkspaceFilesystemOperationOptions, + ): Promise { + if (this.readOnly) { + return { error: "Workspace filesystem is read-only." }; + } + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + const result = await backend.edit(filePath, oldString, newString, replaceAll); + if (!result.error) { + this.updateFiles(result.filesUpdate ?? undefined); + } + return result; + } + + async delete( + filePath: string, + options?: WorkspaceFilesystemDeleteOptions, + ): Promise { + if (this.readOnly) { + return { error: "Workspace filesystem is read-only." }; + } + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + if (!backend.delete) { + return { error: "Delete operation is not supported by the configured filesystem backend." }; + } + const result = await backend.delete(filePath, { recursive: options?.recursive }); + if (!result.error) { + this.updateFiles(result.filesUpdate ?? undefined); + } + return result; + } + + async globInfo( + pattern: string, + path = "/", + options?: WorkspaceFilesystemOperationOptions, + ): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + return await backend.globInfo(pattern, path); + } + + async stat( + filePath: string, + options?: WorkspaceFilesystemOperationOptions, + ): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + if (!backend.stat) { + return null; + } + return await backend.stat(filePath); + } + + async exists(filePath: string, options?: WorkspaceFilesystemOperationOptions): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + if (backend.exists) { + return await backend.exists(filePath); + } + if (backend.stat) { + const info = await backend.stat(filePath); + return Boolean(info); + } + try { + await backend.readRaw(filePath); + return true; + } catch { + return false; + } + } + + async mkdir( + path: string, + recursive = true, + options?: WorkspaceFilesystemOperationOptions, + ): Promise { + if (this.readOnly) { + return { error: "Workspace filesystem is read-only." }; + } + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + if (!backend.mkdir) { + return { error: "Mkdir operation is not supported by the configured filesystem backend." }; + } + return await backend.mkdir(path, recursive); + } + + async rmdir( + path: string, + recursive = false, + options?: WorkspaceFilesystemRmdirOptions, + ): Promise { + if (this.readOnly) { + return { error: "Workspace filesystem is read-only." }; + } + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + if (!backend.rmdir) { + return { error: "Rmdir operation is not supported by the configured filesystem backend." }; + } + const result = await backend.rmdir(path, recursive); + if (!result.error) { + this.updateFiles(result.filesUpdate ?? undefined); + } + return result; + } + + async grepRaw( + pattern: string, + options?: WorkspaceFilesystemSearchOptions, + ): Promise { + const backend = resolveBackend(this.backend, this.buildBackendContext(options?.context)); + return await backend.grepRaw(pattern, options?.path, options?.glob ?? null); + } +} + +const setWorkspaceSpanAttributes = ( + operationContext: OperationContext, + attributes: Record, +): void => { + const toolSpan = operationContext.systemContext.get("parentToolSpan") as Span | undefined; + if (!toolSpan) { + return; + } + + for (const [key, value] of Object.entries(attributes)) { + if (value !== undefined) { + toolSpan.setAttribute(key, value as never); + } + } +}; + +const buildWorkspaceAttributes = (workspace?: WorkspaceIdentity): Record => ({ + "workspace.id": workspace?.id, + "workspace.name": workspace?.name, + "workspace.scope": workspace?.scope, +}); + +const formatLsOutput = (infos: FileInfo[]): string => { + if (infos.length === 0) { + return "No files found"; + } + + const lines: string[] = []; + for (const info of infos) { + if (info.is_dir) { + lines.push(`${info.path} (directory)`); + } else { + const size = info.size ? ` (${info.size} bytes)` : ""; + lines.push(`${info.path}${size}`); + } + } + return lines.join("\n"); +}; + +const formatGlobOutput = (infos: FileInfo[], pattern: string): string => { + if (infos.length === 0) { + return `No files found matching pattern '${pattern}'`; + } + return infos.map((info) => info.path).join("\n"); +}; + +const formatGrepOutput = (result: GrepMatch[] | string, pattern: string): string => { + if (typeof result === "string") { + return result; + } + + if (result.length === 0) { + return `No matches found for pattern '${pattern}'`; + } + + return formatGrepMatches(result, "content"); +}; + +const formatStatOutput = (info: FileInfo | null, inputPath: string): string => { + if (!info) { + return `No file or directory found at '${inputPath}'`; + } + + const lines = [`path: ${info.path}`, `type: ${info.is_dir ? "directory" : "file"}`]; + + if (!info.is_dir && info.size !== undefined) { + lines.push(`size: ${info.size} bytes`); + } + + if (info.created_at) { + lines.push(`created_at: ${info.created_at}`); + } + + if (info.modified_at) { + lines.push(`modified_at: ${info.modified_at}`); + } + + return lines.join("\n"); +}; + +const normalizeTrackedPath = (path: string): string => { + const trimmed = path.trim(); + if (!trimmed) { + return "/"; + } + return trimmed.startsWith("/") ? trimmed : `/${trimmed}`; +}; + +type ReadPathRecord = { + modifiedAt?: string | null; +}; + +const getReadPaths = (operationContext: OperationContext): Map => { + let readPaths = operationContext.systemContext.get(WORKSPACE_FS_READ_PATHS_KEY) as + | Map + | undefined; + if (!readPaths) { + readPaths = new Map(); + operationContext.systemContext.set(WORKSPACE_FS_READ_PATHS_KEY, readPaths); + } + return readPaths; +}; + +const recordReadPath = ( + operationContext: OperationContext, + filePath: string, + modifiedAt?: string | null, +): void => { + const readPaths = getReadPaths(operationContext); + readPaths.set(normalizeTrackedPath(filePath), { modifiedAt: modifiedAt ?? null }); +}; + +const enforceReadBeforeWrite = async ( + operationContext: OperationContext, + filesystem: WorkspaceFilesystem, + filePath: string, + requireReadBeforeWrite?: boolean, + context?: WorkspaceFilesystemCallContext, +): Promise => { + if (!requireReadBeforeWrite) { + return null; + } + + const normalized = normalizeTrackedPath(filePath); + const info = await filesystem.stat(normalized, { context }); + if (!info) { + return null; + } + if (info.is_dir) { + return null; + } + + const readPaths = getReadPaths(operationContext); + const record = readPaths.get(normalized); + if (!record) { + return `Error: Please read '${normalized}' with read_file before modifying it.`; + } + if (info.modified_at && record.modifiedAt && info.modified_at !== record.modifiedAt) { + return `Error: '${normalized}' has changed since it was last read. Read it again before modifying.`; + } + + return null; +}; + +type WorkspaceFilesystemToolCreateOptions = { + customDescription?: string | undefined; + needsApproval?: WorkspaceFilesystemToolPolicy["needsApproval"]; + operationTimeoutMs?: number; +}; + +type WorkspaceFilesystemWritePolicyOptions = WorkspaceFilesystemToolCreateOptions & { + requireReadBeforeWrite?: boolean; +}; + +const createLsTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolCreateOptions, +) => + createTool({ + name: "ls", + description: options.customDescription || LS_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + path: z.string().optional().default("/").describe("Directory path to list (default: /)"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.list", + "workspace.fs.path": input.path || "/", + }); + const infos = await context.filesystem.lsInfo(input.path || "/", { + context: { agent: context.agent, operationContext }, + }); + return formatLsOutput(infos); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createReadFileTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolCreateOptions, +) => + createTool({ + name: "read_file", + description: options.customDescription || READ_FILE_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + file_path: z.string().describe("Absolute path to the file to read"), + offset: z.coerce + .number() + .optional() + .default(0) + .describe("Line offset to start reading from (0-indexed)"), + limit: z.coerce.number().optional().default(2000).describe("Maximum number of lines to read"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.read", + "workspace.fs.path": input.file_path, + "workspace.fs.offset": input.offset, + "workspace.fs.limit": input.limit, + }); + const statInfo = await context.filesystem.stat(input.file_path, { + context: { agent: context.agent, operationContext }, + }); + const result = await context.filesystem.read(input.file_path, { + offset: input.offset, + limit: input.limit, + context: { agent: context.agent, operationContext }, + }); + if (statInfo && !statInfo.is_dir) { + recordReadPath(operationContext, input.file_path, statInfo.modified_at ?? null); + } + return result; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createWriteFileTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemWritePolicyOptions, +) => + createTool({ + name: "write_file", + description: options.customDescription || WRITE_FILE_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + file_path: z.string().describe("Absolute path to the file to write"), + content: z.string().describe("Content to write to the file"), + overwrite: z + .boolean() + .optional() + .default(false) + .describe("Whether to overwrite the file if it already exists"), + create_parent_dirs: z + .boolean() + .optional() + .default(true) + .describe("Whether to create parent directories if needed"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + const guardError = await enforceReadBeforeWrite( + operationContext, + context.filesystem, + input.file_path, + options.requireReadBeforeWrite, + { agent: context.agent, operationContext }, + ); + if (guardError) { + return guardError; + } + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.write", + "workspace.fs.path": input.file_path, + "workspace.fs.bytes": input.content.length, + }); + const result = await context.filesystem.write(input.file_path, input.content, { + overwrite: input.overwrite, + ensureDirs: input.create_parent_dirs, + context: { agent: context.agent, operationContext }, + }); + if (result.error) { + return result.error; + } + return `Successfully wrote to '${input.file_path}'`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createEditFileTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemWritePolicyOptions, +) => + createTool({ + name: "edit_file", + description: options.customDescription || EDIT_FILE_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + file_path: z.string().describe("Absolute path to the file to edit"), + old_string: z.string().describe("String to be replaced (must match exactly)"), + new_string: z.string().describe("String to replace with"), + replace_all: z + .boolean() + .optional() + .default(false) + .describe("Whether to replace all occurrences"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + const guardError = await enforceReadBeforeWrite( + operationContext, + context.filesystem, + input.file_path, + options.requireReadBeforeWrite, + { agent: context.agent, operationContext }, + ); + if (guardError) { + return guardError; + } + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.edit", + "workspace.fs.path": input.file_path, + }); + const result = await context.filesystem.edit( + input.file_path, + input.old_string, + input.new_string, + input.replace_all, + { context: { agent: context.agent, operationContext } }, + ); + if (result.error) { + return result.error; + } + setWorkspaceSpanAttributes(operationContext, { + "workspace.fs.occurrences": result.occurrences, + }); + return `Successfully replaced ${result.occurrences ?? 0} occurrence(s) in '${input.file_path}'`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createDeleteFileTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemWritePolicyOptions, +) => + createTool({ + name: "delete_file", + description: options.customDescription || DELETE_FILE_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + file_path: z.string().describe("Absolute path to the file to delete"), + recursive: z + .boolean() + .optional() + .default(false) + .describe("Whether to delete directories recursively"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + const guardError = await enforceReadBeforeWrite( + operationContext, + context.filesystem, + input.file_path, + options.requireReadBeforeWrite, + { agent: context.agent, operationContext }, + ); + if (guardError) { + return guardError; + } + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.delete", + "workspace.fs.path": input.file_path, + }); + const result = await context.filesystem.delete(input.file_path, { + recursive: input.recursive, + context: { agent: context.agent, operationContext }, + }); + if (result.error) { + return result.error; + } + return `Successfully deleted '${input.file_path}'`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createGlobTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolCreateOptions, +) => + createTool({ + name: "glob", + description: options.customDescription || GLOB_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + pattern: z.string().describe("Glob pattern (e.g., '*.ts', '**/*.ts')"), + path: z.string().optional().default("/").describe("Base path to search from (default: /)"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.glob", + "workspace.fs.path": input.path || "/", + "workspace.fs.pattern": input.pattern, + }); + const infos = await context.filesystem.globInfo(input.pattern, input.path, { + context: { agent: context.agent, operationContext }, + }); + return formatGlobOutput(infos, input.pattern); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createGrepTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolCreateOptions, +) => + createTool({ + name: "grep", + description: options.customDescription || GREP_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + pattern: z.string().describe("Regex pattern to search for"), + path: z.string().optional().default("/").describe("Base path to search from (default: /)"), + glob: z + .string() + .optional() + .nullable() + .describe("Optional glob pattern to filter files (e.g., '*.ts')"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.grep", + "workspace.fs.path": input.path || "/", + "workspace.search.query": input.pattern, + "workspace.fs.pattern": input.glob ?? undefined, + }); + const result = await context.filesystem.grepRaw(input.pattern, { + path: input.path || "/", + glob: input.glob ?? null, + context: { agent: context.agent, operationContext }, + }); + return formatGrepOutput(result, input.pattern); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createStatTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolCreateOptions, +) => + createTool({ + name: "stat", + description: options.customDescription || STAT_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + path: z.string().describe("Absolute path to the file or directory"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.stat", + "workspace.fs.path": input.path, + }); + const info = await context.filesystem.stat(input.path, { + context: { agent: context.agent, operationContext }, + }); + return formatStatOutput(info, input.path); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createMkdirTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemWritePolicyOptions, +) => + createTool({ + name: "mkdir", + description: options.customDescription || MKDIR_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + path: z.string().describe("Absolute path to the directory to create"), + recursive: z + .boolean() + .optional() + .default(true) + .describe("Whether to create parent directories if needed (default: true)"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + const guardError = await enforceReadBeforeWrite( + operationContext, + context.filesystem, + input.path, + options.requireReadBeforeWrite, + { agent: context.agent, operationContext }, + ); + if (guardError) { + return guardError; + } + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.mkdir", + "workspace.fs.path": input.path, + }); + const result = await context.filesystem.mkdir(input.path, input.recursive, { + context: { agent: context.agent, operationContext }, + }); + if (result.error) { + return result.error; + } + return `Successfully created directory '${result.path ?? input.path}'`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createRmdirTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemWritePolicyOptions, +) => + createTool({ + name: "rmdir", + description: options.customDescription || RMDIR_TOOL_DESCRIPTION, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + path: z.string().describe("Absolute path to the directory to remove"), + recursive: z + .boolean() + .optional() + .default(false) + .describe("Whether to remove contents recursively"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + const guardError = await enforceReadBeforeWrite( + operationContext, + context.filesystem, + input.path, + options.requireReadBeforeWrite, + { agent: context.agent, operationContext }, + ); + if (guardError) { + return guardError; + } + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.rmdir", + "workspace.fs.path": input.path, + }); + const result = await context.filesystem.rmdir(input.path, input.recursive, { + context: { agent: context.agent, operationContext }, + }); + if (result.error) { + return result.error; + } + return `Successfully removed directory '${result.path ?? input.path}'`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +const createListTreeTool = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolCreateOptions, + name: "list_tree" | "list_files", + description: string, +) => + createTool({ + name, + description: options.customDescription || description, + tags: [...WORKSPACE_FILESYSTEM_TAGS], + needsApproval: options.needsApproval, + parameters: z.object({ + path: z.string().optional().default("/").describe("Base directory path (default: /)"), + max_depth: z.coerce + .number() + .int() + .min(1) + .optional() + .default(3) + .describe("Maximum depth to traverse (default: 3)"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + const startPath = input.path || "/"; + const maxDepth = input.max_depth ?? 3; + + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "filesystem.list_tree", + "workspace.fs.path": startPath, + "workspace.fs.depth": maxDepth, + }); + + const lines: string[] = []; + const visited = new Set(); + + const normalizeDirPath = (path: string) => (path.endsWith("/") ? path : `${path}/`); + + const walk = async (dirPath: string, depth: number) => { + if (depth > maxDepth) { + return; + } + + const normalizedDir = normalizeDirPath(dirPath); + if (visited.has(normalizedDir)) { + return; + } + visited.add(normalizedDir); + + const infos = await context.filesystem.lsInfo(normalizedDir, { + context: { agent: context.agent, operationContext }, + }); + + if (infos.length === 0) { + return; + } + + const sorted = [...infos].sort((a, b) => { + const aDir = Boolean(a.is_dir); + const bDir = Boolean(b.is_dir); + if (aDir !== bDir) { + return aDir ? -1 : 1; + } + return a.path.localeCompare(b.path); + }); + + for (const info of sorted) { + const relative = info.path.startsWith(normalizedDir) + ? info.path.substring(normalizedDir.length) + : info.path; + const baseName = relative.replace(/\/$/, ""); + const displayName = baseName || relative || info.path; + const indent = " ".repeat(depth); + lines.push(`${indent}- ${displayName}${info.is_dir ? "/" : ""}`); + + if (info.is_dir && depth < maxDepth) { + await walk(info.path, depth + 1); + } + } + }; + + const statInfo = await context.filesystem.stat(startPath, { + context: { agent: context.agent, operationContext }, + }); + + if (statInfo && !statInfo.is_dir) { + return statInfo.path; + } + + const rootPath = statInfo?.is_dir + ? statInfo.path + : startPath.endsWith("/") + ? startPath + : `${startPath}/`; + + lines.push(rootPath); + await walk(rootPath, 1); + + if (lines.length === 1) { + return `${rootPath}\n (empty)`; + } + + const truncated = truncateIfTooLong(lines); + const output = Array.isArray(truncated) ? truncated.join("\n") : truncated; + return output; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + +export const createWorkspaceFilesystemToolkit = ( + context: WorkspaceFilesystemToolkitContext, + options: WorkspaceFilesystemToolkitOptions = {}, +): Toolkit => { + const systemPrompt = + options.systemPrompt === undefined ? WORKSPACE_FILESYSTEM_SYSTEM_PROMPT : options.systemPrompt; + + const isToolPolicyGroup = ( + policies: WorkspaceToolPolicies, + ): policies is WorkspaceToolPolicyGroup< + WorkspaceFilesystemToolName, + WorkspaceFilesystemToolPolicy + > => + Object.prototype.hasOwnProperty.call(policies, "tools") || + Object.prototype.hasOwnProperty.call(policies, "defaults"); + + const resolveToolPolicy = ( + name: WorkspaceFilesystemToolName, + ): WorkspaceFilesystemToolPolicy | undefined => { + const toolPolicies = options.toolPolicies; + if (!toolPolicies) { + return undefined; + } + + if (isToolPolicyGroup(toolPolicies)) { + const defaults = toolPolicies.defaults ?? {}; + const override = toolPolicies.tools?.[name] ?? {}; + const merged = { ...defaults, ...override }; + return Object.keys(merged).length > 0 ? merged : undefined; + } + + return toolPolicies[name]; + }; + + const isToolEnabled = (name: WorkspaceFilesystemToolName) => { + if (context.filesystem.readOnly && READ_ONLY_BLOCKED_TOOLS.has(name)) { + return false; + } + const policy = resolveToolPolicy(name); + return policy?.enabled ?? true; + }; + + const buildToolOptions = (name: WorkspaceFilesystemToolName) => { + const policy = resolveToolPolicy(name); + return { + customDescription: options.customToolDescriptions?.[name], + needsApproval: policy?.needsApproval, + requireReadBeforeWrite: policy?.requireReadBeforeWrite, + operationTimeoutMs: options.operationTimeoutMs, + }; + }; + + const tools: Toolkit["tools"] = []; + if (isToolEnabled("ls")) { + tools.push(createLsTool(context, buildToolOptions("ls"))); + } + if (isToolEnabled("read_file")) { + tools.push(createReadFileTool(context, buildToolOptions("read_file"))); + } + if (isToolEnabled("write_file")) { + tools.push(createWriteFileTool(context, buildToolOptions("write_file"))); + } + if (isToolEnabled("edit_file")) { + tools.push(createEditFileTool(context, buildToolOptions("edit_file"))); + } + if (isToolEnabled("delete_file")) { + tools.push(createDeleteFileTool(context, buildToolOptions("delete_file"))); + } + if (isToolEnabled("stat")) { + tools.push(createStatTool(context, buildToolOptions("stat"))); + } + if (isToolEnabled("mkdir")) { + tools.push(createMkdirTool(context, buildToolOptions("mkdir"))); + } + if (isToolEnabled("rmdir")) { + tools.push(createRmdirTool(context, buildToolOptions("rmdir"))); + } + if (isToolEnabled("list_tree")) { + tools.push( + createListTreeTool( + context, + buildToolOptions("list_tree"), + "list_tree", + LIST_TREE_TOOL_DESCRIPTION, + ), + ); + } + if (isToolEnabled("list_files")) { + tools.push( + createListTreeTool( + context, + buildToolOptions("list_files"), + "list_files", + LIST_FILES_TOOL_DESCRIPTION, + ), + ); + } + if (isToolEnabled("glob")) { + tools.push(createGlobTool(context, buildToolOptions("glob"))); + } + if (isToolEnabled("grep")) { + tools.push(createGrepTool(context, buildToolOptions("grep"))); + } + + return createToolkit({ + name: "workspace_filesystem", + description: "Workspace filesystem tools", + tools, + instructions: systemPrompt || undefined, + addInstructions: Boolean(systemPrompt), + }); +}; diff --git a/packages/core/src/workspace/filesystem/node-filesystem-backend.spec.ts b/packages/core/src/workspace/filesystem/node-filesystem-backend.spec.ts new file mode 100644 index 000000000..926a06e05 --- /dev/null +++ b/packages/core/src/workspace/filesystem/node-filesystem-backend.spec.ts @@ -0,0 +1,28 @@ +import { mkdtemp, readFile, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; +import { NodeFilesystemBackend } from "./backends/filesystem"; + +describe("NodeFilesystemBackend containment", () => { + it("keeps paths within rootDir by default", async () => { + const root = await mkdtemp(path.join(tmpdir(), "va-workspace-")); + try { + const backend = new NodeFilesystemBackend({ rootDir: root }); + + const writeResult = await backend.write("/notes/hello.txt", "hello"); + expect(writeResult.error).toBeUndefined(); + + const stored = await readFile(path.join(root, "notes", "hello.txt"), "utf-8"); + expect(stored).toBe("hello"); + + const traversal = await backend.write("/../outside.txt", "nope"); + expect(traversal.error).toContain("outside root directory"); + + const readResult = await backend.read("/etc/hosts"); + expect(readResult).toContain("ENOENT"); + } finally { + await rm(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/core/src/workspace/filesystem/toolkit.spec.ts b/packages/core/src/workspace/filesystem/toolkit.spec.ts new file mode 100644 index 000000000..c5357e93b --- /dev/null +++ b/packages/core/src/workspace/filesystem/toolkit.spec.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest"; +import { Workspace } from "../index"; +import { createWorkspaceFilesystemToolkit } from "./index"; + +const createExecuteOptions = () => ({ + systemContext: new Map(), + abortController: new AbortController(), +}); + +const buildFileData = (content: string) => { + const timestamp = new Date().toISOString(); + return { + content: content.split("\n"), + created_at: timestamp, + modified_at: timestamp, + }; +}; + +describe("Workspace filesystem toolkit", () => { + it("supports list_tree, glob, grep, stat, mkdir, and rmdir", async () => { + const workspace = new Workspace({ + filesystem: { + files: { + "/notes/summary.md": buildFileData("hello world"), + "/notes/sub/info.txt": buildFileData("beta"), + }, + }, + }); + + const toolkit = createWorkspaceFilesystemToolkit( + { filesystem: workspace.filesystem, workspace }, + {}, + ); + + const getTool = (name: string) => toolkit.tools.find((tool) => tool.name === name); + const executeOptions = createExecuteOptions() as any; + + const listTree = await getTool("list_tree")?.execute?.( + { path: "/notes", max_depth: 3 }, + executeOptions, + ); + expect(String(listTree)).toContain("- summary.md"); + expect(String(listTree)).toContain("- sub/"); + + const listFiles = await getTool("list_files")?.execute?.( + { path: "/notes", max_depth: 3 }, + executeOptions, + ); + expect(String(listFiles)).toContain("- summary.md"); + + const glob = await getTool("glob")?.execute?.( + { pattern: "**/*.md", path: "/notes" }, + executeOptions, + ); + expect(String(glob)).toContain("/notes/summary.md"); + + const grep = await getTool("grep")?.execute?.( + { pattern: "hello", path: "/notes" }, + executeOptions, + ); + expect(String(grep)).toContain("/notes/summary.md:"); + expect(String(grep)).toContain("1: hello world"); + + const stat = await getTool("stat")?.execute?.({ path: "/notes/summary.md" }, executeOptions); + expect(String(stat)).toContain("type: file"); + + const mkdir = await getTool("mkdir")?.execute?.( + { path: "/notes/new", recursive: true }, + executeOptions, + ); + expect(String(mkdir)).toContain("Successfully created directory"); + + const rmdir = await getTool("rmdir")?.execute?.( + { path: "/notes/new", recursive: false }, + executeOptions, + ); + expect(String(rmdir)).toContain("Successfully removed directory"); + + const deleteResult = await getTool("delete_file")?.execute?.( + { file_path: "/notes/summary.md" }, + executeOptions, + ); + expect(String(deleteResult)).toContain("Successfully deleted"); + }); + + it("enforces read-before-write when policy is enabled", async () => { + const workspace = new Workspace({ + filesystem: { + files: { + "/notes/summary.md": buildFileData("hello world"), + }, + }, + toolConfig: { + filesystem: { + tools: { + write_file: { requireReadBeforeWrite: true }, + }, + }, + }, + }); + + const toolkit = workspace.createFilesystemToolkit(); + const executeOptions = createExecuteOptions() as any; + + const writeTool = toolkit.tools.find((tool) => tool.name === "write_file"); + const readTool = toolkit.tools.find((tool) => tool.name === "read_file"); + + const firstWrite = await writeTool?.execute?.( + { file_path: "/notes/summary.md", content: "updated", overwrite: true }, + executeOptions, + ); + expect(String(firstWrite)).toContain("Please read"); + + await readTool?.execute?.({ file_path: "/notes/summary.md" }, executeOptions); + + const secondWrite = await writeTool?.execute?.( + { file_path: "/notes/summary.md", content: "updated", overwrite: true }, + executeOptions, + ); + expect(String(secondWrite)).toContain("Successfully wrote"); + }); +}); diff --git a/packages/core/src/workspace/filesystem/utils.ts b/packages/core/src/workspace/filesystem/utils.ts new file mode 100644 index 000000000..effaa4a3e --- /dev/null +++ b/packages/core/src/workspace/filesystem/utils.ts @@ -0,0 +1,336 @@ +import micromatch from "micromatch"; +import type { FileData, GrepMatch } from "./backends/backend"; + +export const EMPTY_CONTENT_WARNING = "System reminder: File exists but has empty contents"; +export const MAX_LINE_LENGTH = 10000; +export const MAX_GREP_LINE_LENGTH = MAX_LINE_LENGTH; +export const MAX_REGEX_PATTERN_LENGTH = 500; +export const MAX_GREP_MATCHES = 5000; +export const LINE_NUMBER_WIDTH = 6; +export const TOOL_RESULT_TOKEN_LIMIT = 20000; +export const TRUNCATION_GUIDANCE = + "... [results truncated, try being more specific with your parameters]"; + +type RegexSafetyResult = { safe: true } | { safe: false; reason: string }; + +const NESTED_QUANTIFIER_PATTERN = /\((?:[^()\\]|\\.)*[*+{](?:[^()\\]|\\.)*\)\s*[*+{]/; +const OVERLAPPING_QUANTIFIER_PATTERN = /(\.\*|\.\+|\.\{[^}]+\})\s*[*+{]/; + +export function assessRegexPattern(pattern: string): RegexSafetyResult { + if (pattern.length > MAX_REGEX_PATTERN_LENGTH) { + return { + safe: false, + reason: `Pattern length exceeds ${MAX_REGEX_PATTERN_LENGTH} characters`, + }; + } + if (NESTED_QUANTIFIER_PATTERN.test(pattern) || OVERLAPPING_QUANTIFIER_PATTERN.test(pattern)) { + return { safe: false, reason: "Pattern contains nested or overlapping quantifiers" }; + } + return { safe: true }; +} + +export function sanitizeToolCallId(toolCallId: string): string { + return toolCallId.replace(/\./g, "_").replace(/\//g, "_").replace(/\\/g, "_"); +} + +export function formatContentWithLineNumbers(content: string | string[], startLine = 1): string { + let lines: string[]; + if (typeof content === "string") { + lines = content.split("\n"); + if (lines.length > 0 && lines[lines.length - 1] === "") { + lines = lines.slice(0, -1); + } + } else { + lines = content; + } + + const resultLines: string[] = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + const lineNum = i + startLine; + + if (line.length <= MAX_LINE_LENGTH) { + resultLines.push(`${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\t${line}`); + } else { + const numChunks = Math.ceil(line.length / MAX_LINE_LENGTH); + for (let chunkIdx = 0; chunkIdx < numChunks; chunkIdx++) { + const start = chunkIdx * MAX_LINE_LENGTH; + const end = Math.min(start + MAX_LINE_LENGTH, line.length); + const chunk = line.substring(start, end); + if (chunkIdx === 0) { + resultLines.push(`${lineNum.toString().padStart(LINE_NUMBER_WIDTH)}\t${chunk}`); + } else { + const continuationMarker = `${lineNum}.${chunkIdx}`; + resultLines.push(`${continuationMarker.padStart(LINE_NUMBER_WIDTH)}\t${chunk}`); + } + } + } + } + + return resultLines.join("\n"); +} + +export function checkEmptyContent(content: string): string | null { + if (!content || content.trim() === "") { + return EMPTY_CONTENT_WARNING; + } + return null; +} + +export function fileDataToString(fileData: FileData): string { + return fileData.content.join("\n"); +} + +export function createFileData(content: string, createdAt?: string): FileData { + const lines = typeof content === "string" ? content.split("\n") : content; + const now = new Date().toISOString(); + + return { + content: lines, + created_at: createdAt || now, + modified_at: now, + }; +} + +export function updateFileData(fileData: FileData, content: string): FileData { + const lines = typeof content === "string" ? content.split("\n") : content; + const now = new Date().toISOString(); + + return { + content: lines, + created_at: fileData.created_at, + modified_at: now, + }; +} + +export function formatReadResponse(fileData: FileData, offset: number, limit: number): string { + const content = fileDataToString(fileData); + const emptyMsg = checkEmptyContent(content); + if (emptyMsg) { + return emptyMsg; + } + + const lines = content.split("\n"); + const startIdx = offset; + const endIdx = Math.min(startIdx + limit, lines.length); + + if (startIdx >= lines.length) { + return `Error: Line offset ${offset} exceeds file length (${lines.length} lines)`; + } + + const selectedLines = lines.slice(startIdx, endIdx); + return formatContentWithLineNumbers(selectedLines, startIdx + 1); +} + +export function performStringReplacement( + content: string, + oldString: string, + newString: string, + replaceAll: boolean, +): [string, number] | string { + const occurrences = content.split(oldString).length - 1; + + if (occurrences === 0) { + return `Error: String not found in file: '${oldString}'`; + } + + if (occurrences > 1 && !replaceAll) { + return `Error: String '${oldString}' appears ${occurrences} times in file. Use replace_all=true to replace all instances, or provide a more specific string with surrounding context.`; + } + + const newContent = content.split(oldString).join(newString); + + return [newContent, occurrences]; +} + +export function truncateIfTooLong( + result: string[] | string, + maxChars: number = TOOL_RESULT_TOKEN_LIMIT * 4, +): string[] | string { + if (Array.isArray(result)) { + const totalChars = result.reduce((sum, item) => sum + item.length, 0); + if (totalChars > maxChars) { + const truncateAt = Math.floor((result.length * maxChars) / totalChars); + return [...result.slice(0, truncateAt), TRUNCATION_GUIDANCE]; + } + return result; + } + + if (result.length > maxChars) { + return `${result.substring(0, maxChars)}\n${TRUNCATION_GUIDANCE}`; + } + return result; +} + +export function validatePath(path: string | null | undefined): string { + const pathStr = path || "/"; + if (!pathStr || pathStr.trim() === "") { + throw new Error("Path cannot be empty"); + } + + let normalized = pathStr.startsWith("/") ? pathStr : `/${pathStr}`; + + if (!normalized.endsWith("/")) { + normalized += "/"; + } + + return normalized; +} + +function basename(filePath: string): string { + const normalized = filePath.replace(/\\/g, "/"); + const parts = normalized.split("/"); + return parts[parts.length - 1] || ""; +} + +export function globSearchFiles( + files: Record, + pattern: string, + path = "/", +): string { + let normalizedPath: string; + try { + normalizedPath = validatePath(path); + } catch { + return "No files found"; + } + + const filtered = Object.fromEntries( + Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)), + ); + + const matches: Array<[string, string]> = []; + for (const [filePath, fileData] of Object.entries(filtered)) { + let relative = filePath.substring(normalizedPath.length); + if (relative.startsWith("/")) { + relative = relative.substring(1); + } + if (!relative) { + relative = basename(filePath); + } + + if ( + micromatch.isMatch(relative, pattern, { + dot: true, + nobrace: false, + }) + ) { + matches.push([filePath, fileData.modified_at]); + } + } + + matches.sort((a, b) => b[1].localeCompare(a[1])); + + if (matches.length === 0) { + return "No files found"; + } + + return matches.map(([fp]) => fp).join("\n"); +} + +export function grepMatchesFromFiles( + files: Record, + pattern: string, + path: string | null = null, + glob: string | null = null, +): GrepMatch[] | string { + const safety = assessRegexPattern(pattern); + if (!safety.safe) { + return `Unsafe regex pattern: ${safety.reason}`; + } + + let regex: RegExp; + try { + regex = new RegExp(pattern); + } catch (e: any) { + return `Invalid regex pattern: ${e.message}`; + } + + let normalizedPath: string; + try { + normalizedPath = validatePath(path); + } catch { + return []; + } + + let filtered = Object.fromEntries( + Object.entries(files).filter(([fp]) => fp.startsWith(normalizedPath)), + ); + + if (glob) { + filtered = Object.fromEntries( + Object.entries(filtered).filter(([fp]) => { + let relative = fp.substring(normalizedPath.length); + if (relative.startsWith("/")) { + relative = relative.substring(1); + } + if (!relative) { + relative = basename(fp); + } + return micromatch.isMatch(relative, glob, { dot: true, nobrace: false }); + }), + ); + } + + const matches: GrepMatch[] = []; + for (const [filePath, fileData] of Object.entries(filtered)) { + for (let i = 0; i < fileData.content.length; i++) { + const line = fileData.content[i]; + const lineNum = i + 1; + const candidate = + line.length > MAX_GREP_LINE_LENGTH ? line.slice(0, MAX_GREP_LINE_LENGTH) : line; + let matched = false; + try { + matched = regex.test(candidate); + } catch { + matched = false; + } + if (matched) { + matches.push({ path: filePath, line: lineNum, text: line }); + if (matches.length >= MAX_GREP_MATCHES) { + return matches; + } + } + } + } + + return matches; +} + +export function formatGrepMatches( + matches: GrepMatch[], + outputMode: "files_with_matches" | "content" | "count", +): string { + if (matches.length === 0) { + return "No matches found"; + } + + const grouped: Record> = {}; + for (const match of matches) { + if (!grouped[match.path]) { + grouped[match.path] = []; + } + grouped[match.path].push([match.line, match.text]); + } + + if (outputMode === "files_with_matches") { + return Object.keys(grouped).sort().join("\n"); + } + + if (outputMode === "count") { + const lines: string[] = []; + for (const filePath of Object.keys(grouped).sort()) { + lines.push(`${filePath}: ${grouped[filePath].length}`); + } + return lines.join("\n"); + } + + const lines: string[] = []; + for (const filePath of Object.keys(grouped).sort()) { + lines.push(`${filePath}:`); + for (const [lineNum, line] of grouped[filePath]) { + lines.push(` ${lineNum}: ${line}`); + } + } + return lines.join("\n"); +} diff --git a/packages/core/src/workspace/index.spec.ts b/packages/core/src/workspace/index.spec.ts new file mode 100644 index 000000000..ef83e7205 --- /dev/null +++ b/packages/core/src/workspace/index.spec.ts @@ -0,0 +1,97 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { Agent } from "../agent/agent"; +import { createMockLanguageModel } from "../agent/test-utils"; +import { AgentRegistry } from "../registries/agent-registry"; +import { Workspace } from "./index"; + +describe("Workspace global defaults", () => { + const registry = AgentRegistry.getInstance(); + + afterEach(() => { + registry.setGlobalWorkspace(undefined); + }); + + it("inherits the global workspace when agent doesn't specify one", () => { + const workspace = new Workspace({ id: "global-workspace" }); + registry.setGlobalWorkspace(workspace); + + const agent = new Agent({ + name: "test-agent", + instructions: "test", + model: createMockLanguageModel(), + }); + + expect(agent.getWorkspace()).toBe(workspace); + }); + + it("allows agent to opt out of global workspace", () => { + const workspace = new Workspace({ id: "global-workspace" }); + registry.setGlobalWorkspace(workspace); + + const agent = new Agent({ + name: "test-agent", + instructions: "test", + model: createMockLanguageModel(), + workspace: false, + }); + + expect(agent.getWorkspace()).toBeUndefined(); + }); +}); + +describe("Workspace direct search access", () => { + it("rejects direct search when allowDirectAccess is false", async () => { + const workspace = new Workspace({ + search: { + allowDirectAccess: false, + }, + }); + + await expect(workspace.search("hello")).rejects.toThrow("direct access"); + }); + + it("allows direct index/search when allowDirectAccess is true", async () => { + const workspace = new Workspace({ + search: { + allowDirectAccess: true, + }, + }); + + await workspace.index("/doc.txt", "hello world"); + const results = await workspace.search("hello"); + + expect(results.length).toBeGreaterThan(0); + expect(results[0]?.path).toBe("/doc.txt"); + }); +}); + +describe("Workspace lifecycle", () => { + it("starts and destroys the sandbox", async () => { + const start = vi.fn(); + const destroy = vi.fn(); + + const workspace = new Workspace({ + sandbox: { + name: "test", + execute: async () => ({ + stdout: "", + stderr: "", + exitCode: 0, + durationMs: 0, + timedOut: false, + aborted: false, + stdoutTruncated: false, + stderrTruncated: false, + }), + start, + destroy, + }, + }); + + await workspace.init(); + expect(start).toHaveBeenCalled(); + + await workspace.destroy(); + expect(destroy).toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/workspace/index.ts b/packages/core/src/workspace/index.ts new file mode 100644 index 000000000..3876710db --- /dev/null +++ b/packages/core/src/workspace/index.ts @@ -0,0 +1,507 @@ +import { randomUUID } from "../utils/id"; +import { + type DeleteResult, + type EditResult, + type FileData, + type FileInfo, + type FilesystemBackend, + type FilesystemBackendContext, + type FilesystemBackendFactory, + type GrepMatch, + type MkdirResult, + type RmdirResult, + WorkspaceFilesystem, + type WorkspaceFilesystemCallContext, + type WorkspaceFilesystemDeleteOptions, + type WorkspaceFilesystemOperationOptions, + type WorkspaceFilesystemOptions, + type WorkspaceFilesystemReadOptions, + type WorkspaceFilesystemRmdirOptions, + type WorkspaceFilesystemSearchOptions, + type WorkspaceFilesystemToolName, + type WorkspaceFilesystemToolkitOptions, + type WorkspaceFilesystemWriteOptions, + type WriteResult, + createWorkspaceFilesystemToolkit, +} from "./filesystem"; +import type { + LocalSandboxIsolationOptions, + LocalSandboxIsolationProvider, + LocalSandboxOptions, + WorkspaceSandbox, + WorkspaceSandboxExecuteOptions, + WorkspaceSandboxResult, + WorkspaceSandboxStatus, + WorkspaceSandboxToolName, + WorkspaceSandboxToolkitContext, + WorkspaceSandboxToolkitOptions, +} from "./sandbox"; +import { + LocalSandbox, + createWorkspaceSandboxToolkit, + detectLocalSandboxIsolation, +} from "./sandbox"; +import { + WorkspaceSearch, + type WorkspaceSearchToolName, + type WorkspaceSearchToolkitContext, + type WorkspaceSearchToolkitOptions, + createWorkspaceSearchToolkit, +} from "./search"; +import type { + WorkspaceSearchIndexSummary, + WorkspaceSearchOptions, + WorkspaceSearchResult, +} from "./search/types"; +import { + WorkspaceSkills, + type WorkspaceSkillsPromptHookContext, + type WorkspaceSkillsToolName, + type WorkspaceSkillsToolkitContext, + type WorkspaceSkillsToolkitOptions, + createWorkspaceSkillsPromptHook, + createWorkspaceSkillsToolkit, +} from "./skills"; +import type { WorkspaceSkillsPromptOptions } from "./skills/types"; +import { withOperationTimeout } from "./timeout"; +import type { + WorkspaceFilesystemToolPolicy, + WorkspaceToolConfig, + WorkspaceToolPolicies, + WorkspaceToolPolicy, + WorkspaceToolPolicyGroup, +} from "./tool-policy"; +import type { + WorkspaceConfig, + WorkspaceFilesystemConfig, + WorkspaceIdentity, + WorkspaceInfo, + WorkspacePathContext, + WorkspaceScope, + WorkspaceStatus, +} from "./types"; + +const isToolPolicyGroup = ( + policies: WorkspaceToolPolicies, +): policies is WorkspaceToolPolicyGroup => + Object.prototype.hasOwnProperty.call(policies, "tools") || + Object.prototype.hasOwnProperty.call(policies, "defaults"); + +const normalizeToolPolicies = ( + policies?: WorkspaceToolPolicies | null, +): { defaults?: TPolicy; tools?: Partial> } | null => { + if (!policies) { + return null; + } + if (isToolPolicyGroup(policies)) { + return { + defaults: policies.defaults, + tools: policies.tools, + }; + } + return { tools: policies }; +}; + +const mergeToolPolicies = ( + base?: WorkspaceToolPolicies | null, + override?: WorkspaceToolPolicies | null, +): WorkspaceToolPolicies | undefined => { + const baseNormalized = normalizeToolPolicies(base); + const overrideNormalized = normalizeToolPolicies(override); + if (!baseNormalized && !overrideNormalized) { + return undefined; + } + return { + defaults: { + ...(baseNormalized?.defaults ?? {}), + ...(overrideNormalized?.defaults ?? {}), + } as TPolicy, + tools: { + ...(baseNormalized?.tools ?? {}), + ...(overrideNormalized?.tools ?? {}), + }, + }; +}; + +export class Workspace { + readonly id: string; + readonly name?: string; + readonly scope: WorkspaceScope; + readonly filesystem: WorkspaceFilesystem; + readonly sandbox?: WorkspaceSandbox; + private readonly searchService?: WorkspaceSearch; + private readonly allowDirectSearchAccess: boolean; + private readonly operationTimeoutMs?: number; + readonly skills?: WorkspaceSkills; + private readonly toolConfig?: WorkspaceToolConfig; + status: WorkspaceStatus = "idle"; + private initPromise?: Promise; + + constructor(options: WorkspaceConfig = {}) { + this.id = options.id ?? randomUUID(); + this.name = options.name; + this.scope = options.scope ?? "agent"; + this.filesystem = new WorkspaceFilesystem(options.filesystem); + this.sandbox = options.sandbox; + this.operationTimeoutMs = options.operationTimeoutMs; + this.allowDirectSearchAccess = options.search?.allowDirectAccess ?? false; + this.searchService = options.search + ? new WorkspaceSearch({ filesystem: this.filesystem, ...options.search }) + : undefined; + this.skills = options.skills + ? new WorkspaceSkills({ + filesystem: this.filesystem, + workspace: { id: this.id, name: this.name, scope: this.scope }, + ...options.skills, + }) + : undefined; + this.toolConfig = options.toolConfig; + } + + async init(): Promise { + if (this.isDestroyed()) { + throw new Error("Workspace has been destroyed."); + } + if (this.status === "ready") { + return; + } + if (!this.initPromise) { + this.status = "initializing"; + this.initPromise = (async () => { + try { + if (this.isDestroyed()) { + return; + } + this.filesystem.init(); + if (this.isDestroyed()) { + return; + } + await this.sandbox?.start?.(); + if (this.isDestroyed()) { + return; + } + await this.searchService?.init?.(); + if (this.isDestroyed()) { + return; + } + await this.skills?.init?.(); + if (!this.isDestroyed()) { + this.status = "ready"; + } + } catch (error) { + if (!this.isDestroyed()) { + this.status = "error"; + } + throw error; + } finally { + this.initPromise = undefined; + } + })(); + } + await this.initPromise; + } + + async destroy(): Promise { + if (this.isDestroyed()) { + return; + } + this.status = "destroyed"; + if (this.initPromise) { + await this.initPromise.catch(() => undefined); + } + await this.sandbox?.destroy?.(); + this.searchService?.destroy(); + this.skills?.destroy(); + this.filesystem.destroy(); + } + + private isDestroyed(): boolean { + return this.status === "destroyed"; + } + + getInfo(): WorkspaceInfo { + return { + id: this.id, + name: this.name, + scope: this.scope, + status: this.status, + operationTimeoutMs: this.operationTimeoutMs, + filesystem: { + status: this.filesystem.status, + details: this.filesystem.getInfo(), + }, + sandbox: this.sandbox + ? { + status: this.sandbox.status, + details: this.sandbox.getInfo?.(), + } + : undefined, + search: this.searchService + ? { + status: this.searchService.status, + details: this.searchService.getInfo(), + } + : undefined, + skills: this.skills + ? { + status: this.skills.status, + details: this.skills.getInfo(), + } + : undefined, + }; + } + + getPathContext(): WorkspacePathContext { + return { + filesystem: { + status: this.filesystem.status, + instructions: this.filesystem.getInstructions(), + info: this.filesystem.getInfo(), + }, + sandbox: this.sandbox + ? { + status: this.sandbox.status, + instructions: this.sandbox.getInstructions?.() ?? null, + info: this.sandbox.getInfo?.(), + } + : undefined, + }; + } + + getToolsConfig(): WorkspaceToolConfig | undefined { + return this.toolConfig; + } + + getObservabilityAttributes(): Record { + return { + "workspace.id": this.id, + "workspace.name": this.name, + "workspace.scope": this.scope, + }; + } + + private applyOperationTimeout(options: T): T { + if (options.operationTimeoutMs !== undefined || this.operationTimeoutMs === undefined) { + return options; + } + return { ...options, operationTimeoutMs: this.operationTimeoutMs }; + } + + private resolveSearchToolPolicy(name: WorkspaceSearchToolName): WorkspaceToolPolicy | undefined { + const normalized = normalizeToolPolicies(this.toolConfig?.search ?? null); + if (!normalized) { + return undefined; + } + return { + ...(normalized.defaults ?? {}), + ...(normalized.tools?.[name] ?? {}), + } as WorkspaceToolPolicy; + } + + private assertDirectSearchAllowed(name: WorkspaceSearchToolName): WorkspaceSearch { + const searchService = this.searchService; + if (!searchService) { + throw new Error("Workspace search is not configured."); + } + if (!this.allowDirectSearchAccess) { + throw new Error( + "Workspace search direct access is disabled. Use search tools or enable search.allowDirectAccess.", + ); + } + const policy = this.resolveSearchToolPolicy(name); + if (policy?.enabled === false) { + throw new Error(`Workspace search tool '${name}' is disabled by policy.`); + } + if (policy?.needsApproval) { + throw new Error( + `Workspace search tool '${name}' requires approval; use the tool execution flow.`, + ); + } + return searchService; + } + + async index( + path: string, + content: string, + metadata?: Record, + ): Promise { + return await withOperationTimeout( + async () => { + const searchService = this.assertDirectSearchAllowed("workspace_index_content"); + if (this.filesystem.readOnly) { + throw new Error("Workspace filesystem is read-only."); + } + return searchService.indexContent(path, content, metadata); + }, + undefined, + this.operationTimeoutMs, + ); + } + + async search(query: string, options?: WorkspaceSearchOptions): Promise { + return await withOperationTimeout( + async () => { + const searchService = this.assertDirectSearchAllowed("workspace_search"); + return searchService.search(query, options); + }, + undefined, + this.operationTimeoutMs, + ); + } + + createFilesystemToolkit(options: WorkspaceFilesystemToolkitOptions = {}) { + const mergedPolicies = mergeToolPolicies( + this.toolConfig?.filesystem as + | WorkspaceToolPolicies + | null + | undefined, + options.toolPolicies ?? null, + ); + const mergedOptions = + mergedPolicies === undefined ? options : { ...options, toolPolicies: mergedPolicies }; + const finalOptions = this.applyOperationTimeout(mergedOptions); + return createWorkspaceFilesystemToolkit( + { filesystem: this.filesystem, workspace: this }, + finalOptions, + ); + } + + createSandboxToolkit(options: WorkspaceSandboxToolkitOptions = {}) { + const mergedPolicies = mergeToolPolicies( + this.toolConfig?.sandbox as + | WorkspaceToolPolicies + | null + | undefined, + options.toolPolicies ?? null, + ); + const mergedOptions = + mergedPolicies === undefined ? options : { ...options, toolPolicies: mergedPolicies }; + const finalOptions = this.applyOperationTimeout(mergedOptions); + return createWorkspaceSandboxToolkit( + { sandbox: this.sandbox, workspace: this, filesystem: this.filesystem }, + finalOptions, + ); + } + + createSearchToolkit(options: WorkspaceSearchToolkitOptions = {}) { + const mergedPolicies = mergeToolPolicies( + this.toolConfig?.search as + | WorkspaceToolPolicies + | null + | undefined, + options.toolPolicies ?? null, + ); + const mergedOptions = + mergedPolicies === undefined ? options : { ...options, toolPolicies: mergedPolicies }; + const finalOptions = this.applyOperationTimeout(mergedOptions); + return createWorkspaceSearchToolkit( + { search: this.searchService, workspace: this, filesystem: this.filesystem }, + finalOptions, + ); + } + + createSkillsToolkit(options: WorkspaceSkillsToolkitOptions = {}) { + const mergedPolicies = mergeToolPolicies( + this.toolConfig?.skills as + | WorkspaceToolPolicies + | null + | undefined, + options.toolPolicies ?? null, + ); + const mergedOptions = + mergedPolicies === undefined ? options : { ...options, toolPolicies: mergedPolicies }; + const finalOptions = this.applyOperationTimeout(mergedOptions); + return createWorkspaceSkillsToolkit({ skills: this.skills, workspace: this }, finalOptions); + } + + createSkillsPromptHook(options: WorkspaceSkillsPromptOptions = {}) { + return createWorkspaceSkillsPromptHook({ skills: this.skills }, options); + } +} + +export type { + WorkspaceConfig, + WorkspaceFilesystemConfig, + WorkspaceIdentity, + WorkspaceScope, + WorkspaceInfo, + WorkspacePathContext, + WorkspaceStatus, +}; +export { + WorkspaceFilesystem, + createWorkspaceFilesystemToolkit, + type WorkspaceFilesystemToolName, + type WorkspaceFilesystemToolkitOptions, + type WorkspaceFilesystemOptions, + type WorkspaceFilesystemCallContext, + type WorkspaceFilesystemReadOptions, + type WorkspaceFilesystemWriteOptions, + type WorkspaceFilesystemSearchOptions, + type WorkspaceFilesystemOperationOptions, + type WorkspaceFilesystemDeleteOptions, + type WorkspaceFilesystemRmdirOptions, + type DeleteResult as WorkspaceDeleteResult, + type EditResult as WorkspaceEditResult, + type FileData as WorkspaceFileData, + type FileInfo as WorkspaceFileInfo, + type FilesystemBackend as WorkspaceFilesystemBackend, + type FilesystemBackendContext as WorkspaceFilesystemBackendContext, + type FilesystemBackendFactory as WorkspaceFilesystemBackendFactory, + type GrepMatch as WorkspaceGrepMatch, + type MkdirResult as WorkspaceMkdirResult, + type RmdirResult as WorkspaceRmdirResult, + type WriteResult as WorkspaceWriteResult, + LocalSandbox, + detectLocalSandboxIsolation, + type LocalSandboxOptions, + type LocalSandboxIsolationOptions, + type LocalSandboxIsolationProvider, + type WorkspaceSandbox, + type WorkspaceSandboxExecuteOptions, + type WorkspaceSandboxResult, + type WorkspaceSandboxStatus, + type WorkspaceSandboxToolName, + createWorkspaceSandboxToolkit, + type WorkspaceSandboxToolkitOptions, + type WorkspaceSandboxToolkitContext, + WorkspaceSearch, + createWorkspaceSearchToolkit, + type WorkspaceSearchToolName, + type WorkspaceSearchToolkitOptions, + type WorkspaceSearchToolkitContext, + WorkspaceSkills, + createWorkspaceSkillsToolkit, + createWorkspaceSkillsPromptHook, + type WorkspaceSkillsToolkitOptions, + type WorkspaceSkillsToolName, + type WorkspaceSkillsToolkitContext, + type WorkspaceSkillsPromptHookContext, + type WorkspaceFilesystemToolPolicy, + type WorkspaceToolConfig, + type WorkspaceToolPolicies, + type WorkspaceToolPolicy, + type WorkspaceToolPolicyGroup, +}; +export type { + WorkspaceSearchConfig, + WorkspaceSearchHybridWeights, + WorkspaceSearchIndexPath, + WorkspaceSearchIndexSummary, + WorkspaceSearchMode, + WorkspaceSearchOptions, + WorkspaceSearchResult, +} from "./search/types"; +export type { + WorkspaceSkill, + WorkspaceSkillIndexSummary, + WorkspaceSkillMetadata, + WorkspaceSkillSearchMode, + WorkspaceSkillSearchOptions, + WorkspaceSkillSearchResult, + WorkspaceSkillsConfig, + WorkspaceSkillsRootResolver, + WorkspaceSkillsRootResolverContext, + WorkspaceSkillsPromptOptions, + WorkspaceSkillSearchHybridWeights, +} from "./skills/types"; diff --git a/packages/core/src/workspace/sandbox/index.ts b/packages/core/src/workspace/sandbox/index.ts new file mode 100644 index 000000000..c849919ae --- /dev/null +++ b/packages/core/src/workspace/sandbox/index.ts @@ -0,0 +1,19 @@ +export type { + WorkspaceSandbox, + WorkspaceSandboxExecuteOptions, + WorkspaceSandboxResult, + WorkspaceSandboxStatus, +} from "./types"; +export { LocalSandbox } from "./local"; +export { detectLocalSandboxIsolation } from "./local"; +export type { + LocalSandboxOptions, + LocalSandboxIsolationOptions, + LocalSandboxIsolationProvider, +} from "./local"; +export { createWorkspaceSandboxToolkit } from "./toolkit"; +export type { + WorkspaceSandboxToolkitOptions, + WorkspaceSandboxToolkitContext, + WorkspaceSandboxToolName, +} from "./toolkit"; diff --git a/packages/core/src/workspace/sandbox/local.spec.ts b/packages/core/src/workspace/sandbox/local.spec.ts new file mode 100644 index 000000000..16a3a5c35 --- /dev/null +++ b/packages/core/src/workspace/sandbox/local.spec.ts @@ -0,0 +1,157 @@ +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { LocalSandbox, detectLocalSandboxIsolation } from "./local"; + +const runNodeScript = async (sandbox: LocalSandbox, script: string) => { + return await sandbox.execute({ + command: process.execPath, + args: ["-e", script], + }); +}; + +const pathExists = async (target: string): Promise => { + try { + await fs.access(target); + return true; + } catch { + return false; + } +}; + +const waitForRemoval = async (target: string): Promise => { + for (let i = 0; i < 20; i += 1) { + if (!(await pathExists(target))) { + return; + } + await new Promise((resolve) => setTimeout(resolve, 25)); + } +}; + +describe("LocalSandbox defaults", () => { + const originalSecret = process.env.VOLTAGENT_TEST_SECRET; + + beforeEach(() => { + process.env.VOLTAGENT_TEST_SECRET = "secret-value"; + }); + + afterEach(() => { + if (originalSecret === undefined) { + process.env.VOLTAGENT_TEST_SECRET = undefined; + } else { + process.env.VOLTAGENT_TEST_SECRET = originalSecret; + } + }); + + it("passes only PATH by default", async () => { + const sandbox = new LocalSandbox(); + const result = await runNodeScript( + sandbox, + [ + "console.log(process.env.VOLTAGENT_TEST_SECRET ?? 'missing')", + "console.log(process.env.PATH ? 'path' : 'no-path')", + ].join(";"), + ); + + const [secretLine, pathLine] = result.stdout + .trim() + .split("\n") + .map((line) => line.trim()); + expect(secretLine).toBe("missing"); + expect(pathLine).toBe("path"); + }); + + it("passes full env when inheritProcessEnv is true", async () => { + const sandbox = new LocalSandbox({ inheritProcessEnv: true }); + const result = await runNodeScript( + sandbox, + [ + "console.log(process.env.VOLTAGENT_TEST_SECRET ?? 'missing')", + "console.log(process.env.PATH ? 'path' : 'no-path')", + ].join(";"), + ); + + const [secretLine, pathLine] = result.stdout + .trim() + .split("\n") + .map((line) => line.trim()); + expect(secretLine).toBe("secret-value"); + expect(pathLine).toBe("path"); + }); +}); + +describe("LocalSandbox cleanupOnDestroy", () => { + const originalCwd = process.cwd(); + + afterEach(() => { + process.chdir(originalCwd); + }); + + it("cleans the auto-created root directory on destroy", async () => { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "voltagent-sandbox-")); + process.chdir(tempDir); + + const sandbox = new LocalSandbox({ cleanupOnDestroy: true }); + await runNodeScript(sandbox, "console.log('ready')"); + + const rootDir = path.join(tempDir, ".sandbox"); + expect(await pathExists(rootDir)).toBe(true); + + sandbox.destroy(); + await waitForRemoval(rootDir); + expect(await pathExists(rootDir)).toBe(false); + + await fs.rm(tempDir, { recursive: true, force: true }); + }); +}); + +describe("LocalSandbox isolation helpers", () => { + const originalPath = process.env.PATH; + + afterEach(() => { + if (originalPath === undefined) { + process.env.PATH = undefined; + } else { + process.env.PATH = originalPath; + } + }); + + it("detects none when PATH is empty", async () => { + process.env.PATH = ""; + const result = await detectLocalSandboxIsolation(); + expect(result).toBe("none"); + }); + + it("throws for unsupported bwrap on non-linux", async () => { + if (process.platform === "linux") { + return; + } + const sandbox = new LocalSandbox({ + isolation: { provider: "bwrap" }, + }); + + await expect( + sandbox.execute({ + command: "echo", + args: ["test"], + }), + ).rejects.toThrow("bwrap isolation is only supported on Linux"); + }); + + it("throws for unsupported sandbox-exec on non-darwin", async () => { + if (process.platform === "darwin") { + return; + } + const sandbox = new LocalSandbox({ + isolation: { provider: "sandbox-exec" }, + }); + + await expect( + sandbox.execute({ + command: "echo", + args: ["test"], + }), + ).rejects.toThrow("sandbox-exec isolation is only supported on macOS"); + }); +}); diff --git a/packages/core/src/workspace/sandbox/local.ts b/packages/core/src/workspace/sandbox/local.ts new file mode 100644 index 000000000..b14410499 --- /dev/null +++ b/packages/core/src/workspace/sandbox/local.ts @@ -0,0 +1,642 @@ +import { spawn } from "node:child_process"; +import { promises as fs, constants as fsConstants } from "node:fs"; +import * as path from "node:path"; +import type { + WorkspaceSandbox, + WorkspaceSandboxExecuteOptions, + WorkspaceSandboxResult, + WorkspaceSandboxStatus, +} from "./types"; + +export type LocalSandboxOptions = { + rootDir?: string; + cleanupOnDestroy?: boolean; + defaultTimeoutMs?: number; + maxOutputBytes?: number; + env?: Record; + inheritProcessEnv?: boolean; + allowedCommands?: string[]; + blockedCommands?: string[]; + isolation?: LocalSandboxIsolationOptions; +}; + +const DEFAULT_TIMEOUT_MS = 30000; +const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024; + +export type LocalSandboxIsolationProvider = "none" | "sandbox-exec" | "bwrap"; + +export type LocalSandboxIsolationOptions = { + provider?: LocalSandboxIsolationProvider; + allowNetwork?: boolean; + allowSystemBinaries?: boolean; + readWritePaths?: string[]; + readOnlyPaths?: string[]; + seatbeltProfilePath?: string; + bwrapArgs?: string[]; + profile?: string; +}; + +type OutputBuffer = { + chunks: Buffer[]; + size: number; + truncated: boolean; +}; + +const initOutputBuffer = (): OutputBuffer => ({ chunks: [], size: 0, truncated: false }); + +const appendOutput = (buffer: OutputBuffer, data: Buffer, maxBytes: number): void => { + if (maxBytes <= 0) { + buffer.truncated = true; + return; + } + + const remaining = maxBytes - buffer.size; + if (remaining <= 0) { + buffer.truncated = true; + return; + } + + if (data.length > remaining) { + buffer.chunks.push(data.subarray(0, remaining)); + buffer.size += remaining; + buffer.truncated = true; + return; + } + + buffer.chunks.push(data); + buffer.size += data.length; +}; + +const toOutputString = (buffer: OutputBuffer): string => { + if (buffer.chunks.length === 0) { + return ""; + } + return Buffer.concat(buffer.chunks, buffer.size).toString("utf-8"); +}; + +const normalizeEnv = (env?: Record): Record => { + const result: Record = {}; + if (!env) { + return result; + } + for (const [key, value] of Object.entries(env)) { + if (value === undefined || value === null) { + continue; + } + result[key] = String(value); + } + return result; +}; + +const resolvePathEnv = (): Record => { + const pathValue = process.env.PATH ?? process.env.Path ?? process.env.path; + if (!pathValue) { + return {}; + } + return { PATH: String(pathValue) }; +}; + +const isPathWithinRoot = (rootDir: string, candidate: string): boolean => { + const relative = path.relative(rootDir, candidate); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); +}; + +const resolveCwd = (rootDir: string | undefined, cwd?: string): string | undefined => { + if (!rootDir) { + return cwd; + } + + const resolvedRoot = path.resolve(rootDir); + const resolvedCwd = cwd + ? path.isAbsolute(cwd) + ? path.resolve(cwd) + : path.resolve(resolvedRoot, cwd) + : resolvedRoot; + + if (!isPathWithinRoot(resolvedRoot, resolvedCwd)) { + throw new Error(`cwd '${resolvedCwd}' is outside of sandbox root '${resolvedRoot}'`); + } + + return resolvedCwd; +}; + +const normalizeCommand = (command: string): string => path.basename(command); + +const normalizeIsolationProvider = ( + provider?: LocalSandboxIsolationProvider, +): LocalSandboxIsolationProvider => provider ?? "none"; + +const resolveIsolationPaths = ( + paths: string[] | undefined, + rootDir: string | undefined, +): string[] => { + if (!paths || paths.length === 0) { + return []; + } + return paths + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0) + .map((entry) => { + if (path.isAbsolute(entry)) { + return path.resolve(entry); + } + if (rootDir) { + return path.resolve(rootDir, entry); + } + return path.resolve(entry); + }); +}; + +const SYSTEM_BINARIES_PATHS = { + darwin: [ + "/System/Library", + "/System/Applications", + "/usr/bin", + "/usr/sbin", + "/bin", + "/sbin", + "/usr/lib", + "/usr/libexec", + "/usr/share", + "/usr/local/bin", + "/opt/homebrew/bin", + ], + linux: [ + "/usr/bin", + "/usr/sbin", + "/bin", + "/sbin", + "/usr/lib", + "/usr/lib64", + "/lib", + "/lib64", + "/usr/share", + "/usr/local/bin", + "/etc", + ], +}; + +const getSystemBinaryPaths = (): string[] => { + if (process.platform === "darwin") { + return SYSTEM_BINARIES_PATHS.darwin; + } + if (process.platform === "linux") { + return SYSTEM_BINARIES_PATHS.linux; + } + return []; +}; + +const resolveExecutable = async (command: string): Promise => { + const pathValue = process.env.PATH ?? ""; + if (!pathValue) { + return null; + } + + const extensions = process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""]; + + for (const dir of pathValue.split(path.delimiter)) { + if (!dir) { + continue; + } + for (const extension of extensions) { + const candidate = path.join(dir, `${command}${extension}`); + try { + await fs.access(candidate, fsConstants.X_OK); + return candidate; + } catch { + // ignore non-executable candidate + } + } + } + + return null; +}; + +export const detectLocalSandboxIsolation = async (): Promise => { + if (process.platform === "darwin") { + return (await resolveExecutable("sandbox-exec")) ? "sandbox-exec" : "none"; + } + if (process.platform === "linux") { + return (await resolveExecutable("bwrap")) ? "bwrap" : "none"; + } + return "none"; +}; + +const escapeSandboxProfileValue = (value: string): string => value.replace(/"/g, '\\"'); + +const buildSandboxExecProfile = (options: { + rootDir?: string; + allowNetwork?: boolean; + allowSystemBinaries?: boolean; + readWritePaths?: string[]; + readOnlyPaths?: string[]; +}): string => { + const resolvedRoot = options.rootDir ? path.resolve(options.rootDir) : undefined; + const readWritePaths = new Set(resolveIsolationPaths(options.readWritePaths, resolvedRoot)); + const readOnlyPaths = new Set(resolveIsolationPaths(options.readOnlyPaths, resolvedRoot)); + if (options.allowSystemBinaries) { + for (const entry of getSystemBinaryPaths()) { + readOnlyPaths.add(entry); + } + } + + if (resolvedRoot) { + readWritePaths.add(resolvedRoot); + } + + readWritePaths.add("/dev"); + + const allowReadAll = readOnlyPaths.size === 0; + const readAllowedPaths = allowReadAll + ? null + : new Set([...readOnlyPaths, ...readWritePaths]); + + const lines: string[] = []; + lines.push("(version 1)"); + lines.push("(deny default)"); + lines.push("(allow process*)"); + + if (allowReadAll) { + lines.push('(allow file-read* (subpath "/"))'); + } else { + lines.push( + `(allow file-read* ${Array.from(readAllowedPaths ?? []) + .map((p) => `(subpath "${escapeSandboxProfileValue(p)}")`) + .join(" ")})`, + ); + } + + if (readWritePaths.size > 0) { + lines.push( + `(allow file-write* ${Array.from(readWritePaths) + .map((p) => `(subpath "${escapeSandboxProfileValue(p)}")`) + .join(" ")})`, + ); + } + + if (options.allowNetwork) { + lines.push("(allow network*)"); + } + + return lines.join("\n"); +}; + +const loadSeatbeltProfile = async (params: { + rootDir?: string; + isolation?: LocalSandboxIsolationOptions; +}): Promise => { + if (params.isolation?.profile) { + return params.isolation.profile; + } + if (params.isolation?.seatbeltProfilePath) { + return await fs.readFile(params.isolation.seatbeltProfilePath, "utf-8"); + } + return buildSandboxExecProfile({ + rootDir: params.rootDir, + allowNetwork: params.isolation?.allowNetwork, + allowSystemBinaries: params.isolation?.allowSystemBinaries, + readWritePaths: params.isolation?.readWritePaths, + readOnlyPaths: params.isolation?.readOnlyPaths, + }); +}; + +const buildSandboxedCommand = async (params: { + command: string; + args: string[]; + cwd?: string; + isolation?: LocalSandboxIsolationOptions; + rootDir?: string; +}): Promise<{ command: string; args: string[] }> => { + const provider = normalizeIsolationProvider(params.isolation?.provider); + if (provider === "none") { + return { command: params.command, args: params.args }; + } + + if (provider === "sandbox-exec") { + if (process.platform !== "darwin") { + throw new Error("sandbox-exec isolation is only supported on macOS."); + } + const profile = await loadSeatbeltProfile({ + rootDir: params.rootDir, + isolation: params.isolation, + }); + + return { + command: "sandbox-exec", + args: ["-p", profile, params.command, ...params.args], + }; + } + + if (provider === "bwrap") { + if (process.platform !== "linux") { + throw new Error("bwrap isolation is only supported on Linux."); + } + + const resolvedRoot = params.rootDir ? path.resolve(params.rootDir) : undefined; + const readWritePaths = new Set( + resolveIsolationPaths(params.isolation?.readWritePaths, resolvedRoot), + ); + const readOnlyPaths = new Set( + resolveIsolationPaths(params.isolation?.readOnlyPaths, resolvedRoot), + ); + if (params.isolation?.allowSystemBinaries) { + for (const entry of getSystemBinaryPaths()) { + readOnlyPaths.add(entry); + } + } + + if (resolvedRoot) { + readWritePaths.add(resolvedRoot); + } + + const allowReadAll = readOnlyPaths.size === 0; + const bwrapArgs: string[] = [ + "--die-with-parent", + "--unshare-user", + "--unshare-pid", + ...(params.isolation?.bwrapArgs ?? []), + ]; + + const allowNetwork = params.isolation?.allowNetwork === true; + if (!allowNetwork) { + bwrapArgs.push("--unshare-net"); + } + + bwrapArgs.push("--proc", "/proc", "--dev", "/dev"); + + if (allowReadAll) { + bwrapArgs.push("--ro-bind", "/", "/"); + } else { + for (const entry of readOnlyPaths) { + bwrapArgs.push("--ro-bind", entry, entry); + } + } + + for (const entry of readWritePaths) { + bwrapArgs.push("--bind", entry, entry); + } + + bwrapArgs.push("--", params.command, ...params.args); + + return { command: "bwrap", args: bwrapArgs }; + } + + return { command: params.command, args: params.args }; +}; + +export class LocalSandbox implements WorkspaceSandbox { + name = "local"; + status: WorkspaceSandboxStatus = "ready"; + private readonly rootDir?: string; + private readonly autoRootDir: boolean; + private readonly cleanupOnDestroy: boolean; + private readonly defaultTimeoutMs: number; + private readonly maxOutputBytes: number; + private readonly env: Record; + private readonly inheritProcessEnv: boolean; + private readonly allowedCommands?: Set; + private readonly blockedCommands?: Set; + private readonly isolation?: LocalSandboxIsolationOptions; + + constructor(options: LocalSandboxOptions = {}) { + const resolvedRootDir = options.rootDir ?? path.resolve(process.cwd(), ".sandbox"); + this.rootDir = resolvedRootDir; + this.autoRootDir = options.rootDir === undefined; + this.cleanupOnDestroy = options.cleanupOnDestroy ?? false; + this.defaultTimeoutMs = options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS; + this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + this.env = normalizeEnv(options.env); + this.inheritProcessEnv = options.inheritProcessEnv === true; + this.allowedCommands = options.allowedCommands ? new Set(options.allowedCommands) : undefined; + this.blockedCommands = options.blockedCommands ? new Set(options.blockedCommands) : undefined; + this.isolation = options.isolation; + } + + private rootDirReady?: Promise; + + private async ensureRootDir(): Promise { + if (!this.autoRootDir || !this.rootDir) { + return; + } + if (!this.rootDirReady) { + this.rootDirReady = fs.mkdir(this.rootDir, { recursive: true }).then(() => undefined); + } + await this.rootDirReady; + } + + static async detectIsolation(): Promise { + return detectLocalSandboxIsolation(); + } + + start(): void { + if (this.status === "destroyed") { + throw new Error("Sandbox has been destroyed"); + } + this.status = "ready"; + } + + stop(): void { + if (this.status === "destroyed") { + return; + } + this.status = "idle"; + } + + destroy(): void { + if (this.cleanupOnDestroy && this.autoRootDir && this.rootDir) { + fs.rm(this.rootDir, { recursive: true, force: true }).catch(() => {}); + } + this.status = "destroyed"; + } + + getInfo(): Record { + return { + name: this.name, + status: this.status, + rootDir: this.rootDir, + autoRootDir: this.autoRootDir, + cleanupOnDestroy: this.cleanupOnDestroy, + defaultTimeoutMs: this.defaultTimeoutMs, + maxOutputBytes: this.maxOutputBytes, + inheritProcessEnv: this.inheritProcessEnv, + isolation: this.isolation + ? { + provider: normalizeIsolationProvider(this.isolation.provider), + allowNetwork: this.isolation.allowNetwork, + allowSystemBinaries: this.isolation.allowSystemBinaries, + readWritePaths: this.isolation.readWritePaths, + readOnlyPaths: this.isolation.readOnlyPaths, + seatbeltProfilePath: this.isolation.seatbeltProfilePath, + bwrapArgs: this.isolation.bwrapArgs, + hasProfileOverride: Boolean(this.isolation.profile), + } + : undefined, + allowedCommands: this.allowedCommands ? Array.from(this.allowedCommands) : undefined, + blockedCommands: this.blockedCommands ? Array.from(this.blockedCommands) : undefined, + }; + } + + getInstructions(): string | null { + const lines: string[] = ["Local sandbox for running shell commands."]; + if (this.rootDir) { + lines.push(`Root directory: ${this.rootDir}`); + } + if (this.allowedCommands && this.allowedCommands.size > 0) { + lines.push(`Allowed commands: ${Array.from(this.allowedCommands).join(", ")}`); + } + if (this.blockedCommands && this.blockedCommands.size > 0) { + lines.push(`Blocked commands: ${Array.from(this.blockedCommands).join(", ")}`); + } + return lines.join("\n"); + } + + async execute(options: WorkspaceSandboxExecuteOptions): Promise { + if (this.status === "destroyed") { + throw new Error("Sandbox has been destroyed"); + } + if (this.status === "idle") { + this.status = "ready"; + } + + const startTime = Date.now(); + const command = options.command?.trim(); + + if (!command) { + throw new Error("Sandbox command is required"); + } + + const commandKey = normalizeCommand(command); + if (this.allowedCommands && !this.allowedCommands.has(commandKey)) { + throw new Error(`Command '${commandKey}' is not allowed`); + } + if (this.blockedCommands?.has(commandKey)) { + throw new Error(`Command '${commandKey}' is blocked`); + } + + await this.ensureRootDir(); + const cwd = resolveCwd(this.rootDir, options.cwd); + const timeoutMs = + options.timeoutMs === undefined ? this.defaultTimeoutMs : Math.max(0, options.timeoutMs); + const maxOutputBytes = + options.maxOutputBytes === undefined + ? this.maxOutputBytes + : Math.max(0, options.maxOutputBytes); + + const envBase = this.inheritProcessEnv ? normalizeEnv(process.env) : resolvePathEnv(); + const envMerged = { + ...envBase, + ...this.env, + ...normalizeEnv(options.env), + }; + + const stdoutBuffer = initOutputBuffer(); + const stderrBuffer = initOutputBuffer(); + let timedOut = false; + let aborted = false; + + const { command: execCommand, args: execArgs } = await buildSandboxedCommand({ + command, + args: options.args ?? [], + cwd, + isolation: this.isolation, + rootDir: this.rootDir, + }); + + return await new Promise((resolve, reject) => { + const proc = spawn(execCommand, execArgs, { + cwd, + env: envMerged, + stdio: "pipe", + }); + + let timeoutId: NodeJS.Timeout | undefined; + const abortSignal = options.signal; + const onAbort = () => { + aborted = true; + proc.kill("SIGTERM"); + setTimeout(() => { + if (!proc.killed) { + proc.kill("SIGKILL"); + } + }, 1000); + }; + + if (abortSignal) { + if (abortSignal.aborted) { + onAbort(); + } else { + abortSignal.addEventListener("abort", onAbort, { once: true }); + } + } + + if (timeoutMs > 0) { + timeoutId = setTimeout(() => { + timedOut = true; + proc.kill("SIGTERM"); + setTimeout(() => { + if (!proc.killed) { + proc.kill("SIGKILL"); + } + }, 1000); + }, timeoutMs); + } + + proc.stdout?.on("data", (data: Buffer) => { + appendOutput(stdoutBuffer, data, maxOutputBytes); + if (options.onStdout) { + try { + options.onStdout(data.toString("utf-8")); + } catch { + // ignore callback errors + } + } + }); + + proc.stderr?.on("data", (data: Buffer) => { + appendOutput(stderrBuffer, data, maxOutputBytes); + if (options.onStderr) { + try { + options.onStderr(data.toString("utf-8")); + } catch { + // ignore callback errors + } + } + }); + + proc.on("error", (error) => { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (abortSignal) { + abortSignal.removeEventListener("abort", onAbort); + } + reject(error); + }); + + proc.on("close", (code, signal) => { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (abortSignal) { + abortSignal.removeEventListener("abort", onAbort); + } + resolve({ + stdout: toOutputString(stdoutBuffer), + stderr: toOutputString(stderrBuffer), + exitCode: code, + signal: signal ? String(signal) : undefined, + durationMs: Date.now() - startTime, + timedOut, + aborted, + stdoutTruncated: stdoutBuffer.truncated, + stderrTruncated: stderrBuffer.truncated, + }); + }); + + if (options.stdin !== undefined) { + proc.stdin?.write(options.stdin); + } + proc.stdin?.end(); + }); + } +} diff --git a/packages/core/src/workspace/sandbox/toolkit.spec.ts b/packages/core/src/workspace/sandbox/toolkit.spec.ts new file mode 100644 index 000000000..ae400ccbe --- /dev/null +++ b/packages/core/src/workspace/sandbox/toolkit.spec.ts @@ -0,0 +1,55 @@ +import { promises as fs } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { describe, expect, it } from "vitest"; +import { Workspace } from "../index"; +import { LocalSandbox } from "./local"; +import { createWorkspaceSandboxToolkit } from "./toolkit"; + +const buildExecuteOptions = () => ({ + toolContext: { callId: "tool-call-1" }, + systemContext: new Map(), + abortController: new AbortController(), +}); + +describe("Workspace sandbox toolkit", () => { + it("evicts large stdout to workspace files", async () => { + const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), "voltagent-sandbox-")); + const sandbox = new LocalSandbox({ rootDir: tempDir }); + const workspace = new Workspace({ + sandbox, + filesystem: {}, + }); + + const toolkit = createWorkspaceSandboxToolkit( + { + sandbox: workspace.sandbox, + workspace, + filesystem: workspace.filesystem, + }, + { + outputEvictionBytes: 10, + outputEvictionPath: "/sandbox_results", + }, + ); + + const executeTool = toolkit.tools.find((tool) => tool.name === "execute_command"); + if (!executeTool?.execute) { + throw new Error("execute_command tool not found"); + } + + const script = "console.log('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')"; + const result = await executeTool.execute( + { command: process.execPath, args: ["-e", script] }, + buildExecuteOptions() as any, + ); + + expect(String(result)).toContain("saved to /sandbox_results/tool-call-1.stdout.txt"); + + const saved = await workspace.filesystem.read("/sandbox_results/tool-call-1.stdout.txt"); + expect(saved).toContain("aaaaaaaa"); + + sandbox.destroy(); + await fs.rm(tempDir, { recursive: true, force: true }); + }); +}); diff --git a/packages/core/src/workspace/sandbox/toolkit.ts b/packages/core/src/workspace/sandbox/toolkit.ts new file mode 100644 index 000000000..fdf435f65 --- /dev/null +++ b/packages/core/src/workspace/sandbox/toolkit.ts @@ -0,0 +1,330 @@ +import type { Span } from "@opentelemetry/api"; +import { z } from "zod"; +import type { Agent } from "../../agent/agent"; +import type { OperationContext } from "../../agent/types"; +import { createTool } from "../../tool"; +import { createToolkit } from "../../tool/toolkit"; +import type { Toolkit } from "../../tool/toolkit"; +import { randomUUID } from "../../utils/id"; +import type { WorkspaceFilesystem } from "../filesystem"; +import { sanitizeToolCallId } from "../filesystem/utils"; +import { withOperationTimeout } from "../timeout"; +import type { + WorkspaceToolPolicies, + WorkspaceToolPolicy, + WorkspaceToolPolicyGroup, +} from "../tool-policy"; +import type { WorkspaceIdentity } from "../types"; +import type { WorkspaceSandbox, WorkspaceSandboxResult } from "./types"; + +const WORKSPACE_SANDBOX_SYSTEM_PROMPT = `You can execute shell commands in the workspace sandbox. + +- execute_command: run a shell command with optional args, cwd, env, and timeout`; + +const EXECUTE_COMMAND_TOOL_DESCRIPTION = + "Execute a shell command in the workspace sandbox with optional args, cwd, env, and timeout."; +const WORKSPACE_SANDBOX_TAGS = ["workspace", "sandbox"] as const; + +export type WorkspaceSandboxToolkitOptions = { + systemPrompt?: string | null; + operationTimeoutMs?: number; + customToolDescription?: string | null; + outputEvictionBytes?: number; + outputEvictionPath?: string; + toolPolicies?: WorkspaceToolPolicies | null; +}; + +export type WorkspaceSandboxToolkitContext = { + sandbox?: WorkspaceSandbox; + workspace?: WorkspaceIdentity; + agent?: Agent; + filesystem?: WorkspaceFilesystem; +}; + +export type WorkspaceSandboxToolName = "execute_command"; + +const setWorkspaceSpanAttributes = ( + operationContext: OperationContext, + attributes: Record, +): void => { + const toolSpan = operationContext.systemContext.get("parentToolSpan") as Span | undefined; + if (!toolSpan) { + return; + } + + for (const [key, value] of Object.entries(attributes)) { + if (value !== undefined) { + toolSpan.setAttribute(key, value as never); + } + } +}; + +const buildWorkspaceAttributes = (workspace?: WorkspaceIdentity): Record => ({ + "workspace.id": workspace?.id, + "workspace.name": workspace?.name, + "workspace.scope": workspace?.scope, +}); + +const formatSandboxHeader = (result: WorkspaceSandboxResult): string[] => { + const lines: string[] = []; + const exitCodeLabel = result.exitCode === null ? "unknown" : String(result.exitCode); + + lines.push(`Exit code: ${exitCodeLabel}`); + lines.push(`Duration: ${result.durationMs} ms`); + + if (result.signal) { + lines.push(`Signal: ${result.signal}`); + } + if (result.timedOut) { + lines.push("Timed out: true"); + } + if (result.aborted) { + lines.push("Aborted: true"); + } + if (result.stdoutTruncated) { + lines.push("Stdout truncated: true"); + } + if (result.stderrTruncated) { + lines.push("Stderr truncated: true"); + } + + return lines; +}; + +type StreamEvictionResult = { + content: string; + bytes: number; + truncated: boolean; + evicted: boolean; + path?: string; + error?: string; +}; + +const DEFAULT_EVICTION_BYTES = 20000 * 4; +const DEFAULT_EVICTION_PATH = "/sandbox_results"; +const TRUNCATION_SUFFIX = "\n... [output truncated]"; + +const normalizeEvictionPath = (value?: string): string => { + const trimmed = value?.trim(); + const base = trimmed && trimmed.length > 0 ? trimmed : DEFAULT_EVICTION_PATH; + const withSlash = base.startsWith("/") ? base : `/${base}`; + return withSlash.endsWith("/") ? withSlash.slice(0, -1) : withSlash; +}; + +const truncateByBytes = (value: string, maxBytes: number): string => { + if (maxBytes <= 0) { + return ""; + } + const size = Buffer.byteLength(value, "utf-8"); + if (size <= maxBytes) { + return value; + } + const suffixBytes = Buffer.byteLength(TRUNCATION_SUFFIX, "utf-8"); + const targetBytes = Math.max(0, maxBytes - suffixBytes); + const buf = Buffer.from(value, "utf-8"); + const truncated = buf.subarray(0, targetBytes).toString("utf-8"); + return `${truncated}${TRUNCATION_SUFFIX}`; +}; + +const formatStreamOutput = (label: string, info: StreamEvictionResult): string[] => { + const lines: string[] = []; + if (info.evicted && info.path) { + const note = info.truncated ? " (truncated)" : ""; + lines.push(`${label}: saved to ${info.path} (${info.bytes} bytes${note})`); + if (info.error) { + lines.push(`${label} eviction error: ${info.error}`); + } + return lines; + } + + if (info.content) { + lines.push(`${label}:`); + lines.push(info.content); + return lines; + } + + lines.push(`${label}: (empty)`); + return lines; +}; + +export const createWorkspaceSandboxToolkit = ( + context: WorkspaceSandboxToolkitContext, + options: WorkspaceSandboxToolkitOptions = {}, +): Toolkit => { + const systemPrompt = + options.systemPrompt === undefined ? WORKSPACE_SANDBOX_SYSTEM_PROMPT : options.systemPrompt; + const evictionBytes = + options.outputEvictionBytes === undefined + ? DEFAULT_EVICTION_BYTES + : Math.max(0, options.outputEvictionBytes); + const evictionBasePath = normalizeEvictionPath(options.outputEvictionPath); + + const isToolPolicyGroup = ( + policies: WorkspaceToolPolicies, + ): policies is WorkspaceToolPolicyGroup => + Object.prototype.hasOwnProperty.call(policies, "tools") || + Object.prototype.hasOwnProperty.call(policies, "defaults"); + + const resolveToolPolicy = (name: WorkspaceSandboxToolName) => { + const toolPolicies = options.toolPolicies; + if (!toolPolicies) { + return undefined; + } + if (isToolPolicyGroup(toolPolicies)) { + const defaults = toolPolicies.defaults ?? {}; + const override = toolPolicies.tools?.[name] ?? {}; + const merged = { ...defaults, ...override }; + return Object.keys(merged).length > 0 ? merged : undefined; + } + return toolPolicies[name]; + }; + + const isToolEnabled = (name: WorkspaceSandboxToolName) => + resolveToolPolicy(name)?.enabled ?? true; + + const executeTool = createTool({ + name: "execute_command", + description: options.customToolDescription || EXECUTE_COMMAND_TOOL_DESCRIPTION, + tags: [...WORKSPACE_SANDBOX_TAGS], + needsApproval: resolveToolPolicy("execute_command")?.needsApproval, + parameters: z.object({ + command: z.string().describe("Command to execute"), + args: z.array(z.string()).optional().describe("Command arguments"), + cwd: z.string().optional().describe("Working directory for the command"), + timeout_ms: z.coerce.number().optional().describe("Timeout in milliseconds"), + env: z.record(z.string()).optional().describe("Environment variables to set"), + stdin: z.string().optional().describe("Optional stdin input for the command"), + max_output_bytes: z.coerce + .number() + .optional() + .describe("Maximum output bytes to capture per stream (stdout or stderr)"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "sandbox.execute", + "workspace.sandbox.command": input.command, + "workspace.sandbox.args": input.args, + "workspace.sandbox.cwd": input.cwd, + "workspace.sandbox.timeout_ms": input.timeout_ms, + }); + + if (!context.sandbox) { + return "Workspace sandbox is not configured."; + } + + try { + const result = await context.sandbox.execute({ + command: input.command, + args: input.args, + cwd: input.cwd, + env: input.env, + timeoutMs: input.timeout_ms, + maxOutputBytes: input.max_output_bytes, + stdin: input.stdin, + signal: operationContext.abortController?.signal, + }); + + setWorkspaceSpanAttributes(operationContext, { + "workspace.sandbox.exit_code": result.exitCode ?? undefined, + }); + + const callId = executeOptions?.toolContext?.callId || randomUUID(); + const safeCallId = sanitizeToolCallId(callId); + + const evictStream = async ( + stream: "stdout" | "stderr", + content: string, + truncated: boolean, + ): Promise => { + const bytes = Buffer.byteLength(content, "utf-8"); + const shouldEvict = + content.length > 0 && + evictionBytes > 0 && + (bytes > evictionBytes || truncated) && + Boolean(context.filesystem); + + if (!shouldEvict) { + const safeContent = + evictionBytes > 0 && bytes > evictionBytes + ? truncateByBytes(content, evictionBytes) + : content; + return { + content: safeContent, + bytes, + truncated, + evicted: false, + }; + } + + const filePath = `${evictionBasePath}/${safeCallId}.${stream}.txt`; + const filesystem = context.filesystem; + if (!filesystem) { + const safeContent = truncateByBytes(content, evictionBytes); + return { + content: safeContent, + bytes, + truncated, + evicted: false, + path: filePath, + error: "Workspace filesystem is not configured.", + }; + } + + const writeResult = await filesystem.write(filePath, content, { + context: { agent: context.agent, operationContext }, + }); + + if (writeResult.error) { + const safeContent = truncateByBytes(content, evictionBytes); + return { + content: safeContent, + bytes, + truncated, + evicted: false, + path: filePath, + error: writeResult.error, + }; + } + + return { + content: "", + bytes, + truncated, + evicted: true, + path: filePath, + }; + }; + + const stdoutInfo = await evictStream("stdout", result.stdout, result.stdoutTruncated); + const stderrInfo = await evictStream("stderr", result.stderr, result.stderrTruncated); + + const lines: string[] = []; + lines.push(...formatSandboxHeader(result)); + lines.push(...formatStreamOutput("STDOUT", stdoutInfo)); + lines.push(...formatStreamOutput("STDERR", stderrInfo)); + + return lines.join("\n"); + } catch (error: any) { + const message = error?.message ? String(error.message) : "Unknown sandbox error"; + return `Error executing command: ${message}`; + } + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const tools = isToolEnabled("execute_command") ? [executeTool] : []; + + return createToolkit({ + name: "workspace_sandbox", + description: "Workspace sandbox tools", + tools, + instructions: systemPrompt || undefined, + addInstructions: Boolean(systemPrompt), + }); +}; diff --git a/packages/core/src/workspace/sandbox/types.ts b/packages/core/src/workspace/sandbox/types.ts new file mode 100644 index 000000000..f4a121096 --- /dev/null +++ b/packages/core/src/workspace/sandbox/types.ts @@ -0,0 +1,37 @@ +export type WorkspaceSandboxExecuteOptions = { + command: string; + args?: string[]; + cwd?: string; + env?: Record; + timeoutMs?: number; + maxOutputBytes?: number; + stdin?: string; + signal?: AbortSignal; + onStdout?: (chunk: string) => void; + onStderr?: (chunk: string) => void; +}; + +export type WorkspaceSandboxStatus = "idle" | "ready" | "destroyed" | "error"; + +export type WorkspaceSandboxResult = { + stdout: string; + stderr: string; + exitCode: number | null; + signal?: string; + durationMs: number; + timedOut: boolean; + aborted: boolean; + stdoutTruncated: boolean; + stderrTruncated: boolean; +}; + +export interface WorkspaceSandbox { + name: string; + status?: WorkspaceSandboxStatus; + start?: () => Promise | void; + stop?: () => Promise | void; + destroy?: () => Promise | void; + getInfo?: () => Record; + getInstructions?: () => string | null; + execute(options: WorkspaceSandboxExecuteOptions): Promise; +} diff --git a/packages/core/src/workspace/search/bm25.ts b/packages/core/src/workspace/search/bm25.ts new file mode 100644 index 000000000..2e11ded97 --- /dev/null +++ b/packages/core/src/workspace/search/bm25.ts @@ -0,0 +1,161 @@ +export type WorkspaceBm25Document = { + id: string; + path: string; + length: number; + termFreq: Map; + metadata?: Record; +}; + +export type WorkspaceBm25Options = { + k1?: number; + b?: number; +}; + +const DEFAULT_K1 = 1.5; +const DEFAULT_B = 0.75; + +const tokenize = (text: string): string[] => { + return text + .toLowerCase() + .split(/[^a-z0-9]+/g) + .filter((token) => token.length > 0); +}; + +const buildTermFreq = (tokens: string[]): Map => { + const freq = new Map(); + for (const token of tokens) { + freq.set(token, (freq.get(token) ?? 0) + 1); + } + return freq; +}; + +export class WorkspaceBm25Index { + private readonly k1: number; + private readonly b: number; + private readonly docs = new Map(); + private readonly docFreq = new Map(); + private totalDocs = 0; + private totalLength = 0; + + constructor(options: WorkspaceBm25Options = {}) { + this.k1 = options.k1 ?? DEFAULT_K1; + this.b = options.b ?? DEFAULT_B; + } + + getDocument(id: string): WorkspaceBm25Document | undefined { + return this.docs.get(id); + } + + addDocument(params: { + id: string; + path: string; + content: string; + metadata?: Record; + }): void { + if (this.docs.has(params.id)) { + this.removeDocument(params.id); + } + + const tokens = tokenize(params.content); + const termFreq = buildTermFreq(tokens); + const uniqueTerms = new Set(termFreq.keys()); + + for (const term of uniqueTerms) { + this.docFreq.set(term, (this.docFreq.get(term) ?? 0) + 1); + } + + const doc: WorkspaceBm25Document = { + id: params.id, + path: params.path, + length: tokens.length, + termFreq, + metadata: params.metadata, + }; + + this.docs.set(params.id, doc); + this.totalDocs += 1; + this.totalLength += tokens.length; + } + + removeDocument(id: string): void { + const doc = this.docs.get(id); + if (!doc) { + return; + } + + const uniqueTerms = new Set(doc.termFreq.keys()); + for (const term of uniqueTerms) { + const current = this.docFreq.get(term); + if (!current) { + continue; + } + if (current <= 1) { + this.docFreq.delete(term); + } else { + this.docFreq.set(term, current - 1); + } + } + + this.docs.delete(id); + this.totalDocs = Math.max(0, this.totalDocs - 1); + this.totalLength = Math.max(0, this.totalLength - doc.length); + } + + search( + query: string, + options: { + limit?: number; + filter?: (doc: WorkspaceBm25Document) => boolean; + } = {}, + ): Array<{ id: string; score: number }> { + const tokens = tokenize(query); + if (tokens.length === 0 || this.totalDocs === 0) { + return []; + } + + const queryTerms = Array.from(new Set(tokens)); + const rawAvgDocLength = this.totalDocs > 0 ? this.totalLength / this.totalDocs : 0; + const avgDocLength = rawAvgDocLength > 0 ? rawAvgDocLength : 1; + const scores = new Map(); + + for (const doc of this.docs.values()) { + if (options.filter && !options.filter(doc)) { + continue; + } + + let score = 0; + for (const term of queryTerms) { + const tf = doc.termFreq.get(term) ?? 0; + if (tf === 0) { + continue; + } + + const df = this.docFreq.get(term) ?? 0; + if (df === 0) { + continue; + } + + const idf = Math.log(1 + (this.totalDocs - df + 0.5) / (df + 0.5)); + const numerator = tf * (this.k1 + 1); + const denominator = tf + this.k1 * (1 - this.b + (this.b * doc.length) / avgDocLength); + score += idf * (numerator / denominator); + } + + if (score > 0) { + scores.set(doc.id, score); + } + } + + const results = Array.from(scores.entries()) + .map(([id, score]) => ({ id, score })) + .sort((a, b) => b.score - a.score); + + if (options.limit !== undefined) { + return results.slice(0, options.limit); + } + + return results; + } +} + +export const tokenizeSearchText = tokenize; diff --git a/packages/core/src/workspace/search/index.spec.ts b/packages/core/src/workspace/search/index.spec.ts new file mode 100644 index 000000000..33d13758c --- /dev/null +++ b/packages/core/src/workspace/search/index.spec.ts @@ -0,0 +1,196 @@ +import { describe, expect, it } from "vitest"; +import { Workspace } from ".."; +import type { EmbeddingAdapter } from "../../memory/adapters/embedding/types"; +import { InMemoryVectorAdapter } from "../../memory/adapters/vector/in-memory"; +import { WorkspaceFilesystem } from "../filesystem"; +import { WorkspaceSearch } from "./index"; + +const createExecuteOptions = () => ({ + systemContext: new Map(), + abortController: new AbortController(), +}); + +const buildFileData = (content: string) => { + const timestamp = new Date().toISOString(); + return { + content: content.split("\n"), + created_at: timestamp, + modified_at: timestamp, + }; +}; + +describe("WorkspaceSearch", () => { + it("returns normalized scores, line ranges, and score details", async () => { + const filesystem = new WorkspaceFilesystem(); + const search = new WorkspaceSearch({ filesystem }); + + const content = "alpha\nbeta gamma\nbeta again\n"; + await search.indexContent("/doc.txt", content); + + const results = await search.search("beta", { mode: "bm25", topK: 5 }); + expect(results.length).toBeGreaterThan(0); + + const result = results[0]; + expect(result.path).toBe("/doc.txt"); + expect(result.score).toBeGreaterThanOrEqual(0); + expect(result.score).toBeLessThanOrEqual(1); + expect(result.scoreDetails?.bm25).toBeDefined(); + expect(result.lineRange).toEqual({ start: 2, end: 3 }); + }); + + it("applies minScore filtering", async () => { + const filesystem = new WorkspaceFilesystem(); + const search = new WorkspaceSearch({ filesystem }); + + await search.indexContent("/doc.txt", "hello hello hello world"); + await search.indexContent("/other.txt", "hello there"); + const results = await search.search("hello", { mode: "bm25", minScore: 0.9 }); + + expect(results.length).toBe(1); + }); + + it("supports vector and hybrid search modes", async () => { + const filesystem = new WorkspaceFilesystem(); + const vector = new InMemoryVectorAdapter(); + const embedding: EmbeddingAdapter = { + embed: async (text: string) => { + const lower = text.toLowerCase(); + const countA = lower.split("a").length - 1; + const countB = lower.split("b").length - 1; + return [text.length, countA, countB]; + }, + embedBatch: async (texts: string[]) => Promise.all(texts.map((t) => embedding.embed(t))), + getDimensions: () => 3, + getModelName: () => "test-embedding", + }; + + const search = new WorkspaceSearch({ + filesystem, + embedding, + vector, + defaultMode: "hybrid", + }); + + await search.indexContent("/a.txt", "aaaa token"); + await search.indexContent("/b.txt", "bbbb"); + + const vectorResults = await search.search("aaaa", { mode: "vector", topK: 2 }); + expect(vectorResults[0]?.scoreDetails?.vector).toBeDefined(); + expect(vectorResults[0]?.vectorScore).toBeDefined(); + + const hybridResults = await search.search("aaaa", { mode: "hybrid", topK: 2 }); + const hybridForA = hybridResults.find((item) => item.path === "/a.txt"); + expect(hybridForA?.scoreDetails?.bm25).toBeDefined(); + expect(hybridForA?.scoreDetails?.vector).toBeDefined(); + }); + + it("formats index tool summaries", async () => { + const workspace = new Workspace({ + filesystem: { + files: { + "/docs/summary.txt": buildFileData("hello world"), + }, + }, + search: {}, + }); + const toolkit = workspace.createSearchToolkit(); + const executeOptions = createExecuteOptions() as any; + + const indexTool = toolkit.tools.find((tool) => tool.name === "workspace_index"); + const indexContentTool = toolkit.tools.find((tool) => tool.name === "workspace_index_content"); + if (!indexTool?.execute || !indexContentTool?.execute) { + throw new Error("Workspace search index tools not found"); + } + + const indexOutput = await indexTool.execute({ path: "/", glob: "**/*.txt" }, executeOptions); + expect(String(indexOutput)).toContain("Indexed 1 file(s)."); + expect(String(indexOutput)).toContain("Skipped 0 file(s)."); + + const contentOutput = await indexContentTool.execute( + { path: "/inline.txt", content: "alpha beta" }, + executeOptions, + ); + expect(String(contentOutput)).toContain("Indexed 1 file(s)."); + expect(String(contentOutput)).toContain("Skipped 0 file(s)."); + }); + + it("returns min_score filtered results with lineRange and scoreDetails", async () => { + const workspace = new Workspace({ search: {} }); + const toolkit = workspace.createSearchToolkit(); + const executeOptions = createExecuteOptions() as any; + + const indexContentTool = toolkit.tools.find((tool) => tool.name === "workspace_index_content"); + const searchTool = toolkit.tools.find((tool) => tool.name === "workspace_search"); + if (!indexContentTool?.execute || !searchTool?.execute) { + throw new Error("Workspace search tools not found"); + } + + await indexContentTool.execute( + { path: "/doc.txt", content: "alpha\nbeta beta beta\nbeta again\n" }, + executeOptions, + ); + await indexContentTool.execute({ path: "/other.txt", content: "beta" }, executeOptions); + + const output = (await searchTool.execute( + { query: "beta", min_score: 1, top_k: 5 }, + executeOptions, + )) as { + results: Array<{ + path: string; + lineRange?: { start: number; end: number }; + scoreDetails?: { bm25?: number }; + score: number; + }>; + total: number; + }; + + expect(output.results.length).toBe(1); + const [first] = output.results; + expect(first.lineRange).toEqual({ start: 2, end: 3 }); + expect(first.scoreDetails?.bm25).toBeDefined(); + expect(first.score).toBeGreaterThanOrEqual(0); + expect(first.score).toBeLessThanOrEqual(1); + + const modelOutput = searchTool.toModelOutput?.({ output }) as + | { type: string; value: string } + | undefined; + if (!modelOutput) { + throw new Error("workspace_search toModelOutput not available"); + } + expect(modelOutput?.value).toContain("Found 1 result(s):"); + expect(modelOutput?.value).toContain("lines 2-3"); + expect(modelOutput?.value).toContain("bm25="); + }); + + it("can return snippet-only output when include_content is false", async () => { + const workspace = new Workspace({ search: {} }); + const toolkit = workspace.createSearchToolkit(); + const executeOptions = createExecuteOptions() as any; + + const indexContentTool = toolkit.tools.find((tool) => tool.name === "workspace_index_content"); + const searchTool = toolkit.tools.find((tool) => tool.name === "workspace_search"); + if (!indexContentTool?.execute || !searchTool?.execute) { + throw new Error("Workspace search tools not found"); + } + + const content = "alpha beta gamma delta epsilon zeta eta theta I_WANT_FULL_CONTENT"; + await indexContentTool.execute({ path: "/doc.txt", content }, executeOptions); + + const output = (await searchTool.execute( + { + query: "beta", + include_content: false, + snippet_length: 24, + }, + executeOptions, + )) as { results: Array<{ content: string; snippet?: string }> }; + + expect(output.results[0]?.content).toBe(""); + expect(output.results[0]?.snippet).toContain("beta"); + + const modelOutput = searchTool.toModelOutput?.({ output }) as + | { type: string; value: string } + | undefined; + expect(modelOutput?.value).not.toContain("I_WANT_FULL_CONTENT"); + }); +}); diff --git a/packages/core/src/workspace/search/index.ts b/packages/core/src/workspace/search/index.ts new file mode 100644 index 000000000..9d137e615 --- /dev/null +++ b/packages/core/src/workspace/search/index.ts @@ -0,0 +1,937 @@ +import type { Span } from "@opentelemetry/api"; +import micromatch from "micromatch"; +import { z } from "zod"; +import type { Agent } from "../../agent/agent"; +import type { OperationContext } from "../../agent/types"; +import { AiSdkEmbeddingAdapter } from "../../memory/adapters/embedding/ai-sdk"; +import type { + EmbeddingAdapter, + EmbeddingAdapterConfig, + EmbeddingAdapterInput, + VectorAdapter, + VectorItem, +} from "../../memory/types"; +import { createTool } from "../../tool"; +import { createToolkit } from "../../tool/toolkit"; +import type { Toolkit } from "../../tool/toolkit"; +import type { WorkspaceFilesystem } from "../filesystem"; +import { truncateIfTooLong, validatePath } from "../filesystem/utils"; +import { withOperationTimeout } from "../timeout"; +import type { + WorkspaceToolPolicies, + WorkspaceToolPolicy, + WorkspaceToolPolicyGroup, +} from "../tool-policy"; +import type { WorkspaceComponentStatus, WorkspaceIdentity } from "../types"; +import { WorkspaceBm25Index, tokenizeSearchText } from "./bm25"; +import type { + WorkspaceSearchConfig, + WorkspaceSearchIndexPath, + WorkspaceSearchIndexSummary, + WorkspaceSearchMode, + WorkspaceSearchOptions, + WorkspaceSearchResult, +} from "./types"; + +const DEFAULT_TOP_K = 5; +const DEFAULT_SNIPPET_LENGTH = 240; +const DEFAULT_MAX_RESULT_CHARS = 2000; +const DEFAULT_MAX_FILE_BYTES = 2 * 1024 * 1024; +const DEFAULT_HYBRID_LEXICAL_WEIGHT = 0.5; +const DEFAULT_HYBRID_VECTOR_WEIGHT = 0.5; +const WORKSPACE_SEARCH_TAGS = ["workspace", "search"] as const; + +export type WorkspaceSearchToolkitOptions = { + systemPrompt?: string | null; + operationTimeoutMs?: number; + customIndexDescription?: string | null; + customIndexContentDescription?: string | null; + customSearchDescription?: string | null; + toolPolicies?: WorkspaceToolPolicies | null; +}; + +export type WorkspaceSearchToolkitContext = { + search?: WorkspaceSearch; + workspace?: WorkspaceIdentity; + agent?: Agent; + filesystem?: WorkspaceFilesystem; +}; + +export type WorkspaceSearchToolName = + | "workspace_index" + | "workspace_index_content" + | "workspace_search"; + +type WorkspaceSearchToolOutput = { + results: WorkspaceSearchResult[]; + total: number; +}; + +type WorkspaceSearchDocument = { + id: string; + path: string; + content: string; + metadata?: Record; +}; + +const isEmbeddingAdapter = (value: EmbeddingAdapterInput): value is EmbeddingAdapter => + typeof value === "object" && + value !== null && + "embed" in value && + typeof (value as EmbeddingAdapter).embed === "function"; + +const isEmbeddingAdapterConfig = (value: EmbeddingAdapterInput): value is EmbeddingAdapterConfig => + typeof value === "object" && value !== null && "model" in value && !isEmbeddingAdapter(value); + +const resolveEmbeddingAdapter = ( + embedding?: EmbeddingAdapterInput, +): EmbeddingAdapter | undefined => { + if (!embedding) { + return undefined; + } + + if (isEmbeddingAdapter(embedding)) { + return embedding; + } + + if (typeof embedding === "string") { + return new AiSdkEmbeddingAdapter(embedding); + } + + if (isEmbeddingAdapterConfig(embedding)) { + const { model, ...options } = embedding; + return new AiSdkEmbeddingAdapter(model, options); + } + + return new AiSdkEmbeddingAdapter(embedding); +}; + +const normalizePath = (value?: string): string | null => { + if (!value) { + return null; + } + try { + return validatePath(value); + } catch { + return null; + } +}; + +const normalizeDocumentPath = (value: string): string => { + const trimmed = value.trim(); + if (!trimmed) { + return "/"; + } + return trimmed.startsWith("/") ? trimmed : `/${trimmed}`; +}; + +const matchesPathFilter = (docPath: string, basePath: string | null, glob?: string): boolean => { + if (basePath && !docPath.startsWith(basePath)) { + return false; + } + + if (!glob) { + return true; + } + + const relative = basePath + ? docPath.slice(basePath.length).replace(/^\/+/, "") + : docPath.replace(/^\/+/, ""); + return micromatch.isMatch(relative, glob, { dot: true, nobrace: false }); +}; + +const buildSnippet = (content: string, query: string, length: number): string => { + const compact = content.replace(/\s+/g, " ").trim(); + if (compact.length <= length) { + return compact; + } + + const terms = tokenizeSearchText(query); + const lower = compact.toLowerCase(); + for (const term of terms) { + const idx = lower.indexOf(term); + if (idx >= 0) { + const start = Math.max(0, idx - Math.floor(length / 2)); + const end = Math.min(compact.length, start + length); + return compact.slice(start, end).trim(); + } + } + + return compact.slice(0, length).trim(); +}; + +const buildLineRange = ( + content: string, + query: string, +): { start: number; end: number } | undefined => { + const tokens = tokenizeSearchText(query); + if (tokens.length === 0) { + return undefined; + } + + const lowerTokens = tokens.map((token) => token.toLowerCase()); + const lines = content.split("\n"); + let start: number | null = null; + let end: number | null = null; + + for (let idx = 0; idx < lines.length; idx += 1) { + const line = lines[idx].toLowerCase(); + if (lowerTokens.some((token) => line.includes(token))) { + if (start === null) { + start = idx + 1; + } + end = idx + 1; + } + } + + if (start === null || end === null) { + return undefined; + } + + return { start, end }; +}; + +const clampScore = (value: number): number => Math.min(1, Math.max(0, value)); + +const normalizeScores = (scores: Array<{ id: string; score: number }>) => { + const maxScore = scores.reduce((max, item) => Math.max(max, item.score), 0); + if (maxScore <= 0) { + return new Map(scores.map((item) => [item.id, 0])); + } + return new Map(scores.map((item) => [item.id, clampScore(item.score / maxScore)])); +}; + +const clampScores = (scores: Array<{ id: string; score: number }>) => + new Map(scores.map((item) => [item.id, clampScore(item.score)])); + +export class WorkspaceSearch { + private readonly filesystem: WorkspaceFilesystem; + private readonly bm25: WorkspaceBm25Index; + private readonly documents = new Map(); + private readonly embedding?: EmbeddingAdapter; + private readonly vector?: VectorAdapter; + private readonly autoIndexPaths?: Array; + private readonly maxFileBytes: number; + private readonly snippetLength: number; + private readonly defaultMode: WorkspaceSearchMode; + private readonly defaultWeights: { lexicalWeight: number; vectorWeight: number }; + private autoIndexPromise?: Promise; + status: WorkspaceComponentStatus = "idle"; + + constructor(options: WorkspaceSearchConfig & { filesystem: WorkspaceFilesystem }) { + this.filesystem = options.filesystem; + this.bm25 = new WorkspaceBm25Index(options.bm25); + this.embedding = resolveEmbeddingAdapter(options.embedding); + this.vector = options.vector; + this.autoIndexPaths = options.autoIndexPaths; + this.maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES; + this.snippetLength = options.snippetLength ?? DEFAULT_SNIPPET_LENGTH; + this.defaultMode = options.defaultMode ?? (this.embedding && this.vector ? "hybrid" : "bm25"); + this.defaultWeights = { + lexicalWeight: options.hybrid?.lexicalWeight ?? DEFAULT_HYBRID_LEXICAL_WEIGHT, + vectorWeight: options.hybrid?.vectorWeight ?? DEFAULT_HYBRID_VECTOR_WEIGHT, + }; + + if (this.autoIndexPaths && this.autoIndexPaths.length > 0) { + this.autoIndexPromise = this.indexPaths(this.autoIndexPaths) + .then(() => undefined) + .catch((error) => { + console.error("Workspace search auto-index failed:", error); + return undefined; + }); + } + } + + async init(): Promise { + if (this.status === "destroyed") { + throw new Error("Workspace search has been destroyed."); + } + this.status = "ready"; + await this.ensureAutoIndex(); + } + + destroy(): void { + this.status = "destroyed"; + } + + getInfo(): Record { + return { + status: this.status, + defaultMode: this.defaultMode, + autoIndexPaths: this.autoIndexPaths, + maxFileBytes: this.maxFileBytes, + snippetLength: this.snippetLength, + hasEmbedding: Boolean(this.embedding), + hasVector: Boolean(this.vector), + documentCount: this.documents.size, + }; + } + + getInstructions(): string { + return WORKSPACE_SEARCH_SYSTEM_PROMPT; + } + + private async ensureAutoIndex(): Promise { + if (!this.autoIndexPaths || this.autoIndexPaths.length === 0) { + return; + } + if (!this.autoIndexPromise) { + this.autoIndexPromise = this.indexPaths(this.autoIndexPaths) + .then(() => undefined) + .catch((error) => { + console.error("Workspace search auto-index failed:", error); + return undefined; + }); + } + await this.autoIndexPromise; + } + + async indexPaths( + paths?: Array, + options?: { maxFileBytes?: number }, + ): Promise { + const targets = paths && paths.length > 0 ? paths : (this.autoIndexPaths ?? []); + const summary: WorkspaceSearchIndexSummary = { + indexed: 0, + vectorIndexed: this.embedding && this.vector ? 0 : undefined, + skipped: 0, + errors: [], + }; + + if (targets.length === 0) { + return summary; + } + + const maxFileBytes = options?.maxFileBytes ?? this.maxFileBytes; + + for (const entry of targets) { + const target = typeof entry === "string" ? { path: entry } : entry; + const basePath = target.path || "/"; + const glob = target.glob ?? "**/*"; + + let infos: Awaited>; + try { + infos = await this.filesystem.globInfo(glob, basePath); + } catch (error: any) { + summary.errors.push( + `Failed to glob ${basePath}: ${error?.message ? String(error.message) : "unknown error"}`, + ); + continue; + } + const docs: WorkspaceSearchDocument[] = []; + + for (const info of infos) { + if (maxFileBytes > 0 && info.size && info.size > maxFileBytes) { + summary.skipped += 1; + continue; + } + + try { + const data = await this.filesystem.readRaw(info.path); + const content = data.content.join("\n"); + const contentBytes = Buffer.byteLength(content, "utf-8"); + + if (maxFileBytes > 0 && contentBytes > maxFileBytes) { + summary.skipped += 1; + continue; + } + + docs.push({ + id: info.path, + path: info.path, + content, + metadata: { + size: info.size ?? contentBytes, + modified_at: info.modified_at, + }, + }); + } catch (error: any) { + summary.errors.push( + `Failed to read ${info.path}: ${error?.message ? String(error.message) : "unknown error"}`, + ); + } + } + + const result = await this.indexDocuments(docs); + summary.indexed += result.indexed; + if (result.vectorIndexed !== undefined) { + summary.vectorIndexed = (summary.vectorIndexed ?? 0) + result.vectorIndexed; + } + summary.skipped += result.skipped; + summary.errors.push(...result.errors); + } + + return summary; + } + + async indexDocuments(docs: WorkspaceSearchDocument[]): Promise { + const summary: WorkspaceSearchIndexSummary = { + indexed: 0, + vectorIndexed: this.embedding && this.vector ? 0 : undefined, + skipped: 0, + errors: [], + }; + + if (docs.length === 0) { + return summary; + } + + for (const doc of docs) { + this.bm25.addDocument({ + id: doc.id, + path: doc.path, + content: doc.content, + metadata: doc.metadata, + }); + this.documents.set(doc.id, doc); + } + + summary.indexed += docs.length; + + if (this.embedding && this.vector) { + try { + const embeddings = await this.embedding.embedBatch(docs.map((doc) => doc.content)); + const items: VectorItem[] = docs.map((doc, idx) => ({ + id: doc.id, + vector: embeddings[idx], + metadata: { + path: doc.path, + }, + })); + await this.vector.storeBatch(items); + summary.vectorIndexed = (summary.vectorIndexed ?? 0) + docs.length; + } catch (error: any) { + summary.errors.push( + `Vector indexing failed: ${error?.message ? String(error.message) : "unknown error"}`, + ); + } + } + + return summary; + } + + async indexContent( + path: string, + content: string, + metadata?: Record, + ): Promise { + const normalizedPath = normalizeDocumentPath(path); + return this.indexDocuments([ + { + id: normalizedPath, + path: normalizedPath, + content, + metadata, + }, + ]); + } + + async search( + query: string, + options: WorkspaceSearchOptions = {}, + ): Promise { + await this.ensureAutoIndex(); + + const mode = this.resolveMode(options.mode); + const topK = options.topK ?? DEFAULT_TOP_K; + const basePath = normalizePath(options.path); + const glob = options.glob; + const snippetLength = options.snippetLength ?? this.snippetLength; + let lexicalWeight = options.lexicalWeight; + let vectorWeight = options.vectorWeight; + if (lexicalWeight === undefined && vectorWeight === undefined) { + lexicalWeight = this.defaultWeights.lexicalWeight; + vectorWeight = this.defaultWeights.vectorWeight; + } else if (lexicalWeight === undefined && vectorWeight !== undefined) { + lexicalWeight = 1 - vectorWeight; + } else if (vectorWeight === undefined && lexicalWeight !== undefined) { + vectorWeight = 1 - lexicalWeight; + } + lexicalWeight = clampScore(lexicalWeight ?? 0); + vectorWeight = clampScore(vectorWeight ?? 0); + const minScore = clampScore(options.minScore ?? 0); + + const filter = (doc: { path: string }) => matchesPathFilter(doc.path, basePath, glob); + + const bm25Results = + mode === "bm25" || mode === "hybrid" + ? this.bm25.search(query, { + limit: topK * 5, + filter, + }) + : []; + + const vectorResults = + mode === "vector" || mode === "hybrid" + ? await this.searchVector(query, topK * 5, filter) + : []; + + const bm25ScoreMap = new Map(bm25Results.map((item) => [item.id, item.score])); + const vectorScoreMap = new Map(vectorResults.map((item) => [item.id, item.score])); + const normalizedBm25 = normalizeScores(bm25Results); + const normalizedVector = clampScores(vectorResults); + + if (mode === "bm25") { + const normalizedResults = bm25Results.map((item) => ({ + id: item.id, + score: normalizedBm25.get(item.id) ?? 0, + })); + return this.formatResults( + normalizedResults, + { bm25Scores: bm25ScoreMap, bm25Normalized: normalizedBm25 }, + query, + snippetLength, + topK, + minScore, + ); + } + + if (mode === "vector") { + const normalizedResults = vectorResults.map((item) => ({ + id: item.id, + score: normalizedVector.get(item.id) ?? 0, + })); + return this.formatResults( + normalizedResults, + { vectorScores: vectorScoreMap, vectorNormalized: normalizedVector }, + query, + snippetLength, + topK, + minScore, + ); + } + const combined = new Map(); + + for (const item of bm25Results) { + combined.set(item.id, { bm25: item.score }); + } + for (const item of vectorResults) { + const existing = combined.get(item.id) ?? {}; + combined.set(item.id, { ...existing, vector: item.score }); + } + + const mergedResults = Array.from(combined.keys()).map((id) => { + const bm25Score = normalizedBm25.get(id) ?? 0; + const vectorScore = normalizedVector.get(id) ?? 0; + const totalWeight = lexicalWeight + vectorWeight; + const normalizedScore = + totalWeight > 0 + ? (lexicalWeight * bm25Score + vectorWeight * vectorScore) / totalWeight + : 0; + return { + id, + score: normalizedScore, + }; + }); + + mergedResults.sort((a, b) => b.score - a.score); + return this.formatResults( + mergedResults, + { + bm25Scores: bm25ScoreMap, + vectorScores: vectorScoreMap, + bm25Normalized: normalizedBm25, + vectorNormalized: normalizedVector, + }, + query, + snippetLength, + topK, + minScore, + ); + } + + private resolveMode(requested?: WorkspaceSearchMode): WorkspaceSearchMode { + if (!requested) { + return this.defaultMode; + } + + if (requested === "vector" || requested === "hybrid") { + if (!this.embedding || !this.vector) { + throw new Error("Vector search is not configured for this workspace."); + } + } + + return requested; + } + + private async searchVector( + query: string, + limit: number, + filter: (doc: { path: string }) => boolean, + ): Promise> { + if (!this.embedding || !this.vector) { + throw new Error("Vector search is not configured for this workspace."); + } + + const embedding = await this.embedding.embed(query); + const results = await this.vector.search(embedding, { limit }); + const filtered: Array<{ id: string; score: number }> = []; + + for (const item of results) { + const path = + typeof item.metadata?.path === "string" + ? item.metadata.path + : (this.documents.get(item.id)?.path ?? item.id); + + if (!filter({ path })) { + continue; + } + + filtered.push({ id: item.id, score: item.score }); + } + + return filtered; + } + + private formatResults( + results: Array<{ id: string; score: number }>, + options: { + bm25Scores?: Map; + vectorScores?: Map; + bm25Normalized?: Map; + vectorNormalized?: Map; + }, + query: string, + snippetLength: number, + limit: number, + minScore: number, + ): WorkspaceSearchResult[] { + const filtered = minScore > 0 ? results.filter((item) => item.score >= minScore) : results; + const topResults = filtered.slice(0, limit); + + return topResults.map((item) => { + const doc = this.documents.get(item.id); + const path = doc?.path ?? item.id; + const content = doc?.content ?? ""; + const snippet = content ? buildSnippet(content, query, snippetLength) : undefined; + const lineRange = content ? buildLineRange(content, query) : undefined; + const bm25Normalized = options.bm25Normalized?.get(item.id); + const vectorNormalized = options.vectorNormalized?.get(item.id); + const scoreDetails = + bm25Normalized !== undefined || vectorNormalized !== undefined + ? { + bm25: bm25Normalized, + vector: vectorNormalized, + } + : undefined; + return { + id: item.id, + path, + score: clampScore(item.score), + content, + lineRange, + scoreDetails, + bm25Score: options.bm25Scores?.get(item.id), + vectorScore: options.vectorScores?.get(item.id), + snippet, + metadata: doc?.metadata, + }; + }); + } +} + +const WORKSPACE_SEARCH_SYSTEM_PROMPT = `You can index and search workspace files. + +- workspace_index: index files under a path + optional glob +- workspace_index_content: index raw content by path +- workspace_search: search indexed content (BM25/vector/hybrid).`; + +const WORKSPACE_INDEX_TOOL_DESCRIPTION = + "Index workspace files under a path and optional glob for search."; +const WORKSPACE_INDEX_CONTENT_TOOL_DESCRIPTION = "Index raw content by path for search."; +const WORKSPACE_SEARCH_TOOL_DESCRIPTION = + "Search indexed workspace files using BM25, vector, or hybrid search (scores normalized 0-1)."; + +const setWorkspaceSpanAttributes = ( + operationContext: OperationContext, + attributes: Record, +): void => { + const toolSpan = operationContext.systemContext.get("parentToolSpan") as Span | undefined; + if (!toolSpan) { + return; + } + + for (const [key, value] of Object.entries(attributes)) { + if (value !== undefined) { + toolSpan.setAttribute(key, value as never); + } + } +}; + +const buildWorkspaceAttributes = (workspace?: WorkspaceIdentity): Record => ({ + "workspace.id": workspace?.id, + "workspace.name": workspace?.name, + "workspace.scope": workspace?.scope, +}); + +const formatIndexSummary = (summary: WorkspaceSearchIndexSummary): string => { + const lines = [`Indexed ${summary.indexed} file(s).`, `Skipped ${summary.skipped} file(s).`]; + if (summary.vectorIndexed !== undefined) { + lines.push(`Vector indexed ${summary.vectorIndexed} file(s).`); + } + if (summary.errors.length > 0) { + lines.push("Errors:"); + lines.push(...summary.errors.map((err) => `- ${err}`)); + } + return lines.join("\n"); +}; + +const formatSearchResults = (results: WorkspaceSearchResult[]): string => { + if (results.length === 0) { + return "No results found."; + } + + const lines: string[] = []; + lines.push(`Found ${results.length} result(s):`); + results.forEach((result, idx) => { + const scoreParts: string[] = [`score=${result.score.toFixed(3)}`]; + if (result.scoreDetails?.bm25 !== undefined) { + scoreParts.push(`bm25=${result.scoreDetails.bm25.toFixed(3)}`); + } + if (result.scoreDetails?.vector !== undefined) { + scoreParts.push(`vector=${result.scoreDetails.vector.toFixed(3)}`); + } + lines.push(`${idx + 1}. ${result.path} (${scoreParts.join(", ")})`); + if (result.lineRange) { + lines.push(` lines ${result.lineRange.start}-${result.lineRange.end}`); + } + const content = result.snippet || result.content; + if (content) { + const truncated = truncateIfTooLong(content, DEFAULT_MAX_RESULT_CHARS); + const text = Array.isArray(truncated) ? truncated.join("\n") : truncated; + lines.push(` ${text}`); + } + }); + + const output = lines.join("\n"); + const truncatedOutput = truncateIfTooLong(output); + return Array.isArray(truncatedOutput) ? truncatedOutput.join("\n") : truncatedOutput; +}; + +export const createWorkspaceSearchToolkit = ( + context: WorkspaceSearchToolkitContext, + options: WorkspaceSearchToolkitOptions = {}, +): Toolkit => { + const systemPrompt = + options.systemPrompt === undefined ? WORKSPACE_SEARCH_SYSTEM_PROMPT : options.systemPrompt; + + const isToolPolicyGroup = ( + policies: WorkspaceToolPolicies, + ): policies is WorkspaceToolPolicyGroup => + Object.prototype.hasOwnProperty.call(policies, "tools") || + Object.prototype.hasOwnProperty.call(policies, "defaults"); + + const resolveToolPolicy = (name: WorkspaceSearchToolName) => { + const toolPolicies = options.toolPolicies; + if (!toolPolicies) { + return undefined; + } + if (isToolPolicyGroup(toolPolicies)) { + const defaults = toolPolicies.defaults ?? {}; + const override = toolPolicies.tools?.[name] ?? {}; + const merged = { ...defaults, ...override }; + return Object.keys(merged).length > 0 ? merged : undefined; + } + return toolPolicies[name]; + }; + + const isToolEnabled = (name: WorkspaceSearchToolName) => { + const policy = resolveToolPolicy(name); + return policy?.enabled ?? true; + }; + + const indexTool = createTool({ + name: "workspace_index", + description: options.customIndexDescription || WORKSPACE_INDEX_TOOL_DESCRIPTION, + tags: [...WORKSPACE_SEARCH_TAGS], + needsApproval: resolveToolPolicy("workspace_index")?.needsApproval, + parameters: z.object({ + path: z.string().optional().default("/").describe("Base path to index (default: /)"), + glob: z.string().optional().default("**/*").describe("Glob pattern to select files"), + max_file_bytes: z.coerce.number().optional().describe("Override maximum file size to index"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "search.index", + "workspace.fs.path": input.path || "/", + "workspace.fs.pattern": input.glob, + }); + + if (!context.search) { + return "Workspace search is not configured."; + } + + const summary = await context.search.indexPaths( + [{ path: input.path || "/", glob: input.glob }], + { maxFileBytes: input.max_file_bytes }, + ); + + setWorkspaceSpanAttributes(operationContext, { + "workspace.search.results": summary.indexed, + }); + + return formatIndexSummary(summary); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const indexContentTool = createTool({ + name: "workspace_index_content", + description: options.customIndexContentDescription || WORKSPACE_INDEX_CONTENT_TOOL_DESCRIPTION, + tags: [...WORKSPACE_SEARCH_TAGS], + needsApproval: resolveToolPolicy("workspace_index_content")?.needsApproval, + parameters: z.object({ + path: z.string().describe("Path identifier for the content"), + content: z.string().describe("Raw content to index"), + metadata: z.record(z.unknown()).optional().describe("Optional metadata"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "search.index_content", + "workspace.fs.path": input.path, + }); + + if (!context.search) { + return "Workspace search is not configured."; + } + + const summary = await context.search.indexContent( + input.path, + input.content, + input.metadata, + ); + + setWorkspaceSpanAttributes(operationContext, { + "workspace.search.results": summary.indexed, + }); + + return formatIndexSummary(summary); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const searchTool = createTool({ + name: "workspace_search", + description: options.customSearchDescription || WORKSPACE_SEARCH_TOOL_DESCRIPTION, + tags: [...WORKSPACE_SEARCH_TAGS], + needsApproval: resolveToolPolicy("workspace_search")?.needsApproval, + toModelOutput: ({ output }) => { + if (typeof output === "string") { + return { type: "text", value: output }; + } + const payload = output as WorkspaceSearchToolOutput | undefined; + const results = Array.isArray(payload?.results) ? payload.results : []; + return { + type: "text", + value: formatSearchResults(results), + }; + }, + parameters: z.object({ + query: z.string().describe("Search query"), + mode: z.enum(["bm25", "vector", "hybrid"]).optional().describe("Search mode"), + top_k: z.coerce.number().optional().default(DEFAULT_TOP_K), + path: z.string().optional().default("/").describe("Base path filter (default: /)"), + glob: z.string().optional().describe("Optional glob filter"), + snippet_length: z.coerce.number().optional().describe("Snippet length for each result"), + include_content: z + .boolean() + .optional() + .default(true) + .describe("Include full content in results (default: true). Set false to prefer snippets."), + min_score: z.coerce.number().optional().describe("Minimum normalized score (0-1)"), + lexical_weight: z.coerce + .number() + .optional() + .describe("Hybrid lexical weight (0-1). Defaults to 1 - vector_weight if omitted"), + vector_weight: z.coerce + .number() + .optional() + .describe("Hybrid vector weight (0-1). 0 = BM25 only, 1 = vector only"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "search.query", + "workspace.search.query": input.query, + "workspace.search.mode": input.mode, + "workspace.search.top_k": input.top_k, + "workspace.fs.path": input.path || "/", + "workspace.fs.pattern": input.glob, + }); + + if (!context.search) { + return "Workspace search is not configured."; + } + + try { + const results = await context.search.search(input.query, { + mode: input.mode, + topK: input.top_k, + minScore: input.min_score, + path: input.path || "/", + glob: input.glob, + snippetLength: input.snippet_length, + lexicalWeight: input.lexical_weight, + vectorWeight: input.vector_weight, + }); + + setWorkspaceSpanAttributes(operationContext, { + "workspace.search.results": results.length, + }); + + const includeContent = input.include_content ?? true; + const finalResults = includeContent + ? results + : results.map((result) => ({ + ...result, + content: "", + })); + + return { + results: finalResults, + total: finalResults.length, + }; + } catch (error: any) { + const message = error?.message ? String(error.message) : "Unknown search error"; + return `Search failed: ${message}`; + } + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const tools = []; + if (isToolEnabled("workspace_index")) { + tools.push(indexTool); + } + if (isToolEnabled("workspace_index_content")) { + tools.push(indexContentTool); + } + if (isToolEnabled("workspace_search")) { + tools.push(searchTool); + } + + return createToolkit({ + name: "workspace_search", + description: "Workspace search tools (index + query)", + tools, + instructions: systemPrompt || undefined, + addInstructions: Boolean(systemPrompt), + }); +}; diff --git a/packages/core/src/workspace/search/types.ts b/packages/core/src/workspace/search/types.ts new file mode 100644 index 000000000..417ebe75c --- /dev/null +++ b/packages/core/src/workspace/search/types.ts @@ -0,0 +1,59 @@ +import type { EmbeddingAdapterInput, VectorAdapter } from "../../memory/types"; + +export type WorkspaceSearchMode = "bm25" | "vector" | "hybrid"; + +export type WorkspaceSearchIndexPath = { + path: string; + glob?: string; +}; + +export type WorkspaceSearchHybridWeights = { + lexicalWeight?: number; + vectorWeight?: number; +}; + +export type WorkspaceSearchConfig = { + bm25?: { + k1?: number; + b?: number; + }; + embedding?: EmbeddingAdapterInput; + vector?: VectorAdapter; + autoIndexPaths?: Array; + maxFileBytes?: number; + snippetLength?: number; + defaultMode?: WorkspaceSearchMode; + hybrid?: WorkspaceSearchHybridWeights; + allowDirectAccess?: boolean; +}; + +export type WorkspaceSearchOptions = { + mode?: WorkspaceSearchMode; + topK?: number; + minScore?: number; + path?: string; + glob?: string; + snippetLength?: number; + lexicalWeight?: number; + vectorWeight?: number; +}; + +export type WorkspaceSearchResult = { + id: string; + path: string; + score: number; + content: string; + lineRange?: { start: number; end: number }; + scoreDetails?: { bm25?: number; vector?: number }; + bm25Score?: number; + vectorScore?: number; + snippet?: string; + metadata?: Record; +}; + +export type WorkspaceSearchIndexSummary = { + indexed: number; + vectorIndexed?: number; + skipped: number; + errors: string[]; +}; diff --git a/packages/core/src/workspace/skills/index.spec.ts b/packages/core/src/workspace/skills/index.spec.ts new file mode 100644 index 000000000..d6faa7a4e --- /dev/null +++ b/packages/core/src/workspace/skills/index.spec.ts @@ -0,0 +1,235 @@ +import { describe, expect, it, vi } from "vitest"; +import { Workspace } from ".."; +import type { FileData } from "../filesystem"; + +describe("WorkspaceSkills root resolver context", () => { + it("provides workspace identity and filesystem to the resolver", async () => { + const resolver = vi.fn(async () => ["/skills"]); + const workspace = new Workspace({ + id: "workspace-ctx", + skills: { + rootPaths: resolver, + }, + }); + + await workspace.skills?.discoverSkills(); + + expect(resolver).toHaveBeenCalledTimes(1); + const context = resolver.mock.calls[0]?.[0]; + expect(context?.workspace.id).toBe("workspace-ctx"); + expect(context?.filesystem).toBe(workspace.filesystem); + }); +}); + +describe("WorkspaceSkills discovery and activation", () => { + it("discovers, loads, and activates skills", async () => { + const skillContent = `--- +name: Data Analyst +description: Analyze CSV data +version: "1.0.0" +tags: + - data +--- +Analyze the files and summarize findings.`; + + const timestamp = new Date().toISOString(); + const skillFile: FileData = { + content: skillContent.split("\n"), + created_at: timestamp, + modified_at: timestamp, + }; + + const workspace = new Workspace({ + filesystem: { + files: { + "/skills/data/SKILL.md": skillFile, + }, + }, + skills: { + rootPaths: ["/skills"], + autoDiscover: false, + }, + }); + + const skills = await workspace.skills?.discoverSkills(); + expect(skills?.length).toBe(1); + expect(skills?.[0]?.id).toBe("/skills/data"); + + const detail = await workspace.skills?.loadSkill("/skills/data"); + expect(detail?.instructions).toContain("Analyze the files"); + + const activated = await workspace.skills?.activateSkill("Data Analyst"); + expect(activated?.id).toBe("/skills/data"); + expect(workspace.skills?.getActiveSkills().length).toBe(1); + + const deactivated = await workspace.skills?.deactivateSkill("/skills/data"); + expect(deactivated).toBe(true); + expect(workspace.skills?.getActiveSkills().length).toBe(0); + }); +}); + +describe("WorkspaceSkills file access", () => { + it("allows listed reference files and blocks others", async () => { + const timestamp = new Date().toISOString(); + const skillContent = `--- +name: Data Analyst +references: + - references/schema.md +--- +Use the schema reference.`; + + const skillFile = { + content: skillContent.split("\n"), + created_at: timestamp, + modified_at: timestamp, + }; + + const referenceFile = { + content: ["table: customers"], + created_at: timestamp, + modified_at: timestamp, + }; + + const workspace = new Workspace({ + filesystem: { + files: { + "/skills/data/SKILL.md": skillFile, + "/skills/data/references/schema.md": referenceFile, + }, + }, + skills: { + rootPaths: ["/skills"], + autoDiscover: false, + }, + }); + + const toolkit = workspace.createSkillsToolkit(); + const tool = toolkit.tools.find((entry) => entry.name === "workspace_read_skill_reference"); + if (!tool?.execute) { + throw new Error("workspace_read_skill_reference tool not found"); + } + + const executeOptions = { + systemContext: new Map(), + abortController: new AbortController(), + } as any; + + const allowed = await tool.execute( + { skill_id: "/skills/data", reference: "references/schema.md" }, + executeOptions, + ); + expect(String(allowed)).toContain("table: customers"); + + const blocked = await tool.execute( + { skill_id: "/skills/data", reference: "secrets.txt" }, + executeOptions, + ); + expect(String(blocked)).toContain("File not allowed"); + }); + + it("allows listed scripts/assets with normalized paths and blocks traversal", async () => { + const timestamp = new Date().toISOString(); + const skillContent = `--- +name: Script Runner +scripts: + - scripts/run.sh + - scripts\\windows.ps1 +assets: + - assets/input.csv +--- +Use the scripts and assets.`; + + const makeFile = (content: string): FileData => ({ + content: content.split("\n"), + created_at: timestamp, + modified_at: timestamp, + }); + + const workspace = new Workspace({ + filesystem: { + files: { + "/skills/runner/SKILL.md": makeFile(skillContent), + "/skills/runner/scripts/run.sh": makeFile("echo run"), + "/skills/runner/scripts/windows.ps1": makeFile("Write-Host run"), + "/skills/runner/assets/input.csv": makeFile("id,name\n1,alpha"), + }, + }, + skills: { + rootPaths: ["/skills"], + autoDiscover: false, + }, + }); + + const toolkit = workspace.createSkillsToolkit(); + const readScriptTool = toolkit.tools.find( + (tool) => tool.name === "workspace_read_skill_script", + ); + const readAssetTool = toolkit.tools.find((tool) => tool.name === "workspace_read_skill_asset"); + if (!readScriptTool?.execute || !readAssetTool?.execute) { + throw new Error("Workspace skill read tools not found"); + } + + const executeOptions = { + systemContext: new Map(), + abortController: new AbortController(), + } as any; + + const scriptOutput = await readScriptTool.execute( + { skill_id: "/skills/runner", script: "scripts/run.sh" }, + executeOptions, + ); + expect(String(scriptOutput)).toContain("echo run"); + + const normalizedOutput = await readScriptTool.execute( + { skill_id: "/skills/runner", script: "scripts/windows.ps1" }, + executeOptions, + ); + expect(String(normalizedOutput)).toContain("Write-Host run"); + + const assetOutput = await readAssetTool.execute( + { skill_id: "/skills/runner", asset: "assets/input.csv" }, + executeOptions, + ); + expect(String(assetOutput)).toContain("id,name"); + + const blocked = await readAssetTool.execute( + { skill_id: "/skills/runner", asset: "../secret.txt" }, + executeOptions, + ); + expect(String(blocked)).toContain("File not allowed"); + }); +}); + +describe("WorkspaceSkills search", () => { + it("returns BM25 search results with snippets", async () => { + const timestamp = new Date().toISOString(); + const makeFile = (content: string) => ({ + content: content.split("\n"), + created_at: timestamp, + modified_at: timestamp, + }); + + const workspace = new Workspace({ + filesystem: { + files: { + "/skills/data/SKILL.md": makeFile(`--- +name: Data Analyst +--- +Analyze CSV files and produce charts.`), + "/skills/code/SKILL.md": makeFile(`--- +name: Code Helper +--- +Review TypeScript and suggest fixes.`), + }, + }, + skills: { + rootPaths: ["/skills"], + autoDiscover: false, + }, + }); + + const results = await workspace.skills?.search("csv", { mode: "bm25" }); + expect(results?.[0]?.name).toBe("Data Analyst"); + expect(results?.[0]?.snippet).toContain("CSV"); + }); +}); diff --git a/packages/core/src/workspace/skills/index.ts b/packages/core/src/workspace/skills/index.ts new file mode 100644 index 000000000..5220b6606 --- /dev/null +++ b/packages/core/src/workspace/skills/index.ts @@ -0,0 +1,1428 @@ +import type { AttributeValue, Span } from "@opentelemetry/api"; +import { safeStringify } from "@voltagent/internal"; +import matter from "gray-matter"; +import { z } from "zod"; +import type { Agent } from "../../agent/agent"; +import type { AgentHooks, OnPrepareMessagesHookResult } from "../../agent/hooks"; +import type { OperationContext } from "../../agent/types"; +import { AiSdkEmbeddingAdapter } from "../../memory/adapters/embedding/ai-sdk"; +import type { + EmbeddingAdapter, + EmbeddingAdapterConfig, + EmbeddingAdapterInput, + VectorAdapter, + VectorItem, +} from "../../memory/types"; +import { createTool } from "../../tool"; +import { createToolkit } from "../../tool/toolkit"; +import type { Toolkit } from "../../tool/toolkit"; +import { randomUUID } from "../../utils/id"; +import type { WorkspaceFilesystem } from "../filesystem"; +import { WorkspaceBm25Index, tokenizeSearchText } from "../search/bm25"; +import { withOperationTimeout } from "../timeout"; +import type { WorkspaceToolPolicies, WorkspaceToolPolicyGroup } from "../tool-policy"; +import type { WorkspaceComponentStatus, WorkspaceIdentity } from "../types"; +import type { + WorkspaceSkill, + WorkspaceSkillIndexSummary, + WorkspaceSkillMetadata, + WorkspaceSkillSearchMode, + WorkspaceSkillSearchOptions, + WorkspaceSkillSearchResult, + WorkspaceSkillsConfig, + WorkspaceSkillsPromptOptions, + WorkspaceSkillsRootResolver, + WorkspaceSkillsRootResolverContext, +} from "./types"; + +const DEFAULT_SKILL_ROOTS = ["/skills"]; +const DEFAULT_SKILL_GLOB = "**/SKILL.md"; +const DEFAULT_MAX_FILE_BYTES = 512 * 1024; +const DEFAULT_TOP_K = 10; +const DEFAULT_SNIPPET_LENGTH = 240; +const DEFAULT_HYBRID_LEXICAL_WEIGHT = 0.5; +const DEFAULT_HYBRID_VECTOR_WEIGHT = 0.5; +const DEFAULT_MAX_AVAILABLE = 50; +const DEFAULT_MAX_ACTIVATED = 10; +const DEFAULT_MAX_INSTRUCTION_CHARS = 4000; +const DEFAULT_MAX_PROMPT_CHARS = 12000; + +const SKILLS_SYSTEM_PROMPT = `You can manage workspace skills. + +- workspace_list_skills: list available skills +- workspace_search_skills: search skill instructions +- workspace_read_skill: read skill instructions +- workspace_activate_skill: activate a skill for this session +- workspace_deactivate_skill: deactivate a skill +- workspace_read_skill_reference: read skill reference files +- workspace_read_skill_script: read skill scripts +- workspace_read_skill_asset: read skill assets`; + +const LIST_SKILLS_DESCRIPTION = "List available workspace skills."; +const SEARCH_SKILLS_DESCRIPTION = "Search skill instructions by text query."; +const READ_SKILL_DESCRIPTION = "Read a skill's instructions from SKILL.md."; +const ACTIVATE_SKILL_DESCRIPTION = "Activate a workspace skill."; +const DEACTIVATE_SKILL_DESCRIPTION = "Deactivate a workspace skill."; +const READ_SKILL_REFERENCE_DESCRIPTION = "Read a skill reference file."; +const READ_SKILL_SCRIPT_DESCRIPTION = "Read a skill script file."; +const READ_SKILL_ASSET_DESCRIPTION = "Read a skill asset file."; +const WORKSPACE_SKILLS_TAGS = ["workspace", "skills"] as const; + +export type WorkspaceSkillsToolkitOptions = { + systemPrompt?: string | null; + operationTimeoutMs?: number; + customToolDescriptions?: Partial<{ + list: string; + search: string; + read: string; + activate: string; + deactivate: string; + readReference: string; + readScript: string; + readAsset: string; + }> | null; + toolPolicies?: WorkspaceToolPolicies | null; +}; + +export type WorkspaceSkillsToolkitContext = { + skills?: WorkspaceSkills; + workspace?: WorkspaceIdentity; + agent?: Agent; +}; + +export type WorkspaceSkillsToolName = + | "workspace_list_skills" + | "workspace_search_skills" + | "workspace_read_skill" + | "workspace_activate_skill" + | "workspace_deactivate_skill" + | "workspace_read_skill_reference" + | "workspace_read_skill_script" + | "workspace_read_skill_asset"; + +export type WorkspaceSkillsPromptHookContext = { + skills?: WorkspaceSkills; +}; + +const isEmbeddingAdapter = (value: EmbeddingAdapterInput): value is EmbeddingAdapter => + typeof value === "object" && + value !== null && + "embed" in value && + typeof (value as EmbeddingAdapter).embed === "function"; + +const isEmbeddingAdapterConfig = (value: EmbeddingAdapterInput): value is EmbeddingAdapterConfig => + typeof value === "object" && value !== null && "model" in value && !isEmbeddingAdapter(value); + +const resolveEmbeddingAdapter = ( + embedding?: EmbeddingAdapterInput, +): EmbeddingAdapter | undefined => { + if (!embedding) { + return undefined; + } + + if (isEmbeddingAdapter(embedding)) { + return embedding; + } + + if (typeof embedding === "string") { + return new AiSdkEmbeddingAdapter(embedding); + } + + if (isEmbeddingAdapterConfig(embedding)) { + const { model, ...options } = embedding; + return new AiSdkEmbeddingAdapter(model, options); + } + + return new AiSdkEmbeddingAdapter(embedding); +}; + +const normalizeRootPath = (value: string): string => { + const trimmed = value.trim(); + if (!trimmed || trimmed === "/") { + return "/"; + } + const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`; + return withSlash.endsWith("/") ? withSlash.slice(0, -1) : withSlash; +}; + +const normalizeStringArray = (value: unknown): string[] | undefined => { + if (!value) { + return undefined; + } + + if (Array.isArray(value)) { + const items = value + .map((item) => (typeof item === "string" ? item.trim() : "")) + .filter((item) => item.length > 0); + return items.length > 0 ? items : undefined; + } + + if (typeof value === "string") { + const trimmed = value.trim(); + return trimmed ? [trimmed] : undefined; + } + + return undefined; +}; + +const normalizePath = (value: string): string => value.replace(/\\/g, "/"); + +const basename = (value: string): string => { + const normalized = normalizePath(value); + const parts = normalized.split("/").filter(Boolean); + return parts[parts.length - 1] || ""; +}; + +const joinPaths = (root: string, relative: string): string => { + const normalizedRoot = root === "/" ? "" : root; + const normalizedRelative = relative.startsWith("/") ? relative.slice(1) : relative; + if (!normalizedRoot) { + return `/${normalizedRelative}`; + } + return `${normalizedRoot}/${normalizedRelative}`; +}; + +const truncateText = (value: string, maxChars: number): string => { + if (maxChars <= 0) { + return ""; + } + if (value.length <= maxChars) { + return value; + } + return `${value.slice(0, maxChars)}\n... [truncated]`; +}; + +const normalizeScores = (scores: Array<{ id: string; score: number }>) => { + const maxScore = scores.reduce((max, item) => Math.max(max, item.score), 0); + if (maxScore <= 0) { + return new Map(scores.map((item) => [item.id, 0])); + } + return new Map(scores.map((item) => [item.id, item.score / maxScore])); +}; + +const buildSnippet = (content: string, query: string, length: number): string => { + const compact = content.replace(/\s+/g, " ").trim(); + if (compact.length <= length) { + return compact; + } + + const terms = tokenizeSearchText(query); + const lower = compact.toLowerCase(); + for (const term of terms) { + const idx = lower.indexOf(term); + if (idx >= 0) { + const start = Math.max(0, idx - Math.floor(length / 2)); + const end = Math.min(compact.length, start + length); + return compact.slice(start, end).trim(); + } + } + + return compact.slice(0, length).trim(); +}; + +const setWorkspaceSpanAttributes = ( + operationContext: OperationContext, + attributes: Record, +): void => { + const toolSpan = operationContext.systemContext.get("parentToolSpan") as Span | undefined; + if (!toolSpan) { + return; + } + + for (const [key, value] of Object.entries(attributes)) { + const normalized = normalizeAttributeValue(value); + if (normalized !== undefined) { + toolSpan.setAttribute(key, normalized); + } + } +}; + +const normalizeAttributeValue = (value: unknown): AttributeValue | undefined => { + if (value === undefined) { + return undefined; + } + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + return value; + } + if (typeof value === "bigint" || typeof value === "symbol") { + return String(value); + } + if (Array.isArray(value)) { + const allPrimitive = value.every( + (item) => typeof item === "string" || typeof item === "number" || typeof item === "boolean", + ); + if (allPrimitive) { + return value as AttributeValue; + } + const serialized = safeStringify(value); + return typeof serialized === "string" ? serialized : undefined; + } + if (typeof value === "object" || typeof value === "function") { + const serialized = safeStringify(value); + return typeof serialized === "string" ? serialized : undefined; + } + return undefined; +}; + +const buildWorkspaceAttributes = (workspace?: WorkspaceIdentity): Record => ({ + "workspace.id": workspace?.id, + "workspace.name": workspace?.name, + "workspace.scope": workspace?.scope, +}); + +const formatSkillList = (skills: WorkspaceSkillMetadata[], activeIds: Set): string => { + if (skills.length === 0) { + return "No skills found."; + } + + const lines: string[] = []; + skills.forEach((skill) => { + const status = activeIds.has(skill.id) ? "active" : "inactive"; + const description = skill.description ? ` - ${skill.description}` : ""; + lines.push(`[${status}] ${skill.id} (${skill.name})${description}`); + }); + + return lines.join("\n"); +}; + +const formatSkillDetail = (skill: WorkspaceSkill): string => { + const lines: string[] = []; + lines.push(`Name: ${skill.name}`); + lines.push(`Id: ${skill.id}`); + if (skill.description) { + lines.push(`Description: ${skill.description}`); + } + if (skill.version) { + lines.push(`Version: ${skill.version}`); + } + if (skill.tags && skill.tags.length > 0) { + lines.push(`Tags: ${skill.tags.join(", ")}`); + } + lines.push(`Path: ${skill.path}`); + lines.push(""); + lines.push("Instructions:"); + lines.push(skill.instructions || "(empty)"); + return lines.join("\n"); +}; + +const formatSearchResults = (results: WorkspaceSkillSearchResult[]): string => { + if (results.length === 0) { + return "No results found."; + } + + const lines: string[] = []; + lines.push(`Found ${results.length} result(s):`); + results.forEach((result, idx) => { + const scoreParts: string[] = [`score=${result.score.toFixed(3)}`]; + if (result.bm25Score !== undefined) { + scoreParts.push(`bm25=${result.bm25Score.toFixed(3)}`); + } + if (result.vectorScore !== undefined) { + scoreParts.push(`vector=${result.vectorScore.toFixed(3)}`); + } + lines.push(`${idx + 1}. ${result.name} (${result.id}) (${scoreParts.join(", ")})`); + if (result.snippet) { + lines.push(` ${result.snippet}`); + } + }); + return lines.join("\n"); +}; + +const parseSkillFile = ( + content: string, +): { data: Record; instructions: string } => { + const parsed = matter(content); + const data = (parsed.data || {}) as Record; + const instructions = parsed.content.trim(); + return { data, instructions }; +}; + +type WorkspaceSkillDocument = { + id: string; + name: string; + content: string; + metadata?: Record; +}; + +export class WorkspaceSkills { + private readonly filesystem: WorkspaceFilesystem; + private readonly workspaceIdentity: WorkspaceSkillsRootResolverContext["workspace"]; + private rootPaths: string[]; + private readonly rootResolver?: WorkspaceSkillsRootResolver; + private rootResolved = false; + private rootResolvePromise?: Promise; + private readonly glob: string; + private readonly maxFileBytes: number; + private readonly bm25Options?: WorkspaceSkillsConfig["bm25"]; + private bm25: WorkspaceBm25Index; + private readonly embedding?: EmbeddingAdapter; + private readonly vector?: VectorAdapter; + private readonly defaultMode: WorkspaceSkillSearchMode; + private readonly defaultWeights: { lexicalWeight: number; vectorWeight: number }; + + private readonly skillsById = new Map(); + private readonly skillNameMap = new Map(); + private readonly skillCache = new Map(); + private readonly activeSkills = new Set(); + private readonly documents = new Map(); + private readonly indexedSkillIds = new Set(); + private discovered = false; + private indexed = false; + private autoDiscoverPromise?: Promise; + private autoIndexPromise?: Promise; + status: WorkspaceComponentStatus = "idle"; + + constructor( + options: WorkspaceSkillsConfig & { + filesystem: WorkspaceFilesystem; + workspace: WorkspaceSkillsRootResolverContext["workspace"]; + }, + ) { + this.filesystem = options.filesystem; + this.workspaceIdentity = options.workspace; + const rootOption = options.rootPaths; + if (typeof rootOption === "function") { + this.rootResolver = rootOption; + this.rootPaths = []; + } else { + const roots = rootOption && rootOption.length > 0 ? rootOption : DEFAULT_SKILL_ROOTS; + this.rootPaths = roots.map(normalizeRootPath); + this.rootResolved = true; + } + this.glob = options.glob || DEFAULT_SKILL_GLOB; + this.maxFileBytes = options.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES; + this.embedding = resolveEmbeddingAdapter(options.embedding); + this.vector = options.vector; + this.defaultMode = options.defaultMode ?? (this.embedding && this.vector ? "hybrid" : "bm25"); + this.defaultWeights = { + lexicalWeight: options.hybrid?.lexicalWeight ?? DEFAULT_HYBRID_LEXICAL_WEIGHT, + vectorWeight: options.hybrid?.vectorWeight ?? DEFAULT_HYBRID_VECTOR_WEIGHT, + }; + this.bm25Options = options.bm25; + this.bm25 = new WorkspaceBm25Index(this.bm25Options); + + const autoDiscover = options.autoDiscover ?? true; + const autoIndex = options.autoIndex ?? false; + + if (autoDiscover) { + const promise = this.discoverSkills().then(() => undefined); + this.autoDiscoverPromise = promise; + promise.catch(() => { + if (this.autoDiscoverPromise === promise) { + this.autoDiscoverPromise = undefined; + } + }); + } + if (autoIndex) { + const promise = this.indexSkills().then(() => undefined); + this.autoIndexPromise = promise; + promise.catch(() => { + if (this.autoIndexPromise === promise) { + this.autoIndexPromise = undefined; + } + }); + } + } + + async init(): Promise { + if (this.status === "destroyed") { + throw new Error("Workspace skills have been destroyed."); + } + this.status = "ready"; + await this.ensureDiscovered(); + if (this.autoIndexPromise) { + await this.ensureIndexed(); + } + } + + destroy(): void { + this.status = "destroyed"; + } + + getInfo(): Record { + return { + status: this.status, + rootPaths: this.rootPaths, + glob: this.glob, + maxFileBytes: this.maxFileBytes, + discoveredCount: this.skillsById.size, + indexedCount: this.documents.size, + activeCount: this.activeSkills.size, + }; + } + + getInstructions(): string { + return SKILLS_SYSTEM_PROMPT; + } + + private async ensureDiscovered(): Promise { + if (this.discovered) { + return; + } + if (!this.autoDiscoverPromise) { + const promise = this.discoverSkills().then(() => undefined); + this.autoDiscoverPromise = promise; + promise.catch(() => { + if (this.autoDiscoverPromise === promise) { + this.autoDiscoverPromise = undefined; + } + }); + } + const promise = this.autoDiscoverPromise; + try { + await promise; + } catch (error) { + if (this.autoDiscoverPromise === promise) { + this.autoDiscoverPromise = undefined; + } + throw error; + } + } + + private async ensureRootPaths(): Promise { + if (this.rootResolved) { + return; + } + if (!this.rootResolver) { + this.rootResolved = true; + if (this.rootPaths.length === 0) { + this.rootPaths = DEFAULT_SKILL_ROOTS.map(normalizeRootPath); + } + return; + } + if (!this.rootResolvePromise) { + this.rootResolvePromise = (async () => { + try { + const resolved = await this.rootResolver?.({ + workspace: this.workspaceIdentity, + filesystem: this.filesystem, + }); + const normalized = normalizeStringArray(resolved) ?? DEFAULT_SKILL_ROOTS; + this.rootPaths = normalized.map(normalizeRootPath); + this.rootResolved = true; + } catch (error) { + this.rootResolvePromise = undefined; + throw error; + } + })(); + } + await this.rootResolvePromise; + } + + private async ensureIndexed(): Promise { + if (this.indexed) { + return; + } + if (!this.autoIndexPromise) { + const promise = this.indexSkills().then(() => undefined); + this.autoIndexPromise = promise; + promise.catch(() => { + if (this.autoIndexPromise === promise) { + this.autoIndexPromise = undefined; + } + }); + } + const promise = this.autoIndexPromise; + try { + await promise; + } catch (error) { + if (this.autoIndexPromise === promise) { + this.autoIndexPromise = undefined; + } + throw error; + } + } + + async discoverSkills(options: { refresh?: boolean } = {}): Promise { + if (this.discovered && !options.refresh) { + return Array.from(this.skillsById.values()); + } + + await this.ensureRootPaths(); + + this.skillsById.clear(); + this.skillNameMap.clear(); + this.skillCache.clear(); + this.discovered = false; + this.indexed = false; + this.documents.clear(); + this.bm25 = new WorkspaceBm25Index(this.bm25Options); + + for (const root of this.rootPaths) { + let infos: Awaited>; + try { + infos = await this.filesystem.globInfo(this.glob, root); + } catch { + continue; + } + + for (const info of infos) { + const skillPath = info.path; + if (this.maxFileBytes > 0 && info.size && info.size > this.maxFileBytes) { + continue; + } + + try { + const data = await this.filesystem.readRaw(skillPath); + const content = data.content.join("\n"); + const contentBytes = Buffer.byteLength(content, "utf-8"); + if (this.maxFileBytes > 0 && contentBytes > this.maxFileBytes) { + continue; + } + + const normalizedPath = normalizePath(skillPath); + const rootPath = normalizedPath.replace(/\/SKILL\.md$/i, ""); + const { data: frontmatter } = parseSkillFile(content); + const name = + typeof frontmatter.name === "string" && frontmatter.name.trim().length > 0 + ? frontmatter.name.trim() + : basename(rootPath) || basename(normalizedPath) || "skill"; + const rawId = + typeof frontmatter.id === "string" && frontmatter.id.trim().length > 0 + ? frontmatter.id.trim() + : rootPath || normalizedPath; + + let id = rawId; + if (this.skillsById.has(id)) { + let suffix = 2; + while (this.skillsById.has(`${id}-${suffix}`)) { + suffix += 1; + } + id = `${id}-${suffix}`; + } + + const metadata: WorkspaceSkillMetadata = { + id, + name, + description: + typeof frontmatter.description === "string" ? frontmatter.description : undefined, + version: typeof frontmatter.version === "string" ? frontmatter.version : undefined, + tags: normalizeStringArray(frontmatter.tags), + path: skillPath, + root: rootPath || root, + references: normalizeStringArray(frontmatter.references), + scripts: normalizeStringArray(frontmatter.scripts), + assets: normalizeStringArray(frontmatter.assets), + }; + + this.skillsById.set(id, metadata); + const normalizedName = name.trim().toLowerCase(); + if (normalizedName) { + const existing = this.skillNameMap.get(normalizedName) ?? []; + existing.push(id); + this.skillNameMap.set(normalizedName, existing); + } + } catch { + // ignore invalid skill entries + } + } + } + + this.discovered = true; + return Array.from(this.skillsById.values()); + } + + async loadSkill(identifier: string): Promise { + await this.ensureDiscovered(); + const id = this.resolveSkillId(identifier); + if (!id) { + return null; + } + + const cached = this.skillCache.get(id); + if (cached) { + return cached; + } + + const metadata = this.skillsById.get(id); + if (!metadata) { + return null; + } + + const data = await this.filesystem.readRaw(metadata.path); + const content = data.content.join("\n"); + const { data: frontmatter, instructions } = parseSkillFile(content); + const detail: WorkspaceSkill = { + ...metadata, + description: + typeof frontmatter.description === "string" + ? frontmatter.description + : metadata.description, + version: typeof frontmatter.version === "string" ? frontmatter.version : metadata.version, + tags: normalizeStringArray(frontmatter.tags) ?? metadata.tags, + references: normalizeStringArray(frontmatter.references) ?? metadata.references, + scripts: normalizeStringArray(frontmatter.scripts) ?? metadata.scripts, + assets: normalizeStringArray(frontmatter.assets) ?? metadata.assets, + instructions, + }; + + this.skillCache.set(id, detail); + return detail; + } + + async activateSkill(identifier: string): Promise { + await this.ensureDiscovered(); + const id = this.resolveSkillId(identifier); + if (!id) { + return null; + } + this.activeSkills.add(id); + return this.skillsById.get(id) ?? null; + } + + async deactivateSkill(identifier: string): Promise { + await this.ensureDiscovered(); + const id = this.resolveSkillId(identifier); + if (!id) { + return false; + } + return this.activeSkills.delete(id); + } + + getActiveSkills(): WorkspaceSkillMetadata[] { + return Array.from(this.activeSkills) + .map((id) => this.skillsById.get(id)) + .filter((skill): skill is WorkspaceSkillMetadata => Boolean(skill)); + } + + async indexSkills(): Promise { + await this.ensureDiscovered(); + + const summary: WorkspaceSkillIndexSummary = { + indexed: 0, + skipped: 0, + errors: [], + }; + + if (this.skillsById.size === 0) { + this.indexed = true; + return summary; + } + + const previousIds = Array.from(this.indexedSkillIds); + this.indexedSkillIds.clear(); + this.documents.clear(); + this.bm25 = new WorkspaceBm25Index(this.bm25Options); + + if (this.vector && previousIds.length > 0) { + try { + await this.vector.deleteBatch(previousIds); + } catch (error: any) { + summary.errors.push( + `Vector cleanup failed: ${error?.message ? String(error.message) : "unknown error"}`, + ); + } + } + + const docs: WorkspaceSkillDocument[] = []; + + for (const metadata of this.skillsById.values()) { + try { + const skill = await this.loadSkill(metadata.id); + if (!skill) { + summary.skipped += 1; + continue; + } + + const content = [skill.name, skill.description || "", skill.instructions || ""] + .join("\n") + .trim(); + + if (!content) { + summary.skipped += 1; + continue; + } + + docs.push({ + id: skill.id, + name: skill.name, + content, + metadata: { + path: skill.path, + tags: skill.tags, + }, + }); + } catch (error: any) { + summary.errors.push( + `Failed to load ${metadata.id}: ${error?.message ? String(error.message) : "unknown error"}`, + ); + } + } + + for (const doc of docs) { + this.bm25.addDocument({ + id: doc.id, + path: doc.name, + content: doc.content, + metadata: doc.metadata, + }); + this.documents.set(doc.id, doc); + this.indexedSkillIds.add(doc.id); + } + + if (this.embedding && this.vector) { + try { + const embeddings = await this.embedding.embedBatch(docs.map((doc) => doc.content)); + if (!Array.isArray(embeddings) || embeddings.length !== docs.length) { + throw new Error( + `Embedding batch size mismatch (expected ${docs.length}, got ${Array.isArray(embeddings) ? embeddings.length : "non-array"})`, + ); + } + const items: VectorItem[] = []; + embeddings.forEach((vector, idx) => { + if (!vector) { + summary.errors.push(`Vector embedding missing for skill ${docs[idx]?.id ?? "unknown"}`); + return; + } + const doc = docs[idx]; + items.push({ + id: doc.id, + vector, + metadata: { + skill_name: doc.name, + path: doc.metadata?.path, + }, + }); + }); + if (items.length > 0) { + await this.vector.storeBatch(items); + } + } catch (error: any) { + summary.errors.push( + `Vector indexing failed: ${error?.message ? String(error.message) : "unknown error"}`, + ); + } + } + + summary.indexed = docs.length; + this.indexed = true; + return summary; + } + + async search( + query: string, + options: WorkspaceSkillSearchOptions = {}, + ): Promise { + await this.ensureIndexed(); + + const mode = this.resolveMode(options.mode); + const topK = options.topK ?? DEFAULT_TOP_K; + const snippetLength = options.snippetLength ?? DEFAULT_SNIPPET_LENGTH; + const lexicalWeight = options.lexicalWeight ?? this.defaultWeights.lexicalWeight; + const vectorWeight = options.vectorWeight ?? this.defaultWeights.vectorWeight; + + const bm25Results = + mode === "bm25" || mode === "hybrid" ? this.bm25.search(query, { limit: topK * 5 }) : []; + + const vectorResults = + mode === "vector" || mode === "hybrid" ? await this.searchVector(query, topK * 5) : []; + + if (mode === "bm25") { + return this.formatResults( + bm25Results, + { bm25Scores: new Map(bm25Results.map((item) => [item.id, item.score])) }, + query, + snippetLength, + topK, + ); + } + + if (mode === "vector") { + return this.formatResults( + vectorResults, + { vectorScores: new Map(vectorResults.map((item) => [item.id, item.score])) }, + query, + snippetLength, + topK, + ); + } + + const normalizedBm25 = normalizeScores(bm25Results); + const normalizedVector = normalizeScores(vectorResults); + const combined = new Map(); + + for (const item of bm25Results) { + combined.set(item.id, { bm25: item.score }); + } + for (const item of vectorResults) { + const existing = combined.get(item.id) ?? {}; + combined.set(item.id, { ...existing, vector: item.score }); + } + + const mergedResults = Array.from(combined.entries()).map(([id, scores]) => { + const bm25Score = scores.bm25 ?? 0; + const vectorScore = scores.vector ?? 0; + const normalizedScore = + lexicalWeight * (normalizedBm25.get(id) ?? 0) + + vectorWeight * (normalizedVector.get(id) ?? 0); + return { + id, + score: normalizedScore, + bm25Score, + vectorScore, + }; + }); + + mergedResults.sort((a, b) => b.score - a.score); + return this.formatResults( + mergedResults, + { + bm25Scores: new Map(bm25Results.map((item) => [item.id, item.score])), + vectorScores: new Map(vectorResults.map((item) => [item.id, item.score])), + }, + query, + snippetLength, + topK, + ); + } + + async buildPrompt(options: WorkspaceSkillsPromptOptions = {}): Promise { + await this.ensureDiscovered(); + + const includeAvailable = options.includeAvailable ?? true; + const includeActivated = options.includeActivated ?? true; + const maxAvailable = options.maxAvailable ?? DEFAULT_MAX_AVAILABLE; + const maxActivated = options.maxActivated ?? DEFAULT_MAX_ACTIVATED; + const maxInstructionChars = options.maxInstructionChars ?? DEFAULT_MAX_INSTRUCTION_CHARS; + const maxPromptChars = options.maxPromptChars ?? DEFAULT_MAX_PROMPT_CHARS; + + const sections: string[] = []; + + if (includeAvailable) { + const skills = Array.from(this.skillsById.values()).slice(0, maxAvailable); + if (skills.length > 0) { + const lines = skills.map((skill) => { + const description = skill.description ? ` - ${skill.description}` : ""; + return `- ${skill.name} (${skill.id})${description}`; + }); + sections.push(`Available skills:\n${lines.join("\n")}`); + } + } + + if (includeActivated) { + const activeIds = Array.from(this.activeSkills).slice(0, maxActivated); + if (activeIds.length > 0) { + const entries: string[] = []; + for (const id of activeIds) { + const skill = await this.loadSkill(id); + if (!skill) { + continue; + } + const header = `${skill.name} (${skill.id})`; + const body = truncateText(skill.instructions || "", maxInstructionChars); + entries.push(`${header}\n${body}`); + } + if (entries.length > 0) { + sections.push(`Activated skills:\n${entries.join("\n\n")}`); + } + } + } + + if (sections.length === 0) { + return null; + } + + const prompt = `\n${sections.join("\n\n")}\n`; + return truncateText(prompt, maxPromptChars); + } + + private resolveMode(requested?: WorkspaceSkillSearchMode): WorkspaceSkillSearchMode { + if (!requested) { + return this.defaultMode; + } + + if (requested === "vector" || requested === "hybrid") { + if (!this.embedding || !this.vector) { + throw new Error("Vector search is not configured for skills."); + } + } + + return requested; + } + + private async searchVector( + query: string, + limit: number, + ): Promise> { + if (!this.embedding || !this.vector) { + throw new Error("Vector search is not configured for skills."); + } + + const embedding = await this.embedding.embed(query); + const results = await this.vector.search(embedding, { limit }); + return results.map((item) => ({ id: item.id, score: item.score })); + } + + private formatResults( + results: Array<{ id: string; score: number }>, + options: { + bm25Scores?: Map; + vectorScores?: Map; + }, + query: string, + snippetLength: number, + limit: number, + ): WorkspaceSkillSearchResult[] { + const topResults = results.slice(0, limit); + return topResults.map((item) => { + const doc = this.documents.get(item.id); + const name = doc?.name ?? item.id; + const snippet = doc?.content ? buildSnippet(doc.content, query, snippetLength) : undefined; + return { + id: item.id, + name, + score: item.score, + bm25Score: options.bm25Scores?.get(item.id), + vectorScore: options.vectorScores?.get(item.id), + snippet, + metadata: doc?.metadata, + }; + }); + } + + private resolveSkillId(identifier: string): string | null { + const trimmed = identifier.trim(); + if (!trimmed) { + return null; + } + + if (this.skillsById.has(trimmed)) { + return trimmed; + } + + const normalized = trimmed.toLowerCase(); + const matches = this.skillNameMap.get(normalized); + if (matches && matches.length > 0) { + return matches[0]; + } + + return null; + } + + resolveSkillFilePath( + skill: WorkspaceSkillMetadata, + relativePath: string, + allowed: string[] | undefined, + ): string | null { + const normalized = relativePath.trim(); + if (!normalized) { + return null; + } + + if (normalized.includes("..")) { + return null; + } + + const normalizedAllowed = allowed?.map((entry) => normalizePath(entry)) || []; + const matched = normalizedAllowed.find( + (entry) => entry === normalized || entry.endsWith(`/${normalized}`), + ); + + if (!matched) { + return null; + } + + const cleaned = normalizePath(matched); + if (cleaned.startsWith("/")) { + const rootPrefix = skill.root === "/" ? "/" : `${skill.root}/`; + if (!cleaned.startsWith(rootPrefix)) { + return null; + } + return cleaned; + } + + return joinPaths(skill.root, cleaned); + } + + async readFileContent(filePath: string): Promise { + const data = await this.filesystem.readRaw(filePath); + return data.content.join("\n"); + } +} + +export const createWorkspaceSkillsPromptHook = ( + context: WorkspaceSkillsPromptHookContext, + options: WorkspaceSkillsPromptOptions = {}, +): AgentHooks => ({ + onPrepareMessages: async ({ messages }): Promise => { + if (!context.skills) { + return { messages }; + } + + const prompt = await context.skills.buildPrompt(options); + if (!prompt) { + return { messages }; + } + + const systemMessage = { + id: randomUUID(), + role: "system" as const, + parts: [{ type: "text" as const, text: prompt }], + }; + + return { messages: [systemMessage, ...messages] }; + }, +}); + +export const createWorkspaceSkillsToolkit = ( + context: WorkspaceSkillsToolkitContext, + options: WorkspaceSkillsToolkitOptions = {}, +): Toolkit => { + const systemPrompt = + options.systemPrompt === undefined ? SKILLS_SYSTEM_PROMPT : options.systemPrompt; + + const isToolPolicyGroup = ( + policies: WorkspaceToolPolicies, + ): policies is WorkspaceToolPolicyGroup => + Object.prototype.hasOwnProperty.call(policies, "tools") || + Object.prototype.hasOwnProperty.call(policies, "defaults"); + + const resolveToolPolicy = (name: WorkspaceSkillsToolName) => { + const toolPolicies = options.toolPolicies; + if (!toolPolicies) { + return undefined; + } + if (isToolPolicyGroup(toolPolicies)) { + const defaults = toolPolicies.defaults ?? {}; + const override = toolPolicies.tools?.[name] ?? {}; + const merged = { ...defaults, ...override }; + return Object.keys(merged).length > 0 ? merged : undefined; + } + return toolPolicies[name]; + }; + + const isToolEnabled = (name: WorkspaceSkillsToolName) => resolveToolPolicy(name)?.enabled ?? true; + + const listTool = createTool({ + name: "workspace_list_skills", + description: options.customToolDescriptions?.list || LIST_SKILLS_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_list_skills")?.needsApproval, + parameters: z.object({ + refresh: z.boolean().optional().describe("Refresh skill discovery"), + active_only: z.boolean().optional().describe("Only list active skills"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "skills.list", + }); + + if (!context.skills) { + return "Workspace skills are not configured."; + } + + const skills = await context.skills.discoverSkills({ refresh: Boolean(input.refresh) }); + const activeIds = new Set(context.skills.getActiveSkills().map((skill) => skill.id)); + const listed = input.active_only + ? skills.filter((skill) => activeIds.has(skill.id)) + : skills; + return formatSkillList(listed, activeIds); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const searchTool = createTool({ + name: "workspace_search_skills", + description: options.customToolDescriptions?.search || SEARCH_SKILLS_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_search_skills")?.needsApproval, + parameters: z.object({ + query: z.string().describe("Search query"), + mode: z.enum(["bm25", "vector", "hybrid"]).optional().describe("Search mode"), + top_k: z.coerce.number().optional().default(DEFAULT_TOP_K), + snippet_length: z.coerce.number().optional().describe("Snippet length for each result"), + lexical_weight: z.coerce.number().optional().describe("Hybrid lexical weight"), + vector_weight: z.coerce.number().optional().describe("Hybrid vector weight"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "skills.search", + "workspace.search.query": input.query, + "workspace.search.mode": input.mode, + "workspace.search.top_k": input.top_k, + }); + + if (!context.skills) { + return "Workspace skills are not configured."; + } + + try { + const results = await context.skills.search(input.query, { + mode: input.mode, + topK: input.top_k, + snippetLength: input.snippet_length, + lexicalWeight: input.lexical_weight, + vectorWeight: input.vector_weight, + }); + + setWorkspaceSpanAttributes(operationContext, { + "workspace.search.results": results.length, + }); + + return formatSearchResults(results); + } catch (error: any) { + const message = error?.message ? String(error.message) : "Unknown search error"; + return `Search failed: ${message}`; + } + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const readSkillTool = createTool({ + name: "workspace_read_skill", + description: options.customToolDescriptions?.read || READ_SKILL_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_read_skill")?.needsApproval, + parameters: z.object({ + skill_id: z.string().describe("Skill id or name"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "skills.read", + "workspace.skills.name": input.skill_id, + }); + + if (!context.skills) { + return "Workspace skills are not configured."; + } + + const skill = await context.skills.loadSkill(input.skill_id); + if (!skill) { + return `Skill not found: ${input.skill_id}`; + } + + setWorkspaceSpanAttributes(operationContext, { + "workspace.skills.name": skill.name, + "workspace.skills.source": skill.path, + }); + + return formatSkillDetail(skill); + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const activateSkillTool = createTool({ + name: "workspace_activate_skill", + description: options.customToolDescriptions?.activate || ACTIVATE_SKILL_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_activate_skill")?.needsApproval, + parameters: z.object({ + skill_id: z.string().describe("Skill id or name"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "skills.activate", + "workspace.skills.name": input.skill_id, + }); + + if (!context.skills) { + return "Workspace skills are not configured."; + } + + const skill = await context.skills.activateSkill(input.skill_id); + if (!skill) { + return `Skill not found: ${input.skill_id}`; + } + + setWorkspaceSpanAttributes(operationContext, { + "workspace.skills.name": skill.name, + "workspace.skills.source": skill.path, + }); + + return `Activated skill: ${skill.name} (${skill.id})`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const deactivateSkillTool = createTool({ + name: "workspace_deactivate_skill", + description: options.customToolDescriptions?.deactivate || DEACTIVATE_SKILL_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_deactivate_skill")?.needsApproval, + parameters: z.object({ + skill_id: z.string().describe("Skill id or name"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": "skills.deactivate", + "workspace.skills.name": input.skill_id, + }); + + if (!context.skills) { + return "Workspace skills are not configured."; + } + + const success = await context.skills.deactivateSkill(input.skill_id); + if (!success) { + return `Skill not found: ${input.skill_id}`; + } + + return `Deactivated skill: ${input.skill_id}`; + }, + executeOptions, + options.operationTimeoutMs, + ), + }); + + const readSkillFile = async ( + skillId: string, + filePath: string, + kind: "reference" | "script" | "asset", + executeOptions: unknown, + ): Promise => { + const operationContext = executeOptions as OperationContext; + setWorkspaceSpanAttributes(operationContext, { + ...buildWorkspaceAttributes(context.workspace), + "workspace.operation": `skills.read_${kind}`, + "workspace.skills.name": skillId, + }); + + if (!context.skills) { + return "Workspace skills are not configured."; + } + + const skill = await context.skills.loadSkill(skillId); + if (!skill) { + return `Skill not found: ${skillId}`; + } + + const list = + kind === "reference" ? skill.references : kind === "script" ? skill.scripts : skill.assets; + + const resolvedPath = context.skills.resolveSkillFilePath(skill, filePath, list); + if (!resolvedPath) { + const available = list && list.length > 0 ? list.join(", ") : "none"; + return `File not allowed for ${kind}. Available: ${available}`; + } + + setWorkspaceSpanAttributes(operationContext, { + "workspace.skills.name": skill.name, + "workspace.skills.source": resolvedPath, + "workspace.fs.path": resolvedPath, + }); + + try { + const content = await context.skills.readFileContent(resolvedPath); + return content || "(empty)"; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + setWorkspaceSpanAttributes(operationContext, { + "workspace.error": message, + }); + return `Error reading skill file: ${message}`; + } + }; + + const readReferenceTool = createTool({ + name: "workspace_read_skill_reference", + description: options.customToolDescriptions?.readReference || READ_SKILL_REFERENCE_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_read_skill_reference")?.needsApproval, + parameters: z.object({ + skill_id: z.string().describe("Skill id or name"), + reference: z.string().describe("Reference file path"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => readSkillFile(input.skill_id, input.reference, "reference", executeOptions), + executeOptions, + options.operationTimeoutMs, + ), + }); + + const readScriptTool = createTool({ + name: "workspace_read_skill_script", + description: options.customToolDescriptions?.readScript || READ_SKILL_SCRIPT_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_read_skill_script")?.needsApproval, + parameters: z.object({ + skill_id: z.string().describe("Skill id or name"), + script: z.string().describe("Script file path"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => readSkillFile(input.skill_id, input.script, "script", executeOptions), + executeOptions, + options.operationTimeoutMs, + ), + }); + + const readAssetTool = createTool({ + name: "workspace_read_skill_asset", + description: options.customToolDescriptions?.readAsset || READ_SKILL_ASSET_DESCRIPTION, + tags: [...WORKSPACE_SKILLS_TAGS], + needsApproval: resolveToolPolicy("workspace_read_skill_asset")?.needsApproval, + parameters: z.object({ + skill_id: z.string().describe("Skill id or name"), + asset: z.string().describe("Asset file path"), + }), + execute: async (input, executeOptions) => + withOperationTimeout( + async () => readSkillFile(input.skill_id, input.asset, "asset", executeOptions), + executeOptions, + options.operationTimeoutMs, + ), + }); + + const tools = []; + if (isToolEnabled("workspace_list_skills")) { + tools.push(listTool); + } + if (isToolEnabled("workspace_search_skills")) { + tools.push(searchTool); + } + if (isToolEnabled("workspace_read_skill")) { + tools.push(readSkillTool); + } + if (isToolEnabled("workspace_activate_skill")) { + tools.push(activateSkillTool); + } + if (isToolEnabled("workspace_deactivate_skill")) { + tools.push(deactivateSkillTool); + } + if (isToolEnabled("workspace_read_skill_reference")) { + tools.push(readReferenceTool); + } + if (isToolEnabled("workspace_read_skill_script")) { + tools.push(readScriptTool); + } + if (isToolEnabled("workspace_read_skill_asset")) { + tools.push(readAssetTool); + } + + return createToolkit({ + name: "workspace_skills", + description: "Workspace skill management tools", + tools, + instructions: systemPrompt || undefined, + addInstructions: Boolean(systemPrompt), + }); +}; diff --git a/packages/core/src/workspace/skills/types.ts b/packages/core/src/workspace/skills/types.ts new file mode 100644 index 000000000..e65ea7a32 --- /dev/null +++ b/packages/core/src/workspace/skills/types.ts @@ -0,0 +1,85 @@ +import type { EmbeddingAdapterInput, VectorAdapter } from "../../memory/types"; +import type { WorkspaceFilesystem } from "../filesystem"; +import type { WorkspaceIdentity } from "../types"; + +export type WorkspaceSkillSearchMode = "bm25" | "vector" | "hybrid"; + +export type WorkspaceSkillSearchHybridWeights = { + lexicalWeight?: number; + vectorWeight?: number; +}; + +export type WorkspaceSkillsRootResolverContext = { + workspace: WorkspaceIdentity; + filesystem: WorkspaceFilesystem; +}; + +export type WorkspaceSkillsRootResolver = ( + context?: WorkspaceSkillsRootResolverContext, +) => string[] | undefined | null | Promise; + +export type WorkspaceSkillsConfig = { + rootPaths?: string[] | WorkspaceSkillsRootResolver; + glob?: string; + maxFileBytes?: number; + autoDiscover?: boolean; + autoIndex?: boolean; + bm25?: { + k1?: number; + b?: number; + }; + embedding?: EmbeddingAdapterInput; + vector?: VectorAdapter; + defaultMode?: WorkspaceSkillSearchMode; + hybrid?: WorkspaceSkillSearchHybridWeights; +}; + +export type WorkspaceSkillMetadata = { + id: string; + name: string; + description?: string; + version?: string; + tags?: string[]; + path: string; + root: string; + references?: string[]; + scripts?: string[]; + assets?: string[]; +}; + +export type WorkspaceSkill = WorkspaceSkillMetadata & { + instructions: string; +}; + +export type WorkspaceSkillSearchOptions = { + mode?: WorkspaceSkillSearchMode; + topK?: number; + snippetLength?: number; + lexicalWeight?: number; + vectorWeight?: number; +}; + +export type WorkspaceSkillSearchResult = { + id: string; + name: string; + score: number; + bm25Score?: number; + vectorScore?: number; + snippet?: string; + metadata?: Record; +}; + +export type WorkspaceSkillIndexSummary = { + indexed: number; + skipped: number; + errors: string[]; +}; + +export type WorkspaceSkillsPromptOptions = { + includeAvailable?: boolean; + includeActivated?: boolean; + maxAvailable?: number; + maxActivated?: number; + maxInstructionChars?: number; + maxPromptChars?: number; +}; diff --git a/packages/core/src/workspace/timeout.spec.ts b/packages/core/src/workspace/timeout.spec.ts new file mode 100644 index 000000000..5d089374e --- /dev/null +++ b/packages/core/src/workspace/timeout.spec.ts @@ -0,0 +1,35 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { withOperationTimeout } from "./timeout"; + +describe("withOperationTimeout", () => { + afterEach(() => { + vi.useRealTimers(); + }); + + it("returns the task result when no timeout is set", async () => { + const result = await withOperationTimeout(async () => "ok", undefined, undefined); + expect(result).toBe("ok"); + }); + + it("throws when the timeout elapses", async () => { + vi.useFakeTimers(); + const task = () => + new Promise((resolve) => { + setTimeout(() => resolve("late"), 50); + }); + + const promise = withOperationTimeout(task, undefined, 10); + const expectation = expect(promise).rejects.toThrow("timed out"); + await vi.advanceTimersByTimeAsync(20); + await expectation; + }); + + it("throws when the abort signal is already aborted", async () => { + const abortController = new AbortController(); + abortController.abort(); + + await expect( + withOperationTimeout(async () => "ok", { abortController } as any, 100), + ).rejects.toThrow("aborted"); + }); +}); diff --git a/packages/core/src/workspace/timeout.ts b/packages/core/src/workspace/timeout.ts new file mode 100644 index 000000000..84a8419e2 --- /dev/null +++ b/packages/core/src/workspace/timeout.ts @@ -0,0 +1,53 @@ +import type { ToolExecuteOptions } from "../agent/providers/base/types"; + +const DEFAULT_TIMEOUT_MESSAGE = "Workspace operation timed out."; +const DEFAULT_ABORT_MESSAGE = "Workspace operation aborted."; + +const resolveAbortSignal = (options?: ToolExecuteOptions): AbortSignal | undefined => { + return options?.toolContext?.abortSignal ?? options?.abortController?.signal; +}; + +export const withOperationTimeout = async ( + task: () => Promise, + options: ToolExecuteOptions | undefined, + timeoutMs?: number, +): Promise => { + if (!timeoutMs || timeoutMs <= 0) { + return await task(); + } + + const abortSignal = resolveAbortSignal(options); + if (abortSignal?.aborted) { + throw new Error(DEFAULT_ABORT_MESSAGE); + } + + let timeoutId: NodeJS.Timeout | undefined; + let cleanupAbort: (() => void) | undefined; + + const timeoutPromise = new Promise((_, reject) => { + timeoutId = setTimeout(() => reject(new Error(DEFAULT_TIMEOUT_MESSAGE)), timeoutMs); + }); + + const abortPromise = abortSignal + ? new Promise((_, reject) => { + const onAbort = () => reject(new Error(DEFAULT_ABORT_MESSAGE)); + abortSignal.addEventListener("abort", onAbort, { once: true }); + cleanupAbort = () => abortSignal.removeEventListener("abort", onAbort); + }) + : null; + + try { + const races: Array | Promise> = [task(), timeoutPromise]; + if (abortPromise) { + races.push(abortPromise); + } + return await Promise.race(races); + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (cleanupAbort) { + cleanupAbort(); + } + } +}; diff --git a/packages/core/src/workspace/tool-policy.ts b/packages/core/src/workspace/tool-policy.ts new file mode 100644 index 000000000..ba83bfa71 --- /dev/null +++ b/packages/core/src/workspace/tool-policy.ts @@ -0,0 +1,26 @@ +import type { ToolNeedsApprovalFunction } from "@ai-sdk/provider-utils"; + +export type WorkspaceToolPolicy = { + enabled?: boolean; + needsApproval?: boolean | ToolNeedsApprovalFunction; +}; + +export type WorkspaceToolPolicyGroup = { + defaults?: TPolicy; + tools?: Partial>; +}; + +export type WorkspaceToolPolicies = + | Partial> + | WorkspaceToolPolicyGroup; + +export type WorkspaceFilesystemToolPolicy = WorkspaceToolPolicy & { + requireReadBeforeWrite?: boolean; +}; + +export type WorkspaceToolConfig = { + filesystem?: WorkspaceToolPolicies; + sandbox?: WorkspaceToolPolicies; + search?: WorkspaceToolPolicies; + skills?: WorkspaceToolPolicies; +}; diff --git a/packages/core/src/workspace/types.ts b/packages/core/src/workspace/types.ts new file mode 100644 index 000000000..d34293fbb --- /dev/null +++ b/packages/core/src/workspace/types.ts @@ -0,0 +1,66 @@ +import type { FileData, FilesystemBackend, FilesystemBackendFactory } from "./filesystem"; +import type { WorkspaceSandbox } from "./sandbox"; +import type { WorkspaceSearchConfig } from "./search/types"; +import type { WorkspaceSkillsConfig } from "./skills/types"; +import type { WorkspaceToolConfig } from "./tool-policy"; + +export type WorkspaceScope = "agent" | "conversation"; + +export type WorkspaceStatus = "idle" | "initializing" | "ready" | "destroyed" | "error"; + +export type WorkspaceComponentStatus = "idle" | "ready" | "destroyed" | "error"; + +export type WorkspaceIdentity = { + id: string; + name?: string; + scope?: WorkspaceScope; +}; + +export type WorkspaceFilesystemConfig = { + backend?: FilesystemBackend | FilesystemBackendFactory; + files?: Record; + directories?: string[]; + readOnly?: boolean; +}; + +export type WorkspaceComponentInfo = { + status?: WorkspaceComponentStatus; + details?: Record; +}; + +export type WorkspaceInfo = { + id: string; + name?: string; + scope: WorkspaceScope; + status: WorkspaceStatus; + operationTimeoutMs?: number; + filesystem?: WorkspaceComponentInfo; + sandbox?: WorkspaceComponentInfo; + search?: WorkspaceComponentInfo; + skills?: WorkspaceComponentInfo; +}; + +export type WorkspacePathContext = { + filesystem?: { + status?: WorkspaceComponentStatus; + instructions?: string | null; + info?: Record; + }; + sandbox?: { + status?: WorkspaceComponentStatus; + instructions?: string | null; + info?: Record; + }; +}; + +export type WorkspaceConfig = { + id?: string; + name?: string; + scope?: WorkspaceScope; + operationTimeoutMs?: number; + filesystem?: WorkspaceFilesystemConfig; + sandbox?: WorkspaceSandbox; + search?: WorkspaceSearchConfig; + skills?: WorkspaceSkillsConfig; + toolConfig?: WorkspaceToolConfig; +}; diff --git a/packages/sandbox-daytona/package.json b/packages/sandbox-daytona/package.json new file mode 100644 index 000000000..a97cbcf46 --- /dev/null +++ b/packages/sandbox-daytona/package.json @@ -0,0 +1,46 @@ +{ + "name": "@voltagent/sandbox-daytona", + "description": "VoltAgent Daytona sandbox provider", + "version": "2.0.0", + "dependencies": { + "@daytonaio/sdk": "^0.139.0" + }, + "devDependencies": { + "@types/node": "^24.2.1", + "@voltagent/core": "^2.0.0", + "tsup": "^8.5.0", + "typescript": "^5.8.2" + }, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "files": [ + "dist" + ], + "license": "MIT", + "main": "dist/index.js", + "module": "dist/index.mjs", + "peerDependencies": { + "@voltagent/core": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/VoltAgent/voltagent.git", + "directory": "packages/sandbox-daytona" + }, + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit" + }, + "types": "dist/index.d.ts" +} diff --git a/packages/sandbox-daytona/src/index.ts b/packages/sandbox-daytona/src/index.ts new file mode 100644 index 000000000..371876107 --- /dev/null +++ b/packages/sandbox-daytona/src/index.ts @@ -0,0 +1,266 @@ +import * as daytonaModule from "@daytonaio/sdk"; +import type { + WorkspaceSandbox, + WorkspaceSandboxExecuteOptions, + WorkspaceSandboxResult, +} from "@voltagent/core"; + +export type DaytonaSandboxOptions = { + apiKey?: string; + apiUrl?: string; + target?: string; + clientOptions?: Record; + createParams?: Record; + createTimeoutSeconds?: number; + env?: Record; + cwd?: string; + defaultTimeoutMs?: number; + maxOutputBytes?: number; + sandbox?: DaytonaSandboxInstance; +}; + +type DaytonaExecResult = { + exitCode?: number; + result?: string; + artifacts?: { + stdout?: string; + stderr?: string; + }; +}; + +type DaytonaSandboxInstance = { + process: { + executeCommand: ( + command: string, + cwd?: string, + env?: Record, + timeoutSeconds?: number, + ) => Promise; + }; +}; + +type DaytonaClient = { + create: ( + params?: Record, + options?: { timeout?: number }, + ) => Promise; +}; + +type DaytonaModule = { + Daytona: new (options?: Record) => DaytonaClient; +}; + +const DEFAULT_TIMEOUT_MS = 60000; +const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024; +const SAFE_SHELL_ARG = /^[A-Za-z0-9_./:@+=-]+$/; + +const escapeShellArg = (value: string): string => { + if (value.length === 0) { + return "''"; + } + if (SAFE_SHELL_ARG.test(value)) { + return value; + } + return `'${value.replace(/'/g, "'\\''")}'`; +}; + +const buildCommandLine = (command: string, args?: string[]): string => { + if (!args || args.length === 0) { + return command; + } + return [command, ...args].map(escapeShellArg).join(" "); +}; + +const normalizeEnv = (env?: Record): Record => { + const result: Record = {}; + if (!env) { + return result; + } + for (const [key, value] of Object.entries(env)) { + if (value === undefined || value === null) { + continue; + } + result[key] = String(value); + } + return result; +}; + +const truncateOutput = ( + value: string, + maxBytes: number, +): { content: string; truncated: boolean } => { + if (!value) { + return { content: "", truncated: false }; + } + if (maxBytes <= 0) { + return { content: "", truncated: true }; + } + const size = Buffer.byteLength(value, "utf-8"); + if (size <= maxBytes) { + return { content: value, truncated: false }; + } + const truncated = Buffer.from(value, "utf-8").subarray(0, maxBytes).toString("utf-8"); + return { content: truncated, truncated: true }; +}; + +const extractString = (value: unknown): string | undefined => + typeof value === "string" ? value : undefined; + +export class DaytonaSandbox implements WorkspaceSandbox { + name = "daytona"; + private readonly apiKey?: string; + private readonly apiUrl?: string; + private readonly target?: string; + private readonly clientOptions?: Record; + private readonly createParams?: Record; + private readonly createTimeoutSeconds?: number; + private readonly env: Record; + private readonly cwd?: string; + private readonly defaultTimeoutMs: number; + private readonly maxOutputBytes: number; + private sandbox?: DaytonaSandboxInstance; + private sandboxPromise?: Promise; + + constructor(options: DaytonaSandboxOptions = {}) { + this.apiKey = options.apiKey; + this.apiUrl = options.apiUrl; + this.target = options.target; + this.clientOptions = options.clientOptions; + this.createParams = options.createParams; + this.createTimeoutSeconds = options.createTimeoutSeconds; + this.env = normalizeEnv(options.env); + this.cwd = options.cwd; + this.defaultTimeoutMs = options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS; + this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + this.sandbox = options.sandbox; + } + + private buildClientOptions(): Record { + const merged = { ...(this.clientOptions ?? {}) }; + if (this.apiKey !== undefined && merged.apiKey === undefined) { + merged.apiKey = this.apiKey; + } + if (this.apiUrl !== undefined && merged.apiUrl === undefined) { + merged.apiUrl = this.apiUrl; + } + if (this.target !== undefined && merged.target === undefined) { + merged.target = this.target; + } + return merged; + } + + private async createSandbox(): Promise { + const { Daytona } = daytonaModule as unknown as DaytonaModule; + const client = new Daytona(this.buildClientOptions()); + const options = this.createTimeoutSeconds ? { timeout: this.createTimeoutSeconds } : undefined; + return await client.create(this.createParams, options); + } + + private async getSandbox(): Promise { + if (this.sandbox) { + return this.sandbox; + } + if (!this.sandboxPromise) { + this.sandboxPromise = this.createSandbox() + .then((sandbox) => { + this.sandbox = sandbox; + return sandbox; + }) + .catch((error) => { + this.sandboxPromise = undefined; + throw error; + }); + } + return this.sandboxPromise; + } + + async execute(options: WorkspaceSandboxExecuteOptions): Promise { + const startTime = Date.now(); + const command = options.command?.trim(); + + if (!command) { + throw new Error("Sandbox command is required"); + } + + if (options.signal?.aborted) { + return { + stdout: "", + stderr: "", + exitCode: null, + durationMs: 0, + timedOut: false, + aborted: true, + stdoutTruncated: false, + stderrTruncated: false, + }; + } + + const sandbox = await this.getSandbox(); + const maxOutputBytes = + options.maxOutputBytes === undefined + ? this.maxOutputBytes + : Math.max(0, options.maxOutputBytes); + const timeoutMs = + options.timeoutMs === undefined ? this.defaultTimeoutMs : Math.max(0, options.timeoutMs); + const timeoutSeconds = timeoutMs > 0 ? Math.ceil(timeoutMs / 1000) : undefined; + + const envs = { + ...this.env, + ...normalizeEnv(options.env), + }; + + let aborted = false; + let timedOut = false; + let timeoutId: ReturnType | undefined; + let abortListener: (() => void) | undefined; + + if (options.signal) { + abortListener = () => { + aborted = true; + }; + options.signal.addEventListener("abort", abortListener, { once: true }); + } + + if (timeoutMs > 0) { + timeoutId = setTimeout(() => { + timedOut = true; + }, timeoutMs); + } + + let response: DaytonaExecResult; + try { + const commandLine = buildCommandLine(command, options.args); + response = await sandbox.process.executeCommand( + commandLine, + options.cwd ?? this.cwd, + Object.keys(envs).length > 0 ? envs : undefined, + timeoutSeconds, + ); + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (options.signal && abortListener) { + options.signal.removeEventListener("abort", abortListener); + } + } + + const stdoutRaw = + extractString(response.artifacts?.stdout) ?? extractString(response.result) ?? ""; + const stderrRaw = extractString(response.artifacts?.stderr) ?? ""; + + const stdoutInfo = truncateOutput(stdoutRaw, maxOutputBytes); + const stderrInfo = truncateOutput(stderrRaw, maxOutputBytes); + + return { + stdout: stdoutInfo.content, + stderr: stderrInfo.content, + exitCode: typeof response.exitCode === "number" ? response.exitCode : null, + durationMs: Date.now() - startTime, + timedOut, + aborted, + stdoutTruncated: stdoutInfo.truncated, + stderrTruncated: stderrInfo.truncated, + }; + } +} diff --git a/packages/sandbox-daytona/tsconfig.json b/packages/sandbox-daytona/tsconfig.json new file mode 100644 index 000000000..d4612442c --- /dev/null +++ b/packages/sandbox-daytona/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "es2018", + "lib": ["dom", "dom.iterable", "esnext"], + "module": "esnext", + "moduleResolution": "node", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "outDir": "./dist", + "rootDir": "./", + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "strictBindCallApply": true, + "strictPropertyInitialization": true, + "noImplicitThis": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/sandbox-daytona/tsup.config.ts b/packages/sandbox-daytona/tsup.config.ts new file mode 100644 index 000000000..e019584d6 --- /dev/null +++ b/packages/sandbox-daytona/tsup.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from "tsup"; +import { markAsExternalPlugin } from "../shared/tsup-plugins/mark-as-external"; + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["cjs", "esm"], + splitting: false, + sourcemap: true, + clean: false, + target: "es2022", + outDir: "dist", + dts: true, + esbuildPlugins: [markAsExternalPlugin], + esbuildOptions(options) { + options.keepNames = true; + return options; + }, +}); diff --git a/packages/sandbox-e2b/package.json b/packages/sandbox-e2b/package.json new file mode 100644 index 000000000..2f27ba748 --- /dev/null +++ b/packages/sandbox-e2b/package.json @@ -0,0 +1,46 @@ +{ + "name": "@voltagent/sandbox-e2b", + "description": "VoltAgent E2B sandbox provider", + "version": "2.0.0", + "dependencies": { + "e2b": "^2.12.0" + }, + "devDependencies": { + "@types/node": "^24.2.1", + "@voltagent/core": "^2.0.0", + "tsup": "^8.5.0", + "typescript": "^5.8.2" + }, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "files": [ + "dist" + ], + "license": "MIT", + "main": "dist/index.js", + "module": "dist/index.mjs", + "peerDependencies": { + "@voltagent/core": "^2.0.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/VoltAgent/voltagent.git", + "directory": "packages/sandbox-e2b" + }, + "scripts": { + "build": "tsup", + "dev": "tsup --watch", + "typecheck": "tsc --noEmit" + }, + "types": "dist/index.d.ts" +} diff --git a/packages/sandbox-e2b/src/index.ts b/packages/sandbox-e2b/src/index.ts new file mode 100644 index 000000000..774284493 --- /dev/null +++ b/packages/sandbox-e2b/src/index.ts @@ -0,0 +1,562 @@ +import type { + WorkspaceSandbox, + WorkspaceSandboxExecuteOptions, + WorkspaceSandboxResult, +} from "@voltagent/core"; +import * as e2bModule from "e2b"; + +export type E2BSandboxOptions = { + apiKey?: string; + template?: string; + sandboxId?: string; + createOptions?: Record; + connectOptions?: Record; + env?: Record; + cwd?: string; + user?: string; + requestTimeoutMs?: number; + defaultTimeoutMs?: number; + maxOutputBytes?: number; + sandbox?: E2BSdkSandbox; +}; + +type E2BCommandResult = { + stdout?: string; + stderr?: string; + exitCode?: number; + exit_code?: number; + signal?: string; + signalName?: string; + output?: string; + result?: string; +}; + +type E2BCommandHandle = { + pid?: number; + wait?: () => Promise; + kill?: () => Promise | void; + sendStdin?: (input: string) => Promise | void; +}; + +type E2BCommandsClient = { + run: ( + command: string, + options?: Record, + ) => Promise; + kill?: (pid: number, options?: Record) => Promise | void; + sendStdin?: ( + pid: number, + input: string, + options?: Record, + ) => Promise | void; +}; + +type E2BSdkSandbox = { + commands: E2BCommandsClient; +}; + +type E2BSandboxFactory = { + create: ( + ...args: + | [options?: Record] + | [template: string, options?: Record] + ) => Promise; + connect: (sandboxId: string, options?: Record) => Promise; +}; + +type E2BModule = { + Sandbox: E2BSandboxFactory; +}; + +const DEFAULT_TIMEOUT_MS = 60000; +const DEFAULT_MAX_OUTPUT_BYTES = 5 * 1024 * 1024; +const SAFE_SHELL_ARG = /^[A-Za-z0-9_./:@+=-]+$/; + +type OutputBuffer = { + chunks: Buffer[]; + size: number; + truncated: boolean; +}; + +const initOutputBuffer = (): OutputBuffer => ({ chunks: [], size: 0, truncated: false }); + +const appendOutput = (buffer: OutputBuffer, chunk: unknown, maxBytes: number): void => { + if (maxBytes <= 0) { + buffer.truncated = true; + return; + } + + const data = + typeof chunk === "string" + ? Buffer.from(chunk, "utf-8") + : Buffer.isBuffer(chunk) + ? chunk + : Buffer.from(String(chunk), "utf-8"); + + const remaining = maxBytes - buffer.size; + if (remaining <= 0) { + buffer.truncated = true; + return; + } + + if (data.length > remaining) { + buffer.chunks.push(data.subarray(0, remaining)); + buffer.size += remaining; + buffer.truncated = true; + return; + } + + buffer.chunks.push(data); + buffer.size += data.length; +}; + +const toOutputString = (buffer: OutputBuffer): string => { + if (buffer.chunks.length === 0) { + return ""; + } + return Buffer.concat(buffer.chunks, buffer.size).toString("utf-8"); +}; + +const truncateOutput = ( + value: string, + maxBytes: number, +): { content: string; truncated: boolean } => { + if (!value) { + return { content: "", truncated: false }; + } + if (maxBytes <= 0) { + return { content: "", truncated: true }; + } + const buffer = Buffer.from(value, "utf-8"); + if (buffer.length <= maxBytes) { + return { content: value, truncated: false }; + } + let end = maxBytes; + while (end > 0 && (buffer[end] & 0xc0) === 0x80) { + end -= 1; + } + const truncated = buffer.subarray(0, end).toString("utf-8"); + return { content: truncated, truncated: true }; +}; + +const resolveOutput = ( + buffer: OutputBuffer, + fallback: string | undefined, + maxBytes: number, +): { content: string; truncated: boolean } => { + if (buffer.size > 0 || buffer.truncated) { + return { content: toOutputString(buffer), truncated: buffer.truncated }; + } + if (!fallback) { + return { content: "", truncated: false }; + } + return truncateOutput(fallback, maxBytes); +}; + +const escapeShellArg = (value: string): string => { + if (value.length === 0) { + return "''"; + } + if (SAFE_SHELL_ARG.test(value)) { + return value; + } + return `'${value.replace(/'/g, "'\\''")}'`; +}; + +// buildCommandLine escapes both command and arguments; pass a program name in `command`. +const buildCommandLine = (command: string, args?: string[]): string => { + const safeCommand = escapeShellArg(command); + if (!args || args.length === 0) { + return safeCommand; + } + return [safeCommand, ...args.map(escapeShellArg)].join(" "); +}; + +const normalizeEnv = (env?: Record): Record => { + const result: Record = {}; + if (!env) { + return result; + } + for (const [key, value] of Object.entries(env)) { + if (value === undefined || value === null) { + continue; + } + result[key] = String(value); + } + return result; +}; + +const pickFirstString = (value: unknown, keys: string[]): string | undefined => { + if (!value || typeof value !== "object") { + return undefined; + } + for (const key of keys) { + const candidate = (value as Record)[key]; + if (typeof candidate === "string") { + return candidate; + } + } + return undefined; +}; + +const extractExitCode = (value: unknown): number | null => { + if (!value || typeof value !== "object") { + return null; + } + const record = value as Record; + const exitCode = record.exitCode ?? record.exit_code; + return typeof exitCode === "number" ? exitCode : null; +}; + +const extractSignal = (value: unknown): string | undefined => { + if (!value || typeof value !== "object") { + return undefined; + } + const record = value as Record; + const signal = record.signal ?? record.signalName; + return typeof signal === "string" ? signal : undefined; +}; + +const isCommandHandle = (value: unknown): value is E2BCommandHandle => { + if (!value || typeof value !== "object") { + return false; + } + return typeof (value as E2BCommandHandle).wait === "function"; +}; + +export class E2BSandbox implements WorkspaceSandbox { + name = "e2b"; + private readonly apiKey?: string; + private readonly template?: string; + private readonly sandboxId?: string; + private readonly createOptions?: Record; + private readonly connectOptions?: Record; + private readonly env: Record; + private readonly cwd?: string; + private readonly user?: string; + private readonly requestTimeoutMs?: number; + private readonly defaultTimeoutMs: number; + private readonly maxOutputBytes: number; + private sandbox?: E2BSdkSandbox; + private sandboxPromise?: Promise; + + constructor(options: E2BSandboxOptions = {}) { + this.apiKey = options.apiKey; + this.template = options.template?.trim() || undefined; + this.sandboxId = options.sandboxId?.trim() || undefined; + this.createOptions = options.createOptions; + this.connectOptions = options.connectOptions; + this.env = normalizeEnv(options.env); + this.cwd = options.cwd; + this.user = options.user; + this.requestTimeoutMs = options.requestTimeoutMs; + this.defaultTimeoutMs = options.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS; + this.maxOutputBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + this.sandbox = options.sandbox; + } + + private buildSandboxOptions(base?: Record): Record { + const merged = { ...(base ?? {}) }; + if (this.apiKey !== undefined && merged.apiKey === undefined) { + merged.apiKey = this.apiKey; + } + return merged; + } + + private async createSandbox(): Promise { + const { Sandbox } = e2bModule as unknown as E2BModule; + if (this.sandboxId) { + const connectOptions = this.buildSandboxOptions(this.connectOptions); + return await Sandbox.connect(this.sandboxId, connectOptions); + } + + const createOptions = this.buildSandboxOptions(this.createOptions); + if (this.template) { + return await Sandbox.create(this.template, createOptions); + } + return await Sandbox.create(createOptions); + } + + private async getSandbox(): Promise { + if (this.sandbox) { + return this.sandbox; + } + if (!this.sandboxPromise) { + this.sandboxPromise = this.createSandbox() + .then((sandbox) => { + this.sandbox = sandbox; + return sandbox; + }) + .catch((error) => { + this.sandboxPromise = undefined; + throw error; + }); + } + return this.sandboxPromise; + } + + private async killCommand(sandbox: E2BSdkSandbox, handle?: E2BCommandHandle): Promise { + if (!handle) { + return; + } + if (typeof handle.kill === "function") { + await handle.kill(); + return; + } + if (handle.pid === undefined || typeof sandbox.commands.kill !== "function") { + return; + } + const options = + this.requestTimeoutMs === undefined ? undefined : { requestTimeoutMs: this.requestTimeoutMs }; + await sandbox.commands.kill(handle.pid, options); + } + + private async sendStdin( + sandbox: E2BSdkSandbox, + handle: E2BCommandHandle, + input: string, + ): Promise { + if (typeof handle.sendStdin === "function") { + await handle.sendStdin(input); + return; + } + if (handle.pid === undefined || typeof sandbox.commands.sendStdin !== "function") { + throw new Error("Workspace sandbox does not support stdin for this command."); + } + const options = + this.requestTimeoutMs === undefined ? undefined : { requestTimeoutMs: this.requestTimeoutMs }; + await sandbox.commands.sendStdin(handle.pid, input, options); + } + + async execute(options: WorkspaceSandboxExecuteOptions): Promise { + const startTime = Date.now(); + const command = options.command?.trim(); + + if (!command) { + throw new Error("Sandbox command is required"); + } + + if (options.signal?.aborted) { + return { + stdout: "", + stderr: "", + exitCode: null, + durationMs: 0, + timedOut: false, + aborted: true, + stdoutTruncated: false, + stderrTruncated: false, + }; + } + + const timeoutMs = + options.timeoutMs === undefined ? this.defaultTimeoutMs : Math.max(0, options.timeoutMs); + const deadline = timeoutMs > 0 ? startTime + timeoutMs : undefined; + let aborted = false; + let timedOut = false; + + const sandbox = + timeoutMs > 0 + ? await new Promise((resolve, reject) => { + const remaining = deadline ? Math.max(0, deadline - Date.now()) : timeoutMs; + if (remaining <= 0) { + timedOut = true; + resolve(null); + return; + } + let settled = false; + const creationTimeoutId = setTimeout(() => { + if (settled) { + return; + } + settled = true; + timedOut = true; + resolve(null); + }, remaining); + this.getSandbox() + .then((resolved) => { + if (settled) { + return; + } + settled = true; + clearTimeout(creationTimeoutId); + resolve(resolved); + }) + .catch((error) => { + if (settled) { + return; + } + settled = true; + clearTimeout(creationTimeoutId); + reject(error); + }); + }) + : await this.getSandbox(); + + if (!sandbox) { + return { + stdout: "", + stderr: "", + exitCode: null, + durationMs: Date.now() - startTime, + timedOut: true, + aborted: false, + stdoutTruncated: false, + stderrTruncated: false, + }; + } + + const maxOutputBytes = + options.maxOutputBytes === undefined + ? this.maxOutputBytes + : Math.max(0, options.maxOutputBytes); + const effectiveTimeoutMs = + deadline !== undefined ? Math.max(0, deadline - Date.now()) : timeoutMs; + if (deadline !== undefined && effectiveTimeoutMs === 0) { + timedOut = true; + return { + stdout: "", + stderr: "", + exitCode: null, + durationMs: Date.now() - startTime, + timedOut, + aborted, + stdoutTruncated: false, + stderrTruncated: false, + }; + } + const envs = { + ...this.env, + ...normalizeEnv(options.env), + }; + + const stdoutBuffer = initOutputBuffer(); + const stderrBuffer = initOutputBuffer(); + let commandHandle: E2BCommandHandle | undefined; + let timeoutId: ReturnType | undefined; + let abortListener: (() => void) | undefined; + + const requestKill = async (): Promise => { + await this.killCommand(sandbox, commandHandle); + }; + + if (options.signal) { + abortListener = () => { + aborted = true; + requestKill().catch(() => undefined); + }; + options.signal.addEventListener("abort", abortListener, { once: true }); + } + + if (effectiveTimeoutMs > 0) { + timeoutId = setTimeout(() => { + timedOut = true; + requestKill().catch(() => undefined); + }, effectiveTimeoutMs); + } + + const runCommand = async (): Promise => { + const commandLine = buildCommandLine(command, options.args); + const runOptions: Record = { + onStdout: (data: string) => { + appendOutput(stdoutBuffer, data, maxOutputBytes); + if (options.onStdout) { + try { + options.onStdout(data); + } catch { + // ignore streaming callback errors + } + } + }, + onStderr: (data: string) => { + appendOutput(stderrBuffer, data, maxOutputBytes); + if (options.onStderr) { + try { + options.onStderr(data); + } catch { + // ignore streaming callback errors + } + } + }, + }; + + if (this.cwd || options.cwd) { + runOptions.cwd = options.cwd ?? this.cwd; + } + if (this.user) { + runOptions.user = this.user; + } + if (Object.keys(envs).length > 0) { + runOptions.envs = envs; + } + if (effectiveTimeoutMs > 0) { + runOptions.timeoutMs = effectiveTimeoutMs; + } + if (this.requestTimeoutMs !== undefined) { + runOptions.requestTimeoutMs = this.requestTimeoutMs; + } + + const needsHandle = + options.stdin !== undefined || Boolean(options.signal) || effectiveTimeoutMs > 0; + if (needsHandle) { + runOptions.background = true; + } + if (options.stdin !== undefined) { + runOptions.stdin = true; + } + + const response = await sandbox.commands.run(commandLine, runOptions); + + if (isCommandHandle(response)) { + commandHandle = response; + if (aborted || timedOut) { + await this.killCommand(sandbox, response); + return {}; + } + if (options.stdin !== undefined) { + await this.sendStdin(sandbox, response, options.stdin); + } + if (typeof response.wait === "function") { + return await response.wait(); + } + } + + return response as E2BCommandResult; + }; + + let result: E2BCommandResult | undefined; + + try { + result = await runCommand(); + } catch (error) { + if (!aborted && !timedOut) { + throw error; + } + } finally { + if (timeoutId) { + clearTimeout(timeoutId); + } + if (options.signal && abortListener) { + options.signal.removeEventListener("abort", abortListener); + } + } + + const stdoutFallback = pickFirstString(result, ["stdout", "output", "result"]); + const stderrFallback = pickFirstString(result, ["stderr"]); + + const stdoutInfo = resolveOutput(stdoutBuffer, stdoutFallback, maxOutputBytes); + const stderrInfo = resolveOutput(stderrBuffer, stderrFallback, maxOutputBytes); + + return { + stdout: stdoutInfo.content, + stderr: stderrInfo.content, + exitCode: extractExitCode(result), + signal: extractSignal(result), + durationMs: Date.now() - startTime, + timedOut, + aborted, + stdoutTruncated: stdoutInfo.truncated, + stderrTruncated: stderrInfo.truncated, + }; + } +} diff --git a/packages/sandbox-e2b/tsconfig.json b/packages/sandbox-e2b/tsconfig.json new file mode 100644 index 000000000..d4612442c --- /dev/null +++ b/packages/sandbox-e2b/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "target": "es2018", + "lib": ["dom", "dom.iterable", "esnext"], + "module": "esnext", + "moduleResolution": "node", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "outDir": "./dist", + "rootDir": "./", + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "strictBindCallApply": true, + "strictPropertyInitialization": true, + "noImplicitThis": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/sandbox-e2b/tsup.config.ts b/packages/sandbox-e2b/tsup.config.ts new file mode 100644 index 000000000..e019584d6 --- /dev/null +++ b/packages/sandbox-e2b/tsup.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from "tsup"; +import { markAsExternalPlugin } from "../shared/tsup-plugins/mark-as-external"; + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["cjs", "esm"], + splitting: false, + sourcemap: true, + clean: false, + target: "es2022", + outDir: "dist", + dts: true, + esbuildPlugins: [markAsExternalPlugin], + esbuildOptions(options) { + options.keepNames = true; + return options; + }, +}); diff --git a/packages/server-core/src/auth/defaults.ts b/packages/server-core/src/auth/defaults.ts index 80282df0b..a9bf3c883 100644 --- a/packages/server-core/src/auth/defaults.ts +++ b/packages/server-core/src/auth/defaults.ts @@ -63,6 +63,11 @@ export const DEFAULT_CONSOLE_ROUTES = [ "GET /agents/:id/card", "GET /agents/:id/history", + "GET /agents/:id/workspace", + "GET /agents/:id/workspace/ls", + "GET /agents/:id/workspace/read", + "GET /agents/:id/workspace/skills", + "GET /agents/:id/workspace/skills/:skillId", "GET /workflows/executions", "GET /workflows/:id/executions/:executionId/state", "GET /api/logs", @@ -90,6 +95,11 @@ export const PROTECTED_ROUTES = [ "GET /agents/:id/chat/:conversationId/stream", // resumeChatStream "POST /agents/:id/object", // generateObject "POST /agents/:id/stream-object", // streamObject + "GET /agents/:id/workspace", // workspace info + "GET /agents/:id/workspace/ls", // workspace list files + "GET /agents/:id/workspace/read", // workspace read file + "GET /agents/:id/workspace/skills", // workspace list skills + "GET /agents/:id/workspace/skills/:skillId", // workspace skill "WS /ws/agents/:id", // WebSocket connection // ======================================== diff --git a/packages/server-core/src/handlers/agent-additional.handlers.ts b/packages/server-core/src/handlers/agent-additional.handlers.ts index 3bbb6d2ad..f818f4aa5 100644 --- a/packages/server-core/src/handlers/agent-additional.handlers.ts +++ b/packages/server-core/src/handlers/agent-additional.handlers.ts @@ -1,4 +1,4 @@ -import type { ServerProviderDeps } from "@voltagent/core"; +import type { ServerProviderDeps, Workspace, WorkspaceSkillMetadata } from "@voltagent/core"; import type { Logger } from "@voltagent/internal"; import type { ApiResponse } from "../types"; @@ -95,3 +95,363 @@ export async function handleGetAgentHistory( }; } } + +const parseOptionalInteger = (value: unknown): number | null | undefined => { + if (value === undefined || value === null || value === "") { + return undefined; + } + if (typeof value === "number" && Number.isFinite(value)) { + return value; + } + const parsed = Number.parseInt(String(value), 10); + return Number.isNaN(parsed) ? null : parsed; +}; + +const parseOptionalBoolean = (value: unknown): boolean | null | undefined => { + if (value === undefined || value === null || value === "") { + return undefined; + } + if (typeof value === "boolean") { + return value; + } + const normalized = String(value).toLowerCase(); + if (normalized === "true") return true; + if (normalized === "false") return false; + return null; +}; + +const resolveAgentWorkspace = ( + agentId: string, + deps: ServerProviderDeps, +): { + agent: ReturnType; + workspace: Workspace | null; +} | null => { + const agent = deps.agentRegistry.getAgent(agentId); + if (!agent) { + return null; + } + const workspace = agent.getWorkspace?.(); + if (!workspace) { + return { agent, workspace: null }; + } + return { agent, workspace }; +}; + +/** + * Handler for getting agent workspace info + */ +export async function handleGetAgentWorkspaceInfo( + agentId: string, + deps: ServerProviderDeps, + logger: Logger, +): Promise { + try { + const resolved = resolveAgentWorkspace(agentId, deps); + if (!resolved) { + return { + success: false, + error: `Agent ${agentId} not found`, + httpStatus: 404, + }; + } + + if (!resolved.workspace) { + return { + success: false, + error: "Workspace not configured for this agent", + httpStatus: 404, + }; + } + + const workspace = resolved.workspace; + + return { + success: true, + data: { + id: workspace.id, + name: workspace.name, + scope: workspace.scope, + capabilities: { + filesystem: true, + sandbox: Boolean(workspace.sandbox), + search: Boolean(workspace.getInfo().search), + skills: Boolean(workspace.skills), + }, + }, + }; + } catch (error) { + logger.error("Failed to get workspace info", { error }); + return { + success: false, + error: error instanceof Error ? error.message : "Failed to get workspace info", + httpStatus: 500, + }; + } +} + +/** + * Handler for listing workspace files + */ +export async function handleListAgentWorkspaceFiles( + agentId: string, + options: { path?: string }, + deps: ServerProviderDeps, + logger: Logger, +): Promise { + try { + const resolved = resolveAgentWorkspace(agentId, deps); + if (!resolved) { + return { + success: false, + error: `Agent ${agentId} not found`, + httpStatus: 404, + }; + } + if (!resolved.workspace) { + return { + success: false, + error: "Workspace not configured for this agent", + httpStatus: 404, + }; + } + + const path = options.path && options.path.trim().length > 0 ? options.path : "/"; + const entries = await resolved.workspace.filesystem.lsInfo(path); + + return { + success: true, + data: { + path, + entries, + }, + }; + } catch (error) { + logger.error("Failed to list workspace files", { error }); + return { + success: false, + error: error instanceof Error ? error.message : "Failed to list workspace files", + httpStatus: 500, + }; + } +} + +/** + * Handler for reading a workspace file + */ +export async function handleReadAgentWorkspaceFile( + agentId: string, + options: { path?: string; offset?: unknown; limit?: unknown }, + deps: ServerProviderDeps, + logger: Logger, +): Promise { + try { + const resolved = resolveAgentWorkspace(agentId, deps); + if (!resolved) { + return { + success: false, + error: `Agent ${agentId} not found`, + httpStatus: 404, + }; + } + if (!resolved.workspace) { + return { + success: false, + error: "Workspace not configured for this agent", + httpStatus: 404, + }; + } + + const path = options.path?.trim(); + if (!path) { + return { + success: false, + error: "Missing required path parameter", + httpStatus: 400, + }; + } + + const offset = parseOptionalInteger(options.offset); + if (offset === null) { + return { + success: false, + error: "Invalid offset parameter", + httpStatus: 400, + }; + } + const limit = parseOptionalInteger(options.limit); + if (limit === null) { + return { + success: false, + error: "Invalid limit parameter", + httpStatus: 400, + }; + } + if (offset !== undefined && offset < 0) { + return { + success: false, + error: "Offset must be >= 0", + httpStatus: 400, + }; + } + if (limit !== undefined && limit < 1) { + return { + success: false, + error: "Limit must be >= 1", + httpStatus: 400, + }; + } + + const content = await resolved.workspace.filesystem.read(path, { + offset: offset ?? 0, + limit: limit ?? 2000, + }); + + return { + success: true, + data: { + path, + content, + }, + }; + } catch (error) { + logger.error("Failed to read workspace file", { error }); + return { + success: false, + error: error instanceof Error ? error.message : "Failed to read workspace file", + httpStatus: 500, + }; + } +} + +/** + * Handler for listing workspace skills + */ +export async function handleListAgentWorkspaceSkills( + agentId: string, + options: { refresh?: unknown }, + deps: ServerProviderDeps, + logger: Logger, +): Promise { + try { + const resolved = resolveAgentWorkspace(agentId, deps); + if (!resolved) { + return { + success: false, + error: `Agent ${agentId} not found`, + httpStatus: 404, + }; + } + if (!resolved.workspace) { + return { + success: false, + error: "Workspace not configured for this agent", + httpStatus: 404, + }; + } + if (!resolved.workspace.skills) { + return { + success: false, + error: "Workspace skills are not configured for this agent", + httpStatus: 404, + }; + } + + const refresh = parseOptionalBoolean(options.refresh); + if (refresh === null) { + return { + success: false, + error: "Invalid refresh parameter", + httpStatus: 400, + }; + } + + const skills: WorkspaceSkillMetadata[] = await resolved.workspace.skills.discoverSkills({ + refresh: Boolean(refresh), + }); + const activeIds = new Set( + resolved.workspace.skills.getActiveSkills().map((skill: WorkspaceSkillMetadata) => skill.id), + ); + const list = skills.map((skill) => ({ + ...skill, + active: activeIds.has(skill.id), + })); + + return { + success: true, + data: { + skills: list, + }, + }; + } catch (error) { + logger.error("Failed to list workspace skills", { error }); + return { + success: false, + error: error instanceof Error ? error.message : "Failed to list workspace skills", + httpStatus: 500, + }; + } +} + +/** + * Handler for reading a workspace skill + */ +export async function handleGetAgentWorkspaceSkill( + agentId: string, + skillId: string, + deps: ServerProviderDeps, + logger: Logger, +): Promise { + try { + const resolved = resolveAgentWorkspace(agentId, deps); + if (!resolved) { + return { + success: false, + error: `Agent ${agentId} not found`, + httpStatus: 404, + }; + } + if (!resolved.workspace) { + return { + success: false, + error: "Workspace not configured for this agent", + httpStatus: 404, + }; + } + if (!resolved.workspace.skills) { + return { + success: false, + error: "Workspace skills are not configured for this agent", + httpStatus: 404, + }; + } + if (!skillId || skillId.trim().length === 0) { + return { + success: false, + error: "Missing skillId parameter", + httpStatus: 400, + }; + } + + const skill = await resolved.workspace.skills.loadSkill(skillId); + if (!skill) { + return { + success: false, + error: `Skill ${skillId} not found`, + httpStatus: 404, + }; + } + + return { + success: true, + data: skill, + }; + } catch (error) { + logger.error("Failed to get workspace skill", { error }); + return { + success: false, + error: error instanceof Error ? error.message : "Failed to get workspace skill", + httpStatus: 500, + }; + } +} diff --git a/packages/server-core/src/routes/definitions.ts b/packages/server-core/src/routes/definitions.ts index ba7bc80ed..b44b1cae7 100644 --- a/packages/server-core/src/routes/definitions.ts +++ b/packages/server-core/src/routes/definitions.ts @@ -262,6 +262,125 @@ export const AGENT_ROUTES = { }, }, }, + getWorkspace: { + method: "get" as const, + path: "/agents/:id/workspace", + summary: "Get agent workspace info", + description: + "Retrieve workspace configuration metadata for an agent, including capabilities (filesystem, sandbox, search, skills).", + tags: ["Agent Workspace"], + operationId: "getAgentWorkspace", + responses: { + 200: { + description: "Successfully retrieved workspace info", + contentType: "application/json", + }, + 404: { + description: "Agent or workspace not found", + contentType: "application/json", + }, + 500: { + description: "Failed to retrieve workspace info due to server error", + contentType: "application/json", + }, + }, + }, + listWorkspaceFiles: { + method: "get" as const, + path: "/agents/:id/workspace/ls", + summary: "List workspace files", + description: "List files and directories under a workspace path.", + tags: ["Agent Workspace"], + operationId: "listWorkspaceFiles", + responses: { + 200: { + description: "Successfully listed workspace files", + contentType: "application/json", + }, + 400: { + description: "Invalid request parameters", + contentType: "application/json", + }, + 404: { + description: "Agent or workspace not found", + contentType: "application/json", + }, + 500: { + description: "Failed to list workspace files due to server error", + contentType: "application/json", + }, + }, + }, + readWorkspaceFile: { + method: "get" as const, + path: "/agents/:id/workspace/read", + summary: "Read workspace file", + description: "Read a file from the workspace filesystem.", + tags: ["Agent Workspace"], + operationId: "readWorkspaceFile", + responses: { + 200: { + description: "Successfully read workspace file", + contentType: "application/json", + }, + 400: { + description: "Invalid request parameters", + contentType: "application/json", + }, + 404: { + description: "Agent or workspace not found", + contentType: "application/json", + }, + 500: { + description: "Failed to read workspace file due to server error", + contentType: "application/json", + }, + }, + }, + listWorkspaceSkills: { + method: "get" as const, + path: "/agents/:id/workspace/skills", + summary: "List workspace skills", + description: "List available workspace skills for an agent.", + tags: ["Agent Workspace"], + operationId: "listWorkspaceSkills", + responses: { + 200: { + description: "Successfully listed workspace skills", + contentType: "application/json", + }, + 404: { + description: "Agent, workspace, or skills not found", + contentType: "application/json", + }, + 500: { + description: "Failed to list workspace skills due to server error", + contentType: "application/json", + }, + }, + }, + getWorkspaceSkill: { + method: "get" as const, + path: "/agents/:id/workspace/skills/:skillId", + summary: "Get workspace skill", + description: "Retrieve a specific workspace skill including its instructions.", + tags: ["Agent Workspace"], + operationId: "getWorkspaceSkill", + responses: { + 200: { + description: "Successfully retrieved workspace skill", + contentType: "application/json", + }, + 404: { + description: "Agent, workspace, or skill not found", + contentType: "application/json", + }, + 500: { + description: "Failed to retrieve workspace skill due to server error", + contentType: "application/json", + }, + }, + }, } as const; /** diff --git a/packages/server-core/src/schemas/agent.schemas.ts b/packages/server-core/src/schemas/agent.schemas.ts index 752525f38..1ecf4e224 100644 --- a/packages/server-core/src/schemas/agent.schemas.ts +++ b/packages/server-core/src/schemas/agent.schemas.ts @@ -56,6 +56,61 @@ export const AgentListSchema = z .array(AgentResponseSchema) .describe("Array of agent objects with their configurations"); +// Workspace schemas +export const WorkspaceInfoSchema = z.object({ + id: z.string().describe("Workspace ID"), + name: z.string().optional().describe("Workspace name"), + scope: z.enum(["agent", "conversation"]).optional().describe("Workspace scope"), + capabilities: z.object({ + filesystem: z.boolean().describe("Filesystem access enabled"), + sandbox: z.boolean().describe("Sandbox execution enabled"), + search: z.boolean().describe("Search enabled"), + skills: z.boolean().describe("Skills enabled"), + }), +}); + +export const WorkspaceFileInfoSchema = z.object({ + path: z.string(), + is_dir: z.boolean(), + size: z.number().optional(), + modified_at: z.string().optional(), +}); + +export const WorkspaceFileListSchema = z.object({ + path: z.string(), + entries: z.array(WorkspaceFileInfoSchema), +}); + +export const WorkspaceReadFileSchema = z.object({ + path: z.string(), + content: z.string(), +}); + +export const WorkspaceSkillMetadataSchema = z.object({ + id: z.string(), + name: z.string(), + description: z.string().optional(), + version: z.string().optional(), + tags: z.array(z.string()).optional(), + path: z.string(), + root: z.string(), + references: z.array(z.string()).optional(), + scripts: z.array(z.string()).optional(), + assets: z.array(z.string()).optional(), +}); + +export const WorkspaceSkillListItemSchema = WorkspaceSkillMetadataSchema.extend({ + active: z.boolean().describe("Whether the skill is currently activated"), +}); + +export const WorkspaceSkillListSchema = z.object({ + skills: z.array(WorkspaceSkillListItemSchema), +}); + +export const WorkspaceSkillSchema = WorkspaceSkillMetadataSchema.extend({ + instructions: z.string(), +}); + // Basic JSON schema for structured output (used in both output and object generation) export const BasicJsonSchema = z .object({ diff --git a/packages/server-elysia/src/routes/agent.routes.ts b/packages/server-elysia/src/routes/agent.routes.ts index 5848f928e..bb68eb7f2 100644 --- a/packages/server-elysia/src/routes/agent.routes.ts +++ b/packages/server-elysia/src/routes/agent.routes.ts @@ -6,7 +6,12 @@ import { handleGenerateText, handleGetAgent, handleGetAgentHistory, + handleGetAgentWorkspaceInfo, + handleGetAgentWorkspaceSkill, handleGetAgents, + handleListAgentWorkspaceFiles, + handleListAgentWorkspaceSkills, + handleReadAgentWorkspaceFile, handleStreamObject, handleStreamText, mapLogResponse, @@ -22,6 +27,11 @@ import { ObjectResponseSchema, TextRequestSchema, TextResponseSchema, + WorkspaceFileListSchema, + WorkspaceInfoSchema, + WorkspaceReadFileSchema, + WorkspaceSkillListSchema, + WorkspaceSkillSchema, } from "../schemas"; // Agent ID parameter @@ -35,6 +45,25 @@ const HistoryQuery = t.Object({ limit: t.Optional(t.String()), }); +const WorkspaceListQuery = t.Object({ + path: t.Optional(t.String()), +}); + +const WorkspaceReadQuery = t.Object({ + path: t.String(), + offset: t.Optional(t.String()), + limit: t.Optional(t.String()), +}); + +const WorkspaceSkillsQuery = t.Object({ + refresh: t.Optional(t.String()), +}); + +const WorkspaceSkillParams = t.Object({ + id: t.String(), + skillId: t.String(), +}); + /** * Register agent routes with full type validation and OpenAPI documentation */ @@ -229,4 +258,169 @@ export function registerAgentRoutes(app: Elysia, deps: ServerProviderDeps, logge }, }, ); + + // GET /agents/:id/workspace - Workspace info + app.get( + "/agents/:id/workspace", + async ({ params, set }) => { + const response = await handleGetAgentWorkspaceInfo(params.id, deps, logger); + if (!response.success) { + set.status = response.httpStatus || 500; + return response; + } + return response; + }, + { + params: AgentIdParam, + response: { + 200: t.Object({ + success: t.Literal(true), + data: WorkspaceInfoSchema, + }), + 404: ErrorSchema, + 500: ErrorSchema, + }, + detail: { + summary: "Get agent workspace info", + description: "Retrieve workspace metadata and capabilities for an agent", + tags: ["Agents"], + }, + }, + ); + + // GET /agents/:id/workspace/ls - List workspace files + app.get( + "/agents/:id/workspace/ls", + async ({ params, query, set }) => { + const response = await handleListAgentWorkspaceFiles( + params.id, + { path: query.path }, + deps, + logger, + ); + if (!response.success) { + set.status = response.httpStatus || 500; + return response; + } + return response; + }, + { + params: AgentIdParam, + query: WorkspaceListQuery, + response: { + 200: t.Object({ + success: t.Literal(true), + data: WorkspaceFileListSchema, + }), + 400: ErrorSchema, + 404: ErrorSchema, + 500: ErrorSchema, + }, + detail: { + summary: "List workspace files", + description: "List files and directories under a workspace path", + tags: ["Agents"], + }, + }, + ); + + // GET /agents/:id/workspace/read - Read workspace file + app.get( + "/agents/:id/workspace/read", + async ({ params, query, set }) => { + const response = await handleReadAgentWorkspaceFile( + params.id, + { path: query.path, offset: query.offset, limit: query.limit }, + deps, + logger, + ); + if (!response.success) { + set.status = response.httpStatus || 500; + return response; + } + return response; + }, + { + params: AgentIdParam, + query: WorkspaceReadQuery, + response: { + 200: t.Object({ + success: t.Literal(true), + data: WorkspaceReadFileSchema, + }), + 400: ErrorSchema, + 404: ErrorSchema, + 500: ErrorSchema, + }, + detail: { + summary: "Read workspace file", + description: "Read a file from the workspace filesystem", + tags: ["Agents"], + }, + }, + ); + + // GET /agents/:id/workspace/skills - List workspace skills + app.get( + "/agents/:id/workspace/skills", + async ({ params, query, set }) => { + const response = await handleListAgentWorkspaceSkills( + params.id, + { refresh: query.refresh }, + deps, + logger, + ); + if (!response.success) { + set.status = response.httpStatus || 500; + return response; + } + return response; + }, + { + params: AgentIdParam, + query: WorkspaceSkillsQuery, + response: { + 200: t.Object({ + success: t.Literal(true), + data: WorkspaceSkillListSchema, + }), + 404: ErrorSchema, + 500: ErrorSchema, + }, + detail: { + summary: "List workspace skills", + description: "List available workspace skills for an agent", + tags: ["Agents"], + }, + }, + ); + + // GET /agents/:id/workspace/skills/:skillId - Get workspace skill + app.get( + "/agents/:id/workspace/skills/:skillId", + async ({ params, set }) => { + const response = await handleGetAgentWorkspaceSkill(params.id, params.skillId, deps, logger); + if (!response.success) { + set.status = response.httpStatus || 500; + return response; + } + return response; + }, + { + params: WorkspaceSkillParams, + response: { + 200: t.Object({ + success: t.Literal(true), + data: WorkspaceSkillSchema, + }), + 404: ErrorSchema, + 500: ErrorSchema, + }, + detail: { + summary: "Get workspace skill", + description: "Retrieve a specific workspace skill including instructions", + tags: ["Agents"], + }, + }, + ); } diff --git a/packages/server-elysia/src/schemas.ts b/packages/server-elysia/src/schemas.ts index 0d32522eb..c5a96a6d1 100644 --- a/packages/server-elysia/src/schemas.ts +++ b/packages/server-elysia/src/schemas.ts @@ -17,6 +17,11 @@ import { WorkflowResumeResponseSchema as ZodWorkflowResumeResponseSchema, WorkflowSuspendRequestSchema as ZodWorkflowSuspendRequestSchema, WorkflowSuspendResponseSchema as ZodWorkflowSuspendResponseSchema, + WorkspaceFileListSchema as ZodWorkspaceFileListSchema, + WorkspaceInfoSchema as ZodWorkspaceInfoSchema, + WorkspaceReadFileSchema as ZodWorkspaceReadFileSchema, + WorkspaceSkillListSchema as ZodWorkspaceSkillListSchema, + WorkspaceSkillSchema as ZodWorkspaceSkillSchema, } from "@voltagent/server-core"; import { t } from "elysia"; import { zodToTypeBox } from "./utils/zod-adapter"; @@ -39,6 +44,13 @@ export const TextResponseSchema = zodToTypeBox(ZodTextResponseSchema); export const ObjectRequestSchema = zodToTypeBox(ZodObjectRequestSchema); export const ObjectResponseSchema = zodToTypeBox(ZodObjectResponseSchema); +// Workspace schemas +export const WorkspaceInfoSchema = zodToTypeBox(ZodWorkspaceInfoSchema); +export const WorkspaceFileListSchema = zodToTypeBox(ZodWorkspaceFileListSchema); +export const WorkspaceReadFileSchema = zodToTypeBox(ZodWorkspaceReadFileSchema); +export const WorkspaceSkillListSchema = zodToTypeBox(ZodWorkspaceSkillListSchema); +export const WorkspaceSkillSchema = zodToTypeBox(ZodWorkspaceSkillSchema); + // Workflow schemas export const WorkflowResponseSchema = zodToTypeBox(ZodWorkflowResponseSchema); export const WorkflowListSchema = zodToTypeBox(ZodWorkflowListSchema); diff --git a/packages/server-hono/src/routes/agent.routes.ts b/packages/server-hono/src/routes/agent.routes.ts index f7050eb32..e6ffb4a4a 100644 --- a/packages/server-hono/src/routes/agent.routes.ts +++ b/packages/server-hono/src/routes/agent.routes.ts @@ -19,6 +19,11 @@ import { WorkflowStreamEventSchema, WorkflowSuspendRequestSchema, WorkflowSuspendResponseSchema, + WorkspaceFileListSchema, + WorkspaceInfoSchema, + WorkspaceReadFileSchema, + WorkspaceSkillListSchema, + WorkspaceSkillSchema, } from "@voltagent/server-core"; import { createRoute, z } from "../zod-openapi-compat"; import { createPathParam } from "./path-params"; @@ -422,6 +427,277 @@ Example event: 'data: {"partialUpdate": {...}}\n\n' or 'data: {"finalObject": {. description: AGENT_ROUTES.streamObject.description, }); +export const workspaceInfoRoute = createRoute({ + method: AGENT_ROUTES.getWorkspace.method, + path: AGENT_ROUTES.getWorkspace.path.replace(":id", "{id}"), + request: { + params: z.object({ + id: agentIdParam(), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + success: z.literal(true), + data: WorkspaceInfoSchema, + }), + }, + }, + description: + AGENT_ROUTES.getWorkspace.responses?.[200]?.description || + "Successfully retrieved workspace info", + }, + 404: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.getWorkspace.responses?.[404]?.description || "Agent or workspace not found", + }, + 500: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.getWorkspace.responses?.[500]?.description || + "Failed to retrieve workspace info", + }, + }, + tags: [...AGENT_ROUTES.getWorkspace.tags], + summary: AGENT_ROUTES.getWorkspace.summary, + description: AGENT_ROUTES.getWorkspace.description, +}); + +export const workspaceListFilesRoute = createRoute({ + method: AGENT_ROUTES.listWorkspaceFiles.method, + path: AGENT_ROUTES.listWorkspaceFiles.path.replace(":id", "{id}"), + request: { + params: z.object({ + id: agentIdParam(), + }), + query: z.object({ + path: z.string().optional().describe("Workspace path to list"), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + success: z.literal(true), + data: WorkspaceFileListSchema, + }), + }, + }, + description: + AGENT_ROUTES.listWorkspaceFiles.responses?.[200]?.description || + "Successfully listed workspace files", + }, + 400: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.listWorkspaceFiles.responses?.[400]?.description || + "Invalid request parameters", + }, + 404: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.listWorkspaceFiles.responses?.[404]?.description || + "Agent or workspace not found", + }, + 500: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.listWorkspaceFiles.responses?.[500]?.description || + "Failed to list workspace files", + }, + }, + tags: [...AGENT_ROUTES.listWorkspaceFiles.tags], + summary: AGENT_ROUTES.listWorkspaceFiles.summary, + description: AGENT_ROUTES.listWorkspaceFiles.description, +}); + +export const workspaceReadFileRoute = createRoute({ + method: AGENT_ROUTES.readWorkspaceFile.method, + path: AGENT_ROUTES.readWorkspaceFile.path.replace(":id", "{id}"), + request: { + params: z.object({ + id: agentIdParam(), + }), + query: z.object({ + path: z.string().describe("File path to read"), + offset: z.number({ coerce: true }).optional().describe("Line offset (0-indexed)"), + limit: z.number({ coerce: true }).optional().describe("Max lines to read"), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + success: z.literal(true), + data: WorkspaceReadFileSchema, + }), + }, + }, + description: + AGENT_ROUTES.readWorkspaceFile.responses?.[200]?.description || + "Successfully read workspace file", + }, + 400: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.readWorkspaceFile.responses?.[400]?.description || + "Invalid request parameters", + }, + 404: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.readWorkspaceFile.responses?.[404]?.description || + "Agent or workspace not found", + }, + 500: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.readWorkspaceFile.responses?.[500]?.description || + "Failed to read workspace file", + }, + }, + tags: [...AGENT_ROUTES.readWorkspaceFile.tags], + summary: AGENT_ROUTES.readWorkspaceFile.summary, + description: AGENT_ROUTES.readWorkspaceFile.description, +}); + +export const workspaceListSkillsRoute = createRoute({ + method: AGENT_ROUTES.listWorkspaceSkills.method, + path: AGENT_ROUTES.listWorkspaceSkills.path.replace(":id", "{id}"), + request: { + params: z.object({ + id: agentIdParam(), + }), + query: z.object({ + refresh: z.boolean({ coerce: true }).optional().describe("Refresh skill discovery"), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + success: z.literal(true), + data: WorkspaceSkillListSchema, + }), + }, + }, + description: + AGENT_ROUTES.listWorkspaceSkills.responses?.[200]?.description || + "Successfully listed workspace skills", + }, + 404: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.listWorkspaceSkills.responses?.[404]?.description || + "Agent, workspace, or skills not found", + }, + 500: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.listWorkspaceSkills.responses?.[500]?.description || + "Failed to list workspace skills", + }, + }, + tags: [...AGENT_ROUTES.listWorkspaceSkills.tags], + summary: AGENT_ROUTES.listWorkspaceSkills.summary, + description: AGENT_ROUTES.listWorkspaceSkills.description, +}); + +export const workspaceGetSkillRoute = createRoute({ + method: AGENT_ROUTES.getWorkspaceSkill.method, + path: AGENT_ROUTES.getWorkspaceSkill.path.replace(":id", "{id}").replace(":skillId", "{skillId}"), + request: { + params: z.object({ + id: agentIdParam(), + skillId: z.string().describe("Skill identifier"), + }), + }, + responses: { + 200: { + content: { + "application/json": { + schema: z.object({ + success: z.literal(true), + data: WorkspaceSkillSchema, + }), + }, + }, + description: + AGENT_ROUTES.getWorkspaceSkill.responses?.[200]?.description || + "Successfully retrieved workspace skill", + }, + 404: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.getWorkspaceSkill.responses?.[404]?.description || + "Agent, workspace, or skill not found", + }, + 500: { + content: { + "application/json": { + schema: ErrorSchema, + }, + }, + description: + AGENT_ROUTES.getWorkspaceSkill.responses?.[500]?.description || + "Failed to retrieve workspace skill", + }, + }, + tags: [...AGENT_ROUTES.getWorkspaceSkill.tags], + summary: AGENT_ROUTES.getWorkspaceSkill.summary, + description: AGENT_ROUTES.getWorkspaceSkill.description, +}); + export const getWorkflowsRoute = createRoute({ method: WORKFLOW_ROUTES.listWorkflows.method, path: WORKFLOW_ROUTES.listWorkflows.path, diff --git a/packages/server-hono/src/routes/index.ts b/packages/server-hono/src/routes/index.ts index 9c3b547e7..7958cb853 100644 --- a/packages/server-hono/src/routes/index.ts +++ b/packages/server-hono/src/routes/index.ts @@ -10,13 +10,18 @@ import { handleGenerateText, handleGetAgent, handleGetAgentHistory, + handleGetAgentWorkspaceInfo, + handleGetAgentWorkspaceSkill, handleGetAgents, handleGetLogs, handleGetWorkflow, handleGetWorkflowState, handleGetWorkflows, handleInstallUpdates, + handleListAgentWorkspaceFiles, + handleListAgentWorkspaceSkills, handleListWorkflowRuns, + handleReadAgentWorkspaceFile, handleResumeChatStream, handleResumeWorkflow, handleStreamObject, @@ -41,6 +46,11 @@ import { streamWorkflowRoute, suspendWorkflowRoute, textRoute, + workspaceGetSkillRoute, + workspaceInfoRoute, + workspaceListFilesRoute, + workspaceListSkillsRoute, + workspaceReadFileRoute, } from "./agent.routes"; import { getLogsRoute } from "./log.routes"; import { registerTriggerRoutes } from "./trigger.routes"; @@ -182,6 +192,75 @@ export function registerAgentRoutes( return c.json(response, 200); }); + // GET /agents/:id/workspace - Workspace info + app.openapi(workspaceInfoRoute, async (c) => { + const agentId = c.req.param("id"); + if (!agentId) { + return c.json({ success: false, error: "Missing agent id parameter" }, 400); + } + const response = await handleGetAgentWorkspaceInfo(agentId, deps, logger); + const status = response.success ? 200 : response.httpStatus || 500; + return c.json(response, status); + }); + + // GET /agents/:id/workspace/ls - List workspace files + app.openapi(workspaceListFilesRoute, async (c) => { + const agentId = c.req.param("id"); + if (!agentId) { + return c.json({ success: false, error: "Missing agent id parameter" }, 400); + } + const path = c.req.query("path") || undefined; + const response = await handleListAgentWorkspaceFiles(agentId, { path }, deps, logger); + const status = response.success ? 200 : response.httpStatus || 500; + return c.json(response, status); + }); + + // GET /agents/:id/workspace/read - Read workspace file + app.openapi(workspaceReadFileRoute, async (c) => { + const agentId = c.req.param("id"); + if (!agentId) { + return c.json({ success: false, error: "Missing agent id parameter" }, 400); + } + const path = c.req.query("path") || undefined; + const offset = c.req.query("offset"); + const limit = c.req.query("limit"); + const response = await handleReadAgentWorkspaceFile( + agentId, + { path, offset, limit }, + deps, + logger, + ); + const status = response.success ? 200 : response.httpStatus || 500; + return c.json(response, status); + }); + + // GET /agents/:id/workspace/skills - List workspace skills + app.openapi(workspaceListSkillsRoute, async (c) => { + const agentId = c.req.param("id"); + if (!agentId) { + return c.json({ success: false, error: "Missing agent id parameter" }, 400); + } + const refresh = c.req.query("refresh"); + const response = await handleListAgentWorkspaceSkills(agentId, { refresh }, deps, logger); + const status = response.success ? 200 : response.httpStatus || 500; + return c.json(response, status); + }); + + // GET /agents/:id/workspace/skills/:skillId - Get workspace skill + app.openapi(workspaceGetSkillRoute, async (c) => { + const agentId = c.req.param("id"); + const skillId = c.req.param("skillId"); + if (!agentId) { + return c.json({ success: false, error: "Missing agent id parameter" }, 400); + } + if (!skillId) { + return c.json({ success: false, error: "Missing skillId parameter" }, 400); + } + const response = await handleGetAgentWorkspaceSkill(agentId, skillId, deps, logger); + const status = response.success ? 200 : response.httpStatus || 500; + return c.json(response, status); + }); + // More agent routes can be added here... } diff --git a/packages/serverless-hono/src/routes.ts b/packages/serverless-hono/src/routes.ts index 30b4c49d4..a06ca5f6a 100644 --- a/packages/serverless-hono/src/routes.ts +++ b/packages/serverless-hono/src/routes.ts @@ -49,6 +49,8 @@ import { handleGenerateText, handleGetAgent, handleGetAgentHistory, + handleGetAgentWorkspaceInfo, + handleGetAgentWorkspaceSkill, handleGetAgents, handleGetLogs, handleGetMemoryConversation, @@ -57,10 +59,13 @@ import { handleGetWorkflowState, handleGetWorkflows, handleInstallUpdates, + handleListAgentWorkspaceFiles, + handleListAgentWorkspaceSkills, handleListMemoryConversationMessages, handleListMemoryConversations, handleListTools, handleListWorkflowRuns, + handleReadAgentWorkspaceFile, handleResumeChatStream, handleResumeWorkflow, handleSaveMemoryMessages, @@ -382,6 +387,47 @@ export function registerAgentRoutes(app: Hono, deps: ServerProviderDeps, logger: const response = await handleGetAgentHistory(agentId, page, limit, deps, logger); return c.json(response, response.success ? 200 : 500); }); + + app.get(AGENT_ROUTES.getWorkspace.path, async (c) => { + const agentId = c.req.param("id"); + const response = await handleGetAgentWorkspaceInfo(agentId, deps, logger); + return c.json(response, response.success ? 200 : response.httpStatus || 500); + }); + + app.get(AGENT_ROUTES.listWorkspaceFiles.path, async (c) => { + const agentId = c.req.param("id"); + const path = c.req.query("path") || undefined; + const response = await handleListAgentWorkspaceFiles(agentId, { path }, deps, logger); + return c.json(response, response.success ? 200 : response.httpStatus || 500); + }); + + app.get(AGENT_ROUTES.readWorkspaceFile.path, async (c) => { + const agentId = c.req.param("id"); + const path = c.req.query("path") || undefined; + const offset = c.req.query("offset"); + const limit = c.req.query("limit"); + const response = await handleReadAgentWorkspaceFile( + agentId, + { path, offset, limit }, + deps, + logger, + ); + return c.json(response, response.success ? 200 : response.httpStatus || 500); + }); + + app.get(AGENT_ROUTES.listWorkspaceSkills.path, async (c) => { + const agentId = c.req.param("id"); + const refresh = c.req.query("refresh"); + const response = await handleListAgentWorkspaceSkills(agentId, { refresh }, deps, logger); + return c.json(response, response.success ? 200 : response.httpStatus || 500); + }); + + app.get(AGENT_ROUTES.getWorkspaceSkill.path, async (c) => { + const agentId = c.req.param("id"); + const skillId = c.req.param("skillId"); + const response = await handleGetAgentWorkspaceSkill(agentId, skillId, deps, logger); + return c.json(response, response.success ? 200 : response.httpStatus || 500); + }); } export function registerWorkflowRoutes(app: Hono, deps: ServerProviderDeps, logger: Logger) { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3db54e0d8..f95a34f8b 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -3449,6 +3449,43 @@ importers: specifier: ^5.8.2 version: 5.9.2 + examples/with-workspace: + dependencies: + '@ai-sdk/openai': + specifier: ^3.0.0 + version: 3.0.12(zod@3.25.76) + '@voltagent/cli': + specifier: ^0.1.21 + version: link:../../packages/cli + '@voltagent/core': + specifier: ^2.3.3 + version: link:../../packages/core + '@voltagent/libsql': + specifier: ^2.1.0 + version: link:../../packages/libsql + '@voltagent/logger': + specifier: ^2.0.2 + version: link:../../packages/logger + '@voltagent/server-hono': + specifier: ^2.0.4 + version: link:../../packages/server-hono + ai: + specifier: ^6.0.0 + version: 6.0.3(zod@3.25.76) + zod: + specifier: ^3.25.76 + version: 3.25.76 + devDependencies: + '@types/node': + specifier: ^24.2.1 + version: 24.6.2 + tsx: + specifier: ^4.19.3 + version: 4.20.4 + typescript: + specifier: ^5.8.2 + version: 5.9.3 + examples/with-youtube-to-blog: dependencies: '@voltagent/cli': @@ -4091,6 +4128,44 @@ importers: specifier: ^2.2.10 version: 2.2.10 + packages/sandbox-daytona: + dependencies: + '@daytonaio/sdk': + specifier: ^0.139.0 + version: 0.139.0(ws@8.18.3) + devDependencies: + '@types/node': + specifier: ^24.2.1 + version: 24.6.2 + '@voltagent/core': + specifier: ^2.0.0 + version: link:../core + tsup: + specifier: ^8.5.0 + version: 8.5.0(@swc/core@1.5.29)(typescript@5.9.3) + typescript: + specifier: ^5.8.2 + version: 5.9.3 + + packages/sandbox-e2b: + dependencies: + e2b: + specifier: ^2.12.0 + version: 2.12.0 + devDependencies: + '@types/node': + specifier: ^24.2.1 + version: 24.6.2 + '@voltagent/core': + specifier: ^2.0.0 + version: link:../core + tsup: + specifier: ^8.5.0 + version: 8.5.0(@swc/core@1.5.29)(typescript@5.9.3) + typescript: + specifier: ^5.8.2 + version: 5.9.3 + packages/scorers: dependencies: '@voltagent/core': @@ -5548,6 +5623,52 @@ packages: tslib: 2.8.1 dev: false + /@aws-crypto/crc32c@5.2.0: + resolution: {integrity: sha512-+iWb8qaHLYKrNvGRbiYRHSdKRWhto5XlZUEBwDjYNf+ly5SVYG6zEoYIdxvf5R3zyeP16w4PLBn3rH1xc74Rag==} + dependencies: + '@aws-crypto/util': 5.2.0 + '@aws-sdk/types': 3.973.1 + tslib: 2.8.1 + dev: false + + /@aws-crypto/sha1-browser@5.2.0: + resolution: {integrity: sha512-OH6lveCFfcDjX4dbAvCFSYUjJZjDr/3XJ3xHtjn3Oj5b9RjojQo8npoLeA/bNwkOkrSQ0wgrHzXk4tDRxGKJeg==} + dependencies: + '@aws-crypto/supports-web-crypto': 5.2.0 + '@aws-crypto/util': 5.2.0 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-locate-window': 3.965.4 + '@smithy/util-utf8': 2.3.0 + tslib: 2.8.1 + dev: false + + /@aws-crypto/sha256-browser@5.2.0: + resolution: {integrity: sha512-AXfN/lGotSQwu6HNcEsIASo7kWXZ5HYWvfOmSNKDsEqC4OashTp8alTmaz+F7TC2L083SFv5RdB+qU3Vs1kZqw==} + dependencies: + '@aws-crypto/sha256-js': 5.2.0 + '@aws-crypto/supports-web-crypto': 5.2.0 + '@aws-crypto/util': 5.2.0 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-locate-window': 3.965.4 + '@smithy/util-utf8': 2.3.0 + tslib: 2.8.1 + dev: false + + /@aws-crypto/sha256-js@5.2.0: + resolution: {integrity: sha512-FFQQyu7edu4ufvIZ+OadFpHHOt+eSTBaYaki44c+akjg7qZg9oOQeLlk77F6tSYqjDAFClrHJk9tMf0HdVyOvA==} + engines: {node: '>=16.0.0'} + dependencies: + '@aws-crypto/util': 5.2.0 + '@aws-sdk/types': 3.973.1 + tslib: 2.8.1 + dev: false + + /@aws-crypto/supports-web-crypto@5.2.0: + resolution: {integrity: sha512-iAvUotm021kM33eCdNfwIN//F77/IADDSs58i+MDaOqFrVjZo9bAal0NK7HurRuWLLpF1iLX7gbWrjHjeo+YFg==} + dependencies: + tslib: 2.8.1 + dev: false + /@aws-crypto/util@5.2.0: resolution: {integrity: sha512-4RkU9EsI6ZpBve5fseQlGNUWKMa1RLPQ1dnjnQoe07ldfIzcsGb5hC5W0Dm7u423KWzawlrpbjXBrXCEv9zazQ==} dependencies: @@ -5556,6 +5677,494 @@ packages: tslib: 2.8.1 dev: false + /@aws-sdk/client-s3@3.985.0: + resolution: {integrity: sha512-S9TqjzzZEEIKBnC7yFpvqM7CG9ALpY5qhQ5BnDBJtdG20NoGpjKLGUUfD2wmZItuhbrcM4Z8c6m6Fg0XYIOVvw==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-crypto/sha1-browser': 5.2.0 + '@aws-crypto/sha256-browser': 5.2.0 + '@aws-crypto/sha256-js': 5.2.0 + '@aws-sdk/core': 3.973.7 + '@aws-sdk/credential-provider-node': 3.972.6 + '@aws-sdk/middleware-bucket-endpoint': 3.972.3 + '@aws-sdk/middleware-expect-continue': 3.972.3 + '@aws-sdk/middleware-flexible-checksums': 3.972.5 + '@aws-sdk/middleware-host-header': 3.972.3 + '@aws-sdk/middleware-location-constraint': 3.972.3 + '@aws-sdk/middleware-logger': 3.972.3 + '@aws-sdk/middleware-recursion-detection': 3.972.3 + '@aws-sdk/middleware-sdk-s3': 3.972.7 + '@aws-sdk/middleware-ssec': 3.972.3 + '@aws-sdk/middleware-user-agent': 3.972.7 + '@aws-sdk/region-config-resolver': 3.972.3 + '@aws-sdk/signature-v4-multi-region': 3.985.0 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-endpoints': 3.985.0 + '@aws-sdk/util-user-agent-browser': 3.972.3 + '@aws-sdk/util-user-agent-node': 3.972.5 + '@smithy/config-resolver': 4.4.6 + '@smithy/core': 3.22.1 + '@smithy/eventstream-serde-browser': 4.2.8 + '@smithy/eventstream-serde-config-resolver': 4.3.8 + '@smithy/eventstream-serde-node': 4.2.8 + '@smithy/fetch-http-handler': 5.3.9 + '@smithy/hash-blob-browser': 4.2.9 + '@smithy/hash-node': 4.2.8 + '@smithy/hash-stream-node': 4.2.8 + '@smithy/invalid-dependency': 4.2.8 + '@smithy/md5-js': 4.2.8 + '@smithy/middleware-content-length': 4.2.8 + '@smithy/middleware-endpoint': 4.4.13 + '@smithy/middleware-retry': 4.4.30 + '@smithy/middleware-serde': 4.2.9 + '@smithy/middleware-stack': 4.2.8 + '@smithy/node-config-provider': 4.3.8 + '@smithy/node-http-handler': 4.4.9 + '@smithy/protocol-http': 5.3.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/url-parser': 4.2.8 + '@smithy/util-base64': 4.3.0 + '@smithy/util-body-length-browser': 4.2.0 + '@smithy/util-body-length-node': 4.2.1 + '@smithy/util-defaults-mode-browser': 4.3.29 + '@smithy/util-defaults-mode-node': 4.2.32 + '@smithy/util-endpoints': 3.2.8 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-retry': 4.2.8 + '@smithy/util-stream': 4.5.11 + '@smithy/util-utf8': 4.2.0 + '@smithy/util-waiter': 4.2.8 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/client-sso@3.985.0: + resolution: {integrity: sha512-81J8iE8MuXhdbMfIz4sWFj64Pe41bFi/uqqmqOC5SlGv+kwoyLsyKS/rH2tW2t5buih4vTUxskRjxlqikTD4oQ==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-crypto/sha256-browser': 5.2.0 + '@aws-crypto/sha256-js': 5.2.0 + '@aws-sdk/core': 3.973.7 + '@aws-sdk/middleware-host-header': 3.972.3 + '@aws-sdk/middleware-logger': 3.972.3 + '@aws-sdk/middleware-recursion-detection': 3.972.3 + '@aws-sdk/middleware-user-agent': 3.972.7 + '@aws-sdk/region-config-resolver': 3.972.3 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-endpoints': 3.985.0 + '@aws-sdk/util-user-agent-browser': 3.972.3 + '@aws-sdk/util-user-agent-node': 3.972.5 + '@smithy/config-resolver': 4.4.6 + '@smithy/core': 3.22.1 + '@smithy/fetch-http-handler': 5.3.9 + '@smithy/hash-node': 4.2.8 + '@smithy/invalid-dependency': 4.2.8 + '@smithy/middleware-content-length': 4.2.8 + '@smithy/middleware-endpoint': 4.4.13 + '@smithy/middleware-retry': 4.4.30 + '@smithy/middleware-serde': 4.2.9 + '@smithy/middleware-stack': 4.2.8 + '@smithy/node-config-provider': 4.3.8 + '@smithy/node-http-handler': 4.4.9 + '@smithy/protocol-http': 5.3.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/url-parser': 4.2.8 + '@smithy/util-base64': 4.3.0 + '@smithy/util-body-length-browser': 4.2.0 + '@smithy/util-body-length-node': 4.2.1 + '@smithy/util-defaults-mode-browser': 4.3.29 + '@smithy/util-defaults-mode-node': 4.2.32 + '@smithy/util-endpoints': 3.2.8 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-retry': 4.2.8 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/core@3.973.7: + resolution: {integrity: sha512-wNZZQQNlJ+hzD49cKdo+PY6rsTDElO8yDImnrI69p2PLBa7QomeUKAJWYp9xnaR38nlHqWhMHZuYLCQ3oSX+xg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@aws-sdk/xml-builder': 3.972.4 + '@smithy/core': 3.22.1 + '@smithy/node-config-provider': 4.3.8 + '@smithy/property-provider': 4.2.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/signature-v4': 5.3.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/util-base64': 4.3.0 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/crc64-nvme@3.972.0: + resolution: {integrity: sha512-ThlLhTqX68jvoIVv+pryOdb5coP1cX1/MaTbB9xkGDCbWbsqQcLqzPxuSoW1DCnAAIacmXCWpzUNOB9pv+xXQw==} + engines: {node: '>=20.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/credential-provider-env@3.972.5: + resolution: {integrity: sha512-LxJ9PEO4gKPXzkufvIESUysykPIdrV7+Ocb9yAhbhJLE4TiAYqbCVUE+VuKP1leGR1bBfjWjYgSV5MxprlX3mQ==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/types': 3.973.1 + '@smithy/property-provider': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/credential-provider-http@3.972.7: + resolution: {integrity: sha512-L2uOGtvp2x3bTcxFTpSM+GkwFIPd8pHfGWO1764icMbo7e5xJh0nfhx1UwkXLnwvocTNEf8A7jISZLYjUSNaTg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/types': 3.973.1 + '@smithy/fetch-http-handler': 5.3.9 + '@smithy/node-http-handler': 4.4.9 + '@smithy/property-provider': 4.2.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/util-stream': 4.5.11 + tslib: 2.8.1 + dev: false + + /@aws-sdk/credential-provider-ini@3.972.5: + resolution: {integrity: sha512-SdDTYE6jkARzOeL7+kudMIM4DaFnP5dZVeatzw849k4bSXDdErDS188bgeNzc/RA2WGrlEpsqHUKP6G7sVXhZg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/credential-provider-env': 3.972.5 + '@aws-sdk/credential-provider-http': 3.972.7 + '@aws-sdk/credential-provider-login': 3.972.5 + '@aws-sdk/credential-provider-process': 3.972.5 + '@aws-sdk/credential-provider-sso': 3.972.5 + '@aws-sdk/credential-provider-web-identity': 3.972.5 + '@aws-sdk/nested-clients': 3.985.0 + '@aws-sdk/types': 3.973.1 + '@smithy/credential-provider-imds': 4.2.8 + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/credential-provider-login@3.972.5: + resolution: {integrity: sha512-uYq1ILyTSI6ZDCMY5+vUsRM0SOCVI7kaW4wBrehVVkhAxC6y+e9rvGtnoZqCOWL1gKjTMouvsf4Ilhc5NCg1Aw==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/nested-clients': 3.985.0 + '@aws-sdk/types': 3.973.1 + '@smithy/property-provider': 4.2.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/credential-provider-node@3.972.6: + resolution: {integrity: sha512-DZ3CnAAtSVtVz+G+ogqecaErMLgzph4JH5nYbHoBMgBkwTUV+SUcjsjOJwdBJTHu3Dm6l5LBYekZoU2nDqQk2A==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/credential-provider-env': 3.972.5 + '@aws-sdk/credential-provider-http': 3.972.7 + '@aws-sdk/credential-provider-ini': 3.972.5 + '@aws-sdk/credential-provider-process': 3.972.5 + '@aws-sdk/credential-provider-sso': 3.972.5 + '@aws-sdk/credential-provider-web-identity': 3.972.5 + '@aws-sdk/types': 3.973.1 + '@smithy/credential-provider-imds': 4.2.8 + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/credential-provider-process@3.972.5: + resolution: {integrity: sha512-HDKF3mVbLnuqGg6dMnzBf1VUOywE12/N286msI9YaK9mEIzdsGCtLTvrDhe3Up0R9/hGFbB+9l21/TwF5L1C6g==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/types': 3.973.1 + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/credential-provider-sso@3.972.5: + resolution: {integrity: sha512-8urj3AoeNeQisjMmMBhFeiY2gxt6/7wQQbEGun0YV/OaOOiXrIudTIEYF8ZfD+NQI6X1FY5AkRsx6O/CaGiybA==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/client-sso': 3.985.0 + '@aws-sdk/core': 3.973.7 + '@aws-sdk/token-providers': 3.985.0 + '@aws-sdk/types': 3.973.1 + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/credential-provider-web-identity@3.972.5: + resolution: {integrity: sha512-OK3cULuJl6c+RcDZfPpaK5o3deTOnKZbxm7pzhFNGA3fI2hF9yDih17fGRazJzGGWaDVlR9ejZrpDef4DJCEsw==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/nested-clients': 3.985.0 + '@aws-sdk/types': 3.973.1 + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/lib-storage@3.985.0(@aws-sdk/client-s3@3.985.0): + resolution: {integrity: sha512-EnqXf2E+5+7e5zuz8mPl+3Dk/DI0ObSL8s7Tsf6H8FL/p2BJw2LhgtxPnFZUmpanpoMO0hC9/qjXNd+aGPV0/w==} + engines: {node: '>=20.0.0'} + peerDependencies: + '@aws-sdk/client-s3': ^3.985.0 + dependencies: + '@aws-sdk/client-s3': 3.985.0 + '@smithy/abort-controller': 4.2.8 + '@smithy/middleware-endpoint': 4.4.13 + '@smithy/smithy-client': 4.11.2 + buffer: 5.6.0 + events: 3.3.0 + stream-browserify: 3.0.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-bucket-endpoint@3.972.3: + resolution: {integrity: sha512-fmbgWYirF67YF1GfD7cg5N6HHQ96EyRNx/rDIrTF277/zTWVuPI2qS/ZHgofwR1NZPe/NWvoppflQY01LrbVLg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-arn-parser': 3.972.2 + '@smithy/node-config-provider': 4.3.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + '@smithy/util-config-provider': 4.2.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-expect-continue@3.972.3: + resolution: {integrity: sha512-4msC33RZsXQpUKR5QR4HnvBSNCPLGHmB55oDiROqqgyOc+TOfVu2xgi5goA7ms6MdZLeEh2905UfWMnMMF4mRg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-flexible-checksums@3.972.5: + resolution: {integrity: sha512-SF/1MYWx67OyCrLA4icIpWUfCkdlOi8Y1KecQ9xYxkL10GMjVdPTGPnYhAg0dw5U43Y9PVUWhAV2ezOaG+0BLg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-crypto/crc32': 5.2.0 + '@aws-crypto/crc32c': 5.2.0 + '@aws-crypto/util': 5.2.0 + '@aws-sdk/core': 3.973.7 + '@aws-sdk/crc64-nvme': 3.972.0 + '@aws-sdk/types': 3.973.1 + '@smithy/is-array-buffer': 4.2.0 + '@smithy/node-config-provider': 4.3.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-stream': 4.5.11 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-host-header@3.972.3: + resolution: {integrity: sha512-aknPTb2M+G3s+0qLCx4Li/qGZH8IIYjugHMv15JTYMe6mgZO8VBpYgeGYsNMGCqCZOcWzuf900jFBG5bopfzmA==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-location-constraint@3.972.3: + resolution: {integrity: sha512-nIg64CVrsXp67vbK0U1/Is8rik3huS3QkRHn2DRDx4NldrEFMgdkZGI/+cZMKD9k4YOS110Dfu21KZLHrFA/1g==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-logger@3.972.3: + resolution: {integrity: sha512-Ftg09xNNRqaz9QNzlfdQWfpqMCJbsQdnZVJP55jfhbKi1+FTWxGuvfPoBhDHIovqWKjqbuiew3HuhxbJ0+OjgA==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-recursion-detection@3.972.3: + resolution: {integrity: sha512-PY57QhzNuXHnwbJgbWYTrqIDHYSeOlhfYERTAuc16LKZpTZRJUjzBFokp9hF7u1fuGeE3D70ERXzdbMBOqQz7Q==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@aws/lambda-invoke-store': 0.2.3 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-sdk-s3@3.972.7: + resolution: {integrity: sha512-VtZ7tMIw18VzjG+I6D6rh2eLkJfTtByiFoCIauGDtTTPBEUMQUiGaJ/zZrPlCY6BsvLLeFKz3+E5mntgiOWmIg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-arn-parser': 3.972.2 + '@smithy/core': 3.22.1 + '@smithy/node-config-provider': 4.3.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/signature-v4': 5.3.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/util-config-provider': 4.2.0 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-stream': 4.5.11 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-ssec@3.972.3: + resolution: {integrity: sha512-dU6kDuULN3o3jEHcjm0c4zWJlY1zWVkjG9NPe9qxYLLpcbdj5kRYBS2DdWYD+1B9f910DezRuws7xDEqKkHQIg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/middleware-user-agent@3.972.7: + resolution: {integrity: sha512-HUD+geASjXSCyL/DHPQc/Ua7JhldTcIglVAoCV8kiVm99IaFSlAbTvEnyhZwdE6bdFyTL+uIaWLaCFSRsglZBQ==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-endpoints': 3.985.0 + '@smithy/core': 3.22.1 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/nested-clients@3.985.0: + resolution: {integrity: sha512-TsWwKzb/2WHafAY0CE7uXgLj0FmnkBTgfioG9HO+7z/zCPcl1+YU+i7dW4o0y+aFxFgxTMG+ExBQpqT/k2ao8g==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-crypto/sha256-browser': 5.2.0 + '@aws-crypto/sha256-js': 5.2.0 + '@aws-sdk/core': 3.973.7 + '@aws-sdk/middleware-host-header': 3.972.3 + '@aws-sdk/middleware-logger': 3.972.3 + '@aws-sdk/middleware-recursion-detection': 3.972.3 + '@aws-sdk/middleware-user-agent': 3.972.7 + '@aws-sdk/region-config-resolver': 3.972.3 + '@aws-sdk/types': 3.973.1 + '@aws-sdk/util-endpoints': 3.985.0 + '@aws-sdk/util-user-agent-browser': 3.972.3 + '@aws-sdk/util-user-agent-node': 3.972.5 + '@smithy/config-resolver': 4.4.6 + '@smithy/core': 3.22.1 + '@smithy/fetch-http-handler': 5.3.9 + '@smithy/hash-node': 4.2.8 + '@smithy/invalid-dependency': 4.2.8 + '@smithy/middleware-content-length': 4.2.8 + '@smithy/middleware-endpoint': 4.4.13 + '@smithy/middleware-retry': 4.4.30 + '@smithy/middleware-serde': 4.2.9 + '@smithy/middleware-stack': 4.2.8 + '@smithy/node-config-provider': 4.3.8 + '@smithy/node-http-handler': 4.4.9 + '@smithy/protocol-http': 5.3.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/url-parser': 4.2.8 + '@smithy/util-base64': 4.3.0 + '@smithy/util-body-length-browser': 4.2.0 + '@smithy/util-body-length-node': 4.2.1 + '@smithy/util-defaults-mode-browser': 4.3.29 + '@smithy/util-defaults-mode-node': 4.2.32 + '@smithy/util-endpoints': 3.2.8 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-retry': 4.2.8 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + + /@aws-sdk/region-config-resolver@3.972.3: + resolution: {integrity: sha512-v4J8qYAWfOMcZ4MJUyatntOicTzEMaU7j3OpkRCGGFSL2NgXQ5VbxauIyORA+pxdKZ0qQG2tCQjQjZDlXEC3Ow==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/config-resolver': 4.4.6 + '@smithy/node-config-provider': 4.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/signature-v4-multi-region@3.985.0: + resolution: {integrity: sha512-W6hTSOPiSbh4IdTYVxN7xHjpCh0qvfQU1GKGBzGQm0ZEIOaMmWqiDEvFfyGYKmfBvumT8vHKxQRTX0av9omtIg==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/middleware-sdk-s3': 3.972.7 + '@aws-sdk/types': 3.973.1 + '@smithy/protocol-http': 5.3.8 + '@smithy/signature-v4': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/token-providers@3.985.0: + resolution: {integrity: sha512-+hwpHZyEq8k+9JL2PkE60V93v2kNhUIv7STFt+EAez1UJsJOQDhc5LpzEX66pNjclI5OTwBROs/DhJjC/BtMjQ==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/core': 3.973.7 + '@aws-sdk/nested-clients': 3.985.0 + '@aws-sdk/types': 3.973.1 + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + transitivePeerDependencies: + - aws-crt + dev: false + /@aws-sdk/types@3.862.0: resolution: {integrity: sha512-Bei+RL0cDxxV+lW2UezLbCYYNeJm6Nzee0TpW0FfyTRBhH9C1XQh4+x+IClriXvgBnRquTMMYsmJfvx8iyLKrg==} engines: {node: '>=18.0.0'} @@ -5564,6 +6173,78 @@ packages: tslib: 2.8.1 dev: false + /@aws-sdk/types@3.973.1: + resolution: {integrity: sha512-DwHBiMNOB468JiX6+i34c+THsKHErYUdNQ3HexeXZvVn4zouLjgaS4FejiGSi2HyBuzuyHg7SuOPmjSvoU9NRg==} + engines: {node: '>=20.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/util-arn-parser@3.972.2: + resolution: {integrity: sha512-VkykWbqMjlSgBFDyrY3nOSqupMc6ivXuGmvci6Q3NnLq5kC+mKQe2QBZ4nrWRE/jqOxeFP2uYzLtwncYYcvQDg==} + engines: {node: '>=20.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@aws-sdk/util-endpoints@3.985.0: + resolution: {integrity: sha512-vth7UfGSUR3ljvaq8V4Rc62FsM7GUTH/myxPWkaEgOrprz1/Pc72EgTXxj+cPPPDAfHFIpjhkB7T7Td0RJx+BA==} + engines: {node: '>=20.0.0'} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/types': 4.12.0 + '@smithy/url-parser': 4.2.8 + '@smithy/util-endpoints': 3.2.8 + tslib: 2.8.1 + dev: false + + /@aws-sdk/util-locate-window@3.965.4: + resolution: {integrity: sha512-H1onv5SkgPBK2P6JR2MjGgbOnttoNzSPIRoeZTNPZYyaplwGg50zS3amXvXqF0/qfXpWEC9rLWU564QTB9bSog==} + engines: {node: '>=20.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@aws-sdk/util-user-agent-browser@3.972.3: + resolution: {integrity: sha512-JurOwkRUcXD/5MTDBcqdyQ9eVedtAsZgw5rBwktsPTN7QtPiS2Ld1jkJepNgYoCufz1Wcut9iup7GJDoIHp8Fw==} + dependencies: + '@aws-sdk/types': 3.973.1 + '@smithy/types': 4.12.0 + bowser: 2.13.1 + tslib: 2.8.1 + dev: false + + /@aws-sdk/util-user-agent-node@3.972.5: + resolution: {integrity: sha512-GsUDF+rXyxDZkkJxUsDxnA67FG+kc5W1dnloCFLl6fWzceevsCYzJpASBzT+BPjwUgREE6FngfJYYYMQUY5fZQ==} + engines: {node: '>=20.0.0'} + peerDependencies: + aws-crt: '>=1.0.0' + peerDependenciesMeta: + aws-crt: + optional: true + dependencies: + '@aws-sdk/middleware-user-agent': 3.972.7 + '@aws-sdk/types': 3.973.1 + '@smithy/node-config-provider': 4.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@aws-sdk/xml-builder@3.972.4: + resolution: {integrity: sha512-0zJ05ANfYqI6+rGqj8samZBFod0dPPousBjLEqg8WdxSgbMAkRgLyn81lP215Do0rFJ/17LIXwr7q0yK24mP6Q==} + engines: {node: '>=20.0.0'} + dependencies: + '@smithy/types': 4.12.0 + fast-xml-parser: 5.3.4 + tslib: 2.8.1 + dev: false + + /@aws/lambda-invoke-store@0.2.3: + resolution: {integrity: sha512-oLvsaPMTBejkkmHhjf09xTgk71mOqyr/409NKhRIL08If7AhVfUsJhVsx386uJaqNd42v9kWamQ9lFbkoC2dYw==} + engines: {node: '>=18.0.0'} + dev: false + /@babel/code-frame@7.26.2: resolution: {integrity: sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==} engines: {node: '>=6.9.0'} @@ -8010,6 +8691,24 @@ packages: hasBin: true dev: false + /@connectrpc/connect-web@2.0.0-rc.3(@bufbuild/protobuf@2.10.1)(@connectrpc/connect@2.0.0-rc.3): + resolution: {integrity: sha512-w88P8Lsn5CCsA7MFRl2e6oLY4J/5toiNtJns/YJrlyQaWOy3RO8pDgkz+iIkG98RPMhj2thuBvsd3Cn4DKKCkw==} + peerDependencies: + '@bufbuild/protobuf': ^2.2.0 + '@connectrpc/connect': 2.0.0-rc.3 + dependencies: + '@bufbuild/protobuf': 2.10.1 + '@connectrpc/connect': 2.0.0-rc.3(@bufbuild/protobuf@2.10.1) + dev: false + + /@connectrpc/connect@2.0.0-rc.3(@bufbuild/protobuf@2.10.1): + resolution: {integrity: sha512-ARBt64yEyKbanyRETTjcjJuHr2YXorzQo0etyS5+P6oSeW8xEuzajA9g+zDnMcj1hlX2dQE93foIWQGfpru7gQ==} + peerDependencies: + '@bufbuild/protobuf': ^2.2.0 + dependencies: + '@bufbuild/protobuf': 2.10.1 + dev: false + /@copilotkit/react-core@1.50.0(@types/react-dom@19.2.3)(@types/react@19.2.7)(react-dom@19.2.3)(react@19.2.3)(zod@4.3.5): resolution: {integrity: sha512-JfUEvmgXgPz7wIQq9EFXWGDMtYLIVKSNqPdJROEomZXLhREDlxpg+jr5KHvoOPUlSnVLzuPObRKSdeJTwVOGsQ==} peerDependencies: @@ -8276,6 +8975,46 @@ packages: kuler: 2.0.0 dev: false + /@daytonaio/api-client@0.139.0: + resolution: {integrity: sha512-Xmjrkq7MW/DaZLQEf0HfT7Y38N8SesXvWqAKSEjdf3ifGVQVx37aOB8El1jOvfrndqzTcSbumSxro2nhKK5K5A==} + dependencies: + axios: 1.13.2 + transitivePeerDependencies: + - debug + dev: false + + /@daytonaio/sdk@0.139.0(ws@8.18.3): + resolution: {integrity: sha512-67NSkhnl9NiUgBfheN5AtkH0/T5U+WTZmGlY2k+ujAAl/ntpyA/T/q+Pznk44oCJyM1O39OEWt/ugmAEyqRWLg==} + dependencies: + '@aws-sdk/client-s3': 3.985.0 + '@aws-sdk/lib-storage': 3.985.0(@aws-sdk/client-s3@3.985.0) + '@daytonaio/api-client': 0.139.0 + '@daytonaio/toolbox-api-client': 0.139.0 + '@iarna/toml': 2.2.5 + axios: 1.13.2 + busboy: 1.6.0 + dotenv: 17.2.2 + expand-tilde: 2.0.2 + fast-glob: 3.3.3 + form-data: 4.0.4 + isomorphic-ws: 5.0.0(ws@8.18.3) + pathe: 2.0.3 + shell-quote: 1.8.3 + tar: 7.5.7 + transitivePeerDependencies: + - aws-crt + - debug + - ws + dev: false + + /@daytonaio/toolbox-api-client@0.139.0: + resolution: {integrity: sha512-zLonkWHsdmrwT2qCZ/zBt4dpWNJ7N08eGYjCk30Bihzk4JY0afNBPDqd+pdGdXKtuJ44yCxR4iJyjfWR11J9PA==} + dependencies: + axios: 1.13.2 + transitivePeerDependencies: + - debug + dev: false + /@dependents/detective-less@5.0.1: resolution: {integrity: sha512-Y6+WUMsTFWE5jb20IFP4YGa5IrGY/+a/FbOSjDF/wz9gepU2hwCYSXRHP/vPwBvwcY3SVMASt4yXxbXNXigmZQ==} engines: {node: '>=18'} @@ -9302,7 +10041,6 @@ packages: /@iarna/toml@2.2.5: resolution: {integrity: sha512-trnsAYxU3xnS1gPHPyU961coFyLkh4gAD/0zQ5mymY4yOZ+CYvsPqUbOFSw0aDM4y0tV7tiFxL/1XfXPNC6IPg==} - dev: true /@iconify-json/mdi@1.2.3: resolution: {integrity: sha512-O3cLwbDOK7NNDf2ihaQOH5F9JglnulNDFV7WprU2dSoZu3h3cWH//h74uQAB87brHmvFVxIOkuBX2sZSzYhScg==} @@ -10188,6 +10926,13 @@ packages: dependencies: '@isaacs/balanced-match': 4.0.1 + /@isaacs/brace-expansion@5.0.1: + resolution: {integrity: sha512-WMz71T1JS624nWj2n2fnYAuPovhv7EUhk69R6i9dsVyzxt5eM3bjwvgk9L+APE1TRscGysAVMANkB0jh0LQZrQ==} + engines: {node: 20 || >=22} + dependencies: + '@isaacs/balanced-match': 4.0.1 + dev: false + /@isaacs/cliui@8.0.2: resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==} engines: {node: '>=12'} @@ -11613,7 +12358,7 @@ packages: parse-imports: 2.2.1 path-key: 4.0.0 semver: 7.7.2 - tar: 7.4.3 + tar: 7.5.1 tmp-promise: 3.0.3 urlpattern-polyfill: 8.0.2 uuid: 11.1.0 @@ -17075,6 +17820,68 @@ packages: '@sinonjs/commons': 3.0.1 dev: true + /@smithy/abort-controller@4.2.8: + resolution: {integrity: sha512-peuVfkYHAmS5ybKxWcfraK7WBBP0J+rkfUcbHJJKQ4ir3UAUNQI+Y4Vt/PqSzGqgloJ5O1dk7+WzNL8wcCSXbw==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/chunked-blob-reader-native@4.2.1: + resolution: {integrity: sha512-lX9Ay+6LisTfpLid2zZtIhSEjHMZoAR5hHCR4H7tBz/Zkfr5ea8RcQ7Tk4mi0P76p4cN+Btz16Ffno7YHpKXnQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/util-base64': 4.3.0 + tslib: 2.8.1 + dev: false + + /@smithy/chunked-blob-reader@5.2.0: + resolution: {integrity: sha512-WmU0TnhEAJLWvfSeMxBNe5xtbselEO8+4wG0NtZeL8oR21WgH1xiO37El+/Y+H/Ie4SCwBy3MxYWmOYaGgZueA==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@smithy/config-resolver@4.4.6: + resolution: {integrity: sha512-qJpzYC64kaj3S0fueiu3kXm8xPrR3PcXDPEgnaNMRn0EjNSZFoFjvbUp0YUDsRhN1CB90EnHJtbxWKevnH99UQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/node-config-provider': 4.3.8 + '@smithy/types': 4.12.0 + '@smithy/util-config-provider': 4.2.0 + '@smithy/util-endpoints': 3.2.8 + '@smithy/util-middleware': 4.2.8 + tslib: 2.8.1 + dev: false + + /@smithy/core@3.22.1: + resolution: {integrity: sha512-x3ie6Crr58MWrm4viHqqy2Du2rHYZjwu8BekasrQx4ca+Y24dzVAwq3yErdqIbc2G3I0kLQA13PQ+/rde+u65g==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/middleware-serde': 4.2.9 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + '@smithy/util-base64': 4.3.0 + '@smithy/util-body-length-browser': 4.2.0 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-stream': 4.5.11 + '@smithy/util-utf8': 4.2.0 + '@smithy/uuid': 1.1.0 + tslib: 2.8.1 + dev: false + + /@smithy/credential-provider-imds@4.2.8: + resolution: {integrity: sha512-FNT0xHS1c/CPN8upqbMFP83+ul5YgdisfCfkZ86Jh2NSmnqw/AJ6x5pEogVCTVvSm7j9MopRU89bmDelxuDMYw==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/node-config-provider': 4.3.8 + '@smithy/property-provider': 4.2.8 + '@smithy/types': 4.12.0 + '@smithy/url-parser': 4.2.8 + tslib: 2.8.1 + dev: false + /@smithy/eventstream-codec@4.0.5: resolution: {integrity: sha512-miEUN+nz2UTNoRYRhRqVTJCx7jMeILdAurStT2XoS+mhokkmz1xAPp95DFW9Gxt4iF2VBqpeF9HbTQ3kY1viOA==} engines: {node: '>=18.0.0'} @@ -17085,6 +17892,99 @@ packages: tslib: 2.8.1 dev: false + /@smithy/eventstream-codec@4.2.8: + resolution: {integrity: sha512-jS/O5Q14UsufqoGhov7dHLOPCzkYJl9QDzusI2Psh4wyYx/izhzvX9P4D69aTxcdfVhEPhjK+wYyn/PzLjKbbw==} + engines: {node: '>=18.0.0'} + dependencies: + '@aws-crypto/crc32': 5.2.0 + '@smithy/types': 4.12.0 + '@smithy/util-hex-encoding': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/eventstream-serde-browser@4.2.8: + resolution: {integrity: sha512-MTfQT/CRQz5g24ayXdjg53V0mhucZth4PESoA5IhvaWVDTOQLfo8qI9vzqHcPsdd2v6sqfTYqF5L/l+pea5Uyw==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/eventstream-serde-universal': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/eventstream-serde-config-resolver@4.3.8: + resolution: {integrity: sha512-ah12+luBiDGzBruhu3efNy1IlbwSEdNiw8fOZksoKoWW1ZHvO/04MQsdnws/9Aj+5b0YXSSN2JXKy/ClIsW8MQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/eventstream-serde-node@4.2.8: + resolution: {integrity: sha512-cYpCpp29z6EJHa5T9WL0KAlq3SOKUQkcgSoeRfRVwjGgSFl7Uh32eYGt7IDYCX20skiEdRffyDpvF2efEZPC0A==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/eventstream-serde-universal': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/eventstream-serde-universal@4.2.8: + resolution: {integrity: sha512-iJ6YNJd0bntJYnX6s52NC4WFYcZeKrPUr1Kmmr5AwZcwCSzVpS7oavAmxMR7pMq7V+D1G4s9F5NJK0xwOsKAlQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/eventstream-codec': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/fetch-http-handler@5.3.9: + resolution: {integrity: sha512-I4UhmcTYXBrct03rwzQX1Y/iqQlzVQaPxWjCjula++5EmWq9YGBrx6bbGqluGc1f0XEfhSkiY4jhLgbsJUMKRA==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/protocol-http': 5.3.8 + '@smithy/querystring-builder': 4.2.8 + '@smithy/types': 4.12.0 + '@smithy/util-base64': 4.3.0 + tslib: 2.8.1 + dev: false + + /@smithy/hash-blob-browser@4.2.9: + resolution: {integrity: sha512-m80d/iicI7DlBDxyQP6Th7BW/ejDGiF0bgI754+tiwK0lgMkcaIBgvwwVc7OFbY4eUzpGtnig52MhPAEJ7iNYg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/chunked-blob-reader': 5.2.0 + '@smithy/chunked-blob-reader-native': 4.2.1 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/hash-node@4.2.8: + resolution: {integrity: sha512-7ZIlPbmaDGxVoxErDZnuFG18WekhbA/g2/i97wGj+wUBeS6pcUeAym8u4BXh/75RXWhgIJhyC11hBzig6MljwA==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + '@smithy/util-buffer-from': 4.2.0 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/hash-stream-node@4.2.8: + resolution: {integrity: sha512-v0FLTXgHrTeheYZFGhR+ehX5qUm4IQsjAiL9qehad2cyjMWcN2QG6/4mSwbSgEQzI7jwfoXj7z4fxZUx/Mhj2w==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/invalid-dependency@4.2.8: + resolution: {integrity: sha512-N9iozRybwAQ2dn9Fot9kI6/w9vos2oTXLhtK7ovGqwZjlOcxu6XhPlpLpC+INsxktqHinn5gS2DXDjDF2kG5sQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + /@smithy/is-array-buffer@2.2.0: resolution: {integrity: sha512-GGP3O9QFD24uGeAXYUjwSTXARoqpZykHadOmA8G5vfJPK0/DC67qa//0qvqrJzL1xc8WQWX7/yc7fwudjPHPhA==} engines: {node: '>=14.0.0'} @@ -17099,6 +17999,180 @@ packages: tslib: 2.8.1 dev: false + /@smithy/is-array-buffer@4.2.0: + resolution: {integrity: sha512-DZZZBvC7sjcYh4MazJSGiWMI2L7E0oCiRHREDzIxi/M2LY79/21iXt6aPLHge82wi5LsuRF5A06Ds3+0mlh6CQ==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@smithy/md5-js@4.2.8: + resolution: {integrity: sha512-oGMaLj4tVZzLi3itBa9TCswgMBr7k9b+qKYowQ6x1rTyTuO1IU2YHdHUa+891OsOH+wCsH7aTPRsTJO3RMQmjQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/middleware-content-length@4.2.8: + resolution: {integrity: sha512-RO0jeoaYAB1qBRhfVyq0pMgBoUK34YEJxVxyjOWYZiOKOq2yMZ4MnVXMZCUDenpozHue207+9P5ilTV1zeda0A==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/middleware-endpoint@4.4.13: + resolution: {integrity: sha512-x6vn0PjYmGdNuKh/juUJJewZh7MoQ46jYaJ2mvekF4EesMuFfrl4LaW/k97Zjf8PTCPQmPgMvwewg7eNoH9n5w==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/core': 3.22.1 + '@smithy/middleware-serde': 4.2.9 + '@smithy/node-config-provider': 4.3.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + '@smithy/url-parser': 4.2.8 + '@smithy/util-middleware': 4.2.8 + tslib: 2.8.1 + dev: false + + /@smithy/middleware-retry@4.4.30: + resolution: {integrity: sha512-CBGyFvN0f8hlnqKH/jckRDz78Snrp345+PVk8Ux7pnkUCW97Iinse59lY78hBt04h1GZ6hjBN94BRwZy1xC8Bg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/node-config-provider': 4.3.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/service-error-classification': 4.2.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-retry': 4.2.8 + '@smithy/uuid': 1.1.0 + tslib: 2.8.1 + dev: false + + /@smithy/middleware-serde@4.2.9: + resolution: {integrity: sha512-eMNiej0u/snzDvlqRGSN3Vl0ESn3838+nKyVfF2FKNXFbi4SERYT6PR392D39iczngbqqGG0Jl1DlCnp7tBbXQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/middleware-stack@4.2.8: + resolution: {integrity: sha512-w6LCfOviTYQjBctOKSwy6A8FIkQy7ICvglrZFl6Bw4FmcQ1Z420fUtIhxaUZZshRe0VCq4kvDiPiXrPZAe8oRA==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/node-config-provider@4.3.8: + resolution: {integrity: sha512-aFP1ai4lrbVlWjfpAfRSL8KFcnJQYfTl5QxLJXY32vghJrDuFyPZ6LtUL+JEGYiFRG1PfPLHLoxj107ulncLIg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/property-provider': 4.2.8 + '@smithy/shared-ini-file-loader': 4.4.3 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/node-http-handler@4.4.9: + resolution: {integrity: sha512-KX5Wml5mF+luxm1szW4QDz32e3NObgJ4Fyw+irhph4I/2geXwUy4jkIMUs5ZPGflRBeR6BUkC2wqIab4Llgm3w==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/abort-controller': 4.2.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/querystring-builder': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/property-provider@4.2.8: + resolution: {integrity: sha512-EtCTbyIveCKeOXDSWSdze3k612yCPq1YbXsbqX3UHhkOSW8zKsM9NOJG5gTIya0vbY2DIaieG8pKo1rITHYL0w==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/protocol-http@5.3.8: + resolution: {integrity: sha512-QNINVDhxpZ5QnP3aviNHQFlRogQZDfYlCkQT+7tJnErPQbDhysondEjhikuANxgMsZrkGeiAxXy4jguEGsDrWQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/querystring-builder@4.2.8: + resolution: {integrity: sha512-Xr83r31+DrE8CP3MqPgMJl+pQlLLmOfiEUnoyAlGzzJIrEsbKsPy1hqH0qySaQm4oWrCBlUqRt+idEgunKB+iw==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + '@smithy/util-uri-escape': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/querystring-parser@4.2.8: + resolution: {integrity: sha512-vUurovluVy50CUlazOiXkPq40KGvGWSdmusa3130MwrR1UNnNgKAlj58wlOe61XSHRpUfIIh6cE0zZ8mzKaDPA==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/service-error-classification@4.2.8: + resolution: {integrity: sha512-mZ5xddodpJhEt3RkCjbmUQuXUOaPNTkbMGR0bcS8FE0bJDLMZlhmpgrvPNCYglVw5rsYTpSnv19womw9WWXKQQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + dev: false + + /@smithy/shared-ini-file-loader@4.4.3: + resolution: {integrity: sha512-DfQjxXQnzC5UbCUPeC3Ie8u+rIWZTvuDPAGU/BxzrOGhRvgUanaP68kDZA+jaT3ZI+djOf+4dERGlm9mWfFDrg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/signature-v4@5.3.8: + resolution: {integrity: sha512-6A4vdGj7qKNRF16UIcO8HhHjKW27thsxYci+5r/uVRkdcBEkOEiY8OMPuydLX4QHSrJqGHPJzPRwwVTqbLZJhg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/is-array-buffer': 4.2.0 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + '@smithy/util-hex-encoding': 4.2.0 + '@smithy/util-middleware': 4.2.8 + '@smithy/util-uri-escape': 4.2.0 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/smithy-client@4.11.2: + resolution: {integrity: sha512-SCkGmFak/xC1n7hKRsUr6wOnBTJ3L22Qd4e8H1fQIuKTAjntwgU8lrdMe7uHdiT2mJAOWA/60qaW9tiMu69n1A==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/core': 3.22.1 + '@smithy/middleware-endpoint': 4.4.13 + '@smithy/middleware-stack': 4.2.8 + '@smithy/protocol-http': 5.3.8 + '@smithy/types': 4.12.0 + '@smithy/util-stream': 4.5.11 + tslib: 2.8.1 + dev: false + + /@smithy/types@4.12.0: + resolution: {integrity: sha512-9YcuJVTOBDjg9LWo23Qp0lTQ3D7fQsQtwle0jVfpbUHy9qBwCEgKuVH4FqFB3VYu0nwdHKiEMA+oXz7oV8X1kw==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + /@smithy/types@4.3.2: resolution: {integrity: sha512-QO4zghLxiQ5W9UZmX2Lo0nta2PuE1sSrXUYDoaB6HMR762C0P7v/HEPHf6ZdglTVssJG1bsrSBxdc3quvDSihw==} engines: {node: '>=18.0.0'} @@ -17106,6 +18180,38 @@ packages: tslib: 2.8.1 dev: false + /@smithy/url-parser@4.2.8: + resolution: {integrity: sha512-NQho9U68TGMEU639YkXnVMV3GEFFULmmaWdlu1E9qzyIePOHsoSnagTGSDv1Zi8DCNN6btxOSdgmy5E/hsZwhA==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/querystring-parser': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-base64@4.3.0: + resolution: {integrity: sha512-GkXZ59JfyxsIwNTWFnjmFEI8kZpRNIBfxKjv09+nkAWPt/4aGaEWMM04m4sxgNVWkbt2MdSvE3KF/PfX4nFedQ==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/util-buffer-from': 4.2.0 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-body-length-browser@4.2.0: + resolution: {integrity: sha512-Fkoh/I76szMKJnBXWPdFkQJl2r9SjPt3cMzLdOB6eJ4Pnpas8hVoWPYemX/peO0yrrvldgCUVJqOAjUrOLjbxg==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@smithy/util-body-length-node@4.2.1: + resolution: {integrity: sha512-h53dz/pISVrVrfxV1iqXlx5pRg3V2YWFcSQyPyXZRrZoZj4R4DeWRDo1a7dd3CPTcFi3kE+98tuNyD2axyZReA==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + /@smithy/util-buffer-from@2.2.0: resolution: {integrity: sha512-IJdWBbTcMQ6DA0gdNhh/BwrLkDR+ADW5Kr1aZmd4k3DIF6ezMV4R2NIAmT08wQJ3yUK82thHWmC/TnK/wpMMIA==} engines: {node: '>=14.0.0'} @@ -17122,6 +18228,53 @@ packages: tslib: 2.8.1 dev: false + /@smithy/util-buffer-from@4.2.0: + resolution: {integrity: sha512-kAY9hTKulTNevM2nlRtxAG2FQ3B2OR6QIrPY3zE5LqJy1oxzmgBGsHLWTcNhWXKchgA0WHW+mZkQrng/pgcCew==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/is-array-buffer': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-config-provider@4.2.0: + resolution: {integrity: sha512-YEjpl6XJ36FTKmD+kRJJWYvrHeUvm5ykaUS5xK+6oXffQPHeEM4/nXlZPe+Wu0lsgRUcNZiliYNh/y7q9c2y6Q==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@smithy/util-defaults-mode-browser@4.3.29: + resolution: {integrity: sha512-nIGy3DNRmOjaYaaKcQDzmWsro9uxlaqUOhZDHQed9MW/GmkBZPtnU70Pu1+GT9IBmUXwRdDuiyaeiy9Xtpn3+Q==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/property-provider': 4.2.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-defaults-mode-node@4.2.32: + resolution: {integrity: sha512-7dtFff6pu5fsjqrVve0YMhrnzJtccCWDacNKOkiZjJ++fmjGExmmSu341x+WU6Oc1IccL7lDuaUj7SfrHpWc5Q==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/config-resolver': 4.4.6 + '@smithy/credential-provider-imds': 4.2.8 + '@smithy/node-config-provider': 4.3.8 + '@smithy/property-provider': 4.2.8 + '@smithy/smithy-client': 4.11.2 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-endpoints@3.2.8: + resolution: {integrity: sha512-8JaVTn3pBDkhZgHQ8R0epwWt+BqPSLCjdjXXusK1onwJlRuN69fbvSK66aIKKO7SwVFM6x2J2ox5X8pOaWcUEw==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/node-config-provider': 4.3.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + /@smithy/util-hex-encoding@4.0.0: resolution: {integrity: sha512-Yk5mLhHtfIgW2W2WQZWSg5kuMZCVbvhFmC7rV4IO2QqnZdbEFPmQnCcGMAX2z/8Qj3B9hYYNjZOhWym+RwhePw==} engines: {node: '>=18.0.0'} @@ -17129,6 +18282,51 @@ packages: tslib: 2.8.1 dev: false + /@smithy/util-hex-encoding@4.2.0: + resolution: {integrity: sha512-CCQBwJIvXMLKxVbO88IukazJD9a4kQ9ZN7/UMGBjBcJYvatpWk+9g870El4cB8/EJxfe+k+y0GmR9CAzkF+Nbw==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + + /@smithy/util-middleware@4.2.8: + resolution: {integrity: sha512-PMqfeJxLcNPMDgvPbbLl/2Vpin+luxqTGPpW3NAQVLbRrFRzTa4rNAASYeIGjRV9Ytuhzny39SpyU04EQreF+A==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-retry@4.2.8: + resolution: {integrity: sha512-CfJqwvoRY0kTGe5AkQokpURNCT1u/MkRzMTASWMPPo2hNSnKtF1D45dQl3DE2LKLr4m+PW9mCeBMJr5mCAVThg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/service-error-classification': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-stream@4.5.11: + resolution: {integrity: sha512-lKmZ0S/3Qj2OF5H1+VzvDLb6kRxGzZHq6f3rAsoSu5cTLGsn3v3VQBA8czkNNXlLjoFEtVu3OQT2jEeOtOE2CA==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/fetch-http-handler': 5.3.9 + '@smithy/node-http-handler': 4.4.9 + '@smithy/types': 4.12.0 + '@smithy/util-base64': 4.3.0 + '@smithy/util-buffer-from': 4.2.0 + '@smithy/util-hex-encoding': 4.2.0 + '@smithy/util-utf8': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-uri-escape@4.2.0: + resolution: {integrity: sha512-igZpCKV9+E/Mzrpq6YacdTQ0qTiLm85gD6N/IrmyDvQFA4UnU3d5g3m8tMT/6zG/vVkWSU+VxeUyGonL62DuxA==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + /@smithy/util-utf8@2.3.0: resolution: {integrity: sha512-R8Rdn8Hy72KKcebgLiv8jQcQkXoLMOGGv5uI1/k0l+snqkOzQ1R0ChUBCxWMlBsFMekWjq0wRudIweFs7sKT5A==} engines: {node: '>=14.0.0'} @@ -17145,6 +18343,30 @@ packages: tslib: 2.8.1 dev: false + /@smithy/util-utf8@4.2.0: + resolution: {integrity: sha512-zBPfuzoI8xyBtR2P6WQj63Rz8i3AmfAaJLuNG8dWsfvPe8lO4aCPYLn879mEgHndZH1zQ2oXmG8O1GGzzaoZiw==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/util-buffer-from': 4.2.0 + tslib: 2.8.1 + dev: false + + /@smithy/util-waiter@4.2.8: + resolution: {integrity: sha512-n+lahlMWk+aejGuax7DPWtqav8HYnWxQwR+LCG2BgCUmaGcTe9qZCFsmw8TMg9iG75HOwhrJCX9TCJRLH+Yzqg==} + engines: {node: '>=18.0.0'} + dependencies: + '@smithy/abort-controller': 4.2.8 + '@smithy/types': 4.12.0 + tslib: 2.8.1 + dev: false + + /@smithy/uuid@1.1.0: + resolution: {integrity: sha512-4aUIteuyxtBUhVdiQqcDhKFitwfd9hqoSDYY2KRXiWtgoWJ9Bmise+KfEPDiVHWeJepvF8xJO9/9+WDIciMFFw==} + engines: {node: '>=18.0.0'} + dependencies: + tslib: 2.8.1 + dev: false + /@so-ric/colorspace@1.1.6: resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==} dependencies: @@ -21731,6 +22953,10 @@ packages: deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info. dev: false + /bowser@2.13.1: + resolution: {integrity: sha512-OHawaAbjwx6rqICCKgSG0SAnT05bzd7ppyKLVUITZpANBaaMFBAsaNkto3LoQ31tyFP5kNujE8Cdx85G9VzOkw==} + dev: false + /boxen@5.1.2: resolution: {integrity: sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==} engines: {node: '>=10'} @@ -21832,6 +23058,13 @@ packages: /buffer-from@1.1.2: resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} + /buffer@5.6.0: + resolution: {integrity: sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==} + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + dev: false + /buffer@5.7.1: resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} dependencies: @@ -24256,6 +25489,13 @@ packages: - supports-color dev: false + /dockerfile-ast@0.7.1: + resolution: {integrity: sha512-oX/A4I0EhSkGqrFv0YuvPkBUSYp1XiY8O8zAKc8Djglx8ocz+JfOr8gP0ryRMC2myqvDLagmnZaU9ot1vG2ijw==} + dependencies: + vscode-languageserver-textdocument: 1.0.12 + vscode-languageserver-types: 3.17.5 + dev: false + /dockerode@4.0.7: resolution: {integrity: sha512-R+rgrSRTRdU5mH14PZTCPZtW/zw3HDWNTS/1ZAQpL/5Upe/ye5K9WQkIysu4wBoiMwKynsz0a8qWuGsHgEvSAA==} engines: {node: '>= 8.0'} @@ -24393,6 +25633,22 @@ packages: stream-shift: 1.0.3 dev: false + /e2b@2.12.0: + resolution: {integrity: sha512-uzMEg11JQ6o90ODBUgPaQXKJ3tQNiQMAYi5yU5jK60Y0l+CSs7U8qoQcgTiSCemkIEyrmIDFub/ega8dv5vMCw==} + engines: {node: '>=20'} + dependencies: + '@bufbuild/protobuf': 2.10.1 + '@connectrpc/connect': 2.0.0-rc.3(@bufbuild/protobuf@2.10.1) + '@connectrpc/connect-web': 2.0.0-rc.3(@bufbuild/protobuf@2.10.1)(@connectrpc/connect@2.0.0-rc.3) + chalk: 5.6.2 + compare-versions: 6.1.1 + dockerfile-ast: 0.7.1 + glob: 11.1.0 + openapi-fetch: 0.14.1 + platform: 1.3.6 + tar: 7.5.7 + dev: false + /eastasianwidth@0.2.0: resolution: {integrity: sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==} @@ -25296,6 +26552,13 @@ packages: engines: {node: '>= 0.8.0'} dev: true + /expand-tilde@2.0.2: + resolution: {integrity: sha512-A5EmesHW6rfnZ9ysHQjPdJRni0SRar0tjtG5MNtm9n5TUvsYU8oozprtRD4AqHxcZWWlVuAmQo2nWKfN9oyjTw==} + engines: {node: '>=0.10.0'} + dependencies: + homedir-polyfill: 1.0.3 + dev: false + /expect-type@1.2.2: resolution: {integrity: sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA==} engines: {node: '>=12.0.0'} @@ -25547,6 +26810,13 @@ packages: /fast-uri@3.0.6: resolution: {integrity: sha512-Atfo14OibSv5wAp4VWNsFYE1AchQRTv9cBGWET4pZWHzYshFSS9NQI6I57rdKn9croWVMbYFbLhJ+yJvmZIIHw==} + /fast-xml-parser@5.3.4: + resolution: {integrity: sha512-EFd6afGmXlCx8H8WTZHhAoDaWaGyuIBoZJ2mknrNxug+aZKjkp0a0dlars9Izl+jF+7Gu1/5f/2h68cQpe0IiA==} + hasBin: true + dependencies: + strnum: 2.1.2 + dev: false + /fastest-levenshtein@1.0.16: resolution: {integrity: sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==} engines: {node: '>= 4.9.1'} @@ -26498,6 +27768,20 @@ packages: path-scurry: 2.0.0 dev: true + /glob@11.1.0: + resolution: {integrity: sha512-vuNwKSaKiqm7g0THUBu2x7ckSs3XJLXE+2ssL7/MfTGPLLcrJQ/4Uq1CjPTtO5cCIiRxqvN6Twy1qOwhL0Xjcw==} + engines: {node: 20 || >=22} + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me + hasBin: true + dependencies: + foreground-child: 3.3.1 + jackspeak: 4.1.1 + minimatch: 10.1.2 + minipass: 7.1.2 + package-json-from-dist: 1.0.1 + path-scurry: 2.0.0 + dev: false + /glob@7.1.4: resolution: {integrity: sha512-hkLPepehmnKk41pUGm3sYxoFs/umurYfYJCerbXEyFIWcAzvpipAgVkBqqT9RBKMGjnq6kMuyYwha6csxbiM1A==} deprecated: Glob versions prior to v9 are no longer supported @@ -26512,7 +27796,7 @@ packages: /glob@7.2.3: resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==} - deprecated: Glob versions prior to v9 are no longer supported + deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me dependencies: fs.realpath: 1.0.0 inflight: 1.0.6 @@ -27147,6 +28431,13 @@ packages: /highlightjs-vue@1.0.0: resolution: {integrity: sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==} + /homedir-polyfill@1.0.3: + resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==} + engines: {node: '>=0.10.0'} + dependencies: + parse-passwd: 1.0.0 + dev: false + /hono@4.10.8: resolution: {integrity: sha512-DDT0A0r6wzhe8zCGoYOmMeuGu3dyTAE40HHjwUsWFTEy5WxK1x2WDSsBPlEXgPbRIFY6miDualuUDbasPogIww==} engines: {node: '>=16.9.0'} @@ -28194,7 +29485,6 @@ packages: engines: {node: 20 || >=22} dependencies: '@isaacs/cliui': 8.0.2 - dev: true /jake@10.9.4: resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==} @@ -29901,7 +31191,6 @@ packages: /lru-cache@11.2.2: resolution: {integrity: sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==} engines: {node: 20 || >=22} - dev: true /lru-cache@4.1.5: resolution: {integrity: sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==} @@ -31018,6 +32307,13 @@ packages: dependencies: '@isaacs/brace-expansion': 5.0.0 + /minimatch@10.1.2: + resolution: {integrity: sha512-fu656aJ0n2kcXwsnwnv9g24tkU5uSmOlTjd6WyyaKm2Z+h1qmY6bAjrcaIxF/BslFqbZ8UBtbJi7KgQOZD2PTw==} + engines: {node: 20 || >=22} + dependencies: + '@isaacs/brace-expansion': 5.0.1 + dev: false + /minimatch@3.0.5: resolution: {integrity: sha512-tUpxzX0VAzJHjLu0xUfFv1gwVp9ba3IOuRAVH2EGuRW8a5emA2FlACLqiT/lDVtS1W+TGNwqz3sWaNyLgDJWuw==} dependencies: @@ -31155,6 +32451,7 @@ packages: engines: {node: '>= 18'} dependencies: minipass: 7.1.2 + dev: false /minizlib@3.1.0: resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==} @@ -31186,6 +32483,7 @@ packages: resolution: {integrity: sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg==} engines: {node: '>=10'} hasBin: true + dev: false /ml-array-max@1.2.4: resolution: {integrity: sha512-BlEeg80jI0tW6WaPyGxf5Sa4sqvcyY6lbSn5Vcv44lp1I2GR6AWojfUvLnGTNsIXrZ8uqWmo8VcG1WpkI2ONMQ==} @@ -32702,7 +34000,7 @@ packages: dependencies: global-agent: 3.0.0 onnxruntime-common: 1.21.0 - tar: 7.4.3 + tar: 7.5.1 dev: false /onnxruntime-web@1.22.0-dev.20250409-89f8206ba4: @@ -32786,10 +34084,20 @@ packages: zod: 4.3.5 dev: true + /openapi-fetch@0.14.1: + resolution: {integrity: sha512-l7RarRHxlEZYjMLd/PR0slfMVse2/vvIAGm75/F7J6MlQ8/b9uUQmUF2kCPrQhJqMXSxmYWObVgeYXbFYzZR+A==} + dependencies: + openapi-typescript-helpers: 0.0.15 + dev: false + /openapi-types@12.1.3: resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==} dev: false + /openapi-typescript-helpers@0.0.15: + resolution: {integrity: sha512-opyTPaunsklCBpTK8JGef6mfPhLSnyy5a0IN9vKtx3+4aExf+KxEqYwIy3hqkedXIB97u357uLMJsOnm3GVjsw==} + dev: false + /openapi3-ts@4.5.0: resolution: {integrity: sha512-jaL+HgTq2Gj5jRcfdutgRGLosCy/hT8sQf6VOy+P+g36cZOjI1iukdPnijC+4CmeRzg/jEllJUboEic2FhxhtQ==} dependencies: @@ -33326,6 +34634,11 @@ packages: resolution: {integrity: sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw==} engines: {node: '>=18'} + /parse-passwd@1.0.0: + resolution: {integrity: sha512-1Y1A//QUXEZK7YKz+rD9WydcE1+EuPr6ZBgKecAB8tmoW6UFv0NREVJe1p+jRxtThkcbbKkfwIbWJe/IeE6m2Q==} + engines: {node: '>=0.10.0'} + dev: false + /parse-path@7.1.0: resolution: {integrity: sha512-EuCycjZtfPcjWk7KTksnJ5xPMvWGA/6i4zrLYhRG0hGvC3GPU/jGUj3Cy+ZR0v30duV3e23R95T1lE2+lsndSw==} dependencies: @@ -33456,7 +34769,6 @@ packages: dependencies: lru-cache: 11.2.2 minipass: 7.1.2 - dev: true /path-to-regexp@0.1.12: resolution: {integrity: sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==} @@ -36479,6 +37791,13 @@ packages: resolution: {integrity: sha512-KXDYZ9dszj6bzvnEMRYvxgeTHU74QBFL54XKtP3nyMuJ81CFYtABZ3bAzL2EdFUaEwJOBOgENyFj3R7oTzDyyw==} engines: {node: '>=4', npm: '>=6'} + /stream-browserify@3.0.0: + resolution: {integrity: sha512-H73RAHsVBapbim0tU2JwwOiXUj+fikfiaoYAKHF3VJfA0pe2BCzkhAHBlLG6REzE+2WNZcxOXjK7lkso+9euLA==} + dependencies: + inherits: 2.0.4 + readable-stream: 3.6.2 + dev: false + /stream-events@1.0.5: resolution: {integrity: sha512-E1GUzBSgvct8Jsb3v2X15pjzN1tYebtbLaMg+eBOUOAxgbLoSbT2NS91ckc5lJD1KfLjId+jXJRgo0qnV5Nerg==} dependencies: @@ -36700,6 +38019,10 @@ packages: engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} dev: true + /strnum@2.1.2: + resolution: {integrity: sha512-l63NF9y/cLROq/yqKXSLtcMeeyOfnSQlfMSlzFt/K73oIaD8DGaQWd7Z34X9GPiKqP5rbSh84Hl4bOlLcjiSrQ==} + dev: false + /strong-log-transformer@2.1.0: resolution: {integrity: sha512-B3Hgul+z0L9a236FAUC9iZsL+nVHgoCJnqCbN588DjYxvGXaXaaFbfmQ/JhvKjZwsOukuR72XbHv71Qkug0HxA==} engines: {node: '>=4'} @@ -37027,6 +38350,7 @@ packages: minizlib: 3.0.2 mkdirp: 3.0.1 yallist: 5.0.0 + dev: false /tar@7.5.1: resolution: {integrity: sha512-nlGpxf+hv0v7GkWBK2V9spgactGOp0qvfWRxUMjqHyzrt3SgwE48DIv/FhqPHJYLHpgW1opq3nERbz5Anq7n1g==} @@ -37038,6 +38362,17 @@ packages: minizlib: 3.1.0 yallist: 5.0.0 + /tar@7.5.7: + resolution: {integrity: sha512-fov56fJiRuThVFXD6o6/Q354S7pnWMJIVlDBYijsTNx6jKSE4pvrDTs6lUnmGvNyfJwFQQwWy3owKz1ucIhveQ==} + engines: {node: '>=18'} + dependencies: + '@isaacs/fs-minipass': 4.0.1 + chownr: 3.0.0 + minipass: 7.1.2 + minizlib: 3.1.0 + yallist: 5.0.0 + dev: false + /teeny-request@10.1.0: resolution: {integrity: sha512-3ZnLvgWF29jikg1sAQ1g0o+lr5JX6sVgYvfUJazn7ZjJroDBUTWp44/+cFVX0bULjv4vci+rBD+oGVAkWqhUbw==} engines: {node: '>=18'} @@ -37726,6 +39061,51 @@ packages: - yaml dev: true + /tsup@8.5.0(@swc/core@1.5.29)(typescript@5.9.3): + resolution: {integrity: sha512-VmBp77lWNQq6PfuMqCHD3xWl22vEoWsKajkF8t+yMBawlUS8JzEI+vOVMeuNZIuMML8qXRizFKi9oD5glKQVcQ==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + '@microsoft/api-extractor': ^7.36.0 + '@swc/core': ^1 + postcss: ^8.4.12 + typescript: '>=4.5.0' + peerDependenciesMeta: + '@microsoft/api-extractor': + optional: true + '@swc/core': + optional: true + postcss: + optional: true + typescript: + optional: true + dependencies: + '@swc/core': 1.5.29(@swc/helpers@0.5.17) + bundle-require: 5.1.0(esbuild@0.25.10) + cac: 6.7.14 + chokidar: 4.0.3 + consola: 3.4.2 + debug: 4.4.3(supports-color@10.2.2) + esbuild: 0.25.10 + fix-dts-default-cjs-exports: 1.0.1 + joycon: 3.1.1 + picocolors: 1.1.1 + postcss-load-config: 6.0.1 + resolve-from: 5.0.0 + rollup: 4.50.2 + source-map: 0.8.0-beta.0 + sucrase: 3.35.0 + tinyexec: 0.3.2 + tinyglobby: 0.2.15 + tree-kill: 1.2.2 + typescript: 5.9.3 + transitivePeerDependencies: + - jiti + - supports-color + - tsx + - yaml + dev: true + /tsx@4.20.4: resolution: {integrity: sha512-yyxBKfORQ7LuRt/BQKBXrpcq59ZvSW0XxwfjAt3w2/8PmdxaFzijtMhTawprSHhpzeM5BgU2hXHG3lklIERZXg==} engines: {node: '>=18.0.0'} diff --git a/website/docs/workspaces/filesystem.md b/website/docs/workspaces/filesystem.md new file mode 100644 index 000000000..5055b808a --- /dev/null +++ b/website/docs/workspaces/filesystem.md @@ -0,0 +1,98 @@ +--- +title: Workspace Filesystem +slug: /workspaces/filesystem +--- + +# Workspace Filesystem + +> **Note: Workspace Filesystem is Experimental** +> The Workspace API is experimental. Expect iteration and possible breaking changes as we refine the API. + +Workspace filesystem provides a persistent (or in-memory) file layer for agents. Use it to store notes, datasets, and intermediate outputs. + +## Backend options + +In-memory is the default. For disk persistence, use `NodeFilesystemBackend`: + +```ts +import { Workspace, NodeFilesystemBackend } from "@voltagent/core"; + +const workspace = new Workspace({ + filesystem: { + backend: new NodeFilesystemBackend({ + rootDir: "./.workspace", + }), + }, +}); +``` + +All filesystem tool paths are workspace-relative and must start with `/`. + +## Filesystem tools + +- `ls`: list files in a directory +- `read_file`: read a file +- `write_file`: write a file +- `edit_file`: edit a file +- `delete_file`: delete a file +- `stat`: get file or directory metadata +- `mkdir`: create a directory +- `rmdir`: remove a directory +- `list_tree`: list files and directories recursively with depth control +- `list_files`: alias for `list_tree` +- `glob`: list files matching a glob +- `grep`: search for a regex pattern + +## Behavior + +- `write_file` supports `overwrite` and `create_parent_dirs` +- `delete_file` supports `recursive` to delete directories + +## Read-only mode + +Mark the filesystem as read-only to block writes and hide write tools from the toolkit: + +```ts +const workspace = new Workspace({ + filesystem: { + readOnly: true, + }, +}); +``` + +When read-only, `workspace_index` and `workspace_index_content` are also disabled. + +## Tool policies (filesystem) + +Tool policies let you enable/disable tools, require approval, or enforce read-before-write: + +```ts +const agent = new Agent({ + name: "workspace-agent", + model, + workspace, + workspaceToolkits: { + filesystem: { + toolPolicies: { + defaults: { needsApproval: true }, + tools: { + write_file: { enabled: false }, + edit_file: { needsApproval: true }, + delete_file: { requireReadBeforeWrite: true }, + mkdir: { requireReadBeforeWrite: true }, + }, + }, + }, + }, +}); +``` + +`requireReadBeforeWrite` forces a `read_file` call before edits/deletes and prompts a re-read if the file changes. + +## Security notes + +- Keep filesystem access within a workspace root. +- Avoid exposing absolute host paths. +- Prefer read-only mode for untrusted agents. + +For broader recommendations, see [Workspace Security](../security). diff --git a/website/docs/workspaces/overview.md b/website/docs/workspaces/overview.md new file mode 100644 index 000000000..279ffc1c9 --- /dev/null +++ b/website/docs/workspaces/overview.md @@ -0,0 +1,106 @@ +--- +title: Workspace +slug: /workspaces +--- + +# Workspace + +> **Note: Workspace is Experimental** +> The Workspace API is experimental. Expect iteration and possible breaking changes as we refine the API. + +Workspace gives agents a persistent home base with filesystem, sandbox execution, search, and skills. It keeps tool usage structured and observable while staying configurable per agent or conversation. + +## Quick start + +```ts +import { Agent, Workspace, LocalSandbox, InMemoryVectorAdapter } from "@voltagent/core"; + +const workspace = new Workspace({ + id: "demo-workspace", + operationTimeoutMs: 30000, + filesystem: { + // Defaults to in-memory. Swap in NodeFilesystemBackend or a custom backend for persistence. + }, + sandbox: new LocalSandbox(), + search: { + autoIndexPaths: ["/"], + embedding: "openai:text-embedding-3-small", + vector: new InMemoryVectorAdapter(), + }, + skills: { + rootPaths: ["/skills"], + }, +}); + +const agent = new Agent({ + name: "workspace-agent", + model, + instructions: "Use workspace tools when needed.", + workspace, + // workspaceToolkits is optional; defaults add filesystem + sandbox + search + skills +}); +``` + +If you only want specific toolkits: + +```ts +const agent = new Agent({ + name: "workspace-agent", + model, + instructions: "Use workspace tools when needed.", + workspace, + workspaceToolkits: { + filesystem: false, + sandbox: {}, + search: {}, + skills: {}, + }, +}); +``` + +You can also set a global workspace on the VoltAgent instance. Agents inherit it unless they pass their own `workspace` or set `workspace: false`: + +```ts +import { Agent, VoltAgent, Workspace } from "@voltagent/core"; + +const workspace = new Workspace({ id: "shared-workspace" }); + +const volt = new VoltAgent({ + workspace, + agents: { + support: new Agent({ name: "support", model }), + }, +}); +``` + +Skills root resolvers can receive context: + +```ts +const workspace = new Workspace({ + skills: { + rootPaths: async ({ workspace, filesystem }) => ["/skills", `/skills/${workspace.id}`], + }, +}); +``` + +## Workspace lifecycle + utilities + +You can initialize or tear down the workspace explicitly, and inspect runtime info: + +```ts +await workspace.init(); + +const info = workspace.getInfo(); +const pathContext = workspace.getPathContext(); +const toolsConfig = workspace.getToolsConfig(); + +await workspace.destroy(); +``` + +## Guides + +- [Filesystem](./filesystem) +- [Search](./search) +- [Sandbox](./sandbox) +- [Skills](./skills) +- [Security](./security) diff --git a/website/docs/workspaces/sandbox.md b/website/docs/workspaces/sandbox.md new file mode 100644 index 000000000..1ef57a42b --- /dev/null +++ b/website/docs/workspaces/sandbox.md @@ -0,0 +1,176 @@ +--- +title: Workspace Sandbox +slug: /workspaces/sandbox +--- + +# Workspace Sandbox + +> **Note: Workspace Sandbox is Experimental** +> The Workspace API is experimental. Expect iteration and possible breaking changes as we refine the API. + +The sandbox toolkit adds `execute_command` with timeout/env/cwd control and automatic stdout/stderr eviction when output is large. + +## LocalSandbox basics + +By default, `LocalSandbox` uses a `.sandbox/` directory under the current working directory. + +```ts +const workspace = new Workspace({ + sandbox: new LocalSandbox({ + rootDir: "/tmp/voltagent", + }), +}); +``` + +You can opt into cleaning the auto-created root directory on destroy: + +```ts +const workspace = new Workspace({ + sandbox: new LocalSandbox({ + cleanupOnDestroy: true, + }), +}); +``` + +## Isolation (macOS + Linux) + +LocalSandbox supports OS-level isolation via `sandbox-exec` on macOS and `bwrap` (bubblewrap) on Linux: + +```ts +const workspace = new Workspace({ + sandbox: new LocalSandbox({ + rootDir: "/tmp/voltagent", + isolation: { + provider: "sandbox-exec", + allowNetwork: false, + readWritePaths: ["/tmp/voltagent"], + }, + }), +}); +``` + +If the provider is unavailable or unsupported on the current OS, execution will throw. + +Auto-detect a provider: + +```ts +const provider = await LocalSandbox.detectIsolation(); + +const workspace = new Workspace({ + sandbox: new LocalSandbox({ + rootDir: "/tmp/voltagent", + isolation: + provider === "none" + ? undefined + : { + provider, + allowNetwork: false, + readWritePaths: ["/tmp/voltagent"], + }, + }), +}); +``` + +Note: `bwrap` requires bubblewrap to be installed and unprivileged user namespaces enabled. + +### Native config overrides + +```ts +const workspace = new Workspace({ + sandbox: new LocalSandbox({ + rootDir: "/tmp/voltagent", + isolation: { + provider: "sandbox-exec", + seatbeltProfilePath: "/path/to/profile.sb", + allowSystemBinaries: true, + }, + }), +}); +``` + +```ts +const workspace = new Workspace({ + sandbox: new LocalSandbox({ + rootDir: "/tmp/voltagent", + isolation: { + provider: "bwrap", + bwrapArgs: ["--unshare-ipc"], + allowSystemBinaries: true, + }, + }), +}); +``` + +`allowSystemBinaries` relaxes read access by mounting common system paths (like `/usr/bin` or `/bin`) as read-only. Keep it `false` unless you need standard OS tools in the sandbox. + +By default, LocalSandbox passes only `PATH` into the environment. Set `inheritProcessEnv: true` to pass the full process environment. + +## Remote sandbox providers + +Install the provider package you need (for example `@voltagent/sandbox-e2b` or `@voltagent/sandbox-daytona`), then configure it on the workspace: + +```ts +import { E2BSandbox } from "@voltagent/sandbox-e2b"; +import { DaytonaSandbox } from "@voltagent/sandbox-daytona"; + +const workspace = new Workspace({ + sandbox: new E2BSandbox({ + apiKey: process.env.E2B_API_KEY, + }), +}); + +const daytonaWorkspace = new Workspace({ + sandbox: new DaytonaSandbox({ + apiKey: process.env.DAYTONA_API_KEY, + apiUrl: "http://localhost:3000", + }), +}); +``` + +## Custom sandbox provider + +You can implement `WorkspaceSandbox` and plug it into `Workspace` directly. + +```ts +import type { + WorkspaceSandbox, + WorkspaceSandboxExecuteOptions, + WorkspaceSandboxResult, +} from "@voltagent/core"; +import { Workspace } from "@voltagent/core"; + +class CustomSandbox implements WorkspaceSandbox { + name = "custom"; + status = "ready" as const; + + getInfo() { + return { provider: "custom-sandbox", status: this.status }; + } + + async execute(options: WorkspaceSandboxExecuteOptions): Promise { + const start = Date.now(); + // TODO: run command in your custom environment + // Respect options.timeoutMs, options.signal, and stream via onStdout/onStderr when possible. + + return { + stdout: "", + stderr: "", + exitCode: 0, + durationMs: Date.now() - start, + timedOut: false, + aborted: false, + stdoutTruncated: false, + stderrTruncated: false, + }; + } +} + +const workspace = new Workspace({ + sandbox: new CustomSandbox(), +}); +``` + +Notes: + +- `onStdout`/`onStderr` are optional streaming hooks for UI integration. +- `timeoutMs` and `signal` should be enforced to avoid runaway processes. diff --git a/website/docs/workspaces/search.md b/website/docs/workspaces/search.md new file mode 100644 index 000000000..e01b831f5 --- /dev/null +++ b/website/docs/workspaces/search.md @@ -0,0 +1,91 @@ +--- +title: Workspace Search +slug: /workspaces/search +--- + +# Workspace Search + +> **Note: Workspace Search is Experimental** +> The Workspace API is experimental. Expect iteration and possible breaking changes as we refine the API. + +Workspace search supports BM25, vector, and hybrid modes over indexed workspace content. + +## Search tools + +- `workspace_index`: index files under a path + glob +- `workspace_index_content`: index raw content by path +- `workspace_search`: BM25, vector, or hybrid search + +```ts +const workspace = new Workspace({ + search: { + autoIndexPaths: [{ path: "/", glob: "**/*.{md,ts,js}" }], + embedding: "openai:text-embedding-3-small", + vector: new InMemoryVectorAdapter(), + }, +}); +``` + +## Direct search API (opt-in) + +Search is tool-only by default. Enable `search.allowDirectAccess` for programmatic access: + +```ts +const workspace = new Workspace({ + search: { + allowDirectAccess: true, + autoIndexPaths: ["/notes"], + }, +}); + +// Index ad-hoc content +await workspace.index("/notes/extra.md", "Hello world", { source: "manual" }); + +// Query with hybrid search + minScore filter +const results = await workspace.search("workspace isolation", { + mode: "hybrid", + minScore: 0.25, + topK: 5, +}); +``` + +Direct calls still respect search tool policies (`enabled` / `needsApproval`). + +## Snippet-only output + +To reduce token usage, you can omit full content in tool output: + +```ts +const results = await agent.generateText("Search notes for retention ideas.", { + tools: { + workspace_search: { + query: "retention", + include_content: false, + snippet_length: 200, + }, + }, +}); +``` + +## Parameters + +`workspace_search` supports: + +- `top_k` (default `5`) +- `min_score` (0-1) +- `snippet_length` +- `include_content` (default `true`) +- `vector_weight` (0-1) +- `lexical_weight` (defaults to `1 - vector_weight`) + +## Result fields + +Search results include: + +- `score`: normalized score (0-1) +- `scoreDetails`: normalized `bm25` / `vector` +- `content`: full content (if `include_content`) +- `snippet`: snippet around query terms +- `lineRange`: 1-based start/end line numbers for matches + +BM25 scores are normalized per result set; vector scores use cosine similarity. In hybrid mode, scores are combined using `vector_weight`. diff --git a/website/docs/workspaces/security.md b/website/docs/workspaces/security.md new file mode 100644 index 000000000..fb87d4df6 --- /dev/null +++ b/website/docs/workspaces/security.md @@ -0,0 +1,69 @@ +--- +title: Workspace Security +slug: /workspaces/security +--- + +# Workspace Security + +> **Note: Workspace Security is Experimental** +> The Workspace API is experimental. Expect iteration and possible breaking changes as we refine the API. + +Workspace is powerful; treat it like a production capability. Recommended practices: + +- **Filesystem containment**: Keep all file access within a workspace root. Avoid exposing absolute host paths. +- **Read-only mode**: Use `filesystem.readOnly` for agents that should never write. +- **Tool policies**: Require approvals for write/delete and sandbox execution in untrusted contexts. +- **Sandbox isolation**: Prefer `LocalSandbox` with isolation enabled (and a dedicated root directory). +- **Environment variables**: Avoid inheriting the full process environment; pass only what is needed. +- **Timeouts**: Set `operationTimeoutMs` (and sandbox `timeout_ms`) to prevent runaway tasks. +- **Direct search access**: Keep `search.allowDirectAccess` disabled unless you truly need it. +- **Skills allowlist**: Access to skill references/scripts/assets is allowlisted; avoid loading arbitrary files. + +## Tool policy defaults + +`toolConfig` lets you set workspace-level defaults; agent-level toolkit options merge on top: + +```ts +const workspace = new Workspace({ + toolConfig: { + filesystem: { + defaults: { needsApproval: true }, + tools: { write_file: { enabled: false } }, + }, + }, +}); +``` + +`requireReadBeforeWrite` ensures the agent calls `read_file` on the path before it can modify or delete it. If the file changes after it was read, the tool will ask the agent to re-read it. + +## Timeboxing operations + +`operationTimeoutMs` applies to workspace tool executions (filesystem, sandbox, search, skills). You can override it per toolkit: + +```ts +const agent = new Agent({ + name: "workspace-agent", + model, + workspace, + workspaceToolkits: { + filesystem: { operationTimeoutMs: 10_000 }, + search: { operationTimeoutMs: 5_000 }, + }, +}); +``` + +Combined example (timeboxed tools + isolated local sandbox): + +```ts +const workspace = new Workspace({ + operationTimeoutMs: 30_000, + sandbox: new LocalSandbox({ + rootDir: "/tmp/voltagent", + isolation: { + provider: "sandbox-exec", + allowNetwork: false, + readWritePaths: ["/tmp/voltagent"], + }, + }), +}); +``` diff --git a/website/docs/workspaces/skills.md b/website/docs/workspaces/skills.md new file mode 100644 index 000000000..b467ea737 --- /dev/null +++ b/website/docs/workspaces/skills.md @@ -0,0 +1,113 @@ +--- +title: Workspace Skills +slug: /workspaces/skills +--- + +# Workspace Skills + +> **Note: Workspace Skills are Experimental** +> The Skills API is experimental and may change as the ecosystem evolves. + +Workspace skills are reusable instructions stored as `SKILL.md` files. They can be discovered, searched, activated, and injected into the agent prompt. + +## Skill layout + +Skills live under a root path (default: `/skills`) and each skill is a folder with a `SKILL.md`. + +``` +/skills + /data-analysis + SKILL.md + references/ + schema.md + scripts/ + analyze.py + assets/ + sample.csv +``` + +You can also provide an async root resolver if skill paths are dynamic: + +```ts +const workspace = new Workspace({ + skills: { + rootPaths: async ({ workspace }) => ["/skills", `/skills/${workspace.id}`], + }, +}); +``` + +## SKILL.md format + +`SKILL.md` uses YAML frontmatter plus Markdown instructions: + +```md +--- +name: Data Analysis +description: Analyze CSV data with pandas and chart results. +version: "1.0.0" +tags: + - data + - python +references: + - references/schema.md +scripts: + - scripts/analyze.py +assets: + - assets/sample.csv +--- + +When analyzing data: + +1. Load CSV files with pandas. +2. Summarize key statistics. +3. Produce a chart and explain it. +``` + +Only files listed under `references`, `scripts`, or `assets` are readable via the skill file tools. + +## Activating skills and prompt injection + +Activate a skill, then inject activated skills into the system prompt: + +```ts +import { Agent, Workspace } from "@voltagent/core"; + +const workspace = new Workspace({ + skills: { + rootPaths: ["/skills"], + }, +}); + +const skillsHook = workspace.createSkillsPromptHook({ + includeAvailable: true, + includeActivated: true, +}); + +const agent = new Agent({ + name: "skills-agent", + model, + instructions: "Use workspace skills when relevant.", + workspace, + hooks: skillsHook, + workspaceToolkits: { skills: {} }, +}); +``` + +The injected prompt is wrapped in `` tags and can include both available and activated skills. + +## Skill tools + +The toolkit provides: + +- `workspace_list_skills`: list available skills +- `workspace_search_skills`: search skills (BM25/vector/hybrid) +- `workspace_read_skill`: read the full SKILL.md instructions +- `workspace_activate_skill`: activate a skill +- `workspace_deactivate_skill`: deactivate a skill +- `workspace_read_skill_reference`: read reference files +- `workspace_read_skill_script`: read scripts +- `workspace_read_skill_asset`: read assets + +## Search notes + +Skill search indexes the skill name, description, and instructions. Vector search requires an embedding model and vector adapter. diff --git a/website/sidebars.ts b/website/sidebars.ts index 6cf64c7aa..31c445814 100644 --- a/website/sidebars.ts +++ b/website/sidebars.ts @@ -116,6 +116,79 @@ const sidebars: SidebarsConfig = { }, items: ["guardrails/overview", "guardrails/built-in"], }, + { + type: "category", + label: "Workspaces", + collapsed: true, + items: [ + { + type: "doc", + id: "workspaces/overview", + label: "Overview", + customProps: { + badge: { + label: "Experimental", + variant: "accent", + }, + }, + }, + { + type: "doc", + id: "workspaces/filesystem", + label: "Filesystem", + customProps: { + badge: { + label: "Experimental", + variant: "accent", + }, + }, + }, + { + type: "doc", + id: "workspaces/search", + label: "Search", + customProps: { + badge: { + label: "Experimental", + variant: "accent", + }, + }, + }, + { + type: "doc", + id: "workspaces/sandbox", + label: "Sandbox", + customProps: { + badge: { + label: "Experimental", + variant: "accent", + }, + }, + }, + { + type: "doc", + id: "workspaces/skills", + label: "Skills", + customProps: { + badge: { + label: "Experimental", + variant: "accent", + }, + }, + }, + { + type: "doc", + id: "workspaces/security", + label: "Security", + customProps: { + badge: { + label: "Experimental", + variant: "accent", + }, + }, + }, + ], + }, { type: "category", label: "Workflows",