@yuridulin/pointer 0.0.0-stage → 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 (71) hide show
  1. package/README.md +54 -2
  2. package/package.json +51 -4
  3. package/server/acp/catalog.ts +111 -0
  4. package/server/acp/connection.ts +233 -0
  5. package/server/acp/fake-agent.ts +408 -0
  6. package/server/acp/protocol.ts +167 -0
  7. package/server/acp/run.ts +139 -0
  8. package/server/acp/session.ts +1249 -0
  9. package/server/attachments.ts +115 -0
  10. package/server/changes.ts +239 -0
  11. package/server/cli.ts +362 -0
  12. package/server/compact.ts +361 -0
  13. package/server/config.ts +176 -0
  14. package/server/db.ts +462 -0
  15. package/server/dev.ts +8 -0
  16. package/server/diff.ts +190 -0
  17. package/server/engines.ts +63 -0
  18. package/server/files.ts +254 -0
  19. package/server/git.ts +319 -0
  20. package/server/history.ts +425 -0
  21. package/server/http/attachments.ts +63 -0
  22. package/server/http/browse.ts +108 -0
  23. package/server/http/chats.ts +627 -0
  24. package/server/http/closing.ts +14 -0
  25. package/server/http/files.ts +115 -0
  26. package/server/http/git.ts +84 -0
  27. package/server/http/preview.ts +21 -0
  28. package/server/http/providers.ts +200 -0
  29. package/server/http/reply.ts +38 -0
  30. package/server/hub.ts +521 -0
  31. package/server/install.ts +169 -0
  32. package/server/jobs.ts +664 -0
  33. package/server/linkPreview.ts +172 -0
  34. package/server/loop.ts +328 -0
  35. package/server/main.ts +353 -0
  36. package/server/probe.ts +34 -0
  37. package/server/process.ts +333 -0
  38. package/server/prompt.ts +196 -0
  39. package/server/providers/fake.ts +100 -0
  40. package/server/providers/opencode.ts +468 -0
  41. package/server/providers/registry.ts +149 -0
  42. package/server/providers/store.ts +210 -0
  43. package/server/segments.ts +248 -0
  44. package/server/sse.ts +93 -0
  45. package/server/tools/bash.ts +222 -0
  46. package/server/tools/edit.ts +254 -0
  47. package/server/tools/glob.ts +63 -0
  48. package/server/tools/grep.ts +122 -0
  49. package/server/tools/ignore.ts +54 -0
  50. package/server/tools/index.ts +129 -0
  51. package/server/tools/jail.ts +85 -0
  52. package/server/tools/jobs.ts +293 -0
  53. package/server/tools/read.ts +248 -0
  54. package/server/tools/write.ts +70 -0
  55. package/server/tray.ps1 +191 -0
  56. package/server/turn.ts +663 -0
  57. package/server/watch.ts +94 -0
  58. package/shared/acpConfig.ts +113 -0
  59. package/shared/links.ts +122 -0
  60. package/shared/types.ts +392 -0
  61. package/web/dist/app.css +1 -0
  62. package/web/dist/assets/codicon-mxdk0fnd.ttf +0 -0
  63. package/web/dist/index.html +28 -0
  64. package/web/dist/main.css +1 -0
  65. package/web/dist/main.js +1366 -0
  66. package/web/dist/tokens.css +1 -0
  67. package/web/dist/workers/css.worker.js +97 -0
  68. package/web/dist/workers/editor.worker.js +30 -0
  69. package/web/dist/workers/html.worker.js +300 -0
  70. package/web/dist/workers/json.worker.js +62 -0
  71. package/web/dist/workers/ts.worker.js +67733 -0
