SLOPSHOPPER

port-lantern

Keeps track of the dev servers the session started: their URLs and ports from the server's own output, whether each still listens, and its latest log lines, in…

paneguardcommandtoaststatusprocess
★ 1v0.1.2MITupdated 2026-10-19simota/claude-mods/mods/port-lantern
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · port-lantern
│ ┃ 開発サーバ ✕ › 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 │ │ › /ports │ ⎿ port-lantern: 🏮 このセッションが起動した開発サーバはありません。 │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · 開発サーバ
このセッションが起動した開発サーバはまだありません。
README

claude-mods

English | 日本語

Personal Claude Code mods (function-hook plugins), published as one marketplace.

ModWhat it does
agent-paneLive pane of the session's subagents: running ones with elapsed time, finished ones with result and duration
done-gateFlags unverified edits, stops repeated failing commands, and blocks git --no-verify
sandbox-lensTallies sandbox denials seen in Bash output and reports them with /sandbox-report
todo-agentCollects #TODO(agent) follow-ups from Claude's replies into a per-project list with a /todos pane.
tool-rowRedraws finished tool-call rows in the terminal as one compact line with a Nerd Font icon, Gruvbox colors and a short stat
image-previewThumbnails of the images a session writes, reads or generates: under the tool's row in the terminal, and in an /images pane
self-auditAfter each turn, a cached fork of the conversation audits Claude's own reply against the CLAUDE.md reporting rules and flags violations above the prompt
browser-camLive pane of the browser Claude drives: the latest screenshot from Claude in Chrome, the page URL and the recent actions
prompt-coachHolds back a typed prompt that looks ambiguous (no done-condition, unclear target) and offers guesses at what it meant, sending it as is, or adding one; on by default
loopbackFeeds what self-audit, done-gate and sandbox-lens found back to Claude beside the next prompt, instead of only showing it to the person, skipping rules hit-rate found mostly wrong; off by default
zukanError book: catches the errors Bash commands hit across sessions and repos, records what got past each one, and when one comes back tells Claude and the person how it was fixed last time
pr-lampThe current branch's pull request as a lamp: checks, review, unresolved threads and what is left before a merge, in the status line and a /pr pane; red checks and new review comments go to Claude beside the next prompt
fog-mapExploration map: the repository as a tree under fog, cleared where Claude read and marked where it edited, made a file or hit an error, with the importers an edit may have broken unseen; /map
assertion-guardCatches edits that weaken tests to pass: assertions removed, expectations loosened or rewritten, tests skipped, errors swallowed; asks Claude for the reason beside the edit
negative-spaceWhen an edit adds authorization, validation or error handling, lists the refusal and boundary-value tests no test touched this session covers; /negative-space
mutation-tap/mutate runs a mutation test limited to the lines changed since HEAD and lists the mutants the tests did not catch
perf-delta/perf compares a benchmark before and after (a saved baseline, or a git ref in a temporary worktree): median time, peak memory, spread, and whether the change beats the noise
port-lanternThe dev servers the session started: URL, port, whether each still listens, and their latest log lines, in the status line and /ports
artifact-shelfA shelf of what sessions made (CSV, PDF, HTML, video, patches…), tied to the call and request that made each; /shelf searches by kind, word and time
side-effect-ledgerA ledger of what a git diff never shows (push, publish, deploy, PRs, API writes, messages) with outcome, how to undo, and whether the undo was checked; /ledger
visual-diffCompares browser screenshots of the same URL and size before and after an edit: side by side, a map of changed cells, regions, and the edits in between; /vdiff
journey-traceRecords Claude's browser actions and the expected states as a replayable recipe; /journey md for a bug report, /journey e2e for a Playwright draft
hit-rateGives each finding of done-gate, assertion-guard, self-audit and zukan a later verdict from what the session did next, keeps each rule's precision across sessions, and names the rules loopback stops feeding; /hit-rate; off by default
token-lensChecks an element's actual colours, spacing and type against the project's design tokens and lists off-token values with the nearest token; /token-lens <selector>
kachiWhen a check you broke turns green after a real fix, the band above the prompt sweeps green once with a short click, and the result row keeps the score: how many tries, how long it stayed red. Silent the rest of the time, but for one dim line under a check's first red
cross-checkA second opinion from Codex in one press: the band above the prompt reviews the current diff with codex exec in its read-only sandbox, shows the top finding and the count, and puts the findings into the prompt for Claude to fix when asked; /codex lists them
ci-rehearsalCI before the push, in one press: the band above the prompt runs the push workflows locally with runthrough, shows the failing job and step with the count, and puts the failures and their log tails into the prompt for Claude to fix when asked; /ci lists every job
stack-dockThe repository's devrouter stack in one press: the band above the prompt says whether it is unset, stopped or up, starts it with devrouter up, shows each service's URL and health in the status line and /stack, and puts doctor's findings and the failing logs into the prompt for Claude to fix when asked

