@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.
- package/README.md +54 -2
- package/package.json +51 -4
- package/server/acp/catalog.ts +111 -0
- package/server/acp/connection.ts +233 -0
- package/server/acp/fake-agent.ts +408 -0
- package/server/acp/protocol.ts +167 -0
- package/server/acp/run.ts +139 -0
- package/server/acp/session.ts +1249 -0
- package/server/attachments.ts +115 -0
- package/server/changes.ts +239 -0
- package/server/cli.ts +362 -0
- package/server/compact.ts +361 -0
- package/server/config.ts +176 -0
- package/server/db.ts +462 -0
- package/server/dev.ts +8 -0
- package/server/diff.ts +190 -0
- package/server/engines.ts +63 -0
- package/server/files.ts +254 -0
- package/server/git.ts +319 -0
- package/server/history.ts +425 -0
- package/server/http/attachments.ts +63 -0
- package/server/http/browse.ts +108 -0
- package/server/http/chats.ts +627 -0
- package/server/http/closing.ts +14 -0
- package/server/http/files.ts +115 -0
- package/server/http/git.ts +84 -0
- package/server/http/preview.ts +21 -0
- package/server/http/providers.ts +200 -0
- package/server/http/reply.ts +38 -0
- package/server/hub.ts +521 -0
- package/server/install.ts +169 -0
- package/server/jobs.ts +664 -0
- package/server/linkPreview.ts +172 -0
- package/server/loop.ts +328 -0
- package/server/main.ts +353 -0
- package/server/probe.ts +34 -0
- package/server/process.ts +333 -0
- package/server/prompt.ts +196 -0
- package/server/providers/fake.ts +100 -0
- package/server/providers/opencode.ts +468 -0
- package/server/providers/registry.ts +149 -0
- package/server/providers/store.ts +210 -0
- package/server/segments.ts +248 -0
- package/server/sse.ts +93 -0
- package/server/tools/bash.ts +222 -0
- package/server/tools/edit.ts +254 -0
- package/server/tools/glob.ts +63 -0
- package/server/tools/grep.ts +122 -0
- package/server/tools/ignore.ts +54 -0
- package/server/tools/index.ts +129 -0
- package/server/tools/jail.ts +85 -0
- package/server/tools/jobs.ts +293 -0
- package/server/tools/read.ts +248 -0
- package/server/tools/write.ts +70 -0
- package/server/tray.ps1 +191 -0
- package/server/turn.ts +663 -0
- package/server/watch.ts +94 -0
- package/shared/acpConfig.ts +113 -0
- package/shared/links.ts +122 -0
- package/shared/types.ts +392 -0
- package/web/dist/app.css +1 -0
- package/web/dist/assets/codicon-mxdk0fnd.ttf +0 -0
- package/web/dist/index.html +28 -0
- package/web/dist/main.css +1 -0
- package/web/dist/main.js +1366 -0
- package/web/dist/tokens.css +1 -0
- package/web/dist/workers/css.worker.js +97 -0
- package/web/dist/workers/editor.worker.js +30 -0
- package/web/dist/workers/html.worker.js +300 -0
- package/web/dist/workers/json.worker.js +62 -0
- package/web/dist/workers/ts.worker.js +67733 -0
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite'
|
|
2
|
+
import type { ModelMessage, StreamEvent, StreamLLMInput, Usage } from '../shared/types'
|
|
3
|
+
import { appendMessage, getChat, listMessages, type ChatRow, type MessageRow } from './db'
|
|
4
|
+
import { INTERRUPTED, modelMessages, repair, visibleRows } from './history'
|
|
5
|
+
import { compactionInstruction, compactionSystem, updateSummaryInstruction } from './prompt'
|
|
6
|
+
import { streamForModel } from './providers/registry'
|
|
7
|
+
import { statisticsBlock, turnStats, writeSegment } from './segments'
|
|
8
|
+
import type { Config } from './config'
|
|
9
|
+
|
|
10
|
+
export const KEEP_RECENT_TOKENS = 20_000
|
|
11
|
+
/** Free space left below the context window before compaction, as in pi and omp. */
|
|
12
|
+
export const RESERVE_TOKENS = 16_384
|
|
13
|
+
/**
|
|
14
|
+
* Share of the window that triggers compaction on its own. Cursor uses the same 0.9
|
|
15
|
+
* as a local fallback when its backend sends no threshold; here it is the cheap
|
|
16
|
+
* guarantee that a request never waits for a provider 400.
|
|
17
|
+
*/
|
|
18
|
+
export const CONTEXT_TRIGGER_FRACTION = 0.9
|
|
19
|
+
const CHARS_PER_TOKEN = 4
|
|
20
|
+
const MESSAGE_OVERHEAD_CHARS = 16
|
|
21
|
+
const MIN_SUMMARY_WINDOW_TOKENS = 4_000
|
|
22
|
+
const SUMMARY_PREFIX = 'Сводка предыдущего разговора:\n\n'
|
|
23
|
+
/**
|
|
24
|
+
* Closes the summary. Cursor appends the same instruction for the same reason: without it a
|
|
25
|
+
* model reads a summary as "work finished" and opens with a greeting instead of continuing.
|
|
26
|
+
*/
|
|
27
|
+
export const COMPACTION_CONTINUATION =
|
|
28
|
+
'После сжатия продолжай незавершённую работу. Не начинай разговор заново и не жди новой задачи: посмотри на раздел Next Steps в сводке и сделай следующий шаг.'
|
|
29
|
+
|
|
30
|
+
export type CompactOutcome =
|
|
31
|
+
| { status: 'compacted'; message: MessageRow; summarized: number; kept: number; segment: string | null }
|
|
32
|
+
| { status: 'not_native' }
|
|
33
|
+
| { status: 'short' }
|
|
34
|
+
| { status: 'empty' }
|
|
35
|
+
| { status: 'error'; error: string }
|
|
36
|
+
|
|
37
|
+
export type CompactInput = {
|
|
38
|
+
db: Database
|
|
39
|
+
config: Config
|
|
40
|
+
chatId: string
|
|
41
|
+
signal?: AbortSignal
|
|
42
|
+
stream?: (input: StreamLLMInput) => AsyncIterable<StreamEvent>
|
|
43
|
+
/** When true, bypasses the tail-size guard because the provider already rejected the prompt as too large. */
|
|
44
|
+
force?: boolean
|
|
45
|
+
/** Test seam; production uses KEEP_RECENT_TOKENS. */
|
|
46
|
+
keepRecentTokens?: number
|
|
47
|
+
/** Test seam; production uses half the context window. */
|
|
48
|
+
summaryWindowTokens?: number
|
|
49
|
+
/** Test seam; production writes under the pointer home. */
|
|
50
|
+
archiveDir?: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const compacting = new Set<string>()
|
|
54
|
+
|
|
55
|
+
export function isCompacting(chatId: string): boolean {
|
|
56
|
+
return compacting.has(chatId)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Manual compaction: summarize the part before the recent tail, insert the summary at the cut,
|
|
61
|
+
* and let history.ts start the model request from it. The old prefix stays in the log.
|
|
62
|
+
*/
|
|
63
|
+
export async function compactChat(input: CompactInput): Promise<CompactOutcome> {
|
|
64
|
+
const chat = getChat(input.db, input.chatId)
|
|
65
|
+
if (!chat) throw new Error(`Chat ${input.chatId} not found`)
|
|
66
|
+
if (chat.engine !== 'native') return { status: 'not_native' }
|
|
67
|
+
if (compacting.has(chat.id)) return { status: 'error', error: 'Сжатие уже идёт' }
|
|
68
|
+
compacting.add(chat.id)
|
|
69
|
+
try {
|
|
70
|
+
repair(input.db, chat.id, INTERRUPTED)
|
|
71
|
+
const visible = visibleRows(listMessages(input.db, chat.id))
|
|
72
|
+
if (visible.length === 0) return { status: 'empty' }
|
|
73
|
+
|
|
74
|
+
const keepChars = (input.keepRecentTokens ?? KEEP_RECENT_TOKENS) * CHARS_PER_TOKEN
|
|
75
|
+
const visibleChars = visible.reduce(
|
|
76
|
+
(total, row) => total + row.content_json.length + MESSAGE_OVERHEAD_CHARS,
|
|
77
|
+
0,
|
|
78
|
+
)
|
|
79
|
+
if (input.force && !visible.some((row) => row.role === 'assistant')) return { status: 'short' }
|
|
80
|
+
if (!input.force && visibleChars <= keepChars) return { status: 'short' }
|
|
81
|
+
|
|
82
|
+
const effectiveKeep = input.force && visibleChars <= keepChars ? 1 : keepChars
|
|
83
|
+
const cut = findCut(visible, effectiveKeep)
|
|
84
|
+
const prefix = cut > 0 ? visible.slice(0, cut) : visible
|
|
85
|
+
const kept = cut > 0 ? visible.length - cut : 0
|
|
86
|
+
const messages = modelMessages(prefix)
|
|
87
|
+
if (messages.length === 0) return { status: 'empty' }
|
|
88
|
+
|
|
89
|
+
const snapshot = visible.map((row) => ({ id: row.id, seq: row.seq }))
|
|
90
|
+
// Counted, not described: the summarizer turns these numbers into "read 118 times" instead
|
|
91
|
+
// of prose that loses the shape of the work.
|
|
92
|
+
const stats = turnStats(prefix)
|
|
93
|
+
const summary = await summarize({
|
|
94
|
+
chat,
|
|
95
|
+
config: input.config,
|
|
96
|
+
db: input.db,
|
|
97
|
+
messages,
|
|
98
|
+
stats: statisticsBlock(stats),
|
|
99
|
+
stream: input.stream,
|
|
100
|
+
signal: input.signal,
|
|
101
|
+
windowTokens: input.summaryWindowTokens,
|
|
102
|
+
})
|
|
103
|
+
if (!summary.ok) return { status: 'error', error: summary.error }
|
|
104
|
+
if (!sameSnapshot(snapshot, visibleRows(listMessages(input.db, chat.id)))) {
|
|
105
|
+
return { status: 'error', error: 'История изменилась во время сжатия' }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// The archive is written before the summary lands, so the pointer in the summary always
|
|
109
|
+
// names a file that exists. A failed write costs the pointer, never the compaction.
|
|
110
|
+
const segment = writeSegment({
|
|
111
|
+
chatId: chat.id,
|
|
112
|
+
rows: prefix,
|
|
113
|
+
stats,
|
|
114
|
+
summary: summary.text,
|
|
115
|
+
...(input.archiveDir ? { dir: input.archiveDir } : {}),
|
|
116
|
+
})
|
|
117
|
+
|
|
118
|
+
const text = `${SUMMARY_PREFIX}${withPointers(summary.text, segment)}`
|
|
119
|
+
const message =
|
|
120
|
+
cut > 0
|
|
121
|
+
? insertSummary(input.db, chat.id, visible[cut]!.seq, text)
|
|
122
|
+
: appendMessage(input.db, chat.id, 'user', { text, compacted: true })
|
|
123
|
+
return { status: 'compacted', message, summarized: prefix.length, kept, segment: segment?.file ?? null }
|
|
124
|
+
} catch (error) {
|
|
125
|
+
return { status: 'error', error: error instanceof Error ? error.message : String(error) }
|
|
126
|
+
} finally {
|
|
127
|
+
compacting.delete(chat.id)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
type SummaryResult = { ok: true; text: string } | { ok: false; error: string }
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Threshold in tokens: compaction starts when the last step used more than the window
|
|
135
|
+
* minus the reserve, or more than `CONTEXT_TRIGGER_FRACTION` of the window.
|
|
136
|
+
*/
|
|
137
|
+
export function compactionThreshold(contextWindow: number): number {
|
|
138
|
+
return Math.min(contextWindow - RESERVE_TOKENS, Math.floor(contextWindow * CONTEXT_TRIGGER_FRACTION))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function exceedsCompactionThreshold(usage: Usage, contextWindow: number): boolean {
|
|
142
|
+
const used = usage.input + usage.output
|
|
143
|
+
return used >= compactionThreshold(contextWindow)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Whether a provider error means the request was larger than the window. The wording
|
|
148
|
+
* differs per gateway, so this matches the shapes seen in the wild rather than one string.
|
|
149
|
+
*/
|
|
150
|
+
export function isOverflowError(text: string | null | undefined): boolean {
|
|
151
|
+
if (!text) return false
|
|
152
|
+
return /context[_ ]length|maximum context|context window|too many tokens|prompt is too long|переполн/i.test(text)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export type AutoCompactInput = CompactInput & { usage: Usage }
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Compaction on the step boundary when the last step filled the window. Returns null when
|
|
159
|
+
* nothing happened: below the threshold, a chat that is not ours, or compaction already
|
|
160
|
+
* running for this chat. Errors come back as a `notice` text instead of failing the run.
|
|
161
|
+
*/
|
|
162
|
+
export async function autoCompactIfNeeded(input: AutoCompactInput): Promise<string | null> {
|
|
163
|
+
if (!exceedsCompactionThreshold(input.usage, input.config.contextWindow)) return null
|
|
164
|
+
if (compacting.has(input.chatId)) return null
|
|
165
|
+
const result = await compactChat(input)
|
|
166
|
+
if (result.status === 'compacted') {
|
|
167
|
+
const used = input.usage.input + input.usage.output
|
|
168
|
+
return `Контекст сжат: ${used} токенов при окне ${input.config.contextWindow}`
|
|
169
|
+
}
|
|
170
|
+
if (result.status === 'error') return `Сжатие контекста не удалось: ${result.error}`
|
|
171
|
+
return null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function summarize(input: {
|
|
175
|
+
chat: ChatRow
|
|
176
|
+
config: Config
|
|
177
|
+
db: Database
|
|
178
|
+
messages: ModelMessage[]
|
|
179
|
+
/** Counted shape of the conversation, prepended to the first request. */
|
|
180
|
+
stats: string
|
|
181
|
+
stream?: (input: StreamLLMInput) => AsyncIterable<StreamEvent>
|
|
182
|
+
signal?: AbortSignal
|
|
183
|
+
windowTokens?: number
|
|
184
|
+
}): Promise<SummaryResult> {
|
|
185
|
+
const windowTokens =
|
|
186
|
+
input.windowTokens ?? Math.max(MIN_SUMMARY_WINDOW_TOKENS, Math.floor(input.config.contextWindow / 2))
|
|
187
|
+
const windows = splitWindows(input.messages, windowTokens * CHARS_PER_TOKEN)
|
|
188
|
+
let summary = ''
|
|
189
|
+
for (let index = 0; index < windows.length; index++) {
|
|
190
|
+
const instruction = index === 0 ? compactionInstruction() : updateSummaryInstruction(summary)
|
|
191
|
+
const request = index === 0 ? `${input.stats}\n\n${instruction}` : instruction
|
|
192
|
+
const result = await summarizeWindow({
|
|
193
|
+
chat: input.chat,
|
|
194
|
+
config: input.config,
|
|
195
|
+
db: input.db,
|
|
196
|
+
stream: input.stream,
|
|
197
|
+
signal: input.signal,
|
|
198
|
+
messages: [...windows[index]!, { role: 'user', content: { text: request } }],
|
|
199
|
+
})
|
|
200
|
+
if (!result.ok) return result
|
|
201
|
+
summary = result.text
|
|
202
|
+
}
|
|
203
|
+
return { ok: true, text: summary }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* The summary as the model will see it: the text it wrote, then where the removed turns went.
|
|
208
|
+
* Without the pointer the model knows a summary exists but has no way back to a detail the
|
|
209
|
+
* summary dropped, which is what made Cursor's segments worth copying.
|
|
210
|
+
*/
|
|
211
|
+
export function withPointers(summary: string, segment: { file: string; indexPath: string } | null): string {
|
|
212
|
+
const parts = [summary.trim()]
|
|
213
|
+
if (segment !== null) {
|
|
214
|
+
parts.push(
|
|
215
|
+
[
|
|
216
|
+
'---',
|
|
217
|
+
`Ранние ходы вынесены в архив: ${segment.file}`,
|
|
218
|
+
`Оглавление сегментов: ${segment.indexPath}`,
|
|
219
|
+
'Файлы только для чтения: если нужна деталь, которой нет в сводке, найди её через grep по архиву или read по нему.',
|
|
220
|
+
].join('\n'),
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
parts.push(`---\n${COMPACTION_CONTINUATION}`)
|
|
224
|
+
return parts.join('\n\n')
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async function summarizeWindow(input: {
|
|
228
|
+
chat: ChatRow
|
|
229
|
+
config: Config
|
|
230
|
+
db: Database
|
|
231
|
+
messages: ModelMessage[]
|
|
232
|
+
stream?: (input: StreamLLMInput) => AsyncIterable<StreamEvent>
|
|
233
|
+
signal?: AbortSignal
|
|
234
|
+
}): Promise<SummaryResult> {
|
|
235
|
+
const stream =
|
|
236
|
+
input.stream ??
|
|
237
|
+
((request: StreamLLMInput) => streamForModel(request.model, input.config, request, { db: input.db }))
|
|
238
|
+
const reasoning = input.chat.reasoning ?? input.config.reasoning
|
|
239
|
+
let text = ''
|
|
240
|
+
try {
|
|
241
|
+
for await (const event of stream({
|
|
242
|
+
model: input.chat.model,
|
|
243
|
+
system: compactionSystem(),
|
|
244
|
+
messages: input.messages,
|
|
245
|
+
signal: input.signal,
|
|
246
|
+
sessionId: input.chat.id,
|
|
247
|
+
...(reasoning ? { reasoning } : {}),
|
|
248
|
+
})) {
|
|
249
|
+
if (event.type === 'text_delta') {
|
|
250
|
+
text += event.text
|
|
251
|
+
} else if (event.type === 'done') {
|
|
252
|
+
const complete = event.blocks
|
|
253
|
+
.filter((block) => block.type === 'text')
|
|
254
|
+
.map((block) => block.text)
|
|
255
|
+
.join('')
|
|
256
|
+
if (complete) text = complete
|
|
257
|
+
if (event.stopReason === 'error') return { ok: false, error: 'Провайдер вернул ошибку при сжатии' }
|
|
258
|
+
if (event.stopReason === 'aborted') return { ok: false, error: 'Сжатие прервано' }
|
|
259
|
+
if (event.stopReason === 'max_tokens') return { ok: false, error: 'Сводка обрезана по лимиту токенов' }
|
|
260
|
+
if (event.stopReason === 'tool_use') return { ok: false, error: 'Модель вернула вызов тула вместо сводки' }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
} catch (error) {
|
|
264
|
+
if (input.signal?.aborted || (error instanceof Error && error.name === 'AbortError')) {
|
|
265
|
+
return { ok: false, error: 'Сжатие прервано' }
|
|
266
|
+
}
|
|
267
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) }
|
|
268
|
+
}
|
|
269
|
+
const trimmed = text.trim()
|
|
270
|
+
if (!trimmed) return { ok: false, error: 'Модель вернула пустую сводку' }
|
|
271
|
+
return { ok: true, text: trimmed }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Groups of whole messages below the summary window; a tool result never opens a group. */
|
|
275
|
+
function splitWindows(messages: ModelMessage[], maxChars: number): ModelMessage[][] {
|
|
276
|
+
const windows: ModelMessage[][] = []
|
|
277
|
+
let current: ModelMessage[] = []
|
|
278
|
+
let chars = 0
|
|
279
|
+
for (const message of messages) {
|
|
280
|
+
const size = JSON.stringify(message.content).length + MESSAGE_OVERHEAD_CHARS
|
|
281
|
+
if (current.length > 0 && chars + size > maxChars && message.role !== 'tool') {
|
|
282
|
+
windows.push(current)
|
|
283
|
+
current = []
|
|
284
|
+
chars = 0
|
|
285
|
+
}
|
|
286
|
+
current.push(message)
|
|
287
|
+
chars += size
|
|
288
|
+
}
|
|
289
|
+
if (current.length > 0) windows.push(current)
|
|
290
|
+
return windows
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Oldest suffix that fits the budget, cut at a user/assistant row. If the newest group alone
|
|
295
|
+
* exceeds the budget it is kept anyway; if there is no older prefix, everything is summarized.
|
|
296
|
+
*/
|
|
297
|
+
function findCut(rows: MessageRow[], budgetChars: number): number {
|
|
298
|
+
let cut = -1
|
|
299
|
+
let chars = 0
|
|
300
|
+
for (let index = rows.length - 1; index >= 0; index--) {
|
|
301
|
+
const row = rows[index]!
|
|
302
|
+
chars += row.content_json.length + MESSAGE_OVERHEAD_CHARS
|
|
303
|
+
if (!isCutBoundary(rows, index)) continue
|
|
304
|
+
if (chars > budgetChars) break
|
|
305
|
+
cut = index
|
|
306
|
+
}
|
|
307
|
+
if (cut >= 0) return cut
|
|
308
|
+
for (let index = rows.length - 1; index >= 0; index--) {
|
|
309
|
+
if (isCutBoundary(rows, index)) return index
|
|
310
|
+
}
|
|
311
|
+
return 0
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function isCutBoundary(rows: MessageRow[], index: number): boolean {
|
|
315
|
+
const role = rows[index]?.role
|
|
316
|
+
if (role === 'user') return true
|
|
317
|
+
return role === 'assistant' && rows[index - 1]?.role !== 'user'
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function sameSnapshot(snapshot: Array<{ id: string; seq: number }>, rows: MessageRow[]): boolean {
|
|
321
|
+
if (snapshot.length !== rows.length) return false
|
|
322
|
+
for (let index = 0; index < rows.length; index++) {
|
|
323
|
+
const row = rows[index]!
|
|
324
|
+
const seen = snapshot[index]!
|
|
325
|
+
if (row.id !== seen.id || row.seq !== seen.seq) return false
|
|
326
|
+
}
|
|
327
|
+
return true
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function insertSummary(db: Database, chatId: string, beforeSeq: number, text: string): MessageRow {
|
|
331
|
+
return db
|
|
332
|
+
.transaction((): MessageRow => {
|
|
333
|
+
const shifting = db
|
|
334
|
+
.query<{ id: string; seq: number }, [string, number]>(
|
|
335
|
+
'SELECT id, seq FROM messages WHERE chat_id = ? AND seq >= ? ORDER BY seq DESC',
|
|
336
|
+
)
|
|
337
|
+
.all(chatId, beforeSeq)
|
|
338
|
+
for (const row of shifting) {
|
|
339
|
+
db.run('UPDATE messages SET seq = ? WHERE id = ?', [row.seq + 1, row.id])
|
|
340
|
+
}
|
|
341
|
+
const now = Date.now()
|
|
342
|
+
const content = JSON.stringify({ text, compacted: true })
|
|
343
|
+
const row: MessageRow = {
|
|
344
|
+
id: crypto.randomUUID(),
|
|
345
|
+
chat_id: chatId,
|
|
346
|
+
seq: beforeSeq,
|
|
347
|
+
role: 'user',
|
|
348
|
+
content_json: content,
|
|
349
|
+
details_json: null,
|
|
350
|
+
created_at: now,
|
|
351
|
+
}
|
|
352
|
+
db.run(
|
|
353
|
+
`INSERT INTO messages (id, chat_id, seq, role, content_json, details_json, created_at)
|
|
354
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
355
|
+
[row.id, row.chat_id, row.seq, row.role, row.content_json, row.details_json, row.created_at],
|
|
356
|
+
)
|
|
357
|
+
db.run('UPDATE chats SET updated_at = ? WHERE id = ?', [now, chatId])
|
|
358
|
+
return row
|
|
359
|
+
})
|
|
360
|
+
.immediate()
|
|
361
|
+
}
|
package/server/config.ts
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import type { ReasoningLevel } from '../shared/types'
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_CONTEXT_WINDOW = 1_000_000
|
|
8
|
+
|
|
9
|
+
const REASONING_LEVELS: readonly ReasoningLevel[] = ['low', 'high', 'max']
|
|
10
|
+
|
|
11
|
+
export type Config = {
|
|
12
|
+
port: number
|
|
13
|
+
baseUrl: string
|
|
14
|
+
model: string
|
|
15
|
+
maxSteps: number
|
|
16
|
+
bashTimeout: number
|
|
17
|
+
contextWindow: number
|
|
18
|
+
token: string
|
|
19
|
+
acpCommand: string
|
|
20
|
+
acpArgs?: string[]
|
|
21
|
+
acpCwd?: string
|
|
22
|
+
providers?: Record<string, { baseUrl?: string }>
|
|
23
|
+
gitPath?: string
|
|
24
|
+
reasoning?: ReasoningLevel
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The installed daemon. `pointer` verbs always use this directory, never `POINTER_HOME`. */
|
|
28
|
+
export function dailyHome(): string {
|
|
29
|
+
const home = process.env.USERPROFILE || homedir()
|
|
30
|
+
return join(home, '.pointer')
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* State directory of this process. `POINTER_HOME` is the dev daemon, so a checkout
|
|
35
|
+
* does not write the daily database. The installed task does not set it.
|
|
36
|
+
*/
|
|
37
|
+
export function pointerHome(): string {
|
|
38
|
+
const override = process.env.POINTER_HOME?.trim()
|
|
39
|
+
if (override) return override
|
|
40
|
+
return dailyHome()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const DEV_HOME_NAME = '.pointer-dev'
|
|
44
|
+
export const DEV_PORT = 8788
|
|
45
|
+
|
|
46
|
+
export const GIT_MISSING =
|
|
47
|
+
'Git не найден: тул bash выключен, git-панель недоступна. Установите Git for Windows или укажите gitPath в config.json'
|
|
48
|
+
|
|
49
|
+
export function loadConfig(home: string): Config {
|
|
50
|
+
mkdirSync(home, { recursive: true, mode: 0o700 })
|
|
51
|
+
const file = join(home, 'config.json')
|
|
52
|
+
if (!existsSync(file)) {
|
|
53
|
+
const config = defaultConfig()
|
|
54
|
+
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
55
|
+
return config
|
|
56
|
+
}
|
|
57
|
+
// Tokens from older installations may have been created with the default umask.
|
|
58
|
+
if (process.platform !== 'win32') {
|
|
59
|
+
try {
|
|
60
|
+
chmodSync(file, 0o600)
|
|
61
|
+
} catch {
|
|
62
|
+
// A read-only config is still usable; do not turn a permission quirk into a startup failure.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return parseConfig(JSON.parse(readFileSync(file, 'utf8')))
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function defaultConfig(): Config {
|
|
69
|
+
return {
|
|
70
|
+
port: process.env.POINTER_HOME?.trim() ? DEV_PORT : 8787,
|
|
71
|
+
baseUrl: 'https://opencode.ai/inference/go',
|
|
72
|
+
model: 'opencode-go/deepseek-v4.1-flash',
|
|
73
|
+
maxSteps: 200,
|
|
74
|
+
bashTimeout: 600,
|
|
75
|
+
contextWindow: DEFAULT_CONTEXT_WINDOW,
|
|
76
|
+
token: randomBytes(32).toString('base64url'),
|
|
77
|
+
acpCommand: 'cursor-agent',
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function parseConfig(value: unknown): Config {
|
|
82
|
+
if (!isRecord(value)) throw new Error('config.json: ожидался объект')
|
|
83
|
+
return {
|
|
84
|
+
port: requiredPort(value.port),
|
|
85
|
+
baseUrl: requiredString(value.baseUrl, 'baseUrl'),
|
|
86
|
+
model: requiredString(value.model, 'model'),
|
|
87
|
+
maxSteps: requiredPositiveInt(value.maxSteps, 'maxSteps'),
|
|
88
|
+
bashTimeout: requiredPositiveInt(value.bashTimeout, 'bashTimeout'),
|
|
89
|
+
contextWindow:
|
|
90
|
+
value.contextWindow === undefined
|
|
91
|
+
? DEFAULT_CONTEXT_WINDOW
|
|
92
|
+
: requiredPositiveInt(value.contextWindow, 'contextWindow'),
|
|
93
|
+
token: requiredString(value.token, 'token'),
|
|
94
|
+
acpCommand: requiredString(value.acpCommand, 'acpCommand'),
|
|
95
|
+
...(value.acpArgs === undefined ? {} : { acpArgs: requiredStringArray(value.acpArgs, 'acpArgs') }),
|
|
96
|
+
...(value.acpCwd === undefined ? {} : { acpCwd: requiredString(value.acpCwd, 'acpCwd') }),
|
|
97
|
+
...(value.providers === undefined ? {} : { providers: requiredProviders(value.providers) }),
|
|
98
|
+
...(value.gitPath === undefined ? {} : { gitPath: requiredString(value.gitPath, 'gitPath') }),
|
|
99
|
+
...(value.reasoning === undefined ? {} : { reasoning: requiredReasoning(value.reasoning) }),
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Finds Git Bash. On Windows the only reliable source is the Git installation itself:
|
|
105
|
+
* `git --exec-path` points at `<Git>/mingw64/libexec/git-core`, so three levels up is
|
|
106
|
+
* `<Git>`, and `<Git>/bin/bash.exe` is Git Bash. `bash` on PATH is the WSL launcher.
|
|
107
|
+
*/
|
|
108
|
+
export function findGitBash(config: Config): string | null {
|
|
109
|
+
try {
|
|
110
|
+
if (process.platform !== 'win32') return Bun.which('bash')
|
|
111
|
+
const result = Bun.spawnSync([config.gitPath ?? 'git', '--exec-path'], {
|
|
112
|
+
stdout: 'pipe',
|
|
113
|
+
stderr: 'pipe',
|
|
114
|
+
stdin: 'ignore',
|
|
115
|
+
})
|
|
116
|
+
if (!result.success) return null
|
|
117
|
+
const execPath = new TextDecoder().decode(result.stdout).trim()
|
|
118
|
+
if (!execPath) return null
|
|
119
|
+
const bash = join(execPath, '..', '..', '..', 'bin', 'bash.exe')
|
|
120
|
+
return existsSync(bash) ? bash : null
|
|
121
|
+
} catch {
|
|
122
|
+
return null
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function requiredString(value: unknown, name: string): string {
|
|
127
|
+
if (typeof value !== 'string' || !value) throw new Error(`config.json: поле ${name}`)
|
|
128
|
+
return value
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function requiredPositiveInt(value: unknown, name: string): number {
|
|
132
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {
|
|
133
|
+
throw new Error(`config.json: поле ${name}`)
|
|
134
|
+
}
|
|
135
|
+
return value
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function requiredStringArray(value: unknown, name: string): string[] {
|
|
139
|
+
if (!Array.isArray(value)) throw new Error(`config.json: поле ${name}`)
|
|
140
|
+
return value.map((item, index) => requiredString(item, `${name}[${index}]`))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function requiredProviders(value: unknown): Record<string, { baseUrl?: string }> {
|
|
144
|
+
if (!isRecord(value)) throw new Error('config.json: поле providers')
|
|
145
|
+
const providers: Record<string, { baseUrl?: string }> = {}
|
|
146
|
+
for (const [id, raw] of Object.entries(value)) {
|
|
147
|
+
if (!id) throw new Error('config.json: поле providers')
|
|
148
|
+
if (!isRecord(raw)) throw new Error(`config.json: providers.${id}`)
|
|
149
|
+
providers[id] =
|
|
150
|
+
raw.baseUrl === undefined ? {} : { baseUrl: requiredString(raw.baseUrl, `providers.${id}.baseUrl`) }
|
|
151
|
+
}
|
|
152
|
+
return providers
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function reasoningLevel(value: unknown): ReasoningLevel | null {
|
|
156
|
+
if (typeof value === 'string' && (REASONING_LEVELS as readonly string[]).includes(value)) {
|
|
157
|
+
return value as ReasoningLevel
|
|
158
|
+
}
|
|
159
|
+
return null
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function requiredReasoning(value: unknown): ReasoningLevel {
|
|
163
|
+
const level = reasoningLevel(value)
|
|
164
|
+
if (!level) throw new Error('config.json: поле reasoning')
|
|
165
|
+
return level
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function requiredPort(value: unknown): number {
|
|
169
|
+
const port = requiredPositiveInt(value, 'port')
|
|
170
|
+
if (port > 65535) throw new Error('config.json: поле port')
|
|
171
|
+
return port
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
175
|
+
return typeof value === 'object' && value !== null
|
|
176
|
+
}
|