@sisu-ai/tool-terminal 6.0.1 → 7.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Tool } from '@sisu-ai/core';
1
+ import type { Tool } from "@sisu-ai/core";
2
2
  export interface TerminalToolConfig {
3
3
  roots: string[];
4
4
  readOnlyRoots?: string[];
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { promises as fs, realpathSync } from 'node:fs';
3
- import path from 'node:path';
4
- import { spawn } from 'node:child_process';
5
- import { minimatch } from 'minimatch';
6
- import { z } from 'zod';
1
+ import { randomUUID } from "node:crypto";
2
+ import { promises as fs, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { spawn } from "node:child_process";
5
+ import { minimatch } from "minimatch";
6
+ import { z } from "zod";
7
7
  const DEFAULT_PATH_DIRS = (() => {
8
- const base = ['/usr/bin', '/bin', '/usr/local/bin'];
9
- if (process.platform === 'darwin')
10
- base.push('/opt/homebrew/bin');
8
+ const base = ["/usr/bin", "/bin", "/usr/local/bin"];
9
+ if (process.platform === "darwin")
10
+ base.push("/opt/homebrew/bin");
11
11
  return base;
12
12
  })();
13
13
  export const DEFAULT_CONFIG = {
@@ -15,17 +15,17 @@ export const DEFAULT_CONFIG = {
15
15
  capabilities: { read: true, write: false, delete: false, exec: true },
16
16
  commands: {
17
17
  allow: [
18
- 'pwd',
19
- 'ls',
20
- 'stat',
21
- 'wc',
22
- 'head',
23
- 'tail',
24
- 'cat',
25
- 'cut',
26
- 'sort',
27
- 'uniq',
28
- 'grep'
18
+ "pwd",
19
+ "ls",
20
+ "stat",
21
+ "wc",
22
+ "head",
23
+ "tail",
24
+ "cat",
25
+ "cut",
26
+ "sort",
27
+ "uniq",
28
+ "grep",
29
29
  ],
30
30
  },
31
31
  execution: {
@@ -36,15 +36,20 @@ export const DEFAULT_CONFIG = {
36
36
  },
37
37
  allowPipe: false,
38
38
  allowSequence: false,
39
- sessions: { enabled: true, ttlMs: 120_000, maxPerAgent: 4 }
39
+ sessions: { enabled: true, ttlMs: 120_000, maxPerAgent: 4 },
40
40
  };
41
41
  // Reusable exports for consumers who want to surface or extend policy
42
- export const TERMINAL_COMMANDS_ALLOW = Object.freeze([...DEFAULT_CONFIG.commands.allow]);
42
+ export const TERMINAL_COMMANDS_ALLOW = Object.freeze([
43
+ ...DEFAULT_CONFIG.commands.allow,
44
+ ]);
43
45
  export function defaultTerminalConfig(overrides) {
44
46
  return {
45
47
  ...DEFAULT_CONFIG,
46
48
  ...overrides,
47
- capabilities: { ...DEFAULT_CONFIG.capabilities, ...(overrides?.capabilities ?? {}) },
49
+ capabilities: {
50
+ ...DEFAULT_CONFIG.capabilities,
51
+ ...(overrides?.capabilities ?? {}),
52
+ },
48
53
  commands: {
49
54
  allow: overrides?.commands?.allow ?? DEFAULT_CONFIG.commands.allow,
50
55
  },
@@ -56,7 +61,7 @@ export function defaultTerminalConfig(overrides) {
56
61
  }
57
62
  function isCommandAllowed(verb, policy) {
58
63
  const opts = { nocase: true };
59
- return policy.allow.some(p => minimatch(verb, p, opts));
64
+ return policy.allow.some((p) => minimatch(verb, p, opts));
60
65
  }
61
66
  function canonicalize(p) {
62
67
  try {
@@ -69,24 +74,26 @@ function canonicalize(p) {
69
74
  }
70
75
  function isPathAllowed(absPath, cfg, mode) {
71
76
  const real = canonicalize(absPath);
72
- const roots = cfg.roots.map(r => canonicalize(r));
73
- const inside = roots.some(r => real === r || real.startsWith(r + path.sep));
77
+ const roots = cfg.roots.map((r) => canonicalize(r));
78
+ const inside = roots.some((r) => real === r || real.startsWith(r + path.sep));
74
79
  if (!inside)
75
80
  return false;
76
- if (mode !== 'read' && cfg.readOnlyRoots) {
77
- const ro = cfg.readOnlyRoots.map(r => canonicalize(r));
78
- const inRo = ro.some(r => real === r || real.startsWith(r + path.sep));
81
+ if (mode !== "read" && cfg.readOnlyRoots) {
82
+ const ro = cfg.readOnlyRoots.map((r) => canonicalize(r));
83
+ const inRo = ro.some((r) => real === r || real.startsWith(r + path.sep));
79
84
  if (inRo)
80
85
  return false;
81
86
  }
82
87
  return true;
83
88
  }
84
89
  function looksLikePath(arg) {
85
- return arg.startsWith('.') || arg.includes('/') || /^(?:[A-Za-z]:[\\/]|\\\\)/.test(arg);
90
+ return (arg.startsWith(".") ||
91
+ arg.includes("/") ||
92
+ /^(?:[A-Za-z]:[\\/]|\\\\)/.test(arg));
86
93
  }
87
94
  function parseArgs(cmd) {
88
95
  const out = [];
89
- let current = '';
96
+ let current = "";
90
97
  let single = false;
91
98
  let double = false;
92
99
  for (let i = 0; i < cmd.length; i++) {
@@ -102,14 +109,14 @@ function parseArgs(cmd) {
102
109
  if (!single && !double && /\s/.test(ch)) {
103
110
  if (current) {
104
111
  out.push(current);
105
- current = '';
112
+ current = "";
106
113
  }
107
114
  continue;
108
115
  }
109
116
  current += ch;
110
117
  }
111
118
  if (single || double)
112
- throw new Error('unbalanced quotes');
119
+ throw new Error("unbalanced quotes");
113
120
  if (current)
114
121
  out.push(current);
115
122
  return out;
@@ -117,7 +124,7 @@ function parseArgs(cmd) {
117
124
  function splitPipeline(cmd) {
118
125
  // Split on '|' outside quotes
119
126
  const out = [];
120
- let current = '';
127
+ let current = "";
121
128
  let single = false;
122
129
  let double = false;
123
130
  for (let i = 0; i < cmd.length; i++) {
@@ -132,11 +139,11 @@ function splitPipeline(cmd) {
132
139
  current += ch;
133
140
  continue;
134
141
  }
135
- if (ch === '|' && !single && !double) {
142
+ if (ch === "|" && !single && !double) {
136
143
  const seg = current.trim();
137
144
  if (seg)
138
145
  out.push(seg);
139
- current = '';
146
+ current = "";
140
147
  continue;
141
148
  }
142
149
  current += ch;
@@ -148,7 +155,7 @@ function splitPipeline(cmd) {
148
155
  }
149
156
  function splitSequence(cmd) {
150
157
  const out = [];
151
- let current = '';
158
+ let current = "";
152
159
  let single = false;
153
160
  let double = false;
154
161
  let nextOp = null;
@@ -166,29 +173,29 @@ function splitSequence(cmd) {
166
173
  continue;
167
174
  }
168
175
  if (!single && !double) {
169
- if (ch === ';') {
176
+ if (ch === ";") {
170
177
  const seg = current.trim();
171
178
  if (seg)
172
179
  out.push({ cmd: seg, op: nextOp });
173
- current = '';
174
- nextOp = ';';
180
+ current = "";
181
+ nextOp = ";";
175
182
  continue;
176
183
  }
177
- if (ch === '&' && nxt === '&') {
184
+ if (ch === "&" && nxt === "&") {
178
185
  const seg = current.trim();
179
186
  if (seg)
180
187
  out.push({ cmd: seg, op: nextOp });
181
- current = '';
182
- nextOp = '&&';
188
+ current = "";
189
+ nextOp = "&&";
183
190
  i++;
184
191
  continue;
185
192
  }
186
- if (ch === '|' && nxt === '|') {
193
+ if (ch === "|" && nxt === "|") {
187
194
  const seg = current.trim();
188
195
  if (seg)
189
196
  out.push({ cmd: seg, op: nextOp });
190
- current = '';
191
- nextOp = '||';
197
+ current = "";
198
+ nextOp = "||";
192
199
  i++;
193
200
  continue;
194
201
  }
@@ -202,61 +209,66 @@ function splitSequence(cmd) {
202
209
  }
203
210
  function commandPolicyCheck(args, cfg) {
204
211
  if (!cfg.capabilities.exec)
205
- return { allowed: false, reason: 'exec disabled' };
206
- if (!isPathAllowed(args.cwd, cfg, 'exec'))
207
- return { allowed: false, reason: 'cwd outside roots' };
212
+ return { allowed: false, reason: "exec disabled" };
213
+ if (!isPathAllowed(args.cwd, cfg, "exec"))
214
+ return { allowed: false, reason: "cwd outside roots" };
208
215
  let parsed;
209
216
  try {
210
217
  parsed = parseArgs(args.command);
211
218
  }
212
219
  catch {
213
- return { allowed: false, reason: 'invalid quoting' };
220
+ return { allowed: false, reason: "invalid quoting" };
214
221
  }
215
222
  if (parsed.length === 0)
216
- return { allowed: false, reason: 'empty command' };
223
+ return { allowed: false, reason: "empty command" };
217
224
  // Detect shell/control operators; allow only configured ones
218
225
  const found = [];
219
226
  const cmdStr = args.command;
220
227
  if (/&&/.test(cmdStr))
221
- found.push('&&');
228
+ found.push("&&");
222
229
  const hasOrOr = /\|\|/.test(cmdStr);
223
230
  if (hasOrOr)
224
- found.push('||');
231
+ found.push("||");
225
232
  // Consider single '|' only after removing '||'
226
- if (/\|/.test(cmdStr.replace(/\|\|/g, '')))
227
- found.push('|');
233
+ if (/\|/.test(cmdStr.replace(/\|\|/g, "")))
234
+ found.push("|");
228
235
  if (/;/.test(cmdStr))
229
- found.push(';');
236
+ found.push(";");
230
237
  if (/\$\(/.test(cmdStr))
231
- found.push('$(...)');
238
+ found.push("$(...)");
232
239
  if (/`/.test(cmdStr))
233
- found.push('`...`');
240
+ found.push("`...`");
234
241
  if (/>/.test(cmdStr))
235
- found.push('>');
242
+ found.push(">");
236
243
  if (/<\<?/.test(cmdStr))
237
- found.push('<');
244
+ found.push("<");
238
245
  if (/(^|\s)&(\s|$)/.test(cmdStr))
239
- found.push('&');
246
+ found.push("&");
240
247
  const allowPipe = cfg.allowPipe ?? false;
241
248
  const allowSequence = cfg.allowSequence ?? false;
242
- const unallowed = found.filter(op => {
243
- if (op === '|' && allowPipe)
249
+ const unallowed = found.filter((op) => {
250
+ if (op === "|" && allowPipe)
244
251
  return false;
245
- if ((op === '&&' || op === '||' || op === ';') && allowSequence)
252
+ if ((op === "&&" || op === "||" || op === ";") && allowSequence)
246
253
  return false;
247
254
  return true;
248
255
  });
249
256
  if (unallowed.length > 0) {
250
- const unique = Array.from(new Set(unallowed)).join(', ');
251
- return { allowed: false, reason: `shell operators not allowed (${unique}). Enable allowPipe and/or allowSequence in config to opt in.` };
257
+ const unique = Array.from(new Set(unallowed)).join(", ");
258
+ return {
259
+ allowed: false,
260
+ reason: `shell operators not allowed (${unique}). Enable allowPipe and/or allowSequence in config to opt in.`,
261
+ };
252
262
  }
253
263
  const [verb, ...rest] = parsed;
254
264
  if (!isCommandAllowed(verb, cfg.commands))
255
- return { allowed: false, reason: 'command denied' };
265
+ return { allowed: false, reason: "command denied" };
256
266
  for (const a of rest) {
257
267
  if (looksLikePath(a)) {
258
- const abs = path.isAbsolute(a) || /^(?:[A-Za-z]:\\|\\)/.test(a) ? a : path.join(args.cwd, a);
259
- if (!isPathAllowed(abs, cfg, 'read')) {
268
+ const abs = path.isAbsolute(a) || /^(?:[A-Za-z]:\\|\\)/.test(a)
269
+ ? a
270
+ : path.join(args.cwd, a);
271
+ if (!isPathAllowed(abs, cfg, "read")) {
260
272
  return { allowed: false, reason: `path outside roots: ${a}` };
261
273
  }
262
274
  }
@@ -265,25 +277,33 @@ function commandPolicyCheck(args, cfg) {
265
277
  if (allowPipe && /\|/.test(args.command)) {
266
278
  const segments = splitPipeline(args.command);
267
279
  if (segments.length < 2)
268
- return { allowed: false, reason: 'invalid pipeline' };
280
+ return { allowed: false, reason: "invalid pipeline" };
269
281
  for (const seg of segments) {
270
282
  let segArgs;
271
283
  try {
272
284
  segArgs = parseArgs(seg);
273
285
  }
274
286
  catch {
275
- return { allowed: false, reason: 'invalid quoting in pipeline segment' };
287
+ return {
288
+ allowed: false,
289
+ reason: "invalid quoting in pipeline segment",
290
+ };
276
291
  }
277
292
  if (segArgs.length === 0)
278
- return { allowed: false, reason: 'empty pipeline segment' };
293
+ return { allowed: false, reason: "empty pipeline segment" };
279
294
  const [v, ...r] = segArgs;
280
295
  if (!isCommandAllowed(v, cfg.commands))
281
296
  return { allowed: false, reason: `command denied in pipeline: ${v}` };
282
297
  for (const a of r) {
283
298
  if (looksLikePath(a)) {
284
- const abs = path.isAbsolute(a) || /^(?:[A-Za-z]:\\|\\)/.test(a) ? a : path.join(args.cwd, a);
285
- if (!isPathAllowed(abs, cfg, 'read'))
286
- return { allowed: false, reason: `path outside roots in pipeline: ${a}` };
299
+ const abs = path.isAbsolute(a) || /^(?:[A-Za-z]:\\|\\)/.test(a)
300
+ ? a
301
+ : path.join(args.cwd, a);
302
+ if (!isPathAllowed(abs, cfg, "read"))
303
+ return {
304
+ allowed: false,
305
+ reason: `path outside roots in pipeline: ${a}`,
306
+ };
287
307
  }
288
308
  }
289
309
  }
@@ -291,7 +311,7 @@ function commandPolicyCheck(args, cfg) {
291
311
  if (allowSequence && /(?:&&|\|\||;)/.test(args.command)) {
292
312
  const seq = splitSequence(args.command);
293
313
  if (seq.length === 0)
294
- return { allowed: false, reason: 'invalid sequence' };
314
+ return { allowed: false, reason: "invalid sequence" };
295
315
  for (const part of seq) {
296
316
  const res = commandPolicyCheck({ command: part.cmd, cwd: args.cwd }, cfg);
297
317
  if (!res.allowed)
@@ -316,7 +336,7 @@ export function createTerminalTool(config) {
316
336
  return s;
317
337
  }
318
338
  function buildEnv(extra) {
319
- const allowed = new Set(['PATH', 'HOME', 'LANG', 'TERM']);
339
+ const allowed = new Set(["PATH", "HOME", "LANG", "TERM"]);
320
340
  const env = {};
321
341
  for (const key of allowed) {
322
342
  const v = process.env[key];
@@ -328,15 +348,15 @@ export function createTerminalTool(config) {
328
348
  env[k] = v;
329
349
  }
330
350
  // Enforce a controlled PATH from config (ignores provided PATH to avoid hijack)
331
- env.PATH = cfg.execution.pathDirs.join(':');
351
+ env.PATH = cfg.execution.pathDirs.join(":");
332
352
  return env;
333
353
  }
334
354
  function start_session(args) {
335
355
  if (!cfg.sessions.enabled)
336
- throw new Error('sessions disabled');
356
+ throw new Error("sessions disabled");
337
357
  const cwd = canonicalize(args?.cwd ? path.resolve(args.cwd) : cfg.roots[0]);
338
- if (!isPathAllowed(cwd, cfg, 'exec')) {
339
- throw new Error('cwd outside allowed roots');
358
+ if (!isPathAllowed(cwd, cfg, "exec")) {
359
+ throw new Error("cwd outside allowed roots");
340
360
  }
341
361
  const sessionId = randomUUID();
342
362
  const expiresAt = Date.now() + cfg.sessions.ttlMs;
@@ -348,7 +368,14 @@ export function createTerminalTool(config) {
348
368
  const cwd = canonicalize(path.resolve(args.cwd ?? session?.cwd ?? cfg.roots[0]));
349
369
  const pre = commandPolicyCheck({ command: args.command, cwd }, cfg);
350
370
  if (!pre.allowed) {
351
- return { exitCode: -1, stdout: '', stderr: '', durationMs: 0, policy: pre, cwd };
371
+ return {
372
+ exitCode: -1,
373
+ stdout: "",
374
+ stderr: "",
375
+ durationMs: 0,
376
+ policy: pre,
377
+ cwd,
378
+ };
352
379
  }
353
380
  const pipelinesAllowed = cfg.allowPipe ?? false;
354
381
  const sequencesAllowed = cfg.allowSequence ?? false;
@@ -358,17 +385,23 @@ export function createTerminalTool(config) {
358
385
  if (hasSeq) {
359
386
  const seq = splitSequence(args.command);
360
387
  let lastExit = 0;
361
- let out = '';
362
- let err = '';
388
+ let out = "";
389
+ let err = "";
363
390
  let durTotal = 0;
364
391
  for (let i = 0; i < seq.length; i++) {
365
392
  const { cmd: subCmd, op } = seq[i];
366
- const shouldRun = i === 0 ? true : (op === ';' ? true : (op === '&&' ? lastExit === 0 : lastExit !== 0));
393
+ const shouldRun = i === 0
394
+ ? true
395
+ : op === ";"
396
+ ? true
397
+ : op === "&&"
398
+ ? lastExit === 0
399
+ : lastExit !== 0;
367
400
  if (!shouldRun)
368
401
  continue;
369
402
  const res = await run_command({ ...args, command: subCmd, cwd });
370
- out += res.stdout || '';
371
- err += res.stderr || '';
403
+ out += res.stdout || "";
404
+ err += res.stderr || "";
372
405
  durTotal += res.durationMs || 0;
373
406
  lastExit = res.exitCode;
374
407
  }
@@ -376,34 +409,49 @@ export function createTerminalTool(config) {
376
409
  session.cwd = cwd;
377
410
  session.expiresAt = Date.now() + cfg.sessions.ttlMs;
378
411
  }
379
- return { exitCode: lastExit, stdout: out, stderr: err, durationMs: durTotal, policy: { allowed: true }, cwd };
412
+ return {
413
+ exitCode: lastExit,
414
+ stdout: out,
415
+ stderr: err,
416
+ durationMs: durTotal,
417
+ policy: { allowed: true },
418
+ cwd,
419
+ };
380
420
  }
381
421
  const argv = parseArgs(args.command);
382
422
  const [cmd, ...cmdArgs] = argv;
383
423
  const env = buildEnv({ ...(session?.env ?? {}), ...(args.env ?? {}) });
384
424
  const start = Date.now();
385
425
  return await new Promise((resolve) => {
386
- let stdout = '', stderr = '';
426
+ let stdout = "", stderr = "";
387
427
  let outBytes = 0, errBytes = 0;
388
428
  const children = [];
389
- const killAll = () => { for (const c of children) {
390
- try {
391
- c.kill('SIGKILL');
429
+ const killAll = () => {
430
+ for (const c of children) {
431
+ try {
432
+ c.kill("SIGKILL");
433
+ }
434
+ catch { }
392
435
  }
393
- catch { }
394
- } };
395
- const onStdout = (d) => { outBytes += d.length; if (outBytes <= cfg.execution.maxStdoutBytes)
396
- stdout += d.toString();
397
- else
398
- killAll(); };
399
- const onStderr = (d) => { errBytes += d.length; if (errBytes <= cfg.execution.maxStderrBytes)
400
- stderr += d.toString();
401
- else
402
- killAll(); };
436
+ };
437
+ const onStdout = (d) => {
438
+ outBytes += d.length;
439
+ if (outBytes <= cfg.execution.maxStdoutBytes)
440
+ stdout += d.toString();
441
+ else
442
+ killAll();
443
+ };
444
+ const onStderr = (d) => {
445
+ errBytes += d.length;
446
+ if (errBytes <= cfg.execution.maxStderrBytes)
447
+ stderr += d.toString();
448
+ else
449
+ killAll();
450
+ };
403
451
  const timeout = setTimeout(() => killAll(), cfg.execution.timeoutMs);
404
452
  if (hasPipe) {
405
453
  const segments = splitPipeline(args.command);
406
- const argvList = segments.map(seg => parseArgs(seg));
454
+ const argvList = segments.map((seg) => parseArgs(seg));
407
455
  let prev;
408
456
  let finished = false;
409
457
  const finish = (exitCode, errMsg) => {
@@ -419,13 +467,20 @@ export function createTerminalTool(config) {
419
467
  if (errMsg) {
420
468
  stderr += (stderr ? "\n" : "") + errMsg;
421
469
  }
422
- resolve({ exitCode, stdout, stderr, durationMs: dur, policy: { allowed: true }, cwd });
470
+ resolve({
471
+ exitCode,
472
+ stdout,
473
+ stderr,
474
+ durationMs: dur,
475
+ policy: { allowed: true },
476
+ cwd,
477
+ });
423
478
  };
424
479
  for (let i = 0; i < argvList.length; i++) {
425
480
  const [pcmd, ...pargs] = argvList[i];
426
481
  const proc = spawn(pcmd, pargs, { cwd, env, shell: false });
427
482
  children.push(proc);
428
- proc.on('error', (err) => {
483
+ proc.on("error", (err) => {
429
484
  killAll();
430
485
  finish(-1, String(err?.message ?? err));
431
486
  });
@@ -437,10 +492,10 @@ export function createTerminalTool(config) {
437
492
  prev.stdout.pipe(proc.stdin);
438
493
  }
439
494
  if (i === argvList.length - 1 && proc.stdout) {
440
- proc.stdout.on('data', onStdout);
495
+ proc.stdout.on("data", onStdout);
441
496
  }
442
497
  if (proc.stderr)
443
- proc.stderr.on('data', onStderr);
498
+ proc.stderr.on("data", onStderr);
444
499
  // Close stdin of previous once piped
445
500
  if (prev && prev.stdin) {
446
501
  prev.stdin.end();
@@ -448,8 +503,8 @@ export function createTerminalTool(config) {
448
503
  prev = proc;
449
504
  }
450
505
  const last = children[children.length - 1];
451
- last.on('close', (code) => finish(code ?? -1));
452
- last.on('error', (err) => finish(-1, String(err?.message ?? err)));
506
+ last.on("close", (code) => finish(code ?? -1));
507
+ last.on("error", (err) => finish(-1, String(err?.message ?? err)));
453
508
  }
454
509
  else {
455
510
  const child = spawn(cmd, cmdArgs, { cwd, env, shell: false });
@@ -457,21 +512,35 @@ export function createTerminalTool(config) {
457
512
  if (args.stdin)
458
513
  child.stdin.write(args.stdin);
459
514
  child.stdin.end();
460
- child.stdout.on('data', onStdout);
461
- child.stderr.on('data', onStderr);
462
- child.on('close', (code) => {
515
+ child.stdout.on("data", onStdout);
516
+ child.stderr.on("data", onStderr);
517
+ child.on("close", (code) => {
463
518
  clearTimeout(timeout);
464
519
  const dur = Date.now() - start;
465
520
  if (session) {
466
521
  session.cwd = cwd;
467
522
  session.expiresAt = Date.now() + cfg.sessions.ttlMs;
468
523
  }
469
- resolve({ exitCode: code ?? -1, stdout, stderr, durationMs: dur, policy: { allowed: true }, cwd });
524
+ resolve({
525
+ exitCode: code ?? -1,
526
+ stdout,
527
+ stderr,
528
+ durationMs: dur,
529
+ policy: { allowed: true },
530
+ cwd,
531
+ });
470
532
  });
471
- child.on('error', (err) => {
533
+ child.on("error", (err) => {
472
534
  clearTimeout(timeout);
473
535
  const dur = Date.now() - start;
474
- resolve({ exitCode: -1, stdout, stderr: String(err.message), durationMs: dur, policy: { allowed: true }, cwd });
536
+ resolve({
537
+ exitCode: -1,
538
+ stdout,
539
+ stderr: String(err.message),
540
+ durationMs: dur,
541
+ policy: { allowed: true },
542
+ cwd,
543
+ });
475
544
  });
476
545
  }
477
546
  });
@@ -488,99 +557,130 @@ export function createTerminalTool(config) {
488
557
  args._createdSessionId = sessionId;
489
558
  }
490
559
  const newPath = canonicalize(path.resolve(session.cwd, args.path));
491
- if (!isPathAllowed(newPath, cfg, 'exec')) {
492
- throw new Error('path outside allowed roots');
560
+ if (!isPathAllowed(newPath, cfg, "exec")) {
561
+ throw new Error("path outside allowed roots");
493
562
  }
494
563
  session.cwd = newPath;
495
564
  session.expiresAt = Date.now() + cfg.sessions.ttlMs;
496
- return { cwd: session.cwd, sessionId: args._createdSessionId ?? args.sessionId };
565
+ return {
566
+ cwd: session.cwd,
567
+ sessionId: args._createdSessionId ?? args.sessionId,
568
+ };
497
569
  }
498
570
  async function read_file(args) {
499
571
  if (!cfg.capabilities.read)
500
- throw new Error('read disabled');
572
+ throw new Error("read disabled");
501
573
  const session = getSession(args.sessionId);
502
574
  const cwd = session?.cwd ?? cfg.roots[0];
503
575
  const abs = canonicalize(path.resolve(cwd, args.path));
504
- if (!isPathAllowed(abs, cfg, 'read'))
505
- throw new Error('path outside allowed roots');
576
+ if (!isPathAllowed(abs, cfg, "read"))
577
+ throw new Error("path outside allowed roots");
506
578
  const buf = await fs.readFile(abs);
507
- const encoding = args.encoding ?? 'utf8';
508
- const contents = encoding === 'base64' ? buf.toString('base64') : buf.toString('utf8');
579
+ const encoding = args.encoding ?? "utf8";
580
+ const contents = encoding === "base64" ? buf.toString("base64") : buf.toString("utf8");
509
581
  return { contents };
510
582
  }
511
583
  const runCommandTool = {
512
- name: 'terminalRun',
584
+ name: "terminalRun",
513
585
  description: [
514
586
  `Run a non-interactive command within allowed roots (${cfg.roots}).`,
515
- `Use for listing files (ls), printing files (cat), simple text processing etc. Allowed commands are ${cfg.commands.allow.join(', ')}.`,
516
- 'Shell operators are rejected and the environment is sanitized before execution.',
517
- 'Always prefer passing a safe single command.',
518
- 'Tips: pass cwd to run in a specific folder; use terminalCd first to set a working directory for subsequent calls; prefer terminalReadFile when you only need file contents.'
519
- ].join(' '),
587
+ `Use for listing files (ls), printing files (cat), simple text processing etc. Allowed commands are ${cfg.commands.allow.join(", ")}.`,
588
+ "Shell operators are rejected and the environment is sanitized before execution.",
589
+ "Always prefer passing a safe single command.",
590
+ "Tips: pass cwd to run in a specific folder; use terminalCd first to set a working directory for subsequent calls; prefer terminalReadFile when you only need file contents.",
591
+ ].join(" "),
520
592
  schema: z.object({
521
593
  command: z.string(),
522
594
  cwd: z.string().optional(),
523
595
  env: z.record(z.string()).optional(),
524
596
  stdin: z.string().optional(),
525
- sessionId: z.string().optional()
597
+ sessionId: z.string().optional(),
526
598
  }),
527
599
  handler: async (a, ctx) => {
528
600
  const s = getSession(a.sessionId);
529
601
  const effCwd = path.resolve(a.cwd ?? s?.cwd ?? cfg.roots[0]);
530
602
  const policy = commandPolicyCheck({ command: a.command, cwd: effCwd }, cfg);
531
- ctx?.log?.debug?.('[terminalRun] policy', { command: a.command, cwd: effCwd, policy });
603
+ ctx?.log?.debug?.("[terminalRun] policy", {
604
+ command: a.command,
605
+ cwd: effCwd,
606
+ policy,
607
+ });
532
608
  const res = await run_command(a);
533
- ctx?.log?.info?.('[terminalRun] result', {
609
+ ctx?.log?.info?.("[terminalRun] result", {
534
610
  command: a.command,
535
611
  cwd: res.cwd,
536
612
  exitCode: res.exitCode,
537
613
  durationMs: res.durationMs,
538
- stdoutBytes: Buffer.byteLength(res.stdout || ''),
539
- stderrBytes: Buffer.byteLength(res.stderr || ''),
614
+ stdoutBytes: Buffer.byteLength(res.stdout || ""),
615
+ stderrBytes: Buffer.byteLength(res.stderr || ""),
540
616
  policy: res.policy,
541
617
  });
542
618
  return res;
543
- }
619
+ },
544
620
  };
545
621
  const cdTool = {
546
- name: 'terminalCd',
622
+ name: "terminalCd",
547
623
  description: [
548
- 'Change the working directory for subsequent terminal operations.',
549
- 'Accepts a path relative to the current directory or absolute within the configured roots.',
550
- 'If no session exists, creates one and returns sessionId.',
551
- 'Use before terminalRun when you need to run multiple commands in the same folder.'
552
- ].join(' '),
624
+ "Change the working directory for subsequent terminal operations.",
625
+ "Accepts a path relative to the current directory or absolute within the configured roots.",
626
+ "If no session exists, creates one and returns sessionId.",
627
+ "Use before terminalRun when you need to run multiple commands in the same folder.",
628
+ ].join(" "),
553
629
  schema: z.object({ path: z.string(), sessionId: z.string().optional() }),
554
630
  handler: async ({ path: relPath, sessionId }, ctx) => {
555
631
  const s = getSession(sessionId);
556
632
  const base = s?.cwd ?? cfg.roots[0];
557
633
  const target = path.resolve(base, relPath);
558
- const allowed = isPathAllowed(target, cfg, 'exec');
559
- ctx?.log?.debug?.('[terminalCd] request', { base, path: relPath, target, allowed });
634
+ const allowed = isPathAllowed(target, cfg, "exec");
635
+ ctx?.log?.debug?.("[terminalCd] request", {
636
+ base,
637
+ path: relPath,
638
+ target,
639
+ allowed,
640
+ });
560
641
  const res = cd({ path: relPath, sessionId });
561
- ctx?.log?.info?.('[terminalCd] result', res);
642
+ ctx?.log?.info?.("[terminalCd] result", res);
562
643
  return res;
563
- }
644
+ },
564
645
  };
565
646
  const readFileTool = {
566
- name: 'terminalReadFile',
647
+ name: "terminalReadFile",
567
648
  description: [
568
- 'Read a small text file from the sandboxed workspace.',
569
- 'Prefer this instead of running `cat` when you only need file contents.',
570
- 'Path must be inside allowed roots; returns UTF-8 text by default.'
571
- ].join(' '),
572
- schema: z.object({ path: z.string(), encoding: z.enum(['utf8', 'base64']).optional(), sessionId: z.string().optional() }),
649
+ "Read a small text file from the sandboxed workspace.",
650
+ "Prefer this instead of running `cat` when you only need file contents.",
651
+ "Path must be inside allowed roots; returns UTF-8 text by default.",
652
+ ].join(" "),
653
+ schema: z.object({
654
+ path: z.string(),
655
+ encoding: z.enum(["utf8", "base64"]).optional(),
656
+ sessionId: z.string().optional(),
657
+ }),
573
658
  handler: async (a, ctx) => {
574
659
  const s = getSession(a.sessionId);
575
660
  const base = s?.cwd ?? cfg.roots[0];
576
661
  const abs = path.resolve(base, a.path);
577
- const allowed = isPathAllowed(abs, cfg, 'read');
578
- ctx?.log?.debug?.('[terminalReadFile] request', { base, path: a.path, abs, allowed });
662
+ const allowed = isPathAllowed(abs, cfg, "read");
663
+ ctx?.log?.debug?.("[terminalReadFile] request", {
664
+ base,
665
+ path: a.path,
666
+ abs,
667
+ allowed,
668
+ });
579
669
  const res = await read_file(a);
580
- ctx?.log?.info?.('[terminalReadFile] result', { abs, bytes: Buffer.byteLength(res.contents || ''), encoding: a.encoding || 'utf8' });
670
+ ctx?.log?.info?.("[terminalReadFile] result", {
671
+ abs,
672
+ bytes: Buffer.byteLength(res.contents || ""),
673
+ encoding: a.encoding || "utf8",
674
+ });
581
675
  return res;
582
- }
676
+ },
583
677
  };
584
678
  // Do not expose start_session as a tool by default to keep the model API simple.
585
- return { start_session, run_command, cd, read_file, tools: [runCommandTool, cdTool, readFileTool] };
679
+ return {
680
+ start_session,
681
+ run_command,
682
+ cd,
683
+ read_file,
684
+ tools: [runCommandTool, cdTool, readFileTool],
685
+ };
586
686
  }
package/package.json CHANGED
@@ -1,21 +1,18 @@
1
1
  {
2
2
  "name": "@sisu-ai/tool-terminal",
3
- "version": "6.0.1",
3
+ "version": "7.0.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "files": [
8
8
  "dist"
9
9
  ],
10
- "scripts": {
11
- "build": "tsc -b"
12
- },
13
10
  "dependencies": {
14
11
  "minimatch": "^9.0.3",
15
12
  "zod": "^3.23.8"
16
13
  },
17
14
  "peerDependencies": {
18
- "@sisu-ai/core": "2.2.1"
15
+ "@sisu-ai/core": "^2.3.1"
19
16
  },
20
17
  "repository": {
21
18
  "type": "git",
@@ -25,5 +22,12 @@
25
22
  "homepage": "https://github.com/finger-gun/sisu#readme",
26
23
  "bugs": {
27
24
  "url": "https://github.com/finger-gun/sisu/issues"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -b",
28
+ "clean": "rm -rf dist",
29
+ "lint": "eslint src --ext .ts,.js",
30
+ "lint:fix": "eslint src --ext .ts,.js --fix",
31
+ "typecheck": "tsc --noEmit"
28
32
  }
29
- }
33
+ }