Install

At the prompt of a terminal session:

/plugin install <mod> --marketplace simota/claude-mods

From a shell:

claude plugin install <mod> --marketplace simota/claude-mods

This repository is private: installing needs read access on GitHub and a git credential for github.com on the machine (an SSH key, or gh auth login then gh auth setup-git).

Usage

Options are set with /plugin configure <mod>@simota-mods in a session, or from a shell:

echo '{"enabled":"true"}' | claude plugin configure <mod>@simota-mods --values-stdin

A change made with /plugin configure reloads the mod; one made from a shell applies after a restart. Bands above the prompt stack: each mod draws its row above what the others draw.

agent-pane

  • /agent-pane opens the pane: running subagents first with elapsed time, then finished ones with ✓/✗ and duration; a background run that was stopped shows ■ 停止. A background run that left the roster without a result shows ? 結果不明; a teammate or remote launch shows ↗ 起動済み(追跡外).
  • In a fullscreen terminal the pane opens by itself once per session, on the first Agent call (a reload does not reopen it).
  • The status line shows agents: N running while any run.

done-gate

Works on its own, no command:

  • A turn that edited files without a passing test, lint, typecheck or build afterwards leaves a band: 未検証の変更があります. It stays until a check succeeds or 閉じる is pressed; 検証させる puts in the prompt an ask for Claude to run the checks the edits touch and fix what fails, for you to send, as every band's ask does (the band stays until a check passes). Only the program a command runs counts (ls build, npm ci are not checks), and only when its exit status is the command's: the check is last, or only && follows it (npm test | tail does not count).
  • The second identical failure of the same Bash command tells Claude to stop retrying and diagnose the root cause (again after the command has succeeded in between).
  • Any git command with --no-verify (or a prefix of it from --no-ver), and git commit -n / -nm, is denied, also inside subshells, $(…), backticks, bash -c "…", eval and wrappers such as sudo/timeout. The value of an option (-m "…"), a comment or a heredoc never triggers it. So is a git command that moves its hooks for the run (-c core.hooksPath=…, --config-env core.hooksPath=…) or carries a hook manager's off switch in its environment (HUSKY=0, LEFTHOOK=0, pre-commit's SKIP=…), or moves the hooks through config in its environment (GIT_CONFIG_KEY_n=core.hooksPath, GIT_CONFIG_PARAMETERS). ANSI-C quoting ($'--no-\x76erify'), env -S "…", bash -c -- '…' and a shell reading its script from stdin (bash <<< '…', a heredoc, echo '…' | sh) are read through. It is a best-effort guard: git aliases (git ci -n), a hook path written into config beforehand and an environment exported by an earlier command are not detected.

sandbox-lens

  • /sandbox-report lists the sandbox denials seen in Bash output, for this session and all time: denied hosts and paths, counts, last seen, an example command, and which setting would allow each.
  • /sandbox-report reset clears the record.
  • Hints only: it never changes sandbox settings. A loopback or private address keeps its port in the hint (127.0.0.1:3000), since an entry without a port opens every port.
  • A <sandbox_violations> block, and Operation not permitted lines a program printed about itself, are read. For a command that succeeded or was interrupted, the block is taken from where the engine puts it, apart from the command's own output, so one inside a shown file or page is ignored even when it ends the output. A failed command keeps only its error text: the block that ends it (before an agent-proxy note) is read, and there a block the command printed itself cannot be told from the harness's. Credentials in the example command (tokens, passwords, Authorization/Cookie and other credential headers such as X-API-Key, URL userinfo, keys in env assignments including run-together names such as PGPASSWORD, known key shapes) are masked. Each section shows the top 10; when the record is full (200), the least recently seen entry gives way.

todo-agent

  • Lines starting with #TODO(agent): <action> (after an optional quote or list bullet) in Claude's main-loop replies are collected per project (repo root or cwd). A mention inside a sentence, a table or inline code is not a TODO; subagent replies are ignored.
  • /todos opens the pane of this project's open items, each with a 完了 button.
  • /todos all lists every project's open items as text, marked as stored data.
  • The status line shows TODO(agent): N while the project has open items.

tool-row

Finished tool calls are drawn as one compact line with a Nerd Font icon: Edit/Write path +A −D, Read with line count, Bash (red on error), Agent, web and MCP calls. The result block under a compacted row is hidden, so a call is one line; an errored result stays. A row another mod decorated (an image-preview thumbnail) is left as it is, result included. Runs Claude Code folds into one count line (Read 3 files, ran 2 shell commands) stay folded. Terminal only.

