@gavin-hu/my-pi-agent 0.17.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/README.md +61 -45
  2. package/README.zh-CN.md +54 -42
  3. package/docs/extensions/README.md +34 -0
  4. package/docs/extensions/board.md +344 -0
  5. package/{extensions/bytefly/README.md → docs/extensions/bytefly.md} +465 -416
  6. package/{extensions/check/README.md → docs/extensions/check.md} +83 -68
  7. package/{extensions/context/README.md → docs/extensions/context.md} +40 -23
  8. package/docs/extensions/file-browse.md +554 -0
  9. package/{extensions/file-open/README.md → docs/extensions/file-open.md} +31 -23
  10. package/{extensions/file-read/README.md → docs/extensions/file-read.md} +47 -55
  11. package/{extensions/goal/README.md → docs/extensions/goal.md} +115 -131
  12. package/{extensions/job/README.md → docs/extensions/job.md} +66 -53
  13. package/{extensions/memory/README.md → docs/extensions/memory.md} +74 -63
  14. package/docs/extensions/plan.md +976 -0
  15. package/{extensions/question/README.md → docs/extensions/question.md} +54 -28
  16. package/{extensions/rewind/README.md → docs/extensions/rewind.md} +115 -122
  17. package/docs/extensions/session-bus.md +285 -0
  18. package/{extensions/subagent/README.md → docs/extensions/subagent.md} +166 -119
  19. package/docs/extensions/team.md +226 -0
  20. package/{extensions/todo/README.md → docs/extensions/todo.md} +85 -88
  21. package/{extensions/watch/README.md → docs/extensions/watch.md} +60 -38
  22. package/{extensions/web-access/README.md → docs/extensions/web-access.md} +93 -50
  23. package/{extensions/wechat/README.md → docs/extensions/wechat.md} +275 -192
  24. package/{extensions/worktree/README.md → docs/extensions/worktree.md} +115 -72
  25. package/extensions/board/commands.ts +87 -0
  26. package/extensions/board/config.ts +36 -0
  27. package/extensions/board/format.ts +72 -0
  28. package/extensions/board/index.ts +40 -0
  29. package/extensions/board/input.ts +54 -0
  30. package/extensions/board/join.ts +42 -0
  31. package/extensions/board/page.ts +312 -0
  32. package/extensions/board/result.ts +99 -0
  33. package/extensions/board/rows.ts +48 -0
  34. package/extensions/board/schema.ts +75 -0
  35. package/extensions/board/seat.ts +29 -0
  36. package/extensions/board/snapshot.ts +41 -0
  37. package/extensions/board/tools.ts +279 -0
  38. package/extensions/board/transport/router.ts +172 -0
  39. package/extensions/board/transport/server.ts +149 -0
  40. package/extensions/board/types.ts +54 -0
  41. package/extensions/board/view/actions.ts +306 -0
  42. package/extensions/board/view/client.ts +41 -0
  43. package/extensions/board/view/keys.ts +121 -0
  44. package/extensions/board/view/live.ts +397 -0
  45. package/extensions/board/view/page.ts +158 -0
  46. package/extensions/board/view/render.ts +496 -0
  47. package/extensions/board/view/styles.ts +211 -0
  48. package/extensions/board/view/team.ts +305 -0
  49. package/extensions/board/writes.ts +99 -0
  50. package/extensions/bytefly/notify/types.ts +1 -1
  51. package/extensions/bytefly/panel/commands.ts +40 -7
  52. package/extensions/bytefly/panel/settings-runtime.ts +0 -6
  53. package/extensions/bytefly/panel/settings.ts +11 -21
  54. package/extensions/bytefly/panel/tui/settings-view.ts +1 -1
  55. package/extensions/bytefly/picker/discovery.ts +0 -2
  56. package/extensions/bytefly/picker/types.ts +0 -2
  57. package/extensions/bytefly/update/check.ts +39 -0
  58. package/extensions/bytefly/update/format.ts +15 -0
  59. package/extensions/bytefly/update/register.ts +73 -34
  60. package/extensions/bytefly/update/state.ts +6 -3
  61. package/extensions/context/tui.ts +1 -1
  62. package/extensions/file-browse/{config.ts → config/config.ts} +13 -4
  63. package/extensions/file-browse/{files.ts → files/files.ts} +1 -14
  64. package/extensions/file-browse/{paths.ts → files/paths.ts} +1 -1
  65. package/extensions/file-browse/{git.ts → git/git.ts} +10 -3
  66. package/extensions/file-browse/index.ts +4 -4
  67. package/extensions/file-browse/{live.ts → live/live.ts} +54 -82
  68. package/extensions/file-browse/live/rev.ts +42 -0
  69. package/extensions/file-browse/{router.ts → transport/router.ts} +44 -17
  70. package/extensions/file-browse/transport/server.ts +110 -0
  71. package/extensions/file-browse/view/chrome.ts +83 -0
  72. package/extensions/file-browse/{client.ts → view/client.ts} +63 -1
  73. package/extensions/file-browse/view/diff-html.ts +94 -0
  74. package/extensions/file-browse/{html.ts → view/html.ts} +32 -158
  75. package/extensions/file-browse/{icons.ts → view/icons.ts} +1 -1
  76. package/extensions/file-browse/{live-client.ts → view/live-client.ts} +47 -1
  77. package/extensions/file-browse/{markdown.ts → view/markdown.ts} +7 -7
  78. package/extensions/file-browse/{raw-html.ts → view/raw-html.ts} +1 -1
  79. package/extensions/file-browse/{styles.ts → view/styles.ts} +31 -5
  80. package/extensions/file-browse/{tree.ts → view/tree.ts} +1 -1
  81. package/extensions/file-browse/{urls.ts → view/urls.ts} +1 -1
  82. package/extensions/file-read/schema.ts +2 -1
  83. package/extensions/goal/plan-route.ts +8 -2
  84. package/extensions/job/index.ts +15 -7
  85. package/extensions/memory/store.ts +12 -5
  86. package/extensions/plan/blocks.ts +23 -2
  87. package/extensions/plan/commands.ts +77 -21
  88. package/extensions/plan/feedback.ts +409 -63
  89. package/extensions/plan/index.ts +7 -5
  90. package/extensions/plan/plan-index.ts +44 -10
  91. package/extensions/plan/plan-text.ts +51 -24
  92. package/extensions/plan/plans.ts +162 -57
  93. package/extensions/plan/policy.ts +20 -12
  94. package/extensions/plan/review-prompt.ts +93 -0
  95. package/extensions/plan/review.ts +51 -95
  96. package/extensions/plan/runtime.ts +22 -10
  97. package/extensions/plan/sections.ts +112 -0
  98. package/extensions/plan/steps.ts +63 -95
  99. package/extensions/plan/tools/enter.ts +8 -3
  100. package/extensions/plan/tools/exit.ts +13 -19
  101. package/extensions/plan/tools/write.ts +8 -3
  102. package/extensions/plan/tools.ts +1 -1
  103. package/extensions/plan/tui.ts +29 -15
  104. package/extensions/plan/types.ts +29 -3
  105. package/extensions/plan/web-chrome.ts +2 -1
  106. package/extensions/plan/web-client.ts +122 -178
  107. package/extensions/plan/web-collab.ts +207 -0
  108. package/extensions/plan/web-comments.ts +269 -0
  109. package/extensions/plan/web-page.ts +96 -17
  110. package/extensions/plan/web-router.ts +109 -47
  111. package/extensions/plan/web-share-session.ts +191 -0
  112. package/extensions/plan/web-share.ts +169 -0
  113. package/extensions/plan/web-streams.ts +124 -0
  114. package/extensions/plan/web-tokens.ts +63 -0
  115. package/extensions/plan/web.ts +245 -151
  116. package/extensions/question/dialogs.ts +91 -1
  117. package/extensions/question/tools.ts +2 -1
  118. package/extensions/rewind/{commands.ts → commands/commands.ts} +5 -5
  119. package/extensions/rewind/{review.ts → commands/review.ts} +13 -13
  120. package/extensions/rewind/{rewind.ts → commands/rewind.ts} +6 -6
  121. package/extensions/rewind/{config.ts → config/config.ts} +1 -1
  122. package/extensions/rewind/index.ts +3 -3
  123. package/extensions/rewind/{policy.ts → state/policy.ts} +4 -4
  124. package/extensions/rewind/{runtime.ts → state/runtime.ts} +11 -11
  125. package/extensions/rewind/{snapshot-run.ts → state/snapshot-run.ts} +1 -1
  126. package/extensions/rewind/{timeline.ts → state/timeline.ts} +2 -2
  127. package/extensions/rewind/{format.ts → text/format.ts} +3 -3
  128. package/extensions/rewind/{git.ts → transport/git.ts} +2 -2
  129. package/extensions/rewind/{restore.ts → transport/restore.ts} +2 -2
  130. package/extensions/rewind/{snapshot.ts → transport/snapshot.ts} +1 -1
  131. package/extensions/rewind/{store.ts → transport/store.ts} +1 -1
  132. package/extensions/rewind/{checklist.ts → view/checklist.ts} +6 -6
  133. package/extensions/rewind/{hunk-picker.ts → view/hunk-picker.ts} +8 -8
  134. package/extensions/rewind/{path-picker.ts → view/path-picker.ts} +7 -7
  135. package/extensions/rewind/{review-tui.ts → view/review-tui.ts} +11 -11
  136. package/extensions/rewind/{rewind-tui.ts → view/rewind-tui.ts} +17 -11
  137. package/extensions/rewind/{status.ts → view/status.ts} +4 -4
  138. package/extensions/session-bus/commands.ts +113 -0
  139. package/extensions/session-bus/format.ts +101 -0
  140. package/extensions/session-bus/index.ts +75 -0
  141. package/extensions/session-bus/join-request.ts +40 -0
  142. package/extensions/session-bus/mail-watch.ts +134 -0
  143. package/extensions/session-bus/notice.ts +86 -0
  144. package/extensions/session-bus/overlap.ts +36 -0
  145. package/extensions/session-bus/protocol.ts +104 -0
  146. package/extensions/session-bus/resolve.ts +67 -0
  147. package/extensions/session-bus/result.ts +208 -0
  148. package/extensions/session-bus/rows.ts +171 -0
  149. package/extensions/session-bus/runtime.ts +466 -0
  150. package/extensions/session-bus/store.ts +365 -0
  151. package/extensions/session-bus/tools.ts +192 -0
  152. package/extensions/session-bus/tui.ts +394 -0
  153. package/extensions/session-bus/types.ts +98 -0
  154. package/extensions/subagent/agents.ts +9 -8
  155. package/extensions/subagent/invocation.ts +4 -2
  156. package/extensions/team/commands.ts +112 -0
  157. package/extensions/team/dispatch.ts +133 -0
  158. package/extensions/team/format.ts +105 -0
  159. package/extensions/team/index.ts +33 -0
  160. package/extensions/team/schema.ts +29 -0
  161. package/extensions/team/tools.ts +246 -0
  162. package/extensions/team/types.ts +48 -0
  163. package/extensions/watch/index.ts +15 -9
  164. package/extensions/web-access/fetch/page.ts +4 -1
  165. package/extensions/web-access/fetch/structured.ts +447 -0
  166. package/extensions/web-access/fetch/tool.ts +2 -1
  167. package/extensions/web-access/search/tool.ts +2 -1
  168. package/extensions/wechat/bridge.ts +76 -92
  169. package/extensions/wechat/{commands.ts → commands/commands.ts} +26 -18
  170. package/extensions/wechat/{doctor.ts → commands/doctor.ts} +5 -5
  171. package/extensions/wechat/{history.ts → commands/history.ts} +1 -1
  172. package/extensions/wechat/{login.ts → commands/login.ts} +3 -3
  173. package/extensions/wechat/{slash.ts → commands/slash.ts} +38 -2
  174. package/extensions/wechat/dialog/channels.ts +136 -0
  175. package/extensions/wechat/{interaction.ts → dialog/interaction.ts} +66 -51
  176. package/extensions/wechat/{prompt.ts → dialog/prompt.ts} +40 -25
  177. package/extensions/wechat/{remote-ui.ts → dialog/remote-ui.ts} +1 -1
  178. package/extensions/wechat/index.ts +10 -10
  179. package/extensions/wechat/{admission.ts → peer/admission.ts} +2 -2
  180. package/extensions/wechat/{peer-session.ts → peer/peer-session.ts} +2 -2
  181. package/extensions/wechat/{peer-worker.ts → peer/peer-worker.ts} +119 -56
  182. package/extensions/wechat/{presence.ts → peer/presence.ts} +11 -11
  183. package/extensions/wechat/{reply-pipeline.ts → peer/reply-pipeline.ts} +13 -5
  184. package/extensions/wechat/{credentials.ts → state/credentials.ts} +2 -2
  185. package/extensions/wechat/{state.ts → state/state.ts} +14 -2
  186. package/extensions/wechat/{format.ts → text/format.ts} +3 -3
  187. package/extensions/wechat/{notices.ts → text/notices.ts} +15 -7
  188. package/extensions/wechat/tools.ts +29 -12
  189. package/extensions/wechat/{client.ts → transport/client.ts} +26 -2
  190. package/extensions/wechat/{deliver.ts → transport/deliver.ts} +104 -40
  191. package/extensions/wechat/{inbound.ts → transport/inbound.ts} +5 -5
  192. package/extensions/wechat/{media.ts → transport/media.ts} +11 -5
  193. package/extensions/wechat/transport/outbound.ts +142 -0
  194. package/extensions/wechat/{poll.ts → transport/poll.ts} +3 -3
  195. package/extensions/wechat/types.ts +10 -1
  196. package/extensions/wechat/{login-screen.ts → view/login-screen.ts} +4 -4
  197. package/extensions/wechat/{status-screen.ts → view/status-screen.ts} +31 -26
  198. package/extensions/worktree/git.ts +5 -0
  199. package/extensions/worktree/guard.ts +3 -5
  200. package/extensions/worktree/registry.ts +11 -5
  201. package/extensions/worktree/status.ts +1 -3
  202. package/lib/README.md +12 -6
  203. package/lib/board/card.ts +290 -0
  204. package/lib/board/links.ts +117 -0
  205. package/lib/board/page-pointer.ts +256 -0
  206. package/lib/board/round-text.ts +72 -0
  207. package/lib/board/round.ts +89 -0
  208. package/lib/board/rules.ts +304 -0
  209. package/lib/board/session.ts +105 -0
  210. package/lib/board/store.ts +310 -0
  211. package/lib/board/view.ts +150 -0
  212. package/lib/errors.ts +12 -4
  213. package/lib/format.ts +13 -0
  214. package/lib/http/guard.ts +112 -0
  215. package/lib/http/index.ts +16 -5
  216. package/lib/http/router.ts +40 -13
  217. package/lib/http/serve.ts +234 -0
  218. package/lib/http/server.ts +29 -13
  219. package/lib/http/sink.ts +110 -0
  220. package/lib/http/token.ts +38 -0
  221. package/lib/interaction.ts +10 -0
  222. package/lib/notice.ts +29 -2
  223. package/lib/plan-entry.ts +7 -2
  224. package/lib/policy.ts +12 -2
  225. package/lib/qr.ts +64 -0
  226. package/lib/repo-key.ts +74 -0
  227. package/lib/report.ts +52 -33
  228. package/lib/requirements.ts +7 -9
  229. package/lib/session-label.ts +64 -0
  230. package/lib/session-roster.ts +130 -0
  231. package/lib/session-tool.ts +184 -0
  232. package/lib/tool-names.ts +25 -2
  233. package/lib/tui/README.md +16 -2
  234. package/lib/tui/dock-screen.ts +85 -17
  235. package/lib/tui/glyphs.ts +2 -0
  236. package/lib/tui/line-pane.ts +15 -4
  237. package/lib/tui/tool.ts +23 -4
  238. package/lib/web/README.md +5 -2
  239. package/lib/web/components.ts +6 -1
  240. package/lib/web/runtime.ts +7 -1
  241. package/lib/web/tokens.ts +25 -2
  242. package/package.json +27 -14
  243. package/skills/init/SKILL.md +80 -45
  244. package/skills/init/references/agents-md-quality.md +26 -2
  245. package/skills/init/references/interview-questions.md +36 -14
  246. package/skills/next/SKILL.md +77 -51
  247. package/skills/project-docs/SKILL.md +133 -0
  248. package/skills/project-docs/references/audit.md +131 -0
  249. package/skills/project-docs/references/changelog.md +105 -0
  250. package/skills/project-docs/references/discovery.md +127 -0
  251. package/skills/project-docs/references/readme.md +80 -0
  252. package/skills/project-docs/references/release.md +84 -0
  253. package/skills/project-docs/references/roadmap.md +93 -0
  254. package/skills/project-docs/scripts/state.ts +316 -0
  255. package/skills/refactor/SKILL.md +100 -125
  256. package/skills/refactor/references/handoff.md +35 -0
  257. package/skills/refactor/references/signals.md +54 -0
  258. package/skills/refactor/scripts/inventory.ts +587 -0
  259. package/extensions/file-browse/README.md +0 -467
  260. package/extensions/file-browse/server.ts +0 -134
  261. package/extensions/plan/README.md +0 -709
  262. package/extensions/plan/config.ts +0 -27
  263. package/extensions/wechat/outbound.ts +0 -100
  264. package/extensions/wechat/qrcode.ts +0 -46
  265. package/skills/changelog/SKILL.md +0 -148
  266. /package/extensions/file-browse/{diff.ts → text/diff.ts} +0 -0
  267. /package/extensions/file-browse/{fuzzy.ts → text/fuzzy.ts} +0 -0
  268. /package/extensions/file-browse/{palette.ts → view/palette.ts} +0 -0
  269. /package/extensions/rewind/{patch.ts → text/patch.ts} +0 -0
  270. /package/extensions/rewind/{paths.ts → text/paths.ts} +0 -0
  271. /package/extensions/rewind/{queue.ts → transport/queue.ts} +0 -0
  272. /package/extensions/rewind/{temp-index.ts → transport/temp-index.ts} +0 -0
  273. /package/extensions/wechat/{lock.ts → state/lock.ts} +0 -0
  274. /package/extensions/wechat/{channel.ts → text/channel.ts} +0 -0
