@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,1249 @@
1
+ import type { Database } from 'bun:sqlite'
2
+ import type { AcpAnswer, AcpQuestion, StopReason, Usage } from '../../shared/types'
3
+ import { BLOB_LIMIT, hashOnDisk, recordRevisions, type Revision, type RevisionRow } from '../changes'
4
+ import { appendMessage, getChat, readAcpConfig, setAcpSessionId, writeAcpConfig, type ChatRow, type MessageRow } from '../db'
5
+ import { diffLines } from '../diff'
6
+ import { acpAgent, resolveAcpCommand, type AcpAgentSpec } from '../engines'
7
+ import { acpOverride } from '../providers/store'
8
+ import { ABORTED } from '../history'
9
+ import type { LoopStep } from '../loop'
10
+ import type { Config } from '../config'
11
+ import { resolveInRoot } from '../tools/jail'
12
+ import type { Shell } from '../tools'
13
+ import { configValueAllowed, parseAcpConfigOptions, type AcpConfigOption } from '../../shared/acpConfig'
14
+ import { AcpConnection } from './connection'
15
+ import {
16
+ AcpError,
17
+ PROTOCOL_VERSION,
18
+ type AcpAskQuestionParams,
19
+ type AcpContentBlock,
20
+ type AcpCreatePlanParams,
21
+ type AcpDiffContent,
22
+ type AcpInitializeResult,
23
+ type AcpPermissionRequest,
24
+ type AcpPlanEntry,
25
+ type AcpPlanTodo,
26
+ type AcpPromptResult,
27
+ type AcpSessionUpdate,
28
+ type AcpToolCall,
29
+ type AcpToolCallUpdate,
30
+ type AcpToolKind,
31
+ type AcpUpdateTodosParams,
32
+ } from './protocol'
33
+
34
+ const ACP_IDLE_MS = 5 * 60 * 1000
35
+ const ACP_CANCEL_GRACE_MS = 2_000
36
+ const ACP_TOOL_TEXT_LIMIT = 30_000
37
+ const ACP_RAW_LIMIT = 200_000
38
+ const ACP_LOGIN_HINT = 'Авторизуй cursor-agent в том окружении, где он запускается.'
39
+
40
+ type ClosedTool = { messageId: string; kind?: AcpToolKind }
41
+
42
+ type CollectedDiff = {
43
+ revisions: Revision[]
44
+ skipped: boolean
45
+ diffDetails: ReturnType<typeof diffLines> | null
46
+ path: string | null
47
+ abs: string | null
48
+ }
49
+
50
+ export type AcpTurn = {
51
+ signal: AbortSignal
52
+ onDelta: (delta: { text?: string; thinking?: string }) => void
53
+ onToolStarted: (callId: string, name: string) => void
54
+ onToolRunning: (callId: string, args: unknown) => void
55
+ onToolOutput: (callId: string, chunk: string) => void
56
+ onAppended: (row: MessageRow) => void
57
+ onFileChanged: (path: string, hash: string | null) => void
58
+ onQuestion: (question: AcpQuestion | null) => void
59
+ beforeSave: () => void
60
+ }
61
+
62
+ type AnswerResult = { ok: true; result: unknown } | { ok: false; error: string }
63
+
64
+ type PendingQuestion = {
65
+ question: AcpQuestion
66
+ validate: (answer: AcpAnswer) => AnswerResult
67
+ resolve: (result: unknown) => void
68
+ }
69
+
70
+ type ToolState = AcpToolCall
71
+
72
+ const sessions = new Map<string, AcpSession>()
73
+
74
+ export function getAcpSession(input: {
75
+ db: Database
76
+ config: Config
77
+ root: string
78
+ chat: ChatRow
79
+ shell?: Shell | null
80
+ }): AcpSession {
81
+ const existing = sessions.get(input.chat.id)
82
+ if (existing) return existing
83
+ const spec = acpAgent(input.chat.engine)
84
+ if (!spec) throw new Error(`Неизвестный ACP-движок: ${input.chat.engine}`)
85
+ const session = new AcpSession(input.db, input.config, input.root, input.chat, spec, input.shell?.path ?? '')
86
+ sessions.set(input.chat.id, session)
87
+ return session
88
+ }
89
+
90
+ export function answerAcpQuestion(
91
+ chatId: string,
92
+ questionId: string,
93
+ answer: AcpAnswer,
94
+ ):
95
+ | { status: 'ok' }
96
+ | { status: 'no_session' | 'no_question' | 'invalid'; error?: string } {
97
+ const session = sessions.get(chatId)
98
+ if (!session) return { status: 'no_session', error: 'ACP-сессия не запущена' }
99
+ return session.answer(questionId, answer)
100
+ }
101
+
102
+ export function stopAcpSession(chatId: string): void {
103
+ const session = sessions.get(chatId)
104
+ if (!session) return
105
+ sessions.delete(chatId)
106
+ session.dispose()
107
+ }
108
+
109
+ export function stopAllAcp(): void {
110
+ for (const [chatId, session] of sessions) {
111
+ sessions.delete(chatId)
112
+ session.dispose()
113
+ }
114
+ }
115
+
116
+ export class AcpSession {
117
+ private readonly db: Database
118
+ private readonly config: Config
119
+ private readonly root: string
120
+ private readonly chatId: string
121
+ private readonly spec: AcpAgentSpec
122
+ private readonly shellPath: string
123
+ private connection: AcpConnection | null = null
124
+ private lastStderr = ''
125
+ private sessionId: string | null = null
126
+ private loadSession = false
127
+ private authMethods: string[] = []
128
+ private loading = false
129
+ private disposed = false
130
+ private turn: AcpTurn | null = null
131
+ private model = ''
132
+ private text = ''
133
+ private thinking = ''
134
+ private lastAssistantText: string | null = null
135
+ private tools = new Map<string, ToolState>()
136
+ private closedTools = new Set<string>()
137
+ private toolMessages = new Map<string, ClosedTool>()
138
+ private revisedCalls = new Set<string>()
139
+ private lastNotice = ''
140
+ private todos: AcpPlanTodo[] = []
141
+ private currentQuestion: PendingQuestion | null = null
142
+ private pending: PendingQuestion[] = []
143
+ private idleTimer: ReturnType<typeof setTimeout> | undefined
144
+ private promptReject: ((error: Error) => void) | null = null
145
+ private starting: Promise<void> | null = null
146
+ private options: AcpConfigOption[] = []
147
+
148
+ constructor(
149
+ db: Database,
150
+ config: Config,
151
+ root: string,
152
+ chat: ChatRow,
153
+ spec: AcpAgentSpec,
154
+ shellPath: string,
155
+ ) {
156
+ this.db = db
157
+ this.config = config
158
+ this.root = root
159
+ this.chatId = chat.id
160
+ this.spec = spec
161
+ this.shellPath = shellPath
162
+ this.model = chat.model
163
+ }
164
+
165
+ async prompt(text: string, turn: AcpTurn): Promise<LoopStep> {
166
+ if (this.disposed) return this.stepResult(false, null, null, 'Сессия остановлена')
167
+ this.turn = turn
168
+ this.text = ''
169
+ this.thinking = ''
170
+ this.lastAssistantText = null
171
+ this.tools.clear()
172
+ this.closedTools.clear()
173
+ this.toolMessages.clear()
174
+ this.revisedCalls.clear()
175
+ this.lastNotice = ''
176
+ this.todos = []
177
+ clearTimeout(this.idleTimer)
178
+ this.idleTimer = undefined
179
+ const chat = getChat(this.db, this.chatId)
180
+ if (chat) this.model = chat.model
181
+
182
+ try {
183
+ await this.ensure(turn.signal)
184
+ if (this.disposed) return this.stepResult(false, null, null, 'Сессия остановлена')
185
+ if (turn.signal.aborted) {
186
+ this.connection?.kill()
187
+ return this.stepResult(true, 'aborted', null, null)
188
+ }
189
+ const connection = this.connection
190
+ if (!connection) throw new Error('ACP-соединение не открыто')
191
+ let cancelTimer: ReturnType<typeof setTimeout> | undefined
192
+ const onAbort = () => {
193
+ this.closeOpenCalls(ABORTED)
194
+ this.cancelQuestions()
195
+ if (this.sessionId) connection.notify('session/cancel', { sessionId: this.sessionId })
196
+ cancelTimer = setTimeout(() => connection.kill(), ACP_CANCEL_GRACE_MS)
197
+ }
198
+ turn.signal.addEventListener('abort', onAbort, { once: true })
199
+ try {
200
+ if (turn.signal.aborted) {
201
+ this.closeOpenCalls(ABORTED)
202
+ this.cancelQuestions()
203
+ connection.kill()
204
+ return this.stepResult(true, 'aborted', null, null)
205
+ }
206
+ const response = await new Promise<AcpPromptResult>((resolve, reject) => {
207
+ this.promptReject = reject
208
+ connection.request('session/prompt', {
209
+ sessionId: this.sessionId,
210
+ prompt: [{ type: 'text', text }],
211
+ }, 0).then(
212
+ (value) => resolve(value as AcpPromptResult),
213
+ (error) => reject(error instanceof Error ? error : new Error(String(error))),
214
+ )
215
+ })
216
+ this.promptReject = null
217
+ if (this.disposed) return this.stepResult(false, null, null, 'Сессия остановлена')
218
+ if (turn.signal.aborted) {
219
+ this.closeOpenCalls(ABORTED)
220
+ this.cancelQuestions()
221
+ this.flushAssistant('aborted')
222
+ return this.stepResult(true, 'aborted', null, null)
223
+ }
224
+ return this.finish(response)
225
+ } finally {
226
+ clearTimeout(cancelTimer)
227
+ turn.signal.removeEventListener('abort', onAbort)
228
+ }
229
+ } catch (error) {
230
+ this.promptReject = null
231
+ if (this.disposed) return this.stepResult(false, null, null, 'Сессия остановлена')
232
+ if (turn.signal.aborted) {
233
+ this.closeOpenCalls(ABORTED)
234
+ this.flushAssistant('aborted')
235
+ this.cancelQuestions()
236
+ return this.stepResult(true, 'aborted', null, null)
237
+ }
238
+ const message = error instanceof Error ? error.message : String(error)
239
+ this.flushAssistant('error')
240
+ this.closeOpenCalls('Агент завершил ход без результата')
241
+ this.cancelQuestions()
242
+ const notice = `ACP-агент вернул ошибку: ${this.withStderr(message)}`
243
+ this.notice('agent_error', notice)
244
+ return this.stepResult(true, 'error', null, notice)
245
+ } finally {
246
+ this.turn = null
247
+ if (!this.disposed) this.scheduleIdle()
248
+ }
249
+ }
250
+
251
+ closeOpenCalls(reason: string): void {
252
+ if (this.disposed) return
253
+ for (const [callId, info] of this.tools) {
254
+ this.tools.delete(callId)
255
+ this.closedTools.add(callId)
256
+ this.writeToolRow({ ...info, status: 'failed' }, reason, [])
257
+ }
258
+ }
259
+
260
+ answer(
261
+ questionId: string,
262
+ answer: AcpAnswer,
263
+ ): { status: 'ok' } | { status: 'no_question' | 'invalid'; error?: string } {
264
+ let item = this.currentQuestion
265
+ let fromCurrent = true
266
+ if (!item || item.question.id !== questionId) {
267
+ const index = this.pending.findIndex((candidate) => candidate.question.id === questionId)
268
+ if (index < 0) return { status: 'no_question', error: 'Вопрос не найден' }
269
+ item = this.pending[index]!
270
+ fromCurrent = false
271
+ this.pending.splice(index, 1)
272
+ }
273
+ const checked = item.validate(answer)
274
+ if (!checked.ok) return { status: 'invalid', error: checked.error }
275
+ if (fromCurrent) {
276
+ this.currentQuestion = null
277
+ item.resolve(checked.result)
278
+ this.publishNextQuestion()
279
+ } else {
280
+ item.resolve(checked.result)
281
+ }
282
+ return { status: 'ok' }
283
+ }
284
+
285
+ async loadConfig(signal: AbortSignal): Promise<AcpConfigOption[]> {
286
+ await this.ensure(signal)
287
+ if (!this.turn) this.scheduleIdle()
288
+ return this.options
289
+ }
290
+
291
+ async setConfig(signal: AbortSignal, configId: string, value: string | boolean): Promise<AcpConfigOption[]> {
292
+ await this.ensure(signal)
293
+ const option = this.options.find((item) => item.configId === configId)
294
+ if (!option) throw new Error('Нет такого параметра')
295
+ if (!configValueAllowed(option, value)) throw new Error('Недопустимое значение')
296
+ const connection = this.connection
297
+ if (!connection || !this.sessionId) throw new Error('ACP-сессия не запущена')
298
+ const result = await connection.request('session/set_config_option', {
299
+ sessionId: this.sessionId,
300
+ configId,
301
+ type: typeof value === 'boolean' ? 'boolean' : 'id',
302
+ value,
303
+ })
304
+ const next = parseAcpConfigOptions(result)
305
+ if (next.length > 0) this.options = next
306
+ const applied = this.options.find((item) => item.configId === configId)
307
+ this.remember(configId, applied ? applied.currentValue : value)
308
+ if (!this.turn) this.scheduleIdle()
309
+ return this.options
310
+ }
311
+
312
+ dispose(): void {
313
+ if (this.disposed) return
314
+ this.disposed = true
315
+ clearTimeout(this.idleTimer)
316
+ this.idleTimer = undefined
317
+ this.promptReject?.(new AcpError('Сессия остановлена', -32000))
318
+ this.promptReject = null
319
+ this.cancelQuestions()
320
+ const connection = this.connection
321
+ this.connection = null
322
+ this.sessionId = null
323
+ connection?.kill()
324
+ }
325
+
326
+ private async ensure(signal: AbortSignal): Promise<void> {
327
+ if (this.starting) {
328
+ await this.starting
329
+ return
330
+ }
331
+ if (signal.aborted || this.disposed) return
332
+ const job = this.connect(signal)
333
+ this.starting = job
334
+ try {
335
+ await job
336
+ } finally {
337
+ if (this.starting === job) this.starting = null
338
+ }
339
+ }
340
+
341
+ private async connect(signal: AbortSignal): Promise<void> {
342
+ if (signal.aborted) return
343
+ if (this.connection && !this.connection.alive) {
344
+ this.connection.kill()
345
+ this.connection = null
346
+ this.sessionId = null
347
+ }
348
+ if (this.connection) return
349
+ const resolved = resolveAcpCommand(this.config, this.spec, acpOverride(this.db))
350
+ if (!resolved) {
351
+ throw new Error(
352
+ `ACP-агент не найден: ${this.config.acpCommand}. Проверь acpCommand в config.json`,
353
+ )
354
+ }
355
+ const marker = crypto.randomUUID()
356
+ this.lastStderr = ''
357
+ const connection = new AcpConnection({
358
+ command: resolved.command,
359
+ args: resolved.args,
360
+ cwd: this.root,
361
+ marker,
362
+ shell: this.shellPath,
363
+ onRequest: (method, params) => this.onRequest(method, params),
364
+ onNotification: (method, params) => this.onNotification(method, params),
365
+ onExit: (_code, tail) => {
366
+ if (this.connection === connection || this.connection === null) this.lastStderr = tail
367
+ if (this.connection === connection) {
368
+ this.connection = null
369
+ this.sessionId = null
370
+ }
371
+ },
372
+ })
373
+ this.connection = connection
374
+ // Startup has no prompt to cancel. Stop kills the process now; waiting out the
375
+ // RPC timeout would leave the turn running after the user already aborted.
376
+ const abortStartup = () => connection.kill()
377
+ signal.addEventListener('abort', abortStartup, { once: true })
378
+ try {
379
+ if (signal.aborted) {
380
+ connection.kill()
381
+ return
382
+ }
383
+ const initialized = (await connection.request('initialize', {
384
+ protocolVersion: PROTOCOL_VERSION,
385
+ clientCapabilities: {
386
+ fs: { readTextFile: false, writeTextFile: false },
387
+ terminal: false,
388
+ _meta: { parameterizedModelPicker: true },
389
+ },
390
+ clientInfo: { name: 'pointer', version: '0.1.0' },
391
+ _meta: { parameterizedModelPicker: true },
392
+ })) as AcpInitializeResult
393
+ if (initialized.protocolVersion !== PROTOCOL_VERSION) {
394
+ throw new Error(
395
+ `ACP-агент объявил протокол ${initialized.protocolVersion}; ожидается ${PROTOCOL_VERSION}`,
396
+ )
397
+ }
398
+ this.loadSession = initialized.agentCapabilities?.loadSession === true
399
+ this.authMethods = (initialized.authMethods ?? [])
400
+ .map((method) => method.id)
401
+ .filter((id): id is string => typeof id === 'string' && id.length > 0)
402
+ try {
403
+ await this.openSession(connection)
404
+ } catch (error) {
405
+ if (!isAuthRequired(error)) throw error
406
+ await this.authenticate(connection)
407
+ await this.openSession(connection)
408
+ }
409
+ } catch (error) {
410
+ if (this.connection === connection) this.connection = null
411
+ connection.kill()
412
+ throw error
413
+ } finally {
414
+ signal.removeEventListener('abort', abortStartup)
415
+ }
416
+ }
417
+
418
+ private async openSession(connection: AcpConnection): Promise<void> {
419
+ const chat = getChat(this.db, this.chatId)
420
+ const stored = chat?.acp_session_id ?? null
421
+ if (stored && this.loadSession) {
422
+ this.loading = true
423
+ try {
424
+ const loaded = await connection.request('session/load', {
425
+ sessionId: stored,
426
+ cwd: this.agentRoot(),
427
+ mcpServers: [],
428
+ })
429
+ this.sessionId = stored
430
+ this.options = parseAcpConfigOptions(loaded)
431
+ } catch (error) {
432
+ if (isAuthRequired(error)) throw error
433
+ setAcpSessionId(this.db, this.chatId, null)
434
+ await this.newSession(connection)
435
+ this.notice('agent_error', 'Сессия агента не найдена; начата новая')
436
+ } finally {
437
+ this.loading = false
438
+ }
439
+ } else {
440
+ await this.newSession(connection)
441
+ }
442
+ await this.applySaved(connection)
443
+ }
444
+
445
+ private async authenticate(connection: AcpConnection): Promise<void> {
446
+ let method = this.spec.authMethod && this.authMethods.includes(this.spec.authMethod)
447
+ ? this.spec.authMethod
448
+ : this.authMethods.length === 1
449
+ ? this.authMethods[0]
450
+ : null
451
+ if (!method) {
452
+ throw new Error(`Агент требует вход, но не объявил подходящий метод. ${ACP_LOGIN_HINT}`)
453
+ }
454
+ try {
455
+ await connection.request('authenticate', { methodId: method })
456
+ } catch (error) {
457
+ const message = error instanceof Error ? error.message : String(error)
458
+ throw new Error(`${message}. ${ACP_LOGIN_HINT}`)
459
+ }
460
+ }
461
+
462
+ private async newSession(connection: AcpConnection): Promise<void> {
463
+ const created = (await connection.request('session/new', {
464
+ cwd: this.agentRoot(),
465
+ mcpServers: [],
466
+ })) as { sessionId?: unknown }
467
+ if (typeof created?.sessionId !== 'string' || !created.sessionId) {
468
+ throw new Error('ACP-агент не вернул sessionId')
469
+ }
470
+ this.sessionId = created.sessionId
471
+ this.options = parseAcpConfigOptions(created)
472
+ setAcpSessionId(this.db, this.chatId, created.sessionId)
473
+ }
474
+
475
+ private async applySaved(connection: AcpConnection): Promise<void> {
476
+ const saved = readAcpConfig(getChat(this.db, this.chatId))
477
+ for (const [configId, value] of Object.entries(saved)) {
478
+ const option = this.options.find((item) => item.configId === configId)
479
+ if (!option || option.currentValue === value || !configValueAllowed(option, value)) continue
480
+ if (!this.sessionId) return
481
+ try {
482
+ const result = await connection.request('session/set_config_option', {
483
+ sessionId: this.sessionId,
484
+ configId,
485
+ type: typeof value === 'boolean' ? 'boolean' : 'id',
486
+ value,
487
+ })
488
+ const next = parseAcpConfigOptions(result)
489
+ if (next.length > 0) this.options = next
490
+ } catch {
491
+ // A stored value the agent no longer accepts does not stop the session.
492
+ }
493
+ }
494
+ }
495
+
496
+ private remember(configId: string, value: string | boolean): void {
497
+ const saved = readAcpConfig(getChat(this.db, this.chatId))
498
+ saved[configId] = value
499
+ writeAcpConfig(this.db, this.chatId, saved)
500
+ }
501
+
502
+ private finish(response: AcpPromptResult): LoopStep {
503
+ const usage = this.usageOf(response.usage)
504
+ const stop = this.mapStop(response.stopReason)
505
+ let notice: string | null = null
506
+ let noticeKind: string | null = null
507
+ if (stop === 'max_tokens') {
508
+ notice = 'Ответ обрезан по лимиту токенов. Продолжи с того же места'
509
+ noticeKind = 'max_tokens'
510
+ } else if (response.stopReason === 'max_turn_requests') {
511
+ notice = 'Агент остановился по своему потолку шагов.'
512
+ noticeKind = 'max_steps'
513
+ } else if (stop === 'error') {
514
+ notice = 'Агент отказался отвечать'
515
+ noticeKind = 'agent_refusal'
516
+ }
517
+ this.flushAssistant(stop, usage ?? undefined)
518
+ this.closeOpenCalls('Агент завершил ход без результата')
519
+ this.cancelQuestions()
520
+ if (notice && noticeKind) this.notice(noticeKind, notice)
521
+ return this.stepResult(true, stop, usage, notice)
522
+ }
523
+
524
+ private mapStop(reason: AcpPromptResult['stopReason']): StopReason {
525
+ if (reason === 'cancelled') return 'aborted'
526
+ if (reason === 'refusal') return 'error'
527
+ if (reason === 'max_tokens') return 'max_tokens'
528
+ return 'end'
529
+ }
530
+
531
+ private usageOf(usage: AcpPromptResult['usage']): Usage | null {
532
+ if (!usage) return null
533
+ return { input: usage.inputTokens ?? 0, output: usage.outputTokens ?? 0 }
534
+ }
535
+
536
+ private stepResult(
537
+ called: boolean,
538
+ stopReason: StopReason | null,
539
+ usage: Usage | null,
540
+ notice: string | null,
541
+ ): LoopStep {
542
+ return {
543
+ called,
544
+ stopReason,
545
+ assistantText: this.lastAssistantText,
546
+ notice,
547
+ usage,
548
+ toolCalls: [],
549
+ }
550
+ }
551
+
552
+ private flushAssistant(stopReason: StopReason, usage?: Usage): void {
553
+ const turn = this.turn
554
+ const text = this.text
555
+ const thinking = this.thinking
556
+ this.text = ''
557
+ this.thinking = ''
558
+ if (!turn) return
559
+ if (!text && !thinking) return
560
+ const blocks: Array<{ type: 'text'; text: string } | { type: 'thinking'; text: string }> = []
561
+ if (thinking) blocks.push({ type: 'thinking', text: thinking })
562
+ if (text) blocks.push({ type: 'text', text })
563
+ turn.beforeSave()
564
+ const row = appendMessage(this.db, this.chatId, 'assistant', {
565
+ blocks,
566
+ stopReason,
567
+ model: this.model,
568
+ ...(usage ? { usage } : {}),
569
+ })
570
+ turn.onAppended(row)
571
+ if (text) this.lastAssistantText = text
572
+ }
573
+
574
+ private handleUpdate(update: AcpSessionUpdate): void {
575
+ const turn = this.turn
576
+ if (!turn) return
577
+ switch (update.sessionUpdate) {
578
+ case 'agent_message_chunk': {
579
+ const text = textOf(update.content)
580
+ if (!text) return
581
+ this.text += text
582
+ turn.onDelta({ text })
583
+ return
584
+ }
585
+ case 'agent_thought_chunk': {
586
+ const text = textOf(update.content)
587
+ if (!text) return
588
+ this.thinking += text
589
+ turn.onDelta({ thinking: text })
590
+ return
591
+ }
592
+ case 'tool_call': {
593
+ const info = update as AcpSessionUpdate & AcpToolCall
594
+ this.applyTool(info, true)
595
+ return
596
+ }
597
+ case 'tool_call_update': {
598
+ const info = update as AcpSessionUpdate & AcpToolCallUpdate
599
+ this.applyTool(info, false)
600
+ return
601
+ }
602
+ case 'plan': {
603
+ const text = formatPlan(update.entries)
604
+ if (text) this.notice('plan', text)
605
+ return
606
+ }
607
+ default:
608
+ return
609
+ }
610
+ }
611
+
612
+ private applyTool(update: AcpToolCall | AcpToolCallUpdate, created: boolean): void {
613
+ const turn = this.turn
614
+ if (!turn) return
615
+ const callId = update.toolCallId
616
+ if (this.closedTools.has(callId)) {
617
+ this.attachLateDiff(update)
618
+ return
619
+ }
620
+ const previous = this.tools.get(callId)
621
+ if (!previous) {
622
+ if (!created) return
623
+ this.flushAssistant('tool_use')
624
+ }
625
+ const info: ToolState = {
626
+ ...(previous ?? { toolCallId: callId }),
627
+ ...update,
628
+ toolCallId: callId,
629
+ }
630
+ this.tools.set(callId, info)
631
+ if (!previous) {
632
+ const name = toolName(info)
633
+ const args = toolArgs(info)
634
+ turn.beforeSave()
635
+ const row = appendMessage(this.db, this.chatId, 'assistant', {
636
+ blocks: [{ type: 'tool_call', id: callId, name, args }],
637
+ stopReason: 'tool_use',
638
+ model: this.model,
639
+ })
640
+ turn.onAppended(row)
641
+ turn.onToolStarted(callId, name)
642
+ if (info.rawInput !== undefined) turn.onToolRunning(callId, args)
643
+ } else if (update.rawInput !== undefined) {
644
+ turn.onToolRunning(callId, toolArgs(info))
645
+ }
646
+ if (update.content) {
647
+ for (const block of update.content) {
648
+ const text = textOf(block)
649
+ if (text) turn.onToolOutput(callId, text)
650
+ }
651
+ }
652
+ if (info.status === 'completed' || info.status === 'failed') this.finalizeTool(callId)
653
+ }
654
+
655
+ private finalizeTool(callId: string): void {
656
+ const info = this.tools.get(callId)
657
+ if (!info) return
658
+ this.tools.delete(callId)
659
+ this.closedTools.add(callId)
660
+ const collected = this.collectDiffs(info)
661
+ const { revisions, path, abs } = collected
662
+ const details = this.toolDetails(info, path, collected.diffDetails, collected.skipped)
663
+ const text = this.toolText(info, false)
664
+ let rows: RevisionRow[] = []
665
+ let row: MessageRow
666
+ try {
667
+ row = this.db.transaction(() => {
668
+ const written = appendMessage(this.db, this.chatId, 'tool', {
669
+ toolCallId: callId,
670
+ text,
671
+ isError: info.status === 'failed',
672
+ }, details)
673
+ rows = revisions.length > 0 ? recordRevisions(this.db, this.chatId, written.id, revisions) : []
674
+ return written
675
+ })()
676
+ } catch (error) {
677
+ row = appendMessage(this.db, this.chatId, 'tool', {
678
+ toolCallId: callId,
679
+ text,
680
+ isError: info.status === 'failed',
681
+ }, {
682
+ ...details,
683
+ revisionError: error instanceof Error ? error.message : String(error),
684
+ })
685
+ }
686
+ this.rememberClosed(callId, row.id, info.kind, revisions.length > 0)
687
+ for (const revision of rows) this.turn?.onFileChanged(revision.path, revision.after_hash)
688
+ if (abs && path) this.turn?.onFileChanged(path, hashOnDisk(abs))
689
+ this.turn?.onAppended(row)
690
+ }
691
+
692
+ private writeToolRow(info: AcpToolCall, text: string, revisions: Revision[]): void {
693
+ const details = this.toolDetails(info, null, null, false)
694
+ const row = this.db.transaction(() => {
695
+ const written = appendMessage(this.db, this.chatId, 'tool', {
696
+ toolCallId: info.toolCallId,
697
+ text,
698
+ isError: true,
699
+ }, details)
700
+ if (revisions.length > 0) recordRevisions(this.db, this.chatId, written.id, revisions)
701
+ return written
702
+ })()
703
+ this.rememberClosed(info.toolCallId, row.id, info.kind, revisions.length > 0)
704
+ this.turn?.onAppended(row)
705
+ }
706
+
707
+ private toolDetails(
708
+ info: AcpToolCall,
709
+ path: string | null,
710
+ diff: ReturnType<typeof diffLines> | null,
711
+ revisionSkipped: boolean,
712
+ ): Record<string, unknown> {
713
+ const raw = safeStringify(info.rawOutput)
714
+ const rawValue =
715
+ raw.length <= ACP_RAW_LIMIT
716
+ ? info.rawOutput
717
+ : { truncated: true, text: raw.slice(0, ACP_RAW_LIMIT) }
718
+ const details: Record<string, unknown> = {
719
+ source: 'acp',
720
+ title: info.title,
721
+ name: toolName(info),
722
+ kind: info.kind,
723
+ status: info.status,
724
+ locations: info.locations,
725
+ rawInput: info.rawInput,
726
+ }
727
+ if (info.rawOutput !== undefined) details.rawOutput = rawValue
728
+ if (path) details.path = path
729
+ if (!path && (info.kind === 'read' || info.kind === 'search' || info.kind === 'edit' || info.kind === 'delete' || info.kind === 'move')) {
730
+ const inferred = toolPath(info)
731
+ if (inferred) {
732
+ try {
733
+ details.path = this.hostPath(inferred).rel
734
+ } catch {
735
+ details.path = inferred
736
+ }
737
+ }
738
+ }
739
+ if (info.kind === 'execute') {
740
+ const output = executeOutput(info)
741
+ details.command = commandOf(info)
742
+ if (output) details.output = output
743
+ const code = executeExitCode(info)
744
+ if (code !== null) details.exitCode = code
745
+ }
746
+ if (info.kind === 'search') details.pattern = searchPattern(info)
747
+ if (diff) details.diff = diff
748
+ if (revisionSkipped) details.revisionSkipped = 'too large'
749
+ return details
750
+ }
751
+
752
+ private toolText(info: AcpToolCall, aborted: boolean): string {
753
+ if (aborted) return 'Aborted by user'
754
+ const parts: string[] = []
755
+ for (const block of info.content ?? []) {
756
+ const text = textOf(block)
757
+ if (text) parts.push(text)
758
+ }
759
+ if (parts.length === 0) {
760
+ if (info.kind === 'execute') {
761
+ const output = executeOutput(info)
762
+ if (output) parts.push(output)
763
+ } else if (info.rawOutput !== undefined) {
764
+ const raw = safeStringify(info.rawOutput)
765
+ if (raw) parts.push(raw)
766
+ }
767
+ }
768
+ return clip(parts.join('\n'), ACP_TOOL_TEXT_LIMIT)
769
+ }
770
+
771
+ private collectDiffs(info: AcpToolCall): CollectedDiff {
772
+ const revisions: Revision[] = []
773
+ let skipped = false
774
+ let diffDetails: ReturnType<typeof diffLines> | null = null
775
+ let path: string | null = null
776
+ let abs: string | null = null
777
+ if (info.kind === 'delete' || info.kind === 'move') {
778
+ return { revisions, skipped, diffDetails, path, abs }
779
+ }
780
+ for (const block of info.content ?? []) {
781
+ if (block.type !== 'diff') continue
782
+ const diff = block as AcpDiffContent
783
+ let resolved
784
+ try {
785
+ resolved = this.hostPath(diff.path)
786
+ } catch {
787
+ continue
788
+ }
789
+ const before = diff.oldText == null ? null : new TextEncoder().encode(diff.oldText)
790
+ const after = new TextEncoder().encode(diff.newText)
791
+ path = resolved.rel
792
+ abs = resolved.abs
793
+ if ((before && before.byteLength > BLOB_LIMIT) || after.byteLength > BLOB_LIMIT) {
794
+ skipped = true
795
+ continue
796
+ }
797
+ revisions.push({ path: resolved.rel, before, after })
798
+ const full = diffLines(diff.oldText ?? null, diff.newText)
799
+ diffDetails =
800
+ JSON.stringify(full).length <= ACP_RAW_LIMIT
801
+ ? full
802
+ : { added: full.added, removed: full.removed, hunks: [] }
803
+ }
804
+ return { revisions, skipped, diffDetails, path, abs }
805
+ }
806
+
807
+ /** A diff can arrive in an update after the tool row was already written. */
808
+ private attachLateDiff(update: AcpToolCall | AcpToolCallUpdate): void {
809
+ const stored = this.toolMessages.get(update.toolCallId)
810
+ if (!stored || this.revisedCalls.has(update.toolCallId)) return
811
+ const info: AcpToolCall = {
812
+ ...update,
813
+ kind: update.kind ?? stored.kind,
814
+ }
815
+ const collected = this.collectDiffs(info)
816
+ if (collected.revisions.length === 0) return
817
+ let rows: RevisionRow[] = []
818
+ try {
819
+ rows = recordRevisions(this.db, this.chatId, stored.messageId, collected.revisions)
820
+ } catch {
821
+ return
822
+ }
823
+ this.revisedCalls.add(update.toolCallId)
824
+ for (const revision of rows) this.turn?.onFileChanged(revision.path, revision.after_hash)
825
+ if (collected.abs && collected.path) this.turn?.onFileChanged(collected.path, hashOnDisk(collected.abs))
826
+ }
827
+
828
+ private rememberClosed(
829
+ callId: string,
830
+ messageId: string,
831
+ kind: AcpToolKind | undefined,
832
+ revised: boolean,
833
+ ): void {
834
+ this.toolMessages.set(callId, { messageId, ...(kind === undefined ? {} : { kind }) })
835
+ if (revised) this.revisedCalls.add(callId)
836
+ }
837
+
838
+ private onRequest(method: string, params: unknown): unknown {
839
+ if (this.disposed) {
840
+ if (method === 'session/request_permission') return { outcome: { outcome: 'cancelled' } }
841
+ if (method === 'cursor/ask_question' || method === 'cursor/create_plan') {
842
+ return { outcome: { outcome: 'cancelled' } }
843
+ }
844
+ return {}
845
+ }
846
+ if (method === 'session/request_permission') {
847
+ return this.permission(params)
848
+ }
849
+ if (method === 'cursor/ask_question') {
850
+ return this.askQuestion(params)
851
+ }
852
+ if (method === 'cursor/create_plan') {
853
+ return this.createPlan(params)
854
+ }
855
+ if (method === 'cursor/update_todos') {
856
+ this.updateTodos(params)
857
+ return {}
858
+ }
859
+ throw new AcpError(`Method not found: ${method}`, -32601)
860
+ }
861
+
862
+ private onNotification(method: string, params: unknown): void {
863
+ if (this.disposed) return
864
+ if (method === 'session/update') {
865
+ const envelope = typeof params === 'object' && params !== null ? params as { update?: unknown } : null
866
+ const update = envelope?.update
867
+ if (
868
+ typeof update === 'object' &&
869
+ update !== null &&
870
+ (update as { sessionUpdate?: unknown }).sessionUpdate === 'config_option_update'
871
+ ) {
872
+ const next = parseAcpConfigOptions(update)
873
+ if (next.length > 0) this.options = next
874
+ }
875
+ if (this.loading || !this.turn) return
876
+ if (
877
+ typeof update === 'object' &&
878
+ update !== null &&
879
+ typeof (update as { sessionUpdate?: unknown }).sessionUpdate === 'string'
880
+ ) {
881
+ this.handleUpdate(update as AcpSessionUpdate)
882
+ }
883
+ return
884
+ }
885
+ if (method === 'cursor/update_todos') {
886
+ this.updateTodos(params)
887
+ }
888
+ }
889
+
890
+ private permission(params: unknown): unknown {
891
+ if (typeof params !== 'object' || params === null) {
892
+ return { outcome: { outcome: 'cancelled' } }
893
+ }
894
+ const request = params as AcpPermissionRequest
895
+ const options = Array.isArray(request.options) ? request.options : []
896
+ const selected =
897
+ options.find((option) => option.kind === 'allow_once') ??
898
+ options.find((option) => option.kind === 'allow_always') ??
899
+ options.find((option) => typeof option.kind === 'string' && option.kind.startsWith('allow_'))
900
+ const title = request.toolCall?.title ?? 'инструмент'
901
+ if (!selected) {
902
+ this.notice('permission', `Разрешение не выдано: ${title}`)
903
+ return { outcome: { outcome: 'cancelled' } }
904
+ }
905
+ this.notice('permission', `Разрешение выдано автоматически: ${title}`)
906
+ return { outcome: { outcome: 'selected', optionId: selected.optionId } }
907
+ }
908
+
909
+ private askQuestion(params: unknown): Promise<unknown> {
910
+ if (!this.turn) return Promise.resolve({ outcome: { outcome: 'cancelled' } })
911
+ const input = params as AcpAskQuestionParams
912
+ if (!input || !Array.isArray(input.questions)) {
913
+ throw new AcpError('Некорректные параметры вопроса', -32602)
914
+ }
915
+ const question: AcpQuestion = {
916
+ kind: 'questions',
917
+ id: input.toolCallId ?? crypto.randomUUID(),
918
+ title: input.title ?? 'Вопрос агента',
919
+ questions: input.questions.map((item) => ({
920
+ id: item.id,
921
+ prompt: item.prompt,
922
+ options: (item.options ?? []).map((option) => ({ id: option.id, label: option.label })),
923
+ ...(item.allowMultiple === undefined ? {} : { allowMultiple: item.allowMultiple }),
924
+ })),
925
+ }
926
+ return new Promise((resolve) => {
927
+ this.enqueueQuestion({
928
+ question,
929
+ resolve,
930
+ validate: (answer) => validateQuestionAnswer(question, answer),
931
+ })
932
+ })
933
+ }
934
+
935
+ private createPlan(params: unknown): Promise<unknown> {
936
+ if (!this.turn) return Promise.resolve({ outcome: { outcome: 'cancelled' } })
937
+ const input = params as AcpCreatePlanParams
938
+ if (!input || typeof input.plan !== 'string') {
939
+ throw new AcpError('Некорректные параметры плана', -32602)
940
+ }
941
+ const question: AcpQuestion = {
942
+ kind: 'plan',
943
+ id: input.toolCallId ?? crypto.randomUUID(),
944
+ title: input.name ?? 'План агента',
945
+ overview: input.overview,
946
+ plan: input.plan,
947
+ todos: sanitizeTodos(input.todos),
948
+ isProject: input.isProject,
949
+ }
950
+ return new Promise((resolve) => {
951
+ this.enqueueQuestion({
952
+ question,
953
+ resolve,
954
+ validate: (answer) => validatePlanAnswer(answer),
955
+ })
956
+ })
957
+ }
958
+
959
+ private updateTodos(params: unknown): void {
960
+ const input = params as AcpUpdateTodosParams
961
+ const todos = sanitizeTodos(input?.todos)
962
+ if (!todos) return
963
+ if (input.merge === true) {
964
+ const byId = new Map(this.todos.map((todo) => [todo.id, todo]))
965
+ for (const todo of todos) byId.set(todo.id, todo)
966
+ this.todos = [...byId.values()]
967
+ } else {
968
+ this.todos = todos
969
+ }
970
+ const text = formatTodos(this.todos)
971
+ if (text) this.notice('plan', text)
972
+ }
973
+
974
+ private enqueueQuestion(item: PendingQuestion): void {
975
+ if (this.currentQuestion === null) {
976
+ this.currentQuestion = item
977
+ this.turn?.onQuestion(item.question)
978
+ } else {
979
+ this.pending.push(item)
980
+ }
981
+ }
982
+
983
+ private publishNextQuestion(): void {
984
+ const next = this.pending.shift() ?? null
985
+ this.currentQuestion = next
986
+ this.turn?.onQuestion(next?.question ?? null)
987
+ }
988
+
989
+ private cancelQuestions(): void {
990
+ const items = [this.currentQuestion, ...this.pending].filter(
991
+ (item): item is PendingQuestion => item !== null,
992
+ )
993
+ this.currentQuestion = null
994
+ this.pending = []
995
+ for (const item of items) {
996
+ item.resolve({ outcome: { outcome: 'cancelled' } })
997
+ }
998
+ this.turn?.onQuestion(null)
999
+ }
1000
+
1001
+ private notice(kind: string, text: string): void {
1002
+ if (this.disposed || !text || text === this.lastNotice) return
1003
+ const turn = this.turn
1004
+ if (!turn) return
1005
+ this.lastNotice = text
1006
+ turn.beforeSave()
1007
+ const row = appendMessage(this.db, this.chatId, 'notice', { kind, text })
1008
+ turn.onAppended(row)
1009
+ }
1010
+
1011
+ private agentCwd(): string | undefined {
1012
+ return acpOverride(this.db).cwd ?? this.config.acpCwd
1013
+ }
1014
+
1015
+ private agentRoot(): string {
1016
+ return this.agentCwd() ?? this.root
1017
+ }
1018
+
1019
+ /** Maps a path reported by a remote-capable agent back into the workspace jail. */
1020
+ private hostPath(input: string): ReturnType<typeof resolveInRoot> {
1021
+ const root = this.agentCwd()
1022
+ if (!root) return resolveInRoot(this.root, input)
1023
+ const base = root.replaceAll('\\', '/').replace(/\/+$/, '')
1024
+ const value = input.replaceAll('\\', '/')
1025
+ if (value === base) return resolveInRoot(this.root, '.')
1026
+ if (value.startsWith(`${base}/`)) return resolveInRoot(this.root, value.slice(base.length + 1))
1027
+ return resolveInRoot(this.root, input)
1028
+ }
1029
+
1030
+ private withStderr(message: string): string {
1031
+ const tail = this.connection?.stderrTail || this.lastStderr
1032
+ return tail ? `${message}. ${tail}` : message
1033
+ }
1034
+
1035
+ private scheduleIdle(): void {
1036
+ clearTimeout(this.idleTimer)
1037
+ this.idleTimer = setTimeout(() => {
1038
+ this.idleTimer = undefined
1039
+ stopAcpSession(this.chatId)
1040
+ }, ACP_IDLE_MS)
1041
+ }
1042
+ }
1043
+
1044
+ function isAuthRequired(error: unknown): boolean {
1045
+ return (
1046
+ error instanceof AcpError &&
1047
+ error.code === -32000 &&
1048
+ /authentication required|auth required/i.test(error.message)
1049
+ )
1050
+ }
1051
+
1052
+ function textOf(content: AcpContentBlock | undefined): string {
1053
+ return content && content.type === 'text' && typeof content.text === 'string' ? content.text : ''
1054
+ }
1055
+
1056
+ function clip(text: string, limit: number): string {
1057
+ if (text.length <= limit) return text
1058
+ let body = text.slice(0, limit)
1059
+ const last = body.charCodeAt(body.length - 1)
1060
+ if (last >= 0xd800 && last <= 0xdbff) body = body.slice(0, -1)
1061
+ return body
1062
+ }
1063
+
1064
+ function safeStringify(value: unknown): string {
1065
+ if (value === undefined) return ''
1066
+ if (typeof value === 'string') return value
1067
+ try {
1068
+ return JSON.stringify(value) ?? ''
1069
+ } catch {
1070
+ return String(value)
1071
+ }
1072
+ }
1073
+
1074
+ function toolName(info: AcpToolCall): string {
1075
+ if (info.kind === 'execute') return 'bash'
1076
+ if (info.kind === 'read') return 'read'
1077
+ if (info.kind === 'search') {
1078
+ const hint = `${info.title ?? ''} ${info.kind}`.toLowerCase()
1079
+ return hint.includes('glob') ? 'glob' : 'grep'
1080
+ }
1081
+ if (info.kind === 'edit' || info.kind === 'delete' || info.kind === 'move') return 'edit'
1082
+ return info.title ?? info.kind ?? 'tool'
1083
+ }
1084
+
1085
+ function toolPath(info: AcpToolCall): string | null {
1086
+ const location = info.locations?.[0]?.path
1087
+ if (typeof location === 'string' && location) return location
1088
+ const raw = info.rawInput
1089
+ if (typeof raw === 'object' && raw !== null) {
1090
+ const path = (raw as { path?: unknown }).path
1091
+ if (typeof path === 'string' && path) return path
1092
+ }
1093
+ return null
1094
+ }
1095
+
1096
+ function toolArgs(info: AcpToolCall): unknown {
1097
+ const raw = typeof info.rawInput === 'object' && info.rawInput !== null
1098
+ ? info.rawInput as Record<string, unknown>
1099
+ : {}
1100
+ if (info.kind === 'execute') return { command: commandOf(info) }
1101
+ if (info.kind === 'read') return { path: toolPath(info) ?? '' }
1102
+ if (info.kind === 'search') {
1103
+ const pattern = searchPattern(info)
1104
+ const path = toolPath(info)
1105
+ return path ? { pattern, path } : { pattern }
1106
+ }
1107
+ if (info.kind === 'edit' || info.kind === 'delete' || info.kind === 'move') {
1108
+ return { path: toolPath(info) ?? '' }
1109
+ }
1110
+ return info.rawInput ?? raw
1111
+ }
1112
+
1113
+ function commandOf(info: AcpToolCall): string {
1114
+ const raw = info.rawInput
1115
+ if (typeof raw === 'object' && raw !== null) {
1116
+ const command = (raw as { command?: unknown }).command
1117
+ if (typeof command === 'string') return command
1118
+ }
1119
+ return info.title ?? ''
1120
+ }
1121
+
1122
+ function searchPattern(info: AcpToolCall): string {
1123
+ const raw = info.rawInput
1124
+ if (typeof raw === 'object' && raw !== null) {
1125
+ const value = (raw as { pattern?: unknown; query?: unknown }).pattern ?? (raw as { query?: unknown }).query
1126
+ if (typeof value === 'string') return value
1127
+ }
1128
+ return info.title ?? ''
1129
+ }
1130
+
1131
+ function executeOutput(info: AcpToolCall): string {
1132
+ const raw = info.rawOutput
1133
+ if (typeof raw === 'string') return raw
1134
+ if (typeof raw !== 'object' || raw === null) return ''
1135
+ const value = raw as { stdout?: unknown; stderr?: unknown; exitCode?: unknown }
1136
+ const stdout = typeof value.stdout === 'string' ? value.stdout : ''
1137
+ const stderr = typeof value.stderr === 'string' ? value.stderr : ''
1138
+ const parts = [stdout, stderr].filter(Boolean)
1139
+ if (typeof value.exitCode === 'number' && !parts.some((part) => part.includes('[exit code:'))) {
1140
+ parts.push(`[exit code: ${value.exitCode}]`)
1141
+ }
1142
+ return parts.join('\n')
1143
+ }
1144
+
1145
+ function executeExitCode(info: AcpToolCall): number | null {
1146
+ const raw = info.rawOutput
1147
+ if (typeof raw !== 'object' || raw === null) return null
1148
+ const code = (raw as { exitCode?: unknown }).exitCode
1149
+ return typeof code === 'number' ? code : null
1150
+ }
1151
+
1152
+ function sanitizeTodos(value: unknown): AcpPlanTodo[] | undefined {
1153
+ if (!Array.isArray(value)) return undefined
1154
+ const todos: AcpPlanTodo[] = []
1155
+ for (const raw of value) {
1156
+ if (typeof raw !== 'object' || raw === null) continue
1157
+ const item = raw as Record<string, unknown>
1158
+ if (typeof item.id !== 'string' || typeof item.content !== 'string') continue
1159
+ const status = item.status
1160
+ if (
1161
+ status !== 'pending' &&
1162
+ status !== 'in_progress' &&
1163
+ status !== 'completed' &&
1164
+ status !== 'cancelled'
1165
+ ) {
1166
+ continue
1167
+ }
1168
+ todos.push({ id: item.id, content: item.content, status })
1169
+ }
1170
+ return todos
1171
+ }
1172
+
1173
+ function formatTodos(todos: AcpPlanTodo[]): string {
1174
+ return todos.map((todo) => formatTodo(todo)).join('\n')
1175
+ }
1176
+
1177
+ function formatPlan(entries: AcpPlanEntry[]): string {
1178
+ if (!Array.isArray(entries)) return ''
1179
+ return entries.map((entry) => formatTodo(entry)).join('\n')
1180
+ }
1181
+
1182
+ function formatTodo(entry: { content: string; status: string }): string {
1183
+ const mark = entry.status === 'completed' ? '[x]' : entry.status === 'in_progress' ? '[~]' : '[ ]'
1184
+ return `${mark} ${entry.content}`
1185
+ }
1186
+
1187
+ function validateQuestionAnswer(question: Extract<AcpQuestion, { kind: 'questions' }>, answer: AcpAnswer): AnswerResult {
1188
+ if (typeof answer !== 'object' || answer === null) return { ok: false, error: 'Некорректный ответ' }
1189
+ if ('skipped' in answer && answer.skipped === true) {
1190
+ return { ok: true, result: { outcome: { outcome: 'skipped' } } }
1191
+ }
1192
+ if (!('answers' in answer) || !Array.isArray(answer.answers)) {
1193
+ return { ok: false, error: 'Нужен answers или skipped' }
1194
+ }
1195
+ if (answer.answers.length === 0) {
1196
+ return { ok: true, result: { outcome: { outcome: 'skipped' } } }
1197
+ }
1198
+ const byId = new Map(question.questions.map((item) => [item.id, item]))
1199
+ for (const item of answer.answers) {
1200
+ if (
1201
+ typeof item !== 'object' ||
1202
+ item === null ||
1203
+ typeof item.questionId !== 'string' ||
1204
+ !Array.isArray(item.selectedOptionIds) ||
1205
+ !item.selectedOptionIds.every((selected) => typeof selected === 'string')
1206
+ ) {
1207
+ return { ok: false, error: 'Некорректный ответ на вопрос' }
1208
+ }
1209
+ const target = byId.get(item.questionId)
1210
+ if (!target) return { ok: false, error: `Неизвестный вопрос: ${item.questionId}` }
1211
+ const options = new Set(target.options.map((option) => option.id))
1212
+ for (const selected of item.selectedOptionIds) {
1213
+ if (!options.has(selected)) return { ok: false, error: `Неизвестный вариант: ${selected}` }
1214
+ }
1215
+ if (target.allowMultiple !== true && item.selectedOptionIds.length > 1) {
1216
+ return { ok: false, error: `Можно выбрать только один вариант: ${target.prompt}` }
1217
+ }
1218
+ }
1219
+ return {
1220
+ ok: true,
1221
+ result: {
1222
+ outcome: {
1223
+ outcome: 'answered',
1224
+ answers: answer.answers.map((item) => ({
1225
+ questionId: item.questionId,
1226
+ selectedOptionIds: item.selectedOptionIds,
1227
+ })),
1228
+ },
1229
+ },
1230
+ }
1231
+ }
1232
+
1233
+ function validatePlanAnswer(answer: AcpAnswer): AnswerResult {
1234
+ if (typeof answer !== 'object' || answer === null) return { ok: false, error: 'Некорректный ответ' }
1235
+ if ('accepted' in answer && typeof answer.accepted === 'boolean') {
1236
+ return {
1237
+ ok: true,
1238
+ result: {
1239
+ outcome: answer.accepted
1240
+ ? { outcome: 'accepted' }
1241
+ : { outcome: 'rejected', ...(answer.reason ? { reason: answer.reason } : {}) },
1242
+ },
1243
+ }
1244
+ }
1245
+ if ('skipped' in answer && answer.skipped === true) {
1246
+ return { ok: true, result: { outcome: { outcome: 'rejected', reason: 'Пропущено' } } }
1247
+ }
1248
+ return { ok: false, error: 'Нужен accepted или skipped' }
1249
+ }