@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/hub.ts ADDED
@@ -0,0 +1,521 @@
1
+ import type { MessageRow, WorkspaceRow } from './db'
2
+ import { pruneJobInfos } from './jobs'
3
+ import type {
4
+ AcpQuestion,
5
+ AssistantDelta,
6
+ ChatSnapshot,
7
+ ChatUpserted,
8
+ Inflight,
9
+ JobFinished,
10
+ JobInfo,
11
+ JobOutputEvent,
12
+ JobStarted,
13
+ QueueUpdated,
14
+ RunQuestionEvent,
15
+ ReasoningLevel,
16
+ RunRetry,
17
+ RunStatus,
18
+ RunStatusEvent,
19
+ ServerEvent,
20
+ SnapshotMessage,
21
+ StartedToolCall,
22
+ ToolOutput,
23
+ ToolOutputState,
24
+ ToolRunning,
25
+ ToolStarted,
26
+ } from '../shared/types'
27
+
28
+ export const GLOBAL_TOPIC = 'global'
29
+ export const BATCH_MS = 33
30
+ export const TOOL_TAIL_LIMIT = 200 * 1024
31
+
32
+ export function chatTopic(chatId: string): string {
33
+ return `chat:${chatId}`
34
+ }
35
+
36
+ export type Schedule = (callback: () => void, delayMs: number) => () => void
37
+
38
+ export type Hub = {
39
+ snapshot(chatId: string, messages: SnapshotMessage[], jobs?: JobInfo[]): ChatSnapshot
40
+ pushDelta(chatId: string, delta: { text?: string; thinking?: string }): void
41
+ toolStarted(chatId: string, callId: string, name: string): void
42
+ toolRunning(chatId: string, callId: string, args: unknown): void
43
+ pushToolOutput(chatId: string, callId: string, chunk: string): void
44
+ flush(chatId: string): void
45
+ appended(chatId: string, message: SnapshotMessage): void
46
+ setRun(chatId: string, runId: string | null, status: RunStatus, meta?: RunMeta): void
47
+ setTitle(chatId: string, title: string): void
48
+ upsertChat(chatId: string, meta: RunMeta & { status?: RunStatus }): void
49
+ resync(chatId: string, messages: SnapshotMessage[]): void
50
+ retry(chatId: string, attempt: number): void
51
+ question(chatId: string, question: AcpQuestion | null): void
52
+ setQueue(chatId: string, queue: string[]): void
53
+ jobStarted(chatId: string, job: JobInfo): void
54
+ pushJobOutput(chatId: string, jobId: string, chunk: string, offset: number): void
55
+ jobFinished(chatId: string, job: JobInfo): void
56
+ fileChanged(workspaceId: string, path: string | null, hash: string | null): void
57
+ workspaceUpserted(workspace: WorkspaceRow): void
58
+ workspaceDeleted(id: string): void
59
+ workspaceFocus(id: string): void
60
+ chatDeleted(chatId: string): void
61
+ }
62
+
63
+ export type RunMeta = {
64
+ title?: string
65
+ workspaceId?: string
66
+ model?: string
67
+ engine?: string
68
+ updatedAt?: number
69
+ archivedAt?: number | null
70
+ reasoning?: ReasoningLevel | null
71
+ }
72
+
73
+ type OutputChunk = { callId: string; chunk: string }
74
+ type JobChunk = { jobId: string; offset: number; chunk: string }
75
+
76
+ type Live = {
77
+ rev: number
78
+ runId: string | null
79
+ status: RunStatus
80
+ title: string
81
+ workspaceId: string
82
+ model?: string
83
+ engine?: string
84
+ updatedAt?: number
85
+ archivedAt?: number | null
86
+ reasoning?: ReasoningLevel | null
87
+ question: AcpQuestion | null
88
+ queue: string[]
89
+ jobs: JobInfo[]
90
+ sentText: string
91
+ sentThinking: string
92
+ sentTool: ToolOutputState | null
93
+ startedCalls: StartedToolCall[]
94
+ runningCallId: string | null
95
+ bufText: string
96
+ bufThinking: string
97
+ bufOutput: OutputChunk[]
98
+ bufJobOutput: JobChunk[]
99
+ // Arrival order of the kinds buffered for the next batch: text before output or the other way round.
100
+ bufOrder: Array<'text' | 'output' | 'job'>
101
+ cancel: (() => void) | null
102
+ }
103
+
104
+ export function messageView(row: MessageRow): SnapshotMessage {
105
+ const view: SnapshotMessage = {
106
+ id: row.id,
107
+ seq: row.seq,
108
+ role: row.role,
109
+ content: JSON.parse(row.content_json) as unknown,
110
+ createdAt: row.created_at,
111
+ }
112
+ if (row.details_json !== null) view.details = JSON.parse(row.details_json) as unknown
113
+ return view
114
+ }
115
+
116
+ export function createHub(publish: (topic: string, event: ServerEvent) => void, schedule: Schedule = defaultSchedule): Hub {
117
+ const chats = new Map<string, Live>()
118
+ const gone = new Set<string>()
119
+
120
+ function ensure(chatId: string): Live {
121
+ const existing = chats.get(chatId)
122
+ if (existing) return existing
123
+ const live: Live = {
124
+ rev: 0,
125
+ runId: null,
126
+ status: 'idle',
127
+ title: '',
128
+ workspaceId: '',
129
+ question: null,
130
+ queue: [],
131
+ jobs: [],
132
+ sentText: '',
133
+ sentThinking: '',
134
+ sentTool: null,
135
+ startedCalls: [],
136
+ runningCallId: null,
137
+ bufText: '',
138
+ bufThinking: '',
139
+ bufOutput: [],
140
+ bufJobOutput: [],
141
+ bufOrder: [],
142
+ cancel: null,
143
+ }
144
+ chats.set(chatId, live)
145
+ return live
146
+ }
147
+
148
+ function inflightOf(live: Live): Inflight | null {
149
+ const tool = live.sentTool
150
+ const started = live.startedCalls
151
+ const running = live.runningCallId
152
+ if (!live.sentText && !live.sentThinking && !tool && started.length === 0 && !running) return null
153
+ return {
154
+ text: live.sentText,
155
+ thinking: live.sentThinking,
156
+ ...(tool ? { tool } : {}),
157
+ ...(started.length > 0 ? { startedCalls: [...started] } : {}),
158
+ ...(running ? { runningCallId: running } : {}),
159
+ }
160
+ }
161
+
162
+ function clearTail(live: Live): void {
163
+ if (live.cancel) {
164
+ live.cancel()
165
+ live.cancel = null
166
+ }
167
+ live.bufText = ''
168
+ live.bufThinking = ''
169
+ live.bufOutput = []
170
+ // Job output outlives a run: keep its buffer and its place in the batch order.
171
+ live.bufOrder = live.bufOrder.filter((kind) => kind === 'job')
172
+ live.sentText = ''
173
+ live.sentThinking = ''
174
+ live.sentTool = null
175
+ live.startedCalls = []
176
+ live.runningCallId = null
177
+ }
178
+
179
+ function flush(chatId: string): void {
180
+ const live = chats.get(chatId)
181
+ if (!live) return
182
+ if (live.cancel) {
183
+ live.cancel()
184
+ live.cancel = null
185
+ }
186
+ if (!live.bufText && !live.bufThinking && live.bufOutput.length === 0 && live.bufJobOutput.length === 0) {
187
+ return
188
+ }
189
+ const order = live.bufOrder
190
+ live.bufOrder = []
191
+ for (const kind of order) {
192
+ if (kind === 'text') flushText(live, chatId)
193
+ else if (kind === 'output') flushOutput(live, chatId)
194
+ else flushJobOutput(live, chatId)
195
+ }
196
+ }
197
+
198
+ function flushText(live: Live, chatId: string): void {
199
+ if (!live.bufText && !live.bufThinking) return
200
+ live.rev += 1
201
+ const text = live.bufText
202
+ const thinking = live.bufThinking
203
+ live.sentText += text
204
+ live.sentThinking += thinking
205
+ live.bufText = ''
206
+ live.bufThinking = ''
207
+ const event: AssistantDelta = {
208
+ type: 'assistant.delta',
209
+ chatId,
210
+ runId: live.runId ?? '',
211
+ rev: live.rev,
212
+ }
213
+ if (text) event.text = text
214
+ if (thinking) event.thinking = thinking
215
+ publish(chatTopic(chatId), event)
216
+ }
217
+
218
+ function flushOutput(live: Live, chatId: string): void {
219
+ const chunks = live.bufOutput
220
+ live.bufOutput = []
221
+ for (const item of chunks) {
222
+ live.rev += 1
223
+ live.sentTool = tailOf(live.sentTool, item.callId, item.chunk)
224
+ const event: ToolOutput = {
225
+ type: 'tool.output',
226
+ chatId,
227
+ runId: live.runId ?? '',
228
+ rev: live.rev,
229
+ callId: item.callId,
230
+ chunk: item.chunk,
231
+ }
232
+ publish(chatTopic(chatId), event)
233
+ }
234
+ }
235
+
236
+ function flushJobOutput(live: Live, chatId: string): void {
237
+ const chunks = live.bufJobOutput
238
+ live.bufJobOutput = []
239
+ for (const item of chunks) {
240
+ const event: JobOutputEvent = {
241
+ type: 'job.output',
242
+ chatId,
243
+ jobId: item.jobId,
244
+ offset: item.offset,
245
+ chunk: item.chunk,
246
+ }
247
+ publish(chatTopic(chatId), event)
248
+ }
249
+ }
250
+
251
+ function buffer(chatId: string, live: Live, kind: 'text' | 'output' | 'job'): void {
252
+ if (!live.bufOrder.includes(kind)) live.bufOrder.push(kind)
253
+ if (live.cancel) return
254
+ live.cancel = schedule(() => flush(chatId), BATCH_MS)
255
+ }
256
+
257
+ function upsert(live: Live, chatId: string): void {
258
+ const event: ChatUpserted = {
259
+ type: 'chat.upserted',
260
+ chatId,
261
+ title: live.title,
262
+ status: live.status,
263
+ workspaceId: live.workspaceId,
264
+ }
265
+ if (live.model !== undefined) event.model = live.model
266
+ if (live.engine !== undefined) event.engine = live.engine
267
+ if (live.updatedAt !== undefined) event.updatedAt = live.updatedAt
268
+ if (live.archivedAt !== undefined) event.archivedAt = live.archivedAt
269
+ if (live.reasoning !== undefined) event.reasoning = live.reasoning
270
+ publish(GLOBAL_TOPIC, event)
271
+ }
272
+
273
+ function snapshotOf(chatId: string, messages: SnapshotMessage[], jobs?: JobInfo[]): ChatSnapshot {
274
+ const live = chats.get(chatId)
275
+ return {
276
+ type: 'chat.snapshot',
277
+ chatId,
278
+ runId: live?.runId ?? null,
279
+ rev: live?.rev ?? 0,
280
+ messages,
281
+ inflight: live ? inflightOf(live) : null,
282
+ status: live?.status ?? 'idle',
283
+ queue: live?.queue ?? [],
284
+ question: live?.question ?? null,
285
+ jobs: jobs ?? live?.jobs ?? [],
286
+ }
287
+ }
288
+
289
+ return {
290
+ snapshot: snapshotOf,
291
+ pushDelta(chatId, delta) {
292
+ if (!delta.text && !delta.thinking) return
293
+ const live = ensure(chatId)
294
+ if (delta.text) live.bufText += delta.text
295
+ if (delta.thinking) live.bufThinking += delta.thinking
296
+ buffer(chatId, live, 'text')
297
+ },
298
+ toolStarted(chatId, callId, name) {
299
+ const live = ensure(chatId)
300
+ if (!live.startedCalls.some((item) => item.callId === callId)) {
301
+ live.startedCalls.push({ callId, name })
302
+ }
303
+ const event: ToolStarted = {
304
+ type: 'tool.started',
305
+ chatId,
306
+ runId: live.runId ?? '',
307
+ rev: live.rev,
308
+ callId,
309
+ name,
310
+ }
311
+ publish(chatTopic(chatId), event)
312
+ },
313
+ toolRunning(chatId, callId, args) {
314
+ const live = ensure(chatId)
315
+ live.runningCallId = callId
316
+ const event: ToolRunning = {
317
+ type: 'tool.running',
318
+ chatId,
319
+ runId: live.runId ?? '',
320
+ rev: live.rev,
321
+ callId,
322
+ args,
323
+ }
324
+ publish(chatTopic(chatId), event)
325
+ },
326
+ pushToolOutput(chatId, callId, chunk) {
327
+ if (!chunk) return
328
+ const live = ensure(chatId)
329
+ const last = live.bufOutput.at(-1)
330
+ if (last && last.callId === callId) last.chunk += chunk
331
+ else live.bufOutput.push({ callId, chunk })
332
+ buffer(chatId, live, 'output')
333
+ },
334
+ flush,
335
+ appended(chatId, message) {
336
+ const live = ensure(chatId)
337
+ if (message.createdAt > 0) live.updatedAt = Math.max(live.updatedAt ?? 0, message.createdAt)
338
+ publish(chatTopic(chatId), {
339
+ type: 'message.appended',
340
+ chatId,
341
+ runId: live.runId,
342
+ rev: live.rev,
343
+ message,
344
+ })
345
+ if (message.role === 'assistant') clearTail(live)
346
+ if (message.role === 'tool') dropTool(live, toolCallIdOf(message))
347
+ },
348
+ setRun(chatId, runId, status, meta) {
349
+ const live = ensure(chatId)
350
+ // A new run must not inherit the thinking, text or tool tail of the one it replaced.
351
+ const freshRun = status === 'running' && live.runId !== runId
352
+ live.runId = runId
353
+ live.status = status
354
+ if (meta?.title !== undefined) live.title = meta.title
355
+ if (meta?.workspaceId !== undefined) live.workspaceId = meta.workspaceId
356
+ if (meta?.model !== undefined) live.model = meta.model
357
+ if (meta?.engine !== undefined) live.engine = meta.engine
358
+ if (meta?.updatedAt !== undefined) live.updatedAt = meta.updatedAt
359
+ if (runId === null || status !== 'running') live.question = null
360
+ if (runId === null) live.queue = []
361
+ if (freshRun || status !== 'running') clearTail(live)
362
+ const event: RunStatusEvent = {
363
+ type: 'run.status',
364
+ chatId,
365
+ runId: live.runId,
366
+ rev: live.rev,
367
+ status,
368
+ }
369
+ publish(chatTopic(chatId), event)
370
+ upsert(live, chatId)
371
+ },
372
+ setTitle(chatId, title) {
373
+ const live = ensure(chatId)
374
+ live.title = title
375
+ upsert(live, chatId)
376
+ },
377
+ upsertChat(chatId, meta) {
378
+ const live = ensure(chatId)
379
+ if (meta.title !== undefined) live.title = meta.title
380
+ if (meta.workspaceId !== undefined) live.workspaceId = meta.workspaceId
381
+ if (meta.model !== undefined) live.model = meta.model
382
+ if (meta.engine !== undefined) live.engine = meta.engine
383
+ if (meta.updatedAt !== undefined) live.updatedAt = meta.updatedAt
384
+ if (meta.archivedAt !== undefined) live.archivedAt = meta.archivedAt
385
+ if ('reasoning' in meta) live.reasoning = meta.reasoning ?? null
386
+ if (meta.status !== undefined) live.status = meta.status
387
+ upsert(live, chatId)
388
+ },
389
+ resync(chatId, messages) {
390
+ publish(chatTopic(chatId), snapshotOf(chatId, messages))
391
+ },
392
+ retry(chatId, attempt) {
393
+ const live = ensure(chatId)
394
+ const event: RunRetry = {
395
+ type: 'run.retry',
396
+ chatId,
397
+ runId: live.runId ?? '',
398
+ rev: live.rev,
399
+ attempt,
400
+ }
401
+ publish(chatTopic(chatId), event)
402
+ },
403
+ question(chatId, question) {
404
+ const live = ensure(chatId)
405
+ live.question = question
406
+ const event: RunQuestionEvent = {
407
+ type: 'run.question',
408
+ chatId,
409
+ runId: live.runId ?? '',
410
+ rev: live.rev,
411
+ question,
412
+ }
413
+ publish(chatTopic(chatId), event)
414
+ },
415
+ jobStarted(chatId, job) {
416
+ if (gone.has(chatId)) return
417
+ const live = ensure(chatId)
418
+ live.jobs = pruneJobInfos(upsertJob(live.jobs, job))
419
+ const event: JobStarted = { type: 'job.started', chatId, job }
420
+ publish(chatTopic(chatId), event)
421
+ },
422
+ pushJobOutput(chatId, jobId, chunk, offset) {
423
+ if (!chunk || gone.has(chatId)) return
424
+ const live = ensure(chatId)
425
+ live.jobs = live.jobs.map((job) =>
426
+ job.id === jobId ? { ...job, outputSize: Math.max(job.outputSize, offset + chunk.length) } : job,
427
+ )
428
+ const last = live.bufJobOutput.at(-1)
429
+ if (last && last.jobId === jobId && last.offset + last.chunk.length === offset) last.chunk += chunk
430
+ else live.bufJobOutput.push({ jobId, offset, chunk })
431
+ buffer(chatId, live, 'job')
432
+ },
433
+ jobFinished(chatId, job) {
434
+ if (gone.has(chatId)) return
435
+ // The last chunks must not land after the finish event on a live socket.
436
+ flush(chatId)
437
+ const live = chats.get(chatId)
438
+ if (!live) return
439
+ live.jobs = pruneJobInfos(upsertJob(live.jobs, job))
440
+ const event: JobFinished = { type: 'job.finished', chatId, job }
441
+ publish(chatTopic(chatId), event)
442
+ },
443
+ setQueue(chatId, queue) {
444
+ const live = ensure(chatId)
445
+ live.queue = [...queue]
446
+ const event: QueueUpdated = {
447
+ type: 'queue.updated',
448
+ chatId,
449
+ runId: live.runId,
450
+ rev: live.rev,
451
+ queue: live.queue,
452
+ }
453
+ publish(chatTopic(chatId), event)
454
+ },
455
+ fileChanged(workspaceId, path, hash) {
456
+ publish(GLOBAL_TOPIC, { type: 'file.changed', workspaceId, path, hash })
457
+ },
458
+ workspaceUpserted(workspace) {
459
+ publish(GLOBAL_TOPIC, {
460
+ type: 'workspace.upserted',
461
+ id: workspace.id,
462
+ name: workspace.name,
463
+ rootPath: workspace.root_path,
464
+ createdAt: workspace.created_at,
465
+ lastOpenedAt: workspace.last_opened_at,
466
+ })
467
+ },
468
+ workspaceDeleted(id) {
469
+ publish(GLOBAL_TOPIC, { type: 'workspace.deleted', id })
470
+ },
471
+ workspaceFocus(id) {
472
+ publish(GLOBAL_TOPIC, { type: 'workspace.focus', id })
473
+ },
474
+ chatDeleted(chatId) {
475
+ gone.add(chatId)
476
+ chats.delete(chatId)
477
+ publish(GLOBAL_TOPIC, { type: 'chat.deleted', chatId })
478
+ },
479
+ }
480
+ }
481
+
482
+ /** Appends the chunk just sent to the tail kept for the reconnect snapshot, capped at TOOL_TAIL_LIMIT. */
483
+ function tailOf(sent: ToolOutputState | null, callId: string, chunk: string): ToolOutputState {
484
+ const output = sent && sent.callId === callId ? sent.output + chunk : chunk
485
+ if (output.length <= TOOL_TAIL_LIMIT) return { callId, output }
486
+ let tail = output.slice(output.length - TOOL_TAIL_LIMIT)
487
+ if (tail.length > 0 && isLowSurrogate(tail.charCodeAt(0))) tail = tail.slice(1)
488
+ return { callId, output: tail }
489
+ }
490
+
491
+ /** The tool row of a call ends its live output: the finished text is in the row itself. */
492
+ function dropTool(live: Live, callId: string | null): void {
493
+ if (live.sentTool && (callId === null || live.sentTool.callId === callId)) live.sentTool = null
494
+ if (live.runningCallId !== null && (callId === null || live.runningCallId === callId)) {
495
+ live.runningCallId = null
496
+ }
497
+ live.bufOutput = callId === null ? [] : live.bufOutput.filter((item) => item.callId !== callId)
498
+ if (live.bufOutput.length === 0) live.bufOrder = live.bufOrder.filter((kind) => kind !== 'output')
499
+ }
500
+
501
+ function toolCallIdOf(message: SnapshotMessage): string | null {
502
+ const content = message.content
503
+ if (typeof content !== 'object' || content === null) return null
504
+ const id = (content as { toolCallId?: unknown }).toolCallId
505
+ return typeof id === 'string' ? id : null
506
+ }
507
+
508
+ function upsertJob(jobs: JobInfo[], next: JobInfo): JobInfo[] {
509
+ const index = jobs.findIndex((job) => job.id === next.id)
510
+ if (index < 0) return [...jobs, next]
511
+ return jobs.map((job) => (job.id === next.id ? next : job))
512
+ }
513
+
514
+ function isLowSurrogate(code: number): boolean {
515
+ return code >= 0xdc00 && code <= 0xdfff
516
+ }
517
+
518
+ function defaultSchedule(callback: () => void, delayMs: number): () => void {
519
+ const timer = setTimeout(callback, delayMs)
520
+ return () => clearTimeout(timer)
521
+ }
@@ -0,0 +1,169 @@
1
+ export const TASK_NAME = 'Pointer'
2
+ export const TASK_FILE = 'task.xml'
3
+ export const LAUNCH_FILE = 'launch.vbs'
4
+ export const UPDATE_FILE = 'update.js'
5
+ export const INSTALL_FILE = 'install.json'
6
+
7
+ export const FOLDER_KEY = 'HKCU\\Software\\Classes\\Directory\\shell\\Pointer'
8
+ export const BACKGROUND_KEY = 'HKCU\\Software\\Classes\\Directory\\Background\\shell\\Pointer'
9
+
10
+ export type InstallRecord = {
11
+ packageName: string
12
+ bun: string
13
+ shim: string
14
+ task: string
15
+ /** Folder or archive installs reinstall from here; registry installs update by name. */
16
+ source: string | null
17
+ /** Only a folder source is rebuilt before reinstall. */
18
+ sourceDir: boolean
19
+ }
20
+
21
+ /** `>=1.4.4` against a bun version string. Anything else fails closed. */
22
+ export function bunSatisfies(actual: string, range: string): boolean {
23
+ const wanted = /^>=(\d+)\.(\d+)\.(\d+)$/.exec(range)
24
+ const have = /^(\d+)\.(\d+)\.(\d+)/.exec(actual)
25
+ if (!wanted || !have) return false
26
+ const left = [Number(have[1]), Number(have[2]), Number(have[3])]
27
+ const right = [Number(wanted[1]), Number(wanted[2]), Number(wanted[3])]
28
+ for (let index = 0; index < 3; index += 1) {
29
+ const a = left[index] ?? 0
30
+ const b = right[index] ?? 0
31
+ if (a > b) return true
32
+ if (a < b) return false
33
+ }
34
+ return true
35
+ }
36
+
37
+ export function readMeta(raw: string): { name: string; bun: string } {
38
+ const value: unknown = JSON.parse(raw)
39
+ if (typeof value !== 'object' || value === null) throw new Error('package.json: ожидался объект')
40
+ const record = value as { name?: unknown; engines?: { bun?: unknown } }
41
+ if (typeof record.name !== 'string' || record.name === '') throw new Error('package.json: поле name')
42
+ const range = record.engines?.bun
43
+ if (typeof range !== 'string' || range === '') throw new Error('package.json: поле engines.bun')
44
+ return { name: record.name, bun: range }
45
+ }
46
+
47
+ function vbsQuote(command: string): string {
48
+ return `"${command.replaceAll('"', '""')}"`
49
+ }
50
+
51
+ /** Hidden logon script: start the daemon, then wait on the tray. */
52
+ export function launchVbs(shim: string, tray: string): string {
53
+ const serve = vbsQuote(`"${shim}" serve`)
54
+ const trayCmd = vbsQuote(
55
+ `powershell.exe -NoProfile -ExecutionPolicy Bypass -STA -WindowStyle Hidden -File "${tray}" -Shim "${shim}"`,
56
+ )
57
+ return [
58
+ 'Set sh = CreateObject("Wscript.Shell")',
59
+ `sh.Run ${serve}, 0, False`,
60
+ `sh.Run ${trayCmd}, 0, True`,
61
+ '',
62
+ ].join('\r\n')
63
+ }
64
+
65
+ function xmlEscape(value: string): string {
66
+ return value
67
+ .replaceAll('&', '&amp;')
68
+ .replaceAll('<', '&lt;')
69
+ .replaceAll('>', '&gt;')
70
+ .replaceAll('"', '&quot;')
71
+ }
72
+
73
+ /**
74
+ * `schtasks /SC ONLOGON` asks for elevation, the same task from XML does not.
75
+ * The trigger and the principal name the current user, the run level stays least privilege.
76
+ */
77
+ export function taskXml(launch: string, user: string): string {
78
+ const account = xmlEscape(user)
79
+ return `<?xml version="1.0" encoding="UTF-16"?>
80
+ <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
81
+ <RegistrationInfo><Description>Pointer</Description></RegistrationInfo>
82
+ <Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${account}</UserId></LogonTrigger></Triggers>
83
+ <Principals><Principal id="Author"><UserId>${account}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals>
84
+ <Settings>
85
+ <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
86
+ <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
87
+ <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
88
+ <StartWhenAvailable>false</StartWhenAvailable>
89
+ <AllowStartOnDemand>true</AllowStartOnDemand>
90
+ <RunOnlyIfIdle>false</RunOnlyIfIdle>
91
+ <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
92
+ <Enabled>true</Enabled>
93
+ <Hidden>false</Hidden>
94
+ </Settings>
95
+ <Actions Context="Author"><Exec><Command>wscript.exe</Command><Arguments>//B //Nologo &quot;${xmlEscape(launch)}&quot;</Arguments></Exec></Actions>
96
+ </Task>
97
+ `
98
+ }
99
+
100
+ /**
101
+ * The global manifest writes a local install as a path and a registry install as a
102
+ * version range. Only the first can be refreshed without the registry.
103
+ */
104
+ export function localSource(manifest: string, packageName: string): string | null {
105
+ try {
106
+ const value: unknown = JSON.parse(manifest)
107
+ if (typeof value !== 'object' || value === null) return null
108
+ const deps = (value as { dependencies?: unknown }).dependencies
109
+ if (typeof deps !== 'object' || deps === null) return null
110
+ const spec = (deps as Record<string, unknown>)[packageName]
111
+ if (typeof spec !== 'string') return null
112
+ if (spec.startsWith('file:')) return spec.slice('file:'.length)
113
+ return /^([A-Za-z]:[\\/]|\/|\.)/.test(spec) ? spec : null
114
+ } catch {
115
+ return null
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Runs outside the package. Waits until the `pointer update` process has exited,
121
+ * then replaces the package and starts the task. A live process started from the
122
+ * package directory holds those files on Windows.
123
+ */
124
+ export function updateProgram(home: string): string {
125
+ const installPath = JSON.stringify(`${home.replaceAll('\\', '/')}/${INSTALL_FILE}`)
126
+ return `const parent = Number(process.argv[2] ?? '0')
127
+ function alive(pid) {
128
+ if (!pid) return false
129
+ try {
130
+ process.kill(pid, 0)
131
+ return true
132
+ } catch (error) {
133
+ return error && error.code === 'EPERM'
134
+ }
135
+ }
136
+ const deadline = Date.now() + 20000
137
+ while (alive(parent) && Date.now() < deadline) {
138
+ await new Promise((resolve) => setTimeout(resolve, 200))
139
+ }
140
+ const install = await Bun.file(${installPath}).json()
141
+ function run(args, options = {}) {
142
+ return Bun.spawnSync([install.bun, ...args], {
143
+ stdin: 'ignore',
144
+ stdout: 'inherit',
145
+ stderr: 'inherit',
146
+ ...options,
147
+ }).exitCode ?? 1
148
+ }
149
+ let code
150
+ if (install.source) {
151
+ if (install.sourceDir) code = run(['run', 'build'], { cwd: install.source })
152
+ if (!code) code = run(['add', '-g', install.source])
153
+ } else {
154
+ code = run(['add', '-g', install.packageName + '@latest'])
155
+ }
156
+ if (code !== 0) process.exit(code)
157
+ process.env.PATH = [install.shim.replace(/[\\\\/][^\\\\/]+$/, ''), process.env.PATH ?? ''].join(';')
158
+ const started = Bun.spawnSync([install.shim, 'install'], {
159
+ stdin: 'ignore',
160
+ stdout: 'inherit',
161
+ stderr: 'inherit',
162
+ })
163
+ process.exit(started.exitCode ?? 1)
164
+ `
165
+ }
166
+
167
+ export function explorerCommand(shim: string, placeholder: '%1' | '%V'): string {
168
+ return `"${shim}" open "${placeholder}"`
169
+ }