SLOPSHOPPER

claudefishing

claudefishing: a shared fishing lobby you play while Claude Code is open; your cat gets a slight buff while Claude is working.

guardcommandstatusprocessnetworktimer
v0.4.2no licenseupdated 2026-10-26bryanlin850/claudefishing
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · claudefishing
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /fishing ⎿ claudefishing: fishing on · server https://claudefishing.io · offline (no identity: could not create /Users/dev/.claudefishin ⎿ claudefishing: this session: model claude-opus-5-5 · effort not known until a turn runs ⎿ claudefishing: identity: /Users/dev/.claudefishing/identity.json (stays on this machine) ⎿ claudefishing: usage: /fishing [status|open [app|browser|default|chrome|edge|brave|firefox|safari]|on|off|link [code]|unlink] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ claudefishing: 🎣 offline
README

claudefishing

The Claude Code plugin for claudefishing, a small multiplayer fishing game you play while a Claude Code session is open. The plugin connects your sessions to the game:

  • the game is playable while at least one Claude Code session on your machine runs this plugin with fishing on;
  • while Claude is working (a turn is running, or it did something in the last 5 minutes, subagents included) your cat gets a slight buff, scaled by the session's model and effort, which also show on your nametag. Time Claude spends waiting on you (a permission prompt, a question, plan approval, an MCP form) does not count as working;
  • /fishing open opens the game. The first time, it asks whether you want an app window (in your default browser, a window with no tabs or address bar when it is Chrome, Edge or Brave) or a link to open in your own browser, and remembers the answer (/fishing open app or /fishing open browser changes it). /fishing open chrome (or edge, brave, firefox, safari) opens it in that browser from then on; /fishing open default goes back. With the app window, the game also opens on its own once per session when one starts (unless CLAUDEFISHING_AUTO_OPEN=0).

This is a Claude Code mod: hooks/register.ts runs inside Claude Code. The game and server are hosted separately; installing the mod requires no game source or build step. Requires Claude Code 2.1.287 or later; development checks use 2.1.289. The mod adds no skills, MCP server, or model calls.

Install

Pick one, then type /reload-plugins in any Claude Code session that is already open (a new session loads the plugin by itself).

Terminal (recommended):

claude plugin marketplace add bryanlin850/claudefishing
claude plugin install claudefishing@claudefishing

or, inside a terminal session of Claude Code, /plugin marketplace add bryanlin850/claudefishing, then /plugin install claudefishing@claudefishing.

Claude desktop app: typing /plugin marketplace add … in the Code tab drops its arguments, so either

  1. send Claude this message; it runs the two commands above with the app's own copy of claude, which is often not on your PATH:
   Install the claudefishing plugin for me by running this in the shell:
   c="${CLAUDE_CODE_EXECPATH:-claude}"; "$c" plugin marketplace add bryanlin850/claudefishing && "$c" plugin install claudefishing@claudefishing
   When it finishes, tell me to type /reload-plugins.
  1. or open Settings, scroll to Plugins, click Add, choose Add from a repository and paste https://github.com/bryanlin850/claudefishing. That adds the marketplace only: find claudefishing in the list and click Install.

Then type /reload-plugins in the Code tab.

One session, from a checkout

claude --plugin-dir /path/to/claudefishing

Every session from a checkout, including the desktop app: name the folder in CLAUDE_CODE_PLUGIN_DIRS, in your shell or in the env block of ~/.claude/settings.json (the desktop app reads the latter):

