write-special-chars-readback
Что он делает
Этот скилл представляет собой вариант обходного пути для спецсимволов с добавленной проверкой после сохранения. Он нужен тем, кто хочет убедиться, что файл с кодом записан правильно.
Когда использовать
- ✓Когда файл с кодом, содержащий кавычки или обратные кавычки, нужно сохранить надежно.
- ✓Когда нужно подтвердить, что сохраненный файл совпадает с задуманным.
- ✓Когда после сохранения нужно удалить временный вспомогательный скрипт.
Ссылка на скилл
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/write-special-chars-readback/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Можешь сохранить этот файл с кодом со всеми кавычками и обратными кавычками, а потом проверить, что он выглядит правильно?”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
Агент сохраняет файл через вспомогательный скрипт, читает файл обратно, чтобы подтвердить содержимое, и затем удаляет вспомогательный скрипт.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с GitHub.
Write File Special Characters Workaround (Verified)
Problem
The write_file tool may fail with [ERROR] unknown error when file content
contains special characters such as:
- Apostrophes / single quotes (
') - Backticks (
`) - Template literals (
`${variable}`) common in TypeScript/JavaScript - Complex combinations of quotes and escape sequences
This is especially common when writing TypeScript, JavaScript, shell scripts, or any source file with string interpolation syntax.
Solution: Python Heredoc Workaround
Write a small Python script to /tmp/ that uses triple-quoted strings to
embed the file content, then execute it with python3.
Step-by-Step
- Compose a Python writer script using triple-quoted strings (
"""..."""). - Write the Python script itself to
/tmp/— its content is plain enough thatwrite_filewill succeed (no problematic characters in the wrapper). - Execute the script with
run_shell:python3 /tmp/write_<name>.py - Verify the written file with
read_fileto confirm contents are correct. - Clean up the
/tmphelper script:rm /tmp/write_<name>.py
Escaping Rules Inside the Python Script
| Character | How to handle |
|---|---|
Backslash \ |
Escape as \\ |
Triple double-quote """ |
Escape as \"\"\" or use ''' strings instead |
Everything else (backticks, $, ', {}) |
No escaping needed |
Template
#!/usr/bin/env python3
content = """
<YOUR FILE CONTENT HERE>
""".lstrip("\n")
with open("/path/to/target/file.ts", "w") as f:
f.write(content)
print("File written successfully.")
Concrete Example
Suppose you need to write a TypeScript file with template literals and
apostrophes that causes write_file to fail:
Step 1 — Write the Python helper to /tmp/:
Use write_file with path /tmp/write_greeting.py and content:
#!/usr/bin/env python3
content = """
export function greet(name: string): string {
const msg = `Hello, ${name}! It's a great day.`;
console.log(`Greeting: ${msg}`);
return msg;
}
""".lstrip("\n")
with open("/app/src/greeting.ts", "w") as f:
f.write(content)
print("Written: /app/src/greeting.ts")
Step 2 — Execute the helper:
python3 /tmp/write_greeting.py
Step 3 — Verify with read_file:
Use read_file with path /app/src/greeting.ts to confirm the file content
is exactly what was intended. This catches silent truncation or encoding
issues that shell cat output might obscure.
Step 4 — Clean up the helper:
rm /tmp/write_greeting.py
This keeps /tmp tidy and prevents stale helper scripts from being confused
with current ones on subsequent runs.
Standard Post-Write Checklist
After every use of this pattern, always complete all three of these steps:
| Step | Action | Why |
|---|---|---|
| ✅ Execute | python3 /tmp/write_<name>.py |
Writes the target file |
| ✅ Verify | read_file on the target path |
Confirms content integrity |
| ✅ Clean up | rm /tmp/write_<name>.py |
Prevents stale helper accumulation |
Skipping verification risks silently shipping a truncated or malformed file. Skipping cleanup risks confusion when the same helper name is reused later.
When to Use This Pattern
write_filereturns[ERROR] unknown errorfor a specific file.- The file contains TypeScript/JavaScript template literals.
- The file contains mixed quote styles or shell-like special characters.
- Any time direct file writing fails and content cannot be easily sanitized.
Multiple Files
For writing several problematic files in one pass, consolidate them into a single Python script:
#!/usr/bin/env python3
import os
files = {
"/app/src/component.tsx": """
import React from 'react';
const App = () => (
<div className={`container`}>
<h1>It's working!</h1>
</div>
);
export default App;
""".lstrip("\n"),
"/app/src/utils.ts": """
export const format = (val: number) => `Value: ${val.toFixed(2)}`;
""".lstrip("\n"),
}
for path, content in files.items():
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(content)
print(f"Written: {path}")
After running the multi-file script:
- Use
read_fileon each target path to verify all files were written correctly. - Then clean up:
rm /tmp/write_<name>.py
Key Advantages
- No shell escaping required — Python triple-q
Частые вопросы
Что делает проверка?
Она читает сохраненный файл обратно, чтобы вы могли убедиться, что текст правильный.
Зачем удалять вспомогательный скрипт?
Так временная папка остается чистой после завершения сохранения.
Меняется ли подход?
Используется тот же метод вспомогательного скрипта, но с добавленными шагами чтения обратно и очистки.
Подробности
Оригинальное описание автора
Workaround for write_file failures caused by special characters (apostrophes, backticks, template literals) using a Python heredoc script, with mandatory post-write verification via read_file and cleanup of /tmp helper scripts.
repo: HKUDS/AgentPilot
Популярность
- Звёзды на GitHub
- 7.8k
- Место в рейтинге
- #13094
- Лицензия
- MIT
- Обновлён
- 01.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
agentpilot
7.8kПомогает агенту улучшать проект шаг за шагом: готовит задачу и запускает цикл AgentPilot, который предлагает, проверяет и оценивает изменения.
openspace
7.8kПомогает агенту настроить OpenSpace, инструмент для хранения и получения скиллов агента, и подключить его к вашему ИИ-приложению через MCP.
rsi-arena
7.8kПомогает агенту настроить и запустить стандартные тесты ИИ, например AIME и Terminal-Bench, чтобы сравнивать разные методы улучшения.
experiment-guide
7.8kПомогает агенту планировать небольшие эксперименты, читать их результаты и записывать выводы, пока он исследует, как улучшить программу.
Похожие скиллы
diffs
394kПозволяет агенту создать настоящее сравнение правок в виде ссылки или файла изображения, которым можно поделиться, вместо ручной сводки.
coding-agent
394kПомогает агенту передать большую задачу по коду в Codex, Claude Code или OpenCode как фоновому исполнителю, а затем проверять ее ход.
gh-issues
394kПомогает агенту находить задачи GitHub, выбирать, над какими работать, и открывать запросы на слияние с исправлениями, включая ответы на комментарии рецензентов.