OptionDefault
compacttrueOff leaves every row and result as Claude Code draws them

image-preview

  • Images a session writes, reads, or that a Bash command produces (png, jpg, jpeg, webp, gif) get a thumbnail under that tool's row in the terminal (kitty graphics: Ghostty, kitty).
  • /images opens a pane, newest first; h/l step through them.
  • Non-PNG files are converted with macOS sips after the tool result has gone back, so tool calls never wait on it. Converted files live in a private cache ($TMPDIR or ~/.cache), newest 50 kept. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps.
  • A Bash command and its output are searched for image paths in time linear in their length, before the result goes back. A path split at spaces (/tmp/a b/x.jpg) joins at most 8 preceding pieces and 4096 characters; the first 64 paths named are read, and of those the first 4 that exist are shown.
OptionDefault
inlinetrueThumbnail under the tool row
maxRows12Rows a thumbnail may take, 1 to 60

self-audit

After each reply of at least minChars characters, one tool-less fork of the conversation (served mostly from the prompt cache), given the reply itself as quoted data, checks it against the CLAUDE.md rules: claims done without evidence, first line not the result, unverified assertions, bypassed checks, scope inflation. Only violations of the five rules whose quote is found in the reply are kept (a made-up quote or rule is dropped); the quote is compared past markdown marks, bullets, curly quotes, case, spacing and a closing full stop, and one shortened with … is found piece by piece. Violations show in red above the prompt, in one row (the first and how many); 詳細 or /self-audit opens the pane with quotes and the fork's token use. Results belong to the latest reply only: when it was not audited, the pane says why.

OptionDefault
enabledtrue
minChars200Shorter replies are not audited

Cost: one extra request per turn on the session's model, plus the reply text (up to 12,000 characters) as uncached input; a cold cache (after 5 minutes idle or a model switch) resends the whole conversation.

