@gaunt-sloth/agent 2.0.0-alpha.0 → 2.0.0-alpha.10

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 (68) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +9 -0
  3. package/dist/builtInToolsConfig.d.ts +5 -0
  4. package/dist/builtInToolsConfig.js +16 -2
  5. package/dist/builtInToolsConfig.js.map +1 -1
  6. package/dist/core/GthDeepAgent.d.ts +108 -13
  7. package/dist/core/GthDeepAgent.js +352 -121
  8. package/dist/core/GthDeepAgent.js.map +1 -1
  9. package/dist/core/debugCapture.d.ts +8 -49
  10. package/dist/core/debugCapture.js +1 -1
  11. package/dist/core/debugCapture.js.map +1 -1
  12. package/dist/core/deepAgentPermissions.d.ts +72 -12
  13. package/dist/core/deepAgentPermissions.js +191 -29
  14. package/dist/core/deepAgentPermissions.js.map +1 -1
  15. package/dist/core/gthAcpServer.js +11 -0
  16. package/dist/core/gthAcpServer.js.map +1 -1
  17. package/dist/core/gthDeepAgentFactory.d.ts +3 -0
  18. package/dist/core/gthDeepAgentFactory.js +9 -1
  19. package/dist/core/gthDeepAgentFactory.js.map +1 -1
  20. package/dist/core/resolveAgentFactory.d.ts +14 -0
  21. package/dist/core/resolveAgentFactory.js +18 -0
  22. package/dist/core/resolveAgentFactory.js.map +1 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +1 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/mcp/OAuthClientProviderImpl.js +2 -2
  27. package/dist/mcp/OAuthClientProviderImpl.js.map +1 -1
  28. package/dist/middleware/registry.d.ts +1 -1
  29. package/dist/middleware/registry.js +1 -1
  30. package/dist/middleware/types.d.ts +1 -1
  31. package/dist/middleware/types.js +1 -1
  32. package/dist/modules/acpModule.d.ts +5 -2
  33. package/dist/modules/acpModule.js +13 -2
  34. package/dist/modules/acpModule.js.map +1 -1
  35. package/dist/modules/apiAgUiModule.js +48 -16
  36. package/dist/modules/apiAgUiModule.js.map +1 -1
  37. package/dist/modules/interactiveSessionModule.js +130 -7
  38. package/dist/modules/interactiveSessionModule.js.map +1 -1
  39. package/dist/tools/GthDevToolkit.d.ts +45 -1
  40. package/dist/tools/GthDevToolkit.js +204 -17
  41. package/dist/tools/GthDevToolkit.js.map +1 -1
  42. package/dist/tools/gthChecklistTool.d.ts +30 -0
  43. package/dist/tools/gthChecklistTool.js +81 -0
  44. package/dist/tools/gthChecklistTool.js.map +1 -0
  45. package/dist/tools/shell/allowlist.d.ts +11 -0
  46. package/dist/tools/shell/allowlist.js +12 -0
  47. package/dist/tools/shell/allowlist.js.map +1 -0
  48. package/dist/tools/shell/arity.d.ts +11 -0
  49. package/dist/tools/shell/arity.js +12 -0
  50. package/dist/tools/shell/arity.js.map +1 -0
  51. package/dist/tools/shell/env.d.ts +22 -0
  52. package/dist/tools/shell/env.js +110 -0
  53. package/dist/tools/shell/env.js.map +1 -0
  54. package/dist/tools/shell/hardline.d.ts +15 -0
  55. package/dist/tools/shell/hardline.js +88 -0
  56. package/dist/tools/shell/hardline.js.map +1 -0
  57. package/dist/tools/shell/normalize.d.ts +10 -0
  58. package/dist/tools/shell/normalize.js +11 -0
  59. package/dist/tools/shell/normalize.js.map +1 -0
  60. package/dist/tools/shell/outputBuffer.d.ts +53 -0
  61. package/dist/tools/shell/outputBuffer.js +157 -0
  62. package/dist/tools/shell/outputBuffer.js.map +1 -0
  63. package/dist/tools/shell/workDir.d.ts +11 -0
  64. package/dist/tools/shell/workDir.js +45 -0
  65. package/dist/tools/shell/workDir.js.map +1 -0
  66. package/dist/utils/mcpUtils.js +16 -0
  67. package/dist/utils/mcpUtils.js.map +1 -1
  68. package/package.json +14 -10
@@ -1,12 +1,33 @@
1
+ import { isShellToolEnabled } from '@gaunt-sloth/core/config.js';
1
2
  import { GthAbstractAgent } from '@gaunt-sloth/core/core/GthAbstractAgent.js';
2
3
  import { StatusLevel } from '@gaunt-sloth/core/core/types.js';
3
4
  import { debugLog, debugLogObject } from '@gaunt-sloth/core/utils/debugUtils.js';
4
5
  import { buildSystemMessages, formatToolCalls, readChatPrompt, readCodePrompt, readExecPrompt, } from '@gaunt-sloth/core/utils/llmUtils.js';
5
6
  import { getCurrentWorkDir } from '@gaunt-sloth/core/utils/systemUtils.js';
6
7
  import { AIMessage, ToolMessage } from '@langchain/core/messages';
8
+ import { GraphInterrupt } from '@langchain/langgraph';
7
9
  import { createMiddleware } from 'langchain';
8
10
  import { createDeepAgent, FilesystemBackend } from 'deepagents';
