@yuridulin/pointer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +54 -2
  2. package/package.json +51 -4
  3. package/server/acp/catalog.ts +111 -0
  4. package/server/acp/connection.ts +233 -0
  5. package/server/acp/fake-agent.ts +408 -0
  6. package/server/acp/protocol.ts +167 -0
  7. package/server/acp/run.ts +139 -0
  8. package/server/acp/session.ts +1249 -0
  9. package/server/attachments.ts +115 -0
  10. package/server/changes.ts +239 -0
  11. package/server/cli.ts +362 -0
  12. package/server/compact.ts +361 -0
  13. package/server/config.ts +176 -0
  14. package/server/db.ts +462 -0
  15. package/server/dev.ts +8 -0
  16. package/server/diff.ts +190 -0
  17. package/server/engines.ts +63 -0
  18. package/server/files.ts +254 -0
  19. package/server/git.ts +319 -0
  20. package/server/history.ts +425 -0
  21. package/server/http/attachments.ts +63 -0
  22. package/server/http/browse.ts +108 -0
  23. package/server/http/chats.ts +627 -0
  24. package/server/http/closing.ts +14 -0
  25. package/server/http/files.ts +115 -0
  26. package/server/http/git.ts +84 -0
  27. package/server/http/preview.ts +21 -0
  28. package/server/http/providers.ts +200 -0
  29. package/server/http/reply.ts +38 -0
  30. package/server/hub.ts +521 -0
  31. package/server/install.ts +169 -0
  32. package/server/jobs.ts +664 -0
  33. package/server/linkPreview.ts +172 -0
  34. package/server/loop.ts +328 -0
  35. package/server/main.ts +353 -0
  36. package/server/probe.ts +34 -0
  37. package/server/process.ts +333 -0
  38. package/server/prompt.ts +196 -0
  39. package/server/providers/fake.ts +100 -0
  40. package/server/providers/opencode.ts +468 -0
  41. package/server/providers/registry.ts +149 -0
  42. package/server/providers/store.ts +210 -0
  43. package/server/segments.ts +248 -0
  44. package/server/sse.ts +93 -0
  45. package/server/tools/bash.ts +222 -0
  46. package/server/tools/edit.ts +254 -0
  47. package/server/tools/glob.ts +63 -0
  48. package/server/tools/grep.ts +122 -0
  49. package/server/tools/ignore.ts +54 -0
  50. package/server/tools/index.ts +129 -0
  51. package/server/tools/jail.ts +85 -0
  52. package/server/tools/jobs.ts +293 -0
  53. package/server/tools/read.ts +248 -0
  54. package/server/tools/write.ts +70 -0
  55. package/server/tray.ps1 +191 -0
  56. package/server/turn.ts +663 -0
  57. package/server/watch.ts +94 -0
  58. package/shared/acpConfig.ts +113 -0
  59. package/shared/links.ts +122 -0
  60. package/shared/types.ts +392 -0
  61. package/web/dist/app.css +1 -0
  62. package/web/dist/assets/codicon-mxdk0fnd.ttf +0 -0
  63. package/web/dist/index.html +28 -0
  64. package/web/dist/main.css +1 -0
  65. package/web/dist/main.js +1366 -0
  66. package/web/dist/tokens.css +1 -0
  67. package/web/dist/workers/css.worker.js +97 -0
  68. package/web/dist/workers/editor.worker.js +30 -0
  69. package/web/dist/workers/html.worker.js +300 -0
  70. package/web/dist/workers/json.worker.js +62 -0
  71. package/web/dist/workers/ts.worker.js +67733 -0