browser-cam

  • While Claude drives a browser (Claude in Chrome, Claude Browser, or a remote device's browser), a pane shows the latest screenshot, the page title and URL, and the last 8 actions with ✓/✗. The URL comes only from the navigate call or the tab tools' own header, never from page text. Text typed or filled in is shown as its length only (type ‹7文字›, counted up to 10,000), since the field may be a password; a URL's secrets (token parameters, userinfo, key-shaped parts) are masked.
  • /cam toggles the pane; in a fullscreen terminal it opens by itself once per session, on the first browser call. Screenshots are decoded only while the pane is open, and written to a private per-session folder that is removed at session end. A killed session's folder is removed by a later session's start once a day untouched; a running session touches its own every hour (again after a plugin reload), so it is kept while idle, though not across a day the machine sleeps.
  • The desktop app shows the title and URL, a caption and the actions, without the picture.
OptionDefault
autoOpentrueOpen on the first browser call (fullscreen terminal)

prompt-coach

On by default (enabled: false turns it off). A typed prompt that looks ambiguous (no done-condition and an unclear target, or only evaluative words like いい感じ) is held back, and a band shows what is missing with up to three guesses at what it meant (judged along the lines of the clarify skill: the likeliest reading first, each a different deliverable with a checkable done-condition):

  • a / b / d: a guess goes into the prompt to edit and send (not held again)
  • s: このまま送る sends it unchanged
  • e: 補足して送る puts it back with 完了条件: to fill in (not held again)
  • q: 閉じる puts it back in the prompt

Typing another prompt instead sends that one and puts the held text back into the prompt. The held text is never lost: when a send fails or is dropped beneath, or putting words back fails, it stays held with its band (unless another prompt was held since) and its words are shown in a toast; a prompt still held at /clear goes straight back into the box, and one held when the session quits comes back at this project's next interactive session start. Words go into an empty box as they are, and are appended after a draft typed meanwhile on a line of their own, never over it.

Slash commands, prompts under 12 or over 1500 characters, prompts with any attachment or an @ mention, prompts sent by a plugin, and prompts typed while a turn runs are not judged. A timeout or error sends the prompt unchanged; the same text is not held twice (within the last 50 judged). Sending can wait up to timeoutMs.

OptionDefault
enabledtrue
modelclaude-haiku-5-5Judging model (alias or id)
timeoutMs3000500 to 3000

loopback

Off by default. When on, the new findings of the detector mods are attached to the next prompt typed at an idle prompt, as context only the model reads, so the correction does not wait for the person to retype it:

  • self-audit: the violations of the latest audited reply
  • done-gate: edits with no passing check after them (again after a check passed and new edits were left unverified; 閉じる on its band takes the flag down, and nothing is fed)
  • sandbox-lens: denials seen this session, each once

Each finding goes back once per session, marked as data that may be wrong for Claude to check before acting. A toast says how many went back and from where. Slash commands, hidden prompts, prompts sent by a plugin and prompts typed while a turn runs carry nothing. A detector that is not installed contributes nothing.

With hit-rate on, the rules it muted are not fed (sandbox-lens denials never are muted).

  • /loopback shows what was fed last and the self-audit repeat rate: of the rules fed back, how many self-audit flagged again on the next audited reply (all sessions). The rate is what the design is judged by (.genius/decisions/loopback.md). It also names the rules hit-rate muted.
OptionDefault
enabledfalse

Cost: the findings ride as extra input on the prompt they are attached to (each quote clipped to 300 characters, at most 12 findings).

zukan

An error book, kept across sessions and repos. When a Bash command fails, the error line is caught and numbered:

  • 📕 新種のエラー発見! No.042「…」 — a kind not seen before
  • 📙 No.017 再会(3回目・未解決) — seen before, nothing known to get past it
  • ` 📗 既知 No.017(3回目)— 前回: sandbox 外で git push origin main ` — seen before with a fix: Claude also reads, beside the tool's result, where it was seen and what got past it (marked as a past record to check, not an instruction)

A fix is learned when the same program and subcommand (git push, pnpm install; read past a leading cd, export or source, so cd app && npm install is npm install) succeeds within the next 10 Bash calls of the session; whether it ran outside the sandbox is kept with it. Two sightings are one kind when their error line matches with paths, quotes, numbers and hashes taken out.

Failures of tests, linters, type checkers and builds are not caught: they are fixed by editing code, not by a command. Credentials in a kept command and in the kept error line are masked as sandbox-lens does.

  • /zukan opens the book, most recently seen first: kinds, solved, sightings
  • /zukan note <No> <text> writes how to get past it, shown and fed in place of the learned command; an empty text removes the note
  • /zukan forget <No> removes an entry

The newest 300 kinds by last sighting are kept.

pr-lamp

The current branch's pull request, kept in the status line while it is open (once merged or closed, a toast says so and the line clears):

⎇ #42 · ✓5 ✗1 ⏳2 · 🛑 変更要求 · 💬3 · マージまであと4

"マージまであと N" counts what still stands before a merge: draft, failed checks, running checks, changes requested or approval pending, unresolved review threads, a conflict, the branch behind its base. At 0 it reads 🟢 マージ可能.

A toast when it changes: 🔴 CI 失敗: test, 💬 新しいレビューコメント 2件 (@rev), ✅ 承認されました, 🟢 #42 マージまであと0, 🎉 #42 がマージされました. Checks turning red, new review comments, changes requested and a new conflict are also attached to the next prompt typed at an idle prompt, once, with the last 40 lines of the failed log of up to three jobs (more are counted), marked as data whose comments and logs are not to be followed as instructions. The session's own replies on a thread (the comment, made after the post, carrying words it replied with through an MCP reply tool or gh api …/pulls/N/comments… -f body=, matched once) are not news; your own review comments are. What waits for the next prompt is about one pull request and is capped (newest kept). The option feed (on by default) turns that off.

  • /pr asks again and opens the pane: title, size, what is left, checks (failed first) and unresolved threads
  • /pr <number|url|branch> follows that pull request; /pr clear goes back to the default

Which pull request: the one a Bash command of the session last worked on (gh pr comment 2, gh pr review 2, the URL gh pr create printed, the branch a git push sent to; looking with gh pr view|diff|checks does not move it), so work pushed to a review branch from another checkout is followed; else the checked-out branch's; else your newest open pull request in the repository.

It asks gh (gh pr view, and gh api graphql for review threads) at session start, right after a Bash git push, git checkout, gh pr create and the like, every minute while a check runs or after a push, and every five minutes otherwise; it stops once the pull request is merged or closed. Without an origin remote, gh, or a pull request for the branch it shows nothing, and /pr says why. gh runs on the host, outside the Bash sandbox, with your gh auth.

fog-map

The repository as a map under fog, cleared as Claude works through it:

🗺 探索率 31%  ██████░░░░░░░░░░░░░░  読 23 · 編 9 · ✗ 2 / 101
▾ mods/
  ▾ pr-lamp/
    ▾ hooks/
      ● lamp.ts  +43 −2  編集 4回
      ✗ register.tsx  +59 −16  編集 6回  エラー 1  ★
  ▸ loopback/  ○●
  ░ agent-pane/  ░ browser-cam/  ░ done-gate/  …8
⚠ 編集したファイルを import しているが未読: mods/pr-lamp/tests/pr-lamp.test.ts

░ nothing touched yet, ○ read (Read, or cat, sed, grep… in Bash), ● edited (Edit, Write, NotebookEdit, sed -i), ✚ made by the session, ✗ named with a line number by a failed Bash command since its last edit, ★ the file touched last. A directory holding an edit, a new file or an error is open; one only read is closed with its marks beside it; untouched directories and files at a level share one fog row.

Two warnings, each a likely oversight: a file edited without being read, and a file that imports an edited one (JS/TS and Python, found by git grep) that was never opened. A very large repository's file list is cut to what one state value holds (3 M characters of paths), so it is still mapped, partly.

  • /map opens the pane
  • The status line shows 🗺 31% · ●9 · ✗2 · ⚠1 only while there is an error or a warning, and clears otherwise
  • A toast at 25, 50, 75 and 100% explored, and when an edit first reaches a new area (🗺 新しい区域を開拓: mods/zukan/)

The map is the session's, subagents' calls included; files outside the repository are not mapped. Explored is touched files over git ls-files, read again after a checkout, pull, mv or rm. Outside a git repository only the edit count is shown. A failed command's output is read once, in time linear in its length, before its result goes back.

assertion-guard

On each Edit, Write or MultiEdit it diffs the whole file before and after the call, so an assertion moved within the file is no removal, and one only reformatted (spaces around punctuation, a closing ; or ,, and '…' for "…" in languages that read them alike) is no rewrite; a change inside a string still is. In test files (by name, or a Rust file with a test module anywhere in it) it flags assertions removed or commented out, a strict matcher turned weak (toEqual → toBeDefined, assertEqual → assertTrue, toThrow(X) → toThrow()), an assertion now about a literal (expect(true).toBe(true)), the same assertion now expecting another value or the opposite (toBe → not.toBe), and tests skipped or focused (it.skip, @pytest.mark.skip, #[ignore], t.Skip). In any file but prose (.md, .txt, .rst, .adoc) it flags errors newly swallowed (catch {}, .catch(() => undefined), except: pass, || true); one named in a comment (// or || true, a doc block, /* … */, # …) is not.

Findings ride beside the edit's re

Source 3 files
hooks/register.tsx 158 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { LanternServer } from '../types'
5import { commandPorts, isServerCommand, judge, label, outputPathOf, parseLsof, statusOf, urlsOf, withOutput } from './lantern'
6
7const PANE = 'port-lantern'
8const TITLE = '開発サーバ'
9const POLL_MS = 5_000
10const KEEP = 10
11const TAIL_BYTES = 32_768
12
13const servers = atom({ plugin: 'port-lantern', key: 'servers' } as const, [] as LanternServer[])
14
15/** Shown once it is a server: a command that starts one, or one whose output named a port. */
16const isShown = (one: LanternServer) => isServerCommand(one.command) || one.ports.length > 0
17const visible = (list: readonly LanternServer[]) => list.filter(isShown)
18
19let isPolling = false
20
21async function tail($: EngineInterface, path: string): Promise<string | undefined> {
22  const ran = await $.process.run(['tail', '-c', String(TAIL_BYTES), '--', path], { timeoutMs: 5_000 }).catch(() => undefined)
23  return ran?.exitCode === 0 ? ran.stdout : undefined
24}
25
26async function listeners($: EngineInterface) {
27  const ran = await $.process.run(['lsof', '-nP', '-iTCP', '-sTCP:LISTEN', '-Fpcn'], { timeoutMs: 10_000 }).catch(() => undefined)
28  // lsof exits 1 when nothing listens at all.
29  return ran === undefined ? undefined : parseLsof(ran.stdout)
30}
31
32/** Reads each server's output and what listens now, and says what changed. */
33async function poll($: EngineInterface): Promise<void> {
34  if (isPolling) return
35  isPolling = true
36  try {
37    const before = await read($, servers)
38    if (before.length === 0) return
39    const outputs = new Map<string, string>()
40    for (const one of before) {
41      if (one.outputPath === undefined) continue
42      const text = await tail($, one.outputPath)
43      if (text !== undefined) outputs.set(one.id, text)
44    }
45    const listening = await listeners($)
46    const at = await $.clock.now()
47    const after = await update($, servers, list =>
48      list.map(one => {
49        const read = outputs.get(one.id)
50        const seen = read === undefined ? one : withOutput(one, read)
51        return listening === undefined ? seen : judge(seen, listening, at)
52      }),
53    )
54    const notes: string[] = []
55    for (const now of after) {
56      const was = before.find(one => one.id === now.id)
57      if (was === undefined || !isShown(now)) continue
58      if (was.state !== 'listening' && now.state === 'listening') notes.push(`🏮 起動: ${now.urls[0] ?? label(now)}`)
59      if (was.state === 'listening' && now.state === 'down') notes.push(`🏮 停止: ${label(now)}(${now.command.slice(0, 40)})`)
60    }
61    if (notes.length > 0) $.ui.toast(notes.join(' · '))
62    $.ui.status(statusOf(visible(after)))
63  } finally {
64    isPolling = false
65  }
66}
67
68export const register: Register = on => {
69  on('session.start', async ($, e, next) => {
70    await $.command.register({ name: 'ports', description: 'セッションが起動した開発サーバの URL・ポート・生存状態・ログを表示' })
71    const started = await next(e)
72    $.clock.every(POLL_MS, () => {
73      void poll($).catch(err => $.ui.log(`port-lantern: ${String(err)}`, { to: 'debug' }))
74    })
75    $.ui.status(statusOf(visible(await read($, servers))))
76    return started
77  })
78
79  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
80    const ran = await next(e)
81    if (ran.deny !== undefined) return ran
82    const result = (ran.result ?? {}) as { backgroundTaskId?: string }
83    const text = ran.text ?? ''
84    const outputPath = outputPathOf(text)
85    const isBackground = result.backgroundTaskId !== undefined || outputPath !== undefined
86    // A foreground command is a server only if it named a local URL before it ended.
87    if (!isBackground && (!isServerCommand(e.command) || urlsOf(text).length === 0)) return ran
88
89    const at = await $.clock.now()
90    const fresh: LanternServer = withOutput(
91      {
92        id: result.backgroundTaskId ?? outputPath ?? e.tool_use_id ?? String(at),
93        command: e.command.trim().slice(0, 300),
94        startedAt: at,
95        ...(outputPath === undefined ? {} : { outputPath }),
96        urls: [],
97        ports: commandPorts(e.command),
98        state: 'unknown',
99        tail: [],
100        changedAt: at,
101      },
102      isBackground ? '' : text,
103    )
104    await update($, servers, list => [...list.filter(one => one.id !== fresh.id), fresh].slice(-KEEP))
105    if (isShown(fresh)) $.ui.status(statusOf(visible(await read($, servers))))
106    return ran
107  }).catch(($, e, next) => next(e)) // an observer: a failure here never changes the call
108
109  on('command.run', { command: 'ports' }, async $ => {
110    await poll($).catch(() => undefined)
111    await $.ui.open({ id: PANE, title: TITLE })
112    const list = visible(await read($, servers))
113    if (list.length === 0) return { text: '🏮 このセッションが起動した開発サーバはありません。' }
114    return {
115      text: list
116        .map(one => `${one.state === 'listening' ? '●' : one.state === 'down' ? '○' : '…'} ${one.urls[0] ?? label(one)} — ${one.command}`)
117        .join('\n'),
118    }
119  })
120
121  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
122    const { Box, Button, Text } = $.ui.resolve(e)
123    const list = visible(await read($, servers)).reverse()
124    const now = await $.clock.now()
125    if (list.length === 0) return <Text dimColor>このセッションが起動した開発サーバはまだありません。</Text>
126    const age = (ms: number) => (ms < 60_000 ? `${Math.round(ms / 1000)}秒` : ms < 3_600_000 ? `${Math.round(ms / 60_000)}分` : `${Math.round(ms / 3_600_000)}時間`)
127    return (
128      <Box flexDirection="column">
129        {list.map(one => {
130          const head = one.state === 'listening' ? '● 稼働中' : one.state === 'down' ? '○ 停止' : '… ポート未検出'
131          const color = one.state === 'listening' ? 'green' : one.state === 'down' ? 'red' : 'yellow'
132          const url = one.urls[0]
133          return (
134            <Box key={one.id} flexDirection="column" marginBottom={1}>
135              <Box>
136                <Text color={color} bold>{`${head} `}</Text>
137                <Text bold wrap="truncate-end">{url ?? label(one)}</Text>
138                {url !== undefined && <Button key={`copy-${one.id}`} plain label=" [コピー]" onPress={press => $.ui.copy({ text: url, surface: press.surface })} />}
139              </Box>
140              <Text dimColor wrap="truncate-end">
141                {`$ ${one.command}  ·  ${one.ports.length > 0 ? `ポート ${one.ports.join(', ')}` : 'ポート不明'}${one.pid !== undefined ? `  ·  pid ${one.pid} ${one.process ?? ''}` : ''}  ·  ${age(now - one.changedAt)}前から`}
142              </Text>
143              {one.urls.slice(1).map(other => (
144                <Text key={`${one.id}-${other}`} dimColor wrap="truncate-end">{`  ${other}`}</Text>
145              ))}
146              {one.tail.map((line, index) => (
147                <Text key={`${one.id}-t${index}`} wrap="truncate-end" color={/\b(?:error|failed|exception|EADDRINUSE)\b/i.test(line) ? 'red' : undefined} dimColor={!/\b(?:error|failed|exception|EADDRINUSE)\b/i.test(line)}>
148                  {`  │ ${line}`}
149                </Text>
150              ))}
151            </Box>
152          )
153        })}
154      </Box>
155    )
156  })
157}
158
hooks/lantern.ts 132 lines
1// The lantern, pure: which commands start servers, the URLs and ports their output names,
2// and what lsof says is listening.
3
4import type { LanternServer } from '../types'
5
6/** Commands that start something meant to keep running and serve. */
7const SERVER =
8  /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|start|serve|preview|storybook)\b|vite(?:\s|$)|next\s+(?:dev|start)|nuxt\s+dev|astro\s+dev|remix\s+dev|webpack(?:-dev-server|\s+serve)|http-server|live-server|python3?\s+-m\s+http\.server|manage\.py\s+runserver|flask\s+run|uvicorn|gunicorn|hypercorn|fastapi\s+(?:dev|run)|rails\s+s(?:erver)?\b|bundle\s+exec\s+rails\s+s|php\s+-S|php\s+artisan\s+serve|hugo\s+server|jekyll\s+serve|mkdocs\s+serve|docker[- ]compose\s+up|docker\s+compose\s+up|wrangler\s+dev|vercel\s+dev|netlify\s+dev|firebase\s+emulators|supabase\s+start|expo\s+start|ng\s+serve|vue-cli-service\s+serve|deno\s+task\s+dev|cargo\s+(?:run|watch)|go\s+run|dotnet\s+(?:run|watch)|mix\s+phx\.server|trunk\s+serve|caddy\s+run)/
9
10export const isServerCommand = (command: string): boolean => SERVER.test(command)
11
12// An OSC sequence (a hyperlink, a title) ends at BEL or at ST (`ESC \`). It is read up to the
13// next ESC or line break at most, so one never ended does not make each later one scan to the
14// end of the output, and is left as it stands rather than taking the lines after it.
15const ANSI = /\u001b\[[0-9;?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b\n]*(?:\u0007|\u001b\\)/g
16export const stripAnsi = (text: string): string => text.replace(ANSI, '')
17
18const LOCAL_URL = /\bhttps?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|[\w-]+\.localhost|[\w.-]+\.local)(?::\d{2,5})?(?:\/[^\s'"<>)\]`]*)?/g
19
20// A trailing dot, comma, semicolon or colon off, by a loop: /[.,;:]+$/ tries from each one of a run.
21function trimPunctuation(url: string): string {
22  let end = url.length
23  while (end > 0 && '.,;:'.includes(url.charAt(end - 1))) end -= 1
24  return url.slice(0, end)
25}
26
27/** Local URLs a text names, in order, `0.0.0.0` read as localhost, a trailing dot or comma off. */
28export function urlsOf(text: string): string[] {
29  const found = new Set<string>()
30  for (const m of stripAnsi(text).matchAll(LOCAL_URL)) found.add(trimPunctuation(m[0]).replace('://0.0.0.0', '://localhost'))
31  return [...found]
32}
33
34const portOfUrl = (url: string): number | undefined => {
35  const m = url.match(/^https?:\/\/[^/]*:(\d{2,5})/)
36  if (m?.[1] !== undefined) return Number(m[1])
37  return url.startsWith('https://') ? 443 : url.startsWith('http://') ? 80 : undefined
38}
39
40const valid = (n: number) => Number.isInteger(n) && n > 0 && n < 65536
41
42/** Ports a command sets (`--port 3000`, `-p 3000`, `PORT=3000`, `:8000` for runserver). */
43export function commandPorts(command: string): number[] {
44  const out = new Set<number>()
45  for (const m of command.matchAll(/(?:--port[= ]|-p\s+|\bPORT=|--listen[= ](?:[\w.]+:)?|runserver\s+(?:[\w.]+:)?|-S\s+[\w.]+:|http\.server\s+)(\d{2,5})\b/g)) out.add(Number(m[1]))
46  return [...out].filter(valid)
47}
48
49/** Ports an output names: its URLs' ports and `listening on port 3000`-like lines. */
50export function outputPorts(text: string): number[] {
51  const out = new Set<number>()
52  for (const url of urlsOf(text)) {
53    const port = portOfUrl(url)
54    if (port !== undefined) out.add(port)
55  }
56  for (const m of stripAnsi(text).matchAll(/\b(?:listening|running|started|serving|available)\b[^\n]{0,40}?\bport\s*:?\s*(\d{2,5})\b/gi)) out.add(Number(m[1]))
57  return [...out].filter(valid)
58}
59
60/** The background task's output file, as the Bash result names it. */
61export function outputPathOf(text: string): string | undefined {
62  return text.match(/Output is being written to: (\S+?\.output)\b/)?.[1]
63}
64
65/** The last `n` non-empty lines of an output, colours taken out. */
66export function tailOf(text: string, n = 6): string[] {
67  return stripAnsi(text)
68    .split(/\r?\n|\r/)
69    .map(line => line.trimEnd())
70    .filter(line => line.trim() !== '')
71    .slice(-n)
72    .map(line => (line.length > 200 ? `${line.slice(0, 199)}…` : line))
73}
74
75export type Listener = { port: number; pid: number; process: string }
76
77/** `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` read as port → process. */
78export function parseLsof(text: string): Listener[] {
79  const out: Listener[] = []
80  let pid = 0
81  let name = ''
82  for (const line of text.split('\n')) {
83    const tag = line[0]
84    const value = line.slice(1)
85    if (tag === 'p') pid = Number(value)
86    else if (tag === 'c') name = value
87    else if (tag === 'n') {
88      const port = Number(value.slice(value.lastIndexOf(':') + 1))
89      if (valid(port) && !out.some(one => one.port === port && one.pid === pid)) out.push({ port, pid, process: name })
90    }
91  }
92  return out
93}
94
95/** A server's state against what listens now; its ports learnt from its output first. */
96export function judge(server: LanternServer, listening: readonly Listener[], at: number): LanternServer {
97  if (server.ports.length === 0) return server
98  const hit = listening.find(one => server.ports.includes(one.port))
99  const state = hit === undefined ? 'down' : 'listening'
100  return {
101    ...server,
102    state,
103    ...(hit === undefined ? {} : { pid: hit.pid, process: hit.process }),
104    changedAt: state === server.state ? server.changedAt : at,
105  }
106}
107
108/** What a newer look at its output adds: URLs and ports seen, and the latest lines. */
109export function withOutput(server: LanternServer, text: string): LanternServer {
110  const urls = [...server.urls, ...urlsOf(text).filter(url => !server.urls.includes(url))].slice(0, 6)
111  const ports = [...new Set([...server.ports, ...outputPorts(text)])].slice(0, 6)
112  const tail = tailOf(text)
113  return { ...server, urls, ports, tail: tail.length > 0 ? tail : server.tail }
114}
115
116export const label = (server: LanternServer): string => (server.ports.length > 0 ? server.ports.map(port => `:${port}`).join(' ') : server.command.split(/\s+/).slice(0, 2).join(' '))
117
118const RANK = { listening: 0, unknown: 1, down: 2 } as const
119
120/** One part per port: the same port started twice is one, told by its liveliest state. */
121export function statusOf(servers: readonly LanternServer[]): string | undefined {
122  if (servers.length === 0) return undefined
123  const byLabel = new Map<string, LanternServer>()
124  for (const one of servers) {
125    const was = byLabel.get(label(one))
126    if (was === undefined || RANK[one.state] <= RANK[was.state]) byLabel.set(label(one), one)
127  }
128  const part = (one: LanternServer) =>
129    one.state === 'listening' ? `● ${label(one)}` : one.state === 'down' ? `○ ${label(one)} 停止` : `… ${label(one)}`
130  return `🏮 ${[...byLabel.values()].map(part).join(' · ')}`
131}
132
types/index.d.ts 31 lines
1/** A server a Bash command of the session started. */
2export type LanternServer = {
3  /** The background task's id, or the call's id for a foreground one. */
4  id: string
5  command: string
6  startedAt: number
7  /** Where the background task writes its output, as the Bash result named it. */
8  outputPath?: string
9  /** Local URLs its output or command named, first seen first. */
10  urls: string[]
11  /** Ports from those URLs, the command (`--port 3000`, `PORT=3000`) or its output. */
12  ports: number[]
13  /** listening: a port is open; down: none of its ports is; unknown: no port seen yet. */
14  state: 'listening' | 'down' | 'unknown'
15  /** The process listening, as lsof names it. */
16  pid?: number
17  process?: string
18  /** The latest lines of its output, colours taken out. */
19  tail: string[]
20  /** When the state last changed. */
21  changedAt: number
22}
23
24declare module 'claude-code' {
25  interface PluginState {
26    'port-lantern': {
27      servers: LanternServer[]
28    }
29  }
30}
31