Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
42 changes: 42 additions & 0 deletions packages/junior/src/chat/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,40 @@ function formatActiveMcpCatalogsForPrompt(
return lines.join("\n");
}

interface ToolPromptContext {
name: string;
promptGuidelines?: string[];
promptSnippet?: string;
}

function formatToolGuidanceForPrompt(
tools: ToolPromptContext[],
): string | null {
const guidedTools = tools.filter(
(tool) =>
Boolean(tool.promptSnippet?.trim()) ||
(tool.promptGuidelines?.length ?? 0) > 0,
);
if (guidedTools.length === 0) {
return null;
}

const lines: string[] = [];
for (const tool of guidedTools) {
lines.push(` <tool name="${escapeXml(tool.name)}">`);
if (tool.promptSnippet?.trim()) {
lines.push(` - ${escapeXml(tool.promptSnippet.trim())}`);
}
if (tool.promptGuidelines && tool.promptGuidelines.length > 0) {
for (const guideline of tool.promptGuidelines) {
lines.push(` - ${escapeXml(guideline)}`);
}
}
lines.push(" </tool>");
}
return lines.join("\n");
}

function formatReferenceFilesLines(): string[] | null {
const files = listReferenceFiles();
if (files.length === 0) {
Expand Down Expand Up @@ -527,6 +561,7 @@ function buildCapabilitiesSection(params: {
availableSkills: SkillMetadata[];
activeSkills: Skill[];
activeMcpCatalogs: ActiveMcpCatalogSummary[];
toolGuidance?: ToolPromptContext[];
}): string {
const blocks: string[] = [];
blocks.push(formatAvailableSkillsForPrompt(params.availableSkills));
Expand All @@ -539,6 +574,11 @@ function buildCapabilitiesSection(params: {
blocks.push(renderTagBlock("active-mcp-catalogs", activeCatalogs));
}

const toolGuidance = formatToolGuidanceForPrompt(params.toolGuidance ?? []);
if (toolGuidance) {
blocks.push(renderTagBlock("tool-guidance", toolGuidance));
}

const providerCatalog = formatProviderCatalogForPrompt();
if (providerCatalog) {
blocks.push(renderTagBlock("providers", providerCatalog));
Expand All @@ -551,6 +591,7 @@ type TurnContextPromptInput = {
availableSkills: SkillMetadata[];
activeSkills: Skill[];
activeMcpCatalogs?: ActiveMcpCatalogSummary[];
toolGuidance?: ToolPromptContext[];
runtime?: {
channelId?: string;
fastModelId?: string;
Expand Down Expand Up @@ -607,6 +648,7 @@ export function buildTurnContextPrompt(params: TurnContextPromptInput): string {
availableSkills: params.availableSkills,
activeSkills: params.activeSkills,
activeMcpCatalogs: params.activeMcpCatalogs ?? [],
toolGuidance: params.toolGuidance ?? [],
}),
buildContextSection({
requester: params.requester,
Expand Down
10 changes: 10 additions & 0 deletions packages/junior/src/chat/respond.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import type { ThreadArtifactsState } from "@/chat/state/artifacts";
import type { ConversationPendingAuthState } from "@/chat/state/conversation";
import { createTools } from "@/chat/tools";
import { resolveChannelCapabilities } from "@/chat/tools/channel-capabilities";
import type { ToolDefinition } from "@/chat/tools/definition";
import { toActiveMcpCatalogSummaries } from "@/chat/tools/skill/mcp-tool-summary";
import type { ImageGenerateToolDeps } from "@/chat/tools/types";
import { createAdvisorToolDefinitions } from "@/chat/tools/advisor/tool";
Expand Down Expand Up @@ -828,6 +829,14 @@ export async function generateAssistantReply(
},
);

const toolGuidance = Object.entries(
tools as Record<string, ToolDefinition<any>>,
).map(([name, definition]) => ({
name,
promptGuidelines: definition.promptGuidelines,
promptSnippet: definition.promptSnippet,
}));

syncResumeState();
for (const skill of activeSkills) {
await turnMcpToolManager.activateForSkill(skill);
Expand All @@ -849,6 +858,7 @@ export async function generateAssistantReply(
availableSkills,
activeSkills,
activeMcpCatalogs,
toolGuidance,
runtime: {
channelId: toolChannelId,
fastModelId: botConfig.fastModelId,
Expand Down
193 changes: 185 additions & 8 deletions packages/junior/src/chat/sandbox/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ import {
} from "@/chat/sandbox/skill-sync";
import type { SandboxWorkspace } from "@/chat/sandbox/workspace";
import type { SkillMetadata } from "@/chat/skills";
import { editFile } from "@/chat/tools/sandbox/edit-file";
import { findFiles } from "@/chat/tools/sandbox/find-files";
import { grepFiles } from "@/chat/tools/sandbox/grep";
import { listDir } from "@/chat/tools/sandbox/list-dir";
import { sliceFileContent } from "@/chat/tools/sandbox/read-file";

// Spec: specs/security-policy.md (sandbox isolation, network policy, credential lifecycle)
// Spec: specs/logging/tracing-spec.md (required sandbox span semantics)
Expand Down Expand Up @@ -60,7 +65,15 @@ export interface SandboxExecutor {
dispose(): Promise<void>;
}

const SANDBOX_TOOL_NAMES = new Set(["bash", "readFile", "writeFile"]);
const SANDBOX_TOOL_NAMES = new Set([
"bash",
"readFile",
"editFile",
"grep",
"findFiles",
"listDir",
"writeFile",
]);

function parseHeaderTransforms(
raw: unknown,
Expand Down Expand Up @@ -165,12 +178,20 @@ export function createSandboxExecutor(options?: {
);
};

const parsePositiveNumber = (raw: unknown): number | undefined => {
if (typeof raw !== "number" || !Number.isFinite(raw) || raw <= 0) {
return undefined;
}
return Math.floor(raw);
};
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated

const executeBashTool = async <T>(
rawInput: Record<string, unknown>,
command: string,
): Promise<SandboxExecutionEnvelope<T>> => {
const headerTransforms = parseHeaderTransforms(rawInput.headerTransforms);
const env = parseEnv(rawInput.env);
const timeoutMs = parsePositiveNumber(rawInput.timeoutMs);
logSandboxBootRequest("tool.bash", {
"app.sandbox.command_length": command.length,
});
Expand All @@ -187,6 +208,7 @@ export function createSandboxExecutor(options?: {
command,
...(headerTransforms ? { headerTransforms } : {}),
...(env ? { env } : {}),
...(timeoutMs ? { timeoutMs } : {}),
});
setSpanAttributes({
"process.exit.code": response.exitCode,
Expand Down Expand Up @@ -222,7 +244,7 @@ export function createSandboxExecutor(options?: {
cwd: SANDBOX_WORKSPACE_ROOT,
exit_code: result.exitCode,
signal: null,
timed_out: false,
timed_out: Boolean(result.timedOut),
stdout: result.stdout,
stderr: result.stderr,
stdout_truncated: result.stdoutTruncated,
Expand All @@ -238,6 +260,8 @@ export function createSandboxExecutor(options?: {
if (!filePath) {
throw new Error("path is required");
}
const offset = parsePositiveNumber(rawInput.offset);
const limit = parsePositiveNumber(rawInput.limit);

if (!sessionManager.getSandboxId()) {
const hostPath =
Expand All @@ -254,11 +278,12 @@ export function createSandboxExecutor(options?: {
});
setSpanStatus("ok");
return {
result: {
result: sliceFileContent({
content,
path: filePath,
success: true,
} as T,
offset,
limit,
}) as T,
};
} catch (error) {
if (!isHostFileMissingError(error)) {
Expand Down Expand Up @@ -288,9 +313,12 @@ export function createSandboxExecutor(options?: {
});
setSpanStatus("ok");
return {
content,
path: filePath,
success: true,
...sliceFileContent({
content,
path: filePath,
offset,
limit,
}),
};
},
);
Expand Down Expand Up @@ -338,6 +366,139 @@ export function createSandboxExecutor(options?: {
};
};

const executeEditFileTool = async <T>(
rawInput: Record<string, unknown>,
): Promise<SandboxExecutionEnvelope<T>> => {
const filePath = String(rawInput.path ?? "").trim();
if (!filePath) {
throw new Error("path is required");
}
if (!Array.isArray(rawInput.edits)) {
throw new Error("edits is required");
}

logSandboxBootRequest("tool.editFile", {
"file.path": filePath,
});
const executors = await sessionManager.ensureToolExecutors();
const result = await withSandboxSpan(
"sandbox.editFile",
"sandbox.fs.edit",
{
"app.sandbox.path.length": filePath.length,
"app.sandbox.edit.count": rawInput.edits.length,
},
async () => {
const response = await editFile({
fs: executors.fs,
path: filePath,
edits: rawInput.edits as Array<{ oldText: string; newText: string }>,
});
setSpanStatus("ok");
return response;
},
);

return { result: result as T };
};

const executeGrepTool = async <T>(
rawInput: Record<string, unknown>,
): Promise<SandboxExecutionEnvelope<T>> => {
const pattern = String(rawInput.pattern ?? "");
if (!pattern) {
throw new Error("pattern is required");
}

logSandboxBootRequest("tool.grep");
const contextLines = parsePositiveNumber(rawInput.context);
const limit = parsePositiveNumber(rawInput.limit);
const executors = await sessionManager.ensureToolExecutors();
const result = await withSandboxSpan(
"sandbox.grep",
"sandbox.fs.search",
{
"app.sandbox.pattern.length": pattern.length,
},
async () => {
const response = await grepFiles({
fs: executors.fs,
pattern,
...(typeof rawInput.path === "string" ? { path: rawInput.path } : {}),
...(typeof rawInput.glob === "string" ? { glob: rawInput.glob } : {}),
...(typeof rawInput.ignoreCase === "boolean"
? { ignoreCase: rawInput.ignoreCase }
: {}),
...(typeof rawInput.literal === "boolean"
? { literal: rawInput.literal }
: {}),
...(contextLines ? { context: contextLines } : {}),
...(limit ? { limit } : {}),
});
setSpanStatus("ok");
return response;
},
);

return { result: result as T };
};

const executeFindFilesTool = async <T>(
rawInput: Record<string, unknown>,
): Promise<SandboxExecutionEnvelope<T>> => {
const pattern = String(rawInput.pattern ?? "");
if (!pattern) {
throw new Error("pattern is required");
}

logSandboxBootRequest("tool.findFiles");
const limit = parsePositiveNumber(rawInput.limit);
const executors = await sessionManager.ensureToolExecutors();
const result = await withSandboxSpan(
"sandbox.findFiles",
"sandbox.fs.find",
{
"app.sandbox.pattern.length": pattern.length,
},
async () => {
const response = await findFiles({
fs: executors.fs,
pattern,
...(typeof rawInput.path === "string" ? { path: rawInput.path } : {}),
...(limit ? { limit } : {}),
});
setSpanStatus("ok");
return response;
},
);

return { result: result as T };
};

const executeListDirTool = async <T>(
rawInput: Record<string, unknown>,
): Promise<SandboxExecutionEnvelope<T>> => {
logSandboxBootRequest("tool.listDir");
const limit = parsePositiveNumber(rawInput.limit);
const executors = await sessionManager.ensureToolExecutors();
const result = await withSandboxSpan(
"sandbox.listDir",
"sandbox.fs.list",
{},
async () => {
const response = await listDir({
fs: executors.fs,
...(typeof rawInput.path === "string" ? { path: rawInput.path } : {}),
...(limit ? { limit } : {}),
});
setSpanStatus("ok");
return response;
},
);

return { result: result as T };
};

const execute = async <T>(
params: SandboxExecutionInput,
): Promise<SandboxExecutionEnvelope<T>> => {
Expand All @@ -364,6 +525,22 @@ export function createSandboxExecutor(options?: {
return await executeReadFileTool(rawInput);
}

if (params.toolName === "editFile") {
return await executeEditFileTool(rawInput);
}

if (params.toolName === "grep") {
return await executeGrepTool(rawInput);
}

if (params.toolName === "findFiles") {
return await executeFindFilesTool(rawInput);
}

if (params.toolName === "listDir") {
return await executeListDirTool(rawInput);
}

if (params.toolName === "writeFile") {
return await executeWriteFileTool(rawInput);
}
Expand Down
Loading
Loading