@openchamber/web 2.0.2 → 2.0.4

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 (257) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -1
  2. package/bin/lib/commands-connect-url.js +6 -5
  3. package/bin/lib/commands-tunnel.js +24 -5
  4. package/dist/assets/{CodeMirrorCommentWidgets-CmKmyb9T.js → CodeMirrorCommentWidgets-C_zL-eri.js} +1 -1
  5. package/dist/assets/{DiffView-8-PFpZ2p.js → DiffView-BeN2_YYF.js} +3 -3
  6. package/dist/assets/FilesView-CN34wm_N.js +17 -0
  7. package/dist/assets/{GitView-DNUSu00w.js → GitView-DLDazOo1.js} +4 -4
  8. package/dist/assets/{GuestAttachDialog-Cv6QzjHC.js → GuestAttachDialog-C0xe_Lyy.js} +1 -1
  9. package/dist/assets/{GuestSurfacePane-Bt3jB_Ye.js → GuestSurfacePane-BdaurnDr.js} +1 -1
  10. package/dist/assets/{JsonTreeView-BlyHTRhM.js → JsonTreeView-B1Xq-k2t.js} +1 -1
  11. package/dist/assets/LinearIssuesView-BryoAHow.js +1 -0
  12. package/dist/assets/{MarkdownImageGallery-2UXJF-5B.js → MarkdownImageGallery-DfuEoaGq.js} +1 -1
  13. package/dist/assets/MarkdownRendererImpl-B_ZcWOvX.js +12 -0
  14. package/dist/assets/OnboardingScreen-C22bGmnP.js +1 -0
  15. package/dist/assets/{PatchDiff-ByvnbG5T.js → PatchDiff-0xd6UeFB.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-BXieg0mH.js → PierreDiffViewer-BC950e3F.js} +3 -3
  17. package/dist/assets/PlanView-B7Xgihqk.js +5 -0
  18. package/dist/assets/PluginPane-2C71F8uF.js +3 -0
  19. package/dist/assets/SettingsView-m_zoFiaT.js +30 -0
  20. package/dist/assets/{SettingsWindow-BIz224xs.js → SettingsWindow-CofS020b.js} +1 -1
  21. package/dist/assets/{SubmoduleDiffSummary-CXKmlps9.js → SubmoduleDiffSummary-BSA9gnIO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-BsgAK8xu.js → ToolOutputDialog-DprkVKcj.js} +7 -7
  23. package/dist/assets/{ToolPartDiffPreview-vdPObXOf.js → ToolPartDiffPreview-Dq0go_fX.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-BkFNKWS5.js → VirtualizedFileDiff-Kp8hKJdT.js} +1 -1
  25. package/dist/assets/WalkthroughView-DGnTzqIU.js +4 -0
  26. package/dist/assets/{appThemeRegistry-aHUNHoqP.js → appThemeRegistry-BdEHBA4s.js} +1 -1
  27. package/dist/assets/{commitAndPush-Bon9r94r.js → commitAndPush-LwtVa2Oc.js} +1 -1
  28. package/dist/assets/{computeVirtualFileMetrics-DKqr_1AQ.js → computeVirtualFileMetrics-6V1xNpO9.js} +2 -2
  29. package/dist/assets/de-DlgBHUAI.js +10 -0
  30. package/dist/assets/es-BC8G41U8.js +16 -0
  31. package/dist/assets/fr-I0z3vVjy.js +14 -0
  32. package/dist/assets/index-CgR5rJq_.js +41 -0
  33. package/dist/assets/{index-DpFttslC.js → index-CmNPYddV.js} +1 -1
  34. package/dist/assets/index-adyy_sEk.css +1 -0
  35. package/dist/assets/{isDiffPlainText-kzAgpIgi.js → isDiffPlainText-1bXcWCrw.js} +1 -1
  36. package/dist/assets/{isFilePlainText-Uj6y-jzz.js → isFilePlainText-CBAppvy1.js} +1 -1
  37. package/dist/assets/ja-BIElEsY8.js +16 -0
  38. package/dist/assets/ko-DRnnHetA.js +16 -0
  39. package/dist/assets/{main-CbfMxn-I.js → main-CzjTMTfW.js} +2 -2
  40. package/dist/assets/main-DVX34beR.js +886 -0
  41. package/dist/assets/markdownCore-Cxbkn5NR.js +7 -0
  42. package/dist/assets/{miniChat-CiAKBC10.js → miniChat-CP68IL8Q.js} +2 -2
  43. package/dist/assets/{mobile-CsT4sJwC.js → mobile-BrlBrNfZ.js} +2 -2
  44. package/dist/assets/nl-DzUV-kwp.js +16 -0
  45. package/dist/assets/{patchFileDiff-DeaE08W0.js → patchFileDiff-pqRSHLHI.js} +2 -2
  46. package/dist/assets/pl-Bb-cb7k7.js +16 -0
  47. package/dist/assets/pt-BR-CyIWrTcE.js +16 -0
  48. package/dist/assets/renderElectronMiniChatApp-DKIilR7N.js +2 -0
  49. package/dist/assets/renderMobileApp-B0z6-x58.js +25 -0
  50. package/dist/assets/runtimeEndpointReset-uu1DBwLL.js +52 -0
  51. package/dist/assets/{scheduledTasksApi-BZCNJ588.js → scheduledTasksApi-BuzWT445.js} +1 -1
  52. package/dist/assets/{shikiHighlight-BSUEa3yF.js → shikiHighlight-BWGrY5YU.js} +1 -1
  53. package/dist/assets/{textMateThemeFromAppTheme-CsATFZIV.js → textMateThemeFromAppTheme-BSUFChBY.js} +1 -1
  54. package/dist/assets/tr-DXEDSoYO.js +7 -0
  55. package/dist/assets/uk-C8hN--q_.js +16 -0
  56. package/dist/assets/useAppFontEffects-Dsl_sLrj.js +7366 -0
  57. package/dist/assets/useInlineCommentController-d5vntsQ_.js +2 -0
  58. package/dist/assets/{useRootScrollLock-Cp1eFoM2.js → useRootScrollLock-2rd5Y6gR.js} +2 -2
  59. package/dist/assets/{vendor-base-ui-CsXYnR5c.js → vendor-base-ui-DnNniUWp.js} +1 -1
  60. package/dist/assets/{vendor-codemirror-language-data-BwwommM0.js → vendor-codemirror-language-data-B1EetJur.js} +2 -2
  61. package/dist/assets/vendor-opencode-client-DSZl7jSi.js +12 -0
  62. package/dist/assets/{vendor-tanstack-react-virtual-ClYN8CzB.js → vendor-tanstack-react-virtual--0sBrLRh.js} +1 -1
  63. package/dist/assets/{vendor-tanstack-virtual-core-BewVQryB.js → vendor-tanstack-virtual-core-BoA4iGMw.js} +1 -1
  64. package/dist/assets/{vendor-zod-BSoePkpP.js → vendor-zod-CxRSdNoV.js} +4 -4
  65. package/dist/assets/{web-components-D3Yjr4Zx.js → web-components-ngpHPEDU.js} +1 -1
  66. package/dist/assets/zh-CN-CtzXdjMZ.js +16 -0
  67. package/dist/assets/zh-TW-Ds0CADSz.js +16 -0
  68. package/dist/index.html +5 -5
  69. package/dist/mini-chat.html +5 -5
  70. package/dist/mobile.html +5 -5
  71. package/package.json +5 -5
  72. package/server/index.js +82 -4
  73. package/server/lib/agent-tool/DOCUMENTATION.md +8 -1
  74. package/server/lib/agent-tool/runtime.js +13 -4
  75. package/server/lib/agent-tool/runtime.test.js +15 -0
  76. package/server/lib/context-obligatory/DOCUMENTATION.md +10 -7
  77. package/server/lib/context-obligatory/runtime.js +2 -1
  78. package/server/lib/context-obligatory/runtime.test.js +76 -30
  79. package/server/lib/dictation/DOCUMENTATION.md +4 -1
  80. package/server/lib/dictation/openai-compatible-session.js +7 -0
  81. package/server/lib/enterprise-mode.d.ts +30 -0
  82. package/server/lib/enterprise-mode.js +253 -0
  83. package/server/lib/enterprise-mode.test.js +247 -0
  84. package/server/lib/event-stream/translate-v2.js +6 -0
  85. package/server/lib/event-stream/translate-v2.test.js +6 -0
  86. package/server/lib/git/DOCUMENTATION.md +2 -1
  87. package/server/lib/git/routes.js +44 -1
  88. package/server/lib/git/routes.test.js +98 -1
  89. package/server/lib/git/service.js +146 -11
  90. package/server/lib/git/service.test.js +195 -0
  91. package/server/lib/github/routes.js +9 -19
  92. package/server/lib/github/routes.test.js +112 -0
  93. package/server/lib/guests/DOCUMENTATION.md +4 -2
  94. package/server/lib/guests/background.test.js +1 -1
  95. package/server/lib/guests/catalog.js +56 -2
  96. package/server/lib/guests/catalog.test.js +24 -1
  97. package/server/lib/guests/clone-network.test.js +52 -0
  98. package/server/lib/guests/clone.js +30 -4
  99. package/server/lib/guests/enterprise.js +68 -0
  100. package/server/lib/guests/enterprise.test.js +106 -0
  101. package/server/lib/guests/grant-scope.js +8 -2
  102. package/server/lib/guests/grant-scope.test.js +9 -0
  103. package/server/lib/guests/html-styles.js +16 -2
  104. package/server/lib/guests/html-styles.test.js +53 -4
  105. package/server/lib/guests/install.js +10 -0
  106. package/server/lib/guests/persist.js +1 -0
  107. package/server/lib/guests/routes.js +40 -5
  108. package/server/lib/guests/updates.js +9 -2
  109. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  110. package/server/lib/notifications/runtime.js +22 -8
  111. package/server/lib/notifications/trigger-runtime.test.js +45 -0
  112. package/server/lib/openchamber-sessions/session-metadata-store.js +27 -0
  113. package/server/lib/openchamber-sessions/session-metadata-store.test.js +18 -0
  114. package/server/lib/opencode/DOCUMENTATION.md +13 -9
  115. package/server/lib/opencode/auth-state-runtime.js +2 -2
  116. package/server/lib/opencode/config-paths.test.js +1 -0
  117. package/server/lib/opencode/env-runtime.js +26 -3
  118. package/server/lib/opencode/env-runtime.test.js +57 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/hmr-state-runtime.js +4 -3
  121. package/server/lib/opencode/lifecycle.js +10 -5
  122. package/server/lib/opencode/lifecycle.test.js +6 -2
  123. package/server/lib/opencode/managed-config-file.js +2 -1
  124. package/server/lib/opencode/managed-config-file.test.js +18 -0
  125. package/server/lib/opencode/npm-registry-config.d.ts +1 -0
  126. package/server/lib/opencode/npm-registry-config.js +123 -0
  127. package/server/lib/opencode/npm-registry-config.test.js +167 -0
  128. package/server/lib/opencode/npm-registry.js +5 -6
  129. package/server/lib/opencode/npm-registry.test.js +30 -0
  130. package/server/lib/opencode/openchamber-routes.js +8 -0
  131. package/server/lib/opencode/project-icon-routes.js +2 -2
  132. package/server/lib/opencode/project-icon-routes.test.js +44 -0
  133. package/server/lib/opencode/provider-source-route.test.js +32 -0
  134. package/server/lib/opencode/routes.js +17 -2
  135. package/server/lib/opencode/settings-helpers.js +26 -3
  136. package/server/lib/opencode/settings-helpers.test.js +12 -5
  137. package/server/lib/opencode/settings-registry.json +35 -1
  138. package/server/lib/opencode/settings-runtime.js +1 -0
  139. package/server/lib/opencode/shutdown-runtime.js +2 -0
  140. package/server/lib/opencode/static-routes-runtime.js +9 -1
  141. package/server/lib/opencode/static-routes-runtime.test.js +58 -1
  142. package/server/lib/package-manager.js +4 -1
  143. package/server/lib/package-manager.test.js +24 -0
  144. package/server/lib/permission-auto-accept/DOCUMENTATION.md +23 -15
  145. package/server/lib/permission-auto-accept/modes.js +26 -0
  146. package/server/lib/permission-auto-accept/runtime.js +146 -40
  147. package/server/lib/permission-auto-accept/runtime.test.js +93 -9
  148. package/server/lib/quota/DOCUMENTATION.md +6 -0
  149. package/server/lib/quota/providers/zhipuai-coding-plan.js +74 -30
  150. package/server/lib/quota/providers/zhipuai-coding-plan.test.js +124 -0
  151. package/server/lib/relay/DOCUMENTATION.md +1 -1
  152. package/server/lib/relay/service.js +32 -12
  153. package/server/lib/relay/service.test.js +30 -0
  154. package/server/lib/routing/DOCUMENTATION.md +150 -41
  155. package/server/lib/routing/classifier.js +156 -0
  156. package/server/lib/routing/defaults.js +27 -0
  157. package/server/lib/routing/jev.js +5 -17
  158. package/server/lib/routing/routes.http.test.js +9 -0
  159. package/server/lib/routing/routes.js +27 -1
  160. package/server/lib/routing/runtime.js +199 -33
  161. package/server/lib/routing/runtime.test.js +299 -15
  162. package/server/lib/routing/store.js +57 -0
  163. package/server/lib/routing/store.test.js +37 -0
  164. package/server/lib/session-assist/DOCUMENTATION.md +17 -7
  165. package/server/lib/session-assist/context.js +42 -2
  166. package/server/lib/session-assist/context.test.js +38 -1
  167. package/server/lib/session-assist/runtime.js +57 -13
  168. package/server/lib/session-assist/runtime.test.js +45 -0
  169. package/server/lib/session-goal/DOCUMENTATION.md +47 -22
  170. package/server/lib/session-goal/audit.js +112 -0
  171. package/server/lib/session-goal/audit.test.js +58 -0
  172. package/server/lib/session-goal/runtime.js +113 -134
  173. package/server/lib/session-goal/runtime.test.js +146 -13
  174. package/server/lib/session-lineage.js +52 -0
  175. package/server/lib/session-lineage.test.js +45 -0
  176. package/server/lib/session-work/DOCUMENTATION.md +108 -0
  177. package/server/lib/session-work/questions.js +126 -0
  178. package/server/lib/session-work/runtime.js +278 -0
  179. package/server/lib/session-work/runtime.test.js +255 -0
  180. package/server/lib/session-work/state.js +48 -0
  181. package/server/lib/session-work/state.test.js +34 -0
  182. package/server/lib/small-model/DOCUMENTATION.md +14 -7
  183. package/server/lib/small-model/client.js +7 -4
  184. package/server/lib/small-model/index.js +11 -21
  185. package/server/lib/small-model/index.test.js +13 -26
  186. package/server/lib/spaces/DOCUMENTATION.md +79 -25
  187. package/server/lib/spaces/gatekeeper-channel.js +63 -11
  188. package/server/lib/spaces/gatekeeper-channel.test.js +34 -4
  189. package/server/lib/spaces/gatekeeper-program.cjs +64 -13
  190. package/server/lib/spaces/gatekeeper-program.test.js +115 -3
  191. package/server/lib/spaces/host.js +58 -13
  192. package/server/lib/spaces/host.test.js +34 -1
  193. package/server/lib/spaces/idle-stop.js +98 -0
  194. package/server/lib/spaces/idle-stop.test.js +130 -0
  195. package/server/lib/spaces/journey.js +427 -17
  196. package/server/lib/spaces/journey.test.js +592 -5
  197. package/server/lib/spaces/layout.js +27 -6
  198. package/server/lib/spaces/manager.test.js +1 -1
  199. package/server/lib/spaces/places/contract-suite.js +4 -2
  200. package/server/lib/spaces/places/docker-live-support.js +27 -4
  201. package/server/lib/spaces/places/docker.js +32 -5
  202. package/server/lib/spaces/places/docker.test.js +38 -8
  203. package/server/lib/spaces/places/escape-suite.js +32 -0
  204. package/server/lib/spaces/places/fake-docker.js +3 -1
  205. package/server/lib/spaces/places/grants.docker.live.test.js +197 -0
  206. package/server/lib/spaces/places/memory-place.js +3 -3
  207. package/server/lib/spaces/places/sessions.docker.live.test.js +4 -2
  208. package/server/lib/spaces/routes.js +49 -1
  209. package/server/lib/spaces/routes.test.js +31 -3
  210. package/server/lib/spaces/space-opencode.js +52 -0
  211. package/server/lib/spaces/space-opencode.test.js +41 -0
  212. package/server/lib/spaces/space-records.js +90 -2
  213. package/server/lib/spaces/space-records.test.js +58 -1
  214. package/server/lib/spaces/space-server.js +13 -1
  215. package/server/lib/spaces/space-server.test.js +13 -0
  216. package/server/lib/spaces/space-setup.js +173 -0
  217. package/server/lib/spaces/space-setup.test.js +174 -0
  218. package/server/lib/tts/DOCUMENTATION.md +3 -0
  219. package/server/lib/tts/base-url.js +8 -0
  220. package/server/lib/tts/routes.js +13 -1
  221. package/server/lib/tts/routes.test.js +26 -0
  222. package/server/lib/tunnels/DOCUMENTATION.md +2 -0
  223. package/server/lib/tunnels/routes.js +14 -0
  224. package/server/lib/tunnels/routes.test.js +26 -0
  225. package/server/lib/walkthrough/index.js +11 -7
  226. package/server/lib/walkthrough/jobs.test.js +8 -0
  227. package/server/lib/walkthrough/languages.js +1 -0
  228. package/server/lib/walkthrough/routes.js +7 -1
  229. package/dist/assets/FilesView-0Ie20mEk.js +0 -17
  230. package/dist/assets/LinearIssuesView-CSl2MUfA.js +0 -1
  231. package/dist/assets/MarkdownRendererImpl-DVHqZoug.js +0 -12
  232. package/dist/assets/OnboardingScreen-CIdXJpfc.js +0 -1
  233. package/dist/assets/PlanView-DEIi3Q7M.js +0 -5
  234. package/dist/assets/PluginPane-BEPUWVho.js +0 -3
  235. package/dist/assets/SettingsView-CiNh-RbW.js +0 -30
  236. package/dist/assets/WalkthroughView-6oE-MuDL.js +0 -4
  237. package/dist/assets/de-CgAJ51z7.js +0 -10
  238. package/dist/assets/es-zGi_ravM.js +0 -16
  239. package/dist/assets/fr-CPfogrWx.js +0 -14
  240. package/dist/assets/index-CHfphYL3.js +0 -41
  241. package/dist/assets/index-DvMJ3w6V.css +0 -1
  242. package/dist/assets/ja-DMk6wd-U.js +0 -16
  243. package/dist/assets/ko-BFpzJ8jc.js +0 -16
  244. package/dist/assets/main-anyZFMIs.js +0 -896
  245. package/dist/assets/markdownCore-CmM47cAE.js +0 -7
  246. package/dist/assets/pl-VdRPcZrB.js +0 -16
  247. package/dist/assets/pt-BR-BRys_lOW.js +0 -16
  248. package/dist/assets/renderElectronMiniChatApp-C5677jy0.js +0 -2
  249. package/dist/assets/renderMobileApp-D4dBBAqQ.js +0 -25
  250. package/dist/assets/runtimeEndpointReset-5r0hkd-2.js +0 -27
  251. package/dist/assets/tr-CA9ckNnm.js +0 -7
  252. package/dist/assets/uk-byjR-y8D.js +0 -16
  253. package/dist/assets/useAppFontEffects-BWQZ5DeI.js +0 -7341
  254. package/dist/assets/useInlineCommentController-DlFyVfBu.js +0 -2
  255. package/dist/assets/vendor-opencode-client-DYdsLbCM.js +0 -12
  256. package/dist/assets/zh-CN-DRabgxdG.js +0 -16
  257. package/dist/assets/zh-TW-rbY5c9UK.js +0 -16
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Which sessions are subsessions, remembered so per-turn work can skip them
3
+ * without asking OpenCode. Whether a session has a parent never changes, so an
4
+ * answer never goes stale; it is learned from `session.created` events (the
5
+ * translated event names the parent) and from any session record a runtime
6
+ * read anyway. Bounded: the oldest entries go first, and a forgotten session
7
+ * is simply unknown again.
8
+ */
9
+ import { z } from 'zod';
10
+
11
+ const DEFAULT_LIMIT = 5000;
12
+
13
+ const createdSchema = z.object({
14
+ type: z.literal('session.created'),
15
+ properties: z.object({
16
+ sessionID: z.string().min(1),
17
+ info: z.object({ parentID: z.string().min(1).optional() }).optional(),
18
+ }),
19
+ });
20
+
21
+ const deletedSchema = z.object({
22
+ type: z.literal('session.deleted'),
23
+ properties: z.object({ sessionID: z.string().min(1) }),
24
+ });
25
+
26
+ export function createSessionLineage({ limit = DEFAULT_LIMIT } = {}) {
27
+ // sessionID → true for a subsession, false for a top-level session.
28
+ const isChildById = new Map();
29
+
30
+ const remember = (sessionId, parentId) => {
31
+ if (!sessionId) return;
32
+ isChildById.delete(sessionId);
33
+ isChildById.set(sessionId, Boolean(parentId));
34
+ while (isChildById.size > limit) isChildById.delete(isChildById.keys().next().value);
35
+ };
36
+
37
+ /** Learns from the server's translated event stream. */
38
+ const observe = (payload) => {
39
+ const created = createdSchema.safeParse(payload);
40
+ if (created.success) {
41
+ remember(created.data.properties.sessionID, created.data.properties.info?.parentID ?? null);
42
+ return;
43
+ }
44
+ const deleted = deletedSchema.safeParse(payload);
45
+ if (deleted.success) isChildById.delete(deleted.data.properties.sessionID);
46
+ };
47
+
48
+ /** True for a known subsession, false for a known top-level session, undefined when unknown. */
49
+ const isChild = (sessionId) => isChildById.get(sessionId);
50
+
51
+ return { observe, remember, isChild };
52
+ }
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createSessionLineage } from './session-lineage.js';
3
+
4
+ const created = (sessionID, parentID) => ({
5
+ type: 'session.created',
6
+ properties: { sessionID, info: parentID ? { id: sessionID, parentID } : { id: sessionID } },
7
+ });
8
+
9
+ describe('session lineage', () => {
10
+ it('learns subsessions and top-level sessions from creation events', () => {
11
+ const lineage = createSessionLineage();
12
+ lineage.observe(created('ses_child', 'ses_parent'));
13
+ lineage.observe(created('ses_root'));
14
+
15
+ expect(lineage.isChild('ses_child')).toBe(true);
16
+ expect(lineage.isChild('ses_root')).toBe(false);
17
+ expect(lineage.isChild('ses_unknown')).toBeUndefined();
18
+ });
19
+
20
+ it('learns from a record read anyway, and forgets a deleted session', () => {
21
+ const lineage = createSessionLineage();
22
+ lineage.remember('ses_old_child', 'ses_parent');
23
+ expect(lineage.isChild('ses_old_child')).toBe(true);
24
+
25
+ lineage.observe({ type: 'session.deleted', properties: { sessionID: 'ses_old_child' } });
26
+ expect(lineage.isChild('ses_old_child')).toBeUndefined();
27
+ });
28
+
29
+ it('stays bounded, forgetting the oldest entry first', () => {
30
+ const lineage = createSessionLineage({ limit: 2 });
31
+ lineage.remember('a', 'p');
32
+ lineage.remember('b', 'p');
33
+ lineage.remember('c', null);
34
+
35
+ expect(lineage.isChild('a')).toBeUndefined();
36
+ expect(lineage.isChild('b')).toBe(true);
37
+ expect(lineage.isChild('c')).toBe(false);
38
+ });
39
+
40
+ it('ignores unrelated events', () => {
41
+ const lineage = createSessionLineage();
42
+ lineage.observe({ type: 'session.status', properties: { sessionID: 'ses_1', status: { type: 'idle' } } });
43
+ expect(lineage.isChild('ses_1')).toBeUndefined();
44
+ });
45
+ });
@@ -0,0 +1,108 @@
1
+ # Session work ("In work")
2
+
3
+ ## Purpose
4
+
5
+ Keeps sessions where real work is going on in one block at the top of the
6
+ sidebar until the user marks them done. Jev moves a session in when work
7
+ starts in it; the user alone closes it. The same turn-end Jev call tells
8
+ session assist whether the Small Model is worth waking.
9
+
10
+ ## Files
11
+
12
+ - `questions.js` — the Jev questions (measured wording, see "Measurement"),
13
+ the thresholds, and the decisions taken from the answers.
14
+ - `state.js` — `metadata.openchamber.work` and the merge patches that change
15
+ it. Every patch is decided against the record at write time.
16
+ - `runtime.js` — `createSessionWorkRuntime`: `processPayload` (a sent message,
17
+ a turn start), `evaluateTurnEnd` (called by session assist), `stop`.
18
+
19
+ ## State
20
+
21
+ `metadata.openchamber.work`:
22
+
23
+ - `state`: `open` | `done`
24
+ - `openedAt`, `openedBy` (`jev` | `user`)
25
+ - `doneAt` once the user closed it
26
+ - `suggestDoneAt` while Jev thinks the last turn closed the work out
27
+
28
+ The UI parser is `packages/ui/src/lib/sessionWorkMetadata.ts`; the user's own
29
+ Track / Done go through the generic metadata route
30
+ (`setSessionWorkState` in `packages/ui/src/sync/session-actions.ts`), which
31
+ also exists in VS Code.
32
+
33
+ ## Invariants
34
+
35
+ - Jev only opens. Nothing here ever writes `done`.
36
+ - Jev reopens a closed session only for a request sent after the user closed
37
+ it (`openByJevPatch` compares the request's `time.created` with `doneAt`).
38
+ - Writes go through `updateSessionMetadata`, which decides the patch inside the
39
+ store's per-session write queue, so a user's Done written a moment earlier
40
+ is seen and kept.
41
+ - A turn-end check is bound to its turn: every turn start and new user
42
+ message advances a per-session counter, and the done hint is written only if
43
+ the counter is unchanged when the write runs (decided inside the store's
44
+ queue). A late Jev answer about a turn the user already moved past writes
45
+ nothing.
46
+ - The done hint is current while `suggestDoneAt >= session.time.idle` (the
47
+ assist's freshness rule). This runtime also deletes a hint it wrote when the
48
+ next turn starts; the rule covers hints written by another process.
49
+ - Only top-level, unarchived project sessions that are not review sessions
50
+ (`openchamber.kind === 'review'`) are asked about. Managed Chats (under the
51
+ `chatRoots` the server passes in) are plain conversations and never in work.
52
+ - A known subsession costs nothing: `../session-lineage.js` remembers which
53
+ sessions have a parent (from `session.created` events and from any record
54
+ read anyway), and a known one is skipped before any read or Jev call.
55
+ - Every failure (no classification provider, Jev error or timeout, an
56
+ unreadable session) leaves state unchanged and returns an unknown gate, so
57
+ session assist runs exactly as it did without Jev.
58
+
59
+ ## When Jev is asked
60
+
61
+ - A user message was sent (`message.updated`, role user, from the hub's
62
+ translation of `session.inbox.enqueued`): only with the feature and auto-open
63
+ on, a usable classification provider, and the session not already in work.
64
+ History is the three settled turns before it (`loadSettledTurns`). Each
65
+ message id is asked about once.
66
+ - A turn ended: session assist calls `evaluateTurnEnd` before it arms its quiet
67
+ window. One call carries only the questions that apply: the open questions
68
+ while not in work, `wrap_up` while in work, `recap` / `next_step` for the
69
+ assist fields the user has on. No applicable question, no call.
70
+
71
+ ## Measurement
72
+
73
+ 156 real sessions (93 work, 50 not, 9 housekeeping, 4 neutral) set the wording;
74
+ 190 older held-out sessions, labelled before looking at answers, checked it:
75
+ send and turn end together missed 4/92 work sessions and opened 10/78 non-work
76
+ ones (four of them discussions of concrete changes, which count as work). The
77
+ misses are work that starts inside a PR-review session. `wrap_up >= 0.8`
78
+ reads the whole turn (a commit, push, merge, sync or release the answer
79
+ reports done closes the work); on the held-out sessions it hinted 80 times
80
+ across 106 work sessions, 22 of them followed by more edits, and caught 53 of
81
+ 81 shipping steps. At 0.85 the same wording hinted 70 times (18) and missed a
82
+ closing turn whose answer asked the user for a last check (0.82); the earlier
83
+ request-only wording at 0.85 hinted 60 times (16) and caught 33.
84
+ `recap` stayed high (0.86–0.96) after a closing "thanks"/"commit" that followed
85
+ real work, because it reads the same three turns the recap does. Do not change
86
+ the wording or thresholds without re-running this measurement.
87
+
88
+ ## Settings
89
+
90
+ `sessionWorkEnabled` (the block and the actions, default on) and
91
+ `sessionWorkAutoOpen` (Jev opens sessions, default on; not offered in VS Code,
92
+ and inert without a classification provider). Both are read at every use.
93
+
94
+ ## Runtime parity
95
+
96
+ - Web, desktop, hosted mobile, Capacitor: all of it; the server owns Jev.
97
+ - VS Code: no OpenChamber server, so no Jev and no done hint. The block and
98
+ Track / Done work through the extension's metadata bridge.
99
+
100
+ ## Tests
101
+
102
+ `state.test.js` (patches, reopen rule, hint lifecycle), `runtime.test.js`
103
+ (send-time open, no repeat asks, ineligible sessions, the combined turn-end
104
+ call, a late answer after the next turn started, never closing, failure as
105
+ unknown), plus the gate cases in
106
+ `../session-assist/runtime.test.js`, `loadSettledTurns` in
107
+ `../session-assist/context.test.js`, and `updateSessionMetadata` in
108
+ `../openchamber-sessions/session-metadata-store.test.js`.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The Jev questions behind "In work" and the session-assist gate, and the
3
+ * decisions taken from their answers.
4
+ *
5
+ * The wording and thresholds were measured on 156 real sessions and then
6
+ * checked on 190 held-out ones (send and turn end together: 4/92 work sessions
7
+ * missed, 10/78 false opens). Keep the criteria general common sense about
8
+ * coding-agent work; never phrase them after one user's habits. Change them
9
+ * only with a new measurement.
10
+ */
11
+ import { z } from 'zod';
12
+
13
+ const TURN_END_CONTEXT = 'This is a turn in a chat between a user and an AI coding agent. `request` is the latest user message, `answer` is the agent\'s reply to it, and `history` holds earlier turns, oldest first, only to explain what a short `request` refers to.';
14
+ const SEND_CONTEXT = 'This is a message a user just sent to an AI coding agent. `request` is that message and `history` holds earlier turns, oldest first, only to explain what a short `request` refers to.';
15
+
16
+ const CHANGE = {
17
+ question: 'Does `request` ask the agent to change the project: build or add a feature, fix a bug, change code, UI, docs, or configuration, or approve a change the agent proposed so it gets carried out?',
18
+ criteria: {
19
+ true: 'The user wants the project changed: "fix this", "add X", "let\'s redesign Y", "implement the proposed improvements", "go ahead" after a proposed change, or feedback that asks to adjust something the agent just changed.',
20
+ false: 'The user only wants information or an opinion: a question, an explanation, research, a report, a code or PR review, triage, a draft message to send someone, a status summary, running a command to show output, or a git housekeeping step such as commit, push, merge, or sync.',
21
+ },
22
+ };
23
+
24
+ const TOWARD_CHANGE = {
25
+ question: 'Is the user working toward a concrete change to their project in `request`: asking for a change, reporting a bug or problem in the project, or discussing how something in the project should change?',
26
+ criteria: {
27
+ true: 'Asking to build, fix, change, redesign, or remove something in the project; a bug report, user complaint, error, or broken behaviour of the project, even without the word "fix"; proposing or discussing a concrete change or redesign; approving a proposal ("go ahead", "yes, do it"); feedback on something just changed.',
28
+ false: 'Only wanting to know or understand: how something works, a status catch-up, a code tour, searching history, a PR review or triage, drafting a reply to someone, general questions or opinions, or tasks unrelated to the project; also a bare housekeeping step such as commit, push, merge, or sync.',
29
+ },
30
+ };
31
+
32
+ /**
33
+ * Reads the whole turn, not only `request`: a shipping step (commit, push,
34
+ * merge, sync, release) closes the work once `answer` reports it done.
35
+ * Measured against the earlier request-only wording at the same threshold:
36
+ * held-out 70 hints in 106 work sessions (18 followed by more edits) against
37
+ * 60 (16), and 47 of 81 shipping steps hinted against 33. The threshold then
38
+ * went from 0.85 to 0.8: 80 hints (22), 53 of 81 shipping steps, so a closing
39
+ * turn whose answer hands the user a last check still gets the hint.
40
+ */
41
+ const WRAP_UP = 'Does this turn close out the work in this conversation: in `request` the user confirms it works or is good, thanks the agent, or asks to commit, push, merge, sync, or release it, without asking for any further change, and `answer` reports that step done?';
42
+
43
+ const RECAP = {
44
+ question: 'Is there substantive work or a finding in this conversation worth a one-line reminder later: something the agent changed, fixed, found out, or a decision that was reached?',
45
+ criteria: {
46
+ true: 'The agent changed code, fixed or diagnosed something, answered a real question with a concrete finding, or the user and agent settled a decision.',
47
+ false: 'Only small talk, a greeting, an acknowledgment, a trivial lookup, or a command whose output needs no reminder.',
48
+ },
49
+ };
50
+
51
+ const NEXT_STEP = {
52
+ question: 'After `answer`, is part of what the user asked for in `request` still unfinished, so the agent could continue it with one more message without the user first testing, deciding, or approving anything?',
53
+ criteria: {
54
+ true: 'The agent stopped part-way: it names remaining steps of the requested work it can do itself, or the work was cut off.',
55
+ false: 'The request is satisfied, or the next move belongs to the user (test, choose, approve, answer a question), or an analysis, explanation, or recommendation was requested and delivered.',
56
+ },
57
+ };
58
+
59
+ /** Open when either passes (measured together). */
60
+ const OPEN_THRESHOLDS = { change: 0.85, towardChange: 0.9 };
61
+ const WRAP_UP_THRESHOLD = 0.8;
62
+ /** The recap is skipped only when Jev is nearly sure there is nothing to remind. */
63
+ const RECAP_SKIP_BELOW = 0.3;
64
+ const NEXT_STEP_THRESHOLD = 0.5;
65
+
66
+ const noul = (context, { question, criteria }) => {
67
+ const asked = { type: 'noul', instructions: [context, question] };
68
+ if (criteria) asked.criteria = criteria;
69
+ return asked;
70
+ };
71
+
72
+ /** The request Jev reads when a message was just sent. */
73
+ export const buildSendRequest = ({ history, request }) => ({
74
+ state: { history, request },
75
+ questions: {
76
+ change: noul(SEND_CONTEXT, CHANGE),
77
+ toward_change: noul(SEND_CONTEXT, TOWARD_CHANGE),
78
+ },
79
+ });
80
+
81
+ /**
82
+ * The request Jev reads when a turn ended, or null when nothing is asked.
83
+ * `ask` names the groups: `open` (the session is not in work), `wrapUp` (it
84
+ * is), `recap` and `nextStep` (the assist fields the user has on).
85
+ */
86
+ export const buildTurnEndRequest = ({ history, request, answer, ask }) => {
87
+ const questions = {};
88
+ if (ask.open) {
89
+ questions.change = noul(TURN_END_CONTEXT, CHANGE);
90
+ questions.toward_change = noul(TURN_END_CONTEXT, TOWARD_CHANGE);
91
+ }
92
+ if (ask.wrapUp) questions.wrap_up = noul(TURN_END_CONTEXT, { question: WRAP_UP });
93
+ if (ask.recap) questions.recap = noul(TURN_END_CONTEXT, RECAP);
94
+ if (ask.nextStep) questions.next_step = noul(TURN_END_CONTEXT, NEXT_STEP);
95
+ if (Object.keys(questions).length === 0) return null;
96
+ return { state: { history, request, answer }, questions };
97
+ };
98
+
99
+ const noulAnswer = z.object({ noul: z.number() });
100
+ const answerOf = (answers, id) => noulAnswer.safeParse(answers?.[id]).data?.noul ?? null;
101
+
102
+ /** True when the answers say real work started; a missing answer never opens. */
103
+ export const decideOpen = (answers) => {
104
+ const change = answerOf(answers, 'change');
105
+ const towardChange = answerOf(answers, 'toward_change');
106
+ return (change !== null && change >= OPEN_THRESHOLDS.change)
107
+ || (towardChange !== null && towardChange >= OPEN_THRESHOLDS.towardChange);
108
+ };
109
+
110
+ export const decideWrapUp = (answers) => {
111
+ const score = answerOf(answers, 'wrap_up');
112
+ return score !== null && score >= WRAP_UP_THRESHOLD;
113
+ };
114
+
115
+ /**
116
+ * Which assist fields are worth the Small Model. A field Jev did not answer
117
+ * stays allowed: an unanswered question must not silence the assist.
118
+ */
119
+ export const decideAssist = (answers) => {
120
+ const recap = answerOf(answers, 'recap');
121
+ const nextStep = answerOf(answers, 'next_step');
122
+ return {
123
+ recap: recap === null || recap >= RECAP_SKIP_BELOW,
124
+ suggestion: nextStep === null || nextStep >= NEXT_STEP_THRESHOLD,
125
+ };
126
+ };
@@ -0,0 +1,278 @@
1
+ /**
2
+ * "In work": Jev moves a session into work when real work starts in it, and
3
+ * says when a turn looks like the end of that work. The user closes; this
4
+ * runtime never does. See DOCUMENTATION.md.
5
+ *
6
+ * Two moments ask Jev:
7
+ * - a user message was sent (`message.updated`, role user): only while the
8
+ * session is not in work, so an open session costs no call here;
9
+ * - a turn ended: session assist calls `evaluateTurnEnd` before it arms its
10
+ * quiet window, and one call answers both this runtime's questions and
11
+ * whether the Small Model is worth waking.
12
+ *
13
+ * Every failure leaves things as they were: nothing opens, no hint appears,
14
+ * and session assist behaves as it did without Jev.
15
+ */
16
+ import fs from 'fs';
17
+ import os from 'os';
18
+ import path from 'path';
19
+ import { OpenCode } from '@opencode/client';
20
+ import { z } from 'zod';
21
+ import { readMergedSettingsSync } from '../opencode/settings-files.js';
22
+ import { loadAssistContext, loadSettledTurns } from '../session-assist/context.js';
23
+ import { turnsToHistory, excerptHead, excerptHeadTail } from '../routing/history.js';
24
+ import {
25
+ buildSendRequest,
26
+ buildTurnEndRequest,
27
+ decideAssist,
28
+ decideOpen,
29
+ decideWrapUp,
30
+ } from './questions.js';
31
+ import { clearSuggestionPatch, openByJevPatch, readWork, suggestDonePatch } from './state.js';
32
+
33
+ const OPENCHAMBER_SETTINGS_FILE = path.join(
34
+ process.env.OPENCHAMBER_DATA_DIR
35
+ ? path.resolve(process.env.OPENCHAMBER_DATA_DIR)
36
+ : path.join(os.homedir(), '.config', 'openchamber'),
37
+ 'settings.json',
38
+ );
39
+
40
+ /** Both default on; read at every use so a change applies without a restart. */
41
+ const readSessionWorkSettings = () => {
42
+ const settings = readMergedSettingsSync({ fs, path, settingsFilePath: OPENCHAMBER_SETTINGS_FILE });
43
+ return {
44
+ enabled: settings.sessionWorkEnabled !== false,
45
+ autoOpen: settings.sessionWorkAutoOpen !== false,
46
+ };
47
+ };
48
+
49
+ const READ_TIMEOUT_MS = 5_000;
50
+ const REQUEST_CHARS = 1_500;
51
+ const SEEN_MESSAGES_LIMIT = 500;
52
+
53
+ const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
54
+
55
+ const userMessageSchema = z.object({
56
+ type: z.literal('message.updated'),
57
+ properties: z.object({
58
+ sessionID: z.string().min(1),
59
+ info: z.object({
60
+ id: z.string().min(1),
61
+ role: z.literal('user'),
62
+ text: z.string(),
63
+ time: z.object({ created: z.number() }).partial().optional(),
64
+ }),
65
+ }),
66
+ });
67
+
68
+ const busySchema = z.object({
69
+ type: z.literal('session.status'),
70
+ properties: z.object({ sessionID: z.string().min(1), status: z.object({ type: z.literal('busy') }) }),
71
+ });
72
+
73
+ const reviewSessionSchema = z.object({ openchamber: z.object({ kind: z.literal('review') }) });
74
+
75
+ export function createSessionWorkRuntime({
76
+ buildOpenCodeUrl,
77
+ getOpenCodeAuthHeaders,
78
+ /** `{ enabled, autoOpen }` as currently saved. */
79
+ getSettings = readSessionWorkSettings,
80
+ /** The classification provider's endpoint, or null when there is no Jev. */
81
+ classifierEndpoint,
82
+ jev,
83
+ readMetadata,
84
+ /** `(sessionID, decide, { directory }) => { metadata, changed }`, decided against the record at write time. */
85
+ updateMetadata,
86
+ isSessionArchived = async () => false,
87
+ /** Roots of managed Chats: plain conversations, never work. */
88
+ chatRoots = [],
89
+ /** `../session-lineage.js`: known subsessions are skipped without reading them. */
90
+ lineage = null,
91
+ now = Date.now,
92
+ }) {
93
+ const resolvedChatRoots = chatRoots.filter(Boolean).map((root) => path.resolve(root));
94
+ const isChatDirectory = (directory) => {
95
+ if (!directory) return false;
96
+ const resolved = path.resolve(directory);
97
+ return resolvedChatRoots.some((root) => resolved === root || resolved.startsWith(`${root}${path.sep}`));
98
+ };
99
+ let stopped = false;
100
+ const seenMessages = new Set();
101
+ // Sessions where this process wrote a done hint, so a new turn can retire it
102
+ // without reading every session's metadata at every turn start.
103
+ const suggested = new Map();
104
+ // A turn counter per session, moved by every turn start and every new user
105
+ // message. A turn-end check captures it before asking Jev and writes the
106
+ // done hint only if no newer turn began in the meantime: a late answer about
107
+ // the previous turn must not land on the next one.
108
+ // Values come from one process-wide counter, so they never repeat: a session
109
+ // evicted from the bounded map reads 0, which no pending check captured
110
+ // after a turn start, and its late answer is dropped rather than accepted.
111
+ const turnGenerations = new Map();
112
+ let lastTurnGeneration = 0;
113
+ const turnGeneration = (sessionId) => turnGenerations.get(sessionId) ?? 0;
114
+ const advanceTurn = (sessionId) => {
115
+ lastTurnGeneration += 1;
116
+ turnGenerations.delete(sessionId);
117
+ turnGenerations.set(sessionId, lastTurnGeneration);
118
+ while (turnGenerations.size > SEEN_MESSAGES_LIMIT) turnGenerations.delete(turnGenerations.keys().next().value);
119
+ };
120
+
121
+ const openCodeClient = (directory) => {
122
+ const headers = { ...getOpenCodeAuthHeaders() };
123
+ // v2 scopes by header and rejects non-ASCII header values.
124
+ if (directory) headers['x-opencode-directory'] = encodeURIComponent(directory);
125
+ return OpenCode.make({ baseUrl: buildOpenCodeUrl('/', '').replace(/\/$/, ''), headers });
126
+ };
127
+
128
+ const readPages = (client, sessionId, signal) => ({ limit, cursor }) => client.message.list(
129
+ { sessionID: sessionId, limit, ...(cursor ? { cursor } : { order: 'desc' }) },
130
+ { signal },
131
+ );
132
+
133
+ /**
134
+ * The session record when it is one this feature serves: a top-level,
135
+ * unarchived project session that is not a review of another one. Chats
136
+ * are plain conversations and never in work. Null otherwise.
137
+ */
138
+ const eligibleSession = async (client, sessionId, signal) => {
139
+ const session = await client.session.get({ sessionID: sessionId }, { signal });
140
+ if (session?.id === sessionId) lineage?.remember(sessionId, session.parentID ?? null);
141
+ if (session?.id !== sessionId || session.parentID) return null;
142
+ if (isChatDirectory(session.location?.directory ?? session.directory)) return null;
143
+ if (reviewSessionSchema.safeParse(session.metadata).success) return null;
144
+ if (await isSessionArchived(sessionId)) return null;
145
+ return session;
146
+ };
147
+
148
+ const markSuggested = (sessionId, directory) => {
149
+ suggested.delete(sessionId);
150
+ suggested.set(sessionId, directory);
151
+ while (suggested.size > SEEN_MESSAGES_LIMIT) suggested.delete(suggested.keys().next().value);
152
+ };
153
+
154
+ const onUserMessage = async ({ sessionId, directory, messageId, text, createdAt }) => {
155
+ const settings = getSettings();
156
+ if (!settings.enabled || !settings.autoOpen || !text.trim()) return;
157
+ if (seenMessages.has(messageId)) return;
158
+ seenMessages.add(messageId);
159
+ while (seenMessages.size > SEEN_MESSAGES_LIMIT) seenMessages.delete(seenMessages.values().next().value);
160
+
161
+ const endpoint = await classifierEndpoint();
162
+ if (!endpoint) return;
163
+ const signal = AbortSignal.timeout(READ_TIMEOUT_MS);
164
+ const client = openCodeClient(directory);
165
+ const session = await eligibleSession(client, sessionId, signal);
166
+ if (!session) return;
167
+ if (readWork(await readMetadata(sessionId, directory))?.state === 'open') return;
168
+
169
+ const turns = await loadSettledTurns({ readPage: readPages(client, sessionId, signal), signal });
170
+ const { answers } = await jev.ask(
171
+ buildSendRequest({ history: turnsToHistory(turns), request: excerptHead(text.trim(), REQUEST_CHARS) }),
172
+ endpoint,
173
+ );
174
+ if (stopped || !decideOpen(answers)) return;
175
+ await updateMetadata(sessionId, (metadata) => openByJevPatch(metadata, { requestAt: createdAt, now: now() }), { directory });
176
+ };
177
+
178
+ const retireSuggestion = (sessionId) => {
179
+ if (!suggested.has(sessionId)) return;
180
+ const directory = suggested.get(sessionId);
181
+ suggested.delete(sessionId);
182
+ Promise.resolve(updateMetadata(sessionId, clearSuggestionPatch, { directory }))
183
+ .catch((error) => console.warn('[session-work] could not retire a done hint:', errorMessage(error)));
184
+ };
185
+
186
+ const processPayload = (payload, directoryHint = '') => {
187
+ if (stopped) return;
188
+ const busy = busySchema.safeParse(payload);
189
+ if (busy.success) {
190
+ advanceTurn(busy.data.properties.sessionID);
191
+ retireSuggestion(busy.data.properties.sessionID);
192
+ return;
193
+ }
194
+ const message = userMessageSchema.safeParse(payload);
195
+ if (!message.success) return;
196
+ const { sessionID, info } = message.data.properties;
197
+ // A subsession is never in work: no read, no Jev.
198
+ if (lineage?.isChild(sessionID) === true) return;
199
+ if (!seenMessages.has(info.id)) advanceTurn(sessionID);
200
+ const directory = payload.properties?.directory || directoryHint;
201
+ void onUserMessage({
202
+ sessionId: sessionID,
203
+ directory,
204
+ messageId: info.id,
205
+ text: info.text,
206
+ createdAt: info.time?.created ?? now(),
207
+ }).catch((error) => console.warn('[session-work] could not check a sent message:', errorMessage(error)));
208
+ };
209
+
210
+ /**
211
+ * One Jev call when a turn ended. `assist` says which assist fields the user
212
+ * has on. Resolves which of them are worth the Small Model, or null when Jev
213
+ * was not asked about them (no Jev, a failure, an ineligible session): the
214
+ * caller then behaves as it always did.
215
+ */
216
+ const evaluateTurnEnd = async ({ sessionId, directory, assist }) => {
217
+ if (stopped || lineage?.isChild(sessionId) === true) return null;
218
+ const settings = getSettings();
219
+ if (!settings.enabled && !assist.recap && !assist.suggestion) return null;
220
+ // Never capture 0: an evicted session also reads 0.
221
+ if (!turnGenerations.has(sessionId)) advanceTurn(sessionId);
222
+ const generation = turnGeneration(sessionId);
223
+ try {
224
+ const endpoint = await classifierEndpoint();
225
+ if (!endpoint) return null;
226
+ const signal = AbortSignal.timeout(READ_TIMEOUT_MS);
227
+ const client = openCodeClient(directory);
228
+ const session = await eligibleSession(client, sessionId, signal);
229
+ if (!session || session.revert?.messageID) return null;
230
+ const work = settings.enabled ? readWork(await readMetadata(sessionId, directory)) : null;
231
+ const ask = {
232
+ open: settings.enabled && settings.autoOpen && work?.state !== 'open',
233
+ wrapUp: settings.enabled && work?.state === 'open',
234
+ recap: assist.recap,
235
+ nextStep: assist.suggestion,
236
+ };
237
+ const context = await loadAssistContext({ readPage: readPages(client, sessionId, signal), signal });
238
+ if (!context) return null;
239
+ const turn = context.turns.at(-1);
240
+ const request = buildTurnEndRequest({
241
+ history: turnsToHistory(context.turns.slice(0, -1)),
242
+ request: excerptHead(turn.user.text, REQUEST_CHARS),
243
+ answer: excerptHeadTail(turn.assistant.text, 300, 300),
244
+ ask,
245
+ });
246
+ if (!request) return null;
247
+ const { answers } = await jev.ask(request, endpoint);
248
+ if (stopped) return null;
249
+ if (ask.open && decideOpen(answers)) {
250
+ const requestAt = turn.user.created ?? now();
251
+ await updateMetadata(sessionId, (metadata) => openByJevPatch(metadata, { requestAt, now: now() }), { directory });
252
+ }
253
+ if (ask.wrapUp && decideWrapUp(answers)) {
254
+ // Decided at write time: a turn that started while Jev was answering
255
+ // makes this answer about an older turn.
256
+ const { changed } = await updateMetadata(
257
+ sessionId,
258
+ (metadata) => (turnGeneration(sessionId) === generation ? suggestDonePatch(metadata, { now: now() }) : null),
259
+ { directory },
260
+ );
261
+ if (changed) markSuggested(sessionId, directory);
262
+ }
263
+ return ask.recap || ask.nextStep ? decideAssist(answers) : null;
264
+ } catch (error) {
265
+ console.warn('[session-work] turn-end check failed:', errorMessage(error));
266
+ return null;
267
+ }
268
+ };
269
+
270
+ const stop = () => {
271
+ stopped = true;
272
+ seenMessages.clear();
273
+ suggested.clear();
274
+ turnGenerations.clear();
275
+ };
276
+
277
+ return { processPayload, evaluateTurnEnd, stop };
278
+ }