@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
package/server/turn.ts ADDED
@@ -0,0 +1,663 @@
1
+ import { join } from 'node:path'
2
+ import type { Database } from 'bun:sqlite'
3
+ import type {
4
+ Block,
5
+ RunStatus,
6
+ StopReason,
7
+ StreamEvent,
8
+ StreamLLMInput,
9
+ TextBlock,
10
+ ToolCallBlock,
11
+ Usage,
12
+ } from '../shared/types'
13
+ import { recordRevisions, type RevisionRow } from './changes'
14
+ import { autoCompactIfNeeded, compactChat, isOverflowError } from './compact'
15
+ import { findGitBash, loadConfig, pointerHome, type Config } from './config'
16
+ import {
17
+ appendMessage,
18
+ ensureChat,
19
+ ensureWorkspace,
20
+ getChat,
21
+ listMessages,
22
+ openDatabase,
23
+ updateChatTitle,
24
+ type ChatRow,
25
+ type MessageRole,
26
+ type MessageRow,
27
+ } from './db'
28
+ import { historyViolation, INTERRUPTED, isCompactionRow, modelMessages, repair, visibleRows } from './history'
29
+ import type { JobCompletion, JobRegistry, QueueWake } from './jobs'
30
+ import { runLoop, type ExecuteTool, type RunHooks } from './loop'
31
+ import { systemPrompt } from './prompt'
32
+ import { streamForModel, defaultProviderId, providerById } from './providers/registry'
33
+ import { archiveDir } from './segments'
34
+ import { bashOutputDir, formatJobPreview } from './jobs'
35
+ import { executeTool, toolDefsFor, type Shell } from './tools'
36
+
37
+ type DoneEvent = Extract<StreamEvent, { type: 'done' }>
38
+
39
+ type StreamResult =
40
+ | { kind: 'done'; event: DoneEvent }
41
+ | { kind: 'abort'; text: string }
42
+ | { kind: 'error'; text: string; message: string }
43
+
44
+ type Delta = { text?: string; thinking?: string }
45
+
46
+ export type TurnOutcome = {
47
+ chatId: string
48
+ called: boolean
49
+ stopReason: StopReason | null
50
+ assistantText: string | null
51
+ notice: string | null
52
+ usage: Usage | null
53
+ }
54
+
55
+ export type TurnInput = {
56
+ db: Database
57
+ config: Config
58
+ root: string
59
+ text: string
60
+ chatId?: string
61
+ now?: Date
62
+ signal?: AbortSignal
63
+ shell?: Shell | null
64
+ stream?: (input: StreamLLMInput) => AsyncIterable<StreamEvent>
65
+ executeTool?: ExecuteTool
66
+ maxSteps?: number
67
+ jobs?: JobRegistry
68
+ queue?: string[]
69
+ queueWait?: QueueWake
70
+ onRetry?: (attempt: number) => void
71
+ onDelta?: (delta: Delta) => void
72
+ onToolStarted?: (callId: string, name: string) => void
73
+ onToolRunning?: (callId: string, args: unknown) => void
74
+ onToolOutput?: (callId: string, chunk: string) => void
75
+ onAppended?: (row: MessageRow) => void
76
+ onTitle?: (title: string) => void
77
+ onFileChanged?: (path: string | null, hash: string | null) => void
78
+ beforeSave?: () => void
79
+ }
80
+
81
+ export type TurnRunInput = {
82
+ db: Database
83
+ config: Config
84
+ root: string
85
+ chat: ChatRow
86
+ workspaceId: string
87
+ text: string
88
+ runId: string
89
+ signal: AbortSignal
90
+ now?: Date
91
+ shell?: Shell | null
92
+ stream?: (input: StreamLLMInput) => AsyncIterable<StreamEvent>
93
+ executeTool?: ExecuteTool
94
+ maxSteps?: number
95
+ jobs?: JobRegistry
96
+ queue?: string[]
97
+ queueWait?: QueueWake
98
+ onRetry?: (attempt: number) => void
99
+ onDelta?: (delta: Delta) => void
100
+ onToolStarted?: (callId: string, name: string) => void
101
+ onToolRunning?: (callId: string, args: unknown) => void
102
+ onToolOutput?: (callId: string, chunk: string) => void
103
+ onAppended?: (row: MessageRow) => void
104
+ onTitle?: (title: string) => void
105
+ onFileChanged?: (path: string | null, hash: string | null) => void
106
+ onRunStart?: (runId: string, meta: { title: string; workspaceId: string; model: string; engine: string; updatedAt: number }) => void
107
+ onRunFinish?: (runId: string, status: RunStatus) => void
108
+ onQueueChanged?: (runId: string, queue: string[]) => void
109
+ onCompacted?: () => void
110
+ beforeSave?: () => void
111
+ }
112
+
113
+ /** One run's view of a chat: a model step, a tool result row, queue rows and run events. */
114
+ export function createTurnRun(input: TurnRunInput): RunHooks {
115
+ const notify = (row: MessageRow) => input.onAppended?.(row)
116
+ const shell = input.shell ?? null
117
+ const execute: ExecuteTool =
118
+ input.executeTool
119
+ ? (call, signal) => {
120
+ input.onToolRunning?.(call.id, call.args)
121
+ return input.executeTool!(call, signal)
122
+ }
123
+ : (call, signal) => {
124
+ input.onToolRunning?.(call.id, call.args)
125
+ return executeTool(call, {
126
+ root: input.root,
127
+ chatId: input.chat.id,
128
+ signal,
129
+ onOutput: (chunk) => input.onToolOutput?.(call.id, chunk),
130
+ onDiskChanged: () => input.onFileChanged?.(null, null),
131
+ shell,
132
+ jobs: input.jobs,
133
+ queue: input.queue,
134
+ queueWait: input.queueWait,
135
+ // Compaction writes the turns it removed outside the project, and truncated bash
136
+ // commands spill their full log next to the harness state.
137
+ extraRoots: [archiveDir(input.chat.id), bashOutputDir(input.chat.id)],
138
+ })
139
+ }
140
+
141
+ const stream =
142
+ input.stream ??
143
+ ((llm: StreamLLMInput) =>
144
+ streamForModel(llm.model, input.config, llm, {
145
+ onRetry: input.onRetry,
146
+ db: input.db,
147
+ }))
148
+ let title = input.chat.title
149
+
150
+ return {
151
+ maxSteps: input.maxSteps ?? input.config.maxSteps,
152
+ started() {
153
+ const current = getChat(input.db, input.chat.id)
154
+ if (current) title = current.title
155
+ input.onRunStart?.(input.runId, {
156
+ title,
157
+ workspaceId: input.workspaceId,
158
+ model: current?.model ?? input.chat.model,
159
+ engine: current?.engine ?? input.chat.engine,
160
+ updatedAt: Date.now(),
161
+ })
162
+ },
163
+ begin() {
164
+ repair(input.db, input.chat.id, INTERRUPTED, notify)
165
+ const empty = listMessages(input.db, input.chat.id).length === 0
166
+ flushJobNotices(input.jobs, input.db, input.chat.id, notify)
167
+ // A run started by a job completion has no user text: the notice is the whole turn.
168
+ if (input.text !== '') {
169
+ write(input.db, input.chat.id, 'user', { text: input.text }, undefined, notify)
170
+ if (empty) {
171
+ title = titleFrom(input.text)
172
+ updateChatTitle(input.db, input.chat.id, title)
173
+ input.onTitle?.(title)
174
+ }
175
+ }
176
+ },
177
+ appendUser(text) {
178
+ write(input.db, input.chat.id, 'user', { text }, undefined, notify)
179
+ },
180
+ execute,
181
+ appendTool(call, result) {
182
+ const written = input.db.transaction((): { row: MessageRow; revisions: RevisionRow[] } => {
183
+ const row = appendMessage(
184
+ input.db,
185
+ input.chat.id,
186
+ 'tool',
187
+ { toolCallId: call.id, text: result.text, isError: result.isError },
188
+ result.details,
189
+ )
190
+ const revisions = recordRevisions(input.db, input.chat.id, row.id, result.revisions ?? [])
191
+ return { row, revisions }
192
+ })()
193
+ for (const revision of written.revisions) {
194
+ input.onFileChanged?.(revision.path, revision.after_hash)
195
+ }
196
+ notify(written.row)
197
+ // Delivery is committed with the row. A result replaced by abort never reaches here
198
+ // with these ids, so the completion stays pending for a notice.
199
+ if (input.jobs && result.deliverJobIds) {
200
+ for (const id of result.deliverJobIds) input.jobs.markDelivered(input.chat.id, id)
201
+ }
202
+ },
203
+ closeDangling(reason) {
204
+ repair(input.db, input.chat.id, reason, notify)
205
+ },
206
+ flushJobs() {
207
+ flushJobNotices(input.jobs, input.db, input.chat.id, notify)
208
+ },
209
+ notice(kind, text, options) {
210
+ const details = options?.intoContext ? { intoContext: true } : undefined
211
+ write(input.db, input.chat.id, 'notice', { kind, text }, details, notify)
212
+ },
213
+ async autoCompact(usage, force) {
214
+ // A forced pass follows a provider overflow, where the usual threshold is moot: the
215
+ // gateway already said the request does not fit.
216
+ if (force) {
217
+ const beforeRows = listMessages(input.db, input.chat.id)
218
+ const lastRow = beforeRows.at(-1)
219
+ const errorRowId =
220
+ lastRow?.role === 'notice' && isOverflowError(parseNoticeText(lastRow.content_json))
221
+ ? lastRow.id
222
+ : null
223
+ const prevRow = beforeRows.at(-2)
224
+ const partialRowId =
225
+ errorRowId !== null && prevRow?.role === 'assistant' && isErrorStop(prevRow.content_json)
226
+ ? prevRow.id
227
+ : null
228
+ if (errorRowId !== null) {
229
+ input.db.transaction(() => {
230
+ if (partialRowId !== null) {
231
+ input.db.run('DELETE FROM messages WHERE id = ?', [partialRowId])
232
+ }
233
+ input.db.run('DELETE FROM messages WHERE id = ?', [errorRowId])
234
+ })()
235
+ }
236
+ const forced = await compactChat({
237
+ db: input.db,
238
+ config: input.config,
239
+ chatId: input.chat.id,
240
+ signal: input.signal,
241
+ stream: input.stream,
242
+ force: true,
243
+ })
244
+ if (forced.status === 'compacted') {
245
+ if (input.onCompacted) input.onCompacted()
246
+ else notify(forced.message)
247
+ return 'Контекст сжат после отказа провайдера; шаг повторяется'
248
+ }
249
+ // If compaction could not run, put the provider error rows back so the run ends with a visible reason.
250
+ if (partialRowId !== null && prevRow) {
251
+ appendMessage(input.db, input.chat.id, 'assistant', JSON.parse(prevRow.content_json))
252
+ }
253
+ if (errorRowId !== null && lastRow) {
254
+ appendMessage(input.db, input.chat.id, 'notice', JSON.parse(lastRow.content_json))
255
+ }
256
+ if (forced.status === 'error') {
257
+ write(
258
+ input.db,
259
+ input.chat.id,
260
+ 'notice',
261
+ { kind: 'compacted', text: `Сжатие контекста не удалось: ${forced.error}` },
262
+ undefined,
263
+ notify,
264
+ )
265
+ }
266
+ return null
267
+ }
268
+ const notice = await autoCompactIfNeeded({
269
+ db: input.db,
270
+ config: input.config,
271
+ chatId: input.chat.id,
272
+ signal: input.signal,
273
+ stream: input.stream,
274
+ usage: usage ?? { input: 0, output: 0 },
275
+ })
276
+ if (notice === null) return null
277
+ if (notice.startsWith('Сжатие контекста не удалось:')) {
278
+ write(input.db, input.chat.id, 'notice', { kind: 'compacted', text: notice }, undefined, notify)
279
+ return null
280
+ }
281
+ const summary = visibleRows(listMessages(input.db, input.chat.id)).find(isCompactionRow)
282
+ if (input.onCompacted) input.onCompacted()
283
+ else if (summary) notify(summary)
284
+ return notice
285
+ },
286
+ step() {
287
+ const { rows, violation } = prepareHistory(input.db, input.chat.id, notify)
288
+ if (violation) {
289
+ write(input.db, input.chat.id, 'notice', { kind: 'history', text: violation }, undefined, notify)
290
+ return Promise.resolve({
291
+ called: false,
292
+ stopReason: null,
293
+ assistantText: null,
294
+ notice: violation,
295
+ usage: null,
296
+ toolCalls: [],
297
+ })
298
+ }
299
+ const fresh = getChat(input.db, input.chat.id)
300
+ const activeModel = fresh?.model ?? input.chat.model
301
+ const reasoning = fresh?.reasoning ?? input.config.reasoning
302
+ return readStream(
303
+ stream({
304
+ model: activeModel,
305
+ system: systemPrompt(input.root, shell !== null, input.now, input.jobs !== undefined),
306
+ messages: modelMessages(rows),
307
+ tools: toolDefsFor(shell, input.jobs),
308
+ signal: input.signal,
309
+ sessionId: input.chat.id,
310
+ ...(reasoning ? { reasoning } : {}),
311
+ }),
312
+ input.signal,
313
+ input.onDelta,
314
+ input.onToolStarted,
315
+ ).then((result) => {
316
+ input.beforeSave?.()
317
+ const saved = persist(input.db, input.chat.id, activeModel, result, notify)
318
+ const toolCalls =
319
+ result.kind === 'done' &&
320
+ (result.event.stopReason === 'tool_use' || result.event.stopReason === 'max_tokens')
321
+ ? result.event.blocks.filter((block): block is ToolCallBlock => block.type === 'tool_call')
322
+ : []
323
+ return { called: true, ...saved, toolCalls }
324
+ })
325
+ },
326
+ queueChanged(queue) {
327
+ input.onQueueChanged?.(input.runId, queue)
328
+ },
329
+ finished(status) {
330
+ input.onRunFinish?.(input.runId, status)
331
+ },
332
+ }
333
+ }
334
+
335
+ /** One message and one run to its end: the CLI path and the older turn tests. */
336
+ export async function runTurn(input: TurnInput): Promise<TurnOutcome> {
337
+ const workspace = ensureWorkspace(input.db, input.root)
338
+ const chat = input.chatId
339
+ ? requiredChat(input.db, input.chatId)
340
+ : ensureChat(input.db, workspace.id, input.config.model, titleFrom(input.text))
341
+ const signal = input.signal ?? new AbortController().signal
342
+ const runId = crypto.randomUUID()
343
+ const hooks = createTurnRun({
344
+ db: input.db,
345
+ config: input.config,
346
+ root: input.root,
347
+ chat,
348
+ workspaceId: workspace.id,
349
+ text: input.text,
350
+ runId,
351
+ signal,
352
+ now: input.now,
353
+ shell: input.shell,
354
+ stream: input.stream,
355
+ executeTool: input.executeTool,
356
+ maxSteps: input.maxSteps,
357
+ jobs: input.jobs,
358
+ queue: input.queue,
359
+ queueWait: input.queueWait,
360
+ onRetry: input.onRetry,
361
+ onDelta: input.onDelta,
362
+ onToolStarted: input.onToolStarted,
363
+ onToolRunning: input.onToolRunning,
364
+ onToolOutput: input.onToolOutput,
365
+ onAppended: input.onAppended,
366
+ onTitle: input.onTitle,
367
+ onFileChanged: input.onFileChanged,
368
+ beforeSave: input.beforeSave,
369
+ })
370
+ hooks.begin()
371
+ const outcome = await runLoop({
372
+ signal: input.signal,
373
+ maxSteps: hooks.maxSteps,
374
+ queue: [],
375
+ appendUser: hooks.appendUser,
376
+ step: hooks.step,
377
+ execute: hooks.execute,
378
+ appendTool: hooks.appendTool,
379
+ closeDangling: hooks.closeDangling,
380
+ notice: hooks.notice,
381
+ autoCompact: hooks.autoCompact,
382
+ flushJobs: hooks.flushJobs,
383
+ })
384
+ return { chatId: chat.id, ...outcome }
385
+ }
386
+
387
+ function prepareHistory(
388
+ db: Database,
389
+ chatId: string,
390
+ notify: (row: MessageRow) => void,
391
+ ): { rows: MessageRow[]; violation: string | null } {
392
+ repair(db, chatId, INTERRUPTED, notify)
393
+ const rows = listMessages(db, chatId)
394
+ return { rows, violation: historyViolation(rows) }
395
+ }
396
+
397
+ function write(
398
+ db: Database,
399
+ chatId: string,
400
+ role: MessageRole,
401
+ content: unknown,
402
+ details: unknown,
403
+ notify: (row: MessageRow) => void,
404
+ ): MessageRow {
405
+ const row = appendMessage(db, chatId, role, content, details)
406
+ notify(row)
407
+ return row
408
+ }
409
+
410
+ function persist(
411
+ db: Database,
412
+ chatId: string,
413
+ model: string,
414
+ result: StreamResult,
415
+ notify: (row: MessageRow) => void,
416
+ ): Omit<TurnOutcome, 'chatId' | 'called'> {
417
+ if (result.kind === 'abort') return saveAborted(db, chatId, model, textBlocks(result.text), null, notify)
418
+ if (result.kind === 'error') return saveError(db, chatId, model, textBlocks(result.text), null, result.message, notify)
419
+ if (result.event.stopReason === 'aborted') {
420
+ return saveAborted(db, chatId, model, abortedBlocks(result.event.blocks), result.event.usage, notify)
421
+ }
422
+ if (result.event.stopReason === 'error') {
423
+ return saveError(
424
+ db,
425
+ chatId,
426
+ model,
427
+ result.event.blocks,
428
+ result.event.usage,
429
+ result.event.error ?? 'Ошибка провайдера',
430
+ notify,
431
+ )
432
+ }
433
+ const text = textOf(result.event.blocks)
434
+ write(
435
+ db,
436
+ chatId,
437
+ 'assistant',
438
+ {
439
+ blocks: result.event.blocks,
440
+ stopReason: result.event.stopReason,
441
+ usage: result.event.usage,
442
+ model,
443
+ ...(result.event.servedCheckpoint ? { servedCheckpoint: result.event.servedCheckpoint } : {}),
444
+ },
445
+ undefined,
446
+ notify,
447
+ )
448
+ const hasToolCalls = result.event.blocks.some((block) => block.type === 'tool_call')
449
+ let notice: string | null = null
450
+ if (result.event.stopReason === 'max_tokens') {
451
+ notice =
452
+ 'Ответ обрезан по лимиту токенов. Вызовы тулов из него не исполнялись: аргументы могли быть неполными. ' +
453
+ 'Переотправь нужные вызовы целиком'
454
+ // When the truncated response also emitted tool calls, the notice is written by the loop
455
+ // after their error tool rows so it never lands between `assistant` and `tool`.
456
+ if (!hasToolCalls) {
457
+ write(
458
+ db,
459
+ chatId,
460
+ 'notice',
461
+ { kind: 'max_tokens', text: notice },
462
+ { intoContext: true },
463
+ notify,
464
+ )
465
+ }
466
+ }
467
+ return { stopReason: result.event.stopReason, assistantText: text || null, notice, usage: result.event.usage }
468
+ }
469
+
470
+ function saveAborted(
471
+ db: Database,
472
+ chatId: string,
473
+ model: string,
474
+ blocks: Block[],
475
+ usage: Usage | null,
476
+ notify: (row: MessageRow) => void,
477
+ ): Omit<TurnOutcome, 'chatId' | 'called'> {
478
+ const text = textOf(blocks)
479
+ if (!text) return { stopReason: 'aborted', assistantText: null, notice: null, usage: null }
480
+ write(
481
+ db,
482
+ chatId,
483
+ 'assistant',
484
+ {
485
+ blocks,
486
+ stopReason: 'aborted',
487
+ ...(usage ? { usage } : {}),
488
+ model,
489
+ },
490
+ undefined,
491
+ notify,
492
+ )
493
+ return { stopReason: 'aborted', assistantText: text, notice: null, usage }
494
+ }
495
+
496
+ function saveError(
497
+ db: Database,
498
+ chatId: string,
499
+ model: string,
500
+ blocks: Block[],
501
+ usage: Usage | null,
502
+ message: string,
503
+ notify: (row: MessageRow) => void,
504
+ ): Omit<TurnOutcome, 'chatId' | 'called'> {
505
+ const text = textOf(blocks)
506
+ if (text) {
507
+ write(
508
+ db,
509
+ chatId,
510
+ 'assistant',
511
+ {
512
+ blocks,
513
+ stopReason: 'error',
514
+ ...(usage ? { usage } : {}),
515
+ model,
516
+ },
517
+ undefined,
518
+ notify,
519
+ )
520
+ }
521
+ write(db, chatId, 'notice', { kind: 'provider_error', text: message }, undefined, notify)
522
+ return { stopReason: 'error', assistantText: text || null, notice: message, usage: text ? usage : null }
523
+ }
524
+
525
+ async function readStream(
526
+ events: AsyncIterable<StreamEvent>,
527
+ signal: AbortSignal | undefined,
528
+ onDelta?: (delta: Delta) => void,
529
+ onToolStarted?: (callId: string, name: string) => void,
530
+ ): Promise<StreamResult> {
531
+ let text = ''
532
+ let done: DoneEvent | undefined
533
+ try {
534
+ for await (const event of events) {
535
+ if (event.type === 'text_delta') {
536
+ text += event.text
537
+ onDelta?.({ text: event.text })
538
+ } else if (event.type === 'thinking_delta') {
539
+ onDelta?.({ thinking: event.text })
540
+ } else if (event.type === 'tool_call_started') {
541
+ onToolStarted?.(event.id, event.name)
542
+ } else if (event.type === 'done') done = event
543
+ }
544
+ } catch (error) {
545
+ if (isAbort(error) || signal?.aborted) return { kind: 'abort', text }
546
+ return { kind: 'error', text, message: error instanceof Error ? error.message : String(error) }
547
+ }
548
+ if (done) return { kind: 'done', event: done }
549
+ if (signal?.aborted) return { kind: 'abort', text }
550
+ return { kind: 'error', text, message: 'Модель не прислала конец ответа' }
551
+ }
552
+
553
+ function abortedBlocks(blocks: Block[]): Block[] {
554
+ const kept: Block[] = []
555
+ for (const block of blocks) {
556
+ if (block.type === 'text' && block.text) kept.push(block)
557
+ else if (block.type === 'thinking' && block.opaque !== undefined) kept.push(block)
558
+ }
559
+ return kept
560
+ }
561
+
562
+ function textBlocks(text: string): Block[] {
563
+ return text ? [{ type: 'text', text }] : []
564
+ }
565
+
566
+ function textOf(blocks: Block[]): string {
567
+ return blocks.filter((block): block is TextBlock => block.type === 'text').map((block) => block.text).join('')
568
+ }
569
+
570
+ function flushJobNotices(
571
+ jobs: JobRegistry | undefined,
572
+ db: Database,
573
+ chatId: string,
574
+ notify: (row: MessageRow) => void,
575
+ ): void {
576
+ if (!jobs) return
577
+ for (const completion of jobs.takePending(chatId)) {
578
+ write(
579
+ db,
580
+ chatId,
581
+ 'notice',
582
+ { kind: 'job', text: jobNoticeText(completion) },
583
+ { intoContext: true },
584
+ notify,
585
+ )
586
+ }
587
+ }
588
+
589
+ export function jobNoticeText(job: JobCompletion): string {
590
+ const header =
591
+ job.status === 'killed'
592
+ ? `Background job ${job.id} was killed (${job.outputSize} chars): ${job.command}`
593
+ : `Background job ${job.id} finished with exit code ${job.exitCode ?? -1} (${job.outputSize} chars): ${job.command}`
594
+ const parts = [header]
595
+ const body = formatJobPreview(job.preview, job.outputSize, job.logPath)
596
+ if (body) parts.push(body)
597
+ return parts.join('\n')
598
+ }
599
+
600
+ export function titleFrom(text: string): string {
601
+ const line = text.trim().split('\n')[0] ?? ''
602
+ if (!line) return 'Chat'
603
+ return line.length > 80 ? line.slice(0, 80) : line
604
+ }
605
+
606
+ function requiredChat(db: Database, chatId: string): ChatRow {
607
+ const chat = getChat(db, chatId)
608
+ if (!chat) throw new Error('Чат не найден')
609
+ return chat
610
+ }
611
+
612
+ function isAbort(error: unknown): boolean {
613
+ return error instanceof Error && error.name === 'AbortError'
614
+ }
615
+
616
+ function parseNoticeText(contentJson: string): string | null {
617
+ try {
618
+ const parsed = JSON.parse(contentJson) as { text?: unknown }
619
+ return typeof parsed?.text === 'string' ? parsed.text : null
620
+ } catch {
621
+ return null
622
+ }
623
+ }
624
+
625
+ function isErrorStop(contentJson: string): boolean {
626
+ try {
627
+ const parsed = JSON.parse(contentJson) as { stopReason?: unknown }
628
+ return parsed?.stopReason === 'error'
629
+ } catch {
630
+ return false
631
+ }
632
+ }
633
+
634
+ async function main(): Promise<void> {
635
+ const text = process.argv[2]
636
+ if (!text) {
637
+ console.error('Использование: bun server/turn.ts "текст"')
638
+ process.exitCode = 1
639
+ return
640
+ }
641
+ const home = pointerHome()
642
+ const config = loadConfig(home)
643
+ const apiKeyEnv = providerById(defaultProviderId(config))?.apiKeyEnv
644
+ if (apiKeyEnv && !process.env[apiKeyEnv]) {
645
+ console.error(`${apiKeyEnv} не задан. Впиши его в .env в корне проекта.`)
646
+ process.exitCode = 1
647
+ return
648
+ }
649
+ const db = openDatabase(join(home, 'state.db'))
650
+ const path = findGitBash(config)
651
+ const shell: Shell | null = path === null ? null : { path, maxTimeout: config.bashTimeout }
652
+ try {
653
+ const outcome = await runTurn({ db, config, root: process.cwd(), text, shell })
654
+ if (outcome.assistantText) process.stdout.write(`${outcome.assistantText}\n`)
655
+ if (outcome.usage) console.error(JSON.stringify(outcome.usage))
656
+ if (outcome.notice) console.error(outcome.notice)
657
+ if (!outcome.called || outcome.stopReason === 'error' || outcome.stopReason === null) process.exitCode = 1
658
+ } finally {
659
+ db.close()
660
+ }
661
+ }
662
+
663
+ if (import.meta.main) await main()