Past a context threshold, records a hand-off and continues the work from the notes: in a new desktop-app session by default, or in this one after a compaction…

Small mods for Claude Code.
A mod is a plugin that changes how Claude Code looks and behaves. This repository holds three, and works as a plugin marketplace, so you can install any of them by name.
| Mod | What it does | Where it works | | :- | :- | :- | | context-meter | Shows the git branch, how full the context window is, how much the last turn added, and how much of your plan limits you have used, in a band above the prompt | Terminal and the Desktop app's Code tab | | auto-pin | Pins a new session in the sidebar as soon as it starts | The Desktop app's Code tab | | context-handoff | Once the context window is 40% full, has Claude write hand-off notes and continues from them in a new session (or after resetting the context) | Terminal and the Desktop app's Code tab |
claude --version./status and read the Claude Code row.A mod is code that runs with your permissions: it can read and write your files, start processes, and make network requests. Read the source before you install, or list what each mod does.
Add this repository as a marketplace, then install the mods you want:
claude plugin marketplace add ulttla/claude-mod-repo
claude plugin install context-meter@claude-mod-repo
claude plugin install auto-pin@claude-mod-repo
claude plugin install context-handoff@claude-mod-repo
In a Claude Code session the same commands are /plugin marketplace add ulttla/claude-mod-repo and /plugin install context-meter@claude-mod-repo.
A mod loads the next time you start a session. In a session that is already open, run /reload-plugins.
Clone the repository and load a mod's folder for one terminal session:
git clone https://github.com/ulttla/claude-mod-repo.git
claude --plugin-dir ./claude-mod-repo/context-meter
With the repository cloned, this lists the events a mod handles and what it asks Claude Code to do, without running it:
claude plugin validate ./claude-mod-repo/context-meter
Draws one line above the prompt:
main Ctx 12% (119k/1M) Last +119k 5H 1% ↻17:30 1W 25% ↻Wed 11:00
| Segment | Meaning | | :- | :- | | main | The current git branch. Left out when the session's folder is not in a git repository. On a detached HEAD, the short commit hash | | Ctx 12% (119k/1M) | Context window: percent full, tokens used, window size | | Last +119k | Tokens the last finished turn added. A negative number means the turn compacted the conversation | | 5H 1% ↻17:30 | Five-hour plan limit: percent used, and when it resets | | 1W 25% ↻Wed 11:00 | Weekly plan limit: percent used, and when it resets |
/context-meter prints the same line as text, for places that don't draw the band, such as the VS Code extension.Each segment can be turned on or off.
| Option | Default | What it shows | | :- | :- | :- | | showBranch | on | The current git branch | | showDirty | off | A * after the branch name when the working tree has uncommitted changes, as in main*. Runs git status on each turn | | showModel | off | The session's model | | showEffort | off | The effort level the session's model requests ask for, as in Effort xhigh. Shown from the first response on, and left out on a model that takes no effort | | showContext | on | Ctx, the context window | | showLastTurn | on | Last, what the last turn added | | showFiveHour | on | 5H, the five-hour plan limit | | showWeekly | on | 1W, the weekly plan limit | | showOtherLimits | on | Any other limit your account reports, such as a gateway's spend limit (Spend) | | showResetTimes | on | When each limit resets | | showCost | off | What the session has cost in US dollars, as in $1.24. On a subscription plan this is an estimate at API prices, not a charge |
To change them in a terminal session, run /plugin configure context-meter@claude-mod-repo. From your shell, pass each one when you install:
claude plugin install context-meter@claude-mod-repo --config showModel=true --config showCost=true
A change takes effect in the next session, or after /reload-plugins.
When you start a new session in the Desktop app's Code tab, the mod pins it in the sidebar. You unpin it yourself when the work is done.
/auto-pin pins the current session on request, says why when it can't, and lists the session's earlier tries.~/.claude/settings.json with "permissions": { "allow": ["mcp__ccd_sidebar__set_pinned"] }. Claude's own pin and unpin calls then run without a check too.A long session gets worse as its context fills up. This mod hands the work over to a fresh context before that happens, without you opening a new session.
After each turn it reads how full the context window is. Past the threshold (40% by default), it:
session-close skill, Claude is told to run it; otherwise Claude follows the session-close procedure in the project's CLAUDE.md, or updates PROGRESS.md, or writes HANDOFF.md at the project root.reset set to session), the hand-off waits for your next message. The Desktop app opens a session only on a turn you started, which a prompt the mod submits is not, so the mod attaches the hand-off instructions to that message instead (Claude reads them beside it; you don't see them). Claude does not work on the message here: it records the notes with your message as the next step, then opens a new Desktop app session in the same folder, whose first prompt has Claude read the notes and take up your message. It starts with this session's model, effort and permission mode. When the turn ends, the mod moves the new session to top level (so it lives on by itself, and this session is not woken each time its turns end) and unpins this session (oldSession). Where no session can be opened (outside the Desktop app, or when the app refuses), the mod compacts the conversation here instead, as below.reset set to compact, it submits the hand-off prompt at once, and when that turn ends, it compacts the conversation down to where the notes are and the next step (the same as /compact with instructions), so the process, model and settings stay as they were. In the Desktop app the session has no compaction call of its own, so the mod runs /compact with those instructions instead, as if you had typed it. With reset set to clear, it instead asks the Desktop app to clear the conversation (the same as /clear): the session keeps its row in the sidebar, the old conversation stays under Resume previous session, but the app starts a new Claude Code process only at your next message. Either way it then submits a prompt that has Claude read the notes and continue from the recorded next step.Each step shows a toast. With compact or clear, a message you had already queued runs first. If you interrupt the hand-off turn, or the reset fails, the mod gives up, says why, and tries again once the context has grown by another 5 points.
/handoff-now hands off right away, at any context size. It is a skill of the mod, so it runs in the turn you type it in, and with a new session that turn opens it. /handoff-status shows where the hand-off stands and what the mod did last.[context-handoff], and each step leaves a dim context-handoff: line there./compact (the Desktop app, or compaction set to command): the /compact line shows in the transcript, the resume follows once its compaction has run, and if nothing has been compacted within five minutes the mod gives up.pauseRemoteControl). Outside the Desktop app there is no app to clear, so the mod gives up after recording the notes.| Option | Default | What it does | | :- | :- | :- | | enabled | on | Hand off on its own past the threshold. Off, only /handoff-now hands off | | threshold | 40 | How full the context window is, in percent, before the hand-off starts | | retriggerStep | 5 | After an interrupted or failed hand-off, try again once the context has grown this many points | | reset | session | Where the work continues: session (a new Desktop app session, opened with your next message, or a compaction here where none can be opened), compact (in place, process and settings kept, no input needed) or clear (the Desktop app's clear: a fresh conversation, continued only after your next message) | | oldSession | unpin | With a new session: unpin the session that handed off, or keep it as it is | | compaction | auto | How the compaction is made: auto (the engine's compaction call, or /compact where the session has none, as in the Desktop app), call (the call alone) or command (/compact alone, queued as if typed) | | closeCommand | session-close | The project skill Claude is told to run to record the hand-off, when the project has it | | closePrompt | empty | Replaces the built-in hand-off prompt and the close skill. {percent} and {threshold} are filled in | | resumePrompt | empty | Replaces the built-in prompt the work continues from: the new session's first prompt, or the one submitted after the reset | | pauseRemoteControl | on | With the clear: turn Remote Control off for it, and on again after the resume. Off, such a session is not cleared |
To change them in a terminal session, run /plugin configure context-handoff@claude-mod-repo, or pass them when you install:
claude plugin install context-handoff@claude-mod-repo --config threshold=50
claude plugin uninstall context-meter@claude-mod-repo
claude plugin uninstall auto-pin@claude-mod-repo
claude plugin uninstall context-handoff@claude-mod-repo
MIT. Shared as is, without support.
mod는 Claude Code의 모양과 동작을 바꾸는 플러그인입니다. 이 리포에는 mod 세 개가 들어 있고, 리포 자체가 플러그인 마켓플레이스 역할을 하므로 이름으로 골라 설치할 수 있습니다.
| Mod | 하는 일 | 동작하는 곳 | | :- | :- | :- | | context-meter | git 브랜치, 컨텍스트 창이 얼마나 찼는지, 직전 턴이 얼마나 늘렸는지, 플랜 한도를 얼마나 썼는지를 입력창 위 한 줄로 표시 | 터미널, 데스크톱 앱 Code 탭 | | auto-pin | 새 세션이 시작되면 사이드바에 바로 고정 | 데스크톱 앱 Code 탭 | | context-handoff | 컨텍스트 창이 40% 차면 Claude가 인계 기록을 쓰게 하고, 새 세션(또는 컨텍스트 초기화 뒤)에서 기록을 읽어 이어감 | 터미널, 데스크톱 앱 Code 탭 |
claude --version으로 확인합니다./status를 입력하고 Claude Code 행을 봅니다.mod는 사용자 권한으로 실행되는 코드입니다. 파일을 읽고 쓰고, 프로세스를 실행하고, 네트워크 요청을 보낼 수 있습니다. 설치하기 전에 소스를 읽거나 mod가 하는 일을 먼저 확인하세요.
이 리포를 마켓플레이스로 추가한 뒤 원하는 mod를 설치합니다.
claude plugin marketplace add ulttla/claude-mod-repo
claude plugin install context-meter@claude-mod-repo
claude plugin install auto-pin@claude-mod-repo
claude plugin install context-handoff@claude-mod-repo
Claude Code 세션 안에서는 같은 명령을 /plugin marketplace add ulttla/claude-mod-repo, /plugin install context-meter@claude-mod-repo로 입력합니다.
mod는 다음에 세션을 시작할 때 로드됩니다. 이미 열려 있는 세션에서는 /reload-plugins를 실행합니다.
리포를 클론한 뒤 터미널 세션 하나에만 mod 폴더를 로드합니다.
git clone https://github.com/ulttla/claude-mod-repo.git
claude --plugin-dir ./claude-mod-repo/context-meter
리포를 클론한 상태에서 아래 명령을 실행하면, mod를 실행하지 않고 어떤 이벤트를 처리하고 Claude Code에 무엇을 요청하는지 나열합니다.
claude plugin validate ./claude-mod-repo/context-meter
입력창 위에 한 줄을 그립니다.
main Ctx 12% (119k/1M) Last +119k 5H 1% ↻17:30 1W 25% ↻Wed 11:00
| 항목 | 의미 | | :- | :- | | main | 현재 git 브랜치. 세션 폴더가 git 리포가 아니면 생략됩니다. detached HEAD에서는 짧은 커밋 해시 | | Ctx 12% (119k/1M) | 컨텍스트 창: 찬 비율, 사용한 토큰, 창 크기 | | Last +119k | 직전에 끝난 턴이 늘린 토큰. 음수면 그 턴에서 대화가 압축된 것 | | 5H 1% ↻17:30 | 5시간 플랜 한도: 사용률과 초기화 시각 | | 1W 25% ↻Wed 11:00 | 주간 플랜 한도: 사용률과 초기화 시각 |
/context-meter는 같은 내용을 텍스트로 출력합니다. VS Code 확장처럼 밴드를 그리지 않는 곳에서 씁니다.항목마다 켜고 끌 수 있습니다.
| 옵션 | 기본값 | 표시 내용 | | :- | :- | :- | | showBranch | 켜짐 | 현재 git 브랜치 | | showDirty | 꺼짐 | 커밋하지 않은 변경이 있으면 브랜치 이름 뒤에 * 표시 (예: main*). 턴마다 git status를 실행합니다 | | showModel | 꺼짐 | 세션의 모델 | | showEffort | 꺼짐 | 세션의 모델 요청에 적용된 effort 수준 (예: Effort xhigh). 첫 응답부터 표시되고, effort를 받지 않는 모델에서는 생략됩니다 | | showContext | 켜짐 | Ctx, 컨텍스트 창 | | showLastTurn | 켜짐 | Last, 직전 턴이 늘린 양 | | showFiveHour | 켜짐 | 5H, 5시간 플랜 한도 | | showWeekly | 켜짐 | 1W, 주간 플랜 한도 | | showOtherLimits | 켜짐 | 계정이 보고하는 그 밖의 한도. 예: 게이트웨이의 지출 한도(Spend) | | showResetTimes | 켜짐 | 각 한도의 초기화 시각 | | showCost | 꺼짐 | 세션 비용(미국 달러, 예: $1.24). 구독 플랜에서는 실제 청구액이 아니라 API 가격 기준 추정치입니다 |
터미널 세션에서는 /plugin configure context-meter@claude-mod-repo로 바꿉니다. 셸에서는 설치할 때 하나씩 넘깁니다.
claude plugin install context-meter@claude-mod-repo --config showModel=true --config showCost=true
변경은 다음 세션부터, 또는 /reload-plugins 후에 적용됩니다.
데스크톱 앱 Code 탭에서 새 세션을 시작하면 사이드바에 고정합니다. 작업이 끝나면 직접 고정을 해제하면 됩니다.
/auto-pin은 현재 세션을 직접 고정하고, 고정하지 못하면 이유를 알려 주며, 이 세션의 이전 시도 기록을 보여 줍니다.~/.claude/settings.json에 "permissions": { "allow": ["mcp__ccd_sidebar__set_pinned"] }를 넣어 고정을 허용하세요. 그러면 Claude가 직접 하는 고정·해제 호출도 확인 없이 실행됩니다.긴 세션은 컨텍스트가 찰수록 품질이 떨어집니다. 이 mod는 그 전에 작업을 새 컨텍스트로 넘깁니다. 새 세션을 직접 열 필요가 없습니다.
턴이 끝날 때마다 컨텍스트 창이 얼마나 찼는지 읽고, 임계값(기본 40%)을 넘으면 다음을 차례로 합니다.
session-close 스킬이 있으면 그 스킬을 실행하라고 지시하고, 없으면 프로젝트 CLAUDE.md의 세션 종료 절차를 따르거나, PROGRESS.md를 갱신하거나, 프로젝트 루트에 HANDOFF.md를 씁니다.reset이 session)은 사용자가 다음 메시지를 보낼 때 인계합니다. 데스크톱 앱은 사용자가 시작한 턴에서만 새 세션을 열어 주는데, mod가 제출한 프롬프트의 턴은 여기에 해당하지 않습니다. 그래서 mod는 인계 지시를 그 메시지에 붙여 보냅니다(Claude만 읽고 화면에는 보이지 않음). Claude는 그 메시지를 여기서 처리하지 않습니다. 메시지를 다음 단계로 삼아 기록을 쓰고, 같은 폴더로 데스크톱 앱 새 세션을 엽니다. 새 세션의 첫 프롬프트는 기록을 읽고 그 메시지부터 처리하라는 것이며, 이 세션의 모델·effort·권한 모드로 시작합니다. 턴이 끝나면 mod가 새 세션을 최상위로 옮기고(독립적으로 남고, 새 세션의 턴이 끝날 때마다 이 세션이 깨어나지 않음) 이 세션의 고정을 풉니다(oldSession). 새 세션을 열 수 없으면(데스크톱 앱 밖이거나 앱이 거부하면) 아래처럼 여기서 압축합니다.reset이 compact면 인계 프롬프트를 바로 제출하고, 그 턴이 끝날 때 대화를 "기록 위치와 다음 단계"만 남기고 압축합니다(/compact에 지시문을 붙인 것과 같음). 프로세스·모델·설정이 그대로 유지됩니다. 데스크톱 앱의 세션에는 압축 호출이 없으므로, 거기서는 직접 입력한 것처럼 같은 지시문으로 /compact를 실행합니다. reset을 clear로 두면 대신 데스크톱 앱에 대화를 비워 달라고 요청합니다(/clear와 같음). 세션은 사이드바의 같은 행에 남고 이전 대화는 Resume previous session으로 되돌릴 수 있지만, 앱은 다음 메시지를 보낼 때에야 새 Claude Code 프로세스를 띄웁니다. 어느 쪽이든 그 뒤 Claude가 기록을 읽고 기록된 다음 시작점부터 이어가도록 프롬프트를 제출합니다.단계마다 토스트로 알립니다. compact·clear일 때 이미 대기 중이던 메시지가 있으면 그것이 먼저 실행됩니다. 인계 턴을 중단하거나 초기화에 실패하면 포기하고 이유를 알린 뒤, 컨텍스트가 5포인트 더 차면 다시 시도합니다.
/handoff-now는 컨텍스트 크기와 상관없이 바로 인계합니다. mod에 딸린 스킬이라 입력한 그 턴에서 실행되므로, 새 세션 모드에서는 그 턴이 새 세션을 엽니다. /handoff-status는 인계가 어느 단계인지와 마지막으로 한 일을 보여 줍니다.[context-handoff] 표시와 함께 대화에 보이고, 단계마다 흐릿한 context-handoff: 줄이 대화에 남습니다./compact로 압축할 때(데스크톱 앱, 또는 compaction을 command로 둔 경우): /compact 줄이 대화에 보이고, 그 압축이 끝나면 재개합니다. 5분 안에 압축되지 않으면 포기합니다.clear일 때: 인계 턴이 시작될 때 앱에 요청하고 턴이 끝날 때 비워집니다. 8초 안에 비워지지 않으면 포기합니다. 대기 중이던 메시지가 인계 턴 뒤에 실행되면 기록을 다시 씁니다. 재개 지시는 mod 저장소에 적어 두므로 앱이 다음에 띄우는 프로세스가 기록을 읽고 이어갑니다. 앱은 비운 뒤 아무리 시간이 지나도 다음 메시지를 보낼 때에야 그 프로세스를 띄우며, 그 메시지가 먼저 실행된 뒤 재개합니다. 그때까지 대화는 비어 있습니다. 다른 기기에서 시작한 세션은 비울 수 없으므로 비우는 동안 Remote Control을 끄고 재개 후 다시 켭니다(pauseRemoteControl). 데스크톱 앱 밖에는 비워 줄 앱이 없으므로 기록만 쓴 뒤 포기합니다.| 옵션 | 기본값 | 하는 일 | | :- | :- | :- | | enabled | 켜짐 | 임계값을 넘으면 자동으로 인계. 끄면 /handoff-now로만 인계 | | threshold | 40 | 인계를 시작하는 컨텍스트 창 사용률(%) | | retriggerStep | 5 | 중단되거나 실패한 인계를 컨텍스트가 몇 포인트 더 찼을 때 다시 시도할지 | | reset | session | 작업을 이어갈 곳: session(다음 메시지와 함께 여는 데스크톱 앱 새 세션, 열 수 없으면 여기서 압축), compact(제자리 압축, 프로세스·설정 유지, 입력 불필요) 또는 clear(데스크톱 앱의 비우기: 새 대화, 다음 메시지를 보내야 이어감) | | oldSession | unpin | 새 세션일 때 인계한 세션의 고정을 풀지(unpin), 그대로 둘지(keep) | | compaction | auto | 압축 방법: auto(엔진의 압축 호출, 데스크톱 앱처럼 호출이 없는 세션에서는 /compact), call(호출만), command(/compact만, 입력한 것처럼 큐에 넣음) | | closeCommand | session-close | 프로젝트에 있을 때 인계 기록용으로 실행하라고 지시할 스킬 | | closePrompt | 비어 있음 | 내장 인계 프롬프트와 스킬 지시를 대체. {percent}, {threshold}가 채워짐 | | resumePrompt | 비어 있음 | 작업을 이어가는 내장 프롬프트를 대체: 새 세션의 첫 프롬프트, 또는 초기화 뒤 제출하는 프롬프트 | | pauseRemoteControl | 켜짐 | clear일 때 비우는 동안 Remote Control을 끄고 재개 후 다시 켬. 끄면 그런 세션은 비우지 않음 |
터미널 세션에서는 /plugin configure context-handoff@claude-mod-repo로 바꾸거나, 설치할 때 넘깁니다.
claude plugin install context-handoff@claude-mod-repo --config threshold=50
claude plugin uninstall context-meter@claude-mod-repo
claude plugin uninstall auto-pin@claude-mod-repo
claude plugin uninstall context-handoff@claude-mod-repo
MIT. 지원 없이 있는 그대로 공유합니다.
hooks/register.js 694 lines1// The mod's name, as toasts, log lines and the hand-off prompts carry it
2const NAME = 'context-handoff'
3// A tag every prompt this mod submits carries, so its own turn can be told apart
4const MARK = '[context-handoff]'
5// The store key that survives the desktop app's clear, which ends the process
6const RESUME_KEY = 'pendingResume'
7// How long the app gets to clear the conversation once the hand-off turn has ended
8const CLEAR_WAIT_MS = 8000
9// The app's tool that opens the session the work continues in
10const START_TOOL = 'mcp__ccd_session__start_session'
11// This plugin's /handoff-now skill, by its name bare or under the plugin's
12const HANDOFF_SKILL = /(^|:)handoff-now$/
13// Where a prompt the user sent comes from: typed, over Remote Control, or the desktop app's own
14// composer, which drives the engine as an SDK host. The app opens a session only on such a turn
15const USER_ORIGINS = ['composer', 'bridge', 'sdk']
16// When the compaction is tried after the hand-off turn: it is refused while a turn still runs
17const COMPACT_TRIES_MS = [300, 1000, 2000, 4000, 8000]
18// How long the /compact command gets to compact the conversation where it stands in for the call
19const COMPACT_COMMAND_WAIT_MS = 5 * 60 * 1000
20// How long after the compaction the resume prompt is submitted
21const RESUME_AFTER_COMPACT_MS = 1000
22// What the summarizer is told when the conversation is compacted after a hand-off
23const COMPACT_INSTRUCTIONS =
24 'A hand-off for a fresh start was just recorded in the project notes. Keep only: where the notes are (file and section), ' +
25 'the exact next step, and any question still waiting for the user. Leave out everything else; it is in the notes.'
26
27// Where the hand-off stands:
28// idle nothing in progress
29// armed (session) past the threshold; the user's next message runs the hand-off
30// closing the hand-off is asked for; waiting for its turn to run and finish
31// handing (session) the hand-off turn has ended; finding the session it opened
32// clearing (clear) the app was asked to clear; waiting for the conversation to end with it
33// compacting (compact) the hand-off turn has ended; compacting the conversation
34// resuming the conversation was reset; waiting to submit the resume prompt
35let phase = 'idle'
36// The hand-off prompt as submitted, and the id of the turn running it
37let closeText = null
38let closeTurnId = null
39// What asks for the hand-off turn: a prompt this mod submits (`prompt`), found by its tag, or
40// the turn the user starts (`user`: their next message, or /handoff-now), the next to start
41let closeBy = null
42// The main loop's turn running now, for /handoff-now expanded after its turn started
43let currentTurnId = null
44// (session) The sessions this one had started before the hand-off, to tell the new one apart
45let linkedBefore = null
46// The context percent at which the last hand-off began; the next waits for `step` more
47let triggeredAt = null
48// The fallback that submits the resume prompt when no SessionStart follows the clear
49let resumeTimer = null
50// Gives up when the app has not cleared the conversation soon after the hand-off turn ended
51let clearWatchdog = null
52// The compaction attempt waiting to run
53let compactTimer = null
54// How the conversation is being compacted: the engine's call, or the /compact command where
55// the session has no such call (a headless one, as the desktop app runs)
56let compactVia = null
57// Gives up when the /compact command has not compacted the conversation in time
58let compactWatchdog = null
59// True while Remote Control is turned off for the clear, to be turned on again after the resume
60let remoteControlPaused = false
61// The last thing that happened, for /handoff-status
62let lastOutcome = 'nothing yet'
63
64// A number option, or its default when unset or out of range
65function numberOf(value, fallback, min, max) {
66 const n = typeof value === 'string' ? Number(value) : value
67 return typeof n === 'number' && Number.isFinite(n) && n >= min && n <= max ? n : fallback
68}
69
70// The settings, from the options plugin.json declares
71function settingsOf(options) {
72 return {
73 enabled: options.enabled !== false,
74 threshold: numberOf(options.threshold, 40, 1, 100),
75 step: numberOf(options.retriggerStep, 5, 1, 100),
76 reset: options.reset === 'clear' || options.reset === 'compact' ? options.reset : 'session',
77 unpinOld: options.oldSession !== 'keep',
78 compaction: options.compaction === 'call' || options.compaction === 'command' ? options.compaction : 'auto',
79 closeCommand: String(options.closeCommand ?? 'session-close').trim().replace(/^\//, ''),
80 closePrompt: String(options.closePrompt ?? '').trim(),
81 resumePrompt: String(options.resumePrompt ?? '').trim(),
82 pauseRemoteControl: options.pauseRemoteControl !== false,
83 }
84}
85
86function fillIn(text, percent, cfg) {
87 return text
88 .replaceAll('{percent}', String(Math.round(percent)))
89 .replaceAll('{threshold}', String(cfg.threshold))
90}
91
92// The prompt that records the hand-off: the project's own close skill when it has one,
93// a custom prompt when configured, or the built-in instructions. It opens with why the
94// hand-off is made, `why` being:
95// threshold the threshold passed (a prompt of its own)
96// asked /handoff-now asked for it, whatever the context holds
97// carry the threshold passed, and the user's message it rides on goes to the new session
98function closePromptFor(cfg, percent, hasClose, why = 'threshold') {
99 const fill = `The context window is ${Math.round(percent)}% full`
100 const carry = why === 'carry'
101 const level =
102 why === 'asked'
103 ? `${fill}; a hand-off was asked for with /handoff-now.`
104 : carry
105 ? `${fill}, past the ${cfg.threshold}% hand-off threshold, so the user's message above is handed to a fresh session ` +
106 'instead of being worked on here. Do not act on it.'
107 : `${fill}, past the ${cfg.threshold}% hand-off threshold.`
108 const pending = carry
109 ? "In the notes, make the user's message above, quoted in full, the first item of the exact next step. " +
110 'If the turn before it stopped to ask the user something, put that question in the notes too.'
111 : 'If the previous turn stopped to ask the user something, put that question in the notes instead of answering it.'
112 // With a new session the turn ends by opening it; otherwise by stopping for the reset
113 const then =
114 cfg.reset === 'session'
115 ? openSessionStep(cfg, carry)
116 : 'When the notes are written, stop: the context is then reset automatically and the work continues from the notes.'
117 if (cfg.closePrompt) {
118 const custom = `${MARK} ${fillIn(cfg.closePrompt, percent, cfg)}`
119 if (carry) return `${custom} ${level} ${pending} ${then}`
120 return cfg.reset === 'session' ? `${custom} ${then}` : custom
121 }
122 // A prompt may not begin with a slash, so the skill is named for the model to invoke
123 if (hasClose) {
124 return (
125 `${MARK} ${level} Run this project's /${cfg.closeCommand} skill now (invoke it with the Skill tool) to record the hand-off, ` +
126 `and make the next starting point exact. ${pending} ${then}`
127 )
128 }
129 return (
130 `${MARK} ${level} Do not start new work. Record a hand-off for a fresh start: ` +
131 "if this project's CLAUDE.md defines a session-close or progress-logging procedure, follow it; " +
132 'otherwise update PROGRESS.md if the project has one, or else write HANDOFF.md at the project root. ' +
133 'Cover what was done this session, the current state, measured facts worth not measuring again, open questions, ' +
134 `and the exact next step. ${pending} ${then}`
135 )
136}
137
138// (session) The last step of the hand-off turn: open the session that continues the work, with
139// the resume as its brief, and the user's message after it when the hand-off carries one. The app
140// opens one only on a turn the user started (their message, or /handoff-now they typed); when it
141// refuses, the turn just stops and the mod compacts this conversation instead.
142function openSessionStep(cfg, carry = false) {
143 const message = carry
144 ? ", then a blank line, the line \"The user's latest message, sent to the old session and not answered there:\", " +
145 "and the user's message above, word for word"
146 : ''
147 return (
148 `When the notes are written, open the session that continues the work: call ${START_TOOL} once ` +
149 '(load it with ToolSearch first if it is deferred) with initiation "user_asked", context "fresh", use_worktree false, ' +
150 'a title naming the work (under 60 characters), a background of at least 80 characters ' +
151 '(the goal, the decisions so far, and which file holds the notes), ' +
152 `and as prompt the text inside <brief>, word for word${message}: <brief>${resumePromptFor(cfg, true)}</brief> ` +
153 'Then stop with one line telling the user the work continues in that session. ' +
154 'If the call is refused, do not retry it or propose a session instead; just stop, and the context is compacted here.'
155 )
156}
157
158// Where the notes are read from and how the work picks up from them
159const READ_NOTES =
160 "Read this project's hand-off notes: the progress file CLAUDE.md names, else PROGRESS.md, else HANDOFF.md at the project root. " +
161 'Say in one line what you are picking up, then continue from the recorded next step without redoing work the notes mark as done. ' +
162 'If the notes hold a question for the user, ask it and wait.'
163
164// The prompt that continues the work: as the brief of the session that takes it over, or after
165// the reset in this conversation (a fallback of the new session included)
166function resumePromptFor(cfg, brief = false) {
167 if (brief) {
168 return cfg.resumePrompt || `This session takes over work from another session whose context filled up. ${READ_NOTES}`
169 }
170 if (cfg.resumePrompt) return `${MARK} ${cfg.resumePrompt}`
171 return `${MARK} The context was reset after a hand-off. ${READ_NOTES}`
172}
173
174function messageOf(error) {
175 return error instanceof Error ? error.message : String(error)
176}
177
178// The text blocks of an MCP result, joined
179function textOf(result) {
180 return (result.content ?? [])
181 .map((block) => (block.type === 'text' ? block.text : ''))
182 .join(' ')
183 .trim()
184}
185
186// Whether the engine answered that this session has no compaction call: a headless (SDK)
187// session, as the desktop app runs, where a compaction runs as a /compact prompt
188function hasNoCompactCall(message) {
189 return /headless|SDK|\/compact prompt/i.test(message)
190}
191
192// The sizes a compaction reports, for the transcript line
193function sizesOf(result) {
194 return typeof result?.tokensBefore === 'number' && typeof result?.tokensAfter === 'number'
195 ? ` (${result.tokensBefore} to ${result.tokensAfter} tokens)`
196 : ''
197}
198
199// Keep what happened: a dim line in the transcript, and the answer of /handoff-status
200function note($, text) {
201 lastOutcome = text
202 $.ui.log(`${NAME}: ${text}`)
203}
204
205// How full the context window is, in percent; null before the first reading
206async function readPercent($) {
207 try {
208 const { context } = await $.session.usage()
209 if (typeof context.percent === 'number') return context.percent
210 if (typeof context.tokens === 'number' && context.window > 0) return (context.tokens / context.window) * 100
211 } catch {
212 // Keep going without a reading
213 }
214 return null
215}
216
217// Whether the project offers the close command: listed as a command, or a skill folder of the project
218async function hasCommand($, name) {
219 if (!name) return false
220 try {
221 if ((await $.command.list()).some((command) => command.name === name)) return true
222 } catch {
223 // Not listable here; look at the folder
224 }
225 try {
226 const root = await $.session.root()
227 return await $.fs.exists(`${root}/.claude/skills/${name}/SKILL.md`)
228 } catch {
229 return false
230 }
231}
232
233// One call on a desktop app server, by default the session one. Resolves to null when it
234// succeeded, else to why not.
235async function callApp($, tool, args, server = 'ccd_session_mgmt') {
236 try {
237 const result = await $.mcp.call(server, tool, args)
238 return result.isError ? textOf(result) || 'no reason given' : null
239 } catch (error) {
240 return messageOf(error)
241 }
242}
243
244// The desktop app's id of this session, which outlives the process; null outside the app
245async function appSessionId($) {
246 try {
247 const result = await $.mcp.call('ccd_session_mgmt', 'get_session', { session_id: 'self' })
248 if (result.isError) return null
249 const id = JSON.parse(textOf(result)).sessionId
250 return typeof id === 'string' ? id : null
251 } catch {
252 return null
253 }
254}
255
256// The ids of the sessions this session started, as the app lists them; [] when it cannot say
257async function linkedSessions($) {
258 try {
259 const result = await $.mcp.call('ccd_session_mgmt', 'list_sessions', { linked: true, limit: 50 })
260 if (result.isError) return []
261 const rows = JSON.parse(textOf(result))
262 return Array.isArray(rows) ? rows.filter((row) => row && typeof row.sessionId === 'string') : []
263 } catch {
264 return []
265 }
266}
267
268// The session the hand-off turn opened: one this session started that was not there before.
269// The list puts the most recent first.
270async function sessionOpened($) {
271 const self = await appSessionId($)
272 const rows = await linkedSessions($)
273 return (
274 rows.find(
275 (row) => !(linkedBefore ?? []).includes(row.sessionId) && (!self || !row.startedBy || row.startedBy === self),
276 ) ?? null
277 )
278}
279
280// Turn Remote Control on again after it was turned off for the clear
281async function restoreRemoteControl($) {
282 if (!remoteControlPaused) return
283 remoteControlPaused = false
284 const failed = await callApp($, 'set_remote_control', { session_id: 'self', enabled: true })
285 note($, failed ? `Remote Control could not be turned on again: ${failed}` : 'Remote Control turned on again')
286}
287
288function cancelTimers() {
289 if (resumeTimer) resumeTimer.cancel()
290 if (clearWatchdog) clearWatchdog.cancel()
291 if (compactTimer) compactTimer.cancel()
292 if (compactWatchdog) compactWatchdog.cancel()
293 resumeTimer = clearWatchdog = compactTimer = compactWatchdog = null
294}
295
296function forgetPendingResume($) {
297 $.store.delete(RESUME_KEY).catch(() => {})
298}
299
300// Give up the hand-off in progress and say why; the next tries once the context grew by the step
301function abandon($, reason) {
302 phase = 'idle'
303 closeText = null
304 closeTurnId = null
305 closeBy = null
306 compactVia = null
307 linkedBefore = null
308 cancelTimers()
309 forgetPendingResume($)
310 note($, `gave up: ${reason}`)
311 $.ui.toast(`${NAME}: ${reason}. /handoff-now retries.`, { timeoutMs: 8000 })
312 void restoreRemoteControl($)
313}
314
315// The hand-off is asked for: its turn is awaited. With a new session, the sessions this one
316// started so far are noted, to tell the one the hand-off turn opens apart
317async function prepare($, cfg, by, percent) {
318 phase = 'closing'
319 closeTurnId = null
320 closeText = null
321 closeBy = by
322 triggeredAt = percent
323 cancelTimers()
324 if (cfg.reset === 'session') linkedBefore = (await linkedSessions($)).map((row) => row.sessionId)
325}
326
327// The turn that runs the hand-off has started. With the clear, the app is asked now, so the
328// conversation is cleared as this turn ends.
329async function closeTurnStarted($, cfg, turnId) {
330 closeTurnId = turnId
331 note($, 'the hand-off turn is running')
332 if (cfg.reset === 'clear') await requestClear($, cfg)
333}
334
335// (session) Past the threshold: the hand-off waits for the user's next message. The app opens
336// a session only on a turn the user started, which a prompt of this mod's is not; so the
337// instructions ride on that message, which the new session takes over unanswered
338function arm($, percent) {
339 phase = 'armed'
340 triggeredAt = percent
341 note($, `context at ${Math.round(percent)}%: your next message goes to a new session, after the hand-off`)
342 $.ui.toast(`${NAME}: context at ${Math.round(percent)}%, your next message hands off to a new session`, {
343 timeoutMs: 8000,
344 })
345}
346
347// Submit the hand-off prompt; its turn is found by the tag at turn.start
348async function begin($, cfg, percent, why) {
349 await prepare($, cfg, 'prompt', percent)
350 const text = closePromptFor(cfg, percent, await hasCommand($, cfg.closeCommand))
351 closeText = text
352 note($, `hand-off started: ${why}`)
353 $.ui.toast(`${NAME}: ${why}, recording the hand-off`)
354 $.prompt
355 .submit({ text, asUser: true })
356 .then((result) => {
357 if (result && result.drop && phase === 'closing' && closeText === text) {
358 abandon($, `the hand-off prompt was refused: ${result.drop}`)
359 }
360 })
361 .catch((error) => {
362 if (phase === 'closing' && closeText === text) abandon($, `the hand-off prompt failed: ${messageOf(error)}`)
363 })
364}
365
366// Ask the desktop app to clear this conversation once the running turn ends. The app keeps
367// the request only while the turn runs and acts on it as the turn's result arrives, so it is
368// made as the hand-off turn starts. A session started from another device (Remote Control)
369// cannot be cleared, so Remote Control is turned off for it when allowed.
370async function requestClear($, cfg) {
371 phase = 'clearing'
372 let refused = await callApp($, 'clear_session', { session_id: 'self' })
373 if (refused && cfg.pauseRemoteControl && /remote control/i.test(refused)) {
374 const failed = await callApp($, 'set_remote_control', { session_id: 'self', enabled: false })
375 if (failed) {
376 return abandon($, `the app refused to clear the context: ${refused}; Remote Control could not be turned off: ${failed}`)
377 }
378 remoteControlPaused = true
379 note($, 'Remote Control turned off for the clear; it is turned on again after the resume')
380 refused = await callApp($, 'clear_session', { session_id: 'self' })
381 }
382 if (refused) return abandon($, `the app refused to clear the context: ${refused}`)
383 // The clear ends this process; the next one finds the resume to make in the store
384 try {
385 await $.store.set(RESUME_KEY, {
386 appSessionId: await appSessionId($),
387 cwd: await $.session.cwd(),
388 askedAt: await $.clock.now(),
389 })
390 } catch (error) {
391 note($, `the resume could not be stored for the next process: ${messageOf(error)}`)
392 }
393 note($, 'the app will clear the conversation when the hand-off turn ends')
394}
395
396// The hand-off turn has ended: the app clears the conversation now, or the hand-off is given up
397function awaitClear($) {
398 note($, 'hand-off recorded, waiting for the app to clear the conversation')
399 $.ui.toast(`${NAME}: hand-off recorded, clearing the context`)
400 if (clearWatchdog) clearWatchdog.cancel()
401 clearWatchdog = $.clock.after(CLEAR_WAIT_MS, () => {
402 clearWatchdog = null
403 if (phase === 'clearing') {
404 abandon($, `the app did not clear the conversation within ${CLEAR_WAIT_MS / 1000} s of the hand-off turn ending`)
405 }
406 })
407}
408
409// (session) The hand-off turn has ended: the session it opened carries the work on. That one is
410// moved to top level, so it lives on by itself and this one is not woken each time its turns
411// end, and this one is unpinned unless kept. With no session opened, this one is compacted.
412async function handOver($, cfg) {
413 phase = 'handing'
414 const opened = await sessionOpened($)
415 if (phase !== 'handing') return
416 if (!opened) {
417 note($, 'no session was opened to continue the work; compacting here instead')
418 return startCompaction($, cfg)
419 }
420 const name = typeof opened.title === 'string' && opened.title ? opened.title : opened.sessionId
421 const detachFailed = await callApp($, 'detach_session', { session_id: opened.sessionId })
422 if (detachFailed) note($, `the new session stays under this one: ${detachFailed}`)
423 if (cfg.unpinOld) {
424 const unpinFailed = await callApp($, 'set_pinned', { session_id: 'self', pinned: false }, 'ccd_sidebar')
425 if (unpinFailed) note($, `this session could not be unpinned: ${unpinFailed}`)
426 }
427 phase = 'idle'
428 closeText = null
429 closeTurnId = null
430 closeBy = null
431 linkedBefore = null
432 note($, `the work continues in the session "${name}" (${opened.sessionId})`)
433 $.ui.toast(`${NAME}: the work continues in "${name}"`, { timeoutMs: 8000 })
434}
435
436// The hand-off turn has ended: compact the conversation down to the notes, then resume.
437// A compaction is refused while a turn still runs, so it is tried a few times. A session
438// with no compaction call of its own (the desktop app's) compacts through /compact instead,
439// as does one configured to.
440function startCompaction($, cfg) {
441 phase = 'compacting'
442 compactVia = 'call'
443 note($, 'hand-off recorded, compacting the conversation')
444 $.ui.toast(`${NAME}: hand-off recorded, compacting the conversation`)
445 const attempt = (i) => {
446 compactTimer = $.clock.after(COMPACT_TRIES_MS[i], async () => {
447 compactTimer = null
448 if (phase !== 'compacting') return
449 if (cfg.compaction === 'command') return compactByCommand($, cfg, 'compacting through /compact, as configured')
450 let result
451 try {
452 result = await $.session.compact({ instructions: COMPACT_INSTRUCTIONS })
453 } catch (error) {
454 const message = messageOf(error)
455 if (cfg.compaction === 'auto' && hasNoCompactCall(message)) {
456 return compactByCommand($, cfg, 'this session has no compaction call; compacting through /compact')
457 }
458 if (i + 1 < COMPACT_TRIES_MS.length) return attempt(i + 1)
459 return abandon($, `the conversation could not be compacted: ${message}`)
460 }
461 if (result && result.skip) return abandon($, `the compaction was skipped: ${result.skip}`)
462 compacted($, cfg, `compacted the conversation${sizesOf(result)}`, 0)
463 })
464 }
465 attempt(0)
466}
467
468// Compact through the /compact command, queued as if typed, with the same instructions.
469// The compaction is seen as it runs, by the session.compact hook; the command's own answer,
470// which may come later or never, stands in when the hook saw nothing.
471function compactByCommand($, cfg, why) {
472 compactVia = 'command'
473 note($, why)
474 if (compactWatchdog) compactWatchdog.cancel()
475 compactWatchdog = $.clock.after(COMPACT_COMMAND_WAIT_MS, () => {
476 compactWatchdog = null
477 if (phase === 'compacting') {
478 abandon($, `the /compact command did not compact the conversation within ${COMPACT_COMMAND_WAIT_MS / 60000} min`)
479 }
480 })
481 $.command
482 .run({ command: 'compact', args: COMPACT_INSTRUCTIONS })
483 .then(async (result) => {
484 if (phase !== 'compacting') return
485 // The hook saw no compaction: the context says whether the command made one
486 const percent = await readPercent($)
487 const answer = typeof result?.text === 'string' && result.text.trim() ? `: ${result.text.trim().slice(0, 160)}` : ''
488 if (percent !== null && triggeredAt && percent >= triggeredAt) {
489 return abandon($, `the /compact command ran, but the context is still at ${Math.round(percent)}%${answer}`)
490 }
491 compacted($, cfg, `the /compact command finished${percent === null ? '' : `, the context at ${Math.round(percent)}%`}`)
492 })
493 .catch((error) => {
494 if (phase === 'compacting') abandon($, `the /compact command failed: ${messageOf(error)}`)
495 })
496}
497
498// The conversation is compacted: the resume prompt follows, once. From the engine's call it
499// follows at once (the call resolves between turns, the compaction installed); from /compact
500// a moment later, as the hook sees the compaction while the command's turn still runs.
501function compacted($, cfg, what, afterMs = RESUME_AFTER_COMPACT_MS) {
502 if (phase !== 'compacting') return
503 phase = 'resuming'
504 cancelTimers()
505 note($, what)
506 if (afterMs === 0) submitResume($, cfg)
507 else resumeTimer = $.clock.after(afterMs, () => submitResume($, cfg))
508}
509
510// Submit the resume prompt into the fresh conversation, once
511function submitResume($, cfg) {
512 if (phase !== 'resuming') return
513 phase = 'idle'
514 closeText = null
515 closeTurnId = null
516 closeBy = null
517 triggeredAt = null
518 compactVia = null
519 cancelTimers()
520 forgetPendingResume($)
521 note($, 'continuing in a fresh context')
522 $.ui.toast(`${NAME}: continuing in a fresh context`)
523 $.prompt.submit({ text: resumePromptFor(cfg), asUser: true }).catch(() => {})
524}
525
526// A fresh process after the app's clear: when the store says this session's hand-off asked
527// for a resume, and no prompt has run yet, continue from the notes. The app starts that process
528// at the user's next message, however long after the clear, so the resume keeps until then
529async function resumeIfPending($, cfg) {
530 let pending
531 try {
532 pending = await $.store.get(RESUME_KEY)
533 } catch {
534 return
535 }
536 if (!pending || typeof pending !== 'object') return
537 const forget = () => forgetPendingResume($)
538 if ((await $.session.turns()) !== 0) return forget()
539 const id = await appSessionId($)
540 const isThisSession =
541 id && pending.appSessionId ? id === pending.appSessionId : (await $.session.cwd()) === pending.cwd
542 // Another session's hand-off: leave its resume to it
543 if (!isThisSession) return
544 forget()
545 phase = 'resuming'
546 note($, 'a fresh process after the clear; continuing from the notes')
547 resumeTimer = $.clock.after(1000, () => submitResume($, cfg))
548}
549
550export function register(on, options) {
551 const cfg = settingsOf(options)
552
553 // Runs before your first prompt, and again after a reload. /handoff-now is this plugin's
554 // skill (skills/handoff-now), so it runs in the turn the user typed it in
555 on('session.start', async ($, e, next) => {
556 await $.command.register({
557 name: 'handoff-status',
558 description: 'Show where the automatic hand-off stands and what it did last',
559 })
560 await resumeIfPending($, cfg)
561 return next(e)
562 })
563
564 // (session) The user's next message after the threshold carries the hand-off instructions,
565 // read by the model beside it. Not a command, nor one typed over a running turn
566 on('prompt.submit', async ($, e, next) => {
567 const text = typeof e.text === 'string' ? e.text : ''
568 const fromUser = USER_ORIGINS.includes(e.origin?.kind)
569 if (phase !== 'armed' || !fromUser || e.turnId !== undefined || text.trimStart().startsWith('/')) return next(e)
570 const percent = (await readPercent($)) ?? triggeredAt ?? cfg.threshold
571 const instructions = closePromptFor(cfg, percent, await hasCommand($, cfg.closeCommand), 'carry')
572 await prepare($, cfg, 'user', percent)
573 note($, `hand-off started: context at ${Math.round(percent)}%, past ${cfg.threshold}%; your message goes to a new session`)
574 const out = await next({ ...e, context: [...(e.context ?? []), instructions] })
575 if (out && out.drop !== undefined && phase === 'closing' && closeTurnId === null) arm($, percent)
576 return out
577 }).catch(($, e, next) => next(e)) // A failure here never holds up the user's message
578
579 // /handoff-now: the skill's own text stands in when this mod is not loaded; here it reads the
580 // hand-off as configured. It runs in the turn the user typed it in, which may have started
581 on('skill.prompt', async ($, e, next) => {
582 const out = await next(e)
583 if (!HANDOFF_SKILL.test(e.skill)) return out
584 if (phase !== 'idle' && phase !== 'armed') {
585 return { text: `${MARK} A hand-off is already in progress (${phase}). Say so in one line and stop.` }
586 }
587 const percent = (await readPercent($)) ?? 0
588 await prepare($, cfg, 'user', percent)
589 note($, 'hand-off started: asked by /handoff-now')
590 $.ui.toast(`${NAME}: asked by /handoff-now, recording the hand-off`)
591 if (currentTurnId !== null) await closeTurnStarted($, cfg, currentTurnId)
592 return { text: closePromptFor(cfg, percent, await hasCommand($, cfg.closeCommand), 'asked') }
593 })
594
595 // The turn that runs the hand-off: for a prompt of this mod's, the one whose text carries the
596 // tag; for one the user started, the next to start
597 on('turn.start', async ($, e, next) => {
598 if (e.agentId === undefined) currentTurnId = e.turnId
599 if (phase === 'closing' && closeTurnId === null && e.agentId === undefined) {
600 const tagged = typeof e.text === 'string' && e.text.includes(MARK)
601 if (closeBy === 'user' || tagged) await closeTurnStarted($, cfg, e.turnId)
602 }
603 return next(e)
604 })
605
606 on('turn.complete', async ($, e, next) => {
607 const out = await next(e)
608 // A subagent's turn is not the conversation's
609 if (e.agentId !== undefined) return out
610 if (e.turnId === currentTurnId) currentTurnId = null
611 const ended = e.reason ?? (e.isAborted ? 'aborted' : 'answer')
612
613 if (phase === 'closing') {
614 // The hand-off prompt is still queued, behind the turn that just ran
615 if (e.turnId !== closeTurnId) return out
616 if (ended === 'aborted') abandon($, 'the hand-off turn was interrupted')
617 else if (cfg.reset === 'session') await handOver($, cfg)
618 else startCompaction($, cfg)
619 return out
620 }
621 if (phase === 'clearing') {
622 if (e.turnId === closeTurnId) {
623 // An interrupted hand-off turn takes the app's queued clear with it
624 if (ended === 'aborted') abandon($, 'the hand-off turn was interrupted')
625 else awaitClear($)
626 } else if (ended === 'answer') {
627 // A turn ran after the hand-off, so the app dropped the clear: record again
628 const percent = (await readPercent($)) ?? triggeredAt ?? cfg.threshold
629 await begin($, cfg, percent, 'a turn ran before the clear')
630 }
631 return out
632 }
633 if (phase !== 'idle') return out
634 // The resume turn has run: the session may serve Remote Control again
635 await restoreRemoteControl($)
636 if (!cfg.enabled || ended !== 'answer') return out
637
638 const percent = await readPercent($)
639 if (percent === null || percent < cfg.threshold) return out
640 if (triggeredAt !== null && percent < triggeredAt + cfg.step) return out
641 if (cfg.reset === 'session') arm($, percent)
642 else await begin($, cfg, percent, `context at ${Math.round(percent)}%, past ${cfg.threshold}%`)
643 return out
644 })
645
646 // A compaction run through /compact passes here as it runs: once it stands, the resume
647 // follows; a compaction the engine makes on its own meanwhile serves as well
648 on('session.compact', async ($, e, next) => {
649 const watching = phase === 'compacting' && compactVia === 'command' && e.agentId === undefined
650 let out
651 try {
652 out = await next(e)
653 } catch (error) {
654 if (watching && phase === 'compacting') abandon($, `the compaction failed: ${messageOf(error)}`)
655 throw error
656 }
657 if (watching && phase === 'compacting') {
658 if (out && out.skip !== undefined) abandon($, `the compaction was skipped: ${out.skip}`)
659 else compacted($, cfg, `compacted the conversation${sizesOf(out)}`)
660 }
661 return out
662 })
663
664 // A /clear ends the conversation; where the process goes on, it continues with a fresh one
665 on('session.end', async ($, e, next) => {
666 if (e.reason === 'clear' && phase === 'clearing') {
667 phase = 'resuming'
668 cancelTimers()
669 resumeTimer = $.clock.after(3000, () => submitResume($, cfg))
670 } else if (e.reason !== 'clear') {
671 phase = 'idle'
672 cancelTimers()
673 }
674 return next(e)
675 })
676
677 // The fresh conversation's SessionStart is the moment to continue
678 on('classic.SessionStart', async ($, e, next) => {
679 const out = await next(e)
680 if (e.source === 'clear' && phase === 'resuming') submitResume($, cfg)
681 return out
682 }).catch(($, e, next) => next(e)) // A failure here never holds up the session
683
684 on('command.run', { command: 'handoff-status' }, async ($) => {
685 const percent = await readPercent($)
686 const fill = percent === null ? 'no reading yet' : `${Math.round(percent)}%`
687 return {
688 text:
689 `Phase: ${phase}. Context: ${fill} (threshold ${cfg.threshold}%). ` +
690 `Automatic hand-off: ${cfg.enabled ? 'on' : 'off'}. Reset: ${cfg.reset}. Last: ${lastOutcome}.`,
691 }
692 })
693}
694