@push.rocks/smartagent 1.8.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/dist_ts/00_commitinfo_data.js +3 -3
  2. package/dist_ts/index.d.ts +8 -14
  3. package/dist_ts/index.js +8 -24
  4. package/dist_ts/plugins.d.ts +8 -9
  5. package/dist_ts/plugins.js +10 -12
  6. package/dist_ts/smartagent.classes.agent.d.ts +2 -0
  7. package/dist_ts/smartagent.classes.agent.js +173 -0
  8. package/dist_ts/smartagent.classes.toolregistry.d.ts +7 -70
  9. package/dist_ts/smartagent.classes.toolregistry.js +11 -155
  10. package/dist_ts/smartagent.interfaces.d.ts +47 -283
  11. package/dist_ts/smartagent.interfaces.js +6 -7
  12. package/dist_ts/smartagent.utils.truncation.d.ts +10 -0
  13. package/dist_ts/smartagent.utils.truncation.js +26 -0
  14. package/dist_ts_compaction/index.d.ts +1 -0
  15. package/dist_ts_compaction/index.js +2 -0
  16. package/dist_ts_compaction/plugins.d.ts +4 -0
  17. package/dist_ts_compaction/plugins.js +3 -0
  18. package/dist_ts_compaction/smartagent.compaction.d.ts +10 -0
  19. package/dist_ts_compaction/smartagent.compaction.js +46 -0
  20. package/dist_ts_tools/index.d.ts +8 -0
  21. package/dist_ts_tools/index.js +6 -0
  22. package/dist_ts_tools/plugins.d.ts +15 -0
  23. package/dist_ts_tools/plugins.js +19 -0
  24. package/dist_ts_tools/tool.filesystem.d.ts +6 -0
  25. package/dist_ts_tools/tool.filesystem.js +102 -0
  26. package/dist_ts_tools/tool.http.d.ts +2 -0
  27. package/dist_ts_tools/tool.http.js +65 -0
  28. package/dist_ts_tools/tool.json.d.ts +2 -0
  29. package/dist_ts_tools/tool.json.js +47 -0
  30. package/dist_ts_tools/tool.shell.d.ts +8 -0
  31. package/dist_ts_tools/tool.shell.js +40 -0
  32. package/npmextra.json +1 -1
  33. package/package.json +30 -18
  34. package/readme.hints.md +38 -84
  35. package/readme.md +254 -682
  36. package/ts/00_commitinfo_data.ts +2 -2
  37. package/ts/index.ts +10 -37
  38. package/ts/plugins.ts +22 -21
  39. package/ts/smartagent.classes.agent.ts +198 -0
  40. package/ts/smartagent.classes.toolregistry.ts +11 -179
  41. package/ts/smartagent.interfaces.ts +51 -363
  42. package/ts/smartagent.utils.truncation.ts +39 -0
  43. package/ts_compaction/index.ts +1 -0
  44. package/ts_compaction/plugins.ts +6 -0
  45. package/ts_compaction/smartagent.compaction.ts +51 -0
  46. package/ts_tools/index.ts +8 -0
  47. package/ts_tools/plugins.ts +30 -0
  48. package/ts_tools/tool.filesystem.ts +131 -0
  49. package/ts_tools/tool.http.ts +78 -0
  50. package/ts_tools/tool.json.ts +53 -0
  51. package/ts_tools/tool.shell.ts +62 -0
  52. package/dist_ts/smartagent.classes.driveragent.d.ts +0 -134
  53. package/dist_ts/smartagent.classes.driveragent.js +0 -671
  54. package/dist_ts/smartagent.classes.dualagent.d.ts +0 -93
  55. package/dist_ts/smartagent.classes.dualagent.js +0 -614
  56. package/dist_ts/smartagent.classes.guardianagent.d.ts +0 -46
  57. package/dist_ts/smartagent.classes.guardianagent.js +0 -201
  58. package/dist_ts/smartagent.tools.base.d.ts +0 -52
  59. package/dist_ts/smartagent.tools.base.js +0 -42
  60. package/dist_ts/smartagent.tools.browser.d.ts +0 -17
  61. package/dist_ts/smartagent.tools.browser.js +0 -229
  62. package/dist_ts/smartagent.tools.deno.d.ts +0 -21
  63. package/dist_ts/smartagent.tools.deno.js +0 -191
  64. package/dist_ts/smartagent.tools.expert.d.ts +0 -27
  65. package/dist_ts/smartagent.tools.expert.js +0 -126
  66. package/dist_ts/smartagent.tools.filesystem.d.ts +0 -40
  67. package/dist_ts/smartagent.tools.filesystem.js +0 -801
  68. package/dist_ts/smartagent.tools.http.d.ts +0 -16
  69. package/dist_ts/smartagent.tools.http.js +0 -264
  70. package/dist_ts/smartagent.tools.json.d.ts +0 -24
  71. package/dist_ts/smartagent.tools.json.js +0 -202
  72. package/dist_ts/smartagent.tools.search.d.ts +0 -29
  73. package/dist_ts/smartagent.tools.search.js +0 -215
  74. package/dist_ts/smartagent.tools.shell.d.ts +0 -17
  75. package/dist_ts/smartagent.tools.shell.js +0 -202
  76. package/ts/smartagent.classes.driveragent.ts +0 -775
  77. package/ts/smartagent.classes.dualagent.ts +0 -692
  78. package/ts/smartagent.classes.guardianagent.ts +0 -241
  79. package/ts/smartagent.tools.base.ts +0 -83
  80. package/ts/smartagent.tools.browser.ts +0 -253
  81. package/ts/smartagent.tools.deno.ts +0 -230
  82. package/ts/smartagent.tools.expert.ts +0 -144
  83. package/ts/smartagent.tools.filesystem.ts +0 -885
  84. package/ts/smartagent.tools.http.ts +0 -283
  85. package/ts/smartagent.tools.json.ts +0 -224
  86. package/ts/smartagent.tools.search.ts +0 -237
  87. package/ts/smartagent.tools.shell.ts +0 -230
