feat: build
This commit is contained in:
commit
f90eee85d8
1906 files changed
+514339
No files matched your search
@@ -0,0 +1,434 @@
|
||||
import { dirname, sep } from 'path'
|
||||
import { logEvent } from 'src/services/analytics/index.js'
|
||||
import { z } from 'zod/v4'
|
||||
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
|
||||
import { diagnosticTracker } from '../../services/diagnosticTracking.js'
|
||||
import { clearDeliveredDiagnosticsForFile } from '../../services/lsp/LSPDiagnosticRegistry.js'
|
||||
import { getLspServerManager } from '../../services/lsp/manager.js'
|
||||
import { notifyVscodeFileUpdated } from '../../services/mcp/vscodeSdkMcp.js'
|
||||
import { checkTeamMemSecrets } from '../../services/teamMemorySync/teamMemSecretGuard.js'
|
||||
import {
|
||||
activateConditionalSkillsForPaths,
|
||||
addSkillDirectories,
|
||||
discoverSkillDirsForPaths,
|
||||
} from '../../skills/loadSkillsDir.js'
|
||||
import type { ToolUseContext } from '../../Tool.js'
|
||||
import { buildTool, type ToolDef } from '../../Tool.js'
|
||||
import { getCwd } from '../../utils/cwd.js'
|
||||
import { logForDebugging } from '../../utils/debug.js'
|
||||
import { countLinesChanged, getPatchForDisplay } from '../../utils/diff.js'
|
||||
import { isEnvTruthy } from '../../utils/envUtils.js'
|
||||
import { isENOENT } from '../../utils/errors.js'
|
||||
import { getFileModificationTime, writeTextContent } from '../../utils/file.js'
|
||||
import {
|
||||
fileHistoryEnabled,
|
||||
fileHistoryTrackEdit,
|
||||
} from '../../utils/fileHistory.js'
|
||||
import { logFileOperation } from '../../utils/fileOperationAnalytics.js'
|
||||
import { readFileSyncWithMetadata } from '../../utils/fileRead.js'
|
||||
import { getFsImplementation } from '../../utils/fsOperations.js'
|
||||
import {
|
||||
fetchSingleFileGitDiff,
|
||||
type ToolUseDiff,
|
||||
} from '../../utils/gitDiff.js'
|
||||
import { lazySchema } from '../../utils/lazySchema.js'
|
||||
import { logError } from '../../utils/log.js'
|
||||
import { expandPath } from '../../utils/path.js'
|
||||
import {
|
||||
checkWritePermissionForTool,
|
||||
matchingRuleForInput,
|
||||
} from '../../utils/permissions/filesystem.js'
|
||||
import type { PermissionDecision } from '../../utils/permissions/PermissionResult.js'
|
||||
import { matchWildcardPattern } from '../../utils/permissions/shellRuleMatching.js'
|
||||
import { FILE_UNEXPECTEDLY_MODIFIED_ERROR } from '../FileEditTool/constants.js'
|
||||
import { gitDiffSchema, hunkSchema } from '../FileEditTool/types.js'
|
||||
import { FILE_WRITE_TOOL_NAME, getWriteToolDescription } from './prompt.js'
|
||||
import {
|
||||
getToolUseSummary,
|
||||
isResultTruncated,
|
||||
renderToolResultMessage,
|
||||
renderToolUseErrorMessage,
|
||||
renderToolUseMessage,
|
||||
renderToolUseRejectedMessage,
|
||||
userFacingName,
|
||||
} from './UI.js'
|
||||
|
||||
const inputSchema = lazySchema(() =>
|
||||
z.strictObject({
|
||||
file_path: z
|
||||
.string()
|
||||
.describe(
|
||||
'The absolute path to the file to write (must be absolute, not relative)',
|
||||
),
|
||||
content: z.string().describe('The content to write to the file'),
|
||||
}),
|
||||
)
|
||||
type InputSchema = ReturnType<typeof inputSchema>
|
||||
|
||||
const outputSchema = lazySchema(() =>
|
||||
z.object({
|
||||
type: z
|
||||
.enum(['create', 'update'])
|
||||
.describe(
|
||||
'Whether a new file was created or an existing file was updated',
|
||||
),
|
||||
filePath: z.string().describe('The path to the file that was written'),
|
||||
content: z.string().describe('The content that was written to the file'),
|
||||
structuredPatch: z
|
||||
.array(hunkSchema())
|
||||
.describe('Diff patch showing the changes'),
|
||||
originalFile: z
|
||||
.string()
|
||||
.nullable()
|
||||
.describe(
|
||||
'The original file content before the write (null for new files)',
|
||||
),
|
||||
gitDiff: gitDiffSchema().optional(),
|
||||
}),
|
||||
)
|
||||
type OutputSchema = ReturnType<typeof outputSchema>
|
||||
|
||||
export type Output = z.infer<OutputSchema>
|
||||
export type FileWriteToolInput = InputSchema
|
||||
|
||||
export const FileWriteTool = buildTool({
|
||||
name: FILE_WRITE_TOOL_NAME,
|
||||
searchHint: 'create or overwrite files',
|
||||
maxResultSizeChars: 100_000,
|
||||
strict: true,
|
||||
async description() {
|
||||
return 'Write a file to the local filesystem.'
|
||||
},
|
||||
userFacingName,
|
||||
getToolUseSummary,
|
||||
getActivityDescription(input) {
|
||||
const summary = getToolUseSummary(input)
|
||||
return summary ? `Writing ${summary}` : 'Writing file'
|
||||
},
|
||||
async prompt() {
|
||||
return getWriteToolDescription()
|
||||
},
|
||||
renderToolUseMessage,
|
||||
isResultTruncated,
|
||||
get inputSchema(): InputSchema {
|
||||
return inputSchema()
|
||||
},
|
||||
get outputSchema(): OutputSchema {
|
||||
return outputSchema()
|
||||
},
|
||||
toAutoClassifierInput(input) {
|
||||
return `${input.file_path}: ${input.content}`
|
||||
},
|
||||
getPath(input): string {
|
||||
return input.file_path
|
||||
},
|
||||
backfillObservableInput(input) {
|
||||
// hooks.mdx documents file_path as absolute; expand so hook allowlists
|
||||
// can't be bypassed via ~ or relative paths.
|
||||
if (typeof input.file_path === 'string') {
|
||||
input.file_path = expandPath(input.file_path)
|
||||
}
|
||||
},
|
||||
async preparePermissionMatcher({ file_path }) {
|
||||
return pattern => matchWildcardPattern(pattern, file_path)
|
||||
},
|
||||
async checkPermissions(input, context): Promise<PermissionDecision> {
|
||||
const appState = context.getAppState()
|
||||
return checkWritePermissionForTool(
|
||||
FileWriteTool,
|
||||
input,
|
||||
appState.toolPermissionContext,
|
||||
)
|
||||
},
|
||||
renderToolUseRejectedMessage,
|
||||
renderToolUseErrorMessage,
|
||||
renderToolResultMessage,
|
||||
extractSearchText() {
|
||||
// Transcript render shows either content (create, via HighlightedCode)
|
||||
// or a structured diff (update). The heuristic's 'content' allowlist key
|
||||
// would index the raw content string even in update mode where it's NOT
|
||||
// shown — phantom. Under-count: tool_use already indexes file_path.
|
||||
return ''
|
||||
},
|
||||
async validateInput({ file_path, content }, toolUseContext: ToolUseContext) {
|
||||
const fullFilePath = expandPath(file_path)
|
||||
|
||||
// Reject writes to team memory files that contain secrets
|
||||
const secretError = checkTeamMemSecrets(fullFilePath, content)
|
||||
if (secretError) {
|
||||
return { result: false, message: secretError, errorCode: 0 }
|
||||
}
|
||||
|
||||
// Check if path should be ignored based on permission settings
|
||||
const appState = toolUseContext.getAppState()
|
||||
const denyRule = matchingRuleForInput(
|
||||
fullFilePath,
|
||||
appState.toolPermissionContext,
|
||||
'edit',
|
||||
'deny',
|
||||
)
|
||||
if (denyRule !== null) {
|
||||
return {
|
||||
result: false,
|
||||
message:
|
||||
'File is in a directory that is denied by your permission settings.',
|
||||
errorCode: 1,
|
||||
}
|
||||
}
|
||||
|
||||
// SECURITY: Skip filesystem operations for UNC paths to prevent NTLM credential leaks.
|
||||
// On Windows, fs.existsSync() on UNC paths triggers SMB authentication which could
|
||||
// leak credentials to malicious servers. Let the permission check handle UNC paths.
|
||||
if (fullFilePath.startsWith('\\\\') || fullFilePath.startsWith('//')) {
|
||||
return { result: true }
|
||||
}
|
||||
|
||||
const fs = getFsImplementation()
|
||||
let fileMtimeMs: number
|
||||
try {
|
||||
const fileStat = await fs.stat(fullFilePath)
|
||||
fileMtimeMs = fileStat.mtimeMs
|
||||
} catch (e) {
|
||||
if (isENOENT(e)) {
|
||||
return { result: true }
|
||||
}
|
||||
throw e
|
||||
}
|
||||
|
||||
const readTimestamp = toolUseContext.readFileState.get(fullFilePath)
|
||||
if (!readTimestamp || readTimestamp.isPartialView) {
|
||||
return {
|
||||
result: false,
|
||||
message:
|
||||
'File has not been read yet. Read it first before writing to it.',
|
||||
errorCode: 2,
|
||||
}
|
||||
}
|
||||
|
||||
// Reuse mtime from the stat above — avoids a redundant statSync via
|
||||
// getFileModificationTime. The readTimestamp guard above ensures this
|
||||
// block is always reached when the file exists.
|
||||
const lastWriteTime = Math.floor(fileMtimeMs)
|
||||
if (lastWriteTime > readTimestamp.timestamp) {
|
||||
return {
|
||||
result: false,
|
||||
message:
|
||||
'File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.',
|
||||
errorCode: 3,
|
||||
}
|
||||
}
|
||||
|
||||
return { result: true }
|
||||
},
|
||||
async call(
|
||||
{ file_path, content },
|
||||
{ readFileState, updateFileHistoryState, dynamicSkillDirTriggers },
|
||||
_,
|
||||
parentMessage,
|
||||
) {
|
||||
const fullFilePath = expandPath(file_path)
|
||||
const dir = dirname(fullFilePath)
|
||||
|
||||
// Discover skills from this file's path (fire-and-forget, non-blocking)
|
||||
const cwd = getCwd()
|
||||
const newSkillDirs = await discoverSkillDirsForPaths([fullFilePath], cwd)
|
||||
if (newSkillDirs.length > 0) {
|
||||
// Store discovered dirs for attachment display
|
||||
for (const dir of newSkillDirs) {
|
||||
dynamicSkillDirTriggers?.add(dir)
|
||||
}
|
||||
// Don't await - let skill loading happen in the background
|
||||
addSkillDirectories(newSkillDirs).catch(() => {})
|
||||
}
|
||||
|
||||
// Activate conditional skills whose path patterns match this file
|
||||
activateConditionalSkillsForPaths([fullFilePath], cwd)
|
||||
|
||||
await diagnosticTracker.beforeFileEdited(fullFilePath)
|
||||
|
||||
// Ensure parent directory exists before the atomic read-modify-write section.
|
||||
// Must stay OUTSIDE the critical section below (a yield between the staleness
|
||||
// check and writeTextContent lets concurrent edits interleave), and BEFORE the
|
||||
// write (lazy-mkdir-on-ENOENT would fire a spurious tengu_atomic_write_error
|
||||
// inside writeFileSyncAndFlush_DEPRECATED before ENOENT propagates back).
|
||||
await getFsImplementation().mkdir(dir)
|
||||
if (fileHistoryEnabled()) {
|
||||
// Backup captures pre-edit content — safe to call before the staleness
|
||||
// check (idempotent v1 backup keyed on content hash; if staleness fails
|
||||
// later we just have an unused backup, not corrupt state).
|
||||
await fileHistoryTrackEdit(
|
||||
updateFileHistoryState,
|
||||
fullFilePath,
|
||||
parentMessage.uuid,
|
||||
)
|
||||
}
|
||||
|
||||
// Load current state and confirm no changes since last read.
|
||||
// Please avoid async operations between here and writing to disk to preserve atomicity.
|
||||
let meta: ReturnType<typeof readFileSyncWithMetadata> | null
|
||||
try {
|
||||
meta = readFileSyncWithMetadata(fullFilePath)
|
||||
} catch (e) {
|
||||
if (isENOENT(e)) {
|
||||
meta = null
|
||||
} else {
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
if (meta !== null) {
|
||||
const lastWriteTime = getFileModificationTime(fullFilePath)
|
||||
const lastRead = readFileState.get(fullFilePath)
|
||||
if (!lastRead || lastWriteTime > lastRead.timestamp) {
|
||||
// Timestamp indicates modification, but on Windows timestamps can change
|
||||
// without content changes (cloud sync, antivirus, etc.). For full reads,
|
||||
// compare content as a fallback to avoid false positives.
|
||||
const isFullRead =
|
||||
lastRead &&
|
||||
lastRead.offset === undefined &&
|
||||
lastRead.limit === undefined
|
||||
// meta.content is CRLF-normalized — matches readFileState's normalized form.
|
||||
if (!isFullRead || meta.content !== lastRead.content) {
|
||||
throw new Error(FILE_UNEXPECTEDLY_MODIFIED_ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const enc = meta?.encoding ?? 'utf8'
|
||||
const oldContent = meta?.content ?? null
|
||||
|
||||
// Write is a full content replacement — the model sent explicit line endings
|
||||
// in `content` and meant them. Do not rewrite them. Previously we preserved
|
||||
// the old file's line endings (or sampled the repo via ripgrep for new
|
||||
// files), which silently corrupted e.g. bash scripts with \r on Linux when
|
||||
// overwriting a CRLF file or when binaries in cwd poisoned the repo sample.
|
||||
writeTextContent(fullFilePath, content, enc, 'LF')
|
||||
|
||||
// Notify LSP servers about file modification (didChange) and save (didSave)
|
||||
const lspManager = getLspServerManager()
|
||||
if (lspManager) {
|
||||
// Clear previously delivered diagnostics so new ones will be shown
|
||||
clearDeliveredDiagnosticsForFile(`file://${fullFilePath}`)
|
||||
// didChange: Content has been modified
|
||||
lspManager.changeFile(fullFilePath, content).catch((err: Error) => {
|
||||
logForDebugging(
|
||||
`LSP: Failed to notify server of file change for ${fullFilePath}: ${err.message}`,
|
||||
)
|
||||
logError(err)
|
||||
})
|
||||
// didSave: File has been saved to disk (triggers diagnostics in TypeScript server)
|
||||
lspManager.saveFile(fullFilePath).catch((err: Error) => {
|
||||
logForDebugging(
|
||||
`LSP: Failed to notify server of file save for ${fullFilePath}: ${err.message}`,
|
||||
)
|
||||
logError(err)
|
||||
})
|
||||
}
|
||||
|
||||
// Notify VSCode about the file change for diff view
|
||||
notifyVscodeFileUpdated(fullFilePath, oldContent, content)
|
||||
|
||||
// Update read timestamp, to invalidate stale writes
|
||||
readFileState.set(fullFilePath, {
|
||||
content,
|
||||
timestamp: getFileModificationTime(fullFilePath),
|
||||
offset: undefined,
|
||||
limit: undefined,
|
||||
})
|
||||
|
||||
// Log when writing to CLAUDE.md
|
||||
if (fullFilePath.endsWith(`${sep}CLAUDE.md`)) {
|
||||
logEvent('tengu_write_claudemd', {})
|
||||
}
|
||||
|
||||
let gitDiff: ToolUseDiff | undefined
|
||||
if (
|
||||
isEnvTruthy(process.env.CLAUDE_CODE_REMOTE) &&
|
||||
getFeatureValue_CACHED_MAY_BE_STALE('tengu_quartz_lantern', false)
|
||||
) {
|
||||
const startTime = Date.now()
|
||||
const diff = await fetchSingleFileGitDiff(fullFilePath)
|
||||
if (diff) gitDiff = diff
|
||||
logEvent('tengu_tool_use_diff_computed', {
|
||||
isWriteTool: true,
|
||||
durationMs: Date.now() - startTime,
|
||||
hasDiff: !!diff,
|
||||
})
|
||||
}
|
||||
|
||||
if (oldContent) {
|
||||
const patch = getPatchForDisplay({
|
||||
filePath: file_path,
|
||||
fileContents: oldContent,
|
||||
edits: [
|
||||
{
|
||||
old_string: oldContent,
|
||||
new_string: content,
|
||||
replace_all: false,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
const data = {
|
||||
type: 'update' as const,
|
||||
filePath: file_path,
|
||||
content,
|
||||
structuredPatch: patch,
|
||||
originalFile: oldContent,
|
||||
...(gitDiff && { gitDiff }),
|
||||
}
|
||||
// Track lines added and removed for file updates, right before yielding result
|
||||
countLinesChanged(patch)
|
||||
|
||||
logFileOperation({
|
||||
operation: 'write',
|
||||
tool: 'FileWriteTool',
|
||||
filePath: fullFilePath,
|
||||
type: 'update',
|
||||
})
|
||||
|
||||
return {
|
||||
data,
|
||||
}
|
||||
}
|
||||
|
||||
const data = {
|
||||
type: 'create' as const,
|
||||
filePath: file_path,
|
||||
content,
|
||||
structuredPatch: [],
|
||||
originalFile: null,
|
||||
...(gitDiff && { gitDiff }),
|
||||
}
|
||||
|
||||
// For creation of new files, count all lines as additions, right before yielding the result
|
||||
countLinesChanged([], content)
|
||||
|
||||
logFileOperation({
|
||||
operation: 'write',
|
||||
tool: 'FileWriteTool',
|
||||
filePath: fullFilePath,
|
||||
type: 'create',
|
||||
})
|
||||
|
||||
return {
|
||||
data,
|
||||
}
|
||||
},
|
||||
mapToolResultToToolResultBlockParam({ filePath, type }, toolUseID) {
|
||||
switch (type) {
|
||||
case 'create':
|
||||
return {
|
||||
tool_use_id: toolUseID,
|
||||
type: 'tool_result',
|
||||
content: `File created successfully at: ${filePath}`,
|
||||
}
|
||||
case 'update':
|
||||
return {
|
||||
tool_use_id: toolUseID,
|
||||
type: 'tool_result',
|
||||
content: `The file ${filePath} has been updated successfully.`,
|
||||
}
|
||||
}
|
||||
},
|
||||
} satisfies ToolDef<InputSchema, Output>)
|
||||
@@ -0,0 +1,405 @@
|
||||
import { c as _c } from "react/compiler-runtime";
|
||||
import type { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs';
|
||||
import type { StructuredPatchHunk } from 'diff';
|
||||
import { isAbsolute, relative, resolve } from 'path';
|
||||
import * as React from 'react';
|
||||
import { Suspense, use, useState } from 'react';
|
||||
import { MessageResponse } from 'src/components/MessageResponse.js';
|
||||
import { extractTag } from 'src/utils/messages.js';
|
||||
import { CtrlOToExpand } from '../../components/CtrlOToExpand.js';
|
||||
import { FallbackToolUseErrorMessage } from '../../components/FallbackToolUseErrorMessage.js';
|
||||
import { FileEditToolUpdatedMessage } from '../../components/FileEditToolUpdatedMessage.js';
|
||||
import { FileEditToolUseRejectedMessage } from '../../components/FileEditToolUseRejectedMessage.js';
|
||||
import { FilePathLink } from '../../components/FilePathLink.js';
|
||||
import { HighlightedCode } from '../../components/HighlightedCode.js';
|
||||
import { useTerminalSize } from '../../hooks/useTerminalSize.js';
|
||||
import { Box, Text } from '../../ink.js';
|
||||
import type { ToolProgressData } from '../../Tool.js';
|
||||
import type { ProgressMessage } from '../../types/message.js';
|
||||
import { getCwd } from '../../utils/cwd.js';
|
||||
import { getPatchForDisplay } from '../../utils/diff.js';
|
||||
import { getDisplayPath } from '../../utils/file.js';
|
||||
import { logError } from '../../utils/log.js';
|
||||
import { getPlansDirectory } from '../../utils/plans.js';
|
||||
import { openForScan, readCapped } from '../../utils/readEditContext.js';
|
||||
import type { Output } from './FileWriteTool.js';
|
||||
const MAX_LINES_TO_RENDER = 10;
|
||||
// Model output uses \n regardless of platform, so always split on \n.
|
||||
// os.EOL is \r\n on Windows, which would give numLines=1 for all files.
|
||||
const EOL = '\n';
|
||||
|
||||
/**
|
||||
* Count visible lines in file content. A trailing newline is treated as a
|
||||
* line terminator (not a new empty line), matching editor line numbering.
|
||||
*/
|
||||
export function countLines(content: string): number {
|
||||
const parts = content.split(EOL);
|
||||
return content.endsWith(EOL) ? parts.length - 1 : parts.length;
|
||||
}
|
||||
function FileWriteToolCreatedMessage(t0) {
|
||||
const $ = _c(25);
|
||||
const {
|
||||
filePath,
|
||||
content,
|
||||
verbose
|
||||
} = t0;
|
||||
const {
|
||||
columns
|
||||
} = useTerminalSize();
|
||||
const contentWithFallback = content || "(No content)";
|
||||
const numLines = countLines(content);
|
||||
const plusLines = numLines - MAX_LINES_TO_RENDER;
|
||||
let t1;
|
||||
if ($[0] !== numLines) {
|
||||
t1 = <Text bold={true}>{numLines}</Text>;
|
||||
$[0] = numLines;
|
||||
$[1] = t1;
|
||||
} else {
|
||||
t1 = $[1];
|
||||
}
|
||||
let t2;
|
||||
if ($[2] !== filePath || $[3] !== verbose) {
|
||||
t2 = verbose ? filePath : relative(getCwd(), filePath);
|
||||
$[2] = filePath;
|
||||
$[3] = verbose;
|
||||
$[4] = t2;
|
||||
} else {
|
||||
t2 = $[4];
|
||||
}
|
||||
let t3;
|
||||
if ($[5] !== t2) {
|
||||
t3 = <Text bold={true}>{t2}</Text>;
|
||||
$[5] = t2;
|
||||
$[6] = t3;
|
||||
} else {
|
||||
t3 = $[6];
|
||||
}
|
||||
let t4;
|
||||
if ($[7] !== t1 || $[8] !== t3) {
|
||||
t4 = <Text>Wrote {t1} lines to{" "}{t3}</Text>;
|
||||
$[7] = t1;
|
||||
$[8] = t3;
|
||||
$[9] = t4;
|
||||
} else {
|
||||
t4 = $[9];
|
||||
}
|
||||
let t5;
|
||||
if ($[10] !== contentWithFallback || $[11] !== verbose) {
|
||||
t5 = verbose ? contentWithFallback : contentWithFallback.split("\n").slice(0, MAX_LINES_TO_RENDER).join("\n");
|
||||
$[10] = contentWithFallback;
|
||||
$[11] = verbose;
|
||||
$[12] = t5;
|
||||
} else {
|
||||
t5 = $[12];
|
||||
}
|
||||
const t6 = columns - 12;
|
||||
let t7;
|
||||
if ($[13] !== filePath || $[14] !== t5 || $[15] !== t6) {
|
||||
t7 = <Box flexDirection="column"><HighlightedCode code={t5} filePath={filePath} width={t6} /></Box>;
|
||||
$[13] = filePath;
|
||||
$[14] = t5;
|
||||
$[15] = t6;
|
||||
$[16] = t7;
|
||||
} else {
|
||||
t7 = $[16];
|
||||
}
|
||||
let t8;
|
||||
if ($[17] !== numLines || $[18] !== plusLines || $[19] !== verbose) {
|
||||
t8 = !verbose && plusLines > 0 && <Text dimColor={true}>… +{plusLines} {plusLines === 1 ? "line" : "lines"}{" "}{numLines > 0 && <CtrlOToExpand />}</Text>;
|
||||
$[17] = numLines;
|
||||
$[18] = plusLines;
|
||||
$[19] = verbose;
|
||||
$[20] = t8;
|
||||
} else {
|
||||
t8 = $[20];
|
||||
}
|
||||
let t9;
|
||||
if ($[21] !== t4 || $[22] !== t7 || $[23] !== t8) {
|
||||
t9 = <MessageResponse><Box flexDirection="column">{t4}{t7}{t8}</Box></MessageResponse>;
|
||||
$[21] = t4;
|
||||
$[22] = t7;
|
||||
$[23] = t8;
|
||||
$[24] = t9;
|
||||
} else {
|
||||
t9 = $[24];
|
||||
}
|
||||
return t9;
|
||||
}
|
||||
export function userFacingName(input: Partial<{
|
||||
file_path: string;
|
||||
content: string;
|
||||
}> | undefined): string {
|
||||
if (input?.file_path?.startsWith(getPlansDirectory())) {
|
||||
return 'Updated plan';
|
||||
}
|
||||
return 'Write';
|
||||
}
|
||||
|
||||
/** Gates fullscreen click-to-expand. Only `create` truncates (to
|
||||
* MAX_LINES_TO_RENDER); `update` renders the full diff regardless of verbose.
|
||||
* Called per visible message on hover/scroll, so early-exit after finding the
|
||||
* (MAX+1)th line instead of splitting the whole (possibly huge) content. */
|
||||
export function isResultTruncated({
|
||||
type,
|
||||
content
|
||||
}: Output): boolean {
|
||||
if (type !== 'create') return false;
|
||||
let pos = 0;
|
||||
for (let i = 0; i < MAX_LINES_TO_RENDER; i++) {
|
||||
pos = content.indexOf(EOL, pos);
|
||||
if (pos === -1) return false;
|
||||
pos++;
|
||||
}
|
||||
// countLines treats a trailing EOL as a terminator, not a new line
|
||||
return pos < content.length;
|
||||
}
|
||||
export function getToolUseSummary(input: Partial<{
|
||||
file_path: string;
|
||||
content: string;
|
||||
}> | undefined): string | null {
|
||||
if (!input?.file_path) {
|
||||
return null;
|
||||
}
|
||||
return getDisplayPath(input.file_path);
|
||||
}
|
||||
export function renderToolUseMessage(input: Partial<{
|
||||
file_path: string;
|
||||
content: string;
|
||||
}>, {
|
||||
verbose
|
||||
}: {
|
||||
verbose: boolean;
|
||||
}): React.ReactNode {
|
||||
if (!input.file_path) {
|
||||
return null;
|
||||
}
|
||||
// For plan files, path is already in userFacingName
|
||||
if (input.file_path.startsWith(getPlansDirectory())) {
|
||||
return '';
|
||||
}
|
||||
return <FilePathLink filePath={input.file_path}>
|
||||
{verbose ? input.file_path : getDisplayPath(input.file_path)}
|
||||
</FilePathLink>;
|
||||
}
|
||||
export function renderToolUseRejectedMessage({
|
||||
file_path,
|
||||
content
|
||||
}: {
|
||||
file_path: string;
|
||||
content: string;
|
||||
}, {
|
||||
style,
|
||||
verbose
|
||||
}: {
|
||||
style?: 'condensed';
|
||||
verbose: boolean;
|
||||
}): React.ReactNode {
|
||||
return <WriteRejectionDiff filePath={file_path} content={content} style={style} verbose={verbose} />;
|
||||
}
|
||||
type RejectionDiffData = {
|
||||
type: 'create';
|
||||
} | {
|
||||
type: 'update';
|
||||
patch: StructuredPatchHunk[];
|
||||
oldContent: string;
|
||||
} | {
|
||||
type: 'error';
|
||||
};
|
||||
function WriteRejectionDiff(t0) {
|
||||
const $ = _c(20);
|
||||
const {
|
||||
filePath,
|
||||
content,
|
||||
style,
|
||||
verbose
|
||||
} = t0;
|
||||
let t1;
|
||||
if ($[0] !== content || $[1] !== filePath) {
|
||||
t1 = () => loadRejectionDiff(filePath, content);
|
||||
$[0] = content;
|
||||
$[1] = filePath;
|
||||
$[2] = t1;
|
||||
} else {
|
||||
t1 = $[2];
|
||||
}
|
||||
const [dataPromise] = useState(t1);
|
||||
let t2;
|
||||
if ($[3] !== content) {
|
||||
t2 = content.split("\n")[0] ?? null;
|
||||
$[3] = content;
|
||||
$[4] = t2;
|
||||
} else {
|
||||
t2 = $[4];
|
||||
}
|
||||
const firstLine = t2;
|
||||
let t3;
|
||||
if ($[5] !== content || $[6] !== filePath || $[7] !== firstLine || $[8] !== verbose) {
|
||||
t3 = <FileEditToolUseRejectedMessage file_path={filePath} operation="write" content={content} firstLine={firstLine} verbose={verbose} />;
|
||||
$[5] = content;
|
||||
$[6] = filePath;
|
||||
$[7] = firstLine;
|
||||
$[8] = verbose;
|
||||
$[9] = t3;
|
||||
} else {
|
||||
t3 = $[9];
|
||||
}
|
||||
const createFallback = t3;
|
||||
let t4;
|
||||
if ($[10] !== createFallback || $[11] !== dataPromise || $[12] !== filePath || $[13] !== firstLine || $[14] !== style || $[15] !== verbose) {
|
||||
t4 = <WriteRejectionBody promise={dataPromise} filePath={filePath} firstLine={firstLine} createFallback={createFallback} style={style} verbose={verbose} />;
|
||||
$[10] = createFallback;
|
||||
$[11] = dataPromise;
|
||||
$[12] = filePath;
|
||||
$[13] = firstLine;
|
||||
$[14] = style;
|
||||
$[15] = verbose;
|
||||
$[16] = t4;
|
||||
} else {
|
||||
t4 = $[16];
|
||||
}
|
||||
let t5;
|
||||
if ($[17] !== createFallback || $[18] !== t4) {
|
||||
t5 = <Suspense fallback={createFallback}>{t4}</Suspense>;
|
||||
$[17] = createFallback;
|
||||
$[18] = t4;
|
||||
$[19] = t5;
|
||||
} else {
|
||||
t5 = $[19];
|
||||
}
|
||||
return t5;
|
||||
}
|
||||
function WriteRejectionBody(t0) {
|
||||
const $ = _c(8);
|
||||
const {
|
||||
promise,
|
||||
filePath,
|
||||
firstLine,
|
||||
createFallback,
|
||||
style,
|
||||
verbose
|
||||
} = t0;
|
||||
const data = use(promise);
|
||||
if (data.type === "create") {
|
||||
return createFallback;
|
||||
}
|
||||
if (data.type === "error") {
|
||||
let t1;
|
||||
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
t1 = <MessageResponse><Text>(No changes)</Text></MessageResponse>;
|
||||
$[0] = t1;
|
||||
} else {
|
||||
t1 = $[0];
|
||||
}
|
||||
return t1;
|
||||
}
|
||||
let t1;
|
||||
if ($[1] !== data.oldContent || $[2] !== data.patch || $[3] !== filePath || $[4] !== firstLine || $[5] !== style || $[6] !== verbose) {
|
||||
t1 = <FileEditToolUseRejectedMessage file_path={filePath} operation="update" patch={data.patch} firstLine={firstLine} fileContent={data.oldContent} style={style} verbose={verbose} />;
|
||||
$[1] = data.oldContent;
|
||||
$[2] = data.patch;
|
||||
$[3] = filePath;
|
||||
$[4] = firstLine;
|
||||
$[5] = style;
|
||||
$[6] = verbose;
|
||||
$[7] = t1;
|
||||
} else {
|
||||
t1 = $[7];
|
||||
}
|
||||
return t1;
|
||||
}
|
||||
async function loadRejectionDiff(filePath: string, content: string): Promise<RejectionDiffData> {
|
||||
try {
|
||||
const fullFilePath = isAbsolute(filePath) ? filePath : resolve(getCwd(), filePath);
|
||||
const handle = await openForScan(fullFilePath);
|
||||
if (handle === null) return {
|
||||
type: 'create'
|
||||
};
|
||||
let oldContent: string | null;
|
||||
try {
|
||||
oldContent = await readCapped(handle);
|
||||
} finally {
|
||||
await handle.close();
|
||||
}
|
||||
// File exceeds MAX_SCAN_BYTES — fall back to the create view rather than
|
||||
// OOMing on a diff of a multi-GB file.
|
||||
if (oldContent === null) return {
|
||||
type: 'create'
|
||||
};
|
||||
const patch = getPatchForDisplay({
|
||||
filePath,
|
||||
fileContents: oldContent,
|
||||
edits: [{
|
||||
old_string: oldContent,
|
||||
new_string: content,
|
||||
replace_all: false
|
||||
}]
|
||||
});
|
||||
return {
|
||||
type: 'update',
|
||||
patch,
|
||||
oldContent
|
||||
};
|
||||
} catch (e) {
|
||||
// User may have manually applied the change while the diff was shown.
|
||||
logError(e as Error);
|
||||
return {
|
||||
type: 'error'
|
||||
};
|
||||
}
|
||||
}
|
||||
export function renderToolUseErrorMessage(result: ToolResultBlockParam['content'], {
|
||||
verbose
|
||||
}: {
|
||||
verbose: boolean;
|
||||
}): React.ReactNode {
|
||||
if (!verbose && typeof result === 'string' && extractTag(result, 'tool_use_error')) {
|
||||
return <MessageResponse>
|
||||
<Text color="error">Error writing file</Text>
|
||||
</MessageResponse>;
|
||||
}
|
||||
return <FallbackToolUseErrorMessage result={result} verbose={verbose} />;
|
||||
}
|
||||
export function renderToolResultMessage({
|
||||
filePath,
|
||||
content,
|
||||
structuredPatch,
|
||||
type,
|
||||
originalFile
|
||||
}: Output, _progressMessagesForMessage: ProgressMessage<ToolProgressData>[], {
|
||||
style,
|
||||
verbose
|
||||
}: {
|
||||
style?: 'condensed';
|
||||
verbose: boolean;
|
||||
}): React.ReactNode {
|
||||
switch (type) {
|
||||
case 'create':
|
||||
{
|
||||
const isPlanFile = filePath.startsWith(getPlansDirectory());
|
||||
|
||||
// Plan files: invert condensed behavior
|
||||
// - Regular mode: just show hint (user can type /plan to see full content)
|
||||
// - Condensed mode (subagent view): show full content
|
||||
if (isPlanFile && !verbose) {
|
||||
if (style !== 'condensed') {
|
||||
return <MessageResponse>
|
||||
<Text dimColor>/plan to preview</Text>
|
||||
</MessageResponse>;
|
||||
}
|
||||
} else if (style === 'condensed' && !verbose) {
|
||||
const numLines = countLines(content);
|
||||
return <Text>
|
||||
Wrote <Text bold>{numLines}</Text> lines to{' '}
|
||||
<Text bold>{relative(getCwd(), filePath)}</Text>
|
||||
</Text>;
|
||||
}
|
||||
return <FileWriteToolCreatedMessage filePath={filePath} content={content} verbose={verbose} />;
|
||||
}
|
||||
case 'update':
|
||||
{
|
||||
const isPlanFile = filePath.startsWith(getPlansDirectory());
|
||||
return <FileEditToolUpdatedMessage filePath={filePath} structuredPatch={structuredPatch} firstLine={content.split('\n')[0] ?? null} fileContent={originalFile ?? undefined} style={style} verbose={verbose} previewHint={isPlanFile ? '/plan to preview' : undefined} />;
|
||||
}
|
||||
}
|
||||
}
|
||||
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJuYW1lcyI6WyJUb29sUmVzdWx0QmxvY2tQYXJhbSIsIlN0cnVjdHVyZWRQYXRjaEh1bmsiLCJpc0Fic29sdXRlIiwicmVsYXRpdmUiLCJyZXNvbHZlIiwiUmVhY3QiLCJTdXNwZW5zZSIsInVzZSIsInVzZVN0YXRlIiwiTWVzc2FnZVJlc3BvbnNlIiwiZXh0cmFjdFRhZyIsIkN0cmxPVG9FeHBhbmQiLCJGYWxsYmFja1Rvb2xVc2VFcnJvck1lc3NhZ2UiLCJGaWxlRWRpdFRvb2xVcGRhdGVkTWVzc2FnZSIsIkZpbGVFZGl0VG9vbFVzZVJlamVjdGVkTWVzc2FnZSIsIkZpbGVQYXRoTGluayIsIkhpZ2hsaWdodGVkQ29kZSIsInVzZVRlcm1pbmFsU2l6ZSIsIkJveCIsIlRleHQiLCJUb29sUH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IHtcbiAgZmlsZVBhdGg6IHN0cmluZ1xuICBjb250ZW50OiBzdHJpbmdcbiAgdmVyYm9zZTogYm9vbGVhblxufSk6IFJlYWN0LlJlYWN0Tm9kZSB7XG4gIGNvbnN0IHsgY29sdW1ucyB9ID0gdXNlVGVybWluYWxTaXplKClcbiAgY29uc3QgY29udGVudFdpdGhGYWxsYmFjayA
Line truncated
|
||||
@@ -0,0 +1,18 @@
|
||||
import { FILE_READ_TOOL_NAME } from '../FileReadTool/prompt.js'
|
||||
|
||||
export const FILE_WRITE_TOOL_NAME = 'Write'
|
||||
export const DESCRIPTION = 'Write a file to the local filesystem.'
|
||||
|
||||
function getPreReadInstruction(): string {
|
||||
return `\n- If this is an existing file, you MUST use the ${FILE_READ_TOOL_NAME} tool first to read the file's contents. This tool will fail if you did not read the file first.`
|
||||
}
|
||||
|
||||
export function getWriteToolDescription(): string {
|
||||
return `Writes a file to the local filesystem.
|
||||
|
||||
Usage:
|
||||
- This tool will overwrite the existing file if there is one at the provided path.${getPreReadInstruction()}
|
||||
- Prefer the Edit tool for modifying existing files \u2014 it only sends the diff. Only use this tool to create new files or for complete rewrites.
|
||||
- NEVER create documentation files (*.md) or README files unless explicitly requested by the User.
|
||||
- Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.`
|
||||
}
|
||||
Reference in new issue
Block a user