Skip to content

Commit 20a3dc7

Browse files
committed
Add 'handoff' command: paste-ready prompts for continuing in another AI agent
The new feature closes the 'I want to switch agents mid-conversation' UX gap. One command produces everything needed to keep going in Claude.ai, ChatGPT, Cursor, or any other chat-style AI tool — without re-explaining context manually. USAGE claude-backup handoff <id-prefix> # print to stdout claude-backup handoff <id-prefix> | pbcopy # macOS — straight to clipboard claude-backup handoff <id-prefix> | xclip ... # Linux claude-backup handoff <id-prefix> -o handoff.md # save to a file claude-backup handoff <id-prefix> --lang en|ru # force wrapper language OUTPUT SHAPE A self-contained prompt with: 1. Framing line ('You are continuing a conversation I started in <source>') 2. Original task (from session title or first user prompt) 3. Started date + dialogue-only message count 4. The full clean transcript (no tool noise — keeps paste size sane) 5. Closing line asking the new agent to acknowledge and wait DESIGN CHOICES - Always uses the dialogue-only render so paste size stays small. 200-msg session is typically 80-200 KB — fine for any modern hosted assistant. - Wrapper language auto-detects Cyrillic in the title or first prompt and picks Russian; otherwise English. Override with --lang. The transcript itself is unchanged either way (the new agent will speak whatever language was in the conversation). - The clipboard tip prints to stderr so '| pbcopy' captures only the prompt, not the helper text. - Reuses the same session-prefix lookup as 'export', so any unique 8-char prefix works. CODE - exporter.py: new render_handoff(), detect_handoff_language(), bilingual templates, source-label maps. - cli.py: extracted shared _resolve_session_or_exit() so 'export' and 'handoff' share the prefix-matching + ambiguity error path. - 10 new tests covering: framing, dialogue-only count, language detection for both Cyrillic and ASCII sessions, explicit --lang override, source label, CLI stdout vs --output, missing-session error, and the stderr-discipline contract for the clipboard tip. DOCS README, README.ru, QUICKSTART, PROMPT all gain a handoff section. The PROMPT additionally instructs the AI assistant to plant a seed about 'handoff' near the end so users learn about it during onboarding. 95/95 tests pass, 91% coverage.
1 parent 66c9c79 commit 20a3dc7

7 files changed

Lines changed: 395 additions & 17 deletions

File tree

