write-special-chars-readback
O que ela faz
Esta skill é uma versão da solução para caracteres especiais que acrescenta uma verificação depois do salvamento. É para pessoas que querem confirmar que um arquivo de código foi escrito corretamente.
Quando usar
- ✓Quando um arquivo de código com aspas ou crases precisa ser salvo de forma confiável.
- ✓Quando você quer confirmar que o arquivo salvo corresponde ao que você pretendia.
- ✓Quando você quer que o script auxiliar temporário seja removido depois do salvamento.
Link da skill
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/write-special-chars-readback/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Pode salvar este arquivo de código com todas as aspas e crases e depois verificar se ele está correto?”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente salva o arquivo por meio de um script auxiliar, lê o arquivo de volta para confirmar o conteúdo e depois apaga o script auxiliar.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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
Perguntas frequentes
O que a verificação faz?
Ela lê o arquivo salvo de volta, para que você possa confirmar se o texto está correto.
Por que remover o script auxiliar?
Isso mantém a pasta temporária limpa depois que o salvamento termina.
Muda a abordagem?
Usa o mesmo método de script auxiliar, com uma etapa de leitura de volta e limpeza acrescentada.
Detalhes
Descrição original do autor
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
Popularidade
- Estrelas no GitHub
- 7,8 mil
- Posição no ranking
- #13094
- Licença
- MIT
- Atualizada em
- 01/11/2026
Comentários
- …
Mais skills deste repositório
agentpilot
7,8 milAjuda seu agente a melhorar um projeto passo a passo, preparando uma tarefa e executando o ciclo do AgentPilot, que propõe, testa e pontua mudanças.
openspace
7,8 milAjuda seu agente a configurar o OpenSpace, uma ferramenta que armazena e busca skills de agentes, e a conectá-la ao seu app de IA pelo MCP.
rsi-arena
7,8 milAjuda seu agente a configurar e rodar testes padrão de benchmark de IA, como AIME e Terminal-Bench, para comparar diferentes métodos de melhoria.
experiment-guide
7,8 milAjuda seu agente a planejar pequenos experimentos, ler seus resultados e registrar descobertas enquanto investiga como melhorar um programa.
Skills parecidas
diffs
394 milPermite que seu agente gere um diff real e compartilhável das edições, como link de visualização ou arquivo de imagem, em vez de um resumo escrito à mão.
coding-agent
394 milAjuda seu agente a passar um trabalho grande de programação para o Codex, Claude Code ou OpenCode em segundo plano e acompanhar o andamento.
gh-issues
394 milAjuda seu agente a encontrar issues do GitHub, escolher quais resolver e abrir pull requests com correções, acompanhando os comentários de revisão.