Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat: implement persistent current working directory state and update all filesystem and git tools to support relative paths

Salman Qureshif2bc1ddc2fbc
diff --git a/src/capabilities/filesystem/approve-scope.ts b/src/capabilities/filesystem/approve-scope.ts
index cb962e3d..e9937b90 100644
--- a/src/capabilities/filesystem/approve-scope.ts
+++ b/src/capabilities/filesystem/approve-scope.ts
@@ -1,9 +1,9 @@
import { tool } from 'ai';
import { z } from 'zod';
-import { resolve } from 'node:path';
+import { resolve, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
-export function createApproveScopeTool(permissions: PermissionManager) {
+export function createApproveScopeTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Request user approval to access a directory outside current scopes. Use this when a file tool returns a permission denied error. The user gets an approval prompt (Allow/Always/Deny buttons on Telegram, yes/always/no on CLI). "Allow" grants session-only access. "Always" persists to disk. After approval, retry the original file operation.',
parameters: z.object({
@@ -11,7 +11,7 @@ export function createApproveScopeTool(permissions: PermissionManager) {
mode: z.enum(['read', 'write']).describe('The access mode needed'),
}),
execute: async ({ path, mode }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const result = await permissions.requestScopeExternal(resolved, mode);
if (result.allowed) {
return `Access approved for ${mode} access to ${resolved}. You can now retry the file operation.`;
diff --git a/src/capabilities/filesystem/create-file.ts b/src/capabilities/filesystem/create-file.ts
index 0233535d..0fd05825 100644
--- a/src/capabilities/filesystem/create-file.ts
+++ b/src/capabilities/filesystem/create-file.ts
@@ -1,10 +1,10 @@
import { tool } from 'ai';
import { z } from 'zod';
import { existsSync, writeFileSync, mkdirSync } from 'node:fs';
-import { resolve, dirname } from 'node:path';
+import { resolve, dirname, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
-export function createCreateFileTool(permissions: PermissionManager) {
+export function createCreateFileTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Create a new file with the given content. Also creates parent directories if needed. The path must be within a writable scope.',
parameters: z.object({
@@ -12,7 +12,7 @@ export function createCreateFileTool(permissions: PermissionManager) {
content: z.string().describe('The content of the new file'),
}),
execute: async ({ path, content }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const check = await permissions.checkFsAccess(resolved, 'write');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/filesystem/delete-file.ts b/src/capabilities/filesystem/delete-file.ts
index b23ea589..7a90d6b4 100644
--- a/src/capabilities/filesystem/delete-file.ts
+++ b/src/capabilities/filesystem/delete-file.ts
@@ -1,17 +1,17 @@
import { tool } from 'ai';
import { z } from 'zod';
import { existsSync, unlinkSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { resolve, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
-export function createDeleteFileTool(permissions: PermissionManager) {
+export function createDeleteFileTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Delete a file. This action cannot be undone. The path must be within a writable scope. Always asks for confirmation.',
parameters: z.object({
path: z.string().describe('Absolute or relative path to the file to delete'),
}),
execute: async ({ path }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const check = await permissions.checkFsAccess(resolved, 'write');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/filesystem/edit-file.ts b/src/capabilities/filesystem/edit-file.ts
index 3e55309b..a4d9efe1 100644
--- a/src/capabilities/filesystem/edit-file.ts
+++ b/src/capabilities/filesystem/edit-file.ts
@@ -1,10 +1,10 @@
import { tool } from 'ai';
import { z } from 'zod';
import { readFileSync, writeFileSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { resolve, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
-export function createEditFileTool(permissions: PermissionManager) {
+export function createEditFileTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Edit a file by replacing an exact string match with new content. Use this instead of write_file when you only need to change part of a file. The old_string must match exactly (including whitespace and indentation). Fails if old_string is not found or found multiple times.',
parameters: z.object({
@@ -13,7 +13,7 @@ export function createEditFileTool(permissions: PermissionManager) {
new_string: z.string().describe('The text to replace it with'),
}),
execute: async ({ path, old_string, new_string }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const fsCheck = await permissions.checkFsAccess(resolved, 'write');
if (!fsCheck.allowed) {
diff --git a/src/capabilities/filesystem/list-dir.ts b/src/capabilities/filesystem/list-dir.ts
index 8f83953d..148ba452 100644
--- a/src/capabilities/filesystem/list-dir.ts
+++ b/src/capabilities/filesystem/list-dir.ts
@@ -1,17 +1,17 @@
import { tool } from 'ai';
import { z } from 'zod';
import { existsSync, readdirSync, statSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { resolve, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
-export function createListDirTool(permissions: PermissionManager) {
+export function createListDirTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'List the contents of a directory. Shows file names, types, and sizes.',
parameters: z.object({
path: z.string().describe('Absolute or relative path to the directory'),
}),
execute: async ({ path }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
return `Error: Permission denied for read access to ${resolved}. Use the approve_scope tool with path="${resolved}" and mode="read" to request access from the user.`;
diff --git a/src/capabilities/filesystem/read-file.ts b/src/capabilities/filesystem/read-file.ts
index b5ddf976..1dc06bb4 100644
--- a/src/capabilities/filesystem/read-file.ts
+++ b/src/capabilities/filesystem/read-file.ts
@@ -1,17 +1,17 @@
import { tool } from 'ai';
import { z } from 'zod';
import { existsSync, readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
+import { resolve, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
-export function createReadFileTool(permissions: PermissionManager) {
+export function createReadFileTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Read the contents of a file. The path must be within an allowed scope.',
parameters: z.object({
path: z.string().describe('Absolute or relative path to the file'),
}),
execute: async ({ path }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/filesystem/send-file.ts b/src/capabilities/filesystem/send-file.ts
index c6e89424..65aa3772 100644
--- a/src/capabilities/filesystem/send-file.ts
+++ b/src/capabilities/filesystem/send-file.ts
@@ -1,11 +1,12 @@
import { tool } from 'ai';
import { z } from 'zod';
import { existsSync, statSync } from 'node:fs';
-import { resolve, basename } from 'node:path';
+import { resolve, basename, isAbsolute } from 'node:path';
import type { PermissionManager } from '../permissions.js';
export function createSendFileTool(
permissions: PermissionManager,
+ getCwd: () => string,
sendFile: (filePath: string) => Promise<void>,
) {
return tool({
@@ -15,7 +16,7 @@ export function createSendFileTool(
path: z.string().describe('Absolute or relative path to the file to send'),
}),
execute: async ({ path }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const check = await permissions.checkFsAccess(resolved, 'read');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/filesystem/write-file.ts b/src/capabilities/filesystem/write-file.ts
index de892b35..49148cb4 100644
--- a/src/capabilities/filesystem/write-file.ts
+++ b/src/capabilities/filesystem/write-file.ts
@@ -1,11 +1,11 @@
import { tool } from 'ai';
import { z } from 'zod';
import { existsSync, writeFileSync, readFileSync } from 'node:fs';
-import { resolve, dirname } from 'node:path';
+import { resolve, dirname, isAbsolute } from 'node:path';
import { mkdirSync } from 'node:fs';
import type { PermissionManager } from '../permissions.js';
-export function createWriteFileTool(permissions: PermissionManager) {
+export function createWriteFileTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Write content to an existing file. The path must be within a writable scope.',
parameters: z.object({
@@ -13,7 +13,7 @@ export function createWriteFileTool(permissions: PermissionManager) {
content: z.string().describe('The content to write to the file'),
}),
execute: async ({ path, content }) => {
- const resolved = resolve(path);
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(getCwd(), path);
const check = await permissions.checkFsAccess(resolved, 'write');
if (!check.allowed) {
const parentDir = resolve(resolved, '..');
diff --git a/src/capabilities/git/git-add.ts b/src/capabilities/git/git-add.ts
index e514eb57..ad2afe92 100644
--- a/src/capabilities/git/git-add.ts
+++ b/src/capabilities/git/git-add.ts
@@ -2,7 +2,7 @@ import { tool } from 'ai';
import { z } from 'zod';
import { execSync } from 'node:child_process';
-export function createGitAddTool() {
+export function createGitAddTool(getCwd: () => string) {
return tool({
description: 'Add file contents to the index (staging area). Prepares files for commit.',
parameters: z.object({
@@ -11,7 +11,7 @@ export function createGitAddTool() {
execute: async ({ paths }) => {
try {
const fileArgs = paths.map(p => `"${p}"`).join(' ');
- const result = execSync(`git add ${fileArgs}`, { encoding: 'utf-8', timeout: 10000 });
+ const result = execSync(`git add ${fileArgs}`, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });
return `Staged ${paths.length} file(s): ${paths.join(', ')}`;
} catch (err: any) {
return `Error: ${err.stderr?.trim() || err.message}`;
diff --git a/src/capabilities/git/git-commit.ts b/src/capabilities/git/git-commit.ts
index c49f0bd4..b6470357 100644
--- a/src/capabilities/git/git-commit.ts
+++ b/src/capabilities/git/git-commit.ts
@@ -4,7 +4,7 @@ import { execSync } from 'node:child_process';
const CO_AUTHOR = 'Mercury <[email protected]>';
-export function createGitCommitTool() {
+export function createGitCommitTool(getCwd: () => string) {
return tool({
description: 'Record changes to the repository. Creates a new commit with staged changes. Automatically includes a Co-authored-by trailer for attribution.',
parameters: z.object({
@@ -14,7 +14,7 @@ export function createGitCommitTool() {
try {
const fullMessage = `${message}\n\nCo-authored-by: ${CO_AUTHOR}`;
const escapedMsg = fullMessage.replace(/"/g, '\\"');
- const result = execSync(`git commit -m "${escapedMsg}"`, { encoding: 'utf-8', timeout: 10000 });
+ const result = execSync(`git commit -m "${escapedMsg}"`, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });
return result.trim() || 'Committed successfully.';
} catch (err: any) {
const stderr = err.stderr?.trim() || '';
diff --git a/src/capabilities/git/git-diff.ts b/src/capabilities/git/git-diff.ts
index c5de70a0..2f67cab0 100644
--- a/src/capabilities/git/git-diff.ts
+++ b/src/capabilities/git/git-diff.ts
@@ -2,7 +2,7 @@ import { tool } from 'ai';
import { z } from 'zod';
import { execSync } from 'node:child_process';
-export function createGitDiffTool() {
+export function createGitDiffTool(getCwd: () => string) {
return tool({
description: 'Show changes between commits, commit and working tree, etc. Shows what has been modified.',
parameters: z.object({
@@ -14,7 +14,7 @@ export function createGitDiffTool() {
let cmd = 'git diff';
if (staged) cmd += ' --cached';
if (path) cmd += ` -- "${path}"`;
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 15000 });
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 15000, cwd: getCwd() });
if (!result.trim()) return 'No differences found.';
const truncated = result.length > 15000 ? result.slice(0, 15000) + '\n... (truncated)' : result;
return truncated;
diff --git a/src/capabilities/git/git-log.ts b/src/capabilities/git/git-log.ts
index 759fc65e..e53116ba 100644
--- a/src/capabilities/git/git-log.ts
+++ b/src/capabilities/git/git-log.ts
@@ -2,7 +2,7 @@ import { tool } from 'ai';
import { z } from 'zod';
import { execSync } from 'node:child_process';
-export function createGitLogTool() {
+export function createGitLogTool(getCwd: () => string) {
return tool({
description: 'Show commit logs. Returns recent commit history with hash, author, date, and message.',
parameters: z.object({
@@ -14,7 +14,7 @@ export function createGitLogTool() {
const n = count ?? 10;
let cmd = `git log --oneline --decorate -${n}`;
if (path) cmd += ` -- "${path}"`;
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000 });
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });
if (!result.trim()) return 'No commits found.';
return result.trim();
} catch (err: any) {
diff --git a/src/capabilities/git/git-push.ts b/src/capabilities/git/git-push.ts
index af48e8e1..a6bc7c5d 100644
--- a/src/capabilities/git/git-push.ts
+++ b/src/capabilities/git/git-push.ts
@@ -3,7 +3,7 @@ import { z } from 'zod';
import { execSync } from 'node:child_process';
import type { PermissionManager } from '../permissions.js';
-export function createGitPushTool(permissions: PermissionManager) {
+export function createGitPushTool(permissions: PermissionManager, getCwd: () => string) {
return tool({
description: 'Push commits to a remote repository. This modifies a remote and requires approval.',
parameters: z.object({
@@ -23,7 +23,7 @@ export function createGitPushTool(permissions: PermissionManager) {
}
try {
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 30000 });
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 30000, cwd: getCwd() });
return result.trim() || 'Pushed successfully.';
} catch (err: any) {
return `Error: ${err.stderr?.trim() || err.message}`;
diff --git a/src/capabilities/git/git-status.ts b/src/capabilities/git/git-status.ts
index 07f20f5e..994da0e3 100644
--- a/src/capabilities/git/git-status.ts
+++ b/src/capabilities/git/git-status.ts
@@ -2,7 +2,7 @@ import { tool } from 'ai';
import { z } from 'zod';
import { execSync } from 'node:child_process';
-export function createGitStatusTool() {
+export function createGitStatusTool(getCwd: () => string) {
return tool({
description: 'Show the working tree status. Returns staged, unstaged, and untracked files.',
parameters: z.object({
@@ -11,7 +11,7 @@ export function createGitStatusTool() {
execute: async ({ path }) => {
try {
const cmd = path ? `git -C "${path}" status --porcelain` : 'git status --porcelain';
- const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000 });
+ const result = execSync(cmd, { encoding: 'utf-8', timeout: 10000, cwd: getCwd() });
if (!result.trim()) return 'Working tree clean — no changes.';
return result.trim();
} catch (err: any) {
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 0b7e139a..1ddf0b88 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -9,6 +9,7 @@ import { createEditFileTool } from './filesystem/edit-file.js';
import { createSendFileTool } from './filesystem/send-file.js';
import { createApproveScopeTool } from './filesystem/approve-scope.js';
import { createRunCommandTool } from './shell/run-command.js';
+import { createCdTool } from './shell/cd.js';
import { createApproveCommandTool } from './shell/approve-command.js';
import { createInstallSkillTool } from './skills/install-skill.js';
import { createListSkillsTool } from './skills/list-skills.js';
@@ -53,6 +54,7 @@ export class CapabilityRegistry {
private currentChannelId = 'cli';
private currentChannelType = 'cli';
private chatCommandContext?: ChatCommandContext;
+ private currentCwd = process.cwd();
constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget) {
this.permissions = new PermissionManager();
@@ -78,6 +80,14 @@ export class CapabilityRegistry {
return { channelId: this.currentChannelId, channelType: this.currentChannelType };
}
+ getCwd(): string {
+ return this.currentCwd;
+ }
+
+ setCwd(dir: string): void {
+ this.currentCwd = dir;
+ }
+
setSendFileHandler(handler: (filePath: string) => Promise<void>): void {
this.sendFileHandler = handler;
}
@@ -86,24 +96,25 @@ export class CapabilityRegistry {
const manifest = this.permissions.getManifest();
if (manifest.capabilities.filesystem.enabled) {
- this.tools.read_file = createReadFileTool(this.permissions);
- this.tools.write_file = createWriteFileTool(this.permissions);
- this.tools.create_file = createCreateFileTool(this.permissions);
- this.tools.list_dir = createListDirTool(this.permissions);
- this.tools.delete_file = createDeleteFileTool(this.permissions);
- this.tools.edit_file = createEditFileTool(this.permissions);
+ this.tools.read_file = createReadFileTool(this.permissions, () => this.getCwd());
+ this.tools.write_file = createWriteFileTool(this.permissions, () => this.getCwd());
+ this.tools.create_file = createCreateFileTool(this.permissions, () => this.getCwd());
+ this.tools.list_dir = createListDirTool(this.permissions, () => this.getCwd());
+ this.tools.delete_file = createDeleteFileTool(this.permissions, () => this.getCwd());
+ this.tools.edit_file = createEditFileTool(this.permissions, () => this.getCwd());
if (this.sendFileHandler) {
- this.tools.send_file = createSendFileTool(this.permissions, this.sendFileHandler);
+ this.tools.send_file = createSendFileTool(this.permissions, () => this.getCwd(), this.sendFileHandler);
}
- this.tools.approve_scope = createApproveScopeTool(this.permissions);
+ this.tools.approve_scope = createApproveScopeTool(this.permissions, () => this.getCwd());
logger.info('Filesystem tools registered');
}
if (manifest.capabilities.shell.enabled) {
- this.tools.run_command = createRunCommandTool(this.permissions);
+ this.tools.run_command = createRunCommandTool(this.permissions, () => this.getCwd(), (dir: string) => this.setCwd(dir));
+ this.tools.cd = createCdTool(() => this.getCwd(), (dir: string) => this.setCwd(dir));
this.tools.approve_command = createApproveCommandTool(this.permissions);
logger.info('Shell tools registered');
}
@@ -128,12 +139,12 @@ export class CapabilityRegistry {
}
if (manifest.capabilities.git?.enabled) {
- this.tools.git_status = createGitStatusTool();
- this.tools.git_diff = createGitDiffTool();
- this.tools.git_log = createGitLogTool();
- this.tools.git_add = createGitAddTool();
- this.tools.git_commit = createGitCommitTool();
- this.tools.git_push = createGitPushTool(this.permissions);
+ this.tools.git_status = createGitStatusTool(() => this.getCwd());
+ this.tools.git_diff = createGitDiffTool(() => this.getCwd());
+ this.tools.git_log = createGitLogTool(() => this.getCwd());
+ this.tools.git_add = createGitAddTool(() => this.getCwd());
+ this.tools.git_commit = createGitCommitTool(() => this.getCwd());
+ this.tools.git_push = createGitPushTool(this.permissions, () => this.getCwd());
logger.info('Git tools registered');
}
diff --git a/src/capabilities/shell/cd.ts b/src/capabilities/shell/cd.ts
new file mode 100644
index 00000000..de449f66
--- /dev/null
+++ b/src/capabilities/shell/cd.ts
@@ -0,0 +1,33 @@
+import { tool } from 'ai';
+import { z } from 'zod';
+import { resolve, isAbsolute } from 'node:path';
+import { existsSync, statSync } from 'node:fs';
+
+export function createCdTool(getCwd: () => string, setCwd: (dir: string) => void) {
+ return tool({
+ description: 'Change the current working directory. All subsequent file operations, shell commands, and git operations will use this directory. Use this before running commands in a specific project folder.',
+ parameters: z.object({
+ path: z.string().describe('The directory to change to. Can be absolute or relative to the current directory.'),
+ }),
+ execute: async ({ path }) => {
+ const cwd = getCwd();
+ const resolved = isAbsolute(path) ? resolve(path) : resolve(cwd, path);
+
+ if (!existsSync(resolved)) {
+ return `Error: Directory not found: ${resolved}`;
+ }
+
+ try {
+ const stat = statSync(resolved);
+ if (!stat.isDirectory()) {
+ return `Error: Not a directory: ${resolved}`;
+ }
+ } catch {
+ return `Error: Cannot access: ${resolved}`;
+ }
+
+ setCwd(resolved);
+ return `Changed directory to ${resolved}`;
+ },
+ });
+}
\ No newline at end of file
diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.ts
index 8123a0a7..171ba24e 100644
--- a/src/capabilities/shell/run-command.ts
+++ b/src/capabilities/shell/run-command.ts
@@ -1,16 +1,17 @@
import { tool } from 'ai';
import { z } from 'zod';
import { execSync } from 'node:child_process';
-import { resolve } from 'node:path';
+import { resolve, isAbsolute } from 'node:path';
+import { existsSync } from 'node:fs';
import type { PermissionManager } from '../permissions.js';
import { logger } from '../../utils/logger.js';
-export function createRunCommandTool(permissions: PermissionManager) {
+export function createRunCommandTool(permissions: PermissionManager, getCwd: () => string, setCwd: (dir: string) => void) {
return tool({
- description: `Run a shell command. Commands run in the current working directory unless an absolute path is given.
+ description: `Run a shell command in the current working directory. Use the cd tool to change directories first — cd commands within this tool only affect chained commands (e.g., "cd /path && ls"), not subsequent calls.
Blocked commands (sudo, rm -rf /, etc.) are never executed.
Auto-approved commands (ls, cat, git status, curl, etc.) run without asking.
-Other commands require user approval — tell the user what command you want to run and ask for confirmation. If they say "yes", try again. If they say "always", use the approve_command tool.`,
+Other commands require user approval.`,
parameters: z.object({
command: z.string().describe('The shell command to execute'),
}),
@@ -25,20 +26,31 @@ Other commands require user approval — tell the user what command you want to
return `Error: ${check.reason}`;
}
+ const cwd = getCwd();
+
try {
- logger.info({ cmd: command }, 'Executing shell command');
+ logger.info({ cmd: command, cwd }, 'Executing shell command');
const result = execSync(command, {
- cwd: process.cwd(),
+ cwd,
timeout: 30000,
maxBuffer: 1024 * 1024,
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
});
- const output = result?.trim() || '(no output)';
- return output;
+
+ const trimmedOutput = result?.trim() || '(no output)';
+
+ detectCd(command, cwd, setCwd);
+
+ return trimmedOutput;
} catch (err: any) {
const stderr = err.stderr?.trim();
const stdout = err.stdout?.trim();
+
+ if (stdout || stderr) {
+ detectCd(command, cwd, setCwd);
+ }
+
let msg = `Command exited with code ${err.status || 'unknown'}`;
if (stdout) msg += `\nOutput: ${stdout}`;
if (stderr) msg += `\nError: ${stderr}`;
@@ -46,4 +58,27 @@ Other commands require user approval — tell the user what command you want to
}
},
});
+}
+
+function detectCd(command: string, currentCwd: string, setCwd: (dir: string) => void): void {
+ const trimmed = command.trim();
+
+ const cdOnly = trimmed.match(/^cd\s+(.+)$/);
+ if (cdOnly) {
+ const target = cdOnly[1].replace(/^["']|["']$/g, '').replace(/~/, process.env.HOME || '');
+ const resolved = isAbsolute(target) ? target : resolve(currentCwd, target);
+ if (existsSync(resolved)) {
+ setCwd(resolved);
+ }
+ return;
+ }
+
+ const cdChain = trimmed.match(/cd\s+(.+?)\s*&&/);
+ if (cdChain) {
+ const target = cdChain[1].replace(/^["']|["']$/g, '').replace(/~/, process.env.HOME || '');
+ const resolved = isAbsolute(target) ? target : resolve(currentCwd, target);
+ if (existsSync(resolved)) {
+ setCwd(resolved);
+ }
+ }
}
\ No newline at end of file