PROMPT.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ The full path:
3232
6. Pick an interesting session with me and have me run `claude-backup export <8-char-prefix> --output ./backups/`. By default this writes two files: `<id>.md` (clean dialogue, only my prompts and Claude's text replies) and `<id>.full.md` (everything — tool calls, tool results, AND any subagent transcripts the session spawned). Explain when to use each.
3333
7. Have me `open ./backups/<filename>.md` (macOS) or `xdg-open` (Linux) to view the result. Ask what I think.
3434
8. If I want a full backup of everything, have me run `claude-backup export-all --output ~/claude-backups`. Explain that the output is split first by source — `code/` and `cowork/` subfolders — and inside each, organised by project (Code mirrors my real working dirs, Cowork uses the friendly codename like `beautiful-charming-curie` that Cowork itself generates).
35+
9. Mention one more useful command for later: `claude-backup handoff <prefix> | pbcopy` (macOS) or `| xclip -selection clipboard` (Linux). It produces a paste-ready prompt I can drop into Claude.ai, ChatGPT, Cursor, or any other AI assistant to continue the same conversation there. Don't make me try it now unless I ask — just plant the seed so I know it exists.
3536
3637
If a command errors: help me debug, don't just dump a fix. Common issues —
3738
- "Claude data not found" → I haven't used either Claude Code or Cowork on this machine yet
@@ -65,6 +66,7 @@ Start with step 1.
6566
6. Выбери со мной одну сессию и вели мне `claude-backup export <8-символьный-префикс> --output ./backups/`. По умолчанию создаются два файла: `<id>.md` (чистый диалог — только мои промпты и текстовые ответы Claude) и `<id>.full.md` (всё: tool-вызовы, tool-результаты И transcripts subagent'ов которые сессия порождала). Объясни когда использовать каждый.
6667
7. `open ./backups/<filename>.md` (macOS) или `xdg-open` (Linux) — посмотреть результат. Спроси что я думаю.
6768
8. Если хочу выгрузить всё — `claude-backup export-all --output ~/claude-backups`. Объясни что вывод сначала разделён по источнику — подпапки `code/` и `cowork/`, — а внутри каждой организован по проекту (Code зеркалит реальные рабочие директории, Cowork использует дружелюбный кодноим типа `beautiful-charming-curie` который Cowork сам генерирует).
69+
9. Упомяни ещё одну полезную команду на будущее: `claude-backup handoff <prefix> | pbcopy` (macOS) или `| xclip -selection clipboard` (Linux). Она создаёт paste-ready промпт, который можно вставить в Claude.ai, ChatGPT, Cursor или любого другого AI-ассистента, чтобы продолжить тот же разговор там. Не заставляй пробовать сейчас если я не попрошу — просто посади семечко чтобы я знал что это есть.
6870
6971
Если команда выдаёт ошибку — помоги отладить, не вываливай готовый фикс. Частые проблемы:
7072
- "Claude data not found" → я ещё не пользовался ни Claude Code, ни Cowork на этой машине

QUICKSTART.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,25 @@ The clean version is typically **half the size** of the audit copy and is what y
133133

134134
---
135135

136-
## Step 6 — Export everything at once
136+
## Step 6 — Continue this conversation in another agent
137+
138+
Want to keep going on this session in **claude.ai web**, **ChatGPT**, **Cursor**, or another AI tool? One command makes a paste-ready prompt:
139+
140+
```bash
141+
# macOS — straight to your clipboard
142+
claude-backup handoff abc12345 | pbcopy
143+
144+
# Linux
145+
claude-backup handoff abc12345 | xclip -selection clipboard
146+
```
147+
148+
Now open the other agent, paste, and hit send. The pasted message tells the new agent it's continuing your conversation, includes the full clean transcript, and asks it to acknowledge context. After it confirms, you keep typing as if you'd never switched.
149+
150+
The wrapper text auto-detects Russian/English from the session, so you don't have to think about it. Pass `--lang en` or `--lang ru` to override, or `--output handoff.md` to save the prompt to a file instead of stdout.
151+
152+
---
153+
154+
## Step 7 — Export everything at once
137155

138156
```bash
139157
claude-backup export-all --output ./backups/ # both files per session

README.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ claude-backup export f7a07eec --output ~/claude-backups/
5353

5454
# Export everything from both sources (organised by source folder)
5555
claude-backup export-all --output ~/claude-backups/
56+
57+
# Continue a session in a DIFFERENT agent — paste-ready prompt to your clipboard
58+
claude-backup handoff f7a07eec | pbcopy # macOS
59+
claude-backup handoff f7a07eec | xclip -selection clipboard # Linux
5660
```
5761

5862
By default each export produces **two files** side-by-side:
@@ -162,6 +166,36 @@ claude-backup --cowork-home /path/to/cowork list # only
162166
claude-backup --claude-home /a --cowork-home /b list # both, custom roots
163167
```
164168

169+
### Continue a session in another agent (`handoff`)
170+
171+
Sometimes you want to keep going in a *different* AI tool — moving a Cowork conversation to claude.ai web, picking up a Code session in ChatGPT or Cursor, sending the discussion to a colleague's agent. The `handoff` command produces a single paste-ready prompt that:
172+
173+
- Tells the new agent it's continuing your conversation
174+
- Names the source (Claude Code or Claude Cowork) and the original task
175+
- Drops the full dialogue-only transcript inline (no tool noise, so it stays paste-friendly)
176+
- Asks the new agent to acknowledge context and wait for your next message
177+
178+
```bash
179+
claude-backup handoff f7a07eec # print to stdout
180+
claude-backup handoff f7a07eec | pbcopy # macOS — straight to clipboard
181+
claude-backup handoff f7a07eec | xclip -selection clipboard # Linux
182+
claude-backup handoff f7a07eec --output ./handoff.md # save to a file
183+
claude-backup handoff f7a07eec --lang en # force English wrapper
184+
claude-backup handoff f7a07eec --lang ru # force Russian wrapper
185+
```
186+
187+
The wrapper language auto-detects from the session: Cyrillic in the title or first prompt → Russian wrapper, otherwise English. The transcript itself is unchanged — the new agent will respond in whatever language the conversation was in.
188+
189+
Workflow:
190+
191+
1. Run `claude-backup handoff <id> | pbcopy`
192+
2. Open Claude.ai (or ChatGPT, Cursor chat, Perplexity, anywhere)
193+
3. Paste into a fresh conversation
194+
4. The agent reads the context, acknowledges in 1–2 sentences
195+
5. You type your next message — the conversation continues there
196+
197+
A 200-message session typically packs into 80–200 KB of text — fine for context windows of any modern hosted assistant.
198+
165199
---
166200

167201
## Output format
@@ -229,6 +263,7 @@ Claude Code generates the AI-title **once**, near the start of a session, and ne
229263
## Behaviour
230264

231265
- **Two sources, one CLI.** Both Claude Code (`~/.claude/projects/`) and Claude Cowork (`~/Library/Application Support/Claude/local-agent-mode-sessions/`) are auto-discovered. If only one source exists on a machine, the other is silently skipped.
266+
- **Portable handoff.** The `handoff` command produces a paste-ready prompt that lets you continue any session in a different AI agent (Claude.ai, ChatGPT, Cursor, etc.). The wrapper auto-detects Russian/English from the session.
232267
- **Subagents recovered.** Both Code and Cowork spawn subagent transcripts under `<session-id>/subagents/agent-*.jsonl`. The full export pulls them in as separate sections; minimal mode drops them. The frontmatter's `subagents:` count tells you how many were attached.
233268
- **Reads the real Claude Code format.** Metadata (first prompt, message count, created timestamp, AI title) is computed by streaming the `.jsonl` directly. No `sessions-index.json` is required — Claude Code doesn't actually create one.
234269
- **AI-titles surfaced.** When the recording app emits an `ai-title` event, the title shows in `list` output and becomes the document heading.
@@ -251,7 +286,7 @@ pytest -v --cov=claude_backup
251286

252287
CI runs on Python 3.9, 3.10, 3.11, and 3.12 — see [.github/workflows/test.yml](.github/workflows/test.yml).
253288

254-
**Test coverage: 91%** (85/85 tests passing) — covers the real Claude Code format, the legacy spec format, the Cowork nested hierarchy, subagent discovery and rendering, edge cases (empty/corrupt JSONL, unicode, missing roots), `--mode` selection (both / minimal / full), the FS-aware project-path decoder, and CLI integration across both sources.
289+
**Test coverage: 90%** (95/95 tests passing) — covers the real Claude Code format, the legacy spec format, the Cowork nested hierarchy, subagent discovery and rendering, edge cases (empty/corrupt JSONL, unicode, missing roots), `--mode` selection (both / minimal / full), the FS-aware project-path decoder, and CLI integration across both sources.
255290

256291
### Project layout
257292

@@ -273,7 +308,8 @@ tests/
273308
├── test_cli.py
274309
├── test_minimal.py # Dialogue-only mode + --mode CLI flag
275310
├── test_real_format.py # Nested message shape, ai-title, project-path decoding
276-
└── test_cowork.py # Cowork hierarchy + subagent rendering across sources
311+
├── test_cowork.py # Cowork hierarchy + subagent rendering across sources
312+
└── test_handoff.py # Paste-ready prompt for continuing in another agent
277313
```
278314

279315
---

README.ru.md

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ claude-backup export f7a07eec --output ~/claude-backups/
5353

5454
# Экспортировать всё из обоих источников (организовано по source-папкам)
5555
claude-backup export-all --output ~/claude-backups/
56+
57+
# Продолжить сессию в ДРУГОМ агенте — paste-ready промпт прямо в буфер
58+
claude-backup handoff f7a07eec | pbcopy # macOS
59+
claude-backup handoff f7a07eec | xclip -selection clipboard # Linux
5660
```
5761

5862
По умолчанию каждый экспорт создаёт **два файла** рядом:
@@ -162,6 +166,36 @@ claude-backup --cowork-home /path/to/cowork list # то
162166
claude-backup --claude-home /a --cowork-home /b list # оба, кастомные пути
163167
```
164168

169+
### Продолжить сессию в другом агенте (`handoff`)
170+
171+
Иногда хочется продолжить разговор в *другом* AI-инструменте — перенести Cowork-сессию в claude.ai web, подцепить Code-сессию в ChatGPT или Cursor, отправить разговор агенту коллеги. Команда `handoff` создаёт один paste-ready промпт, который:
172+
173+
- Говорит новому агенту что он продолжает разговор
174+
- Называет источник (Claude Code или Claude Cowork) и исходную задачу
175+
- Подсовывает полный dialogue-only транскрипт (без tool-шума, чтобы paste не разросся)
176+
- Просит нового агента подтвердить контекст и подождать следующего сообщения
177+
178+
```bash
179+
claude-backup handoff f7a07eec # печать в stdout
180+
claude-backup handoff f7a07eec | pbcopy # macOS — сразу в буфер
181+
claude-backup handoff f7a07eec | xclip -selection clipboard # Linux
182+
claude-backup handoff f7a07eec --output ./handoff.md # сохранить в файл
183+
claude-backup handoff f7a07eec --lang en # форсить English-обёртку
184+
claude-backup handoff f7a07eec --lang ru # форсить Russian-обёртку
185+
```
186+
187+
Язык обёртки авто-определяется по сессии: если в title или первом промпте есть кириллица → русская обёртка, иначе английская. Сам транскрипт не меняется — новый агент ответит на том же языке что был в разговоре.
188+
189+
Workflow:
190+
191+
1. Запустить `claude-backup handoff <id> | pbcopy`
192+
2. Открыть Claude.ai (или ChatGPT, Cursor чат, Perplexity, что угодно)
193+
3. Вставить в новый разговор
194+
4. Агент читает контекст, подтверждает в 1–2 предложениях
195+
5. Печатаешь следующее сообщение — разговор продолжается там
196+
197+
Сессия из 200 сообщений обычно укладывается в 80–200 КБ текста — нормально для context window любого современного хостед-ассистента.
198+
165199
---
166200

167201
## Формат вывода
@@ -226,6 +260,7 @@ Claude Code генерирует AI-title **один раз**, в начале
226260
## Поведение
227261

228262
- **Два источника, один CLI.** И Claude Code (`~/.claude/projects/`), и Claude Cowork (`~/Library/Application Support/Claude/local-agent-mode-sessions/`) обнаруживаются автоматически. Если на машине только один источник — другой молча пропускается.
263+
- **Портативный handoff.** Команда `handoff` создаёт paste-ready промпт, чтобы продолжить любую сессию в другом AI-агенте (Claude.ai, ChatGPT, Cursor и т.д.). Обёртка авто-выбирает русский или английский по сессии.
229264
- **Subagents восстанавливаются.** И Code, и Cowork порождают transcripts subagent'ов в `<session-id>/subagents/agent-*.jsonl`. Полный экспорт подтягивает их как отдельные секции; minimal-режим их роняет. Поле `subagents:` в frontmatter показывает сколько было приклеено.
230265
- **Читает реальный формат Claude Code.** Метаданные (первый промпт, число сообщений, дата создания, AI-title) считаются прямо из `.jsonl` потоковым чтением. Никакого `sessions-index.json` не требуется — Claude Code его на самом деле не создаёт.
231266
- **AI-titles на видном месте.** Если приложение записало событие `ai-title`, заголовок отображается в `list` и используется как H1 в Markdown-документе.
@@ -248,7 +283,7 @@ pytest -v --cov=claude_backup
248283

249284
CI запускается на Python 3.9, 3.10, 3.11 и 3.12 — см. [.github/workflows/test.yml](.github/workflows/test.yml).
250285

251-
**Покрытие тестами: 91%** (85/85 тестов проходят) — реальный формат Claude Code, legacy-формат из спеки, вложенная иерархия Cowork, обнаружение и рендеринг subagent'ов, edge-кейсы (пустой/битый JSONL, unicode, отсутствующие root'ы), выбор `--mode` (both / minimal / full), FS-aware декодинг путей, и интеграционные тесты CLI по обоим источникам.
286+
**Покрытие тестами: 90%** (95/95 тестов проходят) — реальный формат Claude Code, legacy-формат из спеки, вложенная иерархия Cowork, обнаружение и рендеринг subagent'ов, edge-кейсы (пустой/битый JSONL, unicode, отсутствующие root'ы), выбор `--mode` (both / minimal / full), FS-aware декодинг путей, и интеграционные тесты CLI по обоим источникам.
252287

253288
### Структура проекта
254289

@@ -270,7 +305,8 @@ tests/
270305
├── test_cli.py
271306
├── test_minimal.py # Dialogue-only режим + CLI флаг --mode
272307
├── test_real_format.py # Вложенный формат message, ai-title, декодинг путей
273-
└── test_cowork.py # Cowork-иерархия + рендеринг subagent'ов в обоих источниках
308+
├── test_cowork.py # Cowork-иерархия + рендеринг subagent'ов в обоих источниках
309+
└── test_handoff.py # Paste-ready промпт для продолжения в другом агенте
274310
```
275311

276312
---

0 commit comments

Comments
 (0)