@@ -1,467 +0,0 @@
1
- # file-browse — view the working directory in a browser
2
-
3
- `/browse` starts a **read-only** HTTP server rooted at the effective working
4
- directory, opens the default browser at it, and prints the URL. The page is a
5
- two-pane file browser: a collapsible path tree on the left, directory listings
6
- and file views on the right, with image thumbnails, rendered Markdown,
7
- highlighted code, per-language icons, a fuzzy quick-open palette, and a
8
- read-only git diff view. It is
9
- bound to `127.0.0.1`
10
- and ships no dependencies — `node:http` plus one small vanilla script.
11
-
12
- <img src="../../assets/file-browse.png" alt="The loopback file browser, showing the path filter, the file tree, and a rendered Markdown preview" width="100%">
13
-
14
- ```bash
15
- pi --extension ./extensions/file-browse # load just this extension
16
- pi -e . # load the whole @gavin-hu/my-pi-agent package
17
- ```
18
-
19
- ## What it does
20
-
21
- - **One-command browsing.** `/browse` starts the server, prints the URL, and
22
- opens the browser (unless `autoOpen: false`).
23
- - **Two-pane UI.** A server-rendered tree, directory listings, and file pages,
24
- progressively enhanced by one first-party script (filter, lazy tree
25
- expansion, thumbnail fallback). A folder folds from its twisty, and a
26
- `fold all` / `expand all` button beside the filter folds the whole tree at
27
- once. The tree scrolls in
28
- its own pane with quick open and the filter pinned above it; below 860px it
29
- collapses into a `Files` disclosure above the listing. A hairline progress bar
30
- tracks whichever column is scrolling (the card body for a file or diff, the
31
- main column otherwise), and the served folder names the root page.
32
- - **Rich previews.** Text, rendered Markdown, images (thumbnails), and
33
- binary/over-size download cards, with per-language icons.
34
- - **First-party syntax highlighting.** Code files render with keywords,
35
- strings, numbers, and comments colored, in the dark and light palettes:
36
- JavaScript/TypeScript (`js`, `mjs`, `cjs`, `jsx`, `ts`, `mts`, `cts`, `tsx`),
37
- JSON, CSS (`css`, `scss`, `sass`, `less`), HTML/XML and template components
38
- (`html`, `htm`, `xml`, `vue`, `svelte`), shell (`sh`, `bash`, `zsh`),
39
- Python (`py`, `pyw`, `pyi`), Java, YAML (`yaml`, `yml`), and SQL. Other text
40
- types stay plain.
41
- - **Rendered Markdown.** `.md`/`.markdown` files render as headings, lists,
42
- tables, code, inline and reference links, bare-URL autolinks, and images, with
43
- a one-click **raw** view (`?raw=1`). The page fills the card, so the scroll
44
- bar sits at the card edge; headings, prose, and images keep a centred reading
45
- measure of at most 1012px. Code blocks stay
46
- inside that column; tables start at it and take the free gutter to its right,
47
- and a table wider than the pane scrolls, its right edge fading until the last
48
- column is reached. A task list's checkbox is drawn by the page, so a done
49
- item carries the success colour in both themes. Tables size their columns to
50
- the content, and named and numeric character references are decoded. A
51
- README's raw HTML is re-emitted through an allowlist (`<details>`,
52
- `<summary>`, tables, `<kbd>`, images), so it renders without becoming an
53
- injection path. Fenced code blocks are syntax-highlighted when the fence
54
- names a supported language. Headings get stable anchor ids, so in-document
55
- `#anchor` links work. Raw HTML in the source is escaped, never executed, and
56
- external images are shown as links rather than fetched.
57
- - **Sortable listings.** The Name / Size / Modified headers sort the current
58
- directory, directories first, and the choice is remembered per browser.
59
- - **Copy and wrap.** Copy a file's root-relative path or its contents, and
60
- toggle line wrapping for text and raw views.
61
- - **Theme toggle.** A header button switches between the dark and light
62
- palettes and remembers the choice per browser; until it is used, the palette
63
- follows the system `prefers-color-scheme`.
64
- - **Quick open.** `/` (or `Ctrl/Cmd+K`, or the sidebar button) opens a fuzzy
65
- path finder over a capped index of the tree, with keyboard navigation and a
66
- highlighted match; Enter opens the file.
67
- - **Keyboard.** `/` or `Ctrl/Cmd+K` opens quick open, `-` folds or expands
68
- every folder in the tree, `u` toggles line wrapping, `r` switches rendered and
69
- raw Markdown, `n`/`p` step between a diff's hunks, and `?` opens a shortcut
70
- sheet. A diff's hunk headers pin to the top of the code viewport while its
71
- body scrolls.
72
- - **Read-only and loopback-scoped.** No editing, no writing, no LAN exposure.
73
- - **Git context.** A read-only header chip shows the checked-out branch (or
74
- detached head) and reflows on narrow screens. Uncommitted changes are stated
75
- once, by the changes chip below; turn the diff view off (`gitDiff: false`) and
76
- the header reports no changes at all.
77
- - **Git diff view.** A `● N changes +A −D` chip links to `/diff`, a change
78
- overview with `git diff --stat` and a per-file status table, and `/diff/<rel>`
79
- renders one file's unified diff, whose head carries its own `+A −D` and hunk
80
- count. Changed lines are syntax-highlighted with the
81
- file's language, and dirty files and their directories carry a marker in the
82
- listing and the tree. The scope is switchable between `head` / `staged` /
83
- `worktree`; untracked files show as all-add, an unborn `HEAD` falls back to the
84
- index, and a non-repository is a plain empty state. Read-only, capped, and
85
- rendered with the shared diff colors.
86
- - **Live status.** A page left open keeps up with the session: a `◉ live`
87
- chip beside `read-only` says whether status is flowing (green), still
88
- connecting (accent), stalled (amber, after three missed frames), or offline
89
- (red); the branch chip, the `● N changes +A −D` chip, and the change markers in
90
- the tree and the listing update in place; and the footer line reports `up 2m
91
- 14s · 37 requests`. The chip names its state and never counts, so nothing is
92
- repainted between frames. One Server-Sent Events stream per page carries it, on
93
- the same loopback server, so nothing extra is opened and nothing is written;
94
- that stream is also how the server notices the last page closing its window,
95
- after which it stops listening.
96
- - **No dependencies.** `node:http` plus the inline sprite, CSS, and client
97
- script.
98
-
99
- ## Commands
100
-
101
- ```bash
102
- /browse start at the working directory, open the browser, print the URL
103
- /browse <path> start with a subdirectory of the working directory as the root
104
- /browse status print the root and URL, or "not running"
105
- /browse stop stop the server
106
- ```
107
-
108
- - The root is the effective cwd, so an active `worktree` session serves the
109
- worktree. `<path>` must resolve inside it.
110
- - The port is fixed for the session: the first `/browse` picks a random port
111
- in `4780`–`5779` and every later `/browse` in that session reuses it, so the
112
- URL stays stable across roots and restarts. Set `"port"` to pin an explicit
113
- port; a busy port is reported, not silently changed.
114
- - Starting while already running with the same root reprints the URL without
115
- restarting; a different root (or a changed pinned port) restarts the server.
116
- - The server is closed when its last page has been gone for ten seconds, so
117
- closing the browser window ends the session's browse server and `/browse`
118
- starts it again on the same port. A reload or a new tab inside that grace keeps
119
- it. `session_shutdown` closes it too, and `/browse stop` closes it at once.
120
-
121
- ### Status
122
-
123
- While a server is running, the extension publishes a two-tone `◉ <port>` chip
124
- (a green circle-dot and a blue port) under the shared `browse` status key. The
125
- [`bytefly`](../bytefly/) extension routes it to line 1's right zone
126
- beside `⎇ branch` and `⑂ worktree`; it
127
- is cleared on stop and on `session_shutdown`. The chip is session-local: it
128
- reflects only this session's server, with no cross-session sharing.
129
-
130
- The page has its own live status, which is what a left-open tab reads. The
131
- header chip starts hidden and is painted by the client from `/events`: `◉ live`
132
- in the success colour while frames arrive, `◉ connecting` before the first
133
- one, `◉ stale` in the warning colour when three intervals pass without a frame
134
- on an open connection, and `◉ offline` in the danger colour once the stream
135
- errors. The chip names its state rather than counting, so it is repainted only
136
- when that state changes. The same frame carries the branch (or detached head), the
137
- uncommitted-change totals and paths, the server's uptime, and the requests it
138
- has answered, so the branch chip, the changes chip, the markers, and the footer
139
- line are painted from one snapshot rather than four requests. Losing the stream
140
- leaves everything the page last showed in place: it is read-only, so a stale
141
- label is never a stale action. `"live": false` turns the whole surface off — no
142
- chip, no stream, no `/events` route — and so does JavaScript off.
143
-
144
- The stream is also how the server knows a page is still there: when the last one
145
- leaves, the port is released after ten seconds and the chip is cleared, because
146
- nothing is left to serve. That is why a page with JavaScript off — or with live
147
- status off — never counts as a reader, and the server then waits for
148
- `/browse stop` or the end of the session.
149
-
150
- ### The page
151
-
152
- The page is keyboard-first, and the tree is one tab stop rather than two per
153
- folder:
154
-
155
- | Key | What it does in the tree |
156
- |---|---|
157
- | `↑` / `↓` | Move between the rows on screen |
158
- | `→` | Open a folder (reading its children first if needed), or enter it |
159
- | `←` | Close the folder, or step out to its parent |
160
- | `Space` | Open or close the focused folder |
161
- | `Enter` | Follow the focused row's link |
162
- | `Home` / `End` | First or last row on screen |
163
-
164
- The folder's own link carries `aria-expanded`, so a screen reader hears its
165
- state once; the twisty beside it is a pointer control kept out of the tab order.
166
- A mouse click moves the tab stop to that row, so `Tab` comes back to where you
167
- were. Elsewhere the page keeps its own keys: `/` or `Ctrl`/`Cmd`+`K` for quick
168
- open, `-` to fold, `u` to wrap, `r` for raw Markdown, `n`/`p` between diff hunks,
169
- and `?` for the sheet, whose dialog now traps `Tab` and returns focus to its
170
- button.
171
-
172
- Printing is supported: the paper gets the light palette whatever the screen is
173
- showing, the chrome and the tree are dropped, and a file or diff prints whole
174
- instead of inside its scroll box.
175
-
176
- ## Routes
177
-
178
- | Route | Result |
179
- |---|---|
180
- | `/`, `/browse[/<rel>]` | tree + directory listing |
181
- | `/view/<rel>` | tree + file page (text, Markdown, image, binary, or over-size) |
182
- | `/view/<rel>?raw=1` | raw Markdown/text source instead of the rendered view |
183
- | `/raw/<rel>` | raw bytes, streamed; downloads and image sources |
184
- | `/diff[?mode=head\|staged\|worktree]` | changed-file overview with `--stat` |
185
- | `/diff/<rel>[?mode=…]` | one file's unified diff |
186
- | `/api/tree?path=<rel>` | JSON children for lazy tree expansion |
187
- | `/api/files?q=<query>` | JSON fuzzy path matches for the quick-open palette |
188
- | `/events` | Server-Sent Events stream of `status` frames for the open page |
189
- | `/app.js` | the first-party client script |
190
- | `/theme.js` | the pre-paint theme bootstrap |
191
- | `/favicon.ico` | `204` (the icon is a data URI) |
192
-
193
- ## Configuration
194
-
195
- The `file-browse` section of the shared `bytefly.json`, merged from the global
196
- document and the project document (project wins):
197
-
198
- ```jsonc
199
- // bytefly.json → "file-browse"
200
- {
201
- "port": 0, // 0 = one random port fixed for the session
202
- "autoOpen": true, // open the browser on start; false for headless
203
- "maxFileBytes": 1048576, // larger files show a download card only
204
- "maxThumbBytes": 5242880, // larger images get an icon, not a thumbnail
205
- "maxTextLines": 5000, // rendered lines before truncation
206
- "maxDirEntries": 2000, // listed entries before truncation
207
- "thumbnails": true,
208
- "markdown": true, // render Markdown files as formatted HTML
209
- "markdownHtml": true, // re-emit sanitized raw HTML in rendered Markdown
210
- "maxIndexEntries": 20000, // files collected for quick open before truncation
211
- "gitDiff": true, // offer the read-only diff view
212
- "diffContext": 3, // unified diff context lines
213
- "maxDiffLines": 4000, // diff lines rendered before truncation
214
- "live": true, // stream live status to open pages
215
- "liveIntervalMs": 3000 // ms between status frames while a page is connected
216
- }
217
- ```
218
-
219
- ## Security
220
-
221
- - **Loopback only.** Binds `127.0.0.1`; no auth and no LAN exposure.
222
- - **Method and Host.** Only `GET`/`HEAD` are served (else `405`); a `Host`
223
- header that is not `127.0.0.1[:port]`, `localhost[:port]`, or `[::1][:port]`
224
- is rejected (else `403`, DNS-rebinding defense), and no CORS headers are sent.
225
- - **Path guard.** Every path is decoded once, NUL and absolute paths are
226
- rejected, the path is resolved under the root, and the target (or nearest
227
- existing ancestor) is `realpath`-checked for containment. This blocks `../`,
228
- encoded traversal, and symlink escapes. Symlinks are listed but only followed
229
- when their real path stays inside the root.
230
- - **CSP.** Pages allow only same-origin scripts and inline styles, and refuse to
231
- be framed (`frame-ancestors 'none'`, `X-Frame-Options: DENY`), so a local page
232
- cannot clickjack the controls or re-point relative URLs through an injected
233
- `<base>`; the policy comes from `lib/http/headers.ts`, shared with `plan`, so
234
- the two surfaces cannot drift. `/raw` uses
235
- `default-src 'none'; script-src 'none'; sandbox` plus `nosniff`, so a served
236
- SVG/HTML file cannot execute.
237
- - **Markdown safety.** Rendered Markdown is escape-first, and raw HTML passes an
238
- allowlist (`raw-html.ts`): only known elements and attributes are re-emitted,
239
- rebuilt from the parsed names rather than copied, so `script`, `style`,
240
- `iframe`, `svg`, event handlers, `style=` and `class=` never reach the page.
241
- Link schemes are allowlisted (`javascript:`/`data:` dropped), an external
242
- image renders as a link instead of loading, and open elements are balanced at
243
- the end of the document so an unclosed `<div>` cannot swallow the page chrome.
244
- A suppressed element (`script`, `style`, `svg`, …) is dropped with its body;
245
- any other unknown tag is escaped and stays visible. `markdownHtml: false`
246
- restores escape-only rendering. The page CSP keeps the rest inert.
247
- - **Highlighting safety.** The highlighter escapes every literal before it
248
- wraps it in a token span, so a code file's content cannot inject markup or
249
- attributes; only the fixed `tok-*` class names reach the page.
250
- - **Event stream.** `/events` is a `GET` on the same loopback server, behind
251
- the same method and `Host` checks, and it only reads: the frame is the branch,
252
- the change paths, an uptime, and a request count, all of which the page it
253
- feeds already renders. It carries no page policy (`text/event-stream` is not a
254
- document), sends `Cache-Control: no-store`, and cannot be cached or replayed.
255
- A tick runs only while a page is attached, and the timer is `unref`ed, so an
256
- idle server does no work and a forgotten tab cannot hold the process open.
257
- - **Caps.** `maxFileBytes` (inline rendering), `maxTextLines` (rendered lines),
258
- `maxThumbBytes` (thumbnails), and `maxDirEntries` (listings) bound every read.
259
- - **Git reads.** The header chip and the diff view run read-only git
260
- (`rev-parse`, `status --porcelain=v1 -z`, `diff --stat`, `diff -U<n>`) with a
261
- timeout and a short cache; any failure simply omits the chip or the diff. A
262
- per-file diff sets `GIT_LITERAL_PATHSPECS=1`, so a filename containing glob
263
- characters is matched literally.
264
- - **Read-only.** Nothing is ever written.
265
-
266
- ## Limitations
267
-
268
- - Syntax highlighting covers the built-in language set below; any other text
269
- type renders exactly as before. State that the tokenizer does not carry
270
- across lines (shell heredocs, interpolation inside a template literal) is
271
- approximated rather than parsed.
272
- - Live status updates what the page already contains: the header chips, the
273
- markers on the rows it rendered, and the footer line. A file that appears on
274
- disk joins the listing on the next reload, the `/diff` table and a file page's
275
- `changes` action stay page-load snapshots, and the branch chip is only patched
276
- when the page was served inside a repository.
277
- - `/browse` has no auth; a malicious local page could probe the port. The `Host`
278
- allowlist and the absence of CORS headers mitigate reads, and the server is
279
- read-only.
280
- - Serving the root exposes whatever is on disk to the local user who started it;
281
- this is intentional and scoped to loopback.
282
-
283
- ## Non-goals
284
-
285
- - No editing or writing from the browser.
286
- - No third-party assets: the Markdown renderer, its raw-HTML sanitizer, and the
287
- syntax highlighter are first-party, so raw HTML in a Markdown file is
288
- allowlisted and never executed.
289
- - No auth and no LAN exposure: loopback only.
290
- - Not a general static-file server: the root is confined to the effective cwd.
291
-
292
- ## Pi integration
293
-
294
- | Integration point | How |
295
- |---|---|
296
- | Command | `/browse` registers a single command from the factory; no tools are exposed. |
297
- | State | The running server, its root, and the session port live in a module-local closure; nothing is persisted and no session entries are written. |
298
- | Lifecycle | The factory opens no socket; the server is created on `/browse` and closed idempotently by `/browse stop`, by `session_shutdown`, and once its last page has been gone for the idle grace, which also ends every attached status stream. |
299
-
300
- ## Design notes
301
-
302
- - **Lifecycle.** `/browse` resolves `resolveEffectiveCwd(ctx.cwd)`, loads config,
303
- selects the port, parses args, and `await createFileServer(...)`: `realpath`
304
- the root, bind `127.0.0.1`, await `listening`, return `{ url, port, root,
305
- close }`. The port is chosen once for the session: a pinned config `port`
306
- wins, otherwise a random port is drawn and cached after the first successful
307
- bind, so later starts reuse it (a conflict is reported and the next `/browse`
308
- rolls another). `/browse stop` and `session_shutdown` await the idempotent
309
- `close()`; `session_shutdown` also clears the cached port. The page is the
310
- server's only reader, so the channel reports the last page's departure after
311
- `IDLE_STOP_MS` and the command closes the server and clears the chip — the
312
- cached port survives, so the next `/browse` binds the same one.
313
- - **Pure routing.** `handleRequest(context, method, rawUrl, headers)` validates
314
- method and `Host`, parses the URL, matches a route, and runs every path
315
- through `paths.ts`. It returns a plain `ServeResponse`, so routing is tested
316
- without a socket; `server.ts` is the only part that binds a port.
317
- - **Progressive UI.** The page is server-rendered HTML with an inline style
318
- block and inline SVG icons. `client.ts` enhances it: the filter hides
319
- non-matching rows while keeping ancestors, disclosure triangles lazily
320
- `fetch("/api/tree")`, broken thumbnails fall back to the category icon, the
321
- listing headers sort in place, the wrap toggle is remembered, and the copy
322
- buttons use the clipboard. On wide screens the tree is its own scroll pane
323
- under the pinned filter and quick-open trigger; the sidebar is a `<details>`
324
- whose content wrapper has no definite height, so the panel fills it
325
- absolutely and the tree flexes inside. Without JS the page still browses and
326
- renders Markdown, and the JS-only controls (filter, disclosure, actions, quick
327
- open) are hidden; the sort buttons lose their pointer so they do not look
328
- live. The palette is the shared Bytefly web theme (`lib/web/tokens.ts`),
329
- derived from the `bytefly-dark`/`bytefly-light` terminal themes; it follows
330
- `prefers-color-scheme` until an explicit choice sets `data-theme` on the root:
331
- `/theme.js` applies the saved choice in the head before first paint, and the
332
- header toggle flips and stores it (`pi-web-theme` in `localStorage`, the key
333
- shared with plan's review page).
334
- - **Markdown rendering.** `markdown.ts` is a first-party, escape-first renderer
335
- for the constructs that show up in repository READMEs. It emits only a known
336
- tag set, escapes every literal character, allowlists URL schemes (dropping
337
- `javascript:`/`data:`), rewrites local links and images to `/view`/`/raw`, and
338
- renders an external image as a link instead of loading it (the page CSP is
339
- `img-src 'self' data:`). Link reference definitions (`[id]: url`), including
340
- the full `[text][id]`, collapsed `[text][]`, and shortcut `[text]` forms, and
341
- numeric and common named character references are resolved. The Rendered/Raw
342
- switch is a server-side `?raw=1`
343
- link, so it works without JavaScript. Headings are demoted one level so the
344
- card title stays the page's only `h1`, and each gets a slug `id` (unique in
345
- the document). Set `markdown: false` to fall back to the plain-text view. A
346
- fenced code block
347
- whose info string names a supported
348
- language is highlighted through `lib/highlight.ts` (either an extension or a
349
- long-form alias, `fenceLanguage`); an absent or unknown language stays plain.
350
- - **Raw HTML.** A line that starts with an allowed block tag (`<details>`,
351
- `<table>`, `<div>`, `<pre>`, …), a comment, or a closing tag opens an HTML
352
- block that runs to the next blank line; text inside it stays text, and a
353
- suppressed tag (`<script>`, `<style>`, `<svg>`) drops its body through the
354
- matching close tag. `raw-html.ts` re-emits only allowlisted elements and
355
- attributes: `a`/`img` go through the same `/view`/`/raw` resolution as
356
- Markdown, an external image becomes a link, and `class`/`style`/handlers are
357
- dropped. Phrasing tags are also accepted inside a line, while a block tag
358
- mid-paragraph stays escaped. Open elements are balanced across blocks, which
359
- is how a `<details>` can wrap Markdown paragraphs, and `markdownHtml: false`
360
- turns the whole path off.
361
- - **Syntax highlighting.** `lib/highlight.ts` is a first-party, escape-first
362
- tokenizer for the file types that dominate a repository: JavaScript and
363
- TypeScript, JSON, CSS (incl. SCSS/Sass/Less), HTML/XML and template
364
- components, shell, Python, Java, YAML, and SQL. `detectLanguage` maps a
365
- filename to a tokenizer and an unmapped type stays plain. `highlightLines`
366
- walks the whole file, so block comments, template literals, open HTML tags,
367
- CSS brace depth, and Python triple-quoted strings carry across lines; every
368
- literal is escaped with the same `escapeHtml` the plain view uses, and a
369
- line's markup is only the fixed `tok-*` classes the stylesheet colors. It
370
- backs both the plain text view and fenced code blocks in the rendered
371
- Markdown view.
372
- - **Quick open.** `/api/files` ranks the cached index with `fuzzy.ts` and
373
- returns the matched character positions; the client fetches on an 80 ms
374
- debounce and builds rows with `textContent`, so a file name cannot inject
375
- markup. The index skips `.git`, `node_modules`, and symlinks, is capped by
376
- `maxIndexEntries`, and is cached per server for 10 s by `createFileIndex`. The
377
- palette is a `dialog`/`combobox`/`listbox` with `aria-activedescendant` and
378
- `Esc` / arrow / `Enter` handling.
379
- - **Diff view.** `git.ts` extends the read-only provider set with a TTL-cached
380
- `git status --porcelain=v1 -z` and a per-mode `git diff`; `diff.ts` parses the
381
- unified diff and the porcelain records into plain view models, so `router.ts`
382
- and `html.ts` stay pure. `head` compares against `HEAD` (falling back to
383
- `--cached` before the first commit), `staged` against the index, and
384
- `worktree` against the index from the other side. An untracked file renders as
385
- all-add through `readFileView`, so binary and over-size handling is shared
386
- with the file view. `git diff --stat` supplies the chip totals and
387
- `changeDirs` derives the directory markers; the changed lines are highlighted
388
- per hunk by rebuilding the old and new sides for `lib/highlight`.
389
- - **Live status.** `live.ts` builds one snapshot per tick — the git status,
390
- the `head` change index, the server's uptime, and its request count — and
391
- `frameOf` serializes it as one `status` event. `createLiveChannel` holds the
392
- attached pages and starts the ticker on the first attach, so an idle server
393
- does no work; it shares a single in-flight snapshot between pages, drops a
394
- page whose write fails, and stops on the last detach and on `close()`, which
395
- `server.ts` calls before closing the socket. The last detach also arms one
396
- idle-stop timer — a reload re-attaches and cancels it — and `server.ts` turns
397
- that into the extension's `close()` and a cleared chip. Both providers are already
398
- TTL-cached, so a tick re-reads at most one `git status`, and every read
399
- failure degrades to `null` rather than a failed frame. The event-stream
400
- headers and the `retry:` preamble live in `lib/http` with the rest of the
401
- loopback policy, shared with plan's review page. The client half is
402
- `live-client.ts`: one `EventSource`, one snapshot paint (`textContent` only,
403
- never markup), one staleness timeout armed per frame, and a `pagehide` cleanup.
404
- - **Streaming responses.** The server streams `filePath` responses and
405
- suppresses bodies for `HEAD`, so large `/raw` files are not buffered.
406
- - **Root confinement over feature breadth.** The root is deliberately confined
407
- to the effective cwd rather than serving an arbitrary directory, so a
408
- worktree session serves the worktree and nothing above it.
409
-
410
- ## Files
411
-
412
- | File | Purpose |
413
- |---|---|
414
- | `index.ts` | `/browse` command, running-server closure, shutdown cleanup |
415
- | `config.ts` | Config defaults, validation, global/project merge |
416
- | `paths.ts` | Decode/encode, resolve, and `realpath`-containment guard |
417
- | [`../../lib/escape.ts`](../../lib/escape.ts) | `escapeHtml`, the shared HTML escaping used by every renderer |
418
- | [`../../lib/highlight.ts`](../../lib/highlight.ts) | First-party escape-first syntax tokenizer for the code view (shared with `plan`) |
419
- | [`../../lib/web/index.ts`](../../lib/web/index.ts) | The shared Bytefly web brand system: tokens, base, components, layout, runtime, and markup |
420
- | `files.ts` | Classification (incl. Markdown), text reads, and one page-level walk (`directoryView`) that returns a directory's listing and its sidebar tree |
421
- | `diff.ts` | Pure unified-diff and porcelain-status parsing for the diff view |
422
- | `fuzzy.ts` | Fuzzy path matching and ranking for the quick-open palette |
423
- | `markdown.ts` | First-party escape-first Markdown-to-HTML renderer (fenced code highlighted; raw HTML through `raw-html.ts`) |
424
- | `raw-html.ts` | Allowlisted raw-HTML sanitizer: element/attribute policy, suppressed bodies, and cross-block balancing |
425
- | `urls.ts` | Shared link/image URL policy: scheme allowlist and `/view`/`/raw` rewriting |
426
- | `git.ts` | Read-only branch/dirty provider for the header chip |
427
- | `icons.ts` | Inline SVG sprite and the per-language mapping |
428
- | `client.ts` | The `/app.js` source: sort, wrap, copy, hunk navigation, reading progress, and the page keymap |
429
- | `tree.ts` | The sidebar block: path filter, fold-all, lazy tree loading, and the tree's keyboard model (interpolated into `client.ts`) |
430
- | `palette.ts` | The quick-open palette: fuzzy search, the combobox wiring, and the `window.bfPalette` contract (interpolated into `client.ts`) |
431
- | `live-client.ts` | The client's live status block: the event stream, the chips, the markers, and the footer line (interpolated into `client.ts`) |
432
- | `live.ts` | The live status snapshot, its frame, and the fan-out channel that ticks it |
433
- | `styles.ts` | The page-only `browse-*` stylesheet (the `bf-*` kit comes from `lib/web`) |
434
- | `html.ts` | Page renderers: the shared shell, the two-pane layout, the listing, the cards, and the diff body |
435
- | `router.ts` | Pure request handler: routes, the `/raw` sandbox policy, and the error page |
436
- | `server.ts` | `node:http` server: this extension's handler over the shared bind, writer, and close |
437
- | [`../../lib/http/index.ts`](../../lib/http/index.ts) | Loopback HTTP layer shared with `plan`: page/script/JSON/event-stream headers, `ServeResponse`, the request-envelope helpers, bind/respond/close, and `openEventStream` |
438
- | [`../../lib/browser.ts`](../../lib/browser.ts) | Cross-platform browser opener (shared with `plan`) |
439
-
440
- ## Testing
441
-
442
- `extensions/file-browse/` covers the path guard (traversal, encoded, NUL, malformed,
443
- absolute, symlink escape and in-root symlink), file classification/listings/
444
- reads/tree and the quick-open file index, the fuzzy matcher, the syntax
445
- highlighter (language detection, fence aliases, token classes, cross-line
446
- state, and escaping), the Markdown renderer (blocks, inline, fenced-code
447
- highlighting, safety, raw HTML, and path resolution), the raw-HTML sanitizer
448
- (allowlist, suppressed bodies, attribute policy, balancing, and a seeded
449
- invariant test over fragment soup),
450
- the icon mapping and sprite, HTML escaping/encoding/rendering, the client script
451
- and its serving, the platform browser commands with an injected spawn, the router
452
- (routes, `/api/tree`, `/api/files`, `?raw=1`, status codes, `Host`, `HEAD`, `/raw`
453
- headers, and the `/diff` view routes and mode validation)
454
- without a socket, a real `127.0.0.1:0` server, the session-port lifecycle (fixed
455
- on first start, reused, and re-rolled after a conflict), the git status provider
456
- (branch, dirty, detached, non-repo, failure, and TTL cache), the git diff parser
457
- and provider (line kinds, line numbers, status and rename parsing, mode
458
- filtering, untracked all-add, unborn-HEAD fallback, literal pathspec, and TTL
459
- cache), the diff renderers (highlighted changed lines, marker sets, and chip
460
- totals), the live status feed (snapshot fields, degraded providers, the frame,
461
- and the channel's ticker driven by an injected timer, plus the idle stop armed on
462
- the last detach and cancelled by the next page or by `close()`), the `/events`
463
- route and
464
- its 404 when the channel is off, a real socket that reads a page's first frame
465
- and the ticker's next one and sees the stream end when the server closes, the
466
- live chrome a page renders when on and not when off, and the command
467
- lifecycle with injected seams.
@@ -1,134 +0,0 @@
1
- /**
2
- * The HTTP server for the browse extension.
3
- *
4
- * Wraps `node:http` around the pure `handleRequest`: it resolves the root once,
5
- * binds `127.0.0.1`, streams `/raw` responses from disk, feeds the live status
6
- * channel, and exposes an idempotent `close()`. The request handler is injectable
7
- * so tests can avoid a socket when they only need routing.
8
- *
9
- * The bind, the response writer, the event-stream head, and the close come from
10
- * `lib/http`, which `plan` shares; what stays here is this server's own request
11
- * handler, its request count, and the catch that turns a thrown handler into a
12
- * plain-text 500.
13
- */
14
-
15
- import { realpathSync } from "node:fs";
16
- import { createServer } from "node:http";
17
- import {
18
- bindLoopback,
19
- createCloser,
20
- openEventStream,
21
- respond,
22
- textResponse,
23
- type ServeResponse,
24
- } from "../../lib/http/index.ts";
25
- import { IDLE_STOP_MS, type ServeConfig } from "./config.ts";
26
- import { createFileIndex } from "./files.ts";
27
- import type { GitDiffProvider, GitStatusProvider } from "./git.ts";
28
- import { createLiveChannel, createLiveStatus } from "./live.ts";
29
- import { handleRequest, type ServeContext } from "./router.ts";
30
-
31
- export interface FileServer {
32
- /** Origin URL, e.g. `http://127.0.0.1:49152/`. */
33
- url: string;
34
- /** The bound port. */
35
- port: number;
36
- /** Resolved absolute root that is actually served. */
37
- root: string;
38
- /** Stop listening. Safe to call more than once or before `listen` settles. */
39
- close(): Promise<void>;
40
- }
41
-
42
- export interface FileServerOptions {
43
- root: string;
44
- config: ServeConfig;
45
- /** Read-only git context for the page header; omitted when unavailable. */
46
- git?: GitStatusProvider;
47
- /** Read-only diff provider for the change and diff views; omitted when unavailable. */
48
- diff?: GitDiffProvider;
49
- /** Called once the last page has been gone for `idleStopMs`; omitted, the server waits for `close()`. */
50
- onIdle?: () => void;
51
- /** Grace before `onIdle`, in ms; defaults to `IDLE_STOP_MS`. */
52
- idleStopMs?: number;
53
- /** Override the request handler (tests). */
54
- handler?: typeof handleRequest;
55
- }
56
-
57
- /** Start a read-only server rooted at `options.root` on 127.0.0.1. */
58
- export async function createFileServer(options: FileServerOptions): Promise<FileServer> {
59
- const root = realpathSync.native(options.root);
60
- const { config } = options;
61
- // The status feed's two server-owned facts: how long it has been up, and how
62
- // many requests it has answered. Both are read per frame, never cached.
63
- let requests = 0;
64
- const status = config.live
65
- ? createLiveStatus({
66
- git: options.git,
67
- diff: config.gitDiff ? options.diff : undefined,
68
- startedAt: Date.now(),
69
- requests: () => requests,
70
- })
71
- : undefined;
72
- const live = status
73
- ? createLiveChannel({
74
- status,
75
- intervalMs: config.liveIntervalMs,
76
- idleMs: options.idleStopMs ?? IDLE_STOP_MS,
77
- onIdle: options.onIdle,
78
- })
79
- : undefined;
80
- const context: ServeContext = {
81
- root,
82
- config,
83
- git: options.git,
84
- diff: options.diff,
85
- index: createFileIndex(root, config.maxIndexEntries),
86
- live: status,
87
- };
88
- const handler = options.handler ?? handleRequest;
89
-
90
- const server = createServer((request, response) => {
91
- requests += 1;
92
- const answer = async (): Promise<ServeResponse> => {
93
- try {
94
- return await handler(context, request.method ?? "GET", request.url ?? "/", request.headers);
95
- } catch {
96
- return textResponse(500, "Internal error");
97
- }
98
- };
99
- void answer().then((result) => {
100
- // A HEAD of the stream is answered as a plain response: there is no body to
101
- // hold open, and the client would otherwise wait on frames it asked not to get.
102
- if (!result.stream || !live || (request.method ?? "GET").toUpperCase() === "HEAD") {
103
- respond(request, response, result);
104
- return;
105
- }
106
- openEventStream(response, result);
107
- const detach = live.attach({
108
- write: (frame) => {
109
- response.write(frame);
110
- },
111
- end: () => {
112
- if (!response.writableEnded) response.end();
113
- },
114
- });
115
- request.on("close", () => {
116
- detach();
117
- if (!response.writableEnded) response.end();
118
- });
119
- });
120
- });
121
-
122
- const port = await bindLoopback(server, config.port);
123
- const closeServer = createCloser(server);
124
- return {
125
- url: `http://127.0.0.1:${port}/`,
126
- port,
127
- root,
128
- close: async () => {
129
- // End the streams first, so a connected page does not hold the close open.
130
- live?.close();
131
- await closeServer();
132
- },
133
- };
134
- }