@pi-in-go/pigpen-ahp 0.1.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 (304) hide show
  1. package/CREDITS.md +27 -0
  2. package/LICENSE +23 -0
  3. package/README.md +148 -0
  4. package/extensions/ahp/access_options_test.go +116 -0
  5. package/extensions/ahp/extension.go +54 -0
  6. package/extensions/ahp/go.mod +12 -0
  7. package/extensions/ahp/go.sum +2 -0
  8. package/extensions/ahp/go.work +8 -0
  9. package/extensions/ahp/internal/channels/chat.go +110 -0
  10. package/extensions/ahp/internal/channels/root.go +32 -0
  11. package/extensions/ahp/internal/channels/session.go +128 -0
  12. package/extensions/ahp/internal/channels/session_test.go +108 -0
  13. package/extensions/ahp/internal/compose/compose.go +153 -0
  14. package/extensions/ahp/internal/compose/compose_test.go +120 -0
  15. package/extensions/ahp/internal/gaps/gaps_test.go +88 -0
  16. package/extensions/ahp/internal/host/handshake_test.go +206 -0
  17. package/extensions/ahp/internal/host/host.go +1305 -0
  18. package/extensions/ahp/internal/host/reconnect_test.go +197 -0
  19. package/extensions/ahp/internal/host/replaywindow_test.go +31 -0
  20. package/extensions/ahp/internal/host/schema_test.go +79 -0
  21. package/extensions/ahp/internal/host/store.go +291 -0
  22. package/extensions/ahp/internal/host/store_update_test.go +85 -0
  23. package/extensions/ahp/internal/host/subscriptions_test.go +160 -0
  24. package/extensions/ahp/internal/host/surface_test.go +95 -0
  25. package/extensions/ahp/internal/host/workarounds.go +458 -0
  26. package/extensions/ahp/internal/host/workarounds_test.go +96 -0
  27. package/extensions/ahp/internal/live/live.go +328 -0
  28. package/extensions/ahp/internal/live/live_test.go +91 -0
  29. package/extensions/ahp/internal/live/store.go +113 -0
  30. package/extensions/ahp/internal/mapper/activity.go +199 -0
  31. package/extensions/ahp/internal/mapper/activity_test.go +188 -0
  32. package/extensions/ahp/internal/mapper/bench_test.go +38 -0
  33. package/extensions/ahp/internal/mapper/event_mapper_test.go +380 -0
  34. package/extensions/ahp/internal/mapper/fixtures_test.go +387 -0
  35. package/extensions/ahp/internal/mapper/helpers_test.go +251 -0
  36. package/extensions/ahp/internal/mapper/js.go +131 -0
  37. package/extensions/ahp/internal/mapper/mapper.go +600 -0
  38. package/extensions/ahp/internal/mapper/message_input_test.go +196 -0
  39. package/extensions/ahp/internal/mapper/messageinput.go +272 -0
  40. package/extensions/ahp/internal/mapper/schema_helpers_test.go +5 -0
  41. package/extensions/ahp/internal/mapper/testdata/LICENSE-pi-ahp +21 -0
  42. package/extensions/ahp/internal/mapper/testdata/fixtures/abort.json +711 -0
  43. package/extensions/ahp/internal/mapper/testdata/fixtures/bash-long-output.json +1312 -0
  44. package/extensions/ahp/internal/mapper/testdata/fixtures/compaction.json +6285 -0
  45. package/extensions/ahp/internal/mapper/testdata/fixtures/parallel-tools.json +2622 -0
  46. package/extensions/ahp/internal/mapper/testdata/fixtures/plain-text.json +1856 -0
  47. package/extensions/ahp/internal/mapper/testdata/fixtures/single-tool.json +1128 -0
  48. package/extensions/ahp/internal/mapper/testdata/fixtures/steering.json +3926 -0
  49. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-bash.json +2372 -0
  50. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-edit.json +3983 -0
  51. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-error.json +2850 -0
  52. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-find.json +1162 -0
  53. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-grep.json +2783 -0
  54. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-loop.json +1693 -0
  55. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-ls.json +2427 -0
  56. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-write.json +1271 -0
  57. package/extensions/ahp/internal/mapper/title.go +34 -0
  58. package/extensions/ahp/internal/mapper/usermsg.go +87 -0
  59. package/extensions/ahp/internal/pi/activeturn_test.go +296 -0
  60. package/extensions/ahp/internal/pi/backend.go +64 -0
  61. package/extensions/ahp/internal/pi/catalogue.go +370 -0
  62. package/extensions/ahp/internal/pi/catalogue_test.go +271 -0
  63. package/extensions/ahp/internal/pi/chatdriver.go +533 -0
  64. package/extensions/ahp/internal/pi/chatdriver_test.go +416 -0
  65. package/extensions/ahp/internal/pi/clientactions.go +212 -0
  66. package/extensions/ahp/internal/pi/clientactions_test.go +273 -0
  67. package/extensions/ahp/internal/pi/completions.go +230 -0
  68. package/extensions/ahp/internal/pi/completions_test.go +272 -0
  69. package/extensions/ahp/internal/pi/config_test.go +269 -0
  70. package/extensions/ahp/internal/pi/deletesession.go +69 -0
  71. package/extensions/ahp/internal/pi/deletesession_test.go +153 -0
  72. package/extensions/ahp/internal/pi/disposal_test.go +362 -0
  73. package/extensions/ahp/internal/pi/fixture_test.go +308 -0
  74. package/extensions/ahp/internal/pi/foreign_test.go +122 -0
  75. package/extensions/ahp/internal/pi/harness_test.go +83 -0
  76. package/extensions/ahp/internal/pi/history.go +269 -0
  77. package/extensions/ahp/internal/pi/hydrated_test.go +171 -0
  78. package/extensions/ahp/internal/pi/hydratedlifecycle_test.go +196 -0
  79. package/extensions/ahp/internal/pi/hydration_test.go +209 -0
  80. package/extensions/ahp/internal/pi/hydrator.go +212 -0
  81. package/extensions/ahp/internal/pi/imageinput.go +224 -0
  82. package/extensions/ahp/internal/pi/imageinput_test.go +57 -0
  83. package/extensions/ahp/internal/pi/lifecycle_test.go +381 -0
  84. package/extensions/ahp/internal/pi/models.go +212 -0
  85. package/extensions/ahp/internal/pi/models_test.go +128 -0
  86. package/extensions/ahp/internal/pi/paging.go +95 -0
  87. package/extensions/ahp/internal/pi/pagingtruncate_test.go +323 -0
  88. package/extensions/ahp/internal/pi/projecttrust.go +222 -0
  89. package/extensions/ahp/internal/pi/registry.go +924 -0
  90. package/extensions/ahp/internal/pi/restart_test.go +185 -0
  91. package/extensions/ahp/internal/pi/services.go +70 -0
  92. package/extensions/ahp/internal/pi/sessionconfig.go +64 -0
  93. package/extensions/ahp/internal/pi/sessionfiles_test.go +74 -0
  94. package/extensions/ahp/internal/pi/sessionstore.go +83 -0
  95. package/extensions/ahp/internal/pi/summary_test.go +426 -0
  96. package/extensions/ahp/internal/pi/workarounds_wire_test.go +208 -0
  97. package/extensions/ahp/internal/pisession/fromentries_test.go +32 -0
  98. package/extensions/ahp/internal/pisession/json.go +31 -0
  99. package/extensions/ahp/internal/pisession/pisession.go +580 -0
  100. package/extensions/ahp/internal/settings/access.go +63 -0
  101. package/extensions/ahp/internal/settings/access_test.go +52 -0
  102. package/extensions/ahp/internal/settings/settings.go +117 -0
  103. package/extensions/ahp/internal/settings/settings_test.go +104 -0
  104. package/extensions/ahp/internal/svc/etag_other.go +15 -0
  105. package/extensions/ahp/internal/svc/etag_unix.go +34 -0
  106. package/extensions/ahp/internal/svc/glob.go +197 -0
  107. package/extensions/ahp/internal/svc/mime.go +37 -0
  108. package/extensions/ahp/internal/svc/paths.go +108 -0
  109. package/extensions/ahp/internal/svc/pty.go +64 -0
  110. package/extensions/ahp/internal/svc/pty_darwin.go +42 -0
  111. package/extensions/ahp/internal/svc/pty_linux.go +36 -0
  112. package/extensions/ahp/internal/svc/pty_other.go +9 -0
  113. package/extensions/ahp/internal/svc/pty_test.go +114 -0
  114. package/extensions/ahp/internal/svc/pty_unix.go +147 -0
  115. package/extensions/ahp/internal/svc/resource.go +495 -0
  116. package/extensions/ahp/internal/svc/resource_test.go +501 -0
  117. package/extensions/ahp/internal/svc/stat_bsd.go +9 -0
  118. package/extensions/ahp/internal/svc/stat_linux.go +9 -0
  119. package/extensions/ahp/internal/svc/terminal.go +454 -0
  120. package/extensions/ahp/internal/svc/terminal_test.go +512 -0
  121. package/extensions/ahp/internal/svc/watch.go +590 -0
  122. package/extensions/ahp/internal/svc/watch_test.go +627 -0
  123. package/extensions/ahp/internal/svc/watchevents_test.go +452 -0
  124. package/extensions/ahp/internal/svc/watchpolicy.go +81 -0
  125. package/extensions/ahp/internal/svc/watchpolicy_test.go +151 -0
  126. package/extensions/ahp/internal/svc/watchracy_test.go +61 -0
  127. package/extensions/ahp/internal/testkit/schema/LICENSE-agent-host-protocol +21 -0
  128. package/extensions/ahp/internal/testkit/schema/actions.schema.json +9208 -0
  129. package/extensions/ahp/internal/testkit/schema/commands.schema.json +10862 -0
  130. package/extensions/ahp/internal/testkit/schema/errors.schema.json +10928 -0
  131. package/extensions/ahp/internal/testkit/schema/notifications.schema.json +6667 -0
  132. package/extensions/ahp/internal/testkit/schema/state.schema.json +6392 -0
  133. package/extensions/ahp/internal/testkit/schema.go +360 -0
  134. package/extensions/ahp/internal/testkit/testkit.go +367 -0
  135. package/extensions/ahp/internal/twin/twin.go +27 -0
  136. package/extensions/ahp/internal/wire/dispatchable.go +106 -0
  137. package/extensions/ahp/internal/wire/dispatchable_list.go +15 -0
  138. package/extensions/ahp/internal/wire/helpers_test.go +5 -0
  139. package/extensions/ahp/internal/wire/wire.go +218 -0
  140. package/extensions/ahp/internal/wire/wire_test.go +123 -0
  141. package/extensions/ahp/internal/ws/helpers_test.go +7 -0
  142. package/extensions/ahp/internal/ws/vscode_test.go +198 -0
  143. package/extensions/ahp/internal/ws/ws.go +674 -0
  144. package/extensions/ahp/internal/ws/ws_test.go +324 -0
  145. package/extensions/ahp/realpig_test.go +589 -0
  146. package/extensions/ahp/runtime.go +311 -0
  147. package/extensions/ahp/runtime_test.go +110 -0
  148. package/extensions/ahp/testdata/upstream-tests.json +3833 -0
  149. package/extensions/ahp/third_party/agent-host-protocol-go/LICENSE +21 -0
  150. package/extensions/ahp/third_party/agent-host-protocol-go/NOTICE-PIGPEN.md +18 -0
  151. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/client.go +1011 -0
  152. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/error.go +111 -0
  153. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/multi_host_state_mirror.go +239 -0
  154. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/reducers.go +1939 -0
  155. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/transport.go +176 -0
  156. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/actions.generated.go +2447 -0
  157. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/commands.generated.go +1546 -0
  158. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/common.go +205 -0
  159. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/errors.generated.go +65 -0
  160. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/messages.generated.go +138 -0
  161. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/notifications.generated.go +264 -0
  162. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/state.generated.go +6171 -0
  163. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/version.generated.go +31 -0
  164. package/extensions/ahp/third_party/agent-host-protocol-go/go.mod +3 -0
  165. package/extensions/ahp/twins_test.go +91 -0
  166. package/package.json +40 -0
  167. package/proof/PORT.md +121 -0
  168. package/proof/mutations.json +152 -0
  169. package/proof/oracle/LICENSE +21 -0
  170. package/proof/oracle/README.md +120 -0
  171. package/proof/oracle/UPSTREAM.md +7 -0
  172. package/proof/oracle/package.json +68 -0
  173. package/proof/oracle/src/bin/cli.ts +66 -0
  174. package/proof/oracle/src/bin/tunnel.ts +128 -0
  175. package/proof/oracle/src/channels/chat.ts +134 -0
  176. package/proof/oracle/src/channels/root.ts +39 -0
  177. package/proof/oracle/src/channels/session.ts +118 -0
  178. package/proof/oracle/src/channels/terminal.ts +11 -0
  179. package/proof/oracle/src/core/channels.ts +108 -0
  180. package/proof/oracle/src/core/client-workarounds.ts +358 -0
  181. package/proof/oracle/src/core/connection.ts +41 -0
  182. package/proof/oracle/src/core/host.ts +882 -0
  183. package/proof/oracle/src/core/sequencer.ts +75 -0
  184. package/proof/oracle/src/core/state-store.ts +162 -0
  185. package/proof/oracle/src/core/uri.ts +25 -0
  186. package/proof/oracle/src/host/direct-settings.ts +110 -0
  187. package/proof/oracle/src/host/pi-host.ts +220 -0
  188. package/proof/oracle/src/host/serve.ts +71 -0
  189. package/proof/oracle/src/host/terminal-service.ts +346 -0
  190. package/proof/oracle/src/pi/activity.ts +171 -0
  191. package/proof/oracle/src/pi/changeset-service.ts +646 -0
  192. package/proof/oracle/src/pi/changeset-uri.ts +64 -0
  193. package/proof/oracle/src/pi/chat-driver.ts +529 -0
  194. package/proof/oracle/src/pi/completions.ts +160 -0
  195. package/proof/oracle/src/pi/delete-session.ts +53 -0
  196. package/proof/oracle/src/pi/event-mapper.ts +648 -0
  197. package/proof/oracle/src/pi/git-changes.ts +605 -0
  198. package/proof/oracle/src/pi/history.ts +305 -0
  199. package/proof/oracle/src/pi/image-input.ts +56 -0
  200. package/proof/oracle/src/pi/image-mime.ts +8 -0
  201. package/proof/oracle/src/pi/in-process-backend.ts +155 -0
  202. package/proof/oracle/src/pi/message-input.ts +212 -0
  203. package/proof/oracle/src/pi/models.ts +124 -0
  204. package/proof/oracle/src/pi/project-trust.ts +66 -0
  205. package/proof/oracle/src/pi/provider.ts +2 -0
  206. package/proof/oracle/src/pi/resource-paths.ts +80 -0
  207. package/proof/oracle/src/pi/resource-service.ts +356 -0
  208. package/proof/oracle/src/pi/resource-watch-policy.ts +35 -0
  209. package/proof/oracle/src/pi/resource-watch.ts +357 -0
  210. package/proof/oracle/src/pi/session-catalogue.ts +318 -0
  211. package/proof/oracle/src/pi/session-config.ts +84 -0
  212. package/proof/oracle/src/pi/session-history.ts +75 -0
  213. package/proof/oracle/src/pi/session-hydrator.ts +219 -0
  214. package/proof/oracle/src/pi/session-registry.ts +815 -0
  215. package/proof/oracle/src/pi/session-storage.ts +29 -0
  216. package/proof/oracle/src/pi/session-title.ts +18 -0
  217. package/proof/oracle/src/pi/turn-paging.ts +94 -0
  218. package/proof/oracle/src/pi/user-message.ts +66 -0
  219. package/proof/oracle/src/protocol/errors.ts +44 -0
  220. package/proof/oracle/src/protocol/jsonrpc.ts +89 -0
  221. package/proof/oracle/src/protocol/version.ts +39 -0
  222. package/proof/oracle/src/transport/websocket.ts +136 -0
  223. package/proof/oracle/src/tunnel/devtunnel.ts +293 -0
  224. package/proof/oracle/src/tunnel/discovery.ts +37 -0
  225. package/proof/oracle/test/active-turn-reconnect.test.ts +274 -0
  226. package/proof/oracle/test/activity.test.ts +171 -0
  227. package/proof/oracle/test/changeset-lifecycle.test.serial.ts +303 -0
  228. package/proof/oracle/test/changeset-uri.test.ts +37 -0
  229. package/proof/oracle/test/changeset.test.serial.ts +487 -0
  230. package/proof/oracle/test/chat-driver.test.ts +691 -0
  231. package/proof/oracle/test/client-actions.test.ts +409 -0
  232. package/proof/oracle/test/client-workarounds.test.ts +320 -0
  233. package/proof/oracle/test/completions.test.ts +323 -0
  234. package/proof/oracle/test/delete-session.test.ts +142 -0
  235. package/proof/oracle/test/direct-settings.test.ts +81 -0
  236. package/proof/oracle/test/event-mapper.test.ts +619 -0
  237. package/proof/oracle/test/fetch-turns.test.ts +207 -0
  238. package/proof/oracle/test/fixtures/abort.json +711 -0
  239. package/proof/oracle/test/fixtures/bash-long-output.json +1312 -0
  240. package/proof/oracle/test/fixtures/compaction.json +6285 -0
  241. package/proof/oracle/test/fixtures/parallel-tools.json +2622 -0
  242. package/proof/oracle/test/fixtures/plain-text.json +1856 -0
  243. package/proof/oracle/test/fixtures/single-tool.json +1128 -0
  244. package/proof/oracle/test/fixtures/steering.json +3926 -0
  245. package/proof/oracle/test/fixtures/tool-bash.json +2372 -0
  246. package/proof/oracle/test/fixtures/tool-edit.json +3983 -0
  247. package/proof/oracle/test/fixtures/tool-error.json +2850 -0
  248. package/proof/oracle/test/fixtures/tool-find.json +1162 -0
  249. package/proof/oracle/test/fixtures/tool-grep.json +2783 -0
  250. package/proof/oracle/test/fixtures/tool-loop.json +1693 -0
  251. package/proof/oracle/test/fixtures/tool-ls.json +2427 -0
  252. package/proof/oracle/test/fixtures/tool-write.json +1271 -0
  253. package/proof/oracle/test/handshake.test.ts +275 -0
  254. package/proof/oracle/test/harness.ts +153 -0
  255. package/proof/oracle/test/hydrated-session-lifecycle.test.ts +211 -0
  256. package/proof/oracle/test/image-input.test.ts +28 -0
  257. package/proof/oracle/test/image-session.test.ts +69 -0
  258. package/proof/oracle/test/live-turn.test.ts +304 -0
  259. package/proof/oracle/test/mapper-fixtures.test.ts +293 -0
  260. package/proof/oracle/test/message-input.test.ts +181 -0
  261. package/proof/oracle/test/model-discovery.test.ts +170 -0
  262. package/proof/oracle/test/models.test.ts +109 -0
  263. package/proof/oracle/test/pi-host.test.ts +91 -0
  264. package/proof/oracle/test/pi-replay.test.ts +141 -0
  265. package/proof/oracle/test/project-trust.test.ts +125 -0
  266. package/proof/oracle/test/protocol-surface.test.ts +121 -0
  267. package/proof/oracle/test/pty.test.ts +100 -0
  268. package/proof/oracle/test/reconnect.test.ts +389 -0
  269. package/proof/oracle/test/resource-watch-policy.test.ts +78 -0
  270. package/proof/oracle/test/resource-watch.test.serial.ts +536 -0
  271. package/proof/oracle/test/resource.test.ts +499 -0
  272. package/proof/oracle/test/schema.test.ts +88 -0
  273. package/proof/oracle/test/session-catalogue.test.ts +314 -0
  274. package/proof/oracle/test/session-config.test.ts +224 -0
  275. package/proof/oracle/test/session-disposal.test.ts +364 -0
  276. package/proof/oracle/test/session-hydration.test.ts +194 -0
  277. package/proof/oracle/test/session-lifecycle.test.ts +416 -0
  278. package/proof/oracle/test/session-storage.test.serial.ts +32 -0
  279. package/proof/oracle/test/session-summary.test.ts +418 -0
  280. package/proof/oracle/test/subscriptions.test.ts +198 -0
  281. package/proof/oracle/test/support/assertions.ts +32 -0
  282. package/proof/oracle/test/support/async.ts +26 -0
  283. package/proof/oracle/test/support/hydrated-session.ts +205 -0
  284. package/proof/oracle/test/support/images.ts +8 -0
  285. package/proof/oracle/test/support/recorded-fixtures.ts +60 -0
  286. package/proof/oracle/test/support/recorded-scenarios.ts +145 -0
  287. package/proof/oracle/test/support/replay.ts +194 -0
  288. package/proof/oracle/test/support/schema.ts +221 -0
  289. package/proof/oracle/test/support/session-files.ts +12 -0
  290. package/proof/oracle/test/support/session-storage.ts +22 -0
  291. package/proof/oracle/test/support/upstream.ts +25 -0
  292. package/proof/oracle/test/support/watch-events.ts +108 -0
  293. package/proof/oracle/test/terminal-service.test.ts +495 -0
  294. package/proof/oracle/test/truncate.test.ts +230 -0
  295. package/proof/oracle/test/tunnel.test.ts +258 -0
  296. package/proof/oracle/test/upstream-workarounds.test.ts +37 -0
  297. package/proof/oracle/test/uri.test.ts +24 -0
  298. package/proof/oracle/test/watch-events.test.ts +118 -0
  299. package/proof/oracle/tsconfig.json +32 -0
  300. package/proof/proof-piglet/piglet.yaml +18 -0
  301. package/proof/tools/fakellm/go.mod +3 -0
  302. package/proof/tools/fakellm/main.go +109 -0
  303. package/proof/tools/gen-dispatchable.py +30 -0
  304. package/provenance.json +28 -0