@@ -1,366 +1,54 @@
1
- import * as plugins from './plugins.js';
2
-
3
- // ================================
4
- // Tool Visibility & Registry Types
5
- // ================================
6
-
7
- /**
8
- * Tool visibility mode
9
- * - 'initial': Conveyed to model in system prompt AND discoverable via search
10
- * - 'on-demand': Only discoverable via search, must be activated before use
11
- */
12
- export type TToolVisibility = 'initial' | 'on-demand';
13
-
14
- /**
15
- * Tool metadata for discovery and management
16
- */
17
- export interface IToolMetadata {
18
- name: string;
19
- description: string;
20
- actions: IToolAction[];
21
- visibility: TToolVisibility;
22
- isActivated: boolean;
23
- isInitialized: boolean;
24
- tags?: string[];
25
- category?: string;
26
- }
27
-
28
- /**
29
- * Options when registering a tool
30
- */
31
- export interface IToolRegistrationOptions {
32
- visibility?: TToolVisibility;
33
- tags?: string[];
34
- category?: string;
35
- }
36
-
37
- /**
38
- * Configuration for creating an Expert (SubAgent)
39
- */
40
- export interface IExpertConfig {
41
- /** Unique name for the expert */
42
- name: string;
43
- /** Description of the expert's capabilities */
44
- description: string;
45
- /** System message defining expert behavior */
46
- systemMessage: string;
47
- /** Guardian policy for the expert's inner agent */
48
- guardianPolicy: string;
49
- /** AI provider (defaults to parent's provider) */
50
- provider?: plugins.smartai.TProvider;
51
- /** Tools available to this expert */
52
- tools?: IAgentToolWrapper[];
53
- /** Max iterations for expert tasks (default: 10) */
54
- maxIterations?: number;
55
- /** Visibility mode (default: 'initial') */
56
- visibility?: TToolVisibility;
57
- /** Searchable tags */
58
- tags?: string[];
59
- /** Category for grouping */
60
- category?: string;
61
- }
62
-
63
- // ================================
64
- // Task Run Options
65
- // ================================
66
-
67
- /**
68
- * Options for running a task with the DualAgentOrchestrator
69
- */
70
- export interface ITaskRunOptions {
71
- /** Base64-encoded images to include with the task (for vision-capable models) */
72
- images?: string[];
73
- }
74
-
75
- // ================================
76
- // Agent Configuration Interfaces
77
- // ================================
78
-
79
- /**
80
- * Configuration options for the DualAgentOrchestrator
81
- */
82
- export interface IDualAgentOptions extends plugins.smartai.ISmartAiOptions {
83
- /** Existing SmartAi instance to reuse (avoids creating duplicate providers) */
84
- smartAiInstance?: plugins.smartai.SmartAi;
85
- /** Name of the agent system */
86
- name?: string;
87
- /** Default AI provider for both Driver and Guardian */
88
- defaultProvider?: plugins.smartai.TProvider;
89
- /** Optional separate provider for Guardian (for cost optimization) */
90
- guardianProvider?: plugins.smartai.TProvider;
91
- /** System message for the Driver agent */
92
- driverSystemMessage?: string;
93
- /** Policy prompt for the Guardian agent - REQUIRED */
94
- guardianPolicyPrompt: string;
95
- /** Maximum iterations for task completion (default: 20) */
96
- maxIterations?: number;
97
- /** Maximum consecutive rejections before aborting (default: 3) */
98
- maxConsecutiveRejections?: number;
99
- /** Enable verbose logging */
100
- verbose?: boolean;
101
- /** Maximum characters for tool result output before truncation (default: 15000). Set to 0 to disable. */
102
- maxResultChars?: number;
103
- /** Maximum history messages to pass to API (default: 20). Set to 0 for unlimited. */
104
- maxHistoryMessages?: number;
105
- /** Optional callback for live progress updates during execution */
106
- onProgress?: (event: IProgressEvent) => void;
107
- /** Prefix for log messages (e.g., "[README]", "[Commit]"). Default: empty */
108
- logPrefix?: string;
109
- /** Callback fired for each token during LLM generation (streaming mode) */
110
- onToken?: (token: string, source: 'driver' | 'guardian') => void;
1
+ import type { ToolSet, ModelMessage, LanguageModelV3 } from './plugins.js';
2
+
3
+ export interface IAgentRunOptions {
4
+ /** The LanguageModelV3 to use — from smartai.getModel() */
5
+ model: LanguageModelV3;
6
+ /** Initial user message or task description */
7
+ prompt: string;
8
+ /** System prompt override */
9
+ system?: string;
10
+ /** Tools available to the agent */
11
+ tools?: ToolSet;
111
12
  /**
112
- * Enable native tool calling mode (default: false)
113
- * When enabled, uses Ollama's native tool calling API instead of XML parsing
114
- * This is more efficient for models that support it (e.g., GPT-OSS with Harmony format)
13
+ * Maximum number of LLM↔tool round trips.
14
+ * Each step may execute multiple tools in parallel.
15
+ * Default: 20
115
16
  */
116
- useNativeToolCalling?: boolean;
117
- }
118
-
119
- // ================================
120
- // Message Interfaces
121
- // ================================
122
-
123
- /**
124
- * Represents a message in the agent's conversation history
125
- */
126
- export interface IAgentMessage {
127
- role: 'system' | 'user' | 'assistant' | 'tool' | 'guardian';
128
- content: string;
129
- toolName?: string;
130
- toolResult?: unknown;
131
- toolCall?: IToolCallProposal;
132
- guardianDecision?: IGuardianDecision;
133
- timestamp?: Date;
134
- }
135
-
136
- // ================================
137
- // Tool Interfaces
138
- // ================================
139
-
140
- /**
141
- * Represents an action that a tool can perform
142
- */
143
- export interface IToolAction {
144
- /** Action name (e.g., 'read', 'write', 'delete') */
145
- name: string;
146
- /** Description of what this action does */
147
- description: string;
148
- /** JSON schema for action parameters */
149
- parameters: Record<string, unknown>;
150
- }
151
-
152
- /**
153
- * Native tool call from provider (matches Ollama's tool calling format)
154
- * Format: function name is "toolName_actionName" (e.g., "json_validate")
155
- */
156
- export interface INativeToolCall {
157
- function: {
158
- name: string; // Format: "toolName_actionName"
159
- arguments: Record<string, unknown>;
160
- index?: number;
161
- };
162
- }
163
-
164
- /**
165
- * Proposed tool call from the Driver
166
- */
167
- export interface IToolCallProposal {
168
- /** Unique ID for this proposal */
169
- proposalId: string;
170
- /** Name of the tool */
171
- toolName: string;
172
- /** Specific action to perform */
173
- action: string;
174
- /** Parameters for the action */
175
- params: Record<string, unknown>;
176
- /** Driver's reasoning for this call */
177
- reasoning?: string;
178
- }
179
-
180
- /**
181
- * Result of tool execution
182
- */
183
- export interface IToolExecutionResult {
184
- success: boolean;
185
- result?: unknown;
186
- error?: string;
187
- /** Optional human-readable summary for history (if provided, used instead of full result) */
188
- summary?: string;
189
- }
190
-
191
- /**
192
- * Base interface for wrapped tools
193
- */
194
- export interface IAgentToolWrapper {
195
- /** Tool name */
196
- name: string;
197
- /** Tool description */
198
- description: string;
199
- /** Available actions */
200
- actions: IToolAction[];
201
- /** Initialize the tool */
202
- initialize(): Promise<void>;
203
- /** Cleanup resources */
204
- cleanup(): Promise<void>;
205
- /** Execute an action */
206
- execute(action: string, params: Record<string, unknown>): Promise<IToolExecutionResult>;
207
- /** Get a summary for Guardian review */
208
- getCallSummary(action: string, params: Record<string, unknown>): string;
209
- }
210
-
211
- // ================================
212
- // Guardian Interfaces
213
- // ================================
214
-
215
- /**
216
- * Request for Guardian evaluation
217
- */
218
- export interface IGuardianEvaluationRequest {
219
- /** The proposed tool call */
220
- proposal: IToolCallProposal;
221
- /** Current task context */
222
- taskContext: string;
223
- /** Recent conversation history (last N messages) */
224
- recentHistory: IAgentMessage[];
225
- /** Summary of what the tool call will do */
226
- callSummary: string;
227
- }
228
-
229
- /**
230
- * Guardian's decision
231
- */
232
- export interface IGuardianDecision {
233
- /** Approve or reject */
234
- decision: 'approve' | 'reject';
235
- /** Explanation of the decision */
236
- reason: string;
237
- /** Specific concerns if rejected */
238
- concerns?: string[];
239
- /** Suggestions for the Driver if rejected */
240
- suggestions?: string;
241
- /** Confidence level (0-1) */
242
- confidence?: number;
243
- }
244
-
245
- // ================================
246
- // Result Interfaces
247
- // ================================
248
-
249
- /**
250
- * Log entry for tool executions
251
- */
252
- export interface IToolExecutionLog {
253
- timestamp: Date;
254
- toolName: string;
255
- action: string;
256
- params: Record<string, unknown>;
257
- guardianDecision: 'approved' | 'rejected';
258
- guardianReason: string;
259
- executionResult?: unknown;
260
- executionError?: string;
261
- }
262
-
263
- /**
264
- * Status of a dual-agent run
265
- */
266
- export type TDualAgentRunStatus =
267
- | 'completed'
268
- | 'in_progress'
269
- | 'max_iterations_reached'
270
- | 'max_rejections_reached'
271
- | 'clarification_needed'
272
- | 'error';
273
-
274
- /**
275
- * Result of a dual-agent run
276
- */
277
- export interface IDualAgentRunResult {
278
- /** Whether the task was successful */
279
- success: boolean;
280
- /** Whether the task is completed */
281
- completed: boolean;
282
- /** Final result or response */
283
- result: string;
284
- /** Total iterations taken */
285
- iterations: number;
286
- /** Full conversation history */
287
- history: IAgentMessage[];
288
- /** Current status */
289
- status: TDualAgentRunStatus;
290
- /** Number of tool calls made */
291
- toolCallCount?: number;
292
- /** Number of Guardian rejections */
293
- rejectionCount?: number;
294
- /** Tool execution log */
295
- toolLog?: IToolExecutionLog[];
296
- /** Error message if status is 'error' */
297
- error?: string;
298
- }
299
-
300
- // ================================
301
- // Progress Event Interfaces
302
- // ================================
303
-
304
- /**
305
- * Progress event types for live feedback during agent execution
306
- */
307
- export type TProgressEventType =
308
- | 'task_started'
309
- | 'iteration_started'
310
- | 'tool_proposed'
311
- | 'guardian_evaluating'
312
- | 'tool_approved'
313
- | 'tool_rejected'
314
- | 'tool_executing'
315
- | 'tool_completed'
316
- | 'task_completed'
317
- | 'clarification_needed'
318
- | 'max_iterations'
319
- | 'max_rejections';
320
-
321
- /**
322
- * Log level for progress events
323
- */
324
- export type TLogLevel = 'info' | 'warn' | 'error' | 'success';
325
-
326
- /**
327
- * Progress event for live feedback during agent execution
328
- */
329
- export interface IProgressEvent {
330
- /** Type of progress event */
331
- type: TProgressEventType;
332
- /** Current iteration number */
333
- iteration?: number;
334
- /** Maximum iterations configured */
335
- maxIterations?: number;
336
- /** Name of the tool being used */
337
- toolName?: string;
338
- /** Action being performed */
339
- action?: string;
340
- /** Reason for rejection or other explanation */
341
- reason?: string;
342
- /** Human-readable message about the event */
343
- message?: string;
344
- /** Timestamp of the event */
345
- timestamp: Date;
346
- /** Log level for this event (info, warn, error, success) */
347
- logLevel: TLogLevel;
348
- /** Pre-formatted log message ready for output */
349
- logMessage: string;
350
- }
351
-
352
- // ================================
353
- // Utility Types
354
- // ================================
355
-
356
- /**
357
- * Available tool names
358
- */
359
- export type TToolName = 'filesystem' | 'http' | 'browser' | 'shell';
360
-
361
- /**
362
- * Generate a unique proposal ID
363
- */
364
- export function generateProposalId(): string {
365
- return `proposal_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
17
+ maxSteps?: number;
18
+ /** Prior conversation messages to include */
19
+ messages?: ModelMessage[];
20
+ /** Called for each streamed text delta */
21
+ onToken?: (delta: string) => void;
22
+ /** Called when a tool call starts */
23
+ onToolCall?: (toolName: string, input: unknown) => void;
24
+ /** Called when a tool call completes */
25
+ onToolResult?: (toolName: string, result: unknown) => void;
26
+ /**
27
+ * Called when total token usage approaches the model's context limit.
28
+ * Receives the full message history and must return a compacted replacement.
29
+ * If not provided, runAgent throws a ContextOverflowError instead.
30
+ */
31
+ onContextOverflow?: (messages: ModelMessage[]) => Promise<ModelMessage[]>;
32
+ /** AbortSignal to cancel the run mid-flight */
33
+ abort?: AbortSignal;
34
+ }
35
+
36
+ export interface IAgentRunResult {
37
+ /** Final text output from the model */
38
+ text: string;
39
+ /** All messages in the completed conversation */
40
+ messages: ModelMessage[];
41
+ /** Total steps taken */
42
+ steps: number;
43
+ /** Finish reason from the final step */
44
+ finishReason: string;
45
+ /** Accumulated token usage across all steps */
46
+ usage: { inputTokens: number; outputTokens: number; totalTokens: number };
47
+ }
48
+
49
+ export class ContextOverflowError extends Error {
50
+ constructor(message = 'Agent context limit reached and no onContextOverflow handler provided') {
51
+ super(message);
52
+ this.name = 'ContextOverflowError';
53
+ }
366
54
  }
@@ -0,0 +1,39 @@
1
+ // Truncation logic derived from opencode (MIT) — https://github.com/sst/opencode
2
+
3
+ const MAX_LINES = 2000;
4
+ const MAX_BYTES = 50 * 1024; // 50 KB
5
+
6
+ export interface ITruncateResult {
7
+ content: string;
8
+ truncated: boolean;
9
+ /** Set when truncated: describes what was dropped */
10
+ notice?: string;
11
+ }
12
+
13
+ export function truncateOutput(
14
+ text: string,
15
+ options?: { maxLines?: number; maxBytes?: number },
16
+ ): ITruncateResult {
17
+ const maxLines = options?.maxLines ?? MAX_LINES;
18
+ const maxBytes = options?.maxBytes ?? MAX_BYTES;
19
+ const lines = text.split('\n');
20
+ const totalBytes = Buffer.byteLength(text, 'utf-8');
21
+
22
+ if (lines.length <= maxLines && totalBytes <= maxBytes) {
23
+ return { content: text, truncated: false };
24
+ }
25
+
26
+ const out: string[] = [];
27
+ let bytes = 0;
28
+ for (let i = 0; i < lines.length && i < maxLines; i++) {
29
+ const size = Buffer.byteLength(lines[i], 'utf-8') + (i > 0 ? 1 : 0);
30
+ if (bytes + size > maxBytes) break;
31
+ out.push(lines[i]);
32
+ bytes += size;
33
+ }
34
+
35
+ const kept = out.length;
36
+ const dropped = lines.length - kept;
37
+ const notice = `\n[Output truncated: showing ${kept}/${lines.length} lines. ${dropped} lines omitted.]`;
38
+ return { content: out.join('\n') + notice, truncated: true, notice };
39
+ }
@@ -0,0 +1 @@
1
+ export { compactMessages } from './smartagent.compaction.js';
@@ -0,0 +1,6 @@
1
+ import { generateText } from 'ai';
2
+
3
+ export { generateText };
4
+
5
+ export type { ModelMessage } from 'ai';
6
+ export type { LanguageModelV3 } from '@push.rocks/smartai';
@@ -0,0 +1,51 @@
1
+ import * as plugins from './plugins.js';
2
+
3
+ const COMPACTION_PROMPT = `Provide a detailed prompt for continuing our conversation above.
4
+ Focus on information that would be helpful for continuing the conversation, including what we did, what we're doing, which files we're working on, and what we're going to do next.
5
+ The summary that you construct will be used so that another agent can read it and continue the work.
6
+
7
+ When constructing the summary, try to stick to this template:
8
+ ---
9
+ ## Goal
10
+ [What goal(s) is the user trying to accomplish?]
11
+
12
+ ## Instructions
13
+ - [What important instructions did the user give you that are relevant]
14
+
15
+ ## Discoveries
16
+ [What notable things were learned during this conversation that would be useful for the next agent to know]
17
+
18
+ ## Accomplished
19
+ [What work has been completed, what work is still in progress, and what work is left?]
20
+
21
+ ## Relevant files / directories
22
+ [A structured list of relevant files that have been read, edited, or created]
23
+ ---`;
24
+
25
+ /**
26
+ * Compacts a message history into a summary.
27
+ * Pass this as the onContextOverflow handler in IAgentRunOptions.
28
+ *
29
+ * @param model The same model used by runAgent, or a cheaper small model
30
+ * @param messages The full message history that overflowed
31
+ * @returns A minimal ModelMessage[] containing the summary as context
32
+ */
33
+ export async function compactMessages(
34
+ model: plugins.LanguageModelV3,
35
+ messages: plugins.ModelMessage[],
36
+ ): Promise<plugins.ModelMessage[]> {
37
+ const result = await plugins.generateText({
38
+ model,
39
+ messages: [
40
+ ...messages,
41
+ { role: 'user', content: COMPACTION_PROMPT },
42
+ ],
43
+ });
44
+
45
+ return [
46
+ {
47
+ role: 'user',
48
+ content: `[Previous conversation summary]\n\n${result.text}\n\n[End of summary. Continue from here.]`,
49
+ },
50
+ ];
51
+ }
@@ -0,0 +1,8 @@
1
+ export { filesystemTool } from './tool.filesystem.js';
2
+ export type { IFilesystemToolOptions } from './tool.filesystem.js';
3
+ export { shellTool } from './tool.shell.js';
4
+ export type { IShellToolOptions } from './tool.shell.js';
5
+ export { httpTool } from './tool.http.js';
6
+ export { jsonTool } from './tool.json.js';
7
+ export { truncateOutput } from './plugins.js';
8
+ export type { ITruncateResult } from './plugins.js';
@@ -0,0 +1,30 @@
1
+ // node native
2
+ import * as path from 'path';
3
+ import * as fs from 'fs';
4
+
5
+ export { path, fs };
6
+
7
+ // zod
8
+ import { z } from 'zod';
9
+
10
+ export { z };
11
+
12
+ // ai-sdk
13
+ import { tool } from '@push.rocks/smartai';
14
+
15
+ export { tool };
16
+
17
+ export type { ToolSet } from 'ai';
18
+
19
+ // @push.rocks scope
20
+ import * as smartfs from '@push.rocks/smartfs';
21
+ import * as smartshell from '@push.rocks/smartshell';
22
+ import * as smartrequest from '@push.rocks/smartrequest';
23
+
24
+ export { smartfs, smartshell, smartrequest };
25
+
26
+ // cross-folder import
27
+ import { truncateOutput } from '../ts/smartagent.utils.truncation.js';
28
+
29
+ export { truncateOutput };
30
+ export type { ITruncateResult } from '../ts/smartagent.utils.truncation.js';
@@ -0,0 +1,131 @@
1
+ import * as plugins from './plugins.js';
2
+
3
+ export interface IFilesystemToolOptions {
4
+ /** Restrict file access to this directory. Default: process.cwd() */
5
+ rootDir?: string;
6
+ }
7
+
8
+ function validatePath(filePath: string, rootDir?: string): string {
9
+ const resolved = plugins.path.resolve(filePath);
10
+ if (rootDir) {
11
+ const resolvedRoot = plugins.path.resolve(rootDir);
12
+ if (!resolved.startsWith(resolvedRoot + plugins.path.sep) && resolved !== resolvedRoot) {
13
+ throw new Error(`Access denied: "${filePath}" is outside allowed root "${rootDir}"`);
14
+ }
15
+ }
16
+ return resolved;
17
+ }
18
+
19
+ export function filesystemTool(options?: IFilesystemToolOptions): plugins.ToolSet {
20
+ const rootDir = options?.rootDir;
21
+
22
+ return {
23
+ read_file: plugins.tool({
24
+ description:
25
+ 'Read file contents. Returns the full text or a specified line range.',
26
+ inputSchema: plugins.z.object({
27
+ path: plugins.z.string().describe('Absolute path to the file'),
28
+ startLine: plugins.z
29
+ .number()
30
+ .optional()
31
+ .describe('First line (1-indexed, inclusive)'),
32
+ endLine: plugins.z
33
+ .number()
34
+ .optional()
35
+ .describe('Last line (1-indexed, inclusive)'),
36
+ }),
37
+ execute: async ({
38
+ path: filePath,
39
+ startLine,
40
+ endLine,
41
+ }: {
42
+ path: string;
43
+ startLine?: number;
44
+ endLine?: number;
45
+ }) => {
46
+ const resolved = validatePath(filePath, rootDir);
47
+ const content = plugins.fs.readFileSync(resolved, 'utf-8');
48
+
49
+ if (startLine !== undefined || endLine !== undefined) {
50
+ const lines = content.split('\n');
51
+ const start = (startLine ?? 1) - 1;
52
+ const end = endLine ?? lines.length;
53
+ const sliced = lines.slice(start, end).join('\n');
54
+ return plugins.truncateOutput(sliced).content;
55
+ }
56
+
57
+ return plugins.truncateOutput(content).content;
58
+ },
59
+ }),
60
+
61
+ write_file: plugins.tool({
62
+ description:
63
+ 'Write content to a file (creates parent dirs if needed, overwrites existing).',
64
+ inputSchema: plugins.z.object({
65
+ path: plugins.z.string().describe('Absolute path to the file'),
66
+ content: plugins.z.string().describe('Content to write'),
67
+ }),
68
+ execute: async ({ path: filePath, content }: { path: string; content: string }) => {
69
+ const resolved = validatePath(filePath, rootDir);
70
+ const dir = plugins.path.dirname(resolved);
71
+ plugins.fs.mkdirSync(dir, { recursive: true });
72
+ plugins.fs.writeFileSync(resolved, content, 'utf-8');
73
+ return `Written ${content.length} characters to ${filePath}`;
74
+ },
75
+ }),
76
+
77
+ list_directory: plugins.tool({
78
+ description: 'List files and directories at the given path.',
79
+ inputSchema: plugins.z.object({
80
+ path: plugins.z.string().describe('Directory path to list'),
81
+ recursive: plugins.z
82
+ .boolean()
83
+ .optional()
84
+ .describe('List recursively (default: false)'),
85
+ }),
86
+ execute: async ({
87
+ path: dirPath,
88
+ recursive,
89
+ }: {
90
+ path: string;
91
+ recursive?: boolean;
92
+ }) => {
93
+ const resolved = validatePath(dirPath, rootDir);
94
+
95
+ function listDir(dir: string, prefix: string = ''): string[] {
96
+ const entries = plugins.fs.readdirSync(dir, { withFileTypes: true });
97
+ const result: string[] = [];
98
+ for (const entry of entries) {
99
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
100
+ const indicator = entry.isDirectory() ? '/' : '';
101
+ result.push(`${rel}${indicator}`);
102
+ if (recursive && entry.isDirectory()) {
103
+ result.push(...listDir(plugins.path.join(dir, entry.name), rel));
104
+ }
105
+ }
106
+ return result;
107
+ }
108
+
109
+ const entries = listDir(resolved);
110
+ return plugins.truncateOutput(entries.join('\n')).content;
111
+ },
112
+ }),
113
+
114
+ delete_file: plugins.tool({
115
+ description: 'Delete a file or empty directory.',
116
+ inputSchema: plugins.z.object({
117
+ path: plugins.z.string().describe('Path to delete'),
118
+ }),
119
+ execute: async ({ path: filePath }: { path: string }) => {
120
+ const resolved = validatePath(filePath, rootDir);
121
+ const stat = plugins.fs.statSync(resolved);
122
+ if (stat.isDirectory()) {
123
+ plugins.fs.rmdirSync(resolved);
124
+ } else {
125
+ plugins.fs.unlinkSync(resolved);
126
+ }
127
+ return `Deleted ${filePath}`;
128
+ },
129
+ }),
130
+ };
131
+ }