{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claudefishing" } }

Settings

There is nothing to configure: the plugin declares no options (Claude Code would list them as "not yet set" on every install), and it only ever talks to https://claudefishing.io. The game opens by itself once per session when an interactive terminal session starts, or the desktop app or VS Code attaches (a phone never opens it; the server skips it while a game window is already connected, one was opened in the last minute, or fishing is off; and it never opens when you chose the browser link). To keep it from doing that, set CLAUDEFISHING_AUTO_OPEN to 0 (or false, no, off) in your shell or in the env block of ~/.claude/settings.json (the desktop app reads the latter):

{ "env": { "CLAUDEFISHING_AUTO_OPEN": "0" } }

Mods are enabled by default in supported Claude Code versions. Update Claude Code if /fishing is unknown, then run /reload-plugins or restart. Visual status is supported in the terminal and Desktop Code tab. Other surfaces can run hooks without displaying mod UI. The game opens in an external browser.

Updates. Marketplace installs do not update by themselves unless you turn auto-update on (/plugin → Marketplaces → claudefishing → Enable auto-update). By hand:

claude plugin marketplace update claudefishing && claude plugin update claudefishing@claudefishing

then type /reload-plugins (or restart Claude Code). In the desktop app, ask Claude to run it: its shell has the app's own claude as $CLAUDE_CODE_EXECPATH. When a newer plugin is out, the status line says · update available, a toast gives that command once, and /fishing shows it; when the server needs a newer one than yours, the status line says 🎣 update the plugin to play and the game shows an update screen.

Usage

/fishing              status (same as /fishing status)
/fishing open         open the game (pairs this machine with it; turns fishing on if it was off)
/fishing open app     open it in an app window, from now on
/fishing open browser give a link to open in your own browser, from now on
/fishing open chrome  open it in Chrome (or edge, brave, firefox, safari), from now on
/fishing open default open it in your default browser again
/fishing off          stop reporting from every session on this machine, and close its game window
/fishing on           resume
/fishing link         a one-time code for another device to play this cat
/fishing link <code>  play the cat that code was made for, here too
/fishing unlink       go back to this machine's own cat

/fishing status shows whether fishing is on, the server and whether it answers, whether the game window is open, your player, the devices that play it, how many live sessions they have, the model and effort shown on your nametag, the buff, this session's model and effort, and where the identity file is.

Several devices, one cat

Every machine starts with a cat of its own. /fishing link on a machine prints a code (like KQ74-MZ8P, good once, for 10 minutes; the command to type on the other device goes to the clipboard), and /fishing link KQ74-MZ8P on another machine makes that machine play the same cat: same fish, money, level and cosmetics. Its sessions count for the buff from then on, and a game window it has open reopens as that cat.

If the claiming machine's own cat has caught or bought something, a question comes first: it says what that cat has, what it is switching to and what becomes of the old one, and offers Switch to <cat> or Keep <cat>. Nothing is deleted: /fishing unlink switches a linked machine back to its own cat, again asking first if it is the last device of a cat with progress (that cat could not be reached again). In claude -p nobody can be asked, so nothing switches.

On and off is one switch for the whole machine, kept in ~/.claudefishing/fishing.json beside the identity: every session reads it every 5 seconds, whichever copy of the plugin it runs, and a new session starts the way you left it. The server keeps the switch too. While it is off, no session on the machine counts, not even one still running a plugin from before 0.3.0, and turning it off closes the game window the machine opened (the page closes itself, or says fishing is off if the browser will not let it). /fishing off always counts as a flip, so typing it again closes a window opened since. /fishing open turns fishing back on too; the automatic open never does, and opens nothing while fishing is off.

Sessions still on a plugin before 0.3.0 follow the switch at their next keepalive (they read it from the plugin's store, which the plugin keeps in step with the file), and their own /fishing on and /fishing off count as a flip once a session on 0.3.0 reads the store. A copy of the plugin loaded by hand keeps a store of its own: the server leaves its sessions out while fishing is off all the same.

The status line shows one of:

🎣 in gamethe server answers and a game window is connected
🎣 opening gamethis session just opened the game and its window has not joined yet (at most 45 s)
🎣 game closedthe server answers, no game window (/fishing open)
🎣 offlinethe server did not answer, or no session on the machine got an answer for 2½ minutes (the game stays locked unless another session reaches it)
🎣 off/fishing off

plus · ⚡+11% while the buff is on.

The first /fishing open asks "App window" or "Browser link" and keeps the answer in the plugin's store (dismissed, or in claude -p, it opens the app window and asks again next time). The app window opens in the browser chosen with /fishing open <browser>, else in the system's default browser: as an app window (--app=<url>, no tabs or address bar) when that is Chrome, Edge or Brave, else as a plain link. On macOS the default browser is read with osascript (NSWorkspace), and the app window opens with open -nb <bundle id> --args --app=<url>; on Windows it is read from the https handler in the registry, and the window opens with PowerShell's Start-Process <browser> '--app=<url>'; on Linux it is read with xdg-settings get default-web-browser, and the browser starts in the background (one that quits with an error within a second counts as not opening). A plain link goes to open <url> or xdg-open <url>, on Windows rundll32 url.dll,FileProtocolHandler <url>; a chosen browser that will not start falls back to it too. The browser link is printed and copied to the clipboard instead, to open in whichever browser you like. Either way the link carries a one-time pairing code; it works once, for two minutes.

What it sends, and what stays local

Every request goes to https://claudefishing.io (in development, to a server on the same machine) with Authorization: Bearer <secret>.

  • Identity. On first use the plugin creates ~/.claudefishing/identity.json ({ secret, createdAt }, a random 256-bit secret; the folder is mode 700, the file 600). It is written to a temporary file and linked into place, so sessions starting together all end up with the same one. It never leaves your machine except as that bearer token, and the server stores only hashes of it. Your browser never sees it: it is paired with a one-time code instead. Deleting the file makes you a new player; an unreadable one is kept as identity.json.corrupt-<time> and replaced. Set CLAUDEFISHING_HOME=/some/dir to keep it in /some/dir/identity.json instead (a second identity for testing).
  • POST /api/heartbeat per session, at once when something changes (Claude starts or stops working or starts waiting on you, the model or effort changes, activity after 5 idle minutes), every 5 s for up to 45 s after the session opens the game (until the answer says its window joined), once when the session ends, and once when fishing goes off (again a minute later while the server does not answer it). Otherwise as a keepalive once nothing was sent for 60 s, but only from a session Claude worked in during the last 5 minutes (the buff's window). An idle session stays quiet unless no session on the machine has sent a heartbeat for 60 s, so forty idle threads keep the game open with one heartbeat a minute, not forty. Quiet sessions' status lines show the last answer any session on the machine got. Each heartbeat carries:
Field
sessionIdthe Claude Code session id
enabledfalse once, when fishing goes off
endingtrue once, when the session ends; after /clear or /resume, once the next conversation has sent its first heartbeat
modelthe model id the last main-loop request used (claude-opus-5-5), or the one /model switched to, else the session's
effortthe last request's effort (low … max); null before this session's first turn, after a /model switch until the next request, and for a model without effort
workinga turn or a subagent is running right now and Claude is not waiting on you
activeAgoMsmilliseconds since Claude last started a turn, made a model request, called a tool, got a tool's result or finished a turn; null before any
modVersionthis plugin's version (a server may refuse versions older than its minimum)
fishingthe machine's switch, { on, rev }: rev counts the flips, so the server keeps the newest. The answer has the server's, which wins when newer (the file was lost, say)
workwhat Claude has done in the session, as totals (below), for game mechanics; the game may use them or not

work holds numbers only, totals since its random run id began, which only grow (a /clear or /resume starts a new run):

  • model requests answered, the main loop's and subagents', and their tokens by kind (input, output, cache read, cache write), also by the model that answered (claude-opus-5-5), for up to 8 models;
  • main-loop turns ended, of them how many you interrupted and how many ended on an error or a refusal, and their total length; subagent runs ended;
  • tool calls by tool: Claude Code's own tools by name (Bash, Read, Edit …), every MCP tool as mcp and anything else as other, never which server, plugin, command, file or input; and how many different MCP servers were called (their names stay in the session, on your machine);
  • the status line's figures at the last measure: how full the context window is and its size, your plan's rate-limit windows (percent used and when each resets), and what the session has cost so far.
  • The machine's keepalive and last answer, beside the identity and never sent anywhere: ~/.claudefishing/keepalive.json ({ at, sessionId }, stamped before every heartbeat; a session taking the keepalive over from another writes a claim first and beats only if its claim is still there a second later, so idle sessions finding it due together send one heartbeat) and ~/.claudefishing/answer.json (the newest heartbeat answer, which quiet sessions show).
  • POST /api/pair { sessionId, reason: 'auto' | 'manual' } when the game is opened. The server skips auto while fishing is off on the machine; manual (/fishing open) turns it on.
  • POST /api/link {} on /fishing link; POST /api/link/claim { code, sessionId, replace } on /fishing link <code> (replace is true only after you chose to switch); POST /api/unlink { sessionId, confirm } on /fishing unlink.

Nothing else: no prompts, answers, code, file names, tool inputs or paths.

Development

Use Node.js 24 LTS (.node-version names the release CI uses, 24.22.1, the October 2026 security release) and install the development tools (including a local, pinned Claude Code binary):

npm ci
npm run validate
npm test
npm run typecheck

The tests run through Claude Code's engine with filesystem, processes, network and time mocked. They need no account or model call. Type checking first loads a disposable copy to generate .claude-plugin/types/ using the pinned Claude Code binary. It uses a temporary identity/configuration and a closed loopback port; it neither opens the game nor needs an account. Generated declarations are ignored by Git. Run npm run types:generate to refresh them separately.

For a local game server, load this checkout with the server in the environment:

CLAUDEFISHING_SERVER_URL=http://localhost:8790 CLAUDEFISHING_AUTO_OPEN=0 claude --plugin-dir /path/to/claudefishing

CLAUDEFISHING_SERVER_URL only takes a server on the same machine (localhost, 127.0.0.1 or [::1]); anything else is ignored. Every request carries the machine's secret, and a project's .claude/settings.json can set environment variables, so no setting may send it to another server. Use CLAUDEFISHING_HOME to choose a separate test identity (and on/off switch). To copy the mod into an existing hot-reload session, name that session explicitly:

npm run dev:sync -- /absolute/path/to/dev-mods/<session>

SERVER_URL overrides the copy's local server. The helper never guesses the most recent session, and refuses to replace a folder it did not create.

HTTP contract and releases

types/protocol.ts is the public contract for heartbeat, pairing and device linking. It contains no game rules, assets, storage schema or browser protocol. The game vendors an exact copy from a pinned public commit. release.json records its SHA-256, the plugin version and the stable update command.

For a release:

  1. Make backward-compatible changes to the contract and hooks.
  2. Run node scripts/prepare-release.mjs MAJOR.MINOR.PATCH to update version metadata and the contract hash.
  3. Run validation, tests and type checking; review and publish the commit.
  4. Tag that tested commit and update the game's pinned contract/release metadata. Only raise the server's minimum plugin version after the release is installable.

The marketplace uses the version in plugin.json; it does not duplicate it. The game can deploy independently while older plugins remain compatible.

Source and privacy

This repository contains only the Claude Code integration. Its history starts with that integration; game/server/admin source and their history remain in a separate private repository. The hosted game still delivers its browser code and assets to players. No open-source license is granted by this repository.

Source 4 files
hooks/register.ts 1578 lines
1// claudefishing: connects this machine's Claude Code sessions to the
2// claudefishing game. Heartbeats say a session is alive (so the game is
3// playable), which model/effort it runs and whether Claude is working (the
4// buff); /fishing opens the game, turns reporting on/off, shows status and
5// links devices so they play one cat.
6//
7// On and off are one switch for the whole machine: a file beside the
8// identity, which every session and every copy of the plugin reads. Each
9// flip is numbered, every heartbeat carries the switch, and the server keeps
10// each machine's newest: while it is off, no session of the machine counts,
11// not even one running an older plugin that never reads the file.
12//
13// Only sessions Claude works in count for the buff, so only they keep
14// themselves alive: while a turn runs and for the buff window after it. An
15// idle session stays quiet unless no session of the machine has beaten for a
16// keepalive (another file beside the identity), so a machine with forty
17// threads open keeps the game open with one keepalive, not forty. Quiet
18// sessions show the last answer any session of the machine got.
19//
20// Every heartbeat also carries what Claude did in the session, as totals of
21// numbers (model requests and their tokens, turns, tool calls, the status
22// line's figures), for game mechanics; nothing Claude read or wrote.
23
24import type { EngineInterface, Register, SessionMeasureInput, TurnCompleteInput, TurnStepResult, TurnUsage } from 'claude-code'
25import { MOD_VERSION } from '../types/version'
26
27import type { FishingActivity, FishingStep, FishingTurn } from '../types'
28import type {
29  FishingSwitch,
30  HeartbeatRequest,
31  HeartbeatResponse,
32  LinkClaimRequest,
33  LinkClaimResponse,
34  LinkResponse,
35  PairRequest,
36  PairResponse,
37  PlayerSummary,
38  UnlinkRequest,
39  UnlinkResponse,
40  WorkMeasure,
41  WorkReport,
42  WorkTokens,
43} from '../types/protocol'
44
45const DEFAULT_SERVER_URL = 'https://claudefishing.io' // npm run dev:sync swaps in the dev server in its copy only
46// No plugin.json userConfig: Claude Code reports declared options as "not yet set" on install, defaults or
47// not. CLAUDEFISHING_AUTO_OPEN=0 (false, no, off), from the shell or the `env` block of settings.json,
48// keeps the game from opening by itself. CLAUDEFISHING_SERVER_URL is for development and names a server
49// on this machine only: every request carries the machine's secret, and a project's settings can set
50// environment variables, so nothing in them may send it anywhere but the game.
51
52/**
53 * Every change is sent at once (queueBeat); with none, the server still hears this often from a
54 * session Claude worked in within the buff window, and from the machine (any idle session) otherwise.
55 */
56const KEEPALIVE_MS = 60_000
57/** Mirrors the server's presence.sessionTtlMs: no answer on the whole machine for this long, and a quiet session says offline. */
58const ANSWER_STALE_MS = 150_000
59/** A session taking over the machine's keepalive waits this long after its claim: of claims made together, the last one written beats. */
60const CLAIM_SETTLE_MS = 1_000
61/** How often the session checks, without the network, whether a keepalive is due or a turn went stale. */
62const TICK_MS = 5_000
63/** After this session opens the game, every tick beats until the server sees the window join, for at most this long. */
64const OPENING_MS = 45_000
65const HTTP_TIMEOUT_MS = 4_000
66/** /fishing off waits this long for a beat in flight, so its enabled:false lands after it. */
67const OFF_INFLIGHT_WAIT_MS = 300
68/** The switch before anyone flips it: on, no flips yet. */
69const FIRST_SWITCH: FishingSwitch = { on: true, rev: 0 }
70/** session.end has ~1.5 s for the whole chain: an exit spends at most this telling the server (its TTL drops the session anyway). */
71const END_TIMEOUT_MS = 600
72/** A beat already under way for a session id that just ended is dropped for this long; a later return to the id (/resume) beats again. */
73const ENDED_GUARD_MS = 5_000
74/** Mirrors the server's ENDED_TOMBSTONE_MS: it ignores beats for an id this long after that id ended. */
75const SERVER_TOMBSTONE_MS = 10_000
76/** After a /clear or /resume the engine may move to the next conversation's id a moment after session.end: poll for it. */
77const SWITCH_POLL_MS = 50
78const SWITCH_POLLS = 40
79/** Mirrors the server's buff.inactivityMs: activity after this long idle beats at once. */
80const INACTIVE_MS = 5 * 60_000
81/** A turn with no step or tool call for this long counts as over (its end was never seen); long tool runs stay inside it. */
82const STALE_TURN_MS = 30 * 60_000
83/** Notification types that mean a prompt or dialog waits on the person. */
84const PROMPT_NOTIFICATION = /permission_prompt|idle_prompt|elicitation(_url)?_dialog|needs_input/
85/** Tools whose call lasts until the person answers. */
86const ASKS_USER = new Set(['AskUserQuestion', 'ExitPlanMode'])
87const USAGE = 'usage: /fishing [status|open [app|browser|default|chrome|edge|brave|firefox|safari]|on|off|link [code]|unlink]'
88/** Models and tools a work report keeps apart: past these, a request counts in the totals only, a tool as "other". */
89const WORK_MODELS = 8
90const WORK_TOOLS = 40
91/** MCP servers a run tells apart; a new one past these is not counted. */
92const WORK_MCP_SERVERS = 64
93/**
94 * The only tools a work report names: Claude Code's own (this build's, from its tool types, and a
95 * few of older builds'). A plugin can register a tool of any name, and an MCP tool names its server,
96 * so either could say what someone works with: those count as "other" and "mcp".
97 */
98const BUILTIN_TOOLS: ReadonlySet<string> = new Set([
99  'Agent', 'AppifactRepl', 'Artifact', 'ArtifactCheck', 'ArtifactComments', 'ArtifactData', 'AskUserQuestion', 'Bash', 'BashOutput',
100  'CronCreate', 'CronDelete', 'CronList', 'DesignSync', 'Edit', 'EndConversation', 'EnterPlanMode', 'EnterWorktree', 'ExitPlanMode',
101  'ExitWorktree', 'FetchInboxMessage', 'GetTask', 'Glob', 'Grep', 'KillShell', 'LS', 'LSP', 'ListAgents', 'ListConnectors',
102  'ListMcpResourcesTool', 'ListPlugins', 'ListSkills', 'Monitor', 'MultiEdit', 'NotebookEdit', 'NotebookRead', 'Poll', 'Projects',
103  'ProposeGoal', 'PushNotification', 'Read', 'ReadMcpResourceDirTool', 'ReadMcpResourceTool', 'ReadNotifications', 'RemoteTrigger',
104  'ReportFindings', 'ScheduleWakeup', 'SearchMcpRegistry', 'SearchPlugins', 'SearchSkills', 'SendFeedback', 'SendFile', 'SendMessage',
105  'SendUserFile', 'SendUserMessage', 'ShareOnboardingGuide', 'ShowOnboardingRolePicker', 'Skill', 'SlashCommand', 'SuggestConnectors',
106  'SuggestPluginInstall', 'SuggestSkills', 'Task', 'TaskCreate', 'TaskGet', 'TaskList', 'TaskOutput', 'TaskStop', 'TaskUpdate',
107  'TodoWrite', 'ToolSearch', 'WaitForMcpServers', 'WebFetch', 'WebSearch', 'Workflow', 'Write',
108])
109
110// Session-scoped values that survive hot reloads (module variables do not).
111const ACTIVITY = { plugin: 'claudefishing', key: 'activity' } as const
112const TURN = { plugin: 'claudefishing', key: 'turn' } as const
113const AUTO_OPEN = { plugin: 'claudefishing', key: 'autoOpen' } as const
114const WORK = { plugin: 'claudefishing', key: 'work' } as const
115const MCP_SEEN = { plugin: 'claudefishing', key: 'mcpSeen' } as const
116
117/** $.store: how /fishing open opens the game, as the person chose it the first time (or with /fishing open app|browser). */
118const OPEN_IN = 'openIn'
119/** $.store: the browser the game opens in (/fishing open chrome, edge …); absent, the system's default browser. */
120const OPEN_WITH = 'openWith'
121/** app: opened in a browser (an app window when it makes them); browser: the link, to open in any browser. */
122type OpenIn = 'app' | 'browser'
123
124type Identity = { secret: string; createdAt: number }
125
126type Link = 'unknown' | 'online' | 'offline'
127
128/** `status` is set when the server answered with an HTTP error, absent when it could not be reached; `code` is the error the answer named. */
129type Reply = { ok: true; json: unknown } | { ok: false; error: string; status?: number; code?: string }
130
131type Runtime = {
132  /** DEFAULT_SERVER_URL, or a server on this machine from CLAUDEFISHING_SERVER_URL; no trailing slash. */
133  serverUrl: string
134  /** Open the game once per session (CLAUDEFISHING_AUTO_OPEN turns it off). */
135  autoOpen: boolean
136  /** This session acts on: reports while on; turned off it went quiet. Follows `fishing.on` within a tick. */
137  enabled: boolean
138  /** The machine's switch as this session last read it (the file, ~/.claudefishing/fishing.json). */
139  fishing: FishingSwitch
140  fishingPath: string | null
141  /** The flip whose off the server answered (null: none yet): an off it never heard is sent again. */
142  offSentRev: number | null
143  identityPath: string | null
144  identity: Identity | null
145  identityError: string | null
146  /** The one load (or creation) of the identity, shared by every caller while it runs. */
147  identityLoad: Promise<Identity | null> | null
148  /** Set when an unreadable identity file was moved aside. */
149  identityNote: string | null
150  activity: FishingActivity
151  turn: FishingTurn
152  /** What Claude did in this session, as every beat carries it. */
153  work: WorkReport
154  /** The MCP servers this run's tool calls went to, by name (`work.mcpServers` counts them): never sent. */
155  mcpSeen: string[]
156  lastSentWorking: boolean | null
157  /** When this session last sent a heartbeat: the next keepalive is due KEEPALIVE_MS after it. */
158  lastBeatAt: number | null
159  /** ~/.claudefishing/keepalive.json: when any session of the machine last beat. */
160  keepalivePath: string | null
161  /** ~/.claudefishing/answer.json: the last answer any session of the machine got. */
162  answerPath: string | null
163  /** When this session last got an answer, or took one from answer.json. */
164  answeredAt: number | null
165  /** answer.json as this session last wrote or showed it: a quiet session takes it again only once it changed. */
166  answerText: string | null
167  /** The plugin version an update toast was shown for (once each). */
168  updateToastFor: string | null
169  link: Link
170  linkError: string | null
171  last: HeartbeatResponse | null
172  timer: { cancel: () => void } | null
173  isBeatQueued: boolean
174  inFlight: Promise<Reply> | null
175  /** Beats are numbered so a late answer never overwrites a newer one. */
176  sentSeq: number
177  appliedSeq: number
178  isAutoOpening: boolean
179  /** The auto-open could not reach the server: the next beat it answers tries again. */
180  isAutoOpenPending: boolean
181  /** Until when a window this session opened is awaited (null: none): the line says "opening game" meanwhile. */
182  openingUntil: number | null
183  /** Session ids this process told the server were over, and when. */
184  endedAt: Map<string, number>
185}
186
187function hex(bytes: Uint8Array): string {
188  return Array.from(bytes, b => b.toString(16).padStart(2, '0')).join('')
189}
190
191function errorText(err: unknown): string {
192  const text = (err instanceof Error ? err.message : String(err)).split('\n')[0]!
193  if (text.includes('ECONNREFUSED')) return 'connection refused'
194  if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/.test(text)) return 'host not found'
195  return text.replace(/^claudefishing: \$\.[\w.]+(?:\(.*?\))?(?: failed)?: /, '').slice(0, 160)
196}
197
198// Waiting on the person (a permission prompt, a question) is not working, however long the turn stays open.
199function isWorking(rt: Runtime, now: number): boolean {
200  if (rt.turn.waiting || (!rt.turn.running && rt.turn.agents.length === 0)) return false
201  const last = rt.activity.lastActiveAt
202  return last !== null && now - last < STALE_TURN_MS
203}
204
205function isRecentlyEnded(rt: Runtime, sessionId: string, now: number): boolean {
206  const endedAt = rt.endedAt.get(sessionId)
207  return endedAt !== undefined && now - endedAt < ENDED_GUARD_MS
208}
209
210function markEnded(rt: Runtime, sessionId: string, now: number): void {
211  // An end older than a minute matters to nobody: the guard and the server's tombstone are seconds long.
212  for (const [id, at] of rt.endedAt) if (now - at > 60_000) rt.endedAt.delete(id)
213  rt.endedAt.set(sessionId, now)
214}
215
216/** CLAUDEFISHING_SERVER_URL when it names a server on this machine (development), else DEFAULT_SERVER_URL. */
217function serverUrlFrom(value: string | null | undefined): string {
218  const fallback = DEFAULT_SERVER_URL.replace(/\/+$/, '')
219  if (!value?.trim()) return fallback
220  try {
221    const url = new URL(value.trim())
222    const isThisMachine = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)
223    return isThisMachine && (url.protocol === 'http:' || url.protocol === 'https:') ? url.origin : fallback
224  } catch {
225    return fallback
226  }
227}
228
229function autoOpenFrom(value: string | null | undefined): boolean {
230  return !/^(0|false|no|off)$/i.test(value?.trim() ?? '')
231}
232
233function pct(fraction: number): string {
234  return `+${Math.round(fraction * 100)}%`
235}
236
237function statusLine(rt: Runtime): string | undefined {
238  if (!rt.enabled) return '🎣 off'
239  if (rt.link === 'unknown') return undefined
240  if (rt.link === 'offline' || rt.last === null) return '🎣 offline'
241  if (rt.last.modUpdate?.required === true) return '🎣 update the plugin to play (/fishing status)'
242  const base = rt.last.clientConnected ? '🎣 in game' : rt.openingUntil !== null ? '🎣 opening game' : '🎣 game closed'
243  const { buff } = rt.last.presence
244  const update = rt.last.modUpdate ? ' · update available' : ''
245  return buff.active ? `${base} · ⚡${pct(buff.pct)}${update}` : `${base}${update}`
246}
247
248function asHeartbeatResponse(json: unknown): HeartbeatResponse | null {
249  const res = json as Partial<HeartbeatResponse> | null
250  if (res === null || typeof res !== 'object' || res.ok !== true) return null
251  const presence = res.presence
252  if (typeof presence !== 'object' || presence === null || typeof presence.buff !== 'object' || presence.buff === null) return null
253  return res as HeartbeatResponse
254}
255
256// ─── identity ──────────────────────────────────────────────────────────────
257
258/** ~/.claudefishing, where the identity and the switch live. */
259async function homeDir($: EngineInterface): Promise<string> {
260  // $.fs does not expand "~" (it resolves against the session cwd): build it from HOME.
261  const override = await $.env.get('CLAUDEFISHING_HOME')
262  if (override) return override.replace(/\/+$/, '')
263  const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE')) ?? '.'
264  return `${home}/.claudefishing`
265}
266
267async function identityPath($: EngineInterface): Promise<string> {
268  return `${await homeDir($)}/identity.json`
269}
270
271function parseIdentity(text: string): Identity | null {
272  try {
273    const parsed = JSON.parse(text) as Partial<Identity>
274    if (typeof parsed.secret === 'string' && /^[0-9a-f]{64}$/.test(parsed.secret)) {
275      return { secret: parsed.secret, createdAt: Number(parsed.createdAt) || 0 }
276    }
277  } catch {
278    // corrupt
279  }
280  return null
281}
282
283async function readIdentity($: EngineInterface, path: string): Promise<Identity | 'missing' | 'corrupt'> {
284  if (!(await $.fs.exists(path))) return 'missing'
285  return parseIdentity(await $.fs.read(path)) ?? 'corrupt'
286}
287
288// Never leaves a half-written identity.json, and never replaces one: other sessions may be minting at the same moment.
289async function createIdentity($: EngineInterface, path: string): Promise<void> {
290  const identity: Identity = { secret: hex(crypto.getRandomValues(new Uint8Array(32))), createdAt: await $.clock.now() }
291  const text = `${JSON.stringify(identity, null, 2)}\n`
292  const tmp = `${path}.${hex(crypto.getRandomValues(new Uint8Array(6)))}.tmp`
293  await $.fs.write(tmp, text)
294  await $.process.run(['chmod', '600', tmp]).catch(() => undefined) // $.fs has no chmod
295  // link(2) fails when identity.json exists: of two sessions minting at once the first link wins, and both read it back.
296  const linked = await $.process.run(['ln', tmp, path]).catch(() => null)
297  await $.process.run(['rm', '-f', tmp]).catch(() => undefined)
298  if (linked === null && !(await $.fs.exists(path))) await $.fs.write(path, text) // no ln on this system
299}
300
301async function loadIdentity($: EngineInterface, rt: Runtime, path: string): Promise<Identity> {
302  const existing = await readIdentity($, path)
303  if (typeof existing === 'object') return existing
304  // An owner-only folder first, so the secret is never readable by others, even before its chmod.
305  const dir = path.slice(0, Math.max(0, path.lastIndexOf('/')))
306  if (dir !== '') await $.process.run(['mkdir', '-p', '-m', '700', dir]).catch(() => undefined)
307  if (existing === 'corrupt') {
308    // Moved aside, not overwritten: it may still hold a secret worth recovering by hand.
309    const aside = `${path}.corrupt-${await $.clock.now()}`
310    const moved = await $.process.run(['mv', path, aside]).catch(() => null)
311    if (moved?.exitCode === 0) rt.identityNote = `the unreadable one was kept as ${aside}`
312  }
313  await createIdentity($, path)
314  const created = await readIdentity($, path)
315  if (typeof created === 'object') return created
316  throw new Error(`could not create ${path}`)
317}
318
319async function loadIdentitySafely($: EngineInterface, rt: Runtime): Promise<Identity | null> {
320  try {
321    rt.identityPath ??= await identityPath($)
322    rt.identity = await loadIdentity($, rt, rt.identityPath)
323    rt.identityError = null
324  } catch (err) {
325    rt.identityError = errorText(err)
326    rt.identityLoad = null // the next caller tries again
327  }
328  return rt.identity
329}
330
331function ensureIdentity($: EngineInterface, rt: Runtime): Promise<Identity | null> {
332  rt.identityLoad ??= loadIdentitySafely($, rt)
333  return rt.identityLoad
334}
335
336// ─── the switch ────────────────────────────────────────────────────────────
337// /fishing on|off for the whole machine, in ~/.claudefishing/fishing.json. Plugins
338// before 0.3.0 kept it as `enabled` in $.store, which is one file per install (the
339// marketplace's, a hand-loaded copy's): each install's store is kept in step with
340// the file, so their sessions go on and off with it too. `switchRev` stamps the flip
341// a store was last brought to; `enabled` changed under that same stamp is an older
342// plugin's /fishing on|off, which counts as one flip more.
343
344function isSwitch(value: unknown): value is FishingSwitch {
345  const s = value as Partial<FishingSwitch> | null
346  return typeof s === 'object' && s !== null && typeof s.on === 'boolean' && Number.isSafeInteger(s.rev) && (s.rev as number) >= 0
347}
348
349function isSameSwitch(a: FishingSwitch, b: FishingSwitch): boolean {
350  return a.on === b.on && a.rev === b.rev
351}
352
353/** The file; FIRST_SWITCH while there is none, null when it does not read as a switch (being written, or edited by hand). */
354async function readSwitchFile($: EngineInterface, rt: Runtime): Promise<FishingSwitch | null> {
355  rt.fishingPath ??= `${await homeDir($)}/fishing.json`
356  if (!(await $.fs.exists(rt.fishingPath))) return FIRST_SWITCH
357  try {
358    const parsed: unknown = JSON.parse(await $.fs.read(rt.fishingPath))
359    return isSwitch(parsed) ? { on: parsed.on, rev: parsed.rev } : null
360  } catch {
361    return null
362  }
363}
364
365// Whole or not at all: other sessions read it every few seconds.
366async function writeSwitchFile($: EngineInterface, rt: Runtime, fishing: FishingSwitch): Promise<void> {
367  rt.fishingPath ??= `${await homeDir($)}/fishing.json`
368  const text = `${JSON.stringify({ on: fishing.on, rev: fishing.rev })}\n`
369  const tmp = `${rt.fishingPath}.${hex(crypto.getRandomValues(new Uint8Array(6)))}.tmp`
370  await $.fs.write(tmp, text)
371  const moved = await $.process.run(['mv', tmp, rt.fishingPath]).catch(() => null)
372  if (moved?.exitCode === 0) return
373  await $.process.run(['rm', '-f', tmp]).catch(() => undefined)
374  await $.fs.write(rt.fishingPath, text) // no mv on this system
375}
376
377/** This install's store, as plugins before 0.3.0 read it. `enabled` goes first: a stamp never covers a value it does not stand for. */
378async function syncStore($: EngineInterface, fishing: FishingSwitch): Promise<void> {
379  await $.store.set('enabled', fishing.on)
380  await $.store.set('switchRev', fishing.rev)
381}
382
383/** The machine's switch, with what an older plugin in this install did to it since; this install's store follows it. */
384async function loadSwitch($: EngineInterface, rt: Runtime): Promise<FishingSwitch> {
385  const file = await readSwitchFile($, rt)
386  if (file === null) return rt.fishing
387  const enabled = await $.store.get('enabled')
388  const stamp = await $.store.get('switchRev')
389  const stored = typeof enabled === 'boolean' ? enabled : null
390  let fishing = file
391  if (Number.isSafeInteger(stamp)) {
392    const rev = stamp as number
393    // An older plugin flipped `enabled` under the stamp: one flip more. A stamp ahead of the file: the file was lost.
394    if (rev === file.rev && stored !== null && stored !== file.on) fishing = { on: stored, rev: file.rev + 1 }
395    else if (rev > file.rev) fishing = { on: stored !== false, rev }
396  } else if (stored === false && isSameSwitch(file, FIRST_SWITCH)) {
397    fishing = { on: false, rev: 1 } // turned off before 0.3.0: the first flip
398  }
399  if (!isSameSwitch(fishing, file)) await writeSwitchFile($, rt, fishing)
400  if (stored !== fishing.on || stamp !== fishing.rev) await syncStore($, fishing)
401  rt.fishing = fishing
402  return fishing
403}
404
405/** /fishing on|off: one flip more, for every session of the machine (and, with the next beat, the server). */
406async function flip($: EngineInterface, rt: Runtime, on: boolean): Promise<FishingSwitch> {
407  const before = await loadSwitch($, rt)
408  const fishing = { on, rev: before.rev + 1 }
409  await writeSwitchFile($, rt, fishing)
410  await syncStore($, fishing)
411  rt.fishing = fishing
412  return fishing
413}
414
415/** The server's switch, when newer than this session's: a lost file, or the same flip settled the other way. True when taken. */
416async function adoptServerSwitch($: EngineInterface, rt: Runtime, theirs: unknown): Promise<boolean> {
417  if (!isSwitch(theirs)) return false
418  const ours = rt.fishing
419  if (theirs.rev < ours.rev || (theirs.rev === ours.rev && theirs.on === ours.on)) return false
420  const fishing = { on: theirs.on, rev: theirs.rev }
421  await writeSwitchFile($, rt, fishing)
422  await syncStore($, fishing)
423  rt.fishing = fishing
424  return true
425}
426
427// ─── HTTP ──────────────────────────────────────────────────────────────────
428
429// $.http.fetch has no timeout or signal: race it against $.clock.sleep (the fetch is abandoned, not aborted).
430async function postJson($: EngineInterface, rt: Runtime, path: string, secret: string, body: unknown, timeoutMs: number): Promise<Reply> {
431  const request = $.http
432    .fetch(`${rt.serverUrl}${path}`, {
433      method: 'POST',
434      headers: { 'content-type': 'application/json', authorization: `Bearer ${secret}` },
435      body: JSON.stringify(body),
436    })
437    .then(
438      (res): Reply => {
439        let json: unknown
440        try {
441          json = JSON.parse(res.text)
442        } catch {
443          return { ok: false, error: res.ok ? 'the answer was not JSON' : `HTTP ${res.status}`, status: res.status }
444        }
445        if (res.ok) return { ok: true, json }
446        const code = (json as { error?: unknown } | null)?.error
447        if (typeof code !== 'string') return { ok: false, error: `HTTP ${res.status}`, status: res.status }
448        return { ok: false, error: `HTTP ${res.status} ${code}`, status: res.status, code }
449      },
450      (err: unknown): Reply => ({ ok: false, error: errorText(err) }),
451    )
452  const timeout = $.clock.sleep(timeoutMs).then((): Reply => ({ ok: false, error: `no answer within ${timeoutMs / 1000} s` }))
453  return Promise.race([request, timeout])
454}
455
456// ─── heartbeats ────────────────────────────────────────────────────────────
457
458async function heartbeatBody($: EngineInterface, rt: Runtime, sessionId: string, now: number): Promise<HeartbeatRequest> {
459  const step = rt.activity.step
460  const lastActiveAt = rt.activity.lastActiveAt
461  return {
462    sessionId,
463    enabled: rt.enabled,
464    model: step?.model ?? (await $.session.model().catch(() => null)),
465    // Effort is only known from a real request (absent on models without effort), so it is
466    // null until this session's first turn; the buff only exists after a turn anyway.
467    effort: step?.effort ?? null,
468    working: isWorking(rt, now),
469    activeAgoMs: lastActiveAt === null ? null : Math.max(0, now - lastActiveAt),
470    modVersion: MOD_VERSION,
471    fishing: { on: rt.fishing.on, rev: rt.fishing.rev },
472    work: rt.work,
473  }
474}
475
476function applyReply(rt: Runtime, reply: Reply): HeartbeatResponse | null {
477  const res = reply.ok ? asHeartbeatResponse(reply.json) : null
478  rt.link = res !== null ? 'online' : 'offline'
479  rt.linkError = res !== null ? null : reply.ok ? 'unexpected answer' : reply.error
480  rt.last = res ?? rt.last
481  if (res?.clientConnected === true) rt.openingUntil = null // the awaited window joined
482  return res
483}
484
485/** This session is quiet from now on (the server knows: `offSentRev` is the off it heard). */
486function stopReporting(rt: Runtime, offSentRev: number | null): void {
487  rt.enabled = false
488  rt.lastSentWorking = null
489  rt.openingUntil = null
490  rt.offSentRev = offSentRev
491  rt.link = 'unknown'
492  rt.last = null
493}
494
495async function beat($: EngineInterface, rt: Runtime): Promise<void> {
496  // /fishing on|off may have run in another session, or another copy of the plugin, on this machine.
497  const fishing = await loadSwitch($, rt).catch(() => rt.fishing)
498  if (!fishing.on) {
499    // The server hears of an off once from each session (and again, while it never answers).
500    if (rt.enabled || rt.offSentRev !== fishing.rev) await turnOff($, rt)
501    $.ui.status('🎣 off')
502    return
503  }
504  rt.enabled = true
505  const sessionId = await $.session.id()
506  const identity = await ensureIdentity($, rt)
507  if (identity === null) {
508    rt.link = 'offline'
509    rt.linkError = `no identity: ${rt.identityError}`
510    $.ui.status(statusLine(rt))
511    return
512  }
513  const now = await $.clock.now()
514  const body = await heartbeatBody($, rt, sessionId, now)
515  if (isRecentlyEnded(rt, sessionId, now) || !rt.enabled) return // session.end or /fishing off ran meanwhile
516  rt.lastSentWorking = body.working
517  rt.lastBeatAt = now
518  // Before it goes, so idle sessions ticking meanwhile leave the machine's keepalive to this beat.
519  await stampKeepalive($, rt, sessionId, now).catch(() => undefined)
520  const seq = ++rt.sentSeq
521  const request = postJson($, rt, '/api/heartbeat', identity.secret, body, HTTP_TIMEOUT_MS)
522  rt.inFlight = request
523  const reply = await request
524  if (rt.inFlight === request) rt.inFlight = null
525  if (seq < rt.appliedSeq || !rt.enabled) return
526  rt.appliedSeq = seq
527  const res = applyReply(rt, reply)
528  if (res !== null) {
529    rt.answeredAt = now
530    await shareAnswer($, rt, now, res).catch(() => undefined)
531  }
532  // The server has a newer switch: off, this session goes quiet at once (the server already said so).
533  if (res !== null && (await adoptServerSwitch($, rt, res.fishing).catch(() => false)) && !rt.fishing.on) {
534    stopReporting(rt, rt.fishing.rev)
535    $.ui.status('🎣 off')
536    return
537  }
538  $.ui.status(statusLine(rt))
539  toastUpdate($, rt)
540  if (rt.isAutoOpenPending && rt.link === 'online') void autoOpenSafely($, rt)
541}
542
543/** Once per newer plugin, a toast with the command that updates this one. */
544function toastUpdate($: EngineInterface, rt: Runtime): void {
545  const update = rt.link === 'online' ? rt.last?.modUpdate : null
546  if (!update || rt.updateToastFor === update.latest) return
547  rt.updateToastFor = update.latest
548  const why = update.required ? `the game needs ${update.min ?? update.latest} or newer` : `${update.latest} is out`
549  $.ui.toast(`🎣 claudefishing ${MOD_VERSION}: ${why}. Update in a terminal: ${update.command}`)
550}
551
552async function runBeat($: EngineInterface, rt: Runtime): Promise<void> {
553  try {
554    await beat($, rt)
555  } catch (err) {
556    rt.link = 'offline'
557    rt.linkError = errorText(err)
558    $.ui.status(statusLine(rt))
559  }
560}
561
562// Beat as soon as this dispatch is over (a timer runs outside the hook's budget); one queued at a time.
563function queueBeat($: EngineInterface, rt: Runtime): void {
564  if (rt.isBeatQueued) return
565  rt.isBeatQueued = true
566  $.clock.after(0, () => {
567    rt.isBeatQueued = false
568    void runBeat($, rt)
569  })
570}
571
572// ─── one keepalive per machine ─────────────────────────────────────────────
573// The game needs two things of a machine: that Claude Code is open on it, and which sessions
574// Claude worked in within the buff window. Every beat is stamped in keepalive.json before it goes,
575// and an idle session keeps the machine alive only when that stamp is a keepalive old: the session
576// that kept it alive last goes on, any other claims it first (sessions finding it due together
577// would all beat otherwise). Every answer lands in answer.json unless a newer one is there, and the
578// quiet sessions' status lines follow it. Both are written in place: a torn read costs one extra
579// beat, or one tick of an older status line.
580
581/** `claim`: a session taking the keepalive over wrote it, and beats if it is still its claim CLAIM_SETTLE_MS later. */
582type KeepaliveStamp = { at: number; sessionId: string; claim?: string }
583
584type SharedAnswer = { at: number; modVersion: string; answer: HeartbeatResponse }
585
586/** Claude works in this session, or did within the buff window: the server counts it for the buff, so it keeps itself alive. */
587function isReporting(rt: Runtime, now: number): boolean {
588  const last = rt.activity.lastActiveAt
589  return isWorking(rt, now) || (last !== null && now - last < INACTIVE_MS)
590}
591
592/** When a session of the machine last beat (or claimed the keepalive), and which; null with no stamp, or one that does not read. */
593async function readKeepalive($: EngineInterface, rt: Runtime): Promise<KeepaliveStamp | null> {
594  rt.keepalivePath ??= `${await homeDir($)}/keepalive.json`
595  try {
596    if (!(await $.fs.exists(rt.keepalivePath))) return null
597    const { at, sessionId, claim } = JSON.parse(await $.fs.read(rt.keepalivePath)) as Partial<Record<keyof KeepaliveStamp, unknown>>
598    if (typeof at !== 'number' || !Number.isFinite(at) || typeof sessionId !== 'string') return null
599    return { at, sessionId, ...(typeof claim === 'string' ? { claim } : {}) }
600  } catch {
601    return null
602  }
603}
604
605async function stampKeepalive($: EngineInterface, rt: Runtime, sessionId: string, now: number, claim?: string): Promise<void> {
606  rt.keepalivePath ??= `${await homeDir($)}/keepalive.json`
607  const stamp: KeepaliveStamp = { at: now, sessionId, ...(claim !== undefined ? { claim } : {}) }
608  await $.fs.write(rt.keepalivePath, `${JSON.stringify(stamp)}\n`)
609}
610
611/** Claims the machine's keepalive: true when no claim written meanwhile (or beat sent) replaced this one. */
612async function claimKeepalive($: EngineInterface, rt: Runtime, sessionId: string, now: number): Promise<boolean> {
613  const claim = hex(crypto.getRandomValues(new Uint8Array(6)))
614  await stampKeepalive($, rt, sessionId, now, claim)
615  await $.clock.sleep(CLAIM_SETTLE_MS)
616  return (await readKeepalive($, rt))?.claim === claim
617}
618
619/** The last answer any session of the machine got, and the file's text; null with none, or one that does not read. */
620async function readAnswer($: EngineInterface, rt: Runtime): Promise<(SharedAnswer & { text: string }) | null> {
621  rt.answerPath ??= `${await homeDir($)}/answer.json`
622  try {
623    if (!(await $.fs.exists(rt.answerPath))) return null
624    const text = await $.fs.read(rt.answerPath)
625    const shared = JSON.parse(text) as Partial<SharedAnswer> | null
626    const answer = asHeartbeatResponse(shared?.answer)
627    if (answer === null || typeof answer.serverTime !== 'number' || typeof shared?.at !== 'number' || typeof shared.modVersion !== 'string') return null
628    return { at: shared.at, modVersion: shared.modVersion, answer, text }
629  } catch {
630    return null
631  }
632}
633
634/** Unless a newer answer is there already: two sessions' answers can land in either order (of two as old, the later one written stays). */
635async function shareAnswer($: EngineInterface, rt: Runtime, now: number, answer: HeartbeatResponse): Promise<void> {
636  const current = await readAnswer($, rt)
637  if (current !== null && current.answer.serverTime > answer.serverTime) return
638  rt.answerPath ??= `${await homeDir($)}/answer.json`
639  const text = `${JSON.stringify({ at: now, modVersion: MOD_VERSION, answer } satisfies SharedAnswer)}\n`
640  await $.fs.write(rt.answerPath, text)
641  rt.answerText = text
642}
643
644/** Its own keepalive while the server counts it for the buff; past that, the machine's, once no session has beaten for one. */
645async function isKeepaliveDue($: EngineInterface, rt: Runtime, now: number): Promise<boolean> {
646  if (rt.lastBeatAt !== null && now - rt.lastBeatAt < KEEPALIVE_MS) return false
647  if (isReporting(rt, now)) return true
648  const stamp = await readKeepalive($, rt)
649  if (stamp !== null && now - stamp.at < KEEPALIVE_MS) return false
650  const sessionId = await $.session.id()
651  return stamp?.sessionId === sessionId || claimKeepalive($, rt, sessionId, now)
652}
653
654// A quiet session shows the newest answer of the machine: one it has not shown yet, no older than its
655// own. With none for a session's lifetime on the server, no session of the machine reaches the game:
656// offline, as the one trying to will be.
657async function followAnswer($: EngineInterface, rt: Runtime, now: number): Promise<void> {
658  const shared = await readAnswer($, rt)
659  if (shared !== null && shared.text !== rt.answerText && shared.answer.serverTime >= (rt.last?.serverTime ?? -Infinity)) {
660    rt.answerText = shared.text
661    // An answer to another version of the plugin says nothing about this one's updates.
662    const modUpdate = shared.modVersion === MOD_VERSION ? (shared.answer.modUpdate ?? null) : (rt.last?.modUpdate ?? null)
663    rt.last = { ...shared.answer, modUpdate }
664    rt.link = 'online'
665    rt.linkError = null
666    rt.answeredAt = shared.at
667    if (rt.last.clientConnected) rt.openingUntil = null
668    $.ui.status(statusLine(rt))
669    toastUpdate($, rt)
670    if (rt.isAutoOpenPending) void autoOpenSafely($, rt)
671    return
672  }
673  const answeredAt = Math.max(rt.answeredAt ?? -Infinity, shared?.at ?? -Infinity)
674  if (rt.link === 'online' && now - answeredAt > ANSWER_STALE_MS) {
675    rt.link = 'offline'
676    rt.linkError = 'no session on this machine got an answer lately'
677    $.ui.status(statusLine(rt))
678  }
679}
680
681// A keepalive once one is due (isKeepaliveDue), a beat as soon as a turn goes stale (STALE_TURN_MS)
682// and stops counting as work, and one every tick while a window this session opened has not joined
683// (the server only says so in a beat's answer); otherwise the status line follows the machine's
684// answers. The switch is read every tick (no network): a flip anywhere on the machine reaches this
685// session within one.
686async function tick($: EngineInterface, rt: Runtime): Promise<void> {
687  const now = await $.clock.now()
688  if (rt.openingUntil !== null && now >= rt.openingUntil) {
689    rt.openingUntil = null // it never joined: "game closed" again, and keepalives only
690    $.ui.status(statusLine(rt))
691  }
692  const fishing = await loadSwitch($, rt).catch(() => rt.fishing)
693  if (fishing.on !== rt.enabled) return runBeat($, rt)
694  if (!fishing.on) {
695    // An off the server never answered goes again, a keepalive after the last try.
696    if (rt.offSentRev !== fishing.rev && (rt.lastBeatAt === null || now - rt.lastBeatAt >= KEEPALIVE_MS)) await runBeat($, rt)
697    return
698  }
699  const isStale = rt.lastSentWorking === true && !isWorking(rt, now)
700  if (rt.openingUntil === null && !isStale && !(await isKeepaliveDue($, rt, now))) return followAnswer($, rt, now).catch(() => undefined)
701  // Counted as a beat even if it cannot be sent (offline): the next try is a keepalive later.
702  rt.lastBeatAt = now
703  await runBeat($, rt)
704}
705
706function startTimer($: EngineInterface, rt: Runtime): void {
707  rt.timer?.cancel()
708  // Keeps ticking while off too (no network then) so a /fishing on from another session resumes this one.
709  rt.timer = $.clock.every(TICK_MS, () => void tick($, rt))
710}
711
712// /fishing on, and /fishing open when off: a flip on, which every session of the machine follows.
713async function turnOn($: EngineInterface, rt: Runtime): Promise<void> {
714  await flip($, rt, true)
715  rt.enabled = true
716  startTimer($, rt)
717  await runBeat($, rt)
718}
719
720// The server drops this session now rather than after its TTL. An off it has not heard of yet (a
721// newer flip) drops every session of the machine and closes the game window the machine opened.
722async function turnOff($: EngineInterface, rt: Runtime): Promise<void> {
723  const fishing = rt.fishing
724  stopReporting(rt, rt.offSentRev)
725  if (rt.inFlight !== null) await Promise.race([rt.inFlight, $.clock.sleep(OFF_INFLIGHT_WAIT_MS)]) // land it first
726  const identity = rt.identity
727  const sessionId = await $.session.id()
728  const now = await $.clock.now()
729  rt.lastBeatAt = now // a try that gets no answer goes again a keepalive later
730  if (identity === null || isRecentlyEnded(rt, sessionId, now)) return
731  const body = await heartbeatBody($, rt, sessionId, now)
732  const reply = await postJson($, rt, '/api/heartbeat', identity.secret, { ...body, enabled: false }, HTTP_TIMEOUT_MS)
733  if (!reply.ok) return
734  // Heard (a server from before the switch hears it too): sent. A newer switch there wins; on, the next tick resumes.
735  rt.offSentRev = fishing.rev
736  await adoptServerSwitch($, rt, asHeartbeatResponse(reply.json)?.fishing).catch(() => false)
737}
738
739/** `work`: the ended conversation's totals (after a /clear, this process already counts the next one's). */
740async function sendEnding($: EngineInterface, rt: Runtime, sessionId: string, timeoutMs: number, work: WorkReport = rt.work): Promise<void> {
741  const now = await $.clock.now()
742  markEnded(rt, sessionId, now)
743  const identity = rt.identity
744  if (!rt.enabled || identity === null) return
745  const body = await heartbeatBody($, rt, sessionId, now)
746  await postJson($, rt, '/api/heartbeat', identity.secret, { ...body, work, working: false, ending: true }, timeoutMs)
747}
748
749/** A conversation's run as it ended: its totals, and the MCP servers they count. */
750type EndedRun = { work: WorkReport; mcpSeen: string[] }
751
752// After a /clear or an in-session /resume the process goes on as another conversation: beat as it
753// first, then end the old id (with its totals), so the server never sees this machine without a session.
754async function switchSession($: EngineInterface, rt: Runtime, endedId: string, ended: EndedRun): Promise<void> {
755  let sessionId = await $.session.id()
756  for (let i = 0; sessionId === endedId && i < SWITCH_POLLS; i++) {
757    await $.clock.sleep(SWITCH_POLL_MS)
758    sessionId = await $.session.id()
759  }
760  if (sessionId === endedId) {
761    // Still the same conversation: nothing to end, and its run goes on.
762    rt.work = ended.work
763    rt.mcpSeen = ended.mcpSeen
764    await $.state.set(WORK, rt.work).catch(() => undefined)
765    await $.state.set(MCP_SEEN, rt.mcpSeen).catch(() => undefined)
766    return runBeat($, rt)
767  }
768  const endedAt = rt.endedAt.get(sessionId)
769  if (endedAt !== undefined) {
770    // Back to a conversation ended moments ago: the server ignores its beats until its tombstone passes.
771    const wait = endedAt + SERVER_TOMBSTONE_MS + 500 - (await $.clock.now())
772    if (wait > 0) await $.clock.sleep(wait)
773    rt.endedAt.delete(sessionId)
774  }
775  await runBeat($, rt)
776  await sendEnding($, rt, endedId, HTTP_TIMEOUT_MS, ended.work)
777}
778
779async function switchSessionSafely($: EngineInterface, rt: Runtime, endedId: string, ended: EndedRun): Promise<void> {
780  try {
781    await switchSession($, rt, endedId, ended)
782  } catch {
783    // the timer beats as the new id; the server's TTL drops the old one
784  }
785}
786
787// Every sign of Claude going on: stamps the activity and ends any wait on the person.
788async function touch($: EngineInterface, rt: Runtime, turn: Partial<FishingTurn> = {}, step?: FishingStep): Promise<void> {
789  const turnBefore = rt.turn
790  rt.turn = { ...turnBefore, waiting: false, ...turn }
791  const isTurnChanged = rt.turn.running !== turnBefore.running || rt.turn.waiting !== turnBefore.waiting || rt.turn.agents !== turnBefore.agents
792  const now = await $.clock.now()
793  const before = rt.activity
794  const wasInactive = before.lastActiveAt === null || now - before.lastActiveAt >= INACTIVE_MS
795  const isStepChanged = step !== undefined && (before.step?.model !== step.model || before.step?.effort !== step.effort)
796  rt.activity = { lastActiveAt: now, step: step ?? before.step }
797  await $.state.set(ACTIVITY, rt.activity)
798  if (isTurnChanged) await $.state.set(TURN, rt.turn)
799  if (rt.enabled && (wasInactive || isStepChanged || isWorking(rt, now) !== rt.lastSentWorking)) queueBeat($, rt)
800}
801
802// Hooks on the turn's path must never fail because of the game.
803async function touchSafely($: EngineInterface, rt: Runtime, turn?: Partial<FishingTurn>, step?: FishingStep): Promise<void> {
804  try {
805    await touch($, rt, turn, step)
806  } catch {
807    // the next timer beat carries whatever this missed
808  }
809}
810
811// Waiting stamps no activity: the buff runs out 5 minutes after Claude last did something.
812async function setWaiting($: EngineInterface, rt: Runtime, waiting: boolean): Promise<void> {
813  if (rt.turn.waiting === waiting) return
814  rt.turn = { ...rt.turn, waiting }
815  await $.state.set(TURN, rt.turn)
816  if (rt.enabled && isWorking(rt, await $.clock.now()) !== rt.lastSentWorking) queueBeat($, rt)
817}
818
819async function setWaitingSafely($: EngineInterface, rt: Runtime, waiting: boolean): Promise<void> {
820  try {
821    await setWaiting($, rt, waiting)
822  } catch {
823    // the next timer beat carries it
824  }
825}
826
827// The last step's effort belongs to the old model: unknown until the new one runs a step.
828async function switchModel($: EngineInterface, rt: Runtime, model: string): Promise<void> {
829  rt.activity = { ...rt.activity, step: { model, effort: null } }
830  await $.state.set(ACTIVITY, rt.activity)
831  if (rt.enabled) queueBeat($, rt)
832}
833
834async function switchModelSafely($: EngineInterface, rt: Runtime, model: string): Promise<void> {
835  try {
836    await switchModel($, rt, model)
837  } catch {
838    // the next step reports the model
839  }
840}
841
842// ─── what Claude did ───────────────────────────────────────────────────────
843// Totals for game mechanics, on the beats the session sends anyway (the server may use them or not):
844// numbers only, never what Claude read or wrote. Kept in $.state, so a hot reload goes on counting
845// the same run; a /clear or /resume starts a new one.
846
847function noTokens(): WorkTokens {
848  return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
849}
850
851function newWork(): WorkReport {
852  return {
853    run: hex(crypto.getRandomValues(new Uint8Array(6))),
854    steps: 0,
855    tokens: noTokens(),
856    byModel: {},
857    turns: { count: 0, aborted: 0, failed: 0, ms: 0 },
858    agentRuns: 0,
859    tools: {},
860    mcpServers: 0,
861    measure: null,
862  }
863}
864
865/** The totals a previous load of the module kept, with any field it did not have yet at zero. */
866function restoreWork(kept: Partial<WorkReport> | undefined): WorkReport {
867  if (typeof kept?.run !== 'string') return newWork()
868  const fresh = newWork()
869  return {
870    ...fresh,
871    ...kept,
872    run: kept.run,
873    tokens: { ...fresh.tokens, ...kept.tokens },
874    byModel: { ...kept.byModel },
875    turns: { ...fresh.turns, ...kept.turns },
876    tools: { ...kept.tools },
877  }
878}
879
880/** A count from the engine; anything not a finite, non-negative number counts as none. */
881function amount(value: unknown): number {
882  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
883}
884
885function addTokens(to: WorkTokens, usage: TurnUsage): void {
886  to.input += amount(usage.input_tokens)
887  to.output += amount(usage.output_tokens)
888  to.cacheRead += amount(usage.cache_read_input_tokens)
889  to.cacheWrite += amount(usage.cache_creation_input_tokens)
890}
891
892/** A tool as the game hears of it: Claude Code's own by name, never which MCP server or plugin. */
893function toolKind(tool: string): string {
894  if (tool.startsWith('mcp__')) return 'mcp'
895  return BUILTIN_TOOLS.has(tool) ? tool : 'other'
896}
897
898/** A response's model and tokens; a request no response answered counts for nothing. */
899function countStep(work: WorkReport, result: TurnStepResult): void {
900  if (result.stopReason === null && result.usage === null) return
901  work.steps += 1
902  const usage = result.usage
903  if (usage === null) return
904  addTokens(work.tokens, usage)
905  const model = typeof usage.model === 'string' && /^[a-z0-9][a-z0-9.:@-]{0,99}$/i.test(usage.model) ? usage.model : 'other'
906  const byModel = work.byModel[model] ?? (Object.keys(work.byModel).length < WORK_MODELS ? (work.byModel[model] = { steps: 0, ...noTokens() }) : null)
907  if (byModel === null) return
908  byModel.steps += 1
909  addTokens(byModel, usage)
910}
911
912/** True when the call went to an MCP server the run had not seen: `seen` holds the names, the report only how many. */
913function countTool(work: WorkReport, seen: string[], tool: string): boolean {
914  const kind = toolKind(tool)
915  const key = work.tools[kind] !== undefined || Object.keys(work.tools).length < WORK_TOOLS ? kind : 'other'
916  work.tools[key] = (work.tools[key] ?? 0) + 1
917  const server = kind === 'mcp' ? tool.split('__')[1] : undefined
918  if (!server || seen.includes(server) || seen.length >= WORK_MCP_SERVERS) return false
919  seen.push(server)
920  work.mcpServers += 1
921  return true
922}
923
924function countTurn(work: WorkReport, e: TurnCompleteInput): void {
925  if (e.agentId !== undefined) {
926    work.agentRuns += 1
927    return
928  }
929  work.turns.count += 1
930  if (e.isAborted) work.turns.aborted += 1
931  if (e.reason === 'error' || e.reason === 'refusal') work.turns.failed += 1
932  work.turns.ms += amount(e.durationMs)
933}
934
935function measureOf(e: SessionMeasureInput): WorkMeasure {
936  return {
937    contextPct: typeof e.context?.percent === 'number' && Number.isFinite(e.context.percent) ? e.context.percent : null,
938    contextWindow: amount(e.context?.window),
939    rateLimits: (e.rateLimits ?? []).slice(0, 4).map(limit => ({
940      kind: String(limit.kind).slice(0, 32),
941      percentUsed: amount(limit.percentUsed),
942      resetsAt: typeof limit.resetsAt === 'string' ? limit.resetsAt.slice(0, 40) : null,
943    })),
944    costUsd: typeof e.cost?.usd === 'number' && Number.isFinite(e.cost.usd) ? e.cost.usd : null,
945  }
946}
947
948// Counting never holds up Claude: a failure loses one count, kept in memory for the next beat.
949async function countSafely($: EngineInterface, rt: Runtime, change: (work: WorkReport) => void): Promise<void> {
950  try {
951    change(rt.work)
952    await $.state.set(WORK, rt.work)
953  } catch {
954    // the next count saves it
955  }
956}
957
958async function countToolSafely($: EngineInterface, rt: Runtime, tool: string): Promise<void> {
959  try {
960    const isNewServer = countTool(rt.work, rt.mcpSeen, tool)
961    await $.state.set(WORK, rt.work)
962    if (isNewServer) await $.state.set(MCP_SEEN, rt.mcpSeen)
963  } catch {
964    // the next count saves it
965  }
966}
967
968/** The kept server names, from a previous load of the module; anything else is none. */
969function restoreSeen(kept: unknown): string[] {
970  return Array.isArray(kept) ? kept.filter((name): name is string => typeof name === 'string').slice(0, WORK_MCP_SERVERS) : []
971}
972
973// ─── opening the game ──────────────────────────────────────────────────────
974
975/** A browser /fishing open can be told to use. `app`: it makes app windows (--app, a window with no tabs or address bar). */
976type Browser = { name: string; app: boolean; mac: string; windows: string | null; linux: string | null }
977
978const BROWSERS = {
979  chrome: { name: 'Chrome', app: true, mac: 'com.google.Chrome', windows: 'chrome.exe', linux: 'google-chrome' },
980  edge: { name: 'Edge', app: true, mac: 'com.microsoft.edgemac', windows: 'msedge.exe', linux: 'microsoft-edge' },
981  brave: { name: 'Brave', app: true, mac: 'com.brave.Browser', windows: 'brave.exe', linux: 'brave-browser' },
982  firefox: { name: 'Firefox', app: false, mac: 'org.mozilla.firefox', windows: 'firefox.exe', linux: 'firefox' },
983  safari: { name: 'Safari', app: false, mac: 'com.apple.Safari', windows: null, linux: null },
984} as const satisfies Record<string, Browser>
985
986type BrowserId = keyof typeof BROWSERS
987
988function isBrowserId(value: unknown): value is BrowserId {
989  return typeof value === 'string' && Object.hasOwn(BROWSERS, value)
990}
991
992/** One way of opening the link, and what the reply calls it. */
993type Launch = { argv: string[]; how: string }
994
995/** A PowerShell string literal. */
996function psQuote(text: string): string {
997  return `'${text.replaceAll("'", "''")}'`
998}
999
1000/** Windows: Start-Process returns once the browser starts, finds a bare name as Run would (App Paths), and fails with no dialog. */
1001function powershell(command: string): string[] {
1002  return ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', command]
1003}
1004
1005// The https handler the person picked (UserChoiceLatest on newer Windows 11), and the command it opens links with.
1006const WINDOWS_DEFAULT_BROWSER = [
1007  "$k = 'HKCU:\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\'",
1008  "$id = 'UserChoiceLatest\\ProgId', 'UserChoiceLatest', 'UserChoice' | ForEach-Object { (Get-ItemProperty -LiteralPath ($k + $_) -ErrorAction SilentlyContinue).ProgId } | Where-Object { $_ } | Select-Object -First 1",
1009  "if ($id) { (Get-ItemProperty -LiteralPath ('Registry::HKEY_CLASSES_ROOT\\' + $id + '\\shell\\open\\command') -ErrorAction SilentlyContinue).'(default)' }",
1010].join('; ')
1011
1012// macOS: the app links open in, by its bundle id (Safari when nobody changed it).
1013const MAC_DEFAULT_BROWSER =
1014  "ObjC.import('AppKit'); var app = $.NSWorkspace.sharedWorkspace.URLForApplicationToOpenURL($.NSURL.URLWithString('https://claudefishing.io')); " +
1015  "app.isNil() ? '' : ObjC.unwrap($.NSBundle.bundleWithURL(app).bundleIdentifier)"
1016
1017const LINUX_LAUNCH = 'command -v "$0" >/dev/null || exit 1; "$0" "$@" >/dev/null 2>&1 & pid=$!; sleep 1; kill -0 "$pid" 2>/dev/null || wait "$pid"'
1018
1019/** `browser` opening the link: an app window when it makes them. `exe`: its program on Windows, as the default browser names it. */
1020function launches(browser: Browser, url: string, windows: boolean, exe?: string): Launch[] {
1021  const how = browser.app ? `${/^[AEIOU]/.test(browser.name) ? 'an' : 'a'} ${browser.name} app window` : browser.name
1022  const args = browser.app ? [`--app=${url}`] : [url]
1023  if (windows) {
1024    const program = exe ?? browser.windows
1025    return program === null ? [] : [{ argv: powershell(`Start-Process ${psQuote(program)} ${psQuote(args[0]!)}`), how }]
1026  }
1027  return [
1028    // macOS: -n so --args reach a browser that is already running.
1029    { argv: browser.app ? ['open', '-nb', browser.mac, '--args', ...args] : ['open', '-b', browser.mac, url], how },
1030    // Linux: started in the background, so the call returns. One that is not there, or ends with an
1031    // error within a second, fails; still running, or handed to a running browser (exit 0), it opened.
1032    ...(browser.linux === null ? [] : [{ argv: ['sh', '-c', LINUX_LAUNCH, browser.linux, ...args], how }]),
1033  ]
1034}
1035
1036/** The system's default browser among BROWSERS (and its program on Windows); null when it is another one or cannot be told. */
1037/** What `argv` printed, trimmed; null when it could not run or failed. */
1038async function answerOf($: EngineInterface, argv: string[]): Promise<string | null> {
1039  const result = await $.process.run(argv).catch(() => null)
1040  return result?.exitCode === 0 ? result.stdout.trim() : null
1041}
1042
1043async function defaultBrowser($: EngineInterface, windows: boolean): Promise<{ browser: Browser; exe?: string } | null> {
1044  const find = (match: (b: Browser) => boolean) => Object.values(BROWSERS).find(match) ?? null
1045  if (windows) {
1046    // "C:\Program Files\Google\Chrome\Application\chrome.exe" --single-argument %1
1047    const match = /^"([^"]+)"|^(\S+)/.exec((await answerOf($, powershell(WINDOWS_DEFAULT_BROWSER))) ?? '')
1048    const exe = match?.[1] ?? match?.[2]
1049    const name = exe?.split('\\').pop()?.toLowerCase()
1050    const browser = find(b => b.windows === name)
1051    return browser === null ? null : { browser, exe }
1052  }
1053  // macOS answers with a bundle id. Elsewhere there is no osascript, and xdg-settings names the browser's .desktop file.
1054  const bundle = await answerOf($, ['osascript', '-l', 'JavaScript', '-e', MAC_DEFAULT_BROWSER])
1055  if (bundle !== null) {
1056    const browser = find(b => b.mac.toLowerCase() === bundle.toLowerCase())
1057    return browser === null ? null : { browser }
1058  }
1059  const desktop = await answerOf($, ['xdg-settings', 'get', 'default-web-browser'])
1060  const browser = desktop === null ? null : find(b => `${b.linux}.desktop` === desktop)
1061  return browser === null ? null : { browser }
1062}
1063
1064/** The browser /fishing open was told to use (/fishing open chrome …); null: the system's default. */
1065async function loadOpenWith($: EngineInterface): Promise<BrowserId | null> {
1066  const value = await $.store.get(OPEN_WITH).catch(() => undefined)
1067  return isBrowserId(value) ? value : null
1068}
1069
1070async function openUrl($: EngineInterface, url: string): Promise<string | null> {
1071  const windows = (await $.env.get('OS')) === 'Windows_NT'
1072  const chosen = await loadOpenWith($)
1073  const found = chosen === null ? await defaultBrowser($, windows) : null
1074  // The browser chosen, else the default one (an app window when it makes them); either missing, the link handed to the system.
1075  const tries: Launch[] = [
1076    ...(chosen !== null ? launches(BROWSERS[chosen], url, windows) : []),
1077    ...(found !== null && found.browser.app ? launches(found.browser, url, windows, found.exe) : []),
1078    ...(windows
1079      ? [{ argv: ['rundll32.exe', 'url.dll,FileProtocolHandler', url], how: 'the default browser' }]
1080      : [
1081          { argv: ['open', url], how: 'the default browser' },
1082          { argv: ['xdg-open', url], how: 'the default browser' },
1083        ]),
1084  ]
1085  for (const { argv, how } of tries) {
1086    const result = await $.process.run(argv).catch(() => null)
1087    if (result?.exitCode === 0) return chosen !== null && how === 'the default browser' ? `the default browser (${BROWSERS[chosen].name} did not open)` : how
1088  }
1089  return null
1090}
1091
1092/** How the game opens as the person chose it; null until they did (or when the store cannot be read). */
1093async function loadOpenIn($: EngineInterface): Promise<OpenIn | null> {
1094  const value = await $.store.get(OPEN_IN).catch(() => undefined)
1095  return value === 'app' || value === 'browser' ? value : null
1096}
1097
1098const OPEN_OPTIONS = ['App window', 'Browser link'] as const
1099
1100/** The first /fishing open asks; null when the question was dismissed or nobody could be asked (`claude -p`). */
1101async function askOpenIn($: EngineInterface): Promise<OpenIn | null> {
1102  const question = 'Open claudefishing in an app window, or get a link to open in your own browser?'
1103  const answer = await $.ui.ask(question, { header: 'Open game', options: OPEN_OPTIONS }).catch(() => null)
1104  if (answer === null) return null
1105  // Typed under "Other" too: "app", "browser", "a link", "tab".
1106  if (answer === OPEN_OPTIONS[0] || /^\s*app\b/i.test(answer)) return 'app'
1107  if (answer === OPEN_OPTIONS[1] || /\b(browser|link|tab)\b/i.test(answer)) return 'browser'
1108  return null
1109}
1110
1111/** unreachable: the pair request got no answer at all (worth trying again); failed: anything else that went wrong. */
1112type OpenResult = { kind: 'opened' | 'skipped' | 'failed' | 'unreachable'; text: string }
1113
1114async function openGame($: EngineInterface, rt: Runtime, reason: PairRequest['reason'], openIn: OpenIn): Promise<OpenResult> {
1115  const identity = await ensureIdentity($, rt)
1116  if (identity === null) return { kind: 'failed', text: `no identity file: ${rt.identityError}` }
1117  const request: PairRequest = { sessionId: await $.session.id(), reason }
1118  const reply = await postJson($, rt, '/api/pair', identity.secret, request, HTTP_TIMEOUT_MS)
1119  if (!reply.ok) {
1120    return { kind: reply.status === undefined ? 'unreachable' : 'failed', text: `server unreachable at ${rt.serverUrl} (${reply.error})` }
1121  }
1122  const pair = reply.json as PairResponse | null
1123  if (pair === null || typeof pair !== 'object') return { kind: 'failed', text: 'unexpected answer from the server' }
1124  if (pair.ok === false) {
1125    const why = { 'client-connected': 'the game is already open', 'recently-opened': 'the game was opened moments ago', 'fishing-off': 'fishing is off on this machine' }
1126    return { kind: 'skipped', text: why[pair.skipped] ?? why['recently-opened'] }
1127  }
1128  if (typeof pair.code !== 'string') return { kind: 'failed', text: 'unexpected answer from the server' }
1129  const url = `${rt.serverUrl}/#pair=${encodeURIComponent(pair.code)}`
1130  let text: string
1131  if (openIn === 'browser') {
1132    const copied = (await $.ui.copy({ text: url }).catch(() => null))?.isCopied === true
1133    text = `open this link in your browser${copied ? ' (copied)' : ''}; it works once, for 2 minutes:\n${url}`
1134  } else {
1135    const how = await openUrl($, url)
1136    if (how === null) return { kind: 'failed', text: `could not start a browser; open ${url} yourself (the link works once, for 2 minutes)` }
1137    text = `opened in ${how}`
1138  }
1139  // The window takes a few seconds to load and join: until a beat's answer says it did, the line says so.
1140  rt.openingUntil = (await $.clock.now()) + OPENING_MS
1141  $.ui.status(statusLine(rt))
1142  return { kind: 'opened', text }
1143}
1144
1145// Once per session (the terminal at start, the desktop app or VS Code when it attaches); done once the
1146// server answered the pair, even with a skip. One it could not reach is tried again on a later beat.
1147async function autoOpen($: EngineInterface, rt: Runtime): Promise<void> {
1148  if (!rt.autoOpen || !rt.enabled || rt.isAutoOpening) return
1149  rt.isAutoOpening = true
1150  try {
1151    const { value: state } = await $.state.get(AUTO_OPEN)
1152    if (state === 'done') {
1153      rt.isAutoOpenPending = false
1154      return
1155    }
1156    // With the browser chosen there is no window to open, and a link nobody asked for would only expire.
1157    const result: OpenResult =
1158      (await loadOpenIn($)) === 'browser' ? { kind: 'skipped', text: 'the game opens with /fishing open' } : await openGame($, rt, 'auto', 'app')
1159    rt.isAutoOpenPending = result.kind === 'unreachable'
1160    await $.state.set(AUTO_OPEN, rt.isAutoOpenPending ? 'pending' : 'done')
1161    if (result.kind === 'opened') $.ui.toast(`🎣 game ${result.text}`)
1162  } finally {
1163    rt.isAutoOpening = false
1164  }
1165}
1166
1167async function autoOpenSafely($: EngineInterface, rt: Runtime): Promise<void> {
1168  try {
1169    await autoOpen($, rt)
1170  } catch {
1171    // /fishing open is always there
1172  }
1173}
1174
1175// ─── /fishing ──────────────────────────────────────────────────────────────
1176
1177function buffText(res: HeartbeatResponse): string {
1178  const { buff, working } = res.presence
1179  if (!buff.active) return `off (Claude idle; ${pct(buff.potentialPct)} while working)`
1180  if (working || buff.expiresAt === null) return `⚡${pct(buff.pct)} while Claude works`
1181  const minutes = Math.max(1, Math.ceil((buff.expiresAt - res.serverTime) / 60_000))
1182  return `⚡${pct(buff.pct)}, ${minutes} min left`
1183}
1184
1185// Older servers send neither field: one machine, its own cat.
1186function devicesText(res: HeartbeatResponse, cat: PlayerSummary): string {
1187  const machines = typeof res.machines === 'number' ? res.machines : 1
1188  if (res.linked === true) return `${machines} play ${cat.name}, this one linked (/fishing unlink leaves)`
1189  if (machines > 1) return `${machines} play ${cat.name} (/fishing link adds another)`
1190  return `this one only (/fishing link plays ${cat.name} on another too)`
1191}
1192
1193async function statusReport($: EngineInterface, rt: Runtime): Promise<string> {
1194  const now = await $.clock.now()
1195  const body = await heartbeatBody($, rt, await $.session.id(), now)
1196  const link = rt.link === 'online' ? 'online' : rt.link === 'offline' ? `offline (${rt.linkError ?? 'no answer'})` : 'not connected'
1197  const lines = [`fishing ${rt.enabled ? 'on' : 'off'} · server ${rt.serverUrl} · ${rt.enabled ? link : 'not reporting'}`]
1198  const res = rt.enabled && rt.link === 'online' ? rt.last : null
1199  if (res !== null) {
1200    const update = res.modUpdate
types/version.ts 3 lines
1// Checked against plugin.json and release.json by scripts/check-release.mjs.
2export const MOD_VERSION = '0.4.2'
3
types/protocol.ts 200 lines
1// Public HTTP contract between the Claude Code mod and the hosted game.
2// The game vendors this file from a pinned public commit; it has no game-rule dependencies.
3// Additive fields must remain compatible with older deployed servers.
4
5export type EffortLevel = 'low' | 'medium' | 'high' | 'xhigh' | 'max'
6
7export type HeartbeatRequest = {
8  /** The Claude Code session id. */
9  sessionId: string
10  /** false = fishing is off (`fishing` says for the whole machine): drop this session now. */
11  enabled: boolean
12  /** true on session end: drop this session now. */
13  ending?: boolean
14  /** Model as the session reports it ("claude-opus-5-5", "opus", ...). */
15  model: string | null
16  /** Reasoning effort ('low'…'max'), a token budget, or null when unknown. */
17  effort: string | number | null
18  /** A turn is running right now. */
19  working: boolean
20  /** ms since the last sign of Claude working (sender's clock), null if never this session. */
21  activeAgoMs: number | null
22  /** Mod version: a session older than the server's minimum counts for nothing. */
23  modVersion?: string
24  /**
25   * The machine's /fishing on|off as this session read it. The server keeps each machine's newest
26   * (highest `rev`): while it is off no session of the machine counts, an older plugin's included,
27   * and the flip to off closes the game window the machine opened. Absent from plugins before 0.3.0.
28   */
29  fishing?: FishingSwitch
30  /**
31   * What Claude has done in this session, in numbers only, for game mechanics (a server may use it or
32   * not). Rides on the beats the session sends anyway. Absent from plugins before 0.4.0.
33   */
34  work?: WorkReport
35}
36
37/** Token counts by kind, as the API counts them. */
38export type WorkTokens = { input: number; output: number; cacheRead: number; cacheWrite: number }
39
40/**
41 * What Claude has done in a session since `run` began, in numbers only: never a prompt, answer, file,
42 * path, command or tool input. The totals only grow while `run` stays the same, so a server takes the
43 * change since the last report of that run (a lost beat loses nothing, a repeated one adds nothing);
44 * a new `run` starts them over from zero (a /clear or /resume, a reload that lost them).
45 */
46export type WorkReport = {
47  /** A random id for these totals. */
48  run: string
49  /** Model requests answered, the main loop's and subagents' (turn.step). */
50  steps: number
51  /** What they used, summed. */
52  tokens: WorkTokens
53  /** The same by the model that answered ("claude-opus-5-5"), for the first 8 models; requests past those count only above. */
54  byModel: Record<string, WorkTokens & { steps: number }>
55  /** Main-loop turns ended (turn.complete): of them, how many were interrupted and how many ended on an error or a refusal; their wall-clock ms. */
56  turns: { count: number; aborted: number; failed: number; ms: number }
57  /** Subagent runs ended (turn.complete with an agent id). */
58  agentRuns: number
59  /** Tool calls by tool, subagents' included: Claude Code's own by name ("Bash", "Read"), any MCP server's as "mcp", anything else as "other". */
60  tools: Record<string, number>
61  /** How many different MCP servers those "mcp" calls went to; which ones never leaves the machine. */
62  mcpServers: number
63  /** The session's latest measure (session.measure); null before the first. */
64  measure: WorkMeasure | null
65}
66
67/** The session's figures as its status line has them, at the last measure. */
68export type WorkMeasure = {
69  /** The context window's fill, 0 to 100; null until a response reported one. */
70  contextPct: number | null
71  /** The context window's size, in tokens. */
72  contextWindow: number
73  /** The plan's rate-limit windows (`five_hour`, `seven_day`, a gateway's `spend_limit`): percent used, and when each resets (ISO 8601); empty off a subscription. */
74  rateLimits: { kind: string; percentUsed: number; resetsAt: string | null }[]
75  /** What the session has cost so far, in US dollars; null where the host keeps no ledger. */
76  costUsd: number | null
77}
78
79/**
80 * /fishing on|off for a whole machine, shared by every session and every copy of the plugin on it.
81 * `rev` counts the flips: of two, the higher is the newer.
82 */
83export type FishingSwitch = { on: boolean; rev: number }
84
85/**
86 * The plugin is older than the latest (`latest`). `required`: older than the server's minimum
87 * (`min`), so the game is locked until it is updated with `command`.
88 */
89export type ModUpdate = { required: boolean; latest: string; min: string | null; command: string }
90
91export type PresenceView = {
92  playable: boolean
93  sessionCount: number
94  /** Display label of the highest model, e.g. "Opus 5.5". */
95  model: string | null
96  effort: EffortLevel | null
97  working: boolean
98  buff: BuffView
99  /** A live session of the cat runs an older plugin than the latest. Absent from servers before 0.2.0. */
100  modUpdate?: ModUpdate | null
101}
102
103export type BuffView = {
104  active: boolean
105  /** Fraction, 0.08 = +8%. 0 while inactive. */
106  pct: number
107  potentialPct: number
108  /** Server-clock ms; null while a turn runs or while inactive. */
109  expiresAt: number | null
110}
111
112export type HeartbeatResponse = {
113  ok: true
114  serverTime: number
115  /** A game window for this machine's cat is connected right now (opened from any of its machines). */
116  clientConnected: boolean
117  /** The cat this machine plays; null until it has joined the game once. */
118  player: PlayerSummary | null
119  /** Machines that play this cat, this one included: more than 1 once devices are linked. */
120  machines: number
121  /** This machine plays a cat linked from another machine rather than its own. */
122  linked: boolean
123  /** From the sessions of every machine that plays this cat. */
124  presence: PresenceView
125  /** This session's plugin is behind (null: up to date). Absent from servers before 0.2.0. */
126  modUpdate?: ModUpdate | null
127  /**
128   * The machine's switch as the server keeps it. Newer than the plugin's (a higher `rev`, or the
129   * same flip settled the other way), it is the switch. Absent from servers before 0.3.0.
130   */
131  fishing?: FishingSwitch
132}
133
134/** What a cat has to show for itself, as the mod prints it. */
135export type PlayerSummary = { name: string; level: number; rank: string; money: number; totalCaught: number }
136
137export type PairRequest = {
138  sessionId: string
139  /**
140   * 'auto' (session start) is skipped while a window is connected, one was opened moments ago, or
141   * fishing is off on the machine; 'manual' always pairs, and turns an off machine on.
142   */
143  reason: 'auto' | 'manual'
144}
145
146export type PairResponse =
147  | { ok: true; code: string; expiresAt: number }
148  | { ok: false; skipped: 'client-connected' | 'recently-opened' | 'fishing-off' }
149
150// A machine plays its own cat (the player whose id is the machine's) until it
151// claims a link code made on a machine that plays another one; from then on
152// it plays that cat, and `/api/unlink` returns it to its own.
153
154/** A one-time code another machine claims to play this machine's cat, until `expiresAt` (server clock); a newer code replaces it. `no-player`: this machine has no cat yet. */
155export type LinkResponse = { ok: true; code: string; expiresAt: number; serverTime: number; player: PlayerSummary } | { ok: false; error: 'no-player' }
156
157export type LinkClaimRequest = {
158  code: string
159  /** The session asking: it counts for the new cat at once, the machine's other sessions with their next beat. */
160  sessionId: string
161  /** Switch even though this machine's cat has progress (the person chose to). */
162  replace: boolean
163}
164
165/** What becomes of the cat a machine stops playing: `unlink` brings it back to this machine, `shared` other machines still play it, `lost` no machine does. */
166export type LeftBehind = 'unlink' | 'shared' | 'lost'
167
168/**
169 * `has-progress`: this machine's cat has caught or bought something and
170 * `replace` was false; nothing changed and the code still works.
171 * `invalid-code` comes with HTTP 400, an over-budget claim with 429.
172 */
173export type LinkClaimResponse =
174  | {
175      ok: true
176      /** This machine already played that cat: nothing changed. */
177      already: boolean
178      player: PlayerSummary
179      /** The cat this machine played before; null if it had none (or `already`). */
180      previous: PlayerSummary | null
181      /** Machines that play the cat now, this one included. */
182      machines: number
183      /** This machine's game window was open and reopens as the new cat. */
184      windowSwitched: boolean
185    }
186  | { ok: false; error: 'has-progress'; current: PlayerSummary; target: PlayerSummary; afterwards: LeftBehind }
187  | { ok: false; error: 'invalid-code' }
188
189export type UnlinkRequest = {
190  sessionId: string
191  /** Unlink even though no other machine plays the linked cat (the person chose to). */
192  confirm: boolean
193}
194
195/** `last-device`: no other machine plays the linked cat, which has progress, and `confirm` was false. */
196export type UnlinkResponse =
197  | { ok: true; player: PlayerSummary | null; previous: PlayerSummary | null; windowSwitched: boolean }
198  | { ok: false; error: 'not-linked' }
199  | { ok: false; error: 'last-device'; current: PlayerSummary }
200
types/index.d.ts 60 lines
1/** Claude's activity in this session, as the mod saw it (kept in $.state so a hot reload keeps it). */
2export type FishingActivity = {
3  /** Clock ms of the last turn start, model request, tool call or return, or turn end; null before any. */
4  lastActiveAt: number | null
5  /** Model and effort of the last main-loop model request (or the model a /model switched to); null before the first. */
6  step: FishingStep | null
7}
8
9export type FishingStep = {
10  model: string
11  /** Absent on models without effort, and unknown after a /model until the next step: null. */
12  effort: string | number | null
13}
14
15/** Whether Claude is mid-turn (kept in $.state so a hot reload mid-turn keeps it). */
16export type FishingTurn = {
17  /** A main-loop turn is running (turn.start until its turn.complete). */
18  running: boolean
19  /** Subagents seen stepping whose turn.complete has not come yet. */
20  agents: string[]
21  /** Claude waits on the person: a permission prompt, a question, plan approval or an MCP form. */
22  waiting: boolean
23}
24
25/** pending: the auto-open could not reach the server and is tried again; done: the server answered it. */
26export type AutoOpenState = 'pending' | 'done'
27
28/** What Claude did in this session, as every heartbeat carries it (protocol.ts's WorkReport); kept in $.state so a hot reload goes on counting. */
29export type FishingWork = {
30  run: string
31  steps: number
32  tokens: FishingTokens
33  byModel: Record<string, FishingTokens & { steps: number }>
34  turns: { count: number; aborted: number; failed: number; ms: number }
35  agentRuns: number
36  tools: Record<string, number>
37  mcpServers: number
38  measure: {
39    contextPct: number | null
40    contextWindow: number
41    rateLimits: { kind: string; percentUsed: number; resetsAt: string | null }[]
42    costUsd: number | null
43  } | null
44}
45
46export type FishingTokens = { input: number; output: number; cacheRead: number; cacheWrite: number }
47
48declare module 'claude-code' {
49  interface PluginState {
50    'claudefishing': {
51      activity: FishingActivity
52      turn: FishingTurn
53      autoOpen: AutoOpenState
54      work: FishingWork
55      /** The MCP servers the run's tool calls went to, by name: kept here to count `work.mcpServers`, never sent. */
56      mcpSeen: string[]
57    }
58  }
59}
60