package/server/main.ts ADDED
@@ -0,0 +1,353 @@
1
+ import { extname, isAbsolute, join, relative, resolve } from 'node:path'
2
+ import type { Database } from 'bun:sqlite'
3
+ import type { ServerWebSocket } from 'bun'
4
+ import { findGitBash, GIT_MISSING, loadConfig, pointerHome, type Config } from './config'
5
+ import { ensureWorkspace, getChat, getWorkspace, listMessages, listNativeChatIds, listWorkspaces, openDatabase } from './db'
6
+ import { listEngines } from './engines'
7
+ import { isProvidersRoute, providersRoute } from './http/providers'
8
+ import { acpOverride, getProvider, providerEnabled } from './providers/store'
9
+ import { stopAcpCatalog, warmAcpCatalog } from './acp/catalog'
10
+ import { stopAllAcp } from './acp/session'
11
+ import { INTERRUPTED, repair } from './history'
12
+ import { attachmentsRoute, isAttachmentsRoute } from './http/attachments'
13
+ import {
14
+ browseRoute,
15
+ isBrowseRoute,
16
+ isShowRoute,
17
+ isWorkspacesRoute,
18
+ showWorkspace,
19
+ workspacesRoute,
20
+ type FolderShow,
21
+ } from './http/browse'
22
+ import { chatsRoute, isChatsRoute, jobCompletionRun, type ChatDeps } from './http/chats'
23
+ import { filesRoute, isFilesRoute } from './http/files'
24
+ import { gitRoute, isGitRoute } from './http/git'
25
+ import { isPreviewRoute, previewRoute } from './http/preview'
26
+ import { fail, isRecord } from './http/reply'
27
+ import { chatTopic, createHub, GLOBAL_TOPIC, messageView, type Hub, type Schedule } from './hub'
28
+ import { createJobRegistry, bashOutputDir, pruneBashLogs } from './jobs'
29
+ import { activeRunCount } from './loop'
30
+ import { killMarkedOrphans } from './process'
31
+ import type { Shell } from './tools'
32
+ import type { TurnInput } from './turn'
33
+ import { createWorkspaceWatch } from './watch'
34
+
35
+ export type ServerOptions = {
36
+ db: Database
37
+ config: Config
38
+ root: string
39
+ shell: Shell | null
40
+ stream?: TurnInput['stream']
41
+ schedule?: Schedule
42
+ port?: number
43
+ distDir?: string
44
+ attachmentsDir?: string
45
+ /** The scheduled task must not adopt its own cwd as a project. */
46
+ adoptRoot?: boolean
47
+ }
48
+
49
+ export type ServerHandle = {
50
+ port: number
51
+ url: string
52
+ stop: () => Promise<void>
53
+ }
54
+
55
+ export function startServer(options: ServerOptions): ServerHandle {
56
+ pruneBashLogs(bashOutputDir())
57
+ if (options.shell) killMarkedOrphans(options.shell.path)
58
+ for (const id of listNativeChatIds(options.db)) repair(options.db, id, INTERRUPTED)
59
+ if (options.adoptRoot !== false) ensureWorkspace(options.db, options.root)
60
+
61
+ let publish = (_topic: string, _data: string): void => {}
62
+ const baseHub = createHub((topic, event) => publish(topic, JSON.stringify(event)), options.schedule)
63
+ const watch = createWorkspaceWatch((workspaceId) => baseHub.fileChanged(workspaceId, null, null))
64
+ watch.sync(listWorkspaces(options.db))
65
+ const hub: Hub = {
66
+ ...baseHub,
67
+ workspaceUpserted(workspace) {
68
+ watch.add(workspace.id, workspace.root_path)
69
+ baseHub.workspaceUpserted(workspace)
70
+ },
71
+ workspaceDeleted(id) {
72
+ watch.remove(id)
73
+ baseHub.workspaceDeleted(id)
74
+ },
75
+ }
76
+ const distDir = options.distDir ?? join(import.meta.dir, '../web/dist')
77
+
78
+ let deps: ChatDeps | undefined
79
+ // `stop` closes the database before the asynchronous tree killer reports back; a late
80
+ // job event must not touch the closed handle.
81
+ let stopped = false
82
+ const jobs = createJobRegistry({
83
+ onStarted: (job) => {
84
+ if (!stopped) baseHub.jobStarted(job.chatId, job)
85
+ },
86
+ onOutput: (chatId, jobId, chunk, offset) => {
87
+ if (!stopped) baseHub.pushJobOutput(chatId, jobId, chunk, offset)
88
+ },
89
+ onFinished: (job, cause) => {
90
+ if (stopped) return
91
+ baseHub.jobFinished(job.chatId, job)
92
+ const chat = getChat(options.db, job.chatId)
93
+ const workspace = chat ? getWorkspace(options.db, chat.workspace_id) : undefined
94
+ if (workspace) baseHub.fileChanged(workspace.id, null, null)
95
+ if (cause === 'exit' || cause === 'human') {
96
+ if (deps) jobCompletionRun(deps, job.chatId)
97
+ }
98
+ },
99
+ })
100
+ deps = { db: options.db, config: options.config, hub, shell: options.shell, stream: options.stream, jobs }
101
+
102
+ const presence: Presence = { clients: 0, show: null }
103
+ const server = Bun.serve({
104
+ hostname: '127.0.0.1',
105
+ port: options.port ?? options.config.port,
106
+ // A giant JSON or multipart body must fail before it is buffered in memory.
107
+ maxRequestBodySize: 16 * 1024 * 1024,
108
+ fetch(req, bun) {
109
+ return route(req, bun, options, deps!, distDir, presence)
110
+ },
111
+ websocket: {
112
+ open(ws) {
113
+ presence.clients += 1
114
+ ws.subscribe(GLOBAL_TOPIC)
115
+ },
116
+ close() {
117
+ presence.clients = Math.max(0, presence.clients - 1)
118
+ },
119
+ message(ws, raw) {
120
+ onClient(ws, raw, deps!)
121
+ },
122
+ },
123
+ })
124
+
125
+ publish = (topic, data) => {
126
+ server.publish(topic, data)
127
+ }
128
+
129
+ const port = server.port ?? options.config.port
130
+ return {
131
+ port,
132
+ url: `http://127.0.0.1:${port}/?token=${encodeURIComponent(options.config.token)}`,
133
+ async stop() {
134
+ stopped = true
135
+ stopAllAcp()
136
+ stopAcpCatalog()
137
+ watch.close()
138
+ await jobs.stopAll()
139
+ server.stop(true)
140
+ },
141
+ }
142
+ }
143
+
144
+ type Presence = { clients: number; show: FolderShow | null }
145
+
146
+ function route(
147
+ req: Request,
148
+ bun: { port: number | undefined; upgrade(request: Request): boolean },
149
+ options: ServerOptions,
150
+ deps: ChatDeps,
151
+ distDir: string,
152
+ presence: Presence,
153
+ ): Response | undefined | Promise<Response> {
154
+ const url = new URL(req.url)
155
+ const denied = rejectForeign(req, bun.port)
156
+ if (denied) return denied
157
+ if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/index.html')) {
158
+ return serveDist(distDir, 'index.html')
159
+ }
160
+ if (req.method === 'GET' && url.pathname.startsWith('/dist/')) {
161
+ return serveDist(distDir, url.pathname.slice('/dist/'.length))
162
+ }
163
+ if (url.pathname === '/ws') {
164
+ if (url.searchParams.get('token') !== options.config.token) return fail(401, 'Нужен токен')
165
+ if (bun.upgrade(req)) return undefined
166
+ return fail(400, 'Сокет не открылся')
167
+ }
168
+ if (bearer(req) !== options.config.token) return fail(401, 'Нужен токен')
169
+ const upload = req.method === 'POST' && /^\/api\/workspaces\/[^/]+\/upload$/.test(url.pathname)
170
+ const attachmentsUpload = req.method === 'POST' && url.pathname === '/api/attachments'
171
+ if (isWrite(req.method) && !isJson(req) && !((upload || attachmentsUpload) && isMultipart(req))) {
172
+ return fail(415, 'Нужен application/json')
173
+ }
174
+ return api(req, url, options, deps, presence)
175
+ }
176
+
177
+ const DIST_TYPES: Record<string, string> = {
178
+ '.html': 'text/html; charset=utf-8',
179
+ '.js': 'text/javascript; charset=utf-8',
180
+ '.css': 'text/css; charset=utf-8',
181
+ '.map': 'application/json; charset=utf-8',
182
+ '.woff2': 'font/woff2',
183
+ '.ttf': 'font/ttf',
184
+ '.svg': 'image/svg+xml',
185
+ }
186
+
187
+ async function serveDist(distDir: string, rel: string): Promise<Response> {
188
+ let decoded: string
189
+ try {
190
+ decoded = decodeURIComponent(rel)
191
+ } catch {
192
+ return fail(404, 'Not found')
193
+ }
194
+ if (decoded.includes('\0')) return fail(404, 'Not found')
195
+
196
+ const resolved = resolve(distDir, decoded)
197
+ const inside = relative(distDir, resolved)
198
+ if (
199
+ inside === '' ||
200
+ inside === '..' ||
201
+ inside.startsWith('../') ||
202
+ inside.startsWith('..\\') ||
203
+ isAbsolute(inside)
204
+ ) {
205
+ return fail(404, 'Not found')
206
+ }
207
+
208
+ const file = Bun.file(resolved)
209
+ if (!(await file.exists())) {
210
+ if (resolved === resolve(distDir, 'index.html')) {
211
+ return new Response('Клиент не собран: bun run build', {
212
+ status: 503,
213
+ headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' },
214
+ })
215
+ }
216
+ return fail(404, 'Not found')
217
+ }
218
+
219
+ const type = DIST_TYPES[extname(resolved).toLowerCase()] ?? 'application/octet-stream'
220
+ return new Response(file, {
221
+ headers: { 'Content-Type': type, 'Cache-Control': 'no-store' },
222
+ })
223
+ }
224
+
225
+ function api(
226
+ req: Request,
227
+ url: URL,
228
+ options: ServerOptions,
229
+ deps: ChatDeps,
230
+ presence: Presence,
231
+ ): Promise<Response> | Response {
232
+ const { db, config } = options
233
+ const { hub, jobs } = deps
234
+ const parts = url.pathname
235
+ .split('/')
236
+ .filter(Boolean)
237
+ .map((part) => {
238
+ try {
239
+ return decodeURIComponent(part)
240
+ } catch {
241
+ return part
242
+ }
243
+ })
244
+ if (parts.length === 2 && parts[0] === 'api' && parts[1] === 'status' && req.method === 'GET') {
245
+ const runs = activeRunCount()
246
+ const runningJobs = jobs.runningCount()
247
+ return Response.json({
248
+ gitBash: options.shell?.path ?? null,
249
+ contextWindow: config.contextWindow,
250
+ engines: listEngines(config, acpOverride(db), providerEnabled(getProvider(db, 'acp:cursor'))),
251
+ clients: presence.clients,
252
+ activeRuns: runs,
253
+ runningJobs,
254
+ busy: runs + runningJobs > 0,
255
+ show: presence.show,
256
+ })
257
+ }
258
+ if (isShowRoute(parts, req.method)) {
259
+ return showWorkspace(req, db, hub, presence.show).then((shown) => {
260
+ if (shown.response.ok) presence.show = shown.show
261
+ return shown.response
262
+ })
263
+ }
264
+ if (isWorkspacesRoute(parts, req.method)) return workspacesRoute(req, db, hub, jobs, parts[2] ?? '')
265
+ if (isBrowseRoute(parts, req.method)) return browseRoute(url)
266
+ if (isAttachmentsRoute(parts, req.method)) {
267
+ return attachmentsRoute(req, url, db, options.attachmentsDir)
268
+ }
269
+ if (isPreviewRoute(parts, req.method)) return previewRoute(req)
270
+ if (isFilesRoute(parts)) return filesRoute(req, url, db, hub, parts[2] ?? '', parts[3] ?? '')
271
+ if (isGitRoute(parts)) return gitRoute(req, url, db, hub, config, deps.shell, parts[2] ?? '', parts[4] ?? '')
272
+ if (isProvidersRoute(parts)) return providersRoute(req, db, config, parts)
273
+ if (isChatsRoute(parts)) return chatsRoute(req, deps, parts)
274
+ return fail(404, 'Не найдено')
275
+ }
276
+
277
+ function onClient(ws: ServerWebSocket<undefined>, raw: string | Buffer, deps: ChatDeps): void {
278
+ const { db, hub, jobs } = deps
279
+ let parsed: unknown
280
+ try {
281
+ parsed = JSON.parse(typeof raw === 'string' ? raw : raw.toString())
282
+ } catch {
283
+ return
284
+ }
285
+ if (!isRecord(parsed)) return
286
+ if (typeof parsed.sub === 'string') {
287
+ ws.subscribe(chatTopic(parsed.sub))
288
+ const messages = getChat(db, parsed.sub) ? listMessages(db, parsed.sub).map(messageView) : []
289
+ const jobsOfChat = getChat(db, parsed.sub) ? jobs.list(parsed.sub) : []
290
+ ws.send(JSON.stringify(hub.snapshot(parsed.sub, messages, jobsOfChat)))
291
+ }
292
+ if (typeof parsed.unsub === 'string') ws.unsubscribe(chatTopic(parsed.unsub))
293
+ }
294
+
295
+ function rejectForeign(req: Request, port: number | undefined): Response | null {
296
+ const bound = port ?? 0
297
+ if (!allowedHost(req.headers.get('host'), bound)) return fail(403, 'Чужой Host')
298
+ const origin = req.headers.get('origin')
299
+ if (origin && !allowedOrigin(origin, bound)) return fail(403, 'Чужой Origin')
300
+ return null
301
+ }
302
+
303
+ /**
304
+ * On port 80 the browser omits the default port: `Host: 127.0.0.1` and
305
+ * `Origin: http://127.0.0.1`. Both spellings are the same origin there.
306
+ */
307
+ function allowedHost(host: string | null, port: number): boolean {
308
+ if (host === `127.0.0.1:${port}`) return true
309
+ return port === 80 && host === '127.0.0.1'
310
+ }
311
+
312
+ function allowedOrigin(origin: string, port: number): boolean {
313
+ if (origin === `http://127.0.0.1:${port}`) return true
314
+ return port === 80 && origin === 'http://127.0.0.1'
315
+ }
316
+
317
+ function bearer(req: Request): string | null {
318
+ const header = req.headers.get('authorization')
319
+ if (!header?.startsWith('Bearer ')) return null
320
+ const token = header.slice('Bearer '.length).trim()
321
+ return token || null
322
+ }
323
+
324
+ function isWrite(method: string): boolean {
325
+ return method === 'POST' || method === 'PUT' || method === 'PATCH'
326
+ }
327
+
328
+ function isJson(req: Request): boolean {
329
+ const header = req.headers.get('content-type')
330
+ if (!header) return false
331
+ return header.split(';')[0]?.trim().toLowerCase() === 'application/json'
332
+ }
333
+
334
+ function isMultipart(req: Request): boolean {
335
+ const header = req.headers.get('content-type')
336
+ if (!header) return false
337
+ return header.split(';')[0]?.trim().toLowerCase() === 'multipart/form-data'
338
+ }
339
+
340
+ export function bootDaemon(adoptRoot = true): ServerHandle {
341
+ const home = pointerHome()
342
+ const config = loadConfig(home)
343
+ const db = openDatabase(join(home, 'state.db'))
344
+ const path = findGitBash(config)
345
+ if (path === null) console.warn(GIT_MISSING)
346
+ const shell: Shell | null = path === null ? null : { path, maxTimeout: config.bashTimeout }
347
+ const running = startServer({ db, config, root: process.cwd(), shell, adoptRoot })
348
+ warmAcpCatalog(db, config)
349
+ console.log(running.url)
350
+ return running
351
+ }
352
+
353
+ if (import.meta.main) bootDaemon()
@@ -0,0 +1,34 @@
1
+ import { streamLLM } from './providers/opencode'
2
+
3
+ const key = process.env.OPENCODE_API_KEY
4
+ if (!key) {
5
+ console.error('OPENCODE_API_KEY не задан. Впиши его в .env в корне проекта.')
6
+ process.exit(1)
7
+ }
8
+
9
+ let thinkingStarted = false
10
+ for await (const event of streamLLM({
11
+ model: 'deepseek-v4.1-flash',
12
+ messages: [{ role: 'user', content: { text: 'Ответь одним коротким предложением по-русски.' } }],
13
+ })) {
14
+ if (event.type === 'thinking_delta') {
15
+ if (!thinkingStarted) {
16
+ process.stderr.write('thinking: ')
17
+ thinkingStarted = true
18
+ }
19
+ process.stderr.write(event.text)
20
+ continue
21
+ }
22
+ if (event.type === 'text_delta') {
23
+ process.stdout.write(event.text)
24
+ continue
25
+ }
26
+ if (event.type === 'done') {
27
+ if (thinkingStarted) process.stderr.write('\n')
28
+ process.stdout.write('\n')
29
+ console.log(JSON.stringify(event.usage))
30
+ if (event.stopReason !== 'end' || (event.usage.input === 0 && event.usage.output === 0)) {
31
+ process.exitCode = 1
32
+ }
33
+ }
34
+ }