@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,408 @@
1
+ import { writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ type Message = {
5
+ jsonrpc?: string
6
+ id?: number | string
7
+ method?: string
8
+ params?: unknown
9
+ result?: unknown
10
+ error?: unknown
11
+ }
12
+
13
+ let nextId = 1
14
+ let cancelPrompt: (() => void) | null = null
15
+ let sessionCwd = process.cwd()
16
+ let configOptions: Array<Record<string, unknown>> = [
17
+ {
18
+ configId: 'model',
19
+ name: 'Model',
20
+ category: 'model',
21
+ type: 'select',
22
+ currentValue: 'auto',
23
+ options: [
24
+ { value: 'auto', name: 'Auto' },
25
+ { value: 'composer', name: 'Composer' },
26
+ ],
27
+ },
28
+ {
29
+ configId: 'thought',
30
+ name: 'Effort',
31
+ category: 'thought_level',
32
+ type: 'select',
33
+ currentValue: 'medium',
34
+ options: [
35
+ { value: 'low', name: 'Low' },
36
+ { value: 'medium', name: 'Medium' },
37
+ { value: 'high', name: 'High' },
38
+ ],
39
+ },
40
+ {
41
+ configId: 'fast',
42
+ name: 'Fast',
43
+ category: 'model_config',
44
+ type: 'boolean',
45
+ currentValue: false,
46
+ },
47
+ ]
48
+ const pending = new Map<number, (message: Message) => void>()
49
+
50
+ function send(message: Message): void {
51
+ process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`)
52
+ }
53
+
54
+ function respond(id: number | string, result: unknown): void {
55
+ send({ id, result })
56
+ }
57
+
58
+ function request(method: string, params: unknown): Promise<Message> {
59
+ const id = nextId++
60
+ send({ id, method, params })
61
+ return new Promise((resolve) => pending.set(id, resolve))
62
+ }
63
+
64
+ function textOf(params: unknown): string {
65
+ if (typeof params !== 'object' || params === null) return ''
66
+ const prompt = (params as { prompt?: unknown }).prompt
67
+ if (!Array.isArray(prompt)) return ''
68
+ return prompt
69
+ .map((block) => {
70
+ if (typeof block !== 'object' || block === null) return ''
71
+ const text = (block as { text?: unknown }).text
72
+ return typeof text === 'string' ? text : ''
73
+ })
74
+ .join('\n')
75
+ }
76
+
77
+ function update(params: unknown): void {
78
+ send({ method: 'session/update', params })
79
+ }
80
+
81
+ function chunk(text: string): void {
82
+ update({ update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text } } })
83
+ }
84
+
85
+ function thought(text: string): void {
86
+ update({ update: { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text } } })
87
+ }
88
+
89
+ async function prompt(id: number | string, params: unknown): Promise<void> {
90
+ const text = textOf(params)
91
+ if (text.includes('slow-tool')) {
92
+ chunk('slow-start')
93
+ update({
94
+ update: {
95
+ sessionUpdate: 'tool_call',
96
+ toolCallId: 'slow-1',
97
+ title: 'Долгий инструмент',
98
+ kind: 'read',
99
+ status: 'in_progress',
100
+ rawInput: { path: 'x.txt' },
101
+ },
102
+ })
103
+ cancelPrompt = () => {
104
+ cancelPrompt = null
105
+ respond(id, { stopReason: 'cancelled' })
106
+ }
107
+ return
108
+ }
109
+ if (text.includes('slow')) {
110
+ chunk('slow-start')
111
+ cancelPrompt = () => {
112
+ cancelPrompt = null
113
+ respond(id, { stopReason: 'cancelled' })
114
+ }
115
+ return
116
+ }
117
+ if (text.includes('hang')) {
118
+ cancelPrompt = () => {
119
+ cancelPrompt = null
120
+ }
121
+ return
122
+ }
123
+ if (text.includes('question')) {
124
+ const answer = (await request('cursor/ask_question', {
125
+ toolCallId: 'q1',
126
+ title: 'Выбери вариант',
127
+ questions: [
128
+ {
129
+ id: 'first',
130
+ prompt: 'Какой вариант?',
131
+ options: [
132
+ { id: 'a', label: 'A' },
133
+ { id: 'b', label: 'B' },
134
+ ],
135
+ },
136
+ ],
137
+ })) as {
138
+ result?: { outcome?: { outcome?: string; answers?: Array<{ selectedOptionIds?: string[] }> } }
139
+ }
140
+ const picked = answer.result?.outcome?.answers?.[0]?.selectedOptionIds ?? []
141
+ chunk(`picked:${picked.join(',')}`)
142
+ respond(id, { stopReason: 'end_turn', usage: { inputTokens: 2, outputTokens: 1 } })
143
+ return
144
+ }
145
+ if (text.includes('plan')) {
146
+ const answer = (await request('cursor/create_plan', {
147
+ toolCallId: 'plan-1',
148
+ name: 'План проверки',
149
+ overview: 'Короткий обзор',
150
+ plan: '1. Сделать\n2. Проверить',
151
+ todos: [
152
+ { id: 't1', content: 'Сделать', status: 'pending' },
153
+ { id: 't2', content: 'Проверить', status: 'pending' },
154
+ ],
155
+ })) as { result?: { outcome?: { outcome?: string } } }
156
+ chunk(`plan:${answer.result?.outcome?.outcome ?? 'none'}`)
157
+ respond(id, { stopReason: 'end_turn' })
158
+ return
159
+ }
160
+ if (text.includes('permission')) {
161
+ const answer = (await request('session/request_permission', {
162
+ sessionId: 'fake-session',
163
+ toolCall: { toolCallId: 'perm-1', title: 'Запустить команду' },
164
+ options: [
165
+ { optionId: 'allow-once', name: 'Разрешить', kind: 'allow_once' },
166
+ { optionId: 'reject-once', name: 'Отклонить', kind: 'reject_once' },
167
+ ],
168
+ })) as { result?: { outcome?: { optionId?: string } } }
169
+ chunk(`perm:${answer.result?.outcome?.optionId ?? 'none'}`)
170
+ respond(id, { stopReason: 'end_turn' })
171
+ return
172
+ }
173
+ if (text.includes('cwd-check')) {
174
+ chunk(`cwd:${sessionCwd}`)
175
+ respond(id, { stopReason: 'end_turn' })
176
+ return
177
+ }
178
+ if (text.includes('diff-late')) {
179
+ const abs = join(process.cwd(), 'late.txt')
180
+ writeFileSync(abs, 'after\n', 'utf8')
181
+ update({
182
+ update: {
183
+ sessionUpdate: 'tool_call',
184
+ toolCallId: 'late-1',
185
+ title: 'Правка late.txt',
186
+ kind: 'other',
187
+ status: 'completed',
188
+ rawInput: { path: 'late.txt' },
189
+ },
190
+ })
191
+ update({
192
+ update: {
193
+ sessionUpdate: 'tool_call_update',
194
+ toolCallId: 'late-1',
195
+ content: [{ type: 'diff', path: join(sessionCwd, 'late.txt'), oldText: 'before\n', newText: 'after\n' }],
196
+ },
197
+ })
198
+ chunk('edited-late')
199
+ respond(id, { stopReason: 'end_turn' })
200
+ return
201
+ }
202
+ if (text.includes('diff-plain')) {
203
+ const abs = join(process.cwd(), 'plain.txt')
204
+ writeFileSync(abs, 'after\n', 'utf8')
205
+ update({
206
+ update: {
207
+ sessionUpdate: 'tool_call',
208
+ toolCallId: 'plain-1',
209
+ title: 'Правка plain.txt',
210
+ status: 'completed',
211
+ rawInput: { path: 'plain.txt' },
212
+ content: [{ type: 'diff', path: join(sessionCwd, 'plain.txt'), oldText: 'before\n', newText: 'after\n' }],
213
+ },
214
+ })
215
+ chunk('edited-plain')
216
+ respond(id, { stopReason: 'end_turn' })
217
+ return
218
+ }
219
+ if (text.includes('diff-delete')) {
220
+ update({
221
+ update: {
222
+ sessionUpdate: 'tool_call',
223
+ toolCallId: 'del-1',
224
+ title: 'Удалить gone.txt',
225
+ kind: 'delete',
226
+ status: 'completed',
227
+ rawInput: { path: 'gone.txt' },
228
+ content: [{ type: 'diff', path: 'gone.txt', oldText: 'before\n', newText: '' }],
229
+ },
230
+ })
231
+ chunk('deleted')
232
+ respond(id, { stopReason: 'end_turn' })
233
+ return
234
+ }
235
+ if (text.includes('both-output')) {
236
+ update({
237
+ update: {
238
+ sessionUpdate: 'tool_call',
239
+ toolCallId: 'both-1',
240
+ title: 'Прочитать',
241
+ kind: 'read',
242
+ status: 'completed',
243
+ rawInput: { path: 'x.txt' },
244
+ content: [{ type: 'text', text: 'from-content' }],
245
+ rawOutput: 'from-raw',
246
+ },
247
+ })
248
+ respond(id, { stopReason: 'end_turn' })
249
+ return
250
+ }
251
+ if (text.includes('max-steps')) {
252
+ chunk('partial')
253
+ respond(id, { stopReason: 'max_turn_requests' })
254
+ return
255
+ }
256
+ if (text.includes('diff')) {
257
+ const abs = join(process.cwd(), 'file.txt')
258
+ writeFileSync(abs, 'after\n', 'utf8')
259
+ update({
260
+ update: {
261
+ sessionUpdate: 'tool_call',
262
+ toolCallId: 'diff-1',
263
+ title: 'Редактировать file.txt',
264
+ kind: 'edit',
265
+ status: 'in_progress',
266
+ rawInput: { path: 'file.txt' },
267
+ locations: [{ path: 'file.txt' }],
268
+ },
269
+ })
270
+ update({
271
+ update: {
272
+ sessionUpdate: 'tool_call_update',
273
+ toolCallId: 'diff-1',
274
+ status: 'completed',
275
+ content: [{ type: 'diff', path: join(sessionCwd, 'file.txt'), oldText: 'before\n', newText: 'after\n' }],
276
+ },
277
+ })
278
+ chunk('edited')
279
+ respond(id, { stopReason: 'end_turn', usage: { inputTokens: 4, outputTokens: 2 } })
280
+ return
281
+ }
282
+ thought('думаю')
283
+ chunk('hello')
284
+ update({
285
+ update: {
286
+ sessionUpdate: 'tool_call',
287
+ toolCallId: 't1',
288
+ title: 'Прочитать x.txt',
289
+ kind: 'read',
290
+ status: 'in_progress',
291
+ rawInput: { path: 'x.txt' },
292
+ locations: [{ path: 'x.txt' }],
293
+ },
294
+ })
295
+ update({
296
+ update: {
297
+ sessionUpdate: 'tool_call_update',
298
+ toolCallId: 't1',
299
+ status: 'completed',
300
+ content: [{ type: 'text', text: 'x contents' }],
301
+ },
302
+ })
303
+ chunk('done')
304
+ respond(id, { stopReason: 'end_turn', usage: { inputTokens: 3, outputTokens: 5 } })
305
+ }
306
+
307
+ async function handleRequest(message: Message): Promise<void> {
308
+ const id = message.id
309
+ if (id === undefined) return
310
+ switch (message.method) {
311
+ case 'initialize':
312
+ if (process.argv.includes('stall-init')) await Bun.sleep(60_000)
313
+ respond(id, {
314
+ protocolVersion: 1,
315
+ agentCapabilities: { loadSession: true },
316
+ authMethods: process.argv.includes('no-auth-method')
317
+ ? [{ id: 'a' }, { id: 'b' }]
318
+ : [{ id: 'cursor_login' }],
319
+ })
320
+ return
321
+ case 'authenticate':
322
+ respond(id, {})
323
+ return
324
+ case 'session/new': {
325
+ if (process.argv.includes('no-auth-method')) {
326
+ send({ id, error: { code: -32000, message: 'Authentication required' } })
327
+ return
328
+ }
329
+ if (typeof message.params === 'object' && message.params !== null) {
330
+ const cwd = (message.params as { cwd?: unknown }).cwd
331
+ if (typeof cwd === 'string' && cwd) sessionCwd = cwd
332
+ }
333
+ respond(id, { sessionId: 'fake-session', configOptions })
334
+ return
335
+ }
336
+ case 'session/load': {
337
+ if (typeof message.params === 'object' && message.params !== null) {
338
+ const cwd = (message.params as { cwd?: unknown }).cwd
339
+ if (typeof cwd === 'string' && cwd) sessionCwd = cwd
340
+ }
341
+ update({
342
+ update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: 'replayed' } },
343
+ })
344
+ respond(id, { configOptions })
345
+ return
346
+ }
347
+ case 'session/set_config_option': {
348
+ const params = message.params
349
+ const configId = typeof params === 'object' && params !== null ? (params as { configId?: unknown }).configId : null
350
+ const value = typeof params === 'object' && params !== null ? (params as { value?: unknown }).value : null
351
+ const option = configOptions.find((item) => item.configId === configId)
352
+ const choices = Array.isArray(option?.options) ? option.options : []
353
+ const allowed =
354
+ option?.type === 'boolean'
355
+ ? typeof value === 'boolean'
356
+ : typeof value === 'string' && choices.some((choice) => (choice as { value?: unknown }).value === value)
357
+ if (!option || !allowed) {
358
+ send({ id, error: { code: -32602, message: 'Invalid params' } })
359
+ return
360
+ }
361
+ option.currentValue = value
362
+ respond(id, { configOptions })
363
+ return
364
+ }
365
+ case 'session/prompt':
366
+ void prompt(id, message.params)
367
+ return
368
+ default:
369
+ send({ id, error: { code: -32601, message: `Method not found: ${message.method}` } })
370
+ }
371
+ }
372
+
373
+ async function main(): Promise<void> {
374
+ const reader = Bun.stdin.stream().getReader()
375
+ const decoder = new TextDecoder()
376
+ let buffer = ''
377
+ for (;;) {
378
+ const { done, value } = await reader.read()
379
+ if (done) break
380
+ buffer += decoder.decode(value, { stream: true })
381
+ for (;;) {
382
+ const newline = buffer.indexOf('\n')
383
+ if (newline < 0) break
384
+ const line = buffer.slice(0, newline).replace(/\r$/, '')
385
+ buffer = buffer.slice(newline + 1)
386
+ if (!line.trim()) continue
387
+ let message: Message
388
+ try {
389
+ message = JSON.parse(line) as Message
390
+ } catch {
391
+ continue
392
+ }
393
+ if (typeof message.method === 'string' && message.id !== undefined) {
394
+ void handleRequest(message)
395
+ } else if (typeof message.method === 'string') {
396
+ if (message.method === 'session/cancel') cancelPrompt?.()
397
+ } else if (message.id !== undefined) {
398
+ const resolve = pending.get(Number(message.id))
399
+ if (resolve) {
400
+ pending.delete(Number(message.id))
401
+ resolve(message)
402
+ }
403
+ }
404
+ }
405
+ }
406
+ }
407
+
408
+ if (import.meta.main) await main()
@@ -0,0 +1,167 @@
1
+ export const PROTOCOL_VERSION = 1
2
+
3
+ export type JsonRpcId = string | number
4
+
5
+ export type AcpStopReason = 'end_turn' | 'max_tokens' | 'max_turn_requests' | 'refusal' | 'cancelled'
6
+
7
+ export type AcpUsage = {
8
+ inputTokens?: number
9
+ outputTokens?: number
10
+ totalTokens?: number
11
+ }
12
+
13
+ export type AcpTextContent = { type: 'text'; text: string }
14
+ export type AcpImageContent = { type: 'image'; mimeType?: string; data?: string; uri?: string }
15
+ export type AcpResourceLink = { type: 'resource_link'; uri?: string; name?: string; mimeType?: string }
16
+ export type AcpDiffContent = { type: 'diff'; path: string; oldText?: string | null; newText: string }
17
+ export type AcpContentBlock = AcpTextContent | AcpImageContent | AcpResourceLink | AcpDiffContent
18
+
19
+ export type AcpToolKind =
20
+ | 'read'
21
+ | 'edit'
22
+ | 'delete'
23
+ | 'move'
24
+ | 'search'
25
+ | 'execute'
26
+ | 'think'
27
+ | 'fetch'
28
+ | 'switch_mode'
29
+ | 'other'
30
+
31
+ export type AcpToolStatus = 'pending' | 'in_progress' | 'completed' | 'failed'
32
+
33
+ export type AcpToolLocation = { path: string; line?: number | null }
34
+
35
+ export type AcpToolCall = {
36
+ toolCallId: string
37
+ title?: string
38
+ kind?: AcpToolKind
39
+ status?: AcpToolStatus
40
+ content?: AcpContentBlock[]
41
+ locations?: AcpToolLocation[]
42
+ rawInput?: unknown
43
+ rawOutput?: unknown
44
+ }
45
+
46
+ export type AcpToolCallUpdate = Partial<Omit<AcpToolCall, 'toolCallId'>> & { toolCallId: string }
47
+
48
+ export type AcpPlanEntryStatus = 'pending' | 'in_progress' | 'completed'
49
+
50
+ export type AcpPlanEntry = { content: string; status: AcpPlanEntryStatus; priority?: string }
51
+
52
+ export type AcpSessionUpdate =
53
+ | { sessionUpdate: 'user_message_chunk'; content: AcpContentBlock }
54
+ | { sessionUpdate: 'agent_message_chunk'; content: AcpContentBlock }
55
+ | { sessionUpdate: 'agent_thought_chunk'; content: AcpContentBlock }
56
+ | ({ sessionUpdate: 'tool_call' } & AcpToolCall)
57
+ | ({ sessionUpdate: 'tool_call_update' } & AcpToolCallUpdate)
58
+ | { sessionUpdate: 'plan'; entries: AcpPlanEntry[] }
59
+ | { sessionUpdate: 'available_commands_update'; [key: string]: unknown }
60
+ | { sessionUpdate: 'current_mode_update'; [key: string]: unknown }
61
+ | { sessionUpdate: 'config_option_update'; [key: string]: unknown }
62
+ | { sessionUpdate: 'session_info_update'; [key: string]: unknown }
63
+ | { sessionUpdate: 'usage_update'; [key: string]: unknown }
64
+
65
+ export type AcpPermissionOptionKind = 'allow_once' | 'allow_always' | 'reject_once' | 'reject_always'
66
+
67
+ export type AcpPermissionOption = {
68
+ optionId: string
69
+ name: string
70
+ kind: AcpPermissionOptionKind
71
+ }
72
+
73
+ export type AcpPermissionOutcome =
74
+ | { outcome: 'selected'; optionId: string }
75
+ | { outcome: 'cancelled' }
76
+
77
+ export type AcpPermissionResult = { outcome: AcpPermissionOutcome }
78
+
79
+ export type AcpInitializeResult = {
80
+ protocolVersion: number
81
+ agentCapabilities?: {
82
+ loadSession?: boolean
83
+ promptCapabilities?: Record<string, unknown>
84
+ [key: string]: unknown
85
+ }
86
+ authMethods?: Array<{ id: string; name?: string; description?: string }>
87
+ [key: string]: unknown
88
+ }
89
+
90
+ export type AcpSessionNewResult = { sessionId: string; [key: string]: unknown }
91
+
92
+ export type AcpPromptResult = {
93
+ stopReason: AcpStopReason
94
+ usage?: AcpUsage
95
+ [key: string]: unknown
96
+ }
97
+
98
+ export type AcpPermissionRequest = {
99
+ sessionId: string
100
+ toolCall: AcpToolCall
101
+ options: AcpPermissionOption[]
102
+ }
103
+
104
+ export type AcpQuestionOption = { id: string; label: string }
105
+
106
+ export type AcpAskQuestionParams = {
107
+ toolCallId: string
108
+ title?: string
109
+ questions: Array<{
110
+ id: string
111
+ prompt: string
112
+ options: AcpQuestionOption[]
113
+ allowMultiple?: boolean
114
+ }>
115
+ }
116
+
117
+ export type AcpPlanTodo = {
118
+ id: string
119
+ content: string
120
+ status: 'pending' | 'in_progress' | 'completed' | 'cancelled'
121
+ }
122
+
123
+ export type AcpCreatePlanParams = {
124
+ toolCallId: string
125
+ name?: string
126
+ overview?: string
127
+ plan: string
128
+ todos?: AcpPlanTodo[]
129
+ isProject?: boolean
130
+ phases?: unknown
131
+ }
132
+
133
+ export type AcpUpdateTodosParams = {
134
+ todos?: AcpPlanTodo[]
135
+ merge?: boolean
136
+ [key: string]: unknown
137
+ }
138
+
139
+ export type AcpAskQuestionResult = {
140
+ outcome:
141
+ | {
142
+ outcome: 'answered'
143
+ answers: Array<{ questionId: string; selectedOptionIds: string[] }>
144
+ }
145
+ | { outcome: 'skipped'; reason?: string }
146
+ | { outcome: 'cancelled' }
147
+ }
148
+
149
+ export type AcpCreatePlanResult = {
150
+ outcome:
151
+ | { outcome: 'accepted' }
152
+ | { outcome: 'rejected'; reason?: string }
153
+ | { outcome: 'cancelled' }
154
+ }
155
+
156
+ /** A JSON-RPC error reply from the agent. */
157
+ export class AcpError extends Error {
158
+ readonly code: number
159
+ readonly data: unknown
160
+
161
+ constructor(message: string, code = -32000, data?: unknown) {
162
+ super(message)
163
+ this.name = 'AcpError'
164
+ this.code = code
165
+ this.data = data
166
+ }
167
+ }
@@ -0,0 +1,139 @@
1
+ import type { Database } from 'bun:sqlite'
2
+ import type { AcpQuestion, RunStatus, ToolCallBlock } from '../../shared/types'
3
+ import type { Config } from '../config'
4
+ import { appendMessage, getChat, updateChatTitle, type ChatRow, type MessageRow } from '../db'
5
+ import { INTERRUPTED, repair } from '../history'
6
+ import type { RunHooks } from '../loop'
7
+ import type { Shell, ToolResult } from '../tools'
8
+ import { titleFrom } from '../turn'
9
+ import type { RunMeta } from '../hub'
10
+ import { getAcpSession } from './session'
11
+
12
+ export type AcpRunInput = {
13
+ db: Database
14
+ config: Config
15
+ root: string
16
+ chat: ChatRow
17
+ workspaceId: string
18
+ text: string
19
+ runId: string
20
+ signal: AbortSignal
21
+ shell?: Shell | null
22
+ onDelta?: (delta: { text?: string; thinking?: string }) => void
23
+ onToolStarted?: (callId: string, name: string) => void
24
+ onToolRunning?: (callId: string, args: unknown) => void
25
+ onToolOutput?: (callId: string, chunk: string) => void
26
+ onAppended?: (row: MessageRow) => void
27
+ onTitle?: (title: string) => void
28
+ onFileChanged?: (path: string | null, hash: string | null) => void
29
+ onRunStart?: (runId: string, meta: RunMeta) => void
30
+ onRunFinish?: (runId: string, status: RunStatus) => void
31
+ onQueueChanged?: (runId: string, queue: string[]) => void
32
+ onQuestion?: (question: AcpQuestion | null) => void
33
+ beforeSave?: () => void
34
+ }
35
+
36
+ export function createAcpRun(input: AcpRunInput): RunHooks {
37
+ const onAppended = input.onAppended ?? (() => {})
38
+ const onTitle = input.onTitle ?? (() => {})
39
+ const onFileChanged = input.onFileChanged ?? (() => {})
40
+ const onRunStart = input.onRunStart ?? (() => {})
41
+ const onRunFinish = input.onRunFinish ?? (() => {})
42
+ const onQueueChanged = input.onQueueChanged ?? (() => {})
43
+ const onQuestion = input.onQuestion ?? (() => {})
44
+ const beforeSave = input.beforeSave ?? (() => {})
45
+ const onDelta = input.onDelta ?? (() => {})
46
+ const onToolStarted = input.onToolStarted ?? (() => {})
47
+ const onToolRunning = input.onToolRunning ?? (() => {})
48
+ const onToolOutput = input.onToolOutput ?? (() => {})
49
+ const session = getAcpSession({
50
+ db: input.db,
51
+ config: input.config,
52
+ root: input.root,
53
+ chat: input.chat,
54
+ shell: input.shell,
55
+ })
56
+ const pendingTexts = [input.text]
57
+ let title = input.chat.title
58
+
59
+ const write = (role: 'user' | 'notice', content: unknown): MessageRow => {
60
+ const row = appendMessage(input.db, input.chat.id, role, content)
61
+ onAppended(row)
62
+ return row
63
+ }
64
+
65
+ return {
66
+ maxSteps: input.config.maxSteps,
67
+ started() {
68
+ const current = getChat(input.db, input.chat.id)
69
+ if (current) title = current.title
70
+ onRunStart(input.runId, {
71
+ title,
72
+ workspaceId: input.workspaceId,
73
+ model: current?.model ?? input.chat.model,
74
+ engine: current?.engine ?? input.chat.engine,
75
+ updatedAt: Date.now(),
76
+ })
77
+ },
78
+ begin() {
79
+ repair(input.db, input.chat.id, INTERRUPTED, onAppended)
80
+ const empty = input.db
81
+ .query<{ count: number }, [string]>('SELECT COUNT(*) AS count FROM messages WHERE chat_id = ?')
82
+ .get(input.chat.id)?.count === 0
83
+ write('user', { text: input.text })
84
+ if (empty) {
85
+ title = titleFrom(input.text)
86
+ updateChatTitle(input.db, input.chat.id, title)
87
+ onTitle(title)
88
+ }
89
+ },
90
+ appendUser(text) {
91
+ write('user', { text })
92
+ pendingTexts.push(text)
93
+ },
94
+ async step() {
95
+ const text = pendingTexts.splice(0).join('\n\n')
96
+ if (!text) {
97
+ return {
98
+ called: false,
99
+ stopReason: null,
100
+ assistantText: null,
101
+ notice: null,
102
+ usage: null,
103
+ toolCalls: [],
104
+ }
105
+ }
106
+ return session.prompt(text, {
107
+ signal: input.signal,
108
+ onDelta,
109
+ onToolStarted,
110
+ onToolRunning,
111
+ onToolOutput,
112
+ onAppended,
113
+ onFileChanged,
114
+ onQuestion,
115
+ beforeSave,
116
+ })
117
+ },
118
+ execute(): Promise<ToolResult> {
119
+ return Promise.reject(new Error('ACP-чат не исполняет тулы'))
120
+ },
121
+ appendTool(_call: ToolCallBlock, _result: ToolResult) {},
122
+ closeDangling(reason) {
123
+ session.closeOpenCalls(reason)
124
+ },
125
+ notice(kind, text) {
126
+ beforeSave()
127
+ write('notice', { kind, text })
128
+ },
129
+ queueChanged(queue) {
130
+ onQueueChanged(input.runId, queue)
131
+ },
132
+ finished(status) {
133
+ // The agent writes files itself, and a turn need not carry a diff: announce the whole
134
+ // folder so the tree and git status catch up even when no revision was recorded.
135
+ onFileChanged(null, null)
136
+ onRunFinish(input.runId, status)
137
+ },
138
+ }
139
+ }