9
- import { buildPermissions, FILESYSTEM_TOOL_NAMES, } from '#src/core/deepAgentPermissions.js';
11
+ import { buildPermissions, FILESYSTEM_TOOL_NAMES, guardFilesystemBackend, } from '#src/core/deepAgentPermissions.js';
12
+ import { extractDebugRequestExtras } from '#src/core/debugCapture.js';
13
+ // Re-export so existing importers of this module (extractDebugRequestExtras.spec) keep working
14
+ // now that the implementation lives in @gaunt-sloth/core.
15
+ export { extractDebugRequestExtras } from '#src/core/debugCapture.js';
16
+ import { ShellCommandFailedError } from '#src/tools/GthDevToolkit.js';
17
+ /**
18
+ * EXT-16: decide whether the deepagents filesystem backend must run in virtualMode.
19
+ *
20
+ * deepagents' permission layer (`validatePath`) requires POSIX `/`-rooted glob paths, and its
21
+ * fs tools hand the SAME model-supplied path string to both the permission check and the native
22
+ * `path.resolve`/`fs` backend. On Windows a real cwd is `D:\...`, which can satisfy neither side
23
+ * as one string, so the EXT-13 real-path sandbox throws `Error: path must be absolute` on every
24
+ * turn and the agent hangs. The precise trigger is "the real cwd is not POSIX-rooted", so we key
25
+ * off that directly (not just `win32`): when true, run virtualMode (cwd→`/`) with virtual
26
+ * permissions — the pre-EXT-13 known-good behavior. POSIX keeps the EXT-13 real-path namespace.
27
+ */
28
+ function shouldUseVirtualFs() {
29
+ return !getCurrentWorkDir().startsWith('/');
30
+ }
10
31
  /**
11
32
  * Deep agent: builds a `createDeepAgent` graph (deepagents). All run/stream/event
12
33
  * plumbing lives in {@link GthAbstractAgent}; this class only knows how to construct
@@ -18,7 +39,10 @@ import { buildPermissions, FILESYSTEM_TOOL_NAMES, } from '#src/core/deepAgentPer
18
39
  * {@link FilesystemBackend}. gsloth's `.aiignore` + `filesystem` config are mapped
19
40
  * onto deepagents `permissions` (see {@link buildPermissions}). Any resolved tool
20
41
  * that reuses a deepagents filesystem-tool name is therefore superseded and dropped
21
- * (`createDeepAgent` would otherwise throw on the collision).
42
+ * (`createDeepAgent` would otherwise throw on the collision). EXT-14: the
43
+ * `FilesystemBackend` itself is wrapped with {@link guardFilesystemBackend} before it
44
+ * reaches `createDeepAgent`, adding a realpath (symlink-resolved) containment check the
45
+ * permission globs alone can't provide.
22
46
  * - todos / subagents / summarization come from deepagents' standard middleware.
23
47
  *
24
48
  * The transport-agnostic param assembly lives in {@link buildDeepAgentParams} so the ACP
@@ -26,13 +50,8 @@ import { buildPermissions, FILESYSTEM_TOOL_NAMES, } from '#src/core/deepAgentPer
26
50
  * middleware hardening without re-running `createDeepAgent` locally.
27
51
  */
28
52
  export class GthDeepAgent extends GthAbstractAgent {
29
- /**
30
- * Opt-in debug sink for the TUI `/debug` panel. Set AFTER {@link init} via
31
- * `runner.getAgent()`; read lazily inside the `wrapModelCall` middleware so that when it
32
- * is `undefined` (the normal path) the middleware is a transparent pass-through. Never
33
- * touched by the lean agent or the AG-UI server, so those contracts are unchanged.
34
- */
35
- debugCapture;
53
+ // `debugCapture` (the opt-in TUI `/debug` sink) now lives on the shared GthAbstractAgent base
54
+ // so the lean backend supports it too; the wrapModelCall capture middleware below reads it.
36
55
  async init(command, configIn, checkpointer) {
37
56
  const params = await this.buildDeepAgentParams(command, configIn);
38
57
  // Runner-path only: surface requested tool calls to the console. This is intentionally
@@ -83,32 +102,91 @@ export class GthDeepAgent extends GthAbstractAgent {
83
102
  return response;
84
103
  },
85
104
  });
86
- const middleware = [...params.middleware, toolCallStatusMiddleware, debugCaptureMiddleware];
105
+ // EXT-16: whether the deepagents fs backend runs in virtualMode. deepagents' permission layer
106
+ // requires POSIX `/`-rooted paths, so a Windows real cwd (`D:\...`) can't be expressed as a
107
+ // permission glob and the EXT-13 real-path mode hangs there (`Error: path must be absolute`).
108
+ // When the real cwd isn't POSIX-rooted, fall back to virtualMode (cwd→`/`) with virtual
109
+ // permissions — the pre-EXT-13 known-good Windows behavior. Computed here because the EXT-22 S1
110
+ // middleware (below), the backend, and the systemPrompt gate (further down) all key off it.
111
+ const useVirtualFs = shouldUseVirtualFs();
112
+ // EXT-22 (S1): last-word path-namespace correction. Appends the shared guidance as a trailing
113
+ // system-message block ONLY in code + virtualMode (where the fs virtual `/` root and the
114
+ // shell's real-OS paths diverge); a transparent pass-through otherwise. Added LAST in the
115
+ // middleware array so, being the innermost wrapModelCall, its block lands AFTER deepagents'
116
+ // "All file paths must start with a /." line (see handoff/spike-systemmessage-ordering.md).
117
+ const pathNamespaceCorrectionMiddleware = createPathNamespaceCorrectionMiddleware(this.command === 'code' && useVirtualFs);
118
+ const middleware = [
119
+ ...params.middleware,
120
+ toolCallStatusMiddleware,
121
+ debugCaptureMiddleware,
122
+ pathNamespaceCorrectionMiddleware,
123
+ ];
87
124
  this.statusUpdate(StatusLevel.INFO, `Loaded middleware: ${middleware.map((m) => m.name).join(', ')}`);
