Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
"@types/react": "^19.2.14",
"ai": "^6.0.180",
"effect": "^3.21.2",
"globby": "^14.1.0",
"pino": "^9.6.0",
"pino-pretty": "^13.0.0",
"react": "^19.2.6",
Expand Down
2 changes: 1 addition & 1 deletion packages/codingcode/agent/src/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ export const AgentLayer = Layer.effect(
const argsById = new Map(toolCalls.map((tc) => [tc.id, tc.arguments] as const));

for (const r of allResults) {
const output = r.status === 'denied' ? '' : r.output;
const output = r.status === 'denied' ? `[Denied] ${r.reason}` : r.output;
const toolEv = yield* session.recordToolResult(state, {
toolCallId: r.id,
toolName: r.name,
Expand Down
53 changes: 48 additions & 5 deletions packages/codingcode/app/scripts/bundle.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { build } from 'esbuild';
import { resolve, dirname } from 'path';
import { fileURLToPath } from 'url';
import { cpSync, existsSync, mkdirSync, rmSync } from 'node:fs';
import { createRequire } from 'node:module';
import { resolve, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..');
const require = createRequire(import.meta.url);

// Native / binary runtime packages that cannot be inlined into a single CJS file.
const EXTERNAL_RUNTIME_PACKAGES = ['koffi', '@vscode/ripgrep', '@codingcode/process-sandbox'];

await build({
entryPoints: [resolve(root, 'src/cli.ts')],
Expand All @@ -12,8 +18,7 @@ await build({
format: 'cjs',
target: 'node20',
outfile: resolve(root, 'dist/cli.bundle.cjs'),
// pino-pretty 仅在开发模式使用,生产模式不会加载
external: ['pino-pretty'],
external: ['pino-pretty', ...EXTERNAL_RUNTIME_PACKAGES],
splitting: false,
sourcemap: true,
minify: false,
Expand All @@ -25,4 +30,42 @@ await build({
},
});

console.log('Backend bundle written to dist/cli.bundle.cjs');
function packageDirOf(pkgName, extraPaths = []) {
const resolvedEntry = require.resolve(pkgName, {
paths: [
root,
resolve(root, '../fs'),
resolve(root, '../sandbox'),
resolve(root, '../../..'),
...extraPaths,
],
});
let dir = dirname(resolvedEntry);
while (true) {
if (existsSync(resolve(dir, 'package.json'))) return dir;
const parent = dirname(dir);
if (parent === dir) throw new Error(`Could not locate package.json for ${pkgName}`);
dir = parent;
}
}

const runtimeNodeModules = resolve(root, 'dist/runtime-node_modules');
rmSync(runtimeNodeModules, { recursive: true, force: true });
mkdirSync(runtimeNodeModules, { recursive: true });

const processSandboxDir = packageDirOf('@codingcode/process-sandbox');
for (const pkg of EXTERNAL_RUNTIME_PACKAGES) {
const srcDir = packageDirOf(pkg, [processSandboxDir]);
const destDir = resolve(runtimeNodeModules, pkg);
mkdirSync(dirname(destDir), { recursive: true });
cpSync(srcDir, destDir, {
recursive: true,
dereference: true,
filter: (p) => !p.includes(`${resolve(srcDir, 'node_modules')}`),
});
if (!existsSync(destDir)) {
throw new Error(`Failed to stage runtime package ${pkg}`);
}
}

console.log('Backend bundle written to dist/cli.bundle.cjs with staged runtime packages');
2 changes: 2 additions & 0 deletions packages/codingcode/app/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ async function main() {
const httpApp = await Effect.runPromise(createHttpApp());

const nodeServer = createNodeServer();
nodeServer.timeout = 0;
nodeServer.requestTimeout = 0;

nodeServer.once('error', (err) => {
console.error('Server failed to start:', err);
Expand Down
16 changes: 12 additions & 4 deletions packages/codingcode/bash/src/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,11 +65,15 @@ export const bashTool = defineTool({
? ['cmd.exe', '/d', '/s', '/c', command]
: ['/bin/sh', '-lc', command];
const confined = yield* localSandboxProvider.confine(shellArgv, ctx.sandboxPolicy);
if (ctx.sandboxPolicy.enforcement === 'required' && confined.enforcement !== 'full') {
if (ctx.sandboxPolicy.enforcement === 'required' && confined.enforcement === 'disabled') {
yield* Effect.tryPromise({
try: () => confined.cleanup?.() ?? Promise.resolve(),
catch: () => undefined,
}).pipe(Effect.ignore);
return yield* Effect.fail(
new AgentError(
'SANDBOX_UNAVAILABLE',
'The command sandbox did not provide full enforcement'
'The command sandbox did not provide process confinement'
)
);
}
Expand All @@ -78,7 +82,7 @@ export const bashTool = defineTool({
const proc = spawn(program!, argv, {
shell: false,
cwd: workDir,
env: process.env,
env: confined.env ?? process.env,
stdio: ['pipe', 'pipe', 'pipe'],
});

Expand Down Expand Up @@ -141,7 +145,11 @@ export const bashTool = defineTool({
)
);
});
});
}).pipe(
Effect.ensuring(
Effect.promise(() => confined.cleanup?.() ?? Promise.resolve()).pipe(Effect.ignore)
)
);
});
},
});
2 changes: 1 addition & 1 deletion packages/codingcode/fs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"@codingcode/util": "workspace:*",
"@codingcode/sandbox": "workspace:*",
"@codingcode/tool": "workspace:*",
"@vscode/ripgrep": "^1.15.9",
"effect": "^3.21.2",
"globby": "^14.1.0",
"zod": "^4.4.3"
}
}
71 changes: 49 additions & 22 deletions packages/codingcode/fs/src/glob.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
import { z } from 'zod';
import { globby } from 'globby';
import { relative } from 'path';
import { relative, resolve } from 'node:path';
import { Effect } from 'effect';
import { AgentError } from '@codingcode/util';
import { defineTool } from '@codingcode/tool';
import { resolveFileTarget } from '@codingcode/sandbox';
import { DEFAULT_IGNORE_GLOBS, runRipgrep } from './rg.js';

export const globTool = defineTool({
name: 'search_files',
concurrencySafe: true,
description:
'Find files matching a glob pattern. Returns file paths sorted by modification time (newest first). Useful for locating files by name or extension across the project.',
'Find files matching a glob pattern inside the project workspace. Respects .gitignore and excludes node_modules/dist/.git.',
parameters: z.object({
pattern: z.string().describe('Glob pattern to match files, e.g. "**/*.ts", "src/**/*.tsx"'),
path: z
Expand Down Expand Up @@ -41,45 +41,72 @@ export const globTool = defineTool({
: AgentError.toolExecutionFailed('search_files', error),
});

const files = yield* Effect.tryPromise({
try: () =>
globby(pattern, {
cwd: basePath,
gitignore: true,
ignore: ['node_modules/**', 'dist/**', '.git/**', '*.lockb', '*.lock', '*.min.js'],
absolute: true,
onlyFiles: true,
}),
catch: (e) => AgentError.toolExecutionFailed('search_files', e),
});
const normalizedPattern = pattern.replace(/\\/g, '/');
const rgGlob =
normalizedPattern.startsWith('**/') || normalizedPattern.startsWith('/')
? normalizedPattern
: `/${normalizedPattern}`;
const candidates: string[] = [];
const limit = max_results + 1;
const rgArgs = [
'--files',
'--color=never',
'--no-config',
'--glob',
rgGlob,
...DEFAULT_IGNORE_GLOBS.flatMap((g) => ['--glob', g]),
];

const runResult = yield* Effect.either(
Effect.tryPromise({
try: () =>
runRipgrep({
args: rgArgs,
cwd: basePath,
signal: ctx.signal,
onLine: (line) => {
candidates.push(resolve(basePath, line));
return candidates.length < limit;
},
}),
catch: (e) =>
e instanceof AgentError ? e : AgentError.toolExecutionFailed('search_files', e),
})
);

if (runResult._tag === 'Left') {
const err = runResult.left;
if (err.code === 'TOOL_NOT_ALLOWED') return yield* Effect.fail(err);
return `No files matching "${pattern}" in ${relative(base, basePath) || '.'}`;
}

const safeFiles = yield* Effect.tryPromise({
try: async () => {
const checked: string[] = [];
for (const file of files) {
for (const file of candidates) {
try {
checked.push(
await resolveFileTarget(ctx.sandboxPolicy!, { path: file, operation: 'read' })
);
} catch {
// A glob result outside the sandbox is omitted.
// Ignore symlink targets escaping sandbox roots.
}
}
return checked;
},
catch: (e) => AgentError.toolExecutionFailed('search_files', e),
});
const truncated = safeFiles.slice(0, max_results);
const lines = truncated.map((f) => relative(base, f));

if (safeFiles.length === 0) {
return `No files matching "${pattern}" in ${relative(base, basePath) || '.'}`;
}

let out = `Found ${safeFiles.length} file(s) matching "${pattern}"`;
if (safeFiles.length > max_results) {
out += ` (showing first ${max_results})`;
}
const hasMore = safeFiles.length > max_results || runResult.right.stoppedEarly;
const truncated = safeFiles.slice(0, max_results);
const lines = truncated.map((f) => relative(base, f));

let out = `Found ${truncated.length}${hasMore ? '+' : ''} file(s) matching "${pattern}"`;
if (hasMore) out += ` (showing first ${max_results})`;
return out + '\n' + lines.join('\n');
}),
});
Loading
Loading