@@ -0,0 +1,627 @@
1
+ import { readFileSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import type { Database } from 'bun:sqlite'
4
+ import { BLOB_LIMIT, getBlob, getRevision, hashOnDisk, listRevisions, markReviewed, revertRevision } from '../changes'
5
+ import type { AcpAnswer, ReasoningLevel } from '../../shared/types'
6
+ import { compactChat, isCompacting } from '../compact'
7
+ import { reasoningLevel, type Config } from '../config'
8
+ import { acpAgent, isAcpEngine, resolveAcpCommand } from '../engines'
9
+ import { acpOverride, defaultModelId, getProvider, providerEnabled } from '../providers/store'
10
+ import { answerAcpQuestion, getAcpSession, stopAcpSession } from '../acp/session'
11
+ import { createAcpRun } from '../acp/run'
12
+ import {
13
+ createChat,
14
+ deleteChat,
15
+ getChat,
16
+ getWorkspace,
17
+ listChats,
18
+ listMessages,
19
+ updateChat,
20
+ type ChatRow,
21
+ type WorkspaceRow,
22
+ } from '../db'
23
+ import { forkChat, truncateChat, type TruncateResult } from '../history'
24
+ import { messageView, type Hub } from '../hub'
25
+ import { RING_LIMIT, type JobRegistry } from '../jobs'
26
+ import { abortRun, activeRun, postMessage as postChatMessage, startRun, type RunFactory } from '../loop'
27
+ import type { Shell } from '../tools'
28
+ import { createTurnRun, type TurnInput } from '../turn'
29
+ import { fail, isRecord, readJson } from './reply'
30
+ import { isClosing, markClosing, unmarkClosing } from './closing'
31
+
32
+ export type ChatDeps = {
33
+ db: Database
34
+ config: Config
35
+ hub: Hub
36
+ shell: Shell | null
37
+ stream: TurnInput['stream']
38
+ jobs: JobRegistry
39
+ }
40
+
41
+ export function isChatsRoute(parts: string[]): boolean {
42
+ if (parts[0] !== 'api') return false
43
+ if (parts[1] === 'chats') return parts.length >= 3
44
+ return parts[1] === 'workspaces' && parts.length === 4 && parts[3] === 'chats'
45
+ }
46
+
47
+ export function chatsRoute(req: Request, deps: ChatDeps, parts: string[]): Promise<Response> | Response {
48
+ const { db, config, hub, shell, jobs } = deps
49
+ if (parts[1] === 'workspaces' && parts[3] === 'chats') {
50
+ const workspace = getWorkspace(db, parts[2] ?? '')
51
+ if (!workspace) return fail(404, 'Папка не найдена')
52
+ if (req.method === 'GET') {
53
+ return Response.json(
54
+ listChats(db, workspace.id).map((chat) => ({
55
+ ...chat,
56
+ status: hub.snapshot(chat.id, []).status,
57
+ })),
58
+ )
59
+ }
60
+ if (req.method === 'POST') return postCreateChat(req, db, config, hub, workspace)
61
+ return fail(404, 'Не найдено')
62
+ }
63
+
64
+ const chatId = parts[2] ?? ''
65
+ if (parts.length === 4 && parts[3] === 'truncate' && req.method === 'POST') {
66
+ return postTruncate(req, db, hub, chatId)
67
+ }
68
+ if (parts.length === 4 && parts[3] === 'fork' && req.method === 'POST') {
69
+ return postFork(req, db, hub, chatId)
70
+ }
71
+ if (parts.length === 4 && parts[3] === 'compact' && req.method === 'POST') {
72
+ return postCompact(req, deps, chatId)
73
+ }
74
+ if (parts.length === 3) {
75
+ if (req.method === 'GET') return snapshot(deps, chatId)
76
+ if (req.method === 'PATCH') return patchChat(req, db, config, hub, chatId)
77
+ if (req.method === 'DELETE') return deleteChatRoute(deps, chatId)
78
+ }
79
+ if (parts.length === 4 && parts[3] === 'jobs' && req.method === 'GET') {
80
+ if (!getChat(db, chatId)) return fail(404, 'Чат не найден')
81
+ return Response.json(jobs.list(chatId))
82
+ }
83
+ if (parts.length === 6 && parts[3] === 'jobs') {
84
+ const jobId = parts[4] ?? ''
85
+ if (parts[5] === 'output' && req.method === 'GET') return jobOutputRoute(deps, req, chatId, jobId)
86
+ if (parts[5] === 'kill' && req.method === 'POST') return killJobRoute(deps, chatId, jobId)
87
+ }
88
+ if (parts.length === 4 && parts[3] === 'messages' && req.method === 'POST') {
89
+ return postMessage(req, deps, chatId)
90
+ }
91
+ if (parts.length === 4 && parts[3] === 'abort' && req.method === 'POST') {
92
+ return postAbort(db, chatId)
93
+ }
94
+ if (parts.length === 4 && parts[3] === 'answer' && req.method === 'POST') {
95
+ return postAnswer(req, db, chatId)
96
+ }
97
+ if (parts.length === 4 && parts[3] === 'acp-config' && req.method === 'POST') {
98
+ return postAcpConfig(req, db, config, hub, shell, chatId)
99
+ }
100
+ if (parts.length === 4 && parts[3] === 'revisions' && req.method === 'GET') {
101
+ const chat = getChat(db, chatId)
102
+ if (!chat) return fail(404, 'Чат не найден')
103
+ return Response.json(listRevisions(db, chat.id))
104
+ }
105
+ if (parts.length === 6 && parts[3] === 'revisions') {
106
+ const revisionId = parts[4] ?? ''
107
+ if (parts[5] === 'revert' && req.method === 'POST') return postRevert(req, db, hub, chatId, revisionId)
108
+ if (parts[5] === 'before' && req.method === 'GET') return getBefore(db, chatId, revisionId)
109
+ if (parts[5] === 'review' && req.method === 'POST') return postReview(db, chatId, revisionId)
110
+ }
111
+ return fail(404, 'Не найдено')
112
+ }
113
+
114
+ function snapshot(deps: ChatDeps, chatId: string): Response {
115
+ const chat = getChat(deps.db, chatId)
116
+ if (!chat) return fail(404, 'Чат не найден')
117
+ const messages = listMessages(deps.db, chat.id).map(messageView)
118
+ return Response.json(deps.hub.snapshot(chat.id, messages, deps.jobs.list(chat.id)))
119
+ }
120
+
121
+ function jobOutputRoute(deps: ChatDeps, req: Request, chatId: string, jobId: string): Response {
122
+ if (!getChat(deps.db, chatId)) return fail(404, 'Чат не найден')
123
+ const raw = new URL(req.url).searchParams.get('offset') ?? '0'
124
+ const offset = Number(raw)
125
+ if (!Number.isFinite(offset) || offset < 0) return fail(400, 'offset должен быть неотрицательным числом')
126
+ const output = deps.jobs.output(chatId, jobId, Math.floor(offset), RING_LIMIT)
127
+ if (!output) return fail(404, 'Задача не найдена')
128
+ return Response.json(output)
129
+ }
130
+
131
+ async function killJobRoute(deps: ChatDeps, chatId: string, jobId: string): Promise<Response> {
132
+ if (!getChat(deps.db, chatId)) return fail(404, 'Чат не найден')
133
+ const result = await deps.jobs.kill(chatId, jobId, 'human')
134
+ if (result === 'missing') return fail(404, 'Задача не найдена')
135
+ if (result === 'already') return fail(409, 'Задача уже завершена')
136
+ if (result === 'running') return fail(409, 'Задача ещё работает')
137
+ return Response.json({ status: 'killed' })
138
+ }
139
+
140
+ async function patchChat(
141
+ req: Request,
142
+ db: Database,
143
+ config: Config,
144
+ hub: Hub,
145
+ chatId: string,
146
+ ): Promise<Response> {
147
+ const body = await readJson(req)
148
+ if (!isRecord(body)) return fail(400, 'Нужен объект')
149
+ const chat = getChat(db, chatId)
150
+ if (!chat) return fail(404, 'Чат не найден')
151
+ const patch: {
152
+ title?: string
153
+ model?: string
154
+ archived?: boolean
155
+ reasoning?: ReasoningLevel | null
156
+ engine?: string
157
+ } = {}
158
+ if ('title' in body) {
159
+ const title = body.title
160
+ if (typeof title !== 'string' || title.trim() === '') return fail(400, 'Нужен заголовок')
161
+ patch.title = title.trim()
162
+ }
163
+ if ('model' in body) {
164
+ const model = body.model
165
+ if (typeof model !== 'string' || model.trim() === '') return fail(400, 'Нужна модель')
166
+ patch.model = model.trim()
167
+ }
168
+ if ('archived' in body) {
169
+ const archived = body.archived
170
+ if (typeof archived !== 'boolean') return fail(400, 'archived должен быть boolean')
171
+ patch.archived = archived
172
+ }
173
+ if ('reasoning' in body) {
174
+ if (body.reasoning === null) patch.reasoning = null
175
+ else {
176
+ const level = reasoningLevel(body.reasoning)
177
+ if (!level) return fail(400, 'Уровень рассуждения: low, high или max')
178
+ patch.reasoning = level
179
+ }
180
+ }
181
+ if (typeof body.engine === 'string') {
182
+ const engine = body.engine.trim()
183
+ if (engine !== 'native' && !isAcpEngine(engine)) return fail(400, 'Неизвестный движок')
184
+ if (engine !== chat.engine) {
185
+ if (isCompacting(chat.id) || isChatRunning(hub, chat.id)) return fail(409, 'Чат занят')
186
+ if (engine !== 'native') {
187
+ if (!providerEnabled(getProvider(db, engine))) return fail(400, 'Провайдер выключен')
188
+ const spec = acpAgent(engine)
189
+ if (!spec || !resolveAcpCommand(config, spec, acpOverride(db))) return fail(400, 'ACP-агент не найден')
190
+ patch.model = spec.id
191
+ } else if (!('model' in body) && !chat.model.includes('/')) {
192
+ patch.model = defaultModelId(db, config)
193
+ }
194
+ patch.engine = engine
195
+ }
196
+ }
197
+ if (
198
+ patch.title === undefined &&
199
+ patch.model === undefined &&
200
+ patch.archived === undefined &&
201
+ patch.engine === undefined &&
202
+ !('reasoning' in patch)
203
+ ) {
204
+ return fail(400, 'Нужен title, model, archived, reasoning или engine')
205
+ }
206
+ const updated = updateChat(db, chat.id, patch)
207
+ if (updated && isAcpEngine(chat.engine) && !isAcpEngine(updated.engine)) stopAcpSession(chat.id)
208
+ if (!updated) return fail(404, 'Чат не найден')
209
+ hub.upsertChat(updated.id, {
210
+ title: updated.title,
211
+ workspaceId: updated.workspace_id,
212
+ model: updated.model,
213
+ engine: updated.engine,
214
+ updatedAt: updated.updated_at,
215
+ archivedAt: updated.archived_at,
216
+ reasoning: updated.reasoning,
217
+ })
218
+ return Response.json(updated)
219
+ }
220
+
221
+ async function postAcpConfig(
222
+ req: Request,
223
+ db: Database,
224
+ config: Config,
225
+ hub: Hub,
226
+ shell: Shell | null,
227
+ chatId: string,
228
+ ): Promise<Response> {
229
+ const body = await readJson(req)
230
+ if (!isRecord(body)) return fail(400, 'Нужен объект')
231
+ const chat = getChat(db, chatId)
232
+ if (!chat) return fail(404, 'Чат не найден')
233
+ if (!isAcpEngine(chat.engine)) return fail(400, 'Это не ACP-чат')
234
+ const workspace = getWorkspace(db, chat.workspace_id)
235
+ if (!workspace) return fail(404, 'Папка не найдена')
236
+ const configId = typeof body.configId === 'string' ? body.configId.trim() : ''
237
+ if (configId !== '' && (isCompacting(chat.id) || isChatRunning(hub, chat.id))) return fail(409, 'Чат занят')
238
+ const session = getAcpSession({ db, config, root: workspace.root_path, chat, shell })
239
+ try {
240
+ const options =
241
+ configId === ''
242
+ ? await session.loadConfig(AbortSignal.timeout(120_000))
243
+ : await session.setConfig(AbortSignal.timeout(120_000), configId, configValue(body.value))
244
+ return Response.json({ options })
245
+ } catch (error) {
246
+ const message = error instanceof Error ? error.message : String(error)
247
+ return fail(400, message)
248
+ }
249
+ }
250
+
251
+ function configValue(value: unknown): string | boolean {
252
+ if (typeof value === 'string' || typeof value === 'boolean') return value
253
+ throw new Error('Нужно значение')
254
+ }
255
+
256
+ function isChatRunning(hub: Hub, chatId: string): boolean {
257
+ return Boolean(activeRun(chatId)) || hub.snapshot(chatId, []).status === 'running'
258
+ }
259
+
260
+ async function deleteChatRoute(deps: ChatDeps, chatId: string): Promise<Response> {
261
+ const { db, hub, jobs } = deps
262
+ const chat = getChat(db, chatId)
263
+ if (!chat) return fail(404, 'Чат не найден')
264
+ if (isClosing(chat.id) || isChatRunning(hub, chat.id) || isCompacting(chat.id)) {
265
+ return fail(409, 'Чат занят')
266
+ }
267
+ markClosing(chat.id)
268
+ try {
269
+ stopAcpSession(chat.id)
270
+ await jobs.killChat(chat.id)
271
+ if (isChatRunning(hub, chat.id) || isCompacting(chat.id)) return fail(409, 'Чат занят')
272
+ deleteChat(db, chat.id)
273
+ hub.chatDeleted(chat.id)
274
+ return new Response(null, { status: 204 })
275
+ } finally {
276
+ unmarkClosing(chat.id)
277
+ }
278
+ }
279
+
280
+ async function postCreateChat(
281
+ req: Request,
282
+ db: Database,
283
+ config: Config,
284
+ hub: Hub,
285
+ workspace: WorkspaceRow,
286
+ ): Promise<Response> {
287
+ const body = await readJson(req)
288
+ const engine =
289
+ isRecord(body) && typeof body.engine === 'string' && body.engine.trim()
290
+ ? body.engine.trim()
291
+ : 'native'
292
+ if (engine !== 'native' && !isAcpEngine(engine)) return fail(400, 'Неизвестный движок')
293
+ if (engine !== 'native') {
294
+ const spec = acpAgent(engine)
295
+ if (!spec || !resolveAcpCommand(config, spec, acpOverride(db))) return fail(400, 'ACP-агент не найден')
296
+ }
297
+ const model =
298
+ isRecord(body) && typeof body.model === 'string' && body.model.trim()
299
+ ? body.model.trim()
300
+ : engine === 'native'
301
+ ? defaultModelId(db, config)
302
+ : acpAgent(engine)!.id
303
+ const chat = createChat(db, { workspaceId: workspace.id, title: 'Chat', model, engine })
304
+ hub.upsertChat(chat.id, {
305
+ title: chat.title,
306
+ workspaceId: chat.workspace_id,
307
+ model: chat.model,
308
+ engine: chat.engine,
309
+ updatedAt: chat.updated_at,
310
+ reasoning: chat.reasoning,
311
+ status: 'idle',
312
+ })
313
+ return Response.json(chat, { status: 201 })
314
+ }
315
+
316
+ async function postTruncate(req: Request, db: Database, hub: Hub, chatId: string): Promise<Response> {
317
+ // The body is read before any state check: a slow upload must not pass a guard
318
+ // that a concurrent run or compact starts while it is still pending.
319
+ const body = await readJson(req)
320
+ if (!isRecord(body) || !Number.isInteger(body.seq)) return fail(400, 'Нужен seq')
321
+ const chat = getChat(db, chatId)
322
+ if (!chat) return fail(404, 'Чат не найден')
323
+ const workspace = getWorkspace(db, chat.workspace_id)
324
+ if (!workspace) return fail(404, 'Папка не найдена')
325
+ if (isClosing(chat.id) || isCompacting(chat.id)) return fail(409, 'Идёт сжатие')
326
+ if (isChatRunning(hub, chat.id)) return fail(409, 'Чат занят')
327
+ let result: TruncateResult
328
+ try {
329
+ result = truncateChat(db, workspace.root_path, chat.id, body.seq as number, {
330
+ revertFiles: body.revertFiles === true,
331
+ force: body.force === true,
332
+ })
333
+ } catch (error) {
334
+ return fail(400, error instanceof Error ? error.message : String(error))
335
+ }
336
+ if (result.status === 'not_native') return fail(400, 'Обрезка есть только у своего цикла')
337
+ if (result.status === 'conflict') {
338
+ return Response.json(
339
+ {
340
+ status: result.status,
341
+ conflicts: result.conflicts.map((conflict) => ({
342
+ path: conflict.path,
343
+ before: blobText(db, conflict.beforeHash),
344
+ agent: blobText(db, conflict.agentHash),
345
+ disk: conflict.diskHash === null ? null : diskText(workspace.root_path, conflict.path),
346
+ })),
347
+ },
348
+ { status: 409 },
349
+ )
350
+ }
351
+ hub.resync(chat.id, listMessages(db, chat.id).map(messageView))
352
+ for (const path of result.revertedPaths) {
353
+ hub.fileChanged(workspace.id, path, hashOnDisk(join(workspace.root_path, path)))
354
+ }
355
+ return Response.json(result)
356
+ }
357
+
358
+ async function postFork(req: Request, db: Database, hub: Hub, chatId: string): Promise<Response> {
359
+ const body = await readJson(req)
360
+ if (!isRecord(body) || !Number.isInteger(body.seq)) return fail(400, 'Нужен seq')
361
+ const chat = getChat(db, chatId)
362
+ if (!chat) return fail(404, 'Чат не найден')
363
+ if (isClosing(chat.id) || isCompacting(chat.id)) return fail(409, 'Идёт сжатие')
364
+ if (isChatRunning(hub, chat.id)) return fail(409, 'Чат занят')
365
+ let forked: ChatRow
366
+ try {
367
+ forked = forkChat(db, chat.id, body.seq as number)
368
+ } catch (error) {
369
+ return fail(400, error instanceof Error ? error.message : String(error))
370
+ }
371
+ hub.upsertChat(forked.id, {
372
+ title: forked.title,
373
+ workspaceId: forked.workspace_id,
374
+ model: forked.model,
375
+ engine: forked.engine,
376
+ updatedAt: forked.updated_at,
377
+ reasoning: forked.reasoning,
378
+ status: 'idle',
379
+ })
380
+ return Response.json(forked, { status: 201 })
381
+ }
382
+
383
+ async function postCompact(req: Request, deps: ChatDeps, chatId: string): Promise<Response> {
384
+ const { db, config, hub, stream } = deps
385
+ const chat = getChat(db, chatId)
386
+ if (!chat) return fail(404, 'Чат не найден')
387
+ if (isClosing(chat.id) || isChatRunning(hub, chat.id) || isCompacting(chat.id)) {
388
+ return fail(409, 'Чат занят')
389
+ }
390
+ const result = await compactChat({ db, config, chatId: chat.id, stream, signal: req.signal })
391
+ if (result.status === 'not_native') return fail(400, 'Сжатие есть только у своего цикла')
392
+ if (result.status === 'short') return fail(400, 'История короче хвоста: сжимать нечего')
393
+ if (result.status === 'empty') return fail(400, 'Нечего сжимать')
394
+ if (result.status === 'error') return fail(502, result.error)
395
+ hub.resync(chat.id, listMessages(db, chat.id).map(messageView))
396
+ // A job that finished while compact held the chat would otherwise stay pending forever.
397
+ jobCompletionRun(deps, chat.id)
398
+ return Response.json(
399
+ { message: messageView(result.message), summarized: result.summarized, kept: result.kept },
400
+ { status: 201 },
401
+ )
402
+ }
403
+
404
+ async function postMessage(req: Request, deps: ChatDeps, chatId: string): Promise<Response> {
405
+ const { db, config, hub, shell, stream, jobs } = deps
406
+ const body = await readJson(req)
407
+ if (!isRecord(body) || typeof body.text !== 'string' || !body.text.trim()) return fail(400, 'Нужен текст')
408
+ const chat = getChat(db, chatId)
409
+ if (!chat) return fail(404, 'Чат не найден')
410
+ const workspace = getWorkspace(db, chat.workspace_id)
411
+ if (!workspace) return fail(404, 'Папка не найдена')
412
+ if (isClosing(chat.id)) return fail(409, 'Чат занят')
413
+ if (isCompacting(chat.id)) return fail(409, 'Идёт сжатие')
414
+ if (!chatProviderEnabled(db, chat)) return fail(400, 'Провайдер выключен')
415
+ const factory = runFactory({ db, config, hub, shell, stream, jobs }, chat, workspace)
416
+ const result = postChatMessage(chat.id, body.text, body.interrupt === true, factory)
417
+ return Response.json(result, { status: 202 })
418
+ }
419
+
420
+ /** Starts a follow-up run when a background job finished while the chat was idle. */
421
+ export function jobCompletionRun(deps: ChatDeps, chatId: string): void {
422
+ if (activeRun(chatId) !== undefined || isCompacting(chatId) || isClosing(chatId)) return
423
+ const chat = getChat(deps.db, chatId)
424
+ if (!chat || isAcpEngine(chat.engine)) return
425
+ if (!deps.jobs.pending(chatId)) return
426
+ if (!chatProviderEnabled(deps.db, chat)) return
427
+ // A later exit must not hide an error or contradict the max_steps reminder.
428
+ // Abort leaves the chat idle, so that follow-up still starts.
429
+ if (deps.hub.snapshot(chatId, []).status === 'error') return
430
+ if (endedOnMaxSteps(deps.db, chatId)) return
431
+ const workspace = getWorkspace(deps.db, chat.workspace_id)
432
+ if (!workspace) return
433
+ startRun(chatId, '', runFactory(deps, chat, workspace))
434
+ }
435
+
436
+ function runFactory(deps: ChatDeps, chat: ChatRow, workspace: WorkspaceRow): RunFactory {
437
+ const options = deps
438
+ if (isAcpEngine(chat.engine)) {
439
+ return (run, text) =>
440
+ createAcpRun({
441
+ db: options.db,
442
+ config: options.config,
443
+ root: workspace.root_path,
444
+ chat,
445
+ workspaceId: workspace.id,
446
+ text,
447
+ runId: run.runId,
448
+ signal: run.abort.signal,
449
+ shell: options.shell,
450
+ onDelta: (delta) => options.hub.pushDelta(chat.id, delta),
451
+ onToolStarted: (callId, name) => options.hub.toolStarted(chat.id, callId, name),
452
+ onToolRunning: (callId, args) => options.hub.toolRunning(chat.id, callId, args),
453
+ onToolOutput: (callId, chunk) => options.hub.pushToolOutput(chat.id, callId, chunk),
454
+ beforeSave: () => options.hub.flush(chat.id),
455
+ onAppended: (row) => options.hub.appended(chat.id, messageView(row)),
456
+ onTitle: (title) => options.hub.setTitle(chat.id, title),
457
+ onFileChanged: (path, hash) => options.hub.fileChanged(workspace.id, path, hash),
458
+ onRunStart: (runId, meta) => options.hub.setRun(chat.id, runId, 'running', meta),
459
+ onRunFinish: (_runId, status) => options.hub.setRun(chat.id, null, status),
460
+ onQueueChanged: (_runId, queue) => options.hub.setQueue(chat.id, queue),
461
+ onQuestion: (question) => {
462
+ options.hub.flush(chat.id)
463
+ options.hub.question(chat.id, question)
464
+ },
465
+ })
466
+ }
467
+ return (run, text) =>
468
+ createTurnRun({
469
+ db: options.db,
470
+ config: options.config,
471
+ root: workspace.root_path,
472
+ chat,
473
+ workspaceId: workspace.id,
474
+ text,
475
+ runId: run.runId,
476
+ signal: run.abort.signal,
477
+ shell: options.shell,
478
+ stream: options.stream,
479
+ jobs: options.jobs,
480
+ queue: run.queue,
481
+ queueWait: run.wake,
482
+ onRetry: (attempt) => options.hub.retry(chat.id, attempt),
483
+ onDelta: (delta) => options.hub.pushDelta(chat.id, delta),
484
+ onToolStarted: (callId, name) => options.hub.toolStarted(chat.id, callId, name),
485
+ onToolRunning: (callId, args) => options.hub.toolRunning(chat.id, callId, args),
486
+ onToolOutput: (callId, chunk) => options.hub.pushToolOutput(chat.id, callId, chunk),
487
+ beforeSave: () => options.hub.flush(chat.id),
488
+ onAppended: (row) => options.hub.appended(chat.id, messageView(row)),
489
+ onTitle: (title) => options.hub.setTitle(chat.id, title),
490
+ onFileChanged: (path, hash) => options.hub.fileChanged(workspace.id, path, hash),
491
+ onRunStart: (runId, meta) => options.hub.setRun(chat.id, runId, 'running', meta),
492
+ onRunFinish: (_runId, status) => {
493
+ // A pending completion becomes a follow-up run in the same tick: the chat must
494
+ // not blink to idle between the two runs. An error or the step cap stays as it
495
+ // is: another request would hide the error or contradict the max_steps reminder.
496
+ // Abort still starts the follow-up; that run has no user text on purpose.
497
+ const pending = options.jobs.pending(chat.id)
498
+ if (!pending || status === 'error' || endedOnMaxSteps(options.db, chat.id)) {
499
+ options.hub.setRun(chat.id, null, status)
500
+ return
501
+ }
502
+ jobCompletionRun(options, chat.id)
503
+ if (activeRun(chat.id) === undefined) options.hub.setRun(chat.id, null, status)
504
+ },
505
+ onQueueChanged: (_runId, queue) => options.hub.setQueue(chat.id, queue),
506
+ onCompacted: () => options.hub.resync(chat.id, listMessages(options.db, chat.id).map(messageView)),
507
+ })
508
+ }
509
+
510
+ function postAbort(db: Database, chatId: string): Response {
511
+ if (!getChat(db, chatId)) return fail(404, 'Чат не найден')
512
+ if (!abortRun(chatId)) return fail(409, 'Чат свободен')
513
+ return new Response(null, { status: 204 })
514
+ }
515
+
516
+ async function postAnswer(req: Request, db: Database, chatId: string): Promise<Response> {
517
+ const body = await readJson(req)
518
+ if (
519
+ !isRecord(body) ||
520
+ typeof body.questionId !== 'string' ||
521
+ !body.questionId ||
522
+ typeof body.answer !== 'object' ||
523
+ body.answer === null
524
+ ) {
525
+ return fail(400, 'Нужен questionId и answer')
526
+ }
527
+ if (!getChat(db, chatId)) return fail(404, 'Чат не найден')
528
+ const result = answerAcpQuestion(chatId, body.questionId, body.answer as AcpAnswer)
529
+ if (result.status === 'no_session' || result.status === 'no_question') {
530
+ return fail(404, 'Вопрос не найден')
531
+ }
532
+ if (result.status === 'invalid') return fail(400, result.error ?? 'Неверный ответ')
533
+ return Response.json({ status: 'answered' })
534
+ }
535
+
536
+ async function postRevert(
537
+ req: Request,
538
+ db: Database,
539
+ hub: Hub,
540
+ chatId: string,
541
+ revisionId: string,
542
+ ): Promise<Response> {
543
+ const body = await readJson(req)
544
+ const force = isRecord(body) && body.force === true
545
+ const chat = getChat(db, chatId)
546
+ if (!chat) return fail(404, 'Чат не найден')
547
+ const workspace = getWorkspace(db, chat.workspace_id)
548
+ if (!workspace) return fail(404, 'Папка не найдена')
549
+ if (isCompacting(chat.id)) return fail(409, 'Идёт сжатие')
550
+ if (isChatRunning(hub, chat.id)) return fail(409, 'Чат занят')
551
+ let result: ReturnType<typeof revertRevision>
552
+ try {
553
+ result = revertRevision(db, workspace.root_path, chat.id, revisionId, { force })
554
+ } catch (error) {
555
+ return fail(400, error instanceof Error ? error.message : String(error))
556
+ }
557
+ if (result.status === 'not_found') return fail(404, 'Ревизия не найдена')
558
+ if (result.status === 'conflict') {
559
+ return Response.json(
560
+ {
561
+ status: result.status,
562
+ path: result.path,
563
+ before: blobText(db, result.beforeHash),
564
+ agent: blobText(db, result.agentHash),
565
+ disk: result.diskHash === null ? null : diskText(workspace.root_path, result.path),
566
+ },
567
+ { status: 409 },
568
+ )
569
+ }
570
+ hub.resync(chat.id, listMessages(db, chat.id).map(messageView))
571
+ hub.fileChanged(workspace.id, result.path, hashOnDisk(join(workspace.root_path, result.path)))
572
+ return Response.json(result)
573
+ }
574
+
575
+ function getBefore(db: Database, chatId: string, revisionId: string): Response {
576
+ if (!getChat(db, chatId)) return fail(404, 'Чат не найден')
577
+ const revision = getRevision(db, chatId, revisionId)
578
+ if (!revision) return fail(404, 'Ревизия не найдена')
579
+ if (revision.before_hash === null) {
580
+ return Response.json({ path: revision.path, before: null })
581
+ }
582
+ const bytes = getBlob(db, revision.before_hash)
583
+ if (bytes === null) return fail(500, 'Блоб ревизии не найден')
584
+ return Response.json({ path: revision.path, before: new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes) })
585
+ }
586
+
587
+ function endedOnMaxSteps(db: Database, chatId: string): boolean {
588
+ const last = listMessages(db, chatId).at(-1)
589
+ if (!last || last.role !== 'notice') return false
590
+ try {
591
+ const parsed = JSON.parse(last.content_json) as { kind?: unknown }
592
+ return parsed.kind === 'max_steps'
593
+ } catch {
594
+ return false
595
+ }
596
+ }
597
+
598
+ function chatProviderEnabled(db: Database, chat: ChatRow): boolean {
599
+ if (isAcpEngine(chat.engine)) return providerEnabled(getProvider(db, chat.engine))
600
+ const slash = chat.model.indexOf('/')
601
+ if (slash <= 0) return true
602
+ return providerEnabled(getProvider(db, chat.model.slice(0, slash)))
603
+ }
604
+
605
+ function postReview(db: Database, chatId: string, revisionId: string): Response {
606
+ if (!getChat(db, chatId)) return fail(404, 'Чат не найден')
607
+ const revision = getRevision(db, chatId, revisionId)
608
+ if (!revision) return fail(404, 'Ревизия не найдена')
609
+ markReviewed(db, chatId, revision.path)
610
+ return new Response(null, { status: 204 })
611
+ }
612
+
613
+ function blobText(db: Database, hash: string | null): string | null {
614
+ if (!hash) return null
615
+ const bytes = getBlob(db, hash)
616
+ return bytes ? new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes) : null
617
+ }
618
+
619
+ function diskText(root: string, path: string): string | null {
620
+ try {
621
+ const abs = join(root, path)
622
+ if (statSync(abs).size > BLOB_LIMIT) return null
623
+ return new TextDecoder('utf-8', { ignoreBOM: true }).decode(readFileSync(abs))
624
+ } catch {
625
+ return null
626
+ }
627
+ }
@@ -0,0 +1,14 @@
1
+ const closing = new Set<string>()
2
+
3
+ /** A chat delete is in progress: new runs must not start while its jobs are being killed. */
4
+ export function markClosing(chatId: string): void {
5
+ closing.add(chatId)
6
+ }
7
+
8
+ export function unmarkClosing(chatId: string): void {
9
+ closing.delete(chatId)
10
+ }
11
+
12
+ export function isClosing(chatId: string): boolean {
13
+ return closing.has(chatId)
14
+ }