@@ -0,0 +1,815 @@
1
+ /**
2
+ * Live sessions: creation, disposal, adoption from disk, and routing client
3
+ * actions to whatever can carry them out.
4
+ *
5
+ * This is the pi-facing half of the session channel. The protocol-shaped half —
6
+ * building a `SessionState`, deriving a `SessionSummary` — lives in
7
+ * `channels/session.ts` and knows nothing about pi. The dependency runs one
8
+ * way: an adapter depends on the shapes it produces, never the reverse.
9
+ *
10
+ * The session URI's uuid **is** pi's session id. `SessionManager.create()`
11
+ * accepts an explicit id, so the two identity spaces are the same one and no
12
+ * persistent mapping table is needed.
13
+ *
14
+ * @see https://microsoft.github.io/agent-host-protocol/specification/session-channel
15
+ */
16
+
17
+ import type { SessionManager } from "@earendil-works/pi-coding-agent";
18
+ import {
19
+ ActionType,
20
+ type ChatState,
21
+ type Message,
22
+ MessageKind,
23
+ type ModelSelection,
24
+ PendingMessageKind,
25
+ ResponsePartKind,
26
+ type SessionState,
27
+ type SessionSummary,
28
+ type StateAction,
29
+ type URI,
30
+ } from "@microsoft/agent-host-protocol";
31
+ import { installDefaultChat, syncChatSummary } from "../channels/chat.ts";
32
+ import { notifySessionAdded, notifySessionRemoved, notifySessionSummaryChanged } from "../channels/root.ts";
33
+ import { aggregateSessionChats, initialSessionState, sessionSummaryOf } from "../channels/session.ts";
34
+ import { chatUri, ROOT_CHANNEL, sessionIdFromUri } from "../core/channels.ts";
35
+ import type { AhpHost } from "../core/host.ts";
36
+ import { fileUriToPath } from "../core/uri.ts";
37
+ import { ProtocolError } from "../protocol/errors.ts";
38
+ import { ChatDriver, type PiBackend } from "./chat-driver.ts";
39
+ import { messageRejectionReason } from "./message-input.ts";
40
+ import { PI_PROVIDER } from "./provider.ts";
41
+ import type { LiveSessionCatalogueEntry } from "./session-catalogue.ts";
42
+ import { dispatchOlderTurns, truncationAnchor } from "./session-history.ts";
43
+ import type { SessionManagerFactory } from "./session-storage.ts";
44
+ import { fallbackSessionTitle, NEW_SESSION_TITLE } from "./session-title.ts";
45
+
46
+ /** Everything the host tracks for a live session. */
47
+ export interface LiveSession {
48
+ readonly uri: URI;
49
+ /** pi's session id — identical to the uuid in `uri`. */
50
+ readonly sessionId: string;
51
+ readonly workingDirectory: string;
52
+ readonly sessionManager: SessionManager;
53
+ readonly createdAt: string;
54
+ /** The session's single chat channel. */
55
+ readonly chatChannel: URI;
56
+ /** Present once a backend is attached; absent while the session is storage-only. */
57
+ driver?: ChatDriver;
58
+ /**
59
+ * In-flight backend attach, so concurrent actions wait on one attempt.
60
+ *
61
+ * Explicitly `| undefined` rather than only optional: it is cleared by
62
+ * assignment when the attempt settles, which `exactOptionalPropertyTypes`
63
+ * distinguishes from never having been set.
64
+ */
65
+ attaching?: Promise<void> | undefined;
66
+ /**
67
+ * Turn id → the pi session entry that turn ends on.
68
+ *
69
+ * Truncation needs it: the protocol names a turn, pi navigates to an entry.
70
+ * Filled from the rebuild when a session is loaded from disk, and from the
71
+ * leaf pointer as live turns complete.
72
+ */
73
+ readonly turnAnchors: Map<string, string>;
74
+ }
75
+
76
+ /** Creates the agent backend for a session. Absent in storage-only mode. */
77
+ export type BackendFactory = (session: LiveSession) => Promise<PiBackend> | PiBackend;
78
+
79
+ function userMessageRejectionReason(message: Message, originReason: string): string | undefined {
80
+ return messageRejectionReason(message) ?? (message.origin.kind === MessageKind.User ? undefined : originReason);
81
+ }
82
+
83
+ function unsupportedClientActionReason(action: StateAction): string | undefined {
84
+ switch (action.type) {
85
+ case ActionType.SessionActiveClientSet:
86
+ case ActionType.SessionActiveClientRemoved:
87
+ return "This host does not accept active clients";
88
+ case ActionType.SessionWorkingDirectorySet:
89
+ case ActionType.SessionWorkingDirectoryRemoved:
90
+ case ActionType.SessionWorkingDirectoryReplaced:
91
+ case ActionType.ChatWorkingDirectorySet:
92
+ case ActionType.ChatWorkingDirectoryRemoved:
93
+ return "This agent does not support changing working directories";
94
+ case ActionType.SessionCustomizationToggled:
95
+ return "This host does not support customizations";
96
+ case ActionType.SessionMcpServerStartRequested:
97
+ case ActionType.SessionMcpServerStopRequested:
98
+ return "This host does not support MCP servers";
99
+ case ActionType.SessionIsReadChanged:
100
+ case ActionType.SessionIsArchivedChanged:
101
+ return "This host does not persist read or archive state";
102
+ case ActionType.SessionConfigChanged:
103
+ return "This session has no mutable configuration";
104
+ case ActionType.ChatToolCallConfirmed:
105
+ case ActionType.ChatToolCallComplete:
106
+ case ActionType.ChatToolCallResultConfirmed:
107
+ case ActionType.ChatToolCallContentChanged:
108
+ return "This host does not support client tool execution or confirmation";
109
+ case ActionType.ChatInputAnswerChanged:
110
+ case ActionType.ChatInputCompleted:
111
+ return "This host does not support interactive input requests";
112
+ case ActionType.ChatTurnResume:
113
+ return "This host cannot resume an errored turn";
114
+ default:
115
+ return undefined;
116
+ }
117
+ }
118
+
119
+ export interface CreateSessionRequest {
120
+ readonly channel: URI;
121
+ /**
122
+ * A set in the protocol, but this host does not declare
123
+ * `multipleWorkingDirectories`, which is what forbids a client from sending
124
+ * more than one. Anything past the first is ignored rather than refused —
125
+ * the session still runs, in the directory the client asked for first.
126
+ */
127
+ readonly workingDirectories?: readonly URI[];
128
+ readonly provider?: string;
129
+ }
130
+
131
+ export interface SessionFileDeletionResult {
132
+ readonly ok: boolean;
133
+ readonly error?: string;
134
+ }
135
+
136
+ export interface SessionRegistryOptions {
137
+ readonly host: AhpHost;
138
+ /** Used for sessions created without one of their own. */
139
+ readonly defaultWorkingDirectory?: string;
140
+ readonly createBackend?: BackendFactory;
141
+ /** Explicit storage boundary; composition chooses durable or in-memory sessions. */
142
+ readonly createSessionManager: SessionManagerFactory;
143
+ /** Seeds a new chat's draft so a client has a model selected from the start. */
144
+ readonly defaultSelection?: () => ModelSelection | undefined;
145
+ /** A failed result or rejection prevents protocol removal. */
146
+ readonly deleteFile?: (path: string) => SessionFileDeletionResult | Promise<SessionFileDeletionResult>;
147
+ /** Locates the file behind a session this host never ran. */
148
+ readonly findSessionFile?: (sessionId: string) => Promise<string | undefined>;
149
+ readonly log?: (message: string) => void;
150
+ }
151
+
152
+ export type SessionAvailableListener = (session: LiveSession) => void;
153
+ export type SessionDeletionCommittedListener = (sessionId: string) => void | Promise<void>;
154
+
155
+ export class SessionRegistry {
156
+ readonly #options: SessionRegistryOptions;
157
+ readonly #host: AhpHost;
158
+ readonly #sessions = new Map<URI, LiveSession>();
159
+ readonly #byChat = new Map<URI, LiveSession>();
160
+ /** Last root-catalog value used as a diff baseline; never authoritative state. */
161
+ readonly #summaryBaselines = new Map<URI, SessionSummary>();
162
+ /** Coalesces duplicate disposal requests and blocks new work during deletion. */
163
+ readonly #disposals = new Map<URI, Promise<void>>();
164
+ /** Prevents projection-generated session actions from recursively republishing. */
165
+ readonly #projectingSessions = new Set<URI>();
166
+ readonly #sessionAvailableListeners = new Set<SessionAvailableListener>();
167
+ readonly #sessionDeletionCommittedListeners = new Set<SessionDeletionCommittedListener>();
168
+
169
+ constructor(options: SessionRegistryOptions) {
170
+ this.#options = options;
171
+ this.#host = options.host;
172
+
173
+ // Client actions are routed to whichever channel owns them; the host
174
+ // core stays agnostic of chats and backends.
175
+ this.#host.onActionCommitted((channel, action) => {
176
+ const owner = this.#byChat.get(channel);
177
+ if (owner) {
178
+ if (action.type === ActionType.ChatTurnStarted) {
179
+ this.#applyFallbackTitle(owner, action.message.text);
180
+ }
181
+ this.#syncChatProjection(owner);
182
+ return;
183
+ }
184
+ const session = this.#sessions.get(channel);
185
+ if (session && !this.#projectingSessions.has(channel)) {
186
+ this.#publishSummary(session);
187
+ }
188
+ });
189
+
190
+ this.#host.onClientAction((channel, action) => {
191
+ void this.#routeClientAction(channel, action).catch((error) => {
192
+ this.#options.log?.(`side effect failed for ${channel}: ${String(error)}`);
193
+ });
194
+ });
195
+
196
+ this.#host.addClientActionValidator((channel, action) => this.#validateClientAction(channel, action));
197
+ }
198
+
199
+ // ── Lookup ──────────────────────────────────────────────────────────────
200
+
201
+ get(uri: URI): LiveSession | undefined {
202
+ return this.#sessions.get(uri);
203
+ }
204
+
205
+ getByChat(chatChannel: URI): LiveSession | undefined {
206
+ return this.#byChat.get(chatChannel);
207
+ }
208
+
209
+ has(uri: URI): boolean {
210
+ return this.#sessions.has(uri);
211
+ }
212
+
213
+ isDisposing(uri: URI): boolean {
214
+ return this.#disposals.has(uri);
215
+ }
216
+
217
+ /** Observes sessions after their registry and protocol channels exist. */
218
+ onSessionAvailable(listener: SessionAvailableListener): () => void {
219
+ this.#sessionAvailableListeners.add(listener);
220
+ for (const session of this.#sessions.values()) this.#notifySessionAvailable(listener, session);
221
+ return () => this.#sessionAvailableListeners.delete(listener);
222
+ }
223
+
224
+ /** Runs after durable deletion commits, before protocol channels disappear. */
225
+ onSessionDeletionCommitted(listener: SessionDeletionCommittedListener): () => void {
226
+ this.#sessionDeletionCommittedListeners.add(listener);
227
+ return () => this.#sessionDeletionCommittedListeners.delete(listener);
228
+ }
229
+
230
+ /** Live summaries that override or supplement pi's on-disk catalogue. */
231
+ catalogueOverrides(): LiveSessionCatalogueEntry[] {
232
+ return [...this.#sessions.values()].map((session) => {
233
+ const file = session.sessionManager.getSessionFile();
234
+ return {
235
+ summary: this.#summaryOf(session),
236
+ ...(file ? { file } : {}),
237
+ };
238
+ });
239
+ }
240
+
241
+ // ── Lifecycle ───────────────────────────────────────────────────────────
242
+
243
+ /**
244
+ * Handles `createSession`.
245
+ *
246
+ * Returns as soon as the channel exists; readiness arrives later as a
247
+ * `session/ready` action on that channel.
248
+ */
249
+ create(request: CreateSessionRequest): void {
250
+ const uri = request.channel;
251
+ // Only canonical and provider-alias URIs can be recovered after a host restart.
252
+ const sessionId = sessionIdFromUri(uri, [PI_PROVIDER]);
253
+ if (!sessionId) {
254
+ throw ProtocolError.invalidParams(`Not a session URI: ${uri}`);
255
+ }
256
+ if (this.#disposals.has(uri) || this.#sessions.has(uri) || this.#host.store.has(uri)) {
257
+ throw ProtocolError.sessionAlreadyExists(uri);
258
+ }
259
+ if (request.provider !== undefined && request.provider !== PI_PROVIDER) {
260
+ throw ProtocolError.providerNotFound(request.provider);
261
+ }
262
+
263
+ const requested = request.workingDirectories?.[0];
264
+ const workingDirectory = requested
265
+ ? fileUriToPath(requested)
266
+ : (this.#options.defaultWorkingDirectory ?? process.cwd());
267
+
268
+ const title = NEW_SESSION_TITLE;
269
+ const createdAt = new Date().toISOString();
270
+ // A provider-alias URI still needs the session reducer.
271
+ this.#host.store.create(uri, initialSessionState(PI_PROVIDER, title, workingDirectory), "session");
272
+
273
+ // pi withholds the session file until an assistant message exists; the
274
+ // manager still owns the target directory and in-memory entry tree now.
275
+ const sessionManager = this.#options.createSessionManager(workingDirectory, sessionId);
276
+ const chatChannel = installDefaultChat(this.#host, uri, sessionId, title, this.#options.defaultSelection?.());
277
+
278
+ const session: LiveSession = {
279
+ uri,
280
+ sessionId,
281
+ workingDirectory,
282
+ sessionManager,
283
+ chatChannel,
284
+ createdAt,
285
+ turnAnchors: new Map(),
286
+ };
287
+ this.#track(session);
288
+ this.#notifySessionAvailableToAll(session);
289
+
290
+ const summary = this.#summaryOf(session);
291
+ notifySessionAdded(this.#host, summary);
292
+ this.#summaryBaselines.set(uri, summary);
293
+ this.#bumpActiveSessions();
294
+
295
+ // Readiness is genuinely asynchronous once a backend is involved: the
296
+ // client already holds the channel and sees `lifecycle: 'creating'` until
297
+ // the agent is up.
298
+ void this.#attachBackend(session);
299
+ }
300
+
301
+ /**
302
+ * Registers a session loaded from disk.
303
+ *
304
+ * Deliberately without a backend: a client browsing its history would
305
+ * otherwise start an agent for every session it looks at. The agent is
306
+ * attached on the first action that needs one.
307
+ */
308
+ adopt(
309
+ session: Omit<LiveSession, "driver" | "attaching" | "turnAnchors"> & {
310
+ turnAnchors?: Map<string, string>;
311
+ },
312
+ ): LiveSession {
313
+ const existing = this.#sessions.get(session.uri);
314
+ if (existing) {
315
+ return existing;
316
+ }
317
+ const adopted: LiveSession = { ...session, turnAnchors: session.turnAnchors ?? new Map() };
318
+ this.#track(adopted);
319
+ this.#notifySessionAvailableToAll(adopted);
320
+ this.#summaryBaselines.set(adopted.uri, this.#summaryOf(adopted));
321
+ this.#bumpActiveSessions();
322
+ return adopted;
323
+ }
324
+
325
+ /**
326
+ * Handles `disposeSession`.
327
+ *
328
+ * Works for any session in the catalogue, not just ones this host has
329
+ * running. Most sessions a client can see were written by pi and have never
330
+ * been live here, so refusing to dispose them would make the delete
331
+ * affordance fail on almost everything the list shows.
332
+ *
333
+ * AHP requires backend teardown and catalogue removal but does not prescribe
334
+ * how a host stores sessions. This catalogue is the set of pi session files,
335
+ * so stable removal also requires deleting the backing file via the same
336
+ * trash-then-unlink path pi's own `/resume` delete uses.
337
+ */
338
+ dispose(uri: URI): Promise<void> {
339
+ const pending = this.#disposals.get(uri);
340
+ if (pending) {
341
+ return pending;
342
+ }
343
+
344
+ // Defer the work so the gate is installed before backend shutdown can emit
345
+ // events or any other message can observe the transition.
346
+ const operation = Promise.resolve().then(() => this.#disposeOnce(uri));
347
+ this.#disposals.set(uri, operation);
348
+ const clear = (): void => {
349
+ if (this.#disposals.get(uri) === operation) {
350
+ this.#disposals.delete(uri);
351
+ }
352
+ };
353
+ void operation.then(clear, clear);
354
+ return operation;
355
+ }
356
+
357
+ async #disposeOnce(uri: URI): Promise<void> {
358
+ const session = this.#sessions.get(uri);
359
+ let sessionId: string;
360
+ let file: string | undefined;
361
+ let quiesced: ChatDriver | undefined;
362
+
363
+ try {
364
+ if (session) {
365
+ sessionId = session.sessionId;
366
+ quiesced = session.driver;
367
+ await quiesced?.quiesce();
368
+ file = session.sessionManager.getSessionFile();
369
+
370
+ // Storage-only or failed-start backends have no driver to close a turn.
371
+ const chat = this.#host.store.get(session.chatChannel) as ChatState | undefined;
372
+ if (chat?.activeTurn) {
373
+ const started = Date.parse(chat.activeTurn.startedAt);
374
+ this.#host.dispatchServerAction(session.chatChannel, {
375
+ type: ActionType.ChatTurnCancelled,
376
+ turnId: chat.activeTurn.id,
377
+ duration: Number.isFinite(started) ? Math.max(0, Date.now() - started) : 0,
378
+ });
379
+ }
380
+ } else {
381
+ const kind = this.#host.store.kindOf(uri);
382
+ if (kind !== undefined && kind !== "session") {
383
+ throw ProtocolError.sessionNotFound(uri);
384
+ }
385
+ const parsedId = sessionIdFromUri(uri, [PI_PROVIDER]);
386
+ if (!parsedId) {
387
+ throw ProtocolError.sessionNotFound(uri);
388
+ }
389
+ sessionId = parsedId;
390
+ file = await this.#options.findSessionFile?.(sessionId);
391
+ if (!file && !this.#host.store.has(uri)) {
392
+ throw ProtocolError.sessionNotFound(uri);
393
+ }
394
+ }
395
+
396
+ if (file) {
397
+ const deleteFile = this.#options.deleteFile;
398
+ if (!deleteFile) {
399
+ throw new Error("durable session deletion is not configured");
400
+ }
401
+ const result = await deleteFile(file);
402
+ if (!result.ok) {
403
+ throw new Error(result.error ?? "the durable session file remains");
404
+ }
405
+ }
406
+ } catch (error) {
407
+ quiesced?.resume();
408
+ if (error instanceof ProtocolError) {
409
+ throw error;
410
+ }
411
+ const message = error instanceof Error ? error.message : String(error);
412
+ throw new Error(`Could not dispose session ${uri}: ${message}`);
413
+ }
414
+
415
+ // Durable deletion is now committed. Protocol children disappear before
416
+ // the parent so their subscribers can observe final cleanup actions.
417
+ for (const listener of this.#sessionDeletionCommittedListeners) {
418
+ try {
419
+ await listener(sessionId);
420
+ } catch (error) {
421
+ this.#options.log?.(`protocol child cleanup failed for ${uri}: ${String(error)}`);
422
+ }
423
+ }
424
+
425
+ // Re-read the live entry defensively so cleanup cannot leave registry and
426
+ // protocol state disagreeing.
427
+ const current = this.#sessions.get(uri);
428
+ if (current) {
429
+ current.driver?.dispose();
430
+ this.#sessions.delete(uri);
431
+ this.#byChat.delete(current.chatChannel);
432
+ // Disposing a session cascades to every chat in its catalog.
433
+ this.#host.deleteChannel(current.chatChannel);
434
+ } else {
435
+ this.#host.deleteChannel(chatUri(sessionId));
436
+ }
437
+ this.#host.deleteChannel(uri);
438
+ this.#summaryBaselines.delete(uri);
439
+ notifySessionRemoved(this.#host, uri);
440
+ this.#bumpActiveSessions();
441
+ }
442
+
443
+ // ── Backend attachment ──────────────────────────────────────────────────
444
+
445
+ async #attachBackend(session: LiveSession): Promise<void> {
446
+ // Concurrent actions during startup must wait on one attempt, not race
447
+ // to build a second agent over the same session file.
448
+ if (session.attaching) {
449
+ return session.attaching;
450
+ }
451
+ session.attaching = this.#startBackend(session).finally(() => {
452
+ session.attaching = undefined;
453
+ });
454
+ return session.attaching;
455
+ }
456
+
457
+ async #startBackend(session: LiveSession): Promise<void> {
458
+ if (!this.#options.createBackend) {
459
+ // Storage-only mode: the session owns identity and history but has no
460
+ // agent, so it is ready as soon as it exists.
461
+ this.#host.dispatchServerAction(session.uri, { type: ActionType.SessionReady });
462
+ return;
463
+ }
464
+ try {
465
+ const backend = await this.#options.createBackend(session);
466
+ // Disposal may win while an asynchronous backend is starting. Never
467
+ // attach a late backend to a session that no longer exists.
468
+ if (this.#sessions.get(session.uri) !== session) {
469
+ backend.dispose?.();
470
+ return;
471
+ }
472
+ session.driver = new ChatDriver({
473
+ host: this.#host,
474
+ chatChannel: session.chatChannel,
475
+ backend,
476
+ workingDirectory: session.workingDirectory,
477
+ // A completed turn's last entry is wherever the leaf now points.
478
+ recordTurnAnchor: (turnId) => {
479
+ const leaf = session.sessionManager.getLeafEntry();
480
+ // Navigating to a user entry branches before it, so it cannot
481
+ // represent "keep this cancelled user-only turn" safely.
482
+ if (!leaf || (leaf.type === "message" && leaf.message.role === "user")) {
483
+ return;
484
+ }
485
+ session.turnAnchors.set(turnId, leaf.id);
486
+ },
487
+ ...(this.#options.log ? { log: this.#options.log } : {}),
488
+ });
489
+ this.#host.dispatchServerAction(session.uri, { type: ActionType.SessionReady });
490
+ // Tell the client which model and reasoning effort are actually in
491
+ // effect. There is no protocol field for a "default model", but a
492
+ // client initialises its input from `ChatState.draft`, so seeding the
493
+ // draft's selection is how a host answers that question.
494
+ session.driver.publishDefaultSelection();
495
+ } catch (error) {
496
+ if (this.#sessions.get(session.uri) !== session) return;
497
+ const message = error instanceof Error ? error.message : String(error);
498
+ this.#host.dispatchServerAction(session.uri, {
499
+ type: ActionType.SessionCreationFailed,
500
+ error: { errorType: "backendStartFailed", message },
501
+ });
502
+
503
+ // A turn may already be active: the client's `chat/turnStarted` was
504
+ // reduced before the agent was asked for. Nothing will ever emit
505
+ // `agent_settled` now, so close it here or the chat sits in progress
506
+ // forever with no reply and no error.
507
+ const chat = this.#host.store.get(session.chatChannel) as ChatState | undefined;
508
+ if (chat?.activeTurn) {
509
+ this.#host.dispatchServerAction(session.chatChannel, {
510
+ type: ActionType.ChatError,
511
+ turnId: chat.activeTurn.id,
512
+ duration: 0,
513
+ part: {
514
+ kind: ResponsePartKind.Error,
515
+ error: { errorType: "backendStartFailed", message },
516
+ },
517
+ });
518
+ }
519
+ }
520
+ }
521
+
522
+ // ── Client actions ──────────────────────────────────────────────────────
523
+
524
+ #validateClientAction(channel: URI, action: StateAction): string | undefined {
525
+ const session = this.#sessions.get(channel) ?? this.#byChat.get(channel);
526
+ if (this.#disposals.has(channel) || (session && this.#disposals.has(session.uri))) {
527
+ return "This session is being disposed";
528
+ }
529
+
530
+ const unsupported = unsupportedClientActionReason(action);
531
+ if (unsupported) {
532
+ return unsupported;
533
+ }
534
+
535
+ const chat = this.#host.store.get(channel) as ChatState | undefined;
536
+ switch (action.type) {
537
+ case ActionType.SessionTitleChanged:
538
+ return typeof action.title === "string" ? undefined : "A session title must be a string";
539
+ case ActionType.ChatTurnStarted: {
540
+ if (typeof action.turnId !== "string" || typeof action.startedAt !== "string") {
541
+ return "A turn requires string turnId and startedAt fields";
542
+ }
543
+ const invalid = userMessageRejectionReason(
544
+ action.message,
545
+ "A client can only start a turn with a user message",
546
+ );
547
+ if (invalid) return invalid;
548
+ if (action.queuedMessageId !== undefined) {
549
+ return "Only the host can start a queued message";
550
+ }
551
+ return chat?.activeTurn ? "A turn is already active" : undefined;
552
+ }
553
+ case ActionType.ChatTurnCancelled:
554
+ if (typeof action.turnId !== "string" || typeof action.duration !== "number") {
555
+ return "Turn cancellation requires a turnId and duration";
556
+ }
557
+ return chat?.activeTurn?.id === action.turnId ? undefined : "No matching active turn to cancel";
558
+ case ActionType.ChatPendingMessageSet: {
559
+ if (
560
+ typeof action.id !== "string" ||
561
+ (action.kind !== PendingMessageKind.Steering && action.kind !== PendingMessageKind.Queued)
562
+ ) {
563
+ return "A pending message requires an id and supported kind";
564
+ }
565
+ return userMessageRejectionReason(action.message, "A client can only queue a user message");
566
+ }
567
+ case ActionType.ChatPendingMessageRemoved:
568
+ if (typeof action.id !== "string") return "A pending message removal requires an id";
569
+ if (action.kind === PendingMessageKind.Steering) {
570
+ return "A steering message cannot be withdrawn after pi has queued it";
571
+ }
572
+ if (action.kind !== PendingMessageKind.Queued) return "Unsupported pending message kind";
573
+ return chat?.queuedMessages?.some((message) => message.id === action.id)
574
+ ? undefined
575
+ : "No matching queued message to remove";
576
+ case ActionType.ChatQueuedMessagesReordered:
577
+ return Array.isArray(action.order) && action.order.every((id) => typeof id === "string")
578
+ ? undefined
579
+ : "Queued message order must be an array of ids";
580
+ case ActionType.ChatDraftChanged: {
581
+ if (action.draft === undefined) return undefined;
582
+ return userMessageRejectionReason(action.draft, "A client can only draft a user message");
583
+ }
584
+ case ActionType.ChatTruncated: {
585
+ if (action.turnId !== undefined && typeof action.turnId !== "string") {
586
+ return "A truncation turnId must be a string";
587
+ }
588
+ // Accepting an impossible truncation would shorten the client's view
589
+ // while pi kept using context the user believes is gone.
590
+ const session = this.#byChat.get(channel);
591
+ if (!session) {
592
+ return undefined;
593
+ }
594
+ return truncationAnchor(session, action.turnId)
595
+ ? undefined
596
+ : `Cannot truncate: no session entry matches turn ${action.turnId ?? "(all)"}`;
597
+ }
598
+ default:
599
+ return undefined;
600
+ }
601
+ }
602
+
603
+ /**
604
+ * Routes a client action to whatever owns it.
605
+ *
606
+ * Chat actions go to the chat's driver, starting the agent first if this
607
+ * session has only ever been read from disk. Session actions are handled
608
+ * here — they carry no turn and need no agent.
609
+ */
610
+ async #routeClientAction(channel: URI, action: StateAction): Promise<void> {
611
+ const owningSession = this.#sessions.get(channel);
612
+ if (owningSession) {
613
+ this.#handleSessionAction(owningSession, action);
614
+ return;
615
+ }
616
+
617
+ const session = this.#byChat.get(channel);
618
+ if (!session) {
619
+ return;
620
+ }
621
+ if (!session.driver) {
622
+ await this.#attachBackend(session);
623
+ }
624
+ // An action accepted before disposal may have been waiting for lazy
625
+ // backend startup. On failure it still belongs to the surviving session;
626
+ // on success there is no session left to mutate.
627
+ const disposal = this.#disposals.get(session.uri);
628
+ if (disposal) {
629
+ try {
630
+ await disposal;
631
+ return;
632
+ } catch {
633
+ // Disposal rolled back; continue with the action already in state.
634
+ }
635
+ }
636
+ if (this.#sessions.get(session.uri) !== session) {
637
+ return;
638
+ }
639
+ if (action.type === ActionType.ChatTruncated) {
640
+ await this.#truncate(session, action.turnId);
641
+ return;
642
+ }
643
+ if (action.type === ActionType.ChatTurnStarted) {
644
+ const chat = this.#host.store.get(channel) as ChatState | undefined;
645
+ if (chat?.activeTurn?.id !== action.turnId) {
646
+ return;
647
+ }
648
+ }
649
+ session.driver?.handleClientAction(channel, action);
650
+ }
651
+
652
+ #handleSessionAction(session: LiveSession, action: StateAction): void {
653
+ if (action.type !== ActionType.SessionTitleChanged) {
654
+ return;
655
+ }
656
+
657
+ // The reducer has already updated the in-memory title. Persisting it is
658
+ // what makes the rename survive a restart: pi stores session names as
659
+ // `session_info` entries, and this is the same call its own `/resume`
660
+ // rename makes — so a session renamed here reads the same in pi's CLI.
661
+ try {
662
+ session.sessionManager.appendSessionInfo(action.title);
663
+ } catch (error) {
664
+ this.#options.log?.(`could not persist title for ${session.uri}: ${String(error)}`);
665
+ }
666
+
667
+ // The chat mirrors the session's title. Updating its modification time
668
+ // lets the ordinary chat-to-session projection update the root catalogue.
669
+ this.#renameChat(session, action.title);
670
+ }
671
+
672
+ #applyFallbackTitle(session: LiveSession, firstUserMessage: string): void {
673
+ const state = this.#host.store.get(session.uri) as SessionState | undefined;
674
+ if (state?.title !== NEW_SESSION_TITLE || session.sessionManager.getSessionName()) {
675
+ return;
676
+ }
677
+ const title = fallbackSessionTitle(firstUserMessage);
678
+ if (!title) {
679
+ return;
680
+ }
681
+
682
+ // This is pi's unnamed-session fallback, not an explicit session name:
683
+ // publish it to AHP without adding a `session_info` entry.
684
+ this.#host.dispatchServerAction(session.uri, { type: ActionType.SessionTitleChanged, title });
685
+ this.#renameChat(session, title, false);
686
+ }
687
+
688
+ #renameChat(session: LiveSession, title: string, touch = true): void {
689
+ const chat = this.#host.store.get(session.chatChannel) as ChatState | undefined;
690
+ if (!chat || chat.title === title) {
691
+ return;
692
+ }
693
+ // There is no chat title action in AHP 0.9. Replace the authoritative
694
+ // chat state, then run the same projection used after ordinary actions.
695
+ this.#host.store.create(
696
+ session.chatChannel,
697
+ { ...chat, title, ...(touch ? { modifiedAt: new Date().toISOString() } : {}) },
698
+ "chat",
699
+ );
700
+ this.#syncChatProjection(session);
701
+ }
702
+
703
+ // ── History ─────────────────────────────────────────────────────────────
704
+
705
+ /** Serves `fetchTurns`; the page is dispatched before this resolves. */
706
+ async fetchTurns(channel: URI, cursor: string | undefined): Promise<void> {
707
+ const session = this.#byChat.get(channel);
708
+ if (!session) {
709
+ throw ProtocolError.notFound(channel);
710
+ }
711
+ dispatchOlderTurns(this.#host, channel, session, cursor);
712
+ }
713
+
714
+ async #truncate(session: LiveSession, turnId: string | undefined): Promise<void> {
715
+ const anchor = truncationAnchor(session, turnId);
716
+ if (!anchor) {
717
+ // Validated before the action was applied, so this only happens if
718
+ // the file changed underneath us.
719
+ this.#options.log?.(`no truncation anchor for ${turnId ?? "(all)"} in ${session.uri}`);
720
+ return;
721
+ }
722
+ const applied = await session.driver?.truncate(anchor);
723
+ if (applied === false) {
724
+ // An extension vetoed it. Protocol state is already truncated, so
725
+ // the two have diverged; say so loudly rather than pretend.
726
+ this.#options.log?.(`agent refused truncation of ${session.uri}; state and session now differ`);
727
+ }
728
+ }
729
+
730
+ // ── Internals ───────────────────────────────────────────────────────────
731
+
732
+ #summaryOf(session: LiveSession): SessionSummary {
733
+ const state = this.#host.store.get(session.uri) as SessionState | undefined;
734
+ if (!state) {
735
+ throw new Error(`Session state is missing: ${session.uri}`);
736
+ }
737
+ return sessionSummaryOf(session.uri, session.createdAt, state, {
738
+ ...state._meta,
739
+ piSessionId: session.sessionId,
740
+ });
741
+ }
742
+
743
+ /** Publishes only changed root-catalog fields. */
744
+ #publishSummary(session: LiveSession): void {
745
+ const current = this.#summaryOf(session);
746
+ const previous = this.#summaryBaselines.get(session.uri);
747
+ const changes: Partial<SessionSummary> = {};
748
+ if (!previous || current.title !== previous.title) changes.title = current.title;
749
+ if (!previous || current.status !== previous.status) changes.status = current.status;
750
+ if (!previous || current.modifiedAt !== previous.modifiedAt) changes.modifiedAt = current.modifiedAt;
751
+ this.#summaryBaselines.set(session.uri, current);
752
+ if (Object.keys(changes).length > 0) {
753
+ notifySessionSummaryChanged(this.#host, session.uri, changes);
754
+ }
755
+ }
756
+
757
+ /**
758
+ * Projects a reduced chat summary onto its parent session and root catalog.
759
+ *
760
+ * The official 0.9 reducer cannot update top-level `SessionState.status`, so
761
+ * this deliberately leaves that field alone. Clients still receive the live
762
+ * status in `SessionState.chats[]`, `ChatState`, and the root summary.
763
+ */
764
+ #syncChatProjection(session: LiveSession): void {
765
+ this.#projectingSessions.add(session.uri);
766
+ let changed = false;
767
+ try {
768
+ changed = syncChatSummary(this.#host, session.uri, session.chatChannel);
769
+ if (!changed) {
770
+ return;
771
+ }
772
+
773
+ const state = this.#host.store.get(session.uri) as SessionState | undefined;
774
+ if (!state) {
775
+ return;
776
+ }
777
+ const aggregate = aggregateSessionChats(state);
778
+ if (state.activity !== aggregate.activity) {
779
+ this.#host.dispatchServerAction(session.uri, {
780
+ type: ActionType.SessionActivityChanged,
781
+ activity: aggregate.activity,
782
+ });
783
+ }
784
+ } finally {
785
+ this.#projectingSessions.delete(session.uri);
786
+ }
787
+ if (changed && this.#sessions.get(session.uri) === session) {
788
+ this.#publishSummary(session);
789
+ }
790
+ }
791
+
792
+ #track(session: LiveSession): void {
793
+ this.#sessions.set(session.uri, session);
794
+ this.#byChat.set(session.chatChannel, session);
795
+ }
796
+
797
+ #notifySessionAvailableToAll(session: LiveSession): void {
798
+ for (const listener of this.#sessionAvailableListeners) this.#notifySessionAvailable(listener, session);
799
+ }
800
+
801
+ #notifySessionAvailable(listener: SessionAvailableListener, session: LiveSession): void {
802
+ try {
803
+ listener(session);
804
+ } catch (error) {
805
+ this.#options.log?.(`session availability listener failed for ${session.uri}: ${String(error)}`);
806
+ }
807
+ }
808
+
809
+ #bumpActiveSessions(): void {
810
+ this.#host.dispatchServerAction(ROOT_CHANNEL, {
811
+ type: ActionType.RootActiveSessionsChanged,
812
+ activeSessions: this.#sessions.size,
813
+ });
814
+ }
815
+ }