@aiworker/web 1.23.0 → 1.23.1

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 (152) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-B1Gizi3a.js → CodeMirrorCommentWidgets-teB3HmBT.js} +1 -1
  2. package/dist/assets/DiffView-DC9RX3MF.js +4 -0
  3. package/dist/assets/{DirtyBranchSwitchDialog-aig6zJjg.js → DirtyBranchSwitchDialog-DwPkzXsS.js} +1 -1
  4. package/dist/assets/FilesView-BFZkuu4O.js +13 -0
  5. package/dist/assets/{GitView-BXsS3jG6.js → GitView-B_x52MHY.js} +4 -4
  6. package/dist/assets/{JsonTreeView-D_hpXBnF.js → JsonTreeView-cmAzUTiw.js} +1 -1
  7. package/dist/assets/{LinearIssuesView-BoUiLQG1.js → LinearIssuesView-Dehh5afm.js} +1 -1
  8. package/dist/assets/{MarkdownImageGallery-B_B_a9KS.js → MarkdownImageGallery-DgNOqqhE.js} +1 -1
  9. package/dist/assets/{MarkdownRendererImpl-xgyyLiBM.js → MarkdownRendererImpl-DusmMZ_p.js} +2 -2
  10. package/dist/assets/{OnboardingScreen-DIp84OWt.js → OnboardingScreen-B8fm1H4m.js} +1 -1
  11. package/dist/assets/{PatchDiff-8p6nLJaU.js → PatchDiff-BVr7gJU0.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-DjC8nTk9.js → PierreDiffViewer-DzLt-nel.js} +1 -1
  13. package/dist/assets/PlanView-BmQUYT_z.js +5 -0
  14. package/dist/assets/SettingsView-ChWmAcZT.js +28 -0
  15. package/dist/assets/{SettingsWindow-Cpb4hM6q.js → SettingsWindow-Dy3M6ZB9.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-DfaKZXNU.js → ToolOutputDialog-cTl_eLIH.js} +6 -6
  17. package/dist/assets/{ToolPartDiffPreview-DtZLzrSK.js → ToolPartDiffPreview-C_3iYNJQ.js} +2 -2
  18. package/dist/assets/{VirtualizedFileDiff-C8i9HpTB.js → VirtualizedFileDiff-CAWthkoy.js} +4 -4
  19. package/dist/assets/WalkthroughView-C7AHOpCA.js +4 -0
  20. package/dist/assets/{computeVirtualFileMetrics-BBI7ZwrC.js → computeVirtualFileMetrics-BkiDSlTW.js} +2 -2
  21. package/dist/assets/de-DJsQr-p7.js +10 -0
  22. package/dist/assets/es-BuYMlA9g.js +16 -0
  23. package/dist/assets/fr-ePDay33C.js +14 -0
  24. package/dist/assets/index-BD8ILbxF.js +40 -0
  25. package/dist/assets/{index-jXSK5RrB.js → index-n6O3hklM.js} +1 -1
  26. package/dist/assets/index-zhgg-SDz.css +1 -0
  27. package/dist/assets/{isDiffPlainText-B_x_rVon.js → isDiffPlainText-GMdPz-71.js} +1 -1
  28. package/dist/assets/{isFilePlainText-DW_xMer1.js → isFilePlainText-BVuH1zH9.js} +1 -1
  29. package/dist/assets/ja-BzR9xOY_.js +16 -0
  30. package/dist/assets/{ko-idhXGF8j.js → ko-BEjHAm14.js} +3 -3
  31. package/dist/assets/main-BydQ1tr_.js +930 -0
  32. package/dist/assets/{main-CzdPuL0s.js → main-D3ZDQglc.js} +2 -2
  33. package/dist/assets/{markdownCore-Cn4Tyejo.js → markdownCore-Cb2MdZnV.js} +3 -3
  34. package/dist/assets/{miniChat-CCkqKOLp.js → miniChat-d01k801U.js} +2 -2
  35. package/dist/assets/{mobile-mvxTo055.js → mobile-D7VV-Ufz.js} +2 -2
  36. package/dist/assets/patchFileDiff-CdztVMz0.js +13 -0
  37. package/dist/assets/{pl-CGZWUqZJ.js → pl-rQmpxNIF.js} +3 -3
  38. package/dist/assets/pt-BR-CorbsSW-.js +16 -0
  39. package/dist/assets/renderElectronMiniChatApp-BGG9UIlh.js +2 -0
  40. package/dist/assets/renderMobileApp-BRP3J1iv.js +25 -0
  41. package/dist/assets/runtimeEndpointReset-BhT_-c52.js +41 -0
  42. package/dist/assets/scheduledTasksApi-BEuUF_cj.js +1 -0
  43. package/dist/assets/{shikiHighlight-CRl0SUC9.js → shikiHighlight-BzXUjlby.js} +1 -1
  44. package/dist/assets/surface-COKb77Ua.js +1 -0
  45. package/dist/assets/tr-CoAMXPtI.js +7 -0
  46. package/dist/assets/uk-YlAX0rRU.js +16 -0
  47. package/dist/assets/{useAppFontEffects-CPKeOpUo.js → useAppFontEffects-Cwyhjfl5.js} +153 -155
  48. package/dist/assets/useGitComparison-BCZVefdE.js +1 -0
  49. package/dist/assets/{useInlineCommentController-BiWz4AVb.js → useInlineCommentController-DDkpBEU8.js} +2 -2
  50. package/dist/assets/{useRootScrollLock-BS4-kr7P.js → useRootScrollLock-CwjoWuC4.js} +1 -1
  51. package/dist/assets/{vendor-base-ui-DdV8vhHn.js → vendor-base-ui-BY_5qla_.js} +1 -1
  52. package/dist/assets/{vendor-codemirror-language-data-Bg4AEeCr.js → vendor-codemirror-language-data-Cb1YnICj.js} +2 -2
  53. package/dist/assets/vendor-legendapp-list-BuBPBC3R.js +1 -0
  54. package/dist/assets/{vendor-zod-BPAANqvH.js → vendor-zod-B6551dwG.js} +2 -2
  55. package/dist/assets/{web-components-z7hfnS8n.js → web-components-LV3vjTxy.js} +1 -1
  56. package/dist/assets/zh-CN-DDYg0Jl7.js +16 -0
  57. package/dist/assets/zh-TW-CQKaCayr.js +16 -0
  58. package/dist/index.html +4 -4
  59. package/dist/mini-chat.html +4 -4
  60. package/dist/mobile.html +4 -4
  61. package/package.json +1 -1
  62. package/server/index.js +3 -13
  63. package/server/lib/agent-memory/runtime.js +7 -2
  64. package/server/lib/agent-memory/runtime.test.js +22 -0
  65. package/server/lib/event-stream/DOCUMENTATION.md +3 -0
  66. package/server/lib/event-stream/global-hub.js +29 -4
  67. package/server/lib/event-stream/global-hub.test.js +22 -0
  68. package/server/lib/event-stream/global-ws-bridge.js +15 -18
  69. package/server/lib/event-stream/protocol.js +21 -7
  70. package/server/lib/event-stream/runtime.js +9 -6
  71. package/server/lib/event-stream/runtime.test.js +60 -0
  72. package/server/lib/git/DOCUMENTATION.md +10 -1
  73. package/server/lib/git/routes.js +21 -8
  74. package/server/lib/git/routes.test.js +78 -0
  75. package/server/lib/git/service.js +159 -4
  76. package/server/lib/git/service.test.js +74 -0
  77. package/server/lib/github/DOCUMENTATION.md +5 -0
  78. package/server/lib/github/routes.js +2 -2
  79. package/server/lib/message-queue/DOCUMENTATION.md +7 -0
  80. package/server/lib/message-queue/runtime.js +13 -0
  81. package/server/lib/message-queue/runtime.test.js +31 -1
  82. package/server/lib/notifications/DOCUMENTATION.md +1 -1
  83. package/server/lib/notifications/emitter-runtime.js +4 -3
  84. package/server/lib/opencode/DOCUMENTATION.md +18 -4
  85. package/server/lib/opencode/env-runtime.js +5 -1
  86. package/server/lib/opencode/env-runtime.test.js +72 -0
  87. package/server/lib/opencode/feature-routes-runtime.js +15 -1
  88. package/server/lib/opencode/lifecycle.js +4 -3
  89. package/server/lib/opencode/lifecycle.test.js +29 -0
  90. package/server/lib/opencode/managed-plugin-config.js +1 -1
  91. package/server/lib/opencode/proxy.js +33 -0
  92. package/server/lib/opencode/settings-helpers.js +3 -0
  93. package/server/lib/opencode/settings-helpers.test.js +11 -1
  94. package/server/lib/opencode/settings-registry.json +3 -0
  95. package/server/lib/opencode/settings-runtime.js +36 -9
  96. package/server/lib/opencode/settings-runtime.test.js +158 -2
  97. package/server/lib/project-context/DOCUMENTATION.md +13 -3
  98. package/server/lib/project-context/runtime.js +8 -2
  99. package/server/lib/project-context/runtime.test.js +54 -0
  100. package/server/lib/projects/DOCUMENTATION.md +2 -1
  101. package/server/lib/projects/project-config.js +38 -9
  102. package/server/lib/projects/project-config.test.js +97 -0
  103. package/server/lib/projects/project-id.js +26 -0
  104. package/server/lib/relay/DOCUMENTATION.md +20 -0
  105. package/server/lib/relay/host-client.js +7 -0
  106. package/server/lib/relay/host-client.test.js +14 -0
  107. package/server/lib/scheduled-tasks/DOCUMENTATION.md +9 -1
  108. package/server/lib/scheduled-tasks/issue-2710-double-execution.test.js +28 -0
  109. package/server/lib/scheduled-tasks/runtime.js +12 -2
  110. package/server/lib/scheduled-tasks/runtime.test.js +53 -0
  111. package/server/lib/session-assist/DOCUMENTATION.md +131 -66
  112. package/server/lib/session-assist/context.js +127 -0
  113. package/server/lib/session-assist/context.test.js +132 -0
  114. package/server/lib/session-assist/prompt.js +54 -0
  115. package/server/lib/session-assist/runtime.js +111 -257
  116. package/server/lib/session-assist/runtime.test.js +203 -0
  117. package/server/lib/walkthrough/DOCUMENTATION.md +15 -5
  118. package/server/lib/walkthrough/pr-source.test.js +21 -0
  119. package/server/lib/walkthrough/pull-request.js +7 -4
  120. package/server/lib/walkthrough/pull-request.test.js +16 -0
  121. package/server/lib/walkthrough/routes.js +19 -0
  122. package/server/lib/walkthrough/routes.test.js +26 -0
  123. package/server/lib/walkthrough/sources.js +13 -2
  124. package/server/opencode-worktree-readiness.test.js +130 -0
  125. package/dist/assets/DiffView-DXjVsEOw.js +0 -4
  126. package/dist/assets/FilesView-CJdG0-wk.js +0 -17
  127. package/dist/assets/PlanView-CJTmOF6I.js +0 -5
  128. package/dist/assets/SettingsView-DD-JqIJx.js +0 -28
  129. package/dist/assets/WalkthroughView-DeKMvZlL.js +0 -4
  130. package/dist/assets/de-DCrsQ5zS.js +0 -10
  131. package/dist/assets/es-Dwv4YfH6.js +0 -16
  132. package/dist/assets/fr-BCWg4Cnx.js +0 -14
  133. package/dist/assets/index-B68h5S5B.css +0 -1
  134. package/dist/assets/index-DVwMarHI.js +0 -39
  135. package/dist/assets/ja-Bruw3RYC.js +0 -16
  136. package/dist/assets/main-BkyaQhJX.js +0 -930
  137. package/dist/assets/patchFileDiff-Csk4iNUi.js +0 -13
  138. package/dist/assets/pt-BR-B8V7u7tA.js +0 -16
  139. package/dist/assets/renderElectronMiniChatApp-BxoyujA5.js +0 -2
  140. package/dist/assets/renderMobileApp-B48CsP4r.js +0 -25
  141. package/dist/assets/runtimeEndpointReset-Bg5gx18H.js +0 -17
  142. package/dist/assets/scheduledTasksApi-BW0Etzwz.js +0 -1
  143. package/dist/assets/surface-oMvhsog3.js +0 -1
  144. package/dist/assets/tr-BK_KiO2V.js +0 -7
  145. package/dist/assets/uk-CG74xV8N.js +0 -16
  146. package/dist/assets/useGitComparison-DH220WmO.js +0 -1
  147. package/dist/assets/vendor-legendapp-list-gg7YLRW7.js +0 -1
  148. package/dist/assets/zh-CN-T4AXofZI.js +0 -16
  149. package/dist/assets/zh-TW-Dte40sxp.js +0 -16
  150. package/server/lib/mcp-reconnect/DOCUMENTATION.md +0 -55
  151. package/server/lib/mcp-reconnect/runtime.js +0 -122
  152. package/server/lib/mcp-reconnect/runtime.test.js +0 -140