88
- // Default: a virtual-root sandbox anchored at cwd (absolute paths / `..` cannot escape).
89
- // `--allow-dir` (config.allowDirs) opts into widening: drop virtualMode so the listed real
90
- // directories are reachable, and rely on the permission allow-rules (built in
91
- // buildDeepAgentParams) to constrain access to cwd + those dirs. This removes a guardrail,
92
- // so it is announced loudly by the exec command and surfaced here in the status log.
125
+ // EXT-13: the backend always runs in REAL-path mode (virtualMode off) so the deepagents fs
126
+ // tools and the EXT-9 run_shell_command tool share ONE path namespace real absolute paths
127
+ // rooted at cwd. Containment is enforced by the permission allow/deny globs built in
128
+ // buildDeepAgentParams (default: allow cwd/**, deny /**), which match what virtualMode used to
129
+ // give for free (see deepAgentPermissions + the EXT-13 symlink/`..` parity tests), PLUS the
130
+ // EXT-14 realpath guard wrapped around the backend below (closes the intermediate-symlinked-
131
+ // directory gap those lexical globs alone can't catch).
132
+ // `--allow-dir` (config.allowDirs) further widens those allow-rules to reach extra real dirs;
133
+ // it removes a guardrail, so it is announced loudly by the exec command and surfaced here.
93
134
  const allowDirs = this.config?.allowDirs;
94
135
  const widenFs = Array.isArray(allowDirs) && allowDirs.length > 0;
95
136
  if (widenFs) {
96
- this.statusUpdate(StatusLevel.WARNING, `Filesystem sandbox widened beyond cwd (--allow-dir): ${allowDirs.join(', ')}`);
137
+ this.statusUpdate(StatusLevel.WARNING, `Filesystem sandbox widened beyond cwd (--allow-dir): ${allowDirs.join(', ')}` +
138
+ (useVirtualFs
139
+ ? ' — note: on this platform the sandbox runs in virtual mode, so widening beyond cwd is not applied.'
140
+ : ''));
97
141
  }
98
- const backend = new FilesystemBackend({
142
+ // EXT-14: layer the realpath containment guard around the backend deepagents' fs middleware
143
+ // (main agent AND every subagent — they all share this one `backend` reference, see
144
+ // guardFilesystemBackend's doc comment) reads/writes through. Closes the intermediate-
145
+ // symlinked-directory escape that the lexical allow/deny globs alone cannot catch.
146
+ const backend = guardFilesystemBackend(new FilesystemBackend({
99
147
  rootDir: getCurrentWorkDir(),
100
- virtualMode: !widenFs,
148
+ virtualMode: useVirtualFs,
149
+ }), {
150
+ cwd: getCurrentWorkDir(),
151
+ virtual: useVirtualFs,
152
+ allowDirs: widenFs ? allowDirs : undefined,
101
153
  });
154
+ // EXT-13 (part b): on the local-runner code path the model used to be told nothing about
155
+ // where it is, so it assumed `/` was cwd and fed `/`-rooted paths to the real-fs shell. Now
156
+ // the backend uses real absolute paths (above), so inject the dynamic real cwd + path model
157
+ // into the prompt the model actually receives. Code mode only — the surface with full fs +
158
+ // shell access; the ACP transport keeps virtualMode and re-roots per session, so this
159
+ // real-path note must NOT leak there (which is why it lives in init(), not the
160
+ // transport-agnostic buildDeepAgentParams).
161
+ // In virtualMode (EXT-16, Windows) the real-cwd note must NOT be injected — it would mislabel
162
+ // the namespace (the fs tools' `/` is the virtual root, not the real cwd). Instead, EXT-22 (S2)
163
+ // injects the virtualMode path-namespace note so the model is told EARLY that the fs virtual
164
+ // `/` root and run_shell_command's real-OS paths differ (the S1 middleware repeats it as the
165
+ // authoritative last word after deepagents' `/`-rooted line). Non-code paths get neither.
166
+ // EXT-26: after the cwd/virtual-cwd note, append the OS + shell-dialect note so the model is
167
+ // told its host OS and which shell run_shell_command spawns (cmd.exe on Windows, /bin/sh on
168
+ // POSIX). This is ORTHOGONAL to the path-namespace notes above (those say WHERE it is; this
169
+ // says WHAT shell it speaks) and applies in BOTH code-mode branches, independent of
170
+ // virtualMode — the shell dialect matters on every platform. Non-code paths get nothing new.
171
+ const systemPrompt = this.command === 'code'
172
+ ? appendOsShellNote(useVirtualFs
173
+ ? appendVirtualCwdNote(params.systemPrompt)
174
+ : appendCwdNote(params.systemPrompt, getCurrentWorkDir()))
175
+ : params.systemPrompt;
102
176
  this.agent = createDeepAgent({
103
177
  model: params.model,
104
178
  tools: params.tools,
105
179
  // gsloth's composed prompt, combined ADDITIVELY by deepagents with its base + fs prompts
106
180
  // into a single system message (avoids the two-system-message Anthropic rejection).
107
- systemPrompt: params.systemPrompt,
181
+ systemPrompt,
108
182
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
109
183
  middleware: middleware,
110
184
  backend,
111
185
  permissions: params.permissions,
186
+ // Per-tool human-in-the-loop gating (e.g. run_shell_command confirmation). When set,
187
+ // deepagents installs humanInTheLoopMiddleware so a matching tool call suspends the graph
188
+ // for approval; `undefined` (the default, and under yolo) leaves every tool ungated.
189
+ interruptOn: params.interruptOn,
112
190
  checkpointer,
113
191
  });
114
192
  debugLog('Deep agent created successfully');
@@ -202,11 +280,20 @@ export class GthDeepAgent extends GthAbstractAgent {
202
280
  }
203
281
  return true;
204
282
  });
