@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,115 @@
1
+ import type { Database } from 'bun:sqlite'
2
+ import { getWorkspace } from '../db'
3
+ import { deleteEntry, readText, readTree, renameEntry, saveUploads, writeText } from '../files'
4
+ import type { Hub } from '../hub'
5
+ import { fail, guardFile, isRecord, readJson } from './reply'
6
+
7
+ export function isFilesRoute(parts: string[]): boolean {
8
+ return (
9
+ parts.length === 4 &&
10
+ parts[0] === 'api' &&
11
+ parts[1] === 'workspaces' &&
12
+ (parts[3] === 'tree' || parts[3] === 'file' || parts[3] === 'upload')
13
+ )
14
+ }
15
+
16
+ export function filesRoute(
17
+ req: Request,
18
+ url: URL,
19
+ db: Database,
20
+ hub: Hub,
21
+ workspaceId: string,
22
+ action: string,
23
+ ): Promise<Response> | Response {
24
+ const workspace = getWorkspace(db, workspaceId)
25
+ if (!workspace) return fail(404, 'Папка не найдена')
26
+ const root = workspace.root_path
27
+ const path = url.searchParams.get('path') ?? ''
28
+ if (action === 'tree') {
29
+ if (req.method !== 'GET') return fail(404, 'Не найдено')
30
+ return guardFile(() => Response.json(readTree(root)))
31
+ }
32
+ if (action === 'upload') {
33
+ if (req.method !== 'POST') return fail(404, 'Не найдено')
34
+ return guardFile(() => postUpload(req, root, workspace.id, url.searchParams.get('dir') ?? '', hub))
35
+ }
36
+ if (req.method === 'GET') return guardFile(() => Response.json(readText(root, path)))
37
+ if (req.method === 'PUT') return guardFile(() => putFile(req, root, workspace.id, path, hub))
38
+ if (req.method === 'PATCH') return guardFile(() => patchFile(req, root, workspace.id, path, hub))
39
+ if (req.method === 'DELETE') {
40
+ return guardFile(() => deleteFile(root, workspace.id, path, url.searchParams.get('recursive') === 'true', hub))
41
+ }
42
+ return fail(404, 'Не найдено')
43
+ }
44
+
45
+ async function putFile(
46
+ req: Request,
47
+ root: string,
48
+ workspaceId: string,
49
+ path: string,
50
+ hub: Hub,
51
+ ): Promise<Response> {
52
+ const body = await readJson(req)
53
+ if (!isRecord(body) || typeof body.content !== 'string') return fail(400, 'Нужен content')
54
+ const declared = 'baseHash' in body
55
+ if (declared && body.baseHash !== null && typeof body.baseHash !== 'string') {
56
+ return fail(400, 'baseHash должен быть строкой или null')
57
+ }
58
+ const result = writeText(root, path, body.content, declared ? (body.baseHash as string | null) : undefined)
59
+ if (result.status === 'conflict') {
60
+ return Response.json(
61
+ {
62
+ error: 'Файл изменился на диске',
63
+ path: result.path,
64
+ hash: result.hash,
65
+ content: result.content,
66
+ },
67
+ { status: 409 },
68
+ )
69
+ }
70
+ hub.fileChanged(workspaceId, result.path, result.hash)
71
+ return Response.json({ path: result.path, hash: result.hash })
72
+ }
73
+
74
+ async function patchFile(
75
+ req: Request,
76
+ root: string,
77
+ workspaceId: string,
78
+ path: string,
79
+ hub: Hub,
80
+ ): Promise<Response> {
81
+ const body = await readJson(req)
82
+ if (!isRecord(body) || typeof body.to !== 'string' || body.to === '') return fail(400, 'Нужен to')
83
+ const result = renameEntry(root, path, body.to)
84
+ hub.fileChanged(workspaceId, result.from, null)
85
+ hub.fileChanged(workspaceId, result.to, result.hash)
86
+ return Response.json(result)
87
+ }
88
+
89
+ function deleteFile(root: string, workspaceId: string, path: string, recursive: boolean, hub: Hub): Response {
90
+ const result = deleteEntry(root, path, recursive)
91
+ hub.fileChanged(workspaceId, result.path, null)
92
+ return Response.json(result)
93
+ }
94
+
95
+ async function postUpload(
96
+ req: Request,
97
+ root: string,
98
+ workspaceId: string,
99
+ dir: string,
100
+ hub: Hub,
101
+ ): Promise<Response> {
102
+ let form: FormData
103
+ try {
104
+ form = await req.formData()
105
+ } catch {
106
+ return fail(400, 'Нужен multipart/form-data')
107
+ }
108
+ const files: File[] = []
109
+ form.forEach((value) => {
110
+ if (typeof value !== 'string') files.push(value)
111
+ })
112
+ const saved = await saveUploads(root, dir, files)
113
+ for (const file of saved) hub.fileChanged(workspaceId, file.path, file.hash)
114
+ return Response.json({ files: saved }, { status: 201 })
115
+ }
@@ -0,0 +1,84 @@
1
+ import { join } from 'node:path'
2
+ import type { Database } from 'bun:sqlite'
3
+ import { hashOnDisk } from '../changes'
4
+ import type { Config } from '../config'
5
+ import { getWorkspace, type WorkspaceRow } from '../db'
6
+ import { gitBranches, gitCheckout, gitCommit, gitFile, gitStage, gitStatus, gitUnstage, type GitOptions } from '../git'
7
+ import type { Hub } from '../hub'
8
+ import type { Shell } from '../tools'
9
+ import { fail, guardGit, isRecord, readJson } from './reply'
10
+
11
+ export function isGitRoute(parts: string[]): boolean {
12
+ return parts.length === 5 && parts[0] === 'api' && parts[1] === 'workspaces' && parts[3] === 'git'
13
+ }
14
+
15
+ export function gitRoute(
16
+ req: Request,
17
+ url: URL,
18
+ db: Database,
19
+ hub: Hub,
20
+ config: Config,
21
+ shell: Shell | null,
22
+ workspaceId: string,
23
+ action: string,
24
+ ): Promise<Response> | Response {
25
+ const workspace = getWorkspace(db, workspaceId)
26
+ if (!workspace) return fail(404, 'Папка не найдена')
27
+ if (shell === null) return fail(503, 'Git не найден')
28
+ return guardGit(() => gitAction(req, url, workspace, action, hub, config))
29
+ }
30
+
31
+ async function gitAction(
32
+ req: Request,
33
+ url: URL,
34
+ workspace: WorkspaceRow,
35
+ action: string,
36
+ hub: Hub,
37
+ config: Config,
38
+ ): Promise<Response> {
39
+ const root = workspace.root_path
40
+ const options: GitOptions = { gitPath: config.gitPath, signal: req.signal }
41
+ if (action === 'status' && req.method === 'GET') {
42
+ return Response.json(await gitStatus(root, options))
43
+ }
44
+ if (action === 'file' && req.method === 'GET') {
45
+ const ref = url.searchParams.get('ref') || 'HEAD'
46
+ return Response.json(await gitFile(root, ref, url.searchParams.get('path') ?? '', options))
47
+ }
48
+ if (action === 'branches' && req.method === 'GET') {
49
+ return Response.json({ branches: await gitBranches(root, options) })
50
+ }
51
+ if ((action === 'stage' || action === 'unstage') && req.method === 'POST') {
52
+ const body = await readJson(req)
53
+ const all = isRecord(body) && body.all === true
54
+ const paths = isRecord(body) && isPathList(body.paths) ? body.paths : null
55
+ if (!all && paths === null) return fail(400, 'Нужны paths или all')
56
+ if (action === 'stage') await gitStage(root, all ? null : paths, options)
57
+ else await gitUnstage(root, all ? null : paths, options)
58
+ return Response.json({ ok: true })
59
+ }
60
+ if (action === 'commit' && req.method === 'POST') {
61
+ const body = await readJson(req)
62
+ const message = isRecord(body) && typeof body.message === 'string' ? body.message.trim() : ''
63
+ if (message === '') return fail(400, 'Нужно сообщение коммита')
64
+ const amend = isRecord(body) && body.amend === true
65
+ return Response.json(await gitCommit(root, message, amend, options))
66
+ }
67
+ if (action === 'checkout' && req.method === 'POST') {
68
+ const body = await readJson(req)
69
+ const branch = isRecord(body) && typeof body.branch === 'string' ? body.branch.trim() : ''
70
+ if (branch === '') return fail(400, 'Нужно имя ветки')
71
+ const create = isRecord(body) && body.create === true
72
+ const result = await gitCheckout(root, branch, create, options)
73
+ for (const path of result.changed) {
74
+ hub.fileChanged(workspace.id, path, hashOnDisk(join(root, path)))
75
+ }
76
+ return Response.json(result)
77
+ }
78
+ return fail(404, 'Не найдено')
79
+ }
80
+
81
+ function isPathList(value: unknown): value is string[] {
82
+ // An empty list would mean "everything" to git stage/unstage, not "nothing".
83
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'string' && item !== '')
84
+ }
@@ -0,0 +1,21 @@
1
+ import { fetchPreview } from '../linkPreview'
2
+ import { fail, isRecord, readJson } from './reply'
3
+
4
+ export function isPreviewRoute(parts: string[], method: string): boolean {
5
+ return parts.length === 2 && parts[0] === 'api' && parts[1] === 'link-preview' && method === 'POST'
6
+ }
7
+
8
+ export async function previewRoute(req: Request): Promise<Response> {
9
+ const body = await readJson(req)
10
+ if (!isRecord(body) || typeof body.url !== 'string') return fail(400, 'Нужен url')
11
+ let url: URL
12
+ try {
13
+ url = new URL(body.url)
14
+ } catch {
15
+ return fail(400, 'Ссылка должна быть http или https')
16
+ }
17
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
18
+ return fail(400, 'Ссылка должна быть http или https')
19
+ }
20
+ return Response.json(await fetchPreview(url.toString()))
21
+ }
@@ -0,0 +1,200 @@
1
+ import type { Database } from 'bun:sqlite'
2
+ import type { ProviderCatalog, ProviderInfo } from '../../shared/types'
3
+ import type { Config } from '../config'
4
+ import { ensureAcpCatalog } from '../acp/catalog'
5
+ import { acpAgent, resolveAcpCommand } from '../engines'
6
+ import { fail, isRecord, readJson } from './reply'
7
+ import { apiKeyFor, baseUrlFor, providerById } from '../providers/registry'
8
+ import { modelsUrl, type FetchLike } from '../providers/opencode'
9
+ import {
10
+ acpOverride,
11
+ addModel,
12
+ getProvider,
13
+ listModels,
14
+ listProviders,
15
+ parseArgs,
16
+ providerEnabled,
17
+ parseModelIds,
18
+ removeModel,
19
+ replaceModels,
20
+ savedDefaultModel,
21
+ setDefaultModel,
22
+ updateProvider,
23
+ type ProviderRow,
24
+ } from '../providers/store'
25
+
26
+ export type ProviderRouteDeps = {
27
+ fetch?: FetchLike
28
+ }
29
+
30
+ export function isProvidersRoute(parts: string[]): boolean {
31
+ if (parts[0] !== 'api') return false
32
+ if (parts[1] === 'providers') return true
33
+ return parts[1] === 'settings' && parts[2] === 'default-model'
34
+ }
35
+
36
+ export function providersRoute(
37
+ req: Request,
38
+ db: Database,
39
+ config: Config,
40
+ parts: string[],
41
+ deps?: ProviderRouteDeps,
42
+ ): Promise<Response> | Response {
43
+ if (parts[1] === 'settings' && parts[2] === 'default-model' && parts.length === 3 && req.method === 'PUT') {
44
+ return putDefaultModel(req, db, config)
45
+ }
46
+ if (parts[1] !== 'providers') return fail(404, 'Не найдено')
47
+ if (parts.length === 2 && req.method === 'GET') return Response.json(catalog(db, config))
48
+
49
+ const id = parts[2] ?? ''
50
+ if (!getProvider(db, id)) return fail(404, 'Провайдер не найден')
51
+ if (parts.length === 4 && parts[3] === 'options' && req.method === 'GET') {
52
+ if (acpAgent(id) === null) return fail(400, 'Это не ACP-провайдер')
53
+ return Response.json(ensureAcpCatalog(db, config, id))
54
+ }
55
+ if (parts.length === 3 && req.method === 'PUT') return putProvider(req, db, config, id)
56
+ if (parts.length === 4 && parts[3] === 'models' && req.method === 'POST') return postModel(req, db, config, id)
57
+ if (parts.length === 5 && parts[3] === 'models' && parts[4] === 'refresh' && req.method === 'POST') {
58
+ return refreshModels(db, config, id, deps?.fetch ?? fetch)
59
+ }
60
+ if (parts.length === 5 && parts[3] === 'models' && req.method === 'DELETE') {
61
+ removeModel(db, id, parts[4] ?? '')
62
+ return Response.json(catalog(db, config))
63
+ }
64
+ return fail(404, 'Не найдено')
65
+ }
66
+
67
+ function catalog(db: Database, config: Config): ProviderCatalog {
68
+ return {
69
+ providers: listProviders(db).map((row) => providerView(db, config, row)),
70
+ defaultModel: savedDefaultModel(db),
71
+ }
72
+ }
73
+
74
+ function providerView(db: Database, config: Config, row: ProviderRow): ProviderInfo {
75
+ const spec = providerById(row.id)
76
+ const kind = row.kind
77
+ const agent = kind === 'acp' ? acpAgent(row.id) : null
78
+ return {
79
+ id: row.id,
80
+ kind,
81
+ label: row.label,
82
+ baseUrl: row.base_url,
83
+ hasKey: Boolean(row.api_key),
84
+ command: row.command,
85
+ args: parseArgs(row.args_json),
86
+ cwd: row.cwd,
87
+ available: agent ? resolveAcpCommand(config, agent, acpOverride(db)) !== null : null,
88
+ models: listModels(db, row.id),
89
+ fallbackBaseUrl: spec ? baseUrlFor(config, spec, null) : null,
90
+ fallbackCommand: kind === 'acp' ? config.acpCommand : null,
91
+ enabled: providerEnabled(row),
92
+ }
93
+ }
94
+
95
+ async function putProvider(req: Request, db: Database, config: Config, id: string): Promise<Response> {
96
+ const body = await readJson(req)
97
+ if (!isRecord(body)) return fail(400, 'Нужен объект')
98
+ const patch: Parameters<typeof updateProvider>[2] = {}
99
+ if ('label' in body) {
100
+ if (typeof body.label !== 'string' || body.label.trim() === '') return fail(400, 'Нужно имя')
101
+ patch.label = body.label.trim()
102
+ }
103
+ if ('baseUrl' in body) {
104
+ const baseUrl = optionalString(body.baseUrl)
105
+ if (baseUrl instanceof Response) return baseUrl
106
+ if (baseUrl && !/^https?:\/\//i.test(baseUrl)) return fail(400, 'base URL должен начинаться с http:// или https://')
107
+ patch.baseUrl = baseUrl
108
+ }
109
+ if ('apiKey' in body) {
110
+ if (typeof body.apiKey !== 'string') return fail(400, 'Ключ должен быть строкой')
111
+ patch.apiKey = body.apiKey.trim() === '' ? null : body.apiKey
112
+ }
113
+ if ('command' in body) {
114
+ const command = optionalString(body.command)
115
+ if (command instanceof Response) return command
116
+ patch.command = command
117
+ }
118
+ if ('cwd' in body) {
119
+ const cwd = optionalString(body.cwd)
120
+ if (cwd instanceof Response) return cwd
121
+ patch.cwd = cwd
122
+ }
123
+ if ('enabled' in body) {
124
+ if (typeof body.enabled !== 'boolean') return fail(400, 'enabled должен быть boolean')
125
+ patch.enabled = body.enabled
126
+ }
127
+ if ('args' in body) {
128
+ if (body.args === null) patch.args = null
129
+ else if (!Array.isArray(body.args) || !body.args.every((item) => typeof item === 'string')) {
130
+ return fail(400, 'args должен быть массивом строк')
131
+ } else patch.args = body.args
132
+ }
133
+ if (Object.keys(patch).length === 0) return fail(400, 'Нечего сохранять')
134
+ updateProvider(db, id, patch)
135
+ return Response.json(catalog(db, config))
136
+ }
137
+
138
+ async function postModel(req: Request, db: Database, config: Config, id: string): Promise<Response> {
139
+ const body = await readJson(req)
140
+ if (!isRecord(body) || typeof body.model !== 'string') return fail(400, 'Нужна модель')
141
+ if (!addModel(db, id, body.model)) return fail(400, 'Некорректный id модели')
142
+ return Response.json(catalog(db, config))
143
+ }
144
+
145
+ async function refreshModels(
146
+ db: Database,
147
+ config: Config,
148
+ id: string,
149
+ fetchImpl: FetchLike,
150
+ ): Promise<Response> {
151
+ const spec = providerById(id)
152
+ const row = getProvider(db, id)
153
+ if (!spec || !row) return fail(400, 'Модели этого подключения задаются вручную')
154
+ const baseUrl = baseUrlFor(config, spec, row)
155
+ const apiKey = apiKeyFor(spec, row)
156
+ const headers: Record<string, string> = {}
157
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`
158
+ let response: Response
159
+ try {
160
+ response = await fetchImpl(modelsUrl(baseUrl, spec.chatLayout), { headers })
161
+ } catch (error) {
162
+ return fail(502, error instanceof Error ? error.message : 'Не удалось запросить модели')
163
+ }
164
+ if (!response.ok) return fail(502, `Список моделей: ${response.status}`)
165
+ let body: unknown
166
+ try {
167
+ body = await response.json()
168
+ } catch {
169
+ return fail(502, 'Список моделей: ответ не JSON')
170
+ }
171
+ const ids = parseModelIds(body)
172
+ if (!ids) return fail(502, 'Список моделей: неожиданный формат')
173
+ replaceModels(db, id, ids)
174
+ return Response.json(catalog(db, config))
175
+ }
176
+
177
+ async function putDefaultModel(req: Request, db: Database, config: Config): Promise<Response> {
178
+ const body = await readJson(req)
179
+ if (!isRecord(body) || typeof body.model !== 'string') return fail(400, 'Нужна модель')
180
+ const model = body.model.trim()
181
+ if (model === '') {
182
+ setDefaultModel(db, null)
183
+ return Response.json(catalog(db, config))
184
+ }
185
+ const slash = model.indexOf('/')
186
+ const providerId = slash > 0 ? model.slice(0, slash) : ''
187
+ const bare = slash > 0 ? model.slice(slash + 1) : ''
188
+ if ((providerId !== 'opencode-go' && providerId !== 'openai') || !listModels(db, providerId).includes(bare)) {
189
+ return fail(400, 'Модель не из списка')
190
+ }
191
+ setDefaultModel(db, model)
192
+ return Response.json(catalog(db, config))
193
+ }
194
+
195
+ function optionalString(value: unknown): string | null | Response {
196
+ if (value === null) return null
197
+ if (typeof value !== 'string') return fail(400, 'Ожидалась строка')
198
+ const trimmed = value.trim()
199
+ return trimmed === '' ? null : trimmed
200
+ }
@@ -0,0 +1,38 @@
1
+ import { FileError } from '../files'
2
+ import { GitError } from '../git'
3
+
4
+ export function fail(status: number, error: string): Response {
5
+ return Response.json({ error }, { status })
6
+ }
7
+
8
+ export async function readJson(req: Request): Promise<unknown> {
9
+ try {
10
+ return await req.json()
11
+ } catch {
12
+ return null
13
+ }
14
+ }
15
+
16
+ export function isRecord(value: unknown): value is Record<string, unknown> {
17
+ return typeof value === 'object' && value !== null
18
+ }
19
+
20
+ /** Runs one file operation, turning its expected failures into HTTP responses. */
21
+ export async function guardFile(work: () => Response | Promise<Response>): Promise<Response> {
22
+ try {
23
+ return await work()
24
+ } catch (error) {
25
+ if (error instanceof FileError) return fail(error.status, error.message)
26
+ throw error
27
+ }
28
+ }
29
+
30
+ /** Runs one git operation, turning its expected failures into HTTP responses. */
31
+ export async function guardGit(work: () => Promise<Response>): Promise<Response> {
32
+ try {
33
+ return await work()
34
+ } catch (error) {
35
+ if (error instanceof GitError) return fail(error.status, error.message)
36
+ throw error
37
+ }
38
+ }