@@ -1,17 +1,12 @@
1
- // Session assist: after a session goes idle and stays quiet, generate a short
2
- // recap of the agent's last reply plus one suggested user follow-up with the
3
- // small model, and store both on the session's metadata
4
- // (metadata.aiworker.assist). Clients decide visibility from
5
- // assist.forMessageID — a new message makes the payload stale everywhere
6
- // without any extra writes.
7
- //
8
- // Purely event-driven: only sessions that transition busy→idle while the
9
- // server is running ever generate anything. No backfill, no session scans.
10
-
1
+ // Background session assistance. Only live idle events arm generation; there
2
+ // is no backfill. Clients hide results whose forMessageID is no longer current.
11
3
  import fs from 'fs';
12
4
  import os from 'os';
13
5
  import path from 'path';
6
+ import { createOpencodeClient } from '@opencode-ai/sdk/v2';
14
7
  import { readMergedSettingsSync } from '../opencode/settings-files.js';
8
+ import { loadAssistContext } from './context.js';
9
+ import { buildAssistPrompt, buildAssistSystemPrompt } from './prompt.js';
15
10
 
16
11
  const AIWORKER_SETTINGS_FILE = path.join(
17
12
  process.env.AIWORKER_DATA_DIR
@@ -20,9 +15,6 @@ const AIWORKER_SETTINGS_FILE = path.join(
20
15
  'settings.json',
21
16
  );
22
17
 
23
- // The Chat settings are hard generation switches (default on): when both are
24
- // off, no small-model calls and no metadata writes happen at all. Existing
25
- // payloads stay untouched — clients keep showing them and dismissal still works.
26
18
  const getSessionAssistTargets = () => {
27
19
  const settings = readMergedSettingsSync({ fs, path, settingsFilePath: AIWORKER_SETTINGS_FILE });
28
20
  return {
@@ -32,58 +24,11 @@ const getSessionAssistTargets = () => {
32
24
  };
33
25
 
34
26
  const IDLE_QUIET_MS = 60_000;
35
- const TRANSCRIPT_MESSAGE_LIMIT = 12;
36
- const TRANSCRIPT_PART_CHAR_LIMIT = 6_000;
37
27
  const RECAP_CHAR_LIMIT = 320;
38
28
  const SUGGESTION_CHAR_LIMIT = 500;
39
29
  const FETCH_TIMEOUT_MS = 5_000;
40
-
41
- const buildAssistSystemPrompt = ({ recap, suggestion }) => [
42
- 'You assist a user who chats with a coding agent. Based on the conversation transcript, return exactly one JSON object and nothing else — no prose, no markdown, no code fences.',
43
- `Shape: {${[recap ? '"recap": string' : '', suggestion ? '"suggestion": string' : ''].filter(Boolean).join(', ')}}`,
44
- recap
45
- ? 'recap: at most 20 words. State the substance directly — the facts, result, or conclusion, plus the next move if there is one. NEVER narrate ("The assistant explained…", "The agent did…") — write the content itself, like a note the user jotted down.'
46
- : '',
47
- suggestion ? 'suggestion: write ONE immediately sendable next user message addressed TO the coding agent.' : '',
48
- suggestion ? 'The suggestion should be the most useful next step after the assistant\'s latest reply. It should help the user continue productively, not inspect already-known details.' : '',
49
- suggestion ? 'Prefer suggestions that ask the agent to make a concrete improvement, implement something specific, validate the latest change, explain tradeoffs, improve the current approach, or continue from the current result.' : '',
50
- suggestion ? 'Rules for suggestion:' : '',
51
- suggestion ? '- Output exactly one message the user could click and send without editing.' : '',
52
- suggestion ? '- Pick one best next action yourself.' : '',
53
- suggestion ? '- Do not include alternatives, choices, slash-separated options, or "or".' : '',
54
- suggestion ? '- Do not write "Do X or Y", "Ask whether...", "Maybe...", or "You could...".' : '',
55
- suggestion ? '- Do not ask for information the assistant already provided.' : '',
56
- suggestion ? '- Do not ask to see exact code, file paths, prompt locations, or implementation internals unless the assistant did not provide them and they are necessary for the next step.' : '',
57
- suggestion ? '- Do not produce generic workflow commands like "Run tests" unless testing is clearly the next unresolved step.' : '',
58
- suggestion ? '- Do not produce meta/debug requests that merely inspect the implementation.' : '',
59
- suggestion ? '- Use imperative or question form.' : '',
60
- suggestion ? '- Keep it concise.' : '',
61
- suggestion ? 'Use these examples to understand how to choose the suggestion. Do not copy their topic or wording unless the current conversation is about the same thing.' : '',
62
- suggestion ? 'Example 1:' : '',
63
- suggestion ? 'Assistant reply summary:' : '',
64
- suggestion ? 'The assistant already identified the file where the feature is implemented, explained what context is sent to the small model, and summarized the current prompt.' : '',
65
- suggestion ? 'Bad suggestion:' : '',
66
- suggestion ? '"Show me the exact runtime.js code and where the prompt is built."' : '',
67
- suggestion ? 'Why bad:' : '',
68
- suggestion ? 'It asks for information the assistant already provided. It repeats inspection instead of moving to an improvement or decision.' : '',
69
- suggestion ? 'Good suggestion:' : '',
70
- suggestion ? '"Suggest how to improve the prompt and context so the generated suggestion is more useful."' : '',
71
- suggestion ? 'Why good:' : '',
72
- suggestion ? 'It naturally continues from the analysis and asks for a concrete improvement.' : '',
73
- suggestion ? 'Example 2:' : '',
74
- suggestion ? 'Assistant reply summary:' : '',
75
- suggestion ? 'The assistant implemented a timeline dialog redesign, listed concrete UI changes, and reported that type-check and lint passed.' : '',
76
- suggestion ? 'Bad suggestion:' : '',
77
- suggestion ? '"Check whether scrolling or loading older messages works without jumps."' : '',
78
- suggestion ? 'Why bad:' : '',
79
- suggestion ? 'It contains an alternative. A suggestion chip must be one sendable message, not a choice the user has to edit.' : '',
80
- suggestion ? 'Good suggestion:' : '',
81
- suggestion ? '"Check whether scrolling and loading older messages work without jumps."' : '',
82
- suggestion ? 'Why good:' : '',
83
- suggestion ? 'It picks a single validation request that the user can send immediately.' : '',
84
- 'All requested values MUST be written in the same language as the conversation text itself. Ignore any other language preferences or personalization you may have — only the conversation text decides the language.',
85
- 'Use double quotes for JSON strings, no trailing commas.',
86
- ].filter(Boolean).join('\n');
30
+ const GENERATION_TIMEOUT_MS = 120_000;
31
+ const QUIET_FAILURE_CODES = new Set(['context-too-small', 'output-exhausted']);
87
32
 
88
33
  const extractJsonObject = (value) => {
89
34
  const text = String(value ?? '').trim();
@@ -132,23 +77,16 @@ const extractUserMessage = (payload) => {
132
77
  };
133
78
  };
134
79
 
135
- const messagePartsToText = (message) => {
136
- const parts = Array.isArray(message?.parts) ? message.parts : [];
137
- return parts
138
- .map((part) => (part?.type === 'text' && typeof part.text === 'string' ? part.text : ''))
139
- .filter(Boolean)
140
- .join('\n')
141
- .slice(0, TRANSCRIPT_PART_CHAR_LIMIT);
142
- };
143
-
144
80
  export const createSessionAssistRuntime = ({
145
81
  buildOpenCodeUrl,
146
82
  getOpenCodeAuthHeaders,
147
83
  getSmallModelService,
84
+ getTargets = getSessionAssistTargets,
148
85
  quietMs = IDLE_QUIET_MS,
149
86
  }) => {
150
87
  const timers = new Map();
151
- const inflight = new Set();
88
+ const inflight = new Map();
89
+ const ready = new Map();
152
90
  let stopped = false;
153
91
 
154
92
  const clearTimer = (sessionId) => {
@@ -159,233 +97,149 @@ export const createSessionAssistRuntime = ({
159
97
  }
160
98
  };
161
99
 
162
- const openCodeFetch = async (path, { directory, method = 'GET', body } = {}) => {
163
- const base = buildOpenCodeUrl(path, '');
164
- const url = directory ? `${base}?directory=${encodeURIComponent(directory)}` : base;
165
- const response = await fetch(url, {
166
- method,
167
- headers: {
168
- Accept: 'application/json',
169
- ...(body ? { 'Content-Type': 'application/json' } : {}),
170
- ...getOpenCodeAuthHeaders(),
171
- },
172
- ...(body ? { body: JSON.stringify(body) } : {}),
173
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
174
- });
175
- if (!response.ok) {
176
- throw new Error(`OpenCode ${method} ${path} failed with ${response.status}`);
177
- }
178
- return response.json().catch(() => null);
179
- };
180
-
181
- const fetchRecentMessages = async (sessionId, directory) => {
182
- const base = buildOpenCodeUrl(`/session/${encodeURIComponent(sessionId)}/message`, '');
183
- const params = new URLSearchParams({ limit: String(TRANSCRIPT_MESSAGE_LIMIT) });
184
- if (directory) params.set('directory', directory);
185
- const response = await fetch(`${base}?${params.toString()}`, {
186
- method: 'GET',
187
- headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
188
- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
189
- });
190
- if (!response.ok) return null;
191
- const messages = await response.json().catch(() => null);
192
- return Array.isArray(messages) ? messages : null;
100
+ const invalidate = (sessionId) => {
101
+ clearTimer(sessionId);
102
+ ready.delete(sessionId);
103
+ inflight.get(sessionId)?.controller.abort();
193
104
  };
194
105
 
195
- const generateAssist = async (sessionId, directory) => {
196
- const targets = getSessionAssistTargets();
106
+ const generateAssist = async (sessionId, directory, signal) => {
107
+ const targets = getTargets();
197
108
  if (!targets.recap && !targets.suggestion) return;
198
- const session = await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, { directory })
199
- .catch((error) => {
200
- console.warn(`[session-assist] session fetch failed: ${error?.message || error}`);
201
- return null;
202
- });
203
- if (!session || typeof session !== 'object') return;
204
- // Sub-agent/task sessions never surface in chat — skip them.
205
- if (typeof session.parentID === 'string' && session.parentID) return;
206
-
207
- const messages = await fetchRecentMessages(sessionId, directory);
208
- if (!messages || messages.length === 0) {
209
- console.warn('[session-assist] no messages fetched');
210
- return;
211
- }
212
-
213
- let lastAssistant = null;
214
- for (let i = messages.length - 1; i >= 0; i -= 1) {
215
- const info = messages[i]?.info;
216
- if (info?.role === 'assistant') {
217
- lastAssistant = messages[i];
218
- break;
219
- }
220
- }
221
- const lastAssistantInfo = lastAssistant?.info;
222
- if (!lastAssistantInfo?.id) return;
223
-
224
- // Only the last exchange: the assistant reply plus the user message it
225
- // answered (assistant info.parentID → user info.id). Everything else is
226
- // token waste for a one-line recap and a single suggestion.
227
- const parentUserMessage = typeof lastAssistantInfo.parentID === 'string' && lastAssistantInfo.parentID
228
- ? messages.find((message) => message?.info?.id === lastAssistantInfo.parentID && message?.info?.role === 'user')
229
- : null;
230
- const userText = parentUserMessage ? messagePartsToText(parentUserMessage) : '';
231
- const assistantText = messagePartsToText(lastAssistant);
232
- const transcript = [
233
- userText ? `User:\n${userText}` : '',
234
- assistantText ? `Assistant:\n${assistantText}` : '',
235
- ].filter(Boolean).join('\n\n');
236
- if (!transcript) return;
237
-
238
- const { generateSmallModelText } = await getSmallModelService();
239
- const requestedFields = [targets.recap ? 'recap' : '', targets.suggestion ? 'suggestion' : '']
240
- .filter(Boolean)
241
- .join(' and ');
242
- // Instruct the language by example, not by description — account-side
243
- // personalization (e.g. the ChatGPT backend knowing the user's locale)
244
- // otherwise leaks a different language into the output.
245
- const languageSample = (userText || assistantText).slice(0, 200).replace(/\s+/g, ' ').trim();
109
+ const baseUrl = buildOpenCodeUrl('/', '').replace(/\/$/, '');
110
+ const client = createOpencodeClient({ baseUrl, headers: getOpenCodeAuthHeaders(), throwOnError: true });
111
+ const requestOptions = () => ({ signal: AbortSignal.any([signal, AbortSignal.timeout(FETCH_TIMEOUT_MS)]) });
112
+ const checkCurrent = () => {
113
+ signal.throwIfAborted();
114
+ if (buildOpenCodeUrl('/', '').replace(/\/$/, '') !== baseUrl) throw new Error('Session assist runtime changed');
115
+ };
116
+ const { data: session } = await client.session.get({ sessionID: sessionId, directory }, requestOptions());
117
+ checkCurrent();
118
+ // Reverted history is not the active conversation. A new prompt clears
119
+ // the revert boundary before its next idle event.
120
+ if (session?.id !== sessionId || session.parentID || session.revert?.messageID || session.time?.archived) return;
121
+ const context = await loadAssistContext({
122
+ signal,
123
+ readPage: (page) => client.session.messages({ sessionID: sessionId, directory, ...page }, requestOptions()),
124
+ });
125
+ checkCurrent();
126
+ if (!context) return;
127
+ const { last, turns } = context;
128
+ const { describeSmallModel, generateSmallModelText } = await getSmallModelService();
129
+ const preferredProviderID = last.providerID;
130
+ const preferredModelID = last.modelID;
131
+ const described = await describeSmallModel({ directory, preferredProviderID, preferredModelID });
132
+ checkCurrent();
133
+ if (!described) return;
134
+ const system = buildAssistSystemPrompt(targets);
135
+ const prompt = buildAssistPrompt(turns, targets, described.inputCharBudget - system.length - 512);
136
+ if (!prompt) return;
246
137
  let generated;
247
138
  try {
248
139
  generated = await generateSmallModelText({
249
- // Background feature: conversation content must never leave the
250
- // session's own provider unless the user explicitly picked a small
251
- // model (settings override / opencode config).
252
- restrictToPreferredProvider: true,
253
- prompt: `The latest exchange in the conversation:\n\n${transcript}\n\nWrite ${requestedFields} in the SAME language as this sample from the conversation: "${languageSample}"`,
254
- system: buildAssistSystemPrompt(targets),
255
- directory,
256
- sessionID: sessionId,
257
- preferredProviderID: typeof lastAssistantInfo.providerID === 'string' ? lastAssistantInfo.providerID : undefined,
258
- preferredModelID: typeof lastAssistantInfo.modelID === 'string' ? lastAssistantInfo.modelID : undefined,
140
+ prompt: prompt.text, system, directory, sessionID: sessionId,
141
+ preferredProviderID, preferredModelID, restrictToPreferredProvider: true,
142
+ onOverflow: 'error', timeoutMs: GENERATION_TIMEOUT_MS, signal,
259
143
  });
260
144
  } catch (error) {
261
- // No authenticated provider (404) or a transient model failure — this is
262
- // background sugar, never retry loops or logs spam.
263
- if (Number(error?.statusCode) !== 404) {
264
- console.warn('[session-assist] generation failed:', error?.message || error);
145
+ if (!signal.aborted && Number(error?.statusCode) !== 404 && !QUIET_FAILURE_CODES.has(error?.code)) {
146
+ console.warn('[session-assist] generation failed');
265
147
  }
266
148
  return;
267
149
  }
268
-
150
+ checkCurrent();
269
151
  const structured = extractJsonObject(generated?.text);
270
152
  let recap = targets.recap && typeof structured?.recap === 'string' ? structured.recap.trim().slice(0, RECAP_CHAR_LIMIT) : '';
271
153
  let suggestion = targets.suggestion && typeof structured?.suggestion === 'string' ? structured.suggestion.trim().slice(0, SUGGESTION_CHAR_LIMIT) : '';
272
-
273
- // Hard guard against language hallucination: if the conversation contains
274
- // no Cyrillic/CJK at all, the output must not either (and drop per-field,
275
- // so one hallucinated field doesn't kill the other).
276
154
  const hasCyrillic = (text) => /[\u0400-\u04FF]/.test(text);
277
155
  const hasCjk = (text) => /[\u3040-\u30FF\u4E00-\u9FFF\uAC00-\uD7AF]/.test(text);
278
- const inputText = `${userText}\n${assistantText}`;
279
- const scriptMismatch = (text) => (hasCyrillic(text) && !hasCyrillic(inputText))
280
- || (hasCjk(text) && !hasCjk(inputText));
281
- if (recap && scriptMismatch(recap)) {
282
- console.warn('[session-assist] dropped recap: language mismatch with conversation');
283
- recap = '';
284
- }
285
- if (suggestion && scriptMismatch(suggestion)) {
286
- console.warn('[session-assist] dropped suggestion: language mismatch with conversation');
287
- suggestion = '';
288
- }
156
+ // Quoted source and assistant replies cannot authorize a different script.
157
+ // With no authored language sample, leave the decision to the prompt.
158
+ const scriptMismatch = (text) => prompt.language && ((hasCyrillic(text) && !hasCyrillic(prompt.language))
159
+ || (hasCjk(text) && !hasCjk(prompt.language)));
160
+ if (recap && scriptMismatch(recap)) recap = '';
161
+ if (suggestion && scriptMismatch(suggestion)) suggestion = '';
162
+ if (!recap && !suggestion) return;
163
+ const { data: latest } = await client.session.messages({ sessionID: sessionId, directory, limit: 1 }, requestOptions());
164
+ checkCurrent();
165
+ if (latest?.at(-1)?.info.id !== last.id) return;
166
+ // Never fall back to the pre-generation metadata snapshot after a failed
167
+ // fresh read: doing so overwrites dismissals and unrelated metadata.
168
+ const { data: freshSession } = await client.session.get({ sessionID: sessionId, directory }, requestOptions());
169
+ checkCurrent();
170
+ if (freshSession?.id !== sessionId || freshSession.revert?.messageID || freshSession.time?.archived || freshSession.directory !== session.directory) return;
171
+ const enabled = getTargets();
172
+ if (!enabled.recap) recap = '';
173
+ if (!enabled.suggestion) suggestion = '';
289
174
  if (!recap && !suggestion) return;
175
+ const currentMetadata = freshSession.metadata ?? {};
176
+ const currentNamespace = currentMetadata.aiworker ?? {};
177
+ await client.session.update({
178
+ sessionID: sessionId, directory,
179
+ metadata: {
180
+ ...currentMetadata,
181
+ aiworker: {
182
+ ...currentNamespace,
183
+ assist: { recap, suggestion, forMessageID: last.id, generatedAt: Date.now() },
184
+ },
185
+ },
186
+ }, requestOptions());
187
+ };
290
188
 
291
- // The session may have moved on while we generated — a stale patch would
292
- // flash outdated content, so re-check the tail before writing.
293
- const latest = await fetchRecentMessages(sessionId, directory);
294
- const latestAssistantId = (() => {
295
- if (!latest) return null;
296
- for (let i = latest.length - 1; i >= 0; i -= 1) {
297
- const info = latest[i]?.info;
298
- if (info?.role === 'assistant') return info.id;
299
- if (info?.role === 'user') return null;
300
- }
301
- return null;
302
- })();
303
- if (latestAssistantId !== lastAssistantInfo.id) {
304
- console.log('[session-assist] tail moved on, dropping result');
189
+ const startGeneration = (sessionId, directory, armedAt) => {
190
+ if (stopped) return;
191
+ if (inflight.has(sessionId)) {
192
+ ready.set(sessionId, { directory, armedAt });
305
193
  return;
306
194
  }
307
-
308
- // Merge from a FRESH read: generation takes tens of seconds, and merging
309
- // from the session snapshot fetched before it would clobber any metadata
310
- // written meanwhile (suggestion dismissals, review links, …).
311
- const freshSession = await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, { directory })
312
- .catch(() => null);
313
- const currentMetadata = freshSession?.metadata && typeof freshSession.metadata === 'object'
314
- ? freshSession.metadata
315
- : (session.metadata && typeof session.metadata === 'object' ? session.metadata : {});
316
- const currentNamespace = currentMetadata.aiworker && typeof currentMetadata.aiworker === 'object'
317
- ? currentMetadata.aiworker
318
- : {};
319
-
320
- console.log(`[session-assist] generated for ${sessionId} via ${generated.providerID}/${generated.modelID}`);
321
- await openCodeFetch(`/session/${encodeURIComponent(sessionId)}`, {
322
- directory,
323
- method: 'PATCH',
324
- body: {
325
- metadata: {
326
- ...currentMetadata,
327
- aiworker: {
328
- ...currentNamespace,
329
- assist: {
330
- recap,
331
- suggestion,
332
- forMessageID: lastAssistantInfo.id,
333
- generatedAt: Date.now(),
334
- },
335
- },
336
- },
337
- },
338
- });
195
+ const controller = new AbortController();
196
+ inflight.set(sessionId, { controller, armedAt });
197
+ generateAssist(sessionId, directory, controller.signal)
198
+ .catch(() => {
199
+ if (!controller.signal.aborted) console.warn('[session-assist] failed to read or save assistance');
200
+ })
201
+ .finally(() => {
202
+ inflight.delete(sessionId);
203
+ if (ready.has(sessionId)) {
204
+ const next = ready.get(sessionId);
205
+ ready.delete(sessionId);
206
+ startGeneration(sessionId, next.directory, next.armedAt);
207
+ }
208
+ });
339
209
  };
340
210
 
341
211
  const armTimer = (sessionId, directory) => {
342
212
  clearTimer(sessionId);
213
+ const armedAt = Date.now();
343
214
  const timer = setTimeout(() => {
344
215
  timers.delete(sessionId);
345
- if (stopped || inflight.has(sessionId)) return;
346
- inflight.add(sessionId);
347
- generateAssist(sessionId, directory)
348
- .catch((error) => {
349
- console.warn('[session-assist] failed:', error?.message || error);
350
- })
351
- .finally(() => {
352
- inflight.delete(sessionId);
353
- });
216
+ startGeneration(sessionId, directory, armedAt);
354
217
  }, quietMs);
355
- if (typeof timer?.unref === 'function') timer.unref();
356
- timers.set(sessionId, { timer, armedAt: Date.now() });
218
+ timer.unref?.();
219
+ timers.set(sessionId, { timer, armedAt });
357
220
  };
358
221
 
359
222
  const processPayload = (payload, directoryHint = '') => {
360
223
  if (stopped) return;
361
224
  const status = extractSessionStatus(payload);
362
225
  if (status) {
363
- if (status.type === 'idle') {
364
- armTimer(status.sessionId, status.directory || directoryHint);
365
- } else {
366
- clearTimer(status.sessionId);
367
- }
226
+ if (status.type === 'idle') armTimer(status.sessionId, status.directory || directoryHint);
227
+ else invalidate(status.sessionId);
368
228
  return;
369
229
  }
370
230
  const userMessage = extractUserMessage(payload);
371
231
  if (userMessage) {
372
- // OpenCode re-emits message.updated for OLD user messages after the
373
- // session settles (post-completion metadata patches). Only a message
374
- // created after the timer was armed means the user actually moved on.
375
- const armed = timers.get(userMessage.sessionId);
376
- if (armed && userMessage.createdAt >= armed.armedAt) {
377
- clearTimer(userMessage.sessionId);
378
- }
232
+ // Ignore old message.updated events re-emitted after completion.
233
+ const since = timers.get(userMessage.sessionId)?.armedAt ?? inflight.get(userMessage.sessionId)?.armedAt;
234
+ if (since !== undefined && userMessage.createdAt >= since) invalidate(userMessage.sessionId);
379
235
  }
380
236
  };
381
237
 
382
238
  const stop = () => {
383
239
  stopped = true;
384
- for (const { timer } of timers.values()) {
385
- clearTimeout(timer);
386
- }
387
- timers.clear();
240
+ for (const sessionId of timers.keys()) clearTimer(sessionId);
241
+ ready.clear();
242
+ for (const { controller } of inflight.values()) controller.abort();
388
243
  };
389
-
390
244
  return { processPayload, stop };
391
245
  };