@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,425 @@
1
+ import { rmSync } from 'node:fs'
2
+ import type { Database } from 'bun:sqlite'
3
+ import type { AssistantMessage, ModelMessage, ToolMessage, UserMessage } from '../shared/types'
4
+ import {
5
+ getBlob,
6
+ hashOnDisk,
7
+ lastRevision,
8
+ revisionsForMessages,
9
+ writeAtomic,
10
+ type RevisionRow,
11
+ } from './changes'
12
+ import {
13
+ createChat,
14
+ getChat,
15
+ listMessages,
16
+ type ChatRow,
17
+ type MessageRow,
18
+ } from './db'
19
+ import { resolveInRoot } from './tools/jail'
20
+
21
+ export const INTERRUPTED = 'Interrupted'
22
+ export const ABORTED = 'Aborted by user'
23
+
24
+ type Segment = { calls: string[]; tools: string[] }
25
+
26
+ export function repair(
27
+ db: Database,
28
+ chatId: string,
29
+ reason: string,
30
+ notify?: (row: MessageRow) => void,
31
+ ): void {
32
+ const gaps = missingToolGaps(listMessages(db, chatId))
33
+ if (gaps.length === 0) return
34
+ // Later gaps go in first: shifting their seq must not move an earlier anchor.
35
+ const written = db.transaction((): MessageRow[] => {
36
+ const created: MessageRow[] = []
37
+ for (const gap of gaps.slice().reverse()) {
38
+ const rows: MessageRow[] = []
39
+ let after = gap.afterSeq
40
+ for (const id of gap.ids) {
41
+ const row = insertToolAfter(db, chatId, after, {
42
+ toolCallId: id,
43
+ text: reason,
44
+ isError: true,
45
+ })
46
+ rows.push(row)
47
+ after = row.seq
48
+ }
49
+ created.unshift(...rows)
50
+ }
51
+ return created
52
+ })()
53
+ for (const row of written) notify?.(row)
54
+ }
55
+
56
+ export function historyViolation(rows: MessageRow[]): string | null {
57
+ const { segments, errors } = partition(visibleRows(rows))
58
+ for (const segment of segments) {
59
+ const expected = count(segment.calls)
60
+ const actual = count(segment.tools)
61
+ const ids = new Set([...expected.keys(), ...actual.keys()])
62
+ for (const id of ids) {
63
+ const want = expected.get(id) ?? 0
64
+ const got = actual.get(id) ?? 0
65
+ if (want !== got) errors.push(`Вызов ${id}: в истории ${got} строк tool, ожидается ${want}`)
66
+ }
67
+ }
68
+ if (errors.length === 0) return null
69
+ return errors.join('\n')
70
+ }
71
+
72
+ /** Rows from the last compaction summary on: the prefix stays in the log but is not sent to the model. */
73
+ export function visibleRows(rows: MessageRow[]): MessageRow[] {
74
+ let start = 0
75
+ for (let index = 0; index < rows.length; index++) {
76
+ if (isCompactionRow(rows[index]!)) start = index
77
+ }
78
+ return start === 0 ? rows : rows.slice(start)
79
+ }
80
+
81
+ export function isCompactionRow(row: MessageRow): boolean {
82
+ if (row.role !== 'user') return false
83
+ const content = parseJson(row.content_json)
84
+ return isRecord(content) && content.compacted === true && typeof content.text === 'string'
85
+ }
86
+
87
+ export function modelMessages(rows: MessageRow[]): ModelMessage[] {
88
+ const messages: ModelMessage[] = []
89
+ for (const row of visibleRows(rows)) {
90
+ if (row.role === 'notice') {
91
+ // A notice is written for the reader. When the same fact also matters to the model —
92
+ // a step cap, a truncated answer, a compaction — it is sent as a system reminder so
93
+ // the model can act on it instead of discovering it from silence.
94
+ const text = modelNoticeText(row)
95
+ if (text !== null) messages.push({ role: 'user', content: { text } })
96
+ continue
97
+ }
98
+ const content: unknown = JSON.parse(row.content_json)
99
+ if (row.role === 'user') messages.push({ role: 'user', content: content as UserMessage['content'] })
100
+ else if (row.role === 'assistant') {
101
+ messages.push({ role: 'assistant', content: content as AssistantMessage['content'] })
102
+ } else if (row.role === 'tool') messages.push({ role: 'tool', content: content as ToolMessage['content'] })
103
+ }
104
+ return messages
105
+ }
106
+
107
+ /** Notice kinds the model must see, with the wording it gets. */
108
+ export function modelNoticeText(row: MessageRow): string | null {
109
+ const content = parseJson(row.content_json)
110
+ if (!isRecord(content) || typeof content.text !== 'string') return null
111
+ const details = parseJson(row.details_json ?? 'null')
112
+ if (!isRecord(details) || details.intoContext !== true) return null
113
+ return `<system_reminder>\n${content.text}\n</system_reminder>`
114
+ }
115
+
116
+ export type TruncateResult =
117
+ | { status: 'truncated'; removedMessages: number; revertedPaths: string[] }
118
+ | {
119
+ status: 'conflict'
120
+ conflicts: Array<{
121
+ path: string
122
+ beforeHash: string | null
123
+ agentHash: string
124
+ diskHash: string | null
125
+ }>
126
+ }
127
+ | { status: 'not_native' }
128
+
129
+ /** New chat in the same folder with a copy of `seq < N`; revisions are not copied. */
130
+ export function forkChat(db: Database, chatId: string, seq: number): ChatRow {
131
+ return db
132
+ .transaction((): ChatRow => {
133
+ const source = nativeChat(db, chatId, 'fork')
134
+ checkSeq(db, chatId, seq)
135
+ const forked = createChat(db, {
136
+ workspaceId: source.workspace_id,
137
+ title: `${source.title} (форк)`,
138
+ model: source.model,
139
+ reasoning: source.reasoning,
140
+ parentChatId: source.id,
141
+ forkedFromSeq: seq,
142
+ })
143
+ for (const row of listMessages(db, chatId)) {
144
+ if (row.seq >= seq) continue
145
+ db.run(
146
+ `INSERT INTO messages (id, chat_id, seq, role, content_json, details_json, created_at)
147
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
148
+ [
149
+ crypto.randomUUID(),
150
+ forked.id,
151
+ row.seq,
152
+ row.role,
153
+ row.content_json,
154
+ row.details_json,
155
+ row.created_at,
156
+ ],
157
+ )
158
+ }
159
+ repair(db, forked.id, INTERRUPTED)
160
+ return getChat(db, forked.id) ?? forked
161
+ })
162
+ .immediate()
163
+ }
164
+
165
+ export function truncateChat(
166
+ db: Database,
167
+ root: string,
168
+ chatId: string,
169
+ seq: number,
170
+ options: { revertFiles: boolean; force?: boolean },
171
+ ): TruncateResult {
172
+ const chat = getChat(db, chatId)
173
+ if (!chat) throw new Error(`Chat ${chatId} not found`)
174
+ if (chat.engine !== 'native') return { status: 'not_native' }
175
+ checkSeq(db, chatId, seq)
176
+
177
+ const removed = listMessages(db, chatId).filter((row) => row.seq >= seq)
178
+ if (!options.revertFiles) {
179
+ const removedMessages = db.transaction(() => deleteMessages(db, chatId, seq))()
180
+ return { status: 'truncated', removedMessages, revertedPaths: [] }
181
+ }
182
+
183
+ const tail = revisionsForMessages(
184
+ db,
185
+ chatId,
186
+ removed.map((row) => row.id),
187
+ )
188
+ const earliest = new Map<string, RevisionRow>()
189
+ for (const revision of tail) {
190
+ if (!earliest.has(revision.path)) earliest.set(revision.path, revision)
191
+ }
192
+
193
+ const writes: Array<{ abs: string; beforeHash: string | null }> = []
194
+ const conflicts: Array<{
195
+ path: string
196
+ beforeHash: string | null
197
+ agentHash: string
198
+ diskHash: string | null
199
+ }> = []
200
+ for (const [path, revision] of earliest) {
201
+ const agentHash = lastRevision(db, chatId, path)?.after_hash ?? revision.after_hash
202
+ const abs = resolveInRoot(root, path).abs
203
+ const diskHash = hashOnDisk(abs)
204
+ if (diskHash !== agentHash) {
205
+ conflicts.push({ path, beforeHash: revision.before_hash, agentHash, diskHash })
206
+ }
207
+ writes.push({ abs, beforeHash: revision.before_hash })
208
+ }
209
+ if (conflicts.length > 0 && !options.force) return { status: 'conflict', conflicts }
210
+
211
+ for (const write of writes) {
212
+ if (write.beforeHash === null) {
213
+ rmSync(write.abs, { force: true })
214
+ continue
215
+ }
216
+ const bytes = getBlob(db, write.beforeHash)
217
+ if (!bytes) throw new Error(`blob ${write.beforeHash} is missing`)
218
+ writeAtomic(write.abs, bytes)
219
+ }
220
+
221
+ const removedMessages = db.transaction(() => {
222
+ // A previous truncate without a file rollback left later revisions of the same
223
+ // path with message_id NULL. They are not in `tail`, but they are the same
224
+ // rollback as the earliest revision we are undoing, so they go with it.
225
+ for (const revision of earliest.values()) {
226
+ db.run(
227
+ `DELETE FROM file_revisions
228
+ WHERE chat_id = ? AND path = ? AND rowid >= (SELECT rowid FROM file_revisions WHERE id = ?)`,
229
+ [chatId, revision.path, revision.id],
230
+ )
231
+ }
232
+ return deleteMessages(db, chatId, seq)
233
+ })()
234
+
235
+ return { status: 'truncated', removedMessages, revertedPaths: [...earliest.keys()] }
236
+ }
237
+
238
+ function nativeChat(db: Database, chatId: string, action: string): ChatRow {
239
+ const chat = getChat(db, chatId)
240
+ if (!chat) throw new Error(`Chat ${chatId} not found`)
241
+ if (chat.engine !== 'native') throw new Error(`${action} is available only for native chats`)
242
+ return chat
243
+ }
244
+
245
+ function checkSeq(db: Database, chatId: string, seq: number): void {
246
+ const last = maxSeq(db, chatId)
247
+ if (!Number.isInteger(seq) || seq < 1 || seq > last) {
248
+ throw new Error(`seq ${seq} is outside 1..${last}`)
249
+ }
250
+ }
251
+
252
+ function maxSeq(db: Database, chatId: string): number {
253
+ const row = db
254
+ .query<{ seq: number | null }, [string]>(
255
+ 'SELECT MAX(seq) AS seq FROM messages WHERE chat_id = ?',
256
+ )
257
+ .get(chatId)
258
+ return row?.seq ?? 0
259
+ }
260
+
261
+ function deleteMessages(db: Database, chatId: string, seq: number): number {
262
+ return db.run('DELETE FROM messages WHERE chat_id = ? AND seq >= ?', [chatId, seq]).changes
263
+ }
264
+
265
+ type ToolGap = { afterSeq: number; ids: string[] }
266
+
267
+ /**
268
+ * Tool rows that a dangling assistant still needs, anchored at the last row of that
269
+ * segment. Appending them at the end of the chat would land after a later user or
270
+ * context notice and fail the history check forever.
271
+ */
272
+ function missingToolGaps(rows: MessageRow[]): ToolGap[] {
273
+ const gaps: ToolGap[] = []
274
+ let open: ToolGap | null = null
275
+
276
+ const close = (): void => {
277
+ if (open && open.ids.length > 0) gaps.push(open)
278
+ open = null
279
+ }
280
+
281
+ for (const row of rows) {
282
+ if (row.role === 'notice') {
283
+ if (modelNoticeText(row) !== null) close()
284
+ continue
285
+ }
286
+ if (row.role === 'user') {
287
+ close()
288
+ continue
289
+ }
290
+ if (row.role === 'assistant') {
291
+ close()
292
+ const calls = assistantCallIds(parseJson(row.content_json))
293
+ open = calls && calls.length > 0 ? { afterSeq: row.seq, ids: [...calls] } : null
294
+ continue
295
+ }
296
+ if (row.role !== 'tool' || !open) continue
297
+ const id = toolCallId(parseJson(row.content_json))
298
+ if (!id) continue
299
+ const index = open.ids.indexOf(id)
300
+ if (index >= 0) open.ids.splice(index, 1)
301
+ open.afterSeq = row.seq
302
+ }
303
+ close()
304
+ return gaps
305
+ }
306
+
307
+ /** Inserts one tool row at `afterSeq + 1`, shifting every later seq up by one. */
308
+ function insertToolAfter(
309
+ db: Database,
310
+ chatId: string,
311
+ afterSeq: number,
312
+ content: { toolCallId: string; text: string; isError: boolean },
313
+ ): MessageRow {
314
+ const contentJson = JSON.stringify(content)
315
+ const now = Date.now()
316
+ const shifting = db
317
+ .query<{ id: string; seq: number }, [string, number]>(
318
+ 'SELECT id, seq FROM messages WHERE chat_id = ? AND seq > ? ORDER BY seq DESC',
319
+ )
320
+ .all(chatId, afterSeq)
321
+ for (const row of shifting) {
322
+ db.run('UPDATE messages SET seq = ? WHERE id = ?', [row.seq + 1, row.id])
323
+ }
324
+ const seq = afterSeq + 1
325
+ const id = crypto.randomUUID()
326
+ db.run(
327
+ `INSERT INTO messages (id, chat_id, seq, role, content_json, details_json, created_at)
328
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,
329
+ [id, chatId, seq, 'tool', contentJson, null, now],
330
+ )
331
+ db.run('UPDATE chats SET updated_at = ? WHERE id = ?', [now, chatId])
332
+ return {
333
+ id,
334
+ chat_id: chatId,
335
+ seq,
336
+ role: 'tool',
337
+ content_json: contentJson,
338
+ details_json: null,
339
+ created_at: now,
340
+ }
341
+ }
342
+
343
+ function partition(rows: MessageRow[]): { segments: Segment[]; errors: string[] } {
344
+ const segments: Segment[] = []
345
+ const errors: string[] = []
346
+ let current: Segment | null = null
347
+
348
+ for (const row of rows) {
349
+ if (row.role === 'notice') {
350
+ if (modelNoticeText(row) !== null) current = null
351
+ continue
352
+ }
353
+ if (row.role === 'user') {
354
+ current = null
355
+ if (!isUserContent(parseJson(row.content_json))) errors.push(`Сообщение ${row.seq} не разбирается`)
356
+ continue
357
+ }
358
+ if (row.role === 'assistant') {
359
+ const calls = assistantCallIds(parseJson(row.content_json))
360
+ if (!calls) {
361
+ errors.push(`Сообщение ${row.seq} не разбирается`)
362
+ current = { calls: [], tools: [] }
363
+ } else {
364
+ current = { calls, tools: [] }
365
+ }
366
+ segments.push(current)
367
+ continue
368
+ }
369
+ if (row.role === 'tool') {
370
+ const id = toolCallId(parseJson(row.content_json))
371
+ if (!id) {
372
+ errors.push(`Сообщение ${row.seq} не разбирается`)
373
+ continue
374
+ }
375
+ if (!current) {
376
+ errors.push(`Строка tool ${id} без вызова в ближайшем предыдущем assistant`)
377
+ continue
378
+ }
379
+ current.tools.push(id)
380
+ continue
381
+ }
382
+ errors.push(`Сообщение ${row.seq} не разбирается`)
383
+ }
384
+
385
+ return { segments, errors }
386
+ }
387
+
388
+ function assistantCallIds(content: unknown): string[] | null {
389
+ if (!isRecord(content) || !Array.isArray(content.blocks)) return null
390
+ const ids: string[] = []
391
+ for (const block of content.blocks) {
392
+ if (!isRecord(block) || block.type !== 'tool_call') continue
393
+ if (typeof block.id !== 'string' || !block.id) return null
394
+ ids.push(block.id)
395
+ }
396
+ return ids
397
+ }
398
+
399
+ function toolCallId(content: unknown): string | null {
400
+ if (!isRecord(content) || typeof content.toolCallId !== 'string' || !content.toolCallId) return null
401
+ if (typeof content.text !== 'string' || typeof content.isError !== 'boolean') return null
402
+ return content.toolCallId
403
+ }
404
+
405
+ function isUserContent(content: unknown): boolean {
406
+ return isRecord(content) && typeof content.text === 'string'
407
+ }
408
+
409
+ function count(ids: string[]): Map<string, number> {
410
+ const totals = new Map<string, number>()
411
+ for (const id of ids) totals.set(id, (totals.get(id) ?? 0) + 1)
412
+ return totals
413
+ }
414
+
415
+ function parseJson(text: string): unknown {
416
+ try {
417
+ return JSON.parse(text)
418
+ } catch {
419
+ return undefined
420
+ }
421
+ }
422
+
423
+ function isRecord(value: unknown): value is Record<string, unknown> {
424
+ return typeof value === 'object' && value !== null
425
+ }
@@ -0,0 +1,63 @@
1
+ import type { Database } from 'bun:sqlite'
2
+ import { isAbsoluteFilePath } from '../../shared/links'
3
+ import { readImageFile, saveImageAttachments } from '../attachments'
4
+ import { getWorkspace } from '../db'
5
+ import { fail, guardFile } from './reply'
6
+
7
+ export function isAttachmentsRoute(parts: string[], method: string): boolean {
8
+ if (parts.length !== 2 || parts[0] !== 'api') return false
9
+ if (parts[1] === 'attachments') return method === 'POST'
10
+ return parts[1] === 'image' && method === 'GET'
11
+ }
12
+
13
+ export function attachmentsRoute(
14
+ req: Request,
15
+ url: URL,
16
+ db: Database,
17
+ dir?: string,
18
+ ): Promise<Response> | Response {
19
+ if (url.pathname === '/api/attachments') return postAttachments(req, dir)
20
+ return getImage(url, db)
21
+ }
22
+
23
+ async function postAttachments(req: Request, dir?: string): Promise<Response> {
24
+ let form: FormData
25
+ try {
26
+ form = await req.formData()
27
+ } catch {
28
+ return fail(400, 'Нужен multipart/form-data')
29
+ }
30
+ const files: File[] = []
31
+ form.forEach((value) => {
32
+ if (typeof value !== 'string') files.push(value)
33
+ })
34
+ if (files.length === 0) return fail(400, 'Нужен файл')
35
+ return guardFile(async () => {
36
+ const saved = await saveImageAttachments(files, dir)
37
+ return Response.json({ files: saved }, { status: 201 })
38
+ })
39
+ }
40
+
41
+ async function getImage(url: URL, db: Database): Promise<Response> {
42
+ const path = url.searchParams.get('path') ?? ''
43
+ const workspaceId = url.searchParams.get('workspaceId') ?? ''
44
+ if (path === '') return fail(400, 'Нужен путь к изображению')
45
+ const relative = !isAbsoluteFilePath(path)
46
+ if (relative && workspaceId === '') return fail(400, 'Нужен workspaceId')
47
+ let root: string | null = null
48
+ if (workspaceId !== '') {
49
+ const workspace = getWorkspace(db, workspaceId)
50
+ if (!workspace) return fail(404, 'Папка не найдена')
51
+ root = workspace.root_path
52
+ }
53
+ return guardFile(() => {
54
+ const image = readImageFile(path, root)
55
+ return new Response(Bun.file(image.abs), {
56
+ headers: {
57
+ 'Content-Type': image.mime,
58
+ 'Cache-Control': 'private, max-age=60',
59
+ 'X-Content-Type-Options': 'nosniff',
60
+ },
61
+ })
62
+ })
63
+ }
@@ -0,0 +1,108 @@
1
+ import { statSync } from 'node:fs'
2
+ import type { Database } from 'bun:sqlite'
3
+ import { stopAcpSession } from '../acp/session'
4
+ import { isCompacting } from '../compact'
5
+ import { deleteWorkspace, ensureWorkspace, getWorkspace, listWorkspaceChatIds, listWorkspaces, normalizeRoot } from '../db'
6
+ import { browseDirs } from '../files'
7
+ import type { Hub } from '../hub'
8
+ import type { JobRegistry } from '../jobs'
9
+ import { activeRun } from '../loop'
10
+ import { fail, guardFile, isRecord, readJson } from './reply'
11
+ import { isClosing, markClosing, unmarkClosing } from './closing'
12
+
13
+ export function isWorkspacesRoute(parts: string[], method: string): boolean {
14
+ if (parts[0] !== 'api' || parts[1] !== 'workspaces') return false
15
+ if (parts.length === 2) return method === 'GET' || method === 'POST'
16
+ return parts.length === 3 && method === 'DELETE'
17
+ }
18
+
19
+ export function isShowRoute(parts: string[], method: string): boolean {
20
+ return parts.length === 2 && parts[0] === 'api' && parts[1] === 'show' && method === 'POST'
21
+ }
22
+
23
+ export function isBrowseRoute(parts: string[], method: string): boolean {
24
+ return parts.length === 3 && parts[0] === 'api' && parts[1] === 'fs' && parts[2] === 'browse' && method === 'GET'
25
+ }
26
+
27
+ export function workspacesRoute(
28
+ req: Request,
29
+ db: Database,
30
+ hub: Hub,
31
+ jobs: JobRegistry,
32
+ id = '',
33
+ ): Promise<Response> | Response {
34
+ if (req.method === 'DELETE') return deleteWorkspaceRoute(db, hub, jobs, id)
35
+ if (req.method === 'GET') return Response.json(listWorkspaces(db))
36
+ return postWorkspace(req, db, hub)
37
+ }
38
+
39
+ async function deleteWorkspaceRoute(
40
+ db: Database,
41
+ hub: Hub,
42
+ jobs: JobRegistry,
43
+ id: string,
44
+ ): Promise<Response> {
45
+ if (!getWorkspace(db, id)) return fail(404, 'Папка не найдена')
46
+ const chatIds = listWorkspaceChatIds(db, id)
47
+ for (const chatId of chatIds) {
48
+ if (isClosing(chatId) || activeRun(chatId) || isCompacting(chatId) || hub.snapshot(chatId, []).status === 'running') {
49
+ return fail(409, 'Чат занят')
50
+ }
51
+ }
52
+ for (const chatId of chatIds) markClosing(chatId)
53
+ try {
54
+ for (const chatId of chatIds) {
55
+ stopAcpSession(chatId)
56
+ await jobs.killChat(chatId)
57
+ }
58
+ for (const chatId of chatIds) {
59
+ if (activeRun(chatId) || isCompacting(chatId) || hub.snapshot(chatId, []).status === 'running') {
60
+ return fail(409, 'Чат занят')
61
+ }
62
+ }
63
+ if (!deleteWorkspace(db, id)) return fail(404, 'Папка не найдена')
64
+ for (const chatId of chatIds) hub.chatDeleted(chatId)
65
+ hub.workspaceDeleted(id)
66
+ return new Response(null, { status: 204 })
67
+ } finally {
68
+ for (const chatId of chatIds) unmarkClosing(chatId)
69
+ }
70
+ }
71
+
72
+ export function browseRoute(url: URL): Promise<Response> {
73
+ return guardFile(() => Response.json(browseDirs(url.searchParams.get('path') ?? '')))
74
+ }
75
+
76
+ export type FolderShow = { workspaceId: string | null; seq: number }
77
+
78
+ export async function showWorkspace(
79
+ req: Request,
80
+ db: Database,
81
+ hub: Hub,
82
+ current: FolderShow | null,
83
+ ): Promise<{ response: Response; show: FolderShow }> {
84
+ const body = await readJson(req)
85
+ const raw = isRecord(body) && typeof body.workspaceId === 'string' ? body.workspaceId.trim() : ''
86
+ if (raw !== '' && !getWorkspace(db, raw)) {
87
+ return { response: fail(404, 'Папка не найдена'), show: current ?? { workspaceId: null, seq: 0 } }
88
+ }
89
+ const show: FolderShow = { workspaceId: raw === '' ? null : raw, seq: (current?.seq ?? 0) + 1 }
90
+ if (show.workspaceId !== null) hub.workspaceFocus(show.workspaceId)
91
+ return { response: Response.json(show), show }
92
+ }
93
+
94
+ async function postWorkspace(req: Request, db: Database, hub: Hub): Promise<Response> {
95
+ const body = await readJson(req)
96
+ const rootPath = isRecord(body) && typeof body.rootPath === 'string' ? body.rootPath.trim() : ''
97
+ if (rootPath === '') return fail(400, 'Нужен rootPath')
98
+ let isDir = false
99
+ try {
100
+ isDir = statSync(normalizeRoot(rootPath)).isDirectory()
101
+ } catch {
102
+ return fail(400, 'Папка не найдена')
103
+ }
104
+ if (!isDir) return fail(400, 'Это не папка')
105
+ const workspace = ensureWorkspace(db, rootPath)
106
+ hub.workspaceUpserted(workspace)
107
+ return Response.json(workspace)
108
+ }