Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b6308d2113 | |||
| e7968a31b1 | |||
| 05e4f03061 | |||
| 37d4069806 | |||
| fe0de36b1a | |||
| e49f35e7de | |||
| 4fbffdd97d | |||
| 560838477f | |||
| 7503fccbf2 | |||
| a76bd0d3e4 | |||
| 1556a9d3e9 | |||
| 19ba58ca40 | |||
| 8662b73adb |
21
changelog.md
21
changelog.md
@@ -1,5 +1,26 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-01-20 - 1.3.0 - feat(smartagent)
|
||||
add JsonValidatorTool and support passing base64-encoded images with task runs (vision-capable models); bump @push.rocks/smartai to ^0.12.0
|
||||
|
||||
- Add JsonValidatorTool (validate/format actions) implemented in ts/smartagent.tools.json.ts
|
||||
- Export JsonValidatorTool from ts/index.ts
|
||||
- Add ITaskRunOptions interface (images?: string[]) in smartagent.interfaces.ts
|
||||
- DualAgent.run and Driver.startTask accept optional images and pass them to provider.chat/provider.chatStreaming; assistant responses added to message history
|
||||
- Bump dependency @push.rocks/smartai from ^0.11.1 to ^0.12.0 in package.json
|
||||
|
||||
## 2026-01-20 - 1.2.7 - fix(deps(smartai))
|
||||
bump @push.rocks/smartai to ^0.11.0
|
||||
|
||||
- package.json: @push.rocks/smartai updated from ^0.10.1 to ^0.11.0
|
||||
- Recommend a patch release since this is a dependency update with no breaking API changes: 1.2.7
|
||||
|
||||
## 2026-01-20 - 1.2.6 - fix(deps)
|
||||
bump @push.rocks/smartai to ^0.10.1
|
||||
|
||||
- Updated dependency @push.rocks/smartai from ^0.8.0 to ^0.10.1 in package.json
|
||||
- No other code changes; dependency-only update
|
||||
|
||||
## 2025-12-15 - 1.1.1 - fix(ci)
|
||||
Update CI/release config and bump devDependencies; enable verbose tests
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartagent",
|
||||
"version": "1.2.3",
|
||||
"version": "1.3.0",
|
||||
"private": false,
|
||||
"description": "an agentic framework built on top of @push.rocks/smartai",
|
||||
"main": "dist_ts/index.js",
|
||||
@@ -21,12 +21,13 @@
|
||||
"@types/node": "^25.0.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/smartai": "^0.8.0",
|
||||
"@push.rocks/smartai": "^0.12.0",
|
||||
"@push.rocks/smartbrowser": "^2.0.8",
|
||||
"@push.rocks/smartdeno": "^1.2.0",
|
||||
"@push.rocks/smartfs": "^1.2.0",
|
||||
"@push.rocks/smartrequest": "^5.0.1",
|
||||
"@push.rocks/smartshell": "^3.3.0"
|
||||
"@push.rocks/smartshell": "^3.3.0",
|
||||
"minimatch": "^10.1.1"
|
||||
},
|
||||
"packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34",
|
||||
"repository": {
|
||||
|
||||
69
pnpm-lock.yaml
generated
69
pnpm-lock.yaml
generated
@@ -9,8 +9,8 @@ importers:
|
||||
.:
|
||||
dependencies:
|
||||
'@push.rocks/smartai':
|
||||
specifier: ^0.8.0
|
||||
version: 0.8.0(typescript@5.9.3)(ws@8.18.3)(zod@3.25.76)
|
||||
specifier: ^0.12.0
|
||||
version: 0.12.0(typescript@5.9.3)(ws@8.18.3)(zod@3.25.76)
|
||||
'@push.rocks/smartbrowser':
|
||||
specifier: ^2.0.8
|
||||
version: 2.0.8(typescript@5.9.3)
|
||||
@@ -26,6 +26,9 @@ importers:
|
||||
'@push.rocks/smartshell':
|
||||
specifier: ^3.3.0
|
||||
version: 3.3.0
|
||||
minimatch:
|
||||
specifier: ^10.1.1
|
||||
version: 10.1.1
|
||||
devDependencies:
|
||||
'@git.zone/tsbuild':
|
||||
specifier: ^4.0.2
|
||||
@@ -45,8 +48,8 @@ importers:
|
||||
|
||||
packages:
|
||||
|
||||
'@anthropic-ai/sdk@0.65.0':
|
||||
resolution: {integrity: sha512-zIdPOcrCVEI8t3Di40nH4z9EoeyGZfXbYSvWdDLsB/KkaSYMnEgC7gmcgWu83g2NTn1ZTpbMvpdttWDGGIk6zw==}
|
||||
'@anthropic-ai/sdk@0.71.2':
|
||||
resolution: {integrity: sha512-TGNDEUuEstk/DKu0/TflXAEt+p+p/WhTlFzEnoosvbaDU2LTjm42igSdlL0VijrKpWejtOKxX0b8A7uc+XiSAQ==}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
zod: ^3.25.0 || ^4.0.0
|
||||
@@ -717,6 +720,9 @@ packages:
|
||||
'@lit/reactive-element@2.1.1':
|
||||
resolution: {integrity: sha512-N+dm5PAYdQ8e6UlywyyrgI2t++wFGXfHx+dSJ1oBrg6FAxUj40jId++EaRm80MKX5JnlH1sBsyZ5h0bcZKemCg==}
|
||||
|
||||
'@mistralai/mistralai@1.12.0':
|
||||
resolution: {integrity: sha512-oDr1hcS3wsIT/QupBG93TNiA5kilwBYoAIyl5BNYqMM2Ix/xsNq+wT8b++uhp/GTUMx44n+8Bn1mkATbwxe6bQ==}
|
||||
|
||||
'@mixmark-io/domino@2.2.0':
|
||||
resolution: {integrity: sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==}
|
||||
|
||||
@@ -831,8 +837,8 @@ packages:
|
||||
'@push.rocks/qenv@6.1.3':
|
||||
resolution: {integrity: sha512-+z2hsAU/7CIgpYLFqvda8cn9rUBMHqLdQLjsFfRn5jPoD7dJ5rFlpkbhfM4Ws8mHMniwWaxGKo+q/YBhtzRBLg==}
|
||||
|
||||
'@push.rocks/smartai@0.8.0':
|
||||
resolution: {integrity: sha512-guzi28meUDc3mydC8kpoA+4pzExRQqygXYFDD4qQSWPpIRHQ7qhpeNqJzrrGezT1yOH5Gb9taPEGwT56hI+nwQ==}
|
||||
'@push.rocks/smartai@0.12.0':
|
||||
resolution: {integrity: sha512-T4HRaSSxO6TQGGXlQeswX2eYkB+gMu0FbKF9qCUri6FdRlYzmPDn19jgPrPJxyg5m3oj6TzflvfYwcBCFlWo/A==}
|
||||
|
||||
'@push.rocks/smartarchive@4.2.4':
|
||||
resolution: {integrity: sha512-uiqVAXPxmr8G5rv3uZvZFMOCt8l7cZC3nzvsy4YQqKf/VkPhKIEX+b7LkAeNlxPSYUiBQUkNRoawg9+5BaMcHg==}
|
||||
@@ -916,6 +922,9 @@ packages:
|
||||
'@push.rocks/smartfs@1.2.0':
|
||||
resolution: {integrity: sha512-1R47jJZwX869z7DYgKeAZKTU1SbGnM7W/ZmgsI7AkQQhiascNqY3/gF4V5kIprmuf1WhpRbCbZyum8s7J1LDdg==}
|
||||
|
||||
'@push.rocks/smartfs@1.3.1':
|
||||
resolution: {integrity: sha512-ZSduVS8tM+/erbyCTvRRvc9gLWwbpqN5xdIIkMr+gub7fowSeJb7tR2rnGwySa63DyimU0q2KTp79VV9YqGLeg==}
|
||||
|
||||
'@push.rocks/smartguard@3.1.0':
|
||||
resolution: {integrity: sha512-J23q84f1O+TwFGmd4lrO9XLHUh2DaLXo9PN/9VmTWYzTkQDv5JehmifXVI0esophXcCIfbdIu6hbt7/aHlDF4A==}
|
||||
|
||||
@@ -2972,12 +2981,12 @@ packages:
|
||||
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
openai@5.23.2:
|
||||
resolution: {integrity: sha512-MQBzmTulj+MM5O8SKEk/gL8a7s5mktS9zUtAkU257WjvobGc9nKcBuVwjyEEcb9SI8a8Y2G/mzn3vm9n1Jlleg==}
|
||||
openai@6.16.0:
|
||||
resolution: {integrity: sha512-fZ1uBqjFUjXzbGc35fFtYKEOxd20kd9fDpFeqWtsOZWiubY8CZ1NAlXHW3iathaFvqmNtCWMIsosCuyeI7Joxg==}
|
||||
hasBin: true
|
||||
peerDependencies:
|
||||
ws: ^8.18.0
|
||||
zod: ^3.23.8
|
||||
zod: ^3.25 || ^4.0
|
||||
peerDependenciesMeta:
|
||||
ws:
|
||||
optional: true
|
||||
@@ -3293,8 +3302,9 @@ packages:
|
||||
safer-buffer@2.1.2:
|
||||
resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}
|
||||
|
||||
sax@1.4.3:
|
||||
resolution: {integrity: sha512-yqYn1JhPczigF94DMS+shiDMjDowYO6y9+wB/4WgO0Y19jWYk0lQ4tuG5KI7kj4FTp1wxPj5IFfcrz/s1c3jjQ==}
|
||||
sax@1.4.4:
|
||||
resolution: {integrity: sha512-1n3r/tGXO6b6VXMdFT54SHzT9ytu9yr7TaELowdYpMqY/Ao7EnlQGmAQ1+RatX7Tkkdm6hONI2owqNx2aZj5Sw==}
|
||||
engines: {node: '>=11.0.0'}
|
||||
|
||||
semver@6.3.1:
|
||||
resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}
|
||||
@@ -3732,6 +3742,11 @@ packages:
|
||||
resolution: {integrity: sha512-Ow9nuGZE+qp1u4JIPvg+uCiUr7xGQWdff7JQSk5VGYTAZMDe2q8lxJ10ygv10qmSj031Ty/6FNJpLO4o1Sgc+w==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
zod-to-json-schema@3.25.1:
|
||||
resolution: {integrity: sha512-pM/SU9d3YAggzi6MtR4h7ruuQlqKtad8e9S0fmxcMi+ueAK5Korys/aWcV9LIIHTVbj01NdzxcnXSN+O74ZIVA==}
|
||||
peerDependencies:
|
||||
zod: ^3.25 || ^4
|
||||
|
||||
zod@3.25.76:
|
||||
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
|
||||
|
||||
@@ -3740,7 +3755,7 @@ packages:
|
||||
|
||||
snapshots:
|
||||
|
||||
'@anthropic-ai/sdk@0.65.0(zod@3.25.76)':
|
||||
'@anthropic-ai/sdk@0.71.2(zod@3.25.76)':
|
||||
dependencies:
|
||||
json-schema-to-ts: 3.1.1
|
||||
optionalDependencies:
|
||||
@@ -4891,6 +4906,11 @@ snapshots:
|
||||
dependencies:
|
||||
'@lit-labs/ssr-dom-shim': 1.4.0
|
||||
|
||||
'@mistralai/mistralai@1.12.0':
|
||||
dependencies:
|
||||
zod: 3.25.76
|
||||
zod-to-json-schema: 3.25.1(zod@3.25.76)
|
||||
|
||||
'@mixmark-io/domino@2.2.0': {}
|
||||
|
||||
'@module-federation/error-codes@0.21.6': {}
|
||||
@@ -5138,17 +5158,18 @@ snapshots:
|
||||
'@push.rocks/smartlog': 3.1.10
|
||||
'@push.rocks/smartpath': 6.0.0
|
||||
|
||||
'@push.rocks/smartai@0.8.0(typescript@5.9.3)(ws@8.18.3)(zod@3.25.76)':
|
||||
'@push.rocks/smartai@0.12.0(typescript@5.9.3)(ws@8.18.3)(zod@3.25.76)':
|
||||
dependencies:
|
||||
'@anthropic-ai/sdk': 0.65.0(zod@3.25.76)
|
||||
'@anthropic-ai/sdk': 0.71.2(zod@3.25.76)
|
||||
'@mistralai/mistralai': 1.12.0
|
||||
'@push.rocks/smartarray': 1.1.0
|
||||
'@push.rocks/smartfile': 11.2.7
|
||||
'@push.rocks/smartfs': 1.3.1
|
||||
'@push.rocks/smartpath': 6.0.0
|
||||
'@push.rocks/smartpdf': 4.1.1(typescript@5.9.3)
|
||||
'@push.rocks/smartpromise': 4.2.3
|
||||
'@push.rocks/smartrequest': 4.4.2
|
||||
'@push.rocks/smartrequest': 5.0.1
|
||||
'@push.rocks/webstream': 1.0.10
|
||||
openai: 5.23.2(ws@8.18.3)(zod@3.25.76)
|
||||
openai: 6.16.0(ws@8.18.3)(zod@3.25.76)
|
||||
transitivePeerDependencies:
|
||||
- '@nuxt/kit'
|
||||
- aws-crt
|
||||
@@ -5444,6 +5465,10 @@ snapshots:
|
||||
dependencies:
|
||||
'@push.rocks/smartpath': 6.0.0
|
||||
|
||||
'@push.rocks/smartfs@1.3.1':
|
||||
dependencies:
|
||||
'@push.rocks/smartpath': 6.0.0
|
||||
|
||||
'@push.rocks/smartguard@3.1.0':
|
||||
dependencies:
|
||||
'@push.rocks/smartpromise': 4.2.3
|
||||
@@ -8151,7 +8176,7 @@ snapshots:
|
||||
is-docker: 2.2.1
|
||||
is-wsl: 2.2.0
|
||||
|
||||
openai@5.23.2(ws@8.18.3)(zod@3.25.76):
|
||||
openai@6.16.0(ws@8.18.3)(zod@3.25.76):
|
||||
optionalDependencies:
|
||||
ws: 8.18.3
|
||||
zod: 3.25.76
|
||||
@@ -8522,7 +8547,7 @@ snapshots:
|
||||
|
||||
safer-buffer@2.1.2: {}
|
||||
|
||||
sax@1.4.3: {}
|
||||
sax@1.4.4: {}
|
||||
|
||||
semver@6.3.1: {}
|
||||
|
||||
@@ -8999,7 +9024,7 @@ snapshots:
|
||||
|
||||
xml2js@0.5.0:
|
||||
dependencies:
|
||||
sax: 1.4.3
|
||||
sax: 1.4.4
|
||||
xmlbuilder: 11.0.1
|
||||
|
||||
xmlbuilder@11.0.1: {}
|
||||
@@ -9034,6 +9059,10 @@ snapshots:
|
||||
buffer-crc32: 0.2.13
|
||||
pend: 1.2.0
|
||||
|
||||
zod-to-json-schema@3.25.1(zod@3.25.76):
|
||||
dependencies:
|
||||
zod: 3.25.76
|
||||
|
||||
zod@3.25.76: {}
|
||||
|
||||
zwitch@2.0.4: {}
|
||||
|
||||
184
readme.md
184
readme.md
@@ -1,21 +1,31 @@
|
||||
# @push.rocks/smartagent
|
||||
A dual-agent agentic framework with Driver and Guardian agents for safe, policy-controlled AI task execution.
|
||||
|
||||
A dual-agent agentic framework with **Driver** and **Guardian** agents for safe, policy-controlled AI task execution. 🤖🛡️
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartagent
|
||||
# or
|
||||
pnpm install @push.rocks/smartagent
|
||||
```
|
||||
|
||||
## Issue Reporting and Security
|
||||
|
||||
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://community.foss.global/). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/](https://code.foss.global/) account to submit Pull Requests directly.
|
||||
|
||||
## Overview
|
||||
|
||||
SmartAgent implements a dual-agent architecture:
|
||||
SmartAgent implements a **dual-agent architecture** where AI safety isn't just an afterthought—it's baked into the core design:
|
||||
|
||||
- **Driver Agent**: Executes tasks, reasons about goals, and proposes tool calls
|
||||
- **Guardian Agent**: Evaluates tool call proposals against a policy prompt, approving or rejecting with feedback
|
||||
- **🎯 Driver Agent**: The executor. Reasons about goals, plans steps, and proposes tool calls
|
||||
- **🛡️ Guardian Agent**: The gatekeeper. Evaluates every tool call against your policy, approving or rejecting with feedback
|
||||
|
||||
This design ensures safe tool use through AI-based policy evaluation rather than rigid programmatic rules.
|
||||
This design ensures safe tool use through **AI-based policy evaluation** rather than rigid programmatic rules. The Guardian can understand context, nuance, and intent—catching dangerous operations that simple regex or allowlists would miss.
|
||||
|
||||
### Why Dual-Agent?
|
||||
|
||||
Traditional AI agents have a fundamental problem: they're given tools and expected to use them responsibly. SmartAgent adds a second AI specifically trained to evaluate whether each action is safe and appropriate. Think of it as separation of concerns, but for AI safety.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -89,8 +99,11 @@ await orchestrator.stop();
|
||||
|
||||
## Standard Tools
|
||||
|
||||
### FilesystemTool
|
||||
File and directory operations using `@push.rocks/smartfs`.
|
||||
SmartAgent comes with five battle-tested tools out of the box:
|
||||
|
||||
### 🗂️ FilesystemTool
|
||||
|
||||
File and directory operations powered by `@push.rocks/smartfs`.
|
||||
|
||||
**Actions**: `read`, `write`, `append`, `list`, `delete`, `exists`, `stat`, `copy`, `move`, `mkdir`
|
||||
|
||||
@@ -104,7 +117,15 @@ File and directory operations using `@push.rocks/smartfs`.
|
||||
</tool_call>
|
||||
```
|
||||
|
||||
### HttpTool
|
||||
**Scoped Filesystem**: Lock file operations to a specific directory:
|
||||
|
||||
```typescript
|
||||
// Only allow access within a specific directory
|
||||
orchestrator.registerScopedFilesystemTool('/home/user/workspace');
|
||||
```
|
||||
|
||||
### 🌐 HttpTool
|
||||
|
||||
HTTP requests using `@push.rocks/smartrequest`.
|
||||
|
||||
**Actions**: `get`, `post`, `put`, `patch`, `delete`
|
||||
@@ -113,13 +134,14 @@ HTTP requests using `@push.rocks/smartrequest`.
|
||||
<tool_call>
|
||||
<tool>http</tool>
|
||||
<action>get</action>
|
||||
<params>{"url": "https://api.example.com/data"}</params>
|
||||
<params>{"url": "https://api.example.com/data", "headers": {"Authorization": "Bearer token"}}</params>
|
||||
<reasoning>Fetching data from the API endpoint</reasoning>
|
||||
</tool_call>
|
||||
```
|
||||
|
||||
### ShellTool
|
||||
Secure shell command execution using `@push.rocks/smartshell` with `execSpawn` (no shell injection).
|
||||
### 💻 ShellTool
|
||||
|
||||
Secure shell command execution using `@push.rocks/smartshell` with `execSpawn` (no shell injection possible).
|
||||
|
||||
**Actions**: `execute`, `which`
|
||||
|
||||
@@ -132,7 +154,10 @@ Secure shell command execution using `@push.rocks/smartshell` with `execSpawn` (
|
||||
</tool_call>
|
||||
```
|
||||
|
||||
### BrowserTool
|
||||
> 🔒 **Security Note**: The shell tool uses `execSpawn` with `shell: false`, meaning command and arguments are passed separately. This makes shell injection attacks impossible.
|
||||
|
||||
### 🌍 BrowserTool
|
||||
|
||||
Web page interaction using `@push.rocks/smartbrowser` (Puppeteer-based).
|
||||
|
||||
**Actions**: `screenshot`, `pdf`, `evaluate`, `getPageContent`
|
||||
@@ -146,17 +171,18 @@ Web page interaction using `@push.rocks/smartbrowser` (Puppeteer-based).
|
||||
</tool_call>
|
||||
```
|
||||
|
||||
### DenoTool
|
||||
Execute TypeScript/JavaScript code in a sandboxed Deno environment using `@push.rocks/smartdeno`.
|
||||
### 🦕 DenoTool
|
||||
|
||||
Execute TypeScript/JavaScript code in a **sandboxed Deno environment** with fine-grained permission control.
|
||||
|
||||
**Actions**: `execute`, `executeWithResult`
|
||||
|
||||
**Permissions**: `all`, `env`, `ffi`, `hrtime`, `net`, `read`, `run`, `sys`, `write`
|
||||
|
||||
By default, code runs fully sandboxed with no permissions. Permissions must be explicitly requested.
|
||||
By default, code runs **fully sandboxed with no permissions**. Permissions must be explicitly requested and are subject to Guardian approval.
|
||||
|
||||
```typescript
|
||||
// Simple code execution
|
||||
// Simple code execution (sandboxed, no permissions)
|
||||
<tool_call>
|
||||
<tool>deno</tool>
|
||||
<action>execute</action>
|
||||
@@ -188,7 +214,10 @@ By default, code runs fully sandboxed with no permissions. Permissions must be e
|
||||
|
||||
## Guardian Policy Examples
|
||||
|
||||
### Strict Security Policy
|
||||
The Guardian's power comes from your policy. Here are battle-tested examples:
|
||||
|
||||
### 🔐 Strict Security Policy
|
||||
|
||||
```typescript
|
||||
const securityPolicy = `
|
||||
SECURITY POLICY:
|
||||
@@ -204,7 +233,8 @@ When rejecting, always explain:
|
||||
`;
|
||||
```
|
||||
|
||||
### Development Environment Policy
|
||||
### 🛠️ Development Environment Policy
|
||||
|
||||
```typescript
|
||||
const devPolicy = `
|
||||
DEVELOPMENT POLICY:
|
||||
@@ -221,7 +251,8 @@ Always verify:
|
||||
`;
|
||||
```
|
||||
|
||||
### Deno Code Execution Policy
|
||||
### 🦕 Deno Code Execution Policy
|
||||
|
||||
```typescript
|
||||
const denoPolicy = `
|
||||
DENO CODE EXECUTION POLICY:
|
||||
@@ -253,6 +284,9 @@ interface IDualAgentOptions {
|
||||
groqToken?: string;
|
||||
xaiToken?: string;
|
||||
|
||||
// Use existing SmartAi instance (optional - avoids duplicate providers)
|
||||
smartAiInstance?: SmartAi;
|
||||
|
||||
// Provider selection
|
||||
defaultProvider?: TProvider; // For both Driver and Guardian
|
||||
guardianProvider?: TProvider; // Optional: separate provider for Guardian
|
||||
@@ -278,6 +312,14 @@ interface IDualAgentRunResult {
|
||||
history: IAgentMessage[]; // Full conversation history
|
||||
status: TDualAgentRunStatus; // 'completed' | 'max_iterations_reached' | etc.
|
||||
}
|
||||
|
||||
type TDualAgentRunStatus =
|
||||
| 'completed'
|
||||
| 'in_progress'
|
||||
| 'max_iterations_reached'
|
||||
| 'max_rejections_reached'
|
||||
| 'clarification_needed'
|
||||
| 'error';
|
||||
```
|
||||
|
||||
## Custom Tools
|
||||
@@ -306,10 +348,12 @@ class MyCustomTool extends BaseToolWrapper {
|
||||
];
|
||||
|
||||
public async initialize(): Promise<void> {
|
||||
// Setup your tool (called when orchestrator.start() runs)
|
||||
this.isInitialized = true;
|
||||
}
|
||||
|
||||
public async cleanup(): Promise<void> {
|
||||
// Cleanup resources (called when orchestrator.stop() runs)
|
||||
this.isInitialized = false;
|
||||
}
|
||||
|
||||
@@ -327,6 +371,7 @@ class MyCustomTool extends BaseToolWrapper {
|
||||
return { success: false, error: 'Unknown action' };
|
||||
}
|
||||
|
||||
// Human-readable summary for Guardian evaluation
|
||||
public getCallSummary(action: string, params: Record<string, unknown>): string {
|
||||
return `Custom action "${action}" with input "${params.input}"`;
|
||||
}
|
||||
@@ -336,32 +381,111 @@ class MyCustomTool extends BaseToolWrapper {
|
||||
orchestrator.registerTool(new MyCustomTool());
|
||||
```
|
||||
|
||||
## Reusing SmartAi Instances
|
||||
|
||||
If you already have a `@push.rocks/smartai` instance, you can share it:
|
||||
|
||||
```typescript
|
||||
import { SmartAi } from '@push.rocks/smartai';
|
||||
import { DualAgentOrchestrator } from '@push.rocks/smartagent';
|
||||
|
||||
const smartai = new SmartAi({ openaiToken: 'sk-...' });
|
||||
await smartai.start();
|
||||
|
||||
const orchestrator = new DualAgentOrchestrator({
|
||||
smartAiInstance: smartai, // Reuse existing instance
|
||||
guardianPolicyPrompt: '...',
|
||||
});
|
||||
|
||||
await orchestrator.start();
|
||||
// ... use orchestrator ...
|
||||
await orchestrator.stop();
|
||||
|
||||
// SmartAi instance lifecycle is managed separately
|
||||
await smartai.stop();
|
||||
```
|
||||
|
||||
## Supported Providers
|
||||
|
||||
SmartAgent supports all providers from `@push.rocks/smartai`:
|
||||
|
||||
| Provider | Driver | Guardian |
|
||||
|----------|:------:|:--------:|
|
||||
| OpenAI | Yes | Yes |
|
||||
| Anthropic | Yes | Yes |
|
||||
| Perplexity | Yes | Yes |
|
||||
| Groq | Yes | Yes |
|
||||
| Ollama | Yes | Yes |
|
||||
| XAI | Yes | Yes |
|
||||
| OpenAI | ✅ | ✅ |
|
||||
| Anthropic | ✅ | ✅ |
|
||||
| Perplexity | ✅ | ✅ |
|
||||
| Groq | ✅ | ✅ |
|
||||
| Ollama | ✅ | ✅ |
|
||||
| XAI | ✅ | ✅ |
|
||||
| Exo | ✅ | ✅ |
|
||||
|
||||
**💡 Pro tip**: Use a faster/cheaper model for Guardian (like Groq) and a more capable model for Driver:
|
||||
|
||||
```typescript
|
||||
const orchestrator = new DualAgentOrchestrator({
|
||||
openaiToken: 'sk-...',
|
||||
groqToken: 'gsk-...',
|
||||
defaultProvider: 'openai', // Driver uses OpenAI
|
||||
guardianProvider: 'groq', // Guardian uses Groq (faster, cheaper)
|
||||
guardianPolicyPrompt: '...',
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### DualAgentOrchestrator
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `start()` | Initialize all tools and AI providers |
|
||||
| `stop()` | Cleanup all tools and resources |
|
||||
| `run(task: string)` | Execute a task and return result |
|
||||
| `continueTask(input: string)` | Continue a task with user input |
|
||||
| `registerTool(tool)` | Register a custom tool |
|
||||
| `registerStandardTools()` | Register all built-in tools |
|
||||
| `registerScopedFilesystemTool(basePath)` | Register filesystem tool with path restriction |
|
||||
| `setGuardianPolicy(policy)` | Update Guardian policy at runtime |
|
||||
| `getHistory()` | Get conversation history |
|
||||
| `getToolNames()` | Get list of registered tool names |
|
||||
| `isActive()` | Check if orchestrator is running |
|
||||
|
||||
### Exports
|
||||
|
||||
```typescript
|
||||
// Main classes
|
||||
export { DualAgentOrchestrator } from '@push.rocks/smartagent';
|
||||
export { DriverAgent } from '@push.rocks/smartagent';
|
||||
export { GuardianAgent } from '@push.rocks/smartagent';
|
||||
|
||||
// Tools
|
||||
export { BaseToolWrapper } from '@push.rocks/smartagent';
|
||||
export { FilesystemTool } from '@push.rocks/smartagent';
|
||||
export { HttpTool } from '@push.rocks/smartagent';
|
||||
export { ShellTool } from '@push.rocks/smartagent';
|
||||
export { BrowserTool } from '@push.rocks/smartagent';
|
||||
export { DenoTool } from '@push.rocks/smartagent';
|
||||
|
||||
// Types and interfaces
|
||||
export * from '@push.rocks/smartagent'; // All interfaces
|
||||
```
|
||||
|
||||
## License and Legal Information
|
||||
|
||||
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
|
||||
|
||||
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
||||
|
||||
### Trademarks
|
||||
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
|
||||
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein.
|
||||
|
||||
Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
|
||||
|
||||
### Company Information
|
||||
|
||||
Task Venture Capital GmbH
|
||||
Registered at District court Bremen HRB 35230 HB, Germany
|
||||
Task Venture Capital GmbH
|
||||
Registered at District Court Bremen HRB 35230 HB, Germany
|
||||
|
||||
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc.
|
||||
For any legal inquiries or further information, please contact us via email at hello@task.vc.
|
||||
|
||||
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartagent',
|
||||
version: '1.1.1',
|
||||
version: '1.3.0',
|
||||
description: 'an agentic framework built on top of @push.rocks/smartai'
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export { HttpTool } from './smartagent.tools.http.js';
|
||||
export { ShellTool } from './smartagent.tools.shell.js';
|
||||
export { BrowserTool } from './smartagent.tools.browser.js';
|
||||
export { DenoTool, type TDenoPermission } from './smartagent.tools.deno.js';
|
||||
export { JsonValidatorTool } from './smartagent.tools.json.js';
|
||||
|
||||
// Export all interfaces
|
||||
export * from './smartagent.interfaces.js';
|
||||
|
||||
@@ -3,6 +3,11 @@ import * as path from 'path';
|
||||
|
||||
export { path };
|
||||
|
||||
// third party
|
||||
import { minimatch } from 'minimatch';
|
||||
|
||||
export { minimatch };
|
||||
|
||||
// @push.rocks scope
|
||||
import * as smartai from '@push.rocks/smartai';
|
||||
import * as smartdeno from '@push.rocks/smartdeno';
|
||||
|
||||
@@ -2,6 +2,18 @@ import * as plugins from './plugins.js';
|
||||
import * as interfaces from './smartagent.interfaces.js';
|
||||
import type { BaseToolWrapper } from './smartagent.tools.base.js';
|
||||
|
||||
/**
|
||||
* Options for configuring the DriverAgent
|
||||
*/
|
||||
export interface IDriverAgentOptions {
|
||||
/** Custom system message for the driver */
|
||||
systemMessage?: string;
|
||||
/** Maximum history messages to pass to API (default: 20). Set to 0 for unlimited. */
|
||||
maxHistoryMessages?: number;
|
||||
/** Callback fired for each token during LLM generation */
|
||||
onToken?: (token: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* DriverAgent - Executes tasks by reasoning and proposing tool calls
|
||||
* Works in conjunction with GuardianAgent for approval
|
||||
@@ -9,15 +21,34 @@ import type { BaseToolWrapper } from './smartagent.tools.base.js';
|
||||
export class DriverAgent {
|
||||
private provider: plugins.smartai.MultiModalModel;
|
||||
private systemMessage: string;
|
||||
private maxHistoryMessages: number;
|
||||
private messageHistory: plugins.smartai.ChatMessage[] = [];
|
||||
private tools: Map<string, BaseToolWrapper> = new Map();
|
||||
private onToken?: (token: string) => void;
|
||||
|
||||
constructor(
|
||||
provider: plugins.smartai.MultiModalModel,
|
||||
systemMessage?: string
|
||||
options?: IDriverAgentOptions | string
|
||||
) {
|
||||
this.provider = provider;
|
||||
this.systemMessage = systemMessage || this.getDefaultSystemMessage();
|
||||
|
||||
// Support both legacy string systemMessage and new options object
|
||||
if (typeof options === 'string') {
|
||||
this.systemMessage = options || this.getDefaultSystemMessage();
|
||||
this.maxHistoryMessages = 20;
|
||||
} else {
|
||||
this.systemMessage = options?.systemMessage || this.getDefaultSystemMessage();
|
||||
this.maxHistoryMessages = options?.maxHistoryMessages ?? 20;
|
||||
this.onToken = options?.onToken;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the token callback for streaming mode
|
||||
* @param callback Function to call for each generated token
|
||||
*/
|
||||
public setOnToken(callback: (token: string) => void): void {
|
||||
this.onToken = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,8 +67,10 @@ export class DriverAgent {
|
||||
|
||||
/**
|
||||
* Initialize a new conversation for a task
|
||||
* @param task The task description
|
||||
* @param images Optional base64-encoded images for vision tasks
|
||||
*/
|
||||
public async startTask(task: string): Promise<interfaces.IAgentMessage> {
|
||||
public async startTask(task: string, images?: string[]): Promise<interfaces.IAgentMessage> {
|
||||
// Reset message history
|
||||
this.messageHistory = [];
|
||||
|
||||
@@ -66,18 +99,34 @@ export class DriverAgent {
|
||||
fullSystemMessage = this.getNoToolsSystemMessage();
|
||||
}
|
||||
|
||||
// Get response from provider
|
||||
const response = await this.provider.chat({
|
||||
systemMessage: fullSystemMessage,
|
||||
userMessage: userMessage,
|
||||
messageHistory: [],
|
||||
});
|
||||
// Get response from provider - use streaming if available and callback is set
|
||||
let response: plugins.smartai.ChatResponse;
|
||||
|
||||
// Add assistant response to history
|
||||
this.messageHistory.push({
|
||||
if (this.onToken && typeof (this.provider as any).chatStreaming === 'function') {
|
||||
// Use streaming mode with token callback
|
||||
response = await (this.provider as any).chatStreaming({
|
||||
systemMessage: fullSystemMessage,
|
||||
userMessage: userMessage,
|
||||
messageHistory: [],
|
||||
images: images,
|
||||
onToken: this.onToken,
|
||||
});
|
||||
} else {
|
||||
// Fallback to non-streaming mode
|
||||
response = await this.provider.chat({
|
||||
systemMessage: fullSystemMessage,
|
||||
userMessage: userMessage,
|
||||
messageHistory: [],
|
||||
images: images,
|
||||
});
|
||||
}
|
||||
|
||||
// Add assistant response to history (store images if provided)
|
||||
const historyMessage: plugins.smartai.ChatMessage = {
|
||||
role: 'assistant',
|
||||
content: response.message,
|
||||
});
|
||||
};
|
||||
this.messageHistory.push(historyMessage);
|
||||
|
||||
return {
|
||||
role: 'assistant',
|
||||
@@ -105,14 +154,40 @@ export class DriverAgent {
|
||||
fullSystemMessage = this.getNoToolsSystemMessage();
|
||||
}
|
||||
|
||||
// Get response from provider (pass all but last user message as history)
|
||||
const historyForChat = this.messageHistory.slice(0, -1);
|
||||
// Get response from provider with history windowing
|
||||
// Keep original task and most recent messages to avoid token explosion
|
||||
let historyForChat: plugins.smartai.ChatMessage[];
|
||||
const fullHistory = this.messageHistory.slice(0, -1); // Exclude the just-added message
|
||||
|
||||
const response = await this.provider.chat({
|
||||
systemMessage: fullSystemMessage,
|
||||
userMessage: message,
|
||||
messageHistory: historyForChat,
|
||||
});
|
||||
if (this.maxHistoryMessages > 0 && fullHistory.length > this.maxHistoryMessages) {
|
||||
// Keep the original task (first message) and most recent messages
|
||||
historyForChat = [
|
||||
fullHistory[0], // Original task
|
||||
...fullHistory.slice(-(this.maxHistoryMessages - 1)), // Recent messages
|
||||
];
|
||||
} else {
|
||||
historyForChat = fullHistory;
|
||||
}
|
||||
|
||||
// Get response from provider - use streaming if available and callback is set
|
||||
let response: plugins.smartai.ChatResponse;
|
||||
|
||||
if (this.onToken && typeof (this.provider as any).chatStreaming === 'function') {
|
||||
// Use streaming mode with token callback
|
||||
response = await (this.provider as any).chatStreaming({
|
||||
systemMessage: fullSystemMessage,
|
||||
userMessage: message,
|
||||
messageHistory: historyForChat,
|
||||
onToken: this.onToken,
|
||||
});
|
||||
} else {
|
||||
// Fallback to non-streaming mode
|
||||
response = await this.provider.chat({
|
||||
systemMessage: fullSystemMessage,
|
||||
userMessage: message,
|
||||
messageHistory: historyForChat,
|
||||
});
|
||||
}
|
||||
|
||||
// Add assistant response to history
|
||||
this.messageHistory.push({
|
||||
|
||||
@@ -30,6 +30,8 @@ export class DualAgentOrchestrator {
|
||||
maxIterations: 20,
|
||||
maxConsecutiveRejections: 3,
|
||||
defaultProvider: 'openai',
|
||||
maxResultChars: 15000,
|
||||
maxHistoryMessages: 20,
|
||||
...options,
|
||||
};
|
||||
|
||||
@@ -68,6 +70,60 @@ export class DualAgentOrchestrator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emit a progress event if callback is configured
|
||||
*/
|
||||
private emitProgress(event: Omit<interfaces.IProgressEvent, 'timestamp' | 'logLevel' | 'logMessage'>): void {
|
||||
if (this.options.onProgress) {
|
||||
const prefix = this.options.logPrefix ? `${this.options.logPrefix} ` : '';
|
||||
const { logLevel, logMessage } = this.formatProgressEvent(event, prefix);
|
||||
|
||||
this.options.onProgress({
|
||||
...event,
|
||||
timestamp: new Date(),
|
||||
logLevel,
|
||||
logMessage,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a progress event into a log level and message
|
||||
*/
|
||||
private formatProgressEvent(
|
||||
event: Omit<interfaces.IProgressEvent, 'timestamp' | 'logLevel' | 'logMessage'>,
|
||||
prefix: string
|
||||
): { logLevel: interfaces.TLogLevel; logMessage: string } {
|
||||
switch (event.type) {
|
||||
case 'task_started':
|
||||
return { logLevel: 'info', logMessage: `${prefix}Task started` };
|
||||
case 'iteration_started':
|
||||
return { logLevel: 'info', logMessage: `${prefix}Iteration ${event.iteration}/${event.maxIterations}` };
|
||||
case 'tool_proposed':
|
||||
return { logLevel: 'info', logMessage: `${prefix} → Proposing: ${event.toolName}.${event.action}` };
|
||||
case 'guardian_evaluating':
|
||||
return { logLevel: 'info', logMessage: `${prefix} ⏳ Guardian evaluating...` };
|
||||
case 'tool_approved':
|
||||
return { logLevel: 'info', logMessage: `${prefix} ✓ Approved: ${event.toolName}.${event.action}` };
|
||||
case 'tool_rejected':
|
||||
return { logLevel: 'warn', logMessage: `${prefix} ✗ Rejected: ${event.toolName}.${event.action} - ${event.reason}` };
|
||||
case 'tool_executing':
|
||||
return { logLevel: 'info', logMessage: `${prefix} ⚡ Executing: ${event.toolName}.${event.action}...` };
|
||||
case 'tool_completed':
|
||||
return { logLevel: 'info', logMessage: `${prefix} ✓ Completed: ${event.message}` };
|
||||
case 'task_completed':
|
||||
return { logLevel: 'success', logMessage: `${prefix}Task completed in ${event.iteration} iterations` };
|
||||
case 'clarification_needed':
|
||||
return { logLevel: 'warn', logMessage: `${prefix}Clarification needed from user` };
|
||||
case 'max_iterations':
|
||||
return { logLevel: 'error', logMessage: `${prefix}${event.message}` };
|
||||
case 'max_rejections':
|
||||
return { logLevel: 'error', logMessage: `${prefix}${event.message}` };
|
||||
default:
|
||||
return { logLevel: 'info', logMessage: `${prefix}${event.type}` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom tool
|
||||
*/
|
||||
@@ -102,9 +158,10 @@ export class DualAgentOrchestrator {
|
||||
/**
|
||||
* Register a scoped filesystem tool that can only access files within the specified directory
|
||||
* @param basePath The directory to scope filesystem operations to
|
||||
* @param excludePatterns Optional glob patterns to exclude from listings (e.g., ['.nogit/**', 'node_modules/**'])
|
||||
*/
|
||||
public registerScopedFilesystemTool(basePath: string): void {
|
||||
const scopedTool = new FilesystemTool({ basePath });
|
||||
public registerScopedFilesystemTool(basePath: string, excludePatterns?: string[]): void {
|
||||
const scopedTool = new FilesystemTool({ basePath, excludePatterns });
|
||||
this.registerTool(scopedTool);
|
||||
}
|
||||
|
||||
@@ -124,7 +181,16 @@ export class DualAgentOrchestrator {
|
||||
: this.driverProvider;
|
||||
|
||||
// NOW create agents with initialized providers
|
||||
this.driver = new DriverAgent(this.driverProvider, this.options.driverSystemMessage);
|
||||
// Set up token callback wrapper if streaming is enabled
|
||||
const driverOnToken = this.options.onToken
|
||||
? (token: string) => this.options.onToken!(token, 'driver')
|
||||
: undefined;
|
||||
|
||||
this.driver = new DriverAgent(this.driverProvider, {
|
||||
systemMessage: this.options.driverSystemMessage,
|
||||
maxHistoryMessages: this.options.maxHistoryMessages,
|
||||
onToken: driverOnToken,
|
||||
});
|
||||
this.guardian = new GuardianAgent(this.guardianProvider, this.options.guardianPolicyPrompt);
|
||||
|
||||
// Register any tools that were added before start() with the agents
|
||||
@@ -168,8 +234,10 @@ export class DualAgentOrchestrator {
|
||||
|
||||
/**
|
||||
* Run a task through the dual-agent system
|
||||
* @param task The task description
|
||||
* @param options Optional task run options (e.g., images for vision tasks)
|
||||
*/
|
||||
public async run(task: string): Promise<interfaces.IDualAgentRunResult> {
|
||||
public async run(task: string, options?: interfaces.ITaskRunOptions): Promise<interfaces.IDualAgentRunResult> {
|
||||
if (!this.isRunning) {
|
||||
throw new Error('Orchestrator not started. Call start() first.');
|
||||
}
|
||||
@@ -180,16 +248,25 @@ export class DualAgentOrchestrator {
|
||||
let completed = false;
|
||||
let finalResult: string | null = null;
|
||||
|
||||
// Extract images from options
|
||||
const images = options?.images;
|
||||
|
||||
// Add initial task to history
|
||||
this.conversationHistory.push({
|
||||
role: 'user',
|
||||
content: task,
|
||||
});
|
||||
|
||||
// Start the driver with the task
|
||||
let driverResponse = await this.driver.startTask(task);
|
||||
// Start the driver with the task and optional images
|
||||
let driverResponse = await this.driver.startTask(task, images);
|
||||
this.conversationHistory.push(driverResponse);
|
||||
|
||||
// Emit task started event
|
||||
this.emitProgress({
|
||||
type: 'task_started',
|
||||
message: task.length > 100 ? task.substring(0, 100) + '...' : task,
|
||||
});
|
||||
|
||||
while (
|
||||
iterations < this.options.maxIterations! &&
|
||||
consecutiveRejections < this.options.maxConsecutiveRejections! &&
|
||||
@@ -197,15 +274,36 @@ export class DualAgentOrchestrator {
|
||||
) {
|
||||
iterations++;
|
||||
|
||||
// Emit iteration started event
|
||||
this.emitProgress({
|
||||
type: 'iteration_started',
|
||||
iteration: iterations,
|
||||
maxIterations: this.options.maxIterations,
|
||||
});
|
||||
|
||||
// Check if task is complete
|
||||
if (this.driver.isTaskComplete(driverResponse.content)) {
|
||||
completed = true;
|
||||
finalResult = this.driver.extractTaskResult(driverResponse.content) || driverResponse.content;
|
||||
|
||||
// Emit task completed event
|
||||
this.emitProgress({
|
||||
type: 'task_completed',
|
||||
iteration: iterations,
|
||||
message: 'Task completed successfully',
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
// Check if driver needs clarification
|
||||
if (this.driver.needsClarification(driverResponse.content)) {
|
||||
// Emit clarification needed event
|
||||
this.emitProgress({
|
||||
type: 'clarification_needed',
|
||||
iteration: iterations,
|
||||
message: 'Driver needs clarification from user',
|
||||
});
|
||||
|
||||
// Return with clarification needed status
|
||||
return {
|
||||
success: false,
|
||||
@@ -232,6 +330,15 @@ export class DualAgentOrchestrator {
|
||||
// Process the first proposal (one at a time)
|
||||
const proposal = proposals[0];
|
||||
|
||||
// Emit tool proposed event
|
||||
this.emitProgress({
|
||||
type: 'tool_proposed',
|
||||
iteration: iterations,
|
||||
toolName: proposal.toolName,
|
||||
action: proposal.action,
|
||||
message: `${proposal.toolName}.${proposal.action}`,
|
||||
});
|
||||
|
||||
// Quick validation first
|
||||
const quickDecision = this.guardian.quickValidate(proposal);
|
||||
let decision: interfaces.IGuardianDecision;
|
||||
@@ -239,6 +346,14 @@ export class DualAgentOrchestrator {
|
||||
if (quickDecision) {
|
||||
decision = quickDecision;
|
||||
} else {
|
||||
// Emit guardian evaluating event
|
||||
this.emitProgress({
|
||||
type: 'guardian_evaluating',
|
||||
iteration: iterations,
|
||||
toolName: proposal.toolName,
|
||||
action: proposal.action,
|
||||
});
|
||||
|
||||
// Full AI evaluation
|
||||
decision = await this.guardian.evaluate(proposal, task);
|
||||
}
|
||||
@@ -246,6 +361,14 @@ export class DualAgentOrchestrator {
|
||||
if (decision.decision === 'approve') {
|
||||
consecutiveRejections = 0;
|
||||
|
||||
// Emit tool approved event
|
||||
this.emitProgress({
|
||||
type: 'tool_approved',
|
||||
iteration: iterations,
|
||||
toolName: proposal.toolName,
|
||||
action: proposal.action,
|
||||
});
|
||||
|
||||
// Execute the tool
|
||||
const tool = this.tools.get(proposal.toolName);
|
||||
if (!tool) {
|
||||
@@ -258,12 +381,48 @@ export class DualAgentOrchestrator {
|
||||
}
|
||||
|
||||
try {
|
||||
// Emit tool executing event
|
||||
this.emitProgress({
|
||||
type: 'tool_executing',
|
||||
iteration: iterations,
|
||||
toolName: proposal.toolName,
|
||||
action: proposal.action,
|
||||
});
|
||||
|
||||
const result = await tool.execute(proposal.action, proposal.params);
|
||||
|
||||
// Send result to driver
|
||||
const resultMessage = result.success
|
||||
? `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${JSON.stringify(result.result, null, 2)}`
|
||||
: `TOOL ERROR (${proposal.toolName}.${proposal.action}):\n${result.error}`;
|
||||
// Emit tool completed event
|
||||
this.emitProgress({
|
||||
type: 'tool_completed',
|
||||
iteration: iterations,
|
||||
toolName: proposal.toolName,
|
||||
action: proposal.action,
|
||||
message: result.success ? 'success' : result.error,
|
||||
});
|
||||
|
||||
// Build result message (prefer summary if provided, otherwise stringify result)
|
||||
let resultMessage: string;
|
||||
if (result.success) {
|
||||
if (result.summary) {
|
||||
// Use tool-provided summary
|
||||
resultMessage = `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${result.summary}`;
|
||||
} else {
|
||||
// Stringify and potentially truncate
|
||||
const resultStr = JSON.stringify(result.result, null, 2);
|
||||
const maxChars = this.options.maxResultChars ?? 15000;
|
||||
|
||||
if (maxChars > 0 && resultStr.length > maxChars) {
|
||||
// Truncate the result
|
||||
const truncated = resultStr.substring(0, maxChars);
|
||||
const omittedTokens = Math.round((resultStr.length - maxChars) / 4);
|
||||
resultMessage = `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${truncated}\n\n[... output truncated, ~${omittedTokens} tokens omitted. Use more specific parameters to reduce output size.]`;
|
||||
} else {
|
||||
resultMessage = `TOOL RESULT (${proposal.toolName}.${proposal.action}):\n${resultStr}`;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
resultMessage = `TOOL ERROR (${proposal.toolName}.${proposal.action}):\n${result.error}`;
|
||||
}
|
||||
|
||||
this.conversationHistory.push({
|
||||
role: 'system',
|
||||
@@ -285,6 +444,15 @@ export class DualAgentOrchestrator {
|
||||
// Rejected
|
||||
consecutiveRejections++;
|
||||
|
||||
// Emit tool rejected event
|
||||
this.emitProgress({
|
||||
type: 'tool_rejected',
|
||||
iteration: iterations,
|
||||
toolName: proposal.toolName,
|
||||
action: proposal.action,
|
||||
reason: decision.reason,
|
||||
});
|
||||
|
||||
// Build rejection feedback
|
||||
let feedback = `TOOL CALL REJECTED by Guardian:\n`;
|
||||
feedback += `- Reason: ${decision.reason}\n`;
|
||||
@@ -316,8 +484,21 @@ export class DualAgentOrchestrator {
|
||||
if (!completed) {
|
||||
if (iterations >= this.options.maxIterations!) {
|
||||
status = 'max_iterations_reached';
|
||||
// Emit max iterations event
|
||||
this.emitProgress({
|
||||
type: 'max_iterations',
|
||||
iteration: iterations,
|
||||
maxIterations: this.options.maxIterations,
|
||||
message: `Maximum iterations (${this.options.maxIterations}) reached`,
|
||||
});
|
||||
} else if (consecutiveRejections >= this.options.maxConsecutiveRejections!) {
|
||||
status = 'max_rejections_reached';
|
||||
// Emit max rejections event
|
||||
this.emitProgress({
|
||||
type: 'max_rejections',
|
||||
iteration: iterations,
|
||||
message: `Maximum consecutive rejections (${this.options.maxConsecutiveRejections}) reached`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
// ================================
|
||||
// Task Run Options
|
||||
// ================================
|
||||
|
||||
/**
|
||||
* Options for running a task with the DualAgentOrchestrator
|
||||
*/
|
||||
export interface ITaskRunOptions {
|
||||
/** Base64-encoded images to include with the task (for vision-capable models) */
|
||||
images?: string[];
|
||||
}
|
||||
|
||||
// ================================
|
||||
// Agent Configuration Interfaces
|
||||
// ================================
|
||||
@@ -26,6 +38,16 @@ export interface IDualAgentOptions extends plugins.smartai.ISmartAiOptions {
|
||||
maxConsecutiveRejections?: number;
|
||||
/** Enable verbose logging */
|
||||
verbose?: boolean;
|
||||
/** Maximum characters for tool result output before truncation (default: 15000). Set to 0 to disable. */
|
||||
maxResultChars?: number;
|
||||
/** Maximum history messages to pass to API (default: 20). Set to 0 for unlimited. */
|
||||
maxHistoryMessages?: number;
|
||||
/** Optional callback for live progress updates during execution */
|
||||
onProgress?: (event: IProgressEvent) => void;
|
||||
/** Prefix for log messages (e.g., "[README]", "[Commit]"). Default: empty */
|
||||
logPrefix?: string;
|
||||
/** Callback fired for each token during LLM generation (streaming mode) */
|
||||
onToken?: (token: string, source: 'driver' | 'guardian') => void;
|
||||
}
|
||||
|
||||
// ================================
|
||||
@@ -84,6 +106,8 @@ export interface IToolExecutionResult {
|
||||
success: boolean;
|
||||
result?: unknown;
|
||||
error?: string;
|
||||
/** Optional human-readable summary for history (if provided, used instead of full result) */
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -195,6 +219,58 @@ export interface IDualAgentRunResult {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// ================================
|
||||
// Progress Event Interfaces
|
||||
// ================================
|
||||
|
||||
/**
|
||||
* Progress event types for live feedback during agent execution
|
||||
*/
|
||||
export type TProgressEventType =
|
||||
| 'task_started'
|
||||
| 'iteration_started'
|
||||
| 'tool_proposed'
|
||||
| 'guardian_evaluating'
|
||||
| 'tool_approved'
|
||||
| 'tool_rejected'
|
||||
| 'tool_executing'
|
||||
| 'tool_completed'
|
||||
| 'task_completed'
|
||||
| 'clarification_needed'
|
||||
| 'max_iterations'
|
||||
| 'max_rejections';
|
||||
|
||||
/**
|
||||
* Log level for progress events
|
||||
*/
|
||||
export type TLogLevel = 'info' | 'warn' | 'error' | 'success';
|
||||
|
||||
/**
|
||||
* Progress event for live feedback during agent execution
|
||||
*/
|
||||
export interface IProgressEvent {
|
||||
/** Type of progress event */
|
||||
type: TProgressEventType;
|
||||
/** Current iteration number */
|
||||
iteration?: number;
|
||||
/** Maximum iterations configured */
|
||||
maxIterations?: number;
|
||||
/** Name of the tool being used */
|
||||
toolName?: string;
|
||||
/** Action being performed */
|
||||
action?: string;
|
||||
/** Reason for rejection or other explanation */
|
||||
reason?: string;
|
||||
/** Human-readable message about the event */
|
||||
message?: string;
|
||||
/** Timestamp of the event */
|
||||
timestamp: Date;
|
||||
/** Log level for this event (info, warn, error, success) */
|
||||
logLevel: TLogLevel;
|
||||
/** Pre-formatted log message ready for output */
|
||||
logMessage: string;
|
||||
}
|
||||
|
||||
// ================================
|
||||
// Utility Types
|
||||
// ================================
|
||||
|
||||
@@ -8,6 +8,8 @@ import { BaseToolWrapper } from './smartagent.tools.base.js';
|
||||
export interface IFilesystemToolOptions {
|
||||
/** Base path to scope all operations to. If set, all paths must be within this directory. */
|
||||
basePath?: string;
|
||||
/** Glob patterns to exclude from listings (e.g., ['.nogit/**', 'node_modules/**']) */
|
||||
excludePatterns?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -20,12 +22,25 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
|
||||
/** Base path to scope all operations to */
|
||||
private basePath?: string;
|
||||
/** Glob patterns to exclude from listings */
|
||||
private excludePatterns: string[];
|
||||
|
||||
constructor(options?: IFilesystemToolOptions) {
|
||||
super();
|
||||
if (options?.basePath) {
|
||||
this.basePath = plugins.path.resolve(options.basePath);
|
||||
}
|
||||
this.excludePatterns = options?.excludePatterns || [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a relative path should be excluded based on exclude patterns
|
||||
*/
|
||||
private isExcluded(relativePath: string): boolean {
|
||||
if (this.excludePatterns.length === 0) return false;
|
||||
return this.excludePatterns.some(pattern =>
|
||||
plugins.minimatch(relativePath, pattern, { dot: true })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,17 +61,25 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
public actions: interfaces.IToolAction[] = [
|
||||
{
|
||||
name: 'read',
|
||||
description: 'Read the contents of a file',
|
||||
description: 'Read file contents (full or specific line range)',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Absolute path to the file' },
|
||||
path: { type: 'string', description: 'Path to the file' },
|
||||
encoding: {
|
||||
type: 'string',
|
||||
enum: ['utf8', 'binary', 'base64'],
|
||||
default: 'utf8',
|
||||
description: 'File encoding',
|
||||
},
|
||||
startLine: {
|
||||
type: 'number',
|
||||
description: 'First line to read (1-indexed, inclusive). If omitted, reads from beginning.',
|
||||
},
|
||||
endLine: {
|
||||
type: 'number',
|
||||
description: 'Last line to read (1-indexed, inclusive). If omitted, reads to end.',
|
||||
},
|
||||
},
|
||||
required: ['path'],
|
||||
},
|
||||
@@ -182,6 +205,55 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
required: ['path'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'tree',
|
||||
description: 'Show directory structure as a tree (no file contents)',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
path: { type: 'string', description: 'Root directory path' },
|
||||
maxDepth: {
|
||||
type: 'number',
|
||||
default: 3,
|
||||
description: 'Maximum depth to traverse (default: 3)',
|
||||
},
|
||||
filter: {
|
||||
type: 'string',
|
||||
description: 'Glob pattern to filter files (e.g., "*.ts")',
|
||||
},
|
||||
showSizes: {
|
||||
type: 'boolean',
|
||||
default: false,
|
||||
description: 'Include file sizes in output',
|
||||
},
|
||||
format: {
|
||||
type: 'string',
|
||||
enum: ['string', 'json'],
|
||||
default: 'string',
|
||||
description: 'Output format: "string" for human-readable tree, "json" for structured array',
|
||||
},
|
||||
},
|
||||
required: ['path'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'glob',
|
||||
description: 'Find files matching a glob pattern',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
pattern: {
|
||||
type: 'string',
|
||||
description: 'Glob pattern (e.g., "**/*.ts", "src/**/*.js")',
|
||||
},
|
||||
path: {
|
||||
type: 'string',
|
||||
description: 'Base path to search from (defaults to current directory)',
|
||||
},
|
||||
},
|
||||
required: ['pattern'],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
private smartfs!: plugins.smartfs.SmartFs;
|
||||
@@ -207,16 +279,61 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
case 'read': {
|
||||
const validatedPath = this.validatePath(params.path as string);
|
||||
const encoding = (params.encoding as string) || 'utf8';
|
||||
const content = await this.smartfs
|
||||
const startLine = params.startLine as number | undefined;
|
||||
const endLine = params.endLine as number | undefined;
|
||||
|
||||
const fullContent = await this.smartfs
|
||||
.file(validatedPath)
|
||||
.encoding(encoding as 'utf8' | 'binary' | 'base64')
|
||||
.read();
|
||||
|
||||
const contentStr = fullContent.toString();
|
||||
const lines = contentStr.split('\n');
|
||||
const totalLines = lines.length;
|
||||
|
||||
// Apply line range if specified
|
||||
let resultContent: string;
|
||||
let resultStartLine = 1;
|
||||
let resultEndLine = totalLines;
|
||||
|
||||
if (startLine !== undefined || endLine !== undefined) {
|
||||
const start = Math.max(1, startLine ?? 1);
|
||||
const end = Math.min(totalLines, endLine ?? totalLines);
|
||||
resultStartLine = start;
|
||||
resultEndLine = end;
|
||||
|
||||
// Convert to 0-indexed for array slicing
|
||||
const selectedLines = lines.slice(start - 1, end);
|
||||
|
||||
// Add line numbers to output for context
|
||||
resultContent = selectedLines
|
||||
.map((line, idx) => `${String(start + idx).padStart(5)}│ ${line}`)
|
||||
.join('\n');
|
||||
} else {
|
||||
// No range specified - return full content but warn if large
|
||||
const MAX_LINES_WITHOUT_RANGE = 500;
|
||||
if (totalLines > MAX_LINES_WITHOUT_RANGE) {
|
||||
// Return first portion with warning
|
||||
const selectedLines = lines.slice(0, MAX_LINES_WITHOUT_RANGE);
|
||||
resultContent = selectedLines
|
||||
.map((line, idx) => `${String(idx + 1).padStart(5)}│ ${line}`)
|
||||
.join('\n');
|
||||
resultContent += `\n\n[... ${totalLines - MAX_LINES_WITHOUT_RANGE} more lines. Use startLine/endLine to read specific ranges.]`;
|
||||
resultEndLine = MAX_LINES_WITHOUT_RANGE;
|
||||
} else {
|
||||
resultContent = contentStr;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
path: params.path,
|
||||
content: content.toString(),
|
||||
content: resultContent,
|
||||
encoding,
|
||||
totalLines,
|
||||
startLine: resultStartLine,
|
||||
endLine: resultEndLine,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -259,7 +376,16 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
if (params.filter) {
|
||||
dir = dir.filter(params.filter as string);
|
||||
}
|
||||
const entries = await dir.list();
|
||||
let entries = await dir.list();
|
||||
|
||||
// Filter out excluded paths
|
||||
if (this.excludePatterns.length > 0) {
|
||||
entries = entries.filter(entry => {
|
||||
const relativePath = plugins.path.relative(validatedPath, entry.path);
|
||||
return !this.isExcluded(relativePath) && !this.isExcluded(entry.name);
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
@@ -364,6 +490,168 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
};
|
||||
}
|
||||
|
||||
case 'tree': {
|
||||
const validatedPath = this.validatePath(params.path as string);
|
||||
const maxDepth = (params.maxDepth as number) ?? 3;
|
||||
const filter = params.filter as string | undefined;
|
||||
const showSizes = (params.showSizes as boolean) ?? false;
|
||||
const format = (params.format as 'string' | 'json') ?? 'string';
|
||||
|
||||
// Collect all entries recursively up to maxDepth
|
||||
interface ITreeEntry {
|
||||
path: string;
|
||||
relativePath: string;
|
||||
isDir: boolean;
|
||||
depth: number;
|
||||
size?: number;
|
||||
}
|
||||
|
||||
const entries: ITreeEntry[] = [];
|
||||
|
||||
const collectEntries = async (dirPath: string, depth: number, relativePath: string) => {
|
||||
if (depth > maxDepth) return;
|
||||
|
||||
let dir = this.smartfs.directory(dirPath);
|
||||
if (filter) {
|
||||
dir = dir.filter(filter);
|
||||
}
|
||||
const items = await dir.list();
|
||||
|
||||
for (const item of items) {
|
||||
// item is IDirectoryEntry with name, path, isFile, isDirectory properties
|
||||
const itemPath = item.path;
|
||||
const itemRelPath = relativePath ? `${relativePath}/${item.name}` : item.name;
|
||||
const isDir = item.isDirectory;
|
||||
|
||||
// Skip excluded paths
|
||||
if (this.isExcluded(itemRelPath) || this.isExcluded(item.name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry: ITreeEntry = {
|
||||
path: itemPath,
|
||||
relativePath: itemRelPath,
|
||||
isDir,
|
||||
depth,
|
||||
};
|
||||
|
||||
if (showSizes && !isDir && item.stats) {
|
||||
entry.size = item.stats.size;
|
||||
}
|
||||
|
||||
entries.push(entry);
|
||||
|
||||
// Recurse into directories
|
||||
if (isDir && depth < maxDepth) {
|
||||
await collectEntries(itemPath, depth + 1, itemRelPath);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await collectEntries(validatedPath, 0, '');
|
||||
|
||||
// Sort entries by path for consistent output
|
||||
entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
||||
|
||||
if (format === 'json') {
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
path: params.path,
|
||||
entries: entries.map((e) => ({
|
||||
path: e.relativePath,
|
||||
isDir: e.isDir,
|
||||
depth: e.depth,
|
||||
...(e.size !== undefined ? { size: e.size } : {}),
|
||||
})),
|
||||
count: entries.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Format as string tree
|
||||
const formatSize = (bytes: number): string => {
|
||||
if (bytes < 1024) return `${bytes}B`;
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)}MB`;
|
||||
};
|
||||
|
||||
// Build tree string with proper indentation
|
||||
let treeStr = `${params.path}/\n`;
|
||||
const pathParts = new Map<string, number>(); // Track which paths are last in their parent
|
||||
|
||||
// Group by parent to determine last child
|
||||
const parentChildCount = new Map<string, number>();
|
||||
const parentCurrentChild = new Map<string, number>();
|
||||
|
||||
for (const entry of entries) {
|
||||
const parentPath = entry.relativePath.includes('/')
|
||||
? entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'))
|
||||
: '';
|
||||
parentChildCount.set(parentPath, (parentChildCount.get(parentPath) || 0) + 1);
|
||||
}
|
||||
|
||||
for (const entry of entries) {
|
||||
const parentPath = entry.relativePath.includes('/')
|
||||
? entry.relativePath.substring(0, entry.relativePath.lastIndexOf('/'))
|
||||
: '';
|
||||
parentCurrentChild.set(parentPath, (parentCurrentChild.get(parentPath) || 0) + 1);
|
||||
const isLast = parentCurrentChild.get(parentPath) === parentChildCount.get(parentPath);
|
||||
|
||||
// Build prefix based on depth
|
||||
let prefix = '';
|
||||
const parts = entry.relativePath.split('/');
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
prefix += '│ ';
|
||||
}
|
||||
prefix += isLast ? '└── ' : '├── ';
|
||||
|
||||
const name = parts[parts.length - 1];
|
||||
const suffix = entry.isDir ? '/' : '';
|
||||
const sizeStr = showSizes && entry.size !== undefined ? ` (${formatSize(entry.size)})` : '';
|
||||
|
||||
treeStr += `${prefix}${name}${suffix}${sizeStr}\n`;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
path: params.path,
|
||||
tree: treeStr,
|
||||
count: entries.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case 'glob': {
|
||||
const pattern = params.pattern as string;
|
||||
const basePath = params.path ? this.validatePath(params.path as string) : (this.basePath || process.cwd());
|
||||
|
||||
// Use smartfs to list with filter
|
||||
const dir = this.smartfs.directory(basePath).recursive().filter(pattern);
|
||||
const matches = await dir.list();
|
||||
|
||||
// Return file paths relative to base path for readability
|
||||
// Filter out excluded paths
|
||||
const files = matches
|
||||
.map((entry) => ({
|
||||
path: entry.path,
|
||||
relativePath: plugins.path.relative(basePath, entry.path),
|
||||
isDirectory: entry.isDirectory,
|
||||
}))
|
||||
.filter((file) => !this.isExcluded(file.relativePath));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
pattern,
|
||||
basePath,
|
||||
files,
|
||||
count: files.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default:
|
||||
return {
|
||||
success: false,
|
||||
@@ -380,8 +668,12 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
|
||||
public getCallSummary(action: string, params: Record<string, unknown>): string {
|
||||
switch (action) {
|
||||
case 'read':
|
||||
return `Read file "${params.path}" with encoding ${params.encoding || 'utf8'}`;
|
||||
case 'read': {
|
||||
const lineRange = params.startLine || params.endLine
|
||||
? ` lines ${params.startLine || 1}-${params.endLine || 'end'}`
|
||||
: '';
|
||||
return `Read file "${params.path}"${lineRange}`;
|
||||
}
|
||||
|
||||
case 'write': {
|
||||
const content = params.content as string;
|
||||
@@ -416,6 +708,12 @@ export class FilesystemTool extends BaseToolWrapper {
|
||||
case 'mkdir':
|
||||
return `Create directory "${params.path}"${params.recursive !== false ? ' (with parents)' : ''}`;
|
||||
|
||||
case 'tree':
|
||||
return `Show tree of "${params.path}" (depth: ${params.maxDepth ?? 3}, format: ${params.format ?? 'string'})`;
|
||||
|
||||
case 'glob':
|
||||
return `Find files matching "${params.pattern}"${params.path ? ` in "${params.path}"` : ''}`;
|
||||
|
||||
default:
|
||||
return `Unknown action: ${action}`;
|
||||
}
|
||||
|
||||
193
ts/smartagent.tools.json.ts
Normal file
193
ts/smartagent.tools.json.ts
Normal file
@@ -0,0 +1,193 @@
|
||||
import * as interfaces from './smartagent.interfaces.js';
|
||||
import { BaseToolWrapper } from './smartagent.tools.base.js';
|
||||
|
||||
/**
|
||||
* JsonValidatorTool - Validates and formats JSON data
|
||||
* Useful for agents to self-validate their JSON output before completing a task
|
||||
*/
|
||||
export class JsonValidatorTool extends BaseToolWrapper {
|
||||
public name = 'json';
|
||||
public description = 'Validate and format JSON data. Use this to verify your JSON output is valid before completing a task.';
|
||||
|
||||
public actions: interfaces.IToolAction[] = [
|
||||
{
|
||||
name: 'validate',
|
||||
description: 'Validate that a string is valid JSON and optionally check required fields',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
jsonString: {
|
||||
type: 'string',
|
||||
description: 'The JSON string to validate',
|
||||
},
|
||||
requiredFields: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
description: 'Optional list of field names that must be present at the root level',
|
||||
},
|
||||
},
|
||||
required: ['jsonString'],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'format',
|
||||
description: 'Parse and pretty-print JSON string',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
jsonString: {
|
||||
type: 'string',
|
||||
description: 'The JSON string to format',
|
||||
},
|
||||
},
|
||||
required: ['jsonString'],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
async initialize(): Promise<void> {
|
||||
this.isInitialized = true;
|
||||
}
|
||||
|
||||
async cleanup(): Promise<void> {
|
||||
this.isInitialized = false;
|
||||
}
|
||||
|
||||
async execute(
|
||||
action: string,
|
||||
params: Record<string, unknown>
|
||||
): Promise<interfaces.IToolExecutionResult> {
|
||||
this.validateAction(action);
|
||||
|
||||
switch (action) {
|
||||
case 'validate':
|
||||
return this.validateJson(params);
|
||||
case 'format':
|
||||
return this.formatJson(params);
|
||||
default:
|
||||
return { success: false, error: `Unknown action: ${action}` };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate JSON string and optionally check for required fields
|
||||
*/
|
||||
private validateJson(params: Record<string, unknown>): interfaces.IToolExecutionResult {
|
||||
const jsonString = params.jsonString as string;
|
||||
const requiredFields = params.requiredFields as string[] | undefined;
|
||||
|
||||
if (!jsonString || typeof jsonString !== 'string') {
|
||||
return {
|
||||
success: false,
|
||||
error: 'jsonString parameter is required and must be a string',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(jsonString);
|
||||
|
||||
// Check required fields if specified
|
||||
if (requiredFields && Array.isArray(requiredFields)) {
|
||||
const missingFields = requiredFields.filter((field) => {
|
||||
if (typeof parsed !== 'object' || parsed === null) {
|
||||
return true;
|
||||
}
|
||||
return !(field in parsed);
|
||||
});
|
||||
|
||||
if (missingFields.length > 0) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Missing required fields: ${missingFields.join(', ')}`,
|
||||
result: {
|
||||
valid: false,
|
||||
missingFields,
|
||||
presentFields: Object.keys(parsed || {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: {
|
||||
valid: true,
|
||||
parsed,
|
||||
type: Array.isArray(parsed) ? 'array' : typeof parsed,
|
||||
fieldCount: typeof parsed === 'object' && parsed !== null ? Object.keys(parsed).length : undefined,
|
||||
},
|
||||
summary: `JSON is valid (${Array.isArray(parsed) ? 'array' : typeof parsed})`,
|
||||
};
|
||||
} catch (error) {
|
||||
const errorMessage = (error as Error).message;
|
||||
|
||||
// Extract position from error message if available
|
||||
const posMatch = errorMessage.match(/position\s*(\d+)/i);
|
||||
const position = posMatch ? parseInt(posMatch[1]) : undefined;
|
||||
|
||||
// Provide context around the error position
|
||||
let context: string | undefined;
|
||||
if (position !== undefined) {
|
||||
const start = Math.max(0, position - 20);
|
||||
const end = Math.min(jsonString.length, position + 20);
|
||||
context = jsonString.substring(start, end);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: `Invalid JSON: ${errorMessage}`,
|
||||
result: {
|
||||
valid: false,
|
||||
errorPosition: position,
|
||||
errorContext: context,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format/pretty-print JSON string
|
||||
*/
|
||||
private formatJson(params: Record<string, unknown>): interfaces.IToolExecutionResult {
|
||||
const jsonString = params.jsonString as string;
|
||||
|
||||
if (!jsonString || typeof jsonString !== 'string') {
|
||||
return {
|
||||
success: false,
|
||||
error: 'jsonString parameter is required and must be a string',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(jsonString);
|
||||
const formatted = JSON.stringify(parsed, null, 2);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
result: formatted,
|
||||
summary: `Formatted JSON (${formatted.length} chars)`,
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
error: `Cannot format invalid JSON: ${(error as Error).message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
getCallSummary(action: string, params: Record<string, unknown>): string {
|
||||
const jsonStr = (params.jsonString as string) || '';
|
||||
const preview = jsonStr.length > 50 ? jsonStr.substring(0, 50) + '...' : jsonStr;
|
||||
|
||||
switch (action) {
|
||||
case 'validate':
|
||||
const fields = params.requiredFields as string[] | undefined;
|
||||
const fieldInfo = fields ? ` (checking fields: ${fields.join(', ')})` : '';
|
||||
return `Validate JSON: ${preview}${fieldInfo}`;
|
||||
case 'format':
|
||||
return `Format JSON: ${preview}`;
|
||||
default:
|
||||
return `JSON ${action}: ${preview}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user