205
- // Soften deepagents' fail-hard filesystem permission denials. By default a denied
206
- // read/write THROWS, which aborts the whole run; wrap tool calls so a denial becomes
207
- // a recoverable ToolMessage instead, letting the model continue and report it. This
208
- // preserves gsloth's recoverable-denial UX (the old GthFileSystemToolkit returned a
209
- // message rather than throwing).
283
+ // Soften deepagents' fail-hard filesystem tool throws. By default the permission layer
284
+ // THROWS on both a denied read/write AND on a malformed path the model supplied a relative
285
+ // path, a `..`/`~` segment, or an empty string (deepagents' validatePath, run BEFORE the
286
+ // permission check in enforcePermission). Any of these aborts the WHOLE run. On the AG-UI
287
+ // transport that throw propagates out of streamWithEvents into the run handler's catch, which
288
+ // emits RUN_ERROR and ends the response WITHOUT a terminal RUN_FINISHED — and since AG-UI's
289
+ // protocol makes RUN_ERROR terminal ("no further events can be sent"), a consumer waiting for
290
+ // RUN_FINISHED hangs (EXT-24). Wrap tool calls so each of these becomes a recoverable error
291
+ // ToolMessage instead, letting the model observe the mistake, retry with a good path, and
292
+ // finish the run normally (reaching RUN_FINISHED). This preserves gsloth's recoverable-denial
293
+ // UX (the old GthFileSystemToolkit returned a message rather than throwing). Only these known
294
+ // fs path/permission messages are caught; every other throw (GraphInterrupt from a client-tool
295
+ // interrupt stub, AbortError on client disconnect, unexpected errors) is rethrown untouched so
296
+ // control-flow and genuine failures still surface.
210
297
  const fsDenialSoftening = createMiddleware({
211
298
  name: 'GthDeepFsDenialSoftening',
212
299
  wrapToolCall: async (request, handler) => {
@@ -214,9 +301,24 @@ export class GthDeepAgent extends GthAbstractAgent {
214
301
  return await handler(request);
215
302
  }
216
303
  catch (e) {
304
+ // EXT-25: rethrow control-flow throws BY TYPE, BEFORE the message regex below. A
305
+ // GraphInterrupt (a client-tool interrupt() suspending the graph for HITL tool
306
+ // approval) and an AbortError (caller cancellation) must ALWAYS propagate so the graph
307
+ // suspends / cancels — never be converted into a benign ToolMessage. Mirrors the guard
308
+ // in GthAbstractAgent (error.name checks + GraphInterrupt instanceof). Today these
309
+ // survive only because their messages happen not to match the regex; guarding by type
310
+ // stops a future regex broadening from silently swallowing the HITL suspend.
311
+ if (e instanceof GraphInterrupt ||
312
+ e?.name === 'GraphInterrupt' ||
313
+ e?.name === 'AbortError') {
314
+ throw e;
315
+ }
217
316
  const message = e instanceof Error ? e.message : String(e);
218
- if (/permission denied for (read|write)/i.test(message)) {
219
- debugLog(`Softened fs permission denial into a ToolMessage: ${message}`);
317
+ // deepagents fs enforcement throws (middleware/fs.ts enforcePermission +
318
+ // permissions/enforce.ts validatePath): a permission denial, or a path that is
319
+ // relative / contains ".." or "~" / is empty. All are recoverable model-input errors.
320
+ if (/permission denied for (read|write)|path must (be absolute|not contain|be a non-empty string)/i.test(message)) {
321
+ debugLog(`Softened fs tool throw into a ToolMessage: ${message}`);
220
322
  return new ToolMessage({
221
323
  content: message,
222
324
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -228,10 +330,44 @@ export class GthDeepAgent extends GthAbstractAgent {
228
330
  }
229
331
  },
230
332
  });
231
- // fsDenialSoftening first so it is the outermost wrapToolCall it must see the throw
232
- // from deepagents' permission-enforcing fs tools. The console-bound tool-call-status
233
- // middleware is NOT added here (see GthDeepAgentParams.middleware); the runner appends it.
234
- const middleware = [fsDenialSoftening, ...configuredMiddleware];
333
+ // EXT-20: sibling of fsDenialSoftening for the run_* (dev/shell) tools. GthDevToolkit's
334
+ // executeCommand now THROWS a ShellCommandFailedError on a non-zero exit or a timeout-kill
335
+ // (instead of resolving with the failure text), so the tool result no longer misreports
336
+ // status:'success' (✓). Catch it here and return an error ToolMessage that PRESERVES the full
337
+ // stdout/stderr body — the model's observation is unchanged except that status flips to
338
+ // 'error', which drives the ✗ (isError) glyph (GthAbstractAgent maps status==='error' →
339
+ // isError). Returning a ToolMessage (rather than rethrowing) also means the approved-then-failed
340
+ // command does NOT trigger a retry loop — it is a normal, observed tool result.
341
+ const shellExitSoftening = createMiddleware({
342
+ name: 'GthDeepShellExitSoftening',
343
+ wrapToolCall: async (request, handler) => {
344
+ try {
345
+ return await handler(request);
346
+ }
347
+ catch (e) {
348
+ if (e instanceof ShellCommandFailedError) {
349
+ debugLog(`Softened shell/dev command failure (exit ${e.exitCode ?? 'timeout'}) into an ` +
350
+ `error ToolMessage for '${e.command}'`);
351
+ return new ToolMessage({
352
+ content: e.output,
353
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
354
+ tool_call_id: request.toolCall?.id ?? '',
355
+ status: 'error',
356
+ });
357
+ }
358
+ throw e;
359
+ }
360
+ },
361
+ });
362
+ // fsDenialSoftening first so it is the outermost wrapToolCall — it must see the throw from
363
+ // deepagents' permission-enforcing fs tools. shellExitSoftening sits right after it (still
364
+ // outboard of any user-configured middleware, so it always sees the raw ShellCommandFailedError
365
+ // throw before a user wrapToolCall could transform it). Order between the two softeners is not
366
+ // load-bearing: they catch DISJOINT conditions (a permission-denied regex vs an
367
+ // `instanceof ShellCommandFailedError`) and each rethrows what it doesn't recognize, so neither
368
+ // can swallow the other. The console-bound tool-call-status middleware is NOT added here (see
369
+ // GthDeepAgentParams.middleware); the runner appends it.
370
+ const middleware = [fsDenialSoftening, shellExitSoftening, ...configuredMiddleware];
235
371
  // Map gsloth's .aiignore + filesystem mode onto deepagents permission rules. When
236
372
  // `--allow-dir` widens the sandbox, the backend runs without virtualMode, so paths are REAL
237
373
  // absolute paths: constrain read+write to cwd + the allowed dirs (everything else denied),
@@ -242,7 +378,10 @@ export class GthDeepAgent extends GthAbstractAgent {
242
378
  allowDirs: Array.isArray(this.config.allowDirs) && this.config.allowDirs.length > 0
243
379
  ? this.config.allowDirs
244
380
  : undefined,
245
- });
381
+ },
382
+ // EXT-16: build virtual (`/`-rooted) permission rules when the backend will run in
383
+ // virtualMode (Windows), matching the FilesystemBackend created in init().
384
+ shouldUseVirtualFs());
246
385
  debugLogObject('Filesystem permissions', permissions);
247
386
  // Compose gsloth's system prompt (backstory + guidelines + per-command mode prompt +
248
387
  // system prompt) so identity profiles (Gaunt Sloth, sorcerer, fisher-alt, …) and
@@ -258,111 +397,203 @@ export class GthDeepAgent extends GthAbstractAgent {
258
397
  : readChatPrompt(this.config);
259
398
  const systemMessages = buildSystemMessages(this.config, modePrompt);
260
399
  const systemPrompt = typeof systemMessages[0]?.content === 'string' ? systemMessages[0].content : undefined;
400
+ // Gate the opt-in run_shell_command tool behind a per-command approval interrupt. The tool
401
+ // is only emitted (by GthDevToolkit, via builtInToolsConfig) when its devTools.shell flag is
402
+ // set; mirror the same per-command devTools resolution here so the interrupt is wired only
403
+ // when the tool actually exists.
404
+ const devTools = this.getEffectiveDevToolsConfig();
405
+ // EXT-12 — pass the active command so the absent-config default (shell ON in `code`)
406
+ // is applied consistently with where the tool is actually emitted (GthDevToolkit).
407
+ const shellEnabled = isShellToolEnabled(devTools, this.command);
408
+ // EXT-12 — auto-approve (shellYolo) interplay with gating:
409
+ // • In interactive `code` mode we KEEP the tool gated even when shellYolo pre-enables
410
+ // auto-approval, so the runner's session flag governs it and `/auto-approve off` can
411
+ // restore the per-command prompt mid-session. The runner seeds that flag ON from
412
+ // shellYolo (see GthAgentRunner.init), so the user still sees no prompt by default; the
413
+ // interactive event/stream path drains the interrupt and auto-approves silently.
414
+ // • In non-interactive modes (exec / ask --write) a single-shot run does NOT drain
415
+ // interrupts, so shellYolo keeps the tool UNGATED (runs inline without suspending),
416
+ // preserving prior behaviour. There is no slash-command surface there to toggle anyway.
417
+ const isInteractive = this.command === 'code';
418
+ const gateShell = shellEnabled && (devTools?.shellYolo !== true || isInteractive);
419
+ const interruptOn = gateShell
420
+ ? { run_shell_command: { allowedDecisions: ['approve', 'reject'] } }
421
+ : undefined;
422
+ if (gateShell && devTools?.shellYolo === true) {
423
+ this.statusUpdate(StatusLevel.INFO, 'Shell tool (run_shell_command) auto-approved by config (shellYolo). Type /auto-approve off to require per-command approval.');
424
+ }
425
+ else if (interruptOn) {
426
+ this.statusUpdate(StatusLevel.INFO, 'Shell tool (run_shell_command) enabled with per-command approval (interruptOn).');
427
+ }
428
+ else if (shellEnabled) {
429
+ this.statusUpdate(StatusLevel.WARNING, 'Shell tool (run_shell_command) enabled in YOLO mode: commands run WITHOUT confirmation.');
430
+ }
261
431
  return {
262
432
  model: this.config.llm,
263
433
  tools: passThroughTools,
264
434
  permissions,
265
435
  middleware,
266
436
  systemPrompt,
437
+ interruptOn,
267
438
  };
268
439
  }
440
+ /**
441
+ * Resolve the {@link GthDevToolsConfig} that applies to the active command, mirroring the
442
+ * per-command selection in `builtInToolsConfig.getDefaultTools` (which is what actually emits
443
+ * the dev tools): `exec` → `commands.exec.devTools`, `ask --write` → `commands.ask.devTools`,
444
+ * otherwise (`code`) → `commands.code.devTools`. Returns `undefined` for any other command,
445
+ * matching the toolkit being inert there. Kept private and side-effect-free so the interrupt
446
+ * wiring above and the tool emission stay in lockstep.
447
+ */
448
+ getEffectiveDevToolsConfig() {
449
+ const config = this.config;
450
+ if (!config)
451
+ return undefined;
452
+ const command = this.command;
453
+ const askWrite = command === 'ask' && config.askWriteMode === true;
454
+ if (command === 'exec')
455
+ return config.commands?.exec?.devTools;
456
+ if (askWrite)
457
+ return config.commands?.ask?.devTools;
458
+ if (command === 'code')
459
+ return config.commands?.code?.devTools;
460
+ return undefined;
461
+ }
269
462
  }
270
463
  /**
271
- * Scalar model-param fields worth surfacing in the `/debug` panel. Deliberately an
272
- * allowlist (NOT a whole-object dump) so no credential field (`apiKey`, `accessToken`, …)
273
- * can ever leak into the rendered debug view.
464
+ * EXT-22: shared virtualMode path-namespace guidance ONE source of truth used by BOTH the S2
465
+ * early-framing note ({@link appendVirtualCwdNote}, injected into gsloth's composed systemPrompt =
466
+ * block 0) and the S1 last-word correction middleware
467
+ * ({@link createPathNamespaceCorrectionMiddleware}, appended after deepagents' `/`-rooted line).
468
+ *
469
+ * In a virtualMode `code` session (EXT-16, e.g. Windows) the deepagents filesystem tools use a
470
+ * VIRTUAL `/` root (= the working dir) while `run_shell_command` uses REAL native OS paths; the
471
+ * model conflates the two forms. This text draws the distinction and steers toward cwd-relative
472
+ * paths (the one form both tool families read alike).
274
473
  *
275
- * `streaming` is intentionally NOT here: it is the model instance's static flag, which is
276
- * usually `false` even when the turn streams the GthAgentRunner decides streaming by calling
277
- * `.stream()` vs `.invoke()`, not by this property so surfacing it just misleads.
474
+ * It deliberately does NOT equate the virtual root with a specific real path (no "`/` = D:\\work"):
475
+ * virtualMode withholds the real cwd on purpose (see the systemPrompt gate in {@link
476
+ * GthDeepAgent.init}), so the guidance is about the DISTINCTION between the two namespaces and the
477
+ * safety of relative paths, not a mapping between them.
278
478
  */
279
- const DEBUG_MODEL_PARAM_KEYS = [
280
- 'model',
281
- 'modelName',
282
- 'modelId',
283
- 'deploymentName',
284
- 'temperature',
285
- 'topP',
286
- 'topK',
287
- 'maxTokens',
288
- 'maxOutputTokens',
289
- 'maxReasoningTokens',
290
- 'reasoningEffort',
291
- 'thinkingBudget',
292
- 'stop',
293
- 'provider',
294
- ];
295
- /** Pull the key-free scalar model params from the (provider-specific) model instance. */
296
- function extractModelParams(model) {
297
- if (!model || typeof model !== 'object')
298
- return undefined;
299
- const src = model;
300
- const out = {};
301
- for (const key of DEBUG_MODEL_PARAM_KEYS) {
302
- const value = src[key];
303
- if (value === undefined || value === null)
304
- continue;
305
- // Only scalars / scalar arrays — never nested objects that could carry credentials.
306
- if (typeof value === 'object' && !Array.isArray(value))
307
- continue;
308
- out[key] = value;
309
- }
310
- // `model` / `modelName` / `modelId` are langchain aliases for the same value; collapse the
311
- // duplicates so the panel shows the model id once instead of two identical lines.
312
- if (typeof out.model !== 'string' && typeof out.modelName === 'string') {
313
- out.model = out.modelName;
314
- }
315
- if (out.modelName === out.model)
316
- delete out.modelName;
317
- if (out.modelId === out.model)
318
- delete out.modelId;
319
- return Object.keys(out).length > 0 ? out : undefined;
479
+ export const PATH_NAMESPACE_GUIDANCE = 'The filesystem tools (ls, read_file, write_file, edit_file, glob, grep) use a VIRTUAL root in ' +
480
+ 'this session: a leading `/` means your working directory, and their paths are written ' +
481
+ '`/`-rooted relative to it (this is what "all file paths must start with a /" refers to). That ' +
482
+ '`/` is NOT the real operating-system filesystem root. run_shell_command is different: it runs ' +
483
+ 'in the real operating system and uses real native paths (on Windows, e.g. ' +
484
+ '`C:\\Users\\...\\project`, with backslashes), never the virtual `/` root. A `/`-rooted path ' +
485
+ 'from the filesystem tools is NOT a valid shell path and must never be passed to ' +
486
+ 'run_shell_command. The one form that means the same thing to both tool families is a path ' +
487
+ 'RELATIVE to the working directory (e.g. `src/index.ts`); prefer relative paths for both. When ' +
488
+ 'you must be absolute, use `/`-rooted form ONLY for the filesystem tools and real native form ' +
489
+ 'ONLY for run_shell_command.';
490
+ /**
491
+ * EXT-22 (S2): virtualMode variant of {@link appendCwdNote}. On the `code` path when the fs
492
+ * backend runs in virtualMode (EXT-16), inject the shared path-namespace guidance EARLY in
493
+ * gsloth's composed systemPrompt (block 0) so the model is framed before deepagents' own prompt.
494
+ *
495
+ * This is early framing only: deepagents' hardcoded `/`-rooted line lands in a LATER block and can
496
+ * partially override block 0, so the authoritative last word is delivered by the S1 middleware
497
+ * ({@link createPathNamespaceCorrectionMiddleware}); see handoff/spike-systemmessage-ordering.md.
498
+ * Returns the note alone when there is no base prompt.
499
+ */
500
+ export function appendVirtualCwdNote(systemPrompt) {
501
+ const note = `Filesystem vs shell path namespaces: ${PATH_NAMESPACE_GUIDANCE}`;
502
+ return systemPrompt ? `${systemPrompt}\n\n${note}` : note;
320
503
  }
321
- /** Best-effort tool definition (name + description + schema) for the debug view. */
322
- function extractToolDefs(tools) {
323
- if (!Array.isArray(tools) || tools.length === 0)
324
- return undefined;
325
- const defs = [];
326
- for (const tool of tools) {
327
- if (!tool || typeof tool !== 'object')
328
- continue;
329
- const t = tool;
330
- const name = typeof t.name === 'string' ? t.name : undefined;
331
- if (!name)
332
- continue;
333
- const description = typeof t.description === 'string' ? t.description : undefined;
334
- // LangChain StructuredTools expose a Zod/JSON `schema`; some carry it on `lc_kwargs`.
335
- const schema = t.schema ?? undefined;
336
- defs.push({ name, description, schema });
337
- }
338
- return defs.length > 0 ? defs : undefined;
504
+ /**
505
+ * EXT-22 (S1): the load-bearing path-namespace correction. A gsloth `wrapModelCall` middleware
506
+ * runs INNERMOST (inside deepagents' filesystem middleware), so appending a trailing block to
507
+ * `request.systemMessage` lands AFTER deepagents' hardcoded "All file paths must start with a /."
508
+ * line — giving gsloth the last word on path semantics (empirically verified; see
509
+ * handoff/spike-systemmessage-ordering.md). It APPENDS via `request.systemMessage.concat(...)`
510
+ * (mirroring how deepagents appends its own fs prompt), never string-splices, and returns a NEW
511
+ * request so it never mutates persisted state (no compounding across turns).
512
+ *
513
+ * `appendCorrection` gates it to `code` + virtualMode: only there do the fs virtual `/` root and
514
+ * the shell's real-OS paths diverge. On POSIX real-path mode deepagents' "start with /" is
515
+ * literally true, so the middleware is a transparent pass-through (like the debug-capture
516
+ * middleware when no sink is attached).
517
+ */
518
+ export function createPathNamespaceCorrectionMiddleware(appendCorrection) {
519
+ return createMiddleware({
520
+ name: 'GthDeepPathNamespaceCorrection',
521
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
522
+ wrapModelCall: async (request, handler) => {
523
+ if (!appendCorrection || !request?.systemMessage)
524
+ return handler(request);
525
+ const correction = 'IMPORTANT — path namespaces (authoritative; this overrides any earlier instruction that ' +
526
+ `implies every path is a simple \`/\`-rooted filesystem path): ${PATH_NAMESPACE_GUIDANCE}`;
527
+ return handler({ ...request, systemMessage: request.systemMessage.concat(correction) });
528
+ },
529
+ });
339
530
  }
340
531
  /**
341
- * Assemble the non-message request parts ({@link DebugRequestExtras}) for the `/debug`
342
- * panel from a `wrapModelCall` request, defensively and key-free. Never throws (the caller
343
- * already guards, but a debug sink must never break a run) and never dumps the raw model.
532
+ * EXT-13 (part b): append a real-cwd / path-model note to the composed code-mode system prompt.
533
+ *
534
+ * The default code-mode backend runs in REAL-path mode (no virtualMode), so the deepagents fs
535
+ * tools and `run_shell_command` share one real-absolute-path namespace rooted at `cwd`. Neither
536
+ * deepagents' base prompt nor `.gsloth.code.md` states the actual cwd, so without this the model
537
+ * assumes `/` is cwd and hands `/`-rooted paths to the real-fs shell. The cwd is injected
538
+ * dynamically (never baked into the .md). Returns the note alone when there is no base prompt.
344
539
  */
345
- export function extractDebugRequestExtras(request) {
346
- if (!request || typeof request !== 'object')
347
- return undefined;
348
- const req = request;
349
- const systemMessage = req.systemMessage;
350
- const systemPrompt = typeof req.systemPrompt === 'string' && req.systemPrompt
351
- ? req.systemPrompt
352
- : typeof systemMessage?.content === 'string'
353
- ? systemMessage.content
354
- : undefined;
355
- const extras = {
356
- systemPrompt,
357
- tools: extractToolDefs(req.tools),
358
- modelParams: extractModelParams(req.model),
359
- toolChoice: req.toolChoice,
360
- };
361
- // Return undefined when nothing useful was captured so the renderer can show a clear empty state.
362
- const hasAny = extras.systemPrompt !== undefined ||
363
- extras.tools !== undefined ||
364
- extras.modelParams !== undefined ||
365
- extras.toolChoice !== undefined;
366
- return hasAny ? extras : undefined;
540
+ export function appendCwdNote(systemPrompt, cwd) {
541
+ const cwdNote = `Working directory: ${cwd}\n` +
542
+ 'Paths are real absolute filesystem paths (there is no virtual root). The working directory ' +
543
+ 'above is where this session runs; relative paths resolve against it, and both the filesystem ' +
544
+ 'tools (ls/glob/read_file/write_file/edit_file/grep) and run_shell_command operate on these ' +
545
+ 'same real paths. Check the current directory before filesystem operations and prefer absolute ' +
546
+ 'paths (or paths relative to the working directory); do not assume the current directory is "/".';
547
+ return systemPrompt ? `${systemPrompt}\n\n${cwdNote}` : cwdNote;
548
+ }
549
+ /**
550
+ * EXT-26: the platform-agnostic tail shared by both {@link appendOsShellNote} branches.
551
+ *
552
+ * The recurring failure mode on non-POSIX hosts is not just wrong command NAMES but shell
553
+ * REDIRECTION quoting: a grouped/multi-line `echo` redirect on cmd.exe reported success yet wrote
554
+ * a 0-byte file. So on every platform we steer file creation/mutation to the deepagents built-in
555
+ * `write_file`/`edit_file` tools (which never touch the shell's quoting) and keep each shell
556
+ * command a single line. Kept short this is prompt text an LLM reads, not documentation.
557
+ */
558
+ export const OS_SHELL_GUIDANCE = 'Prefer the built-in write_file / edit_file tools over shell echo/redirection to create or ' +
559
+ 'modify files: shell redirection quoting is unreliable and can silently write an empty ' +
560
+ '(0-byte) file. Keep each run_shell_command a single line.';
561
+ /**
562
+ * EXT-26: append an OS + shell-dialect note to the composed code-mode system prompt.
563
+ *
564
+ * The deep-agent model was never told its host OS or which shell `run_shell_command` uses, so on
565
+ * non-POSIX hosts it defaulted to POSIX idioms that fail (ran `ls` where cmd.exe has `dir`, a
566
+ * multi-line echo-redirect that wrote 0 bytes, a PowerShell here-string, `python -c` multi-line).
567
+ * This is ORTHOGONAL to the EXT-13/16/22 path-namespace notes: those say WHERE the model is (path
568
+ * form); this says WHAT shell it speaks (dialect).
569
+ *
570
+ * The shell is derived from the SAME rule Node's `spawn(command, { shell: true })` uses — exactly
571
+ * how `run_shell_command` spawns (GthDevToolkit spawn) — so on `win32` it is cmd.exe (via
572
+ * `%ComSpec%`) and on POSIX it is `/bin/sh` (POSIX sh, NOT guaranteed bash). Computed from
573
+ * `process.platform` at call time so the text is correct per host. Returns the note alone when
574
+ * there is no base prompt. A single injection is authoritative (nothing in deepagents' base prompt
575
+ * contradicts shell dialect), so unlike EXT-22 no correction middleware is needed.
576
+ */
577
+ export function appendOsShellNote(systemPrompt) {
578
+ let note;
579
+ if (process.platform === 'win32') {
580
+ note =
581
+ 'Host operating system: Windows. `run_shell_command` runs in cmd.exe. Use native cmd ' +
582
+ 'syntax: `dir` (not `ls`), `type` (not `cat`), `copy` / `move` / `del`, `%VAR%` for ' +
583
+ 'environment variables, and backslash paths. Do NOT use POSIX-only idioms: no sh/bash ' +
584
+ 'heredocs (`<< EOF`), no here-strings (`<<<`), no multi-line quoted command blocks, and do ' +
585
+ `not assume POSIX quoting. ${OS_SHELL_GUIDANCE}`;
586
+ }
587
+ else {
588
+ const osName = process.platform === 'darwin' ? 'macOS' : 'Linux';
589
+ note =
590
+ `Host operating system: ${osName}. \`run_shell_command\` runs in /bin/sh (POSIX sh, not ` +
591
+ 'necessarily bash). Stick to POSIX sh syntax and avoid bash-only constructs such as ' +
592
+ `here-strings (\`<<<\`) and \`[[ ]]\` tests. ${OS_SHELL_GUIDANCE}`;
593
+ }
594
+ return systemPrompt ? `${systemPrompt}\n\n${note}` : note;
367
595
  }
596
+ // The `/debug` request-extras extraction (extractDebugRequestExtras + its model-param / tool-def
597
+ // allowlist helpers) now lives in @gaunt-sloth/core (`core/debugCapture.ts`) so the lean backend
598
+ // shares it. Imported at the top of this module and re-exported for back-compat.
368
599
  //# sourceMappingURL=GthDeepAgent.js.map