@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,54 @@
1
+ import { readdirSync } from 'node:fs'
2
+ import { join, relative } from 'node:path'
3
+
4
+ /** The file tree in the UI uses the same list. */
5
+ export const IGNORED_DIRS = ['.git', 'node_modules', 'dist', 'build', '.delta']
6
+
7
+ const ignored = new Set(IGNORED_DIRS)
8
+
9
+ /** The file tree in the UI skips the same directory names. */
10
+ export function isIgnoredDir(name: string): boolean {
11
+ return ignored.has(name)
12
+ }
13
+
14
+ export type WalkedFile = { abs: string; rel: string }
15
+
16
+ /** Cancellation reaches the walkers as an AbortError; callers own the partial result. */
17
+ export function checkAborted(signal?: AbortSignal): void {
18
+ if (signal?.aborted) throw new DOMException('The operation was aborted.', 'AbortError')
19
+ }
20
+
21
+ /** Links and junctions are skipped: they can loop or lead outside the root. */
22
+ export function* walkFiles(
23
+ rootAbs: string,
24
+ startAbs: string,
25
+ signal?: AbortSignal,
26
+ ): Generator<WalkedFile> {
27
+ yield* walkDir(rootAbs, startAbs, signal)
28
+ }
29
+
30
+ function* walkDir(rootAbs: string, dirAbs: string, signal?: AbortSignal): Generator<WalkedFile> {
31
+ checkAborted(signal)
32
+ let entries
33
+ try {
34
+ entries = readdirSync(dirAbs, { withFileTypes: true })
35
+ } catch {
36
+ return
37
+ }
38
+ entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
39
+ for (const entry of entries) {
40
+ checkAborted(signal)
41
+ const abs = join(dirAbs, entry.name)
42
+ if (entry.isDirectory()) {
43
+ if (ignored.has(entry.name)) continue
44
+ yield* walkDir(rootAbs, abs, signal)
45
+ continue
46
+ }
47
+ if (!entry.isFile()) continue
48
+ yield { abs, rel: toRel(rootAbs, abs) }
49
+ }
50
+ }
51
+
52
+ function toRel(rootAbs: string, abs: string): string {
53
+ return relative(rootAbs, abs).replaceAll('\\', '/')
54
+ }
@@ -0,0 +1,129 @@
1
+ import type { ToolCallBlock, ToolDef } from '../../shared/types'
2
+ import type { Revision } from '../changes'
3
+ import type { JobRegistry, QueueWake } from '../jobs'
4
+ import { bashDef, runBash, type BashArgs } from './bash'
5
+ import { editDef, runEdit, type EditArgs } from './edit'
6
+ import { globDef, runGlob, type GlobArgs } from './glob'
7
+ import { grepDef, runGrep, type GrepArgs } from './grep'
8
+ import {
9
+ jobKillDef,
10
+ jobOutputDef,
11
+ runJobKill,
12
+ runJobOutput,
13
+ runWait,
14
+ waitDef,
15
+ type JobKillArgs,
16
+ type JobOutputArgs,
17
+ type WaitArgs,
18
+ } from './jobs'
19
+ import { readDef, runRead, type ReadArgs } from './read'
20
+ import { runWrite, writeDef, type WriteArgs } from './write'
21
+
22
+ export type Shell = { path: string; maxTimeout: number }
23
+
24
+ export type ToolContext = {
25
+ root: string
26
+ chatId: string
27
+ signal: AbortSignal | undefined
28
+ onOutput(chunk: string): void
29
+ /** The tool changed the disk without naming the files, so the folder is refreshed whole. */
30
+ onDiskChanged?(): void
31
+ shell: Shell | null
32
+ /**
33
+ * Read-only roots outside the workspace, checked after it. Compaction writes the turns it
34
+ * removed to the harness home, and the model needs to reach them to look up a detail the
35
+ * summary dropped.
36
+ */
37
+ extraRoots?: string[]
38
+ /** Background jobs of the chat. Absent in the CLI path and in ACP chats. */
39
+ jobs?: JobRegistry
40
+ /** The run queue: `wait` returns early when a message is waiting there. */
41
+ queue?: string[]
42
+ queueWait?: QueueWake
43
+ }
44
+
45
+ export type ToolResult = {
46
+ text: string
47
+ isError: boolean
48
+ details?: unknown
49
+ revisions?: Revision[]
50
+ /** Finished jobs this result reports. Committed only when the tool row is kept. */
51
+ deliverJobIds?: string[]
52
+ }
53
+
54
+ export type ToolHandler = (args: Record<string, unknown>, ctx: ToolContext) => Promise<ToolResult>
55
+
56
+ export function toolDefsFor(shell: Shell | null, jobs?: JobRegistry): ToolDef[] {
57
+ const defs = [readDef, writeDef, editDef, grepDef, globDef]
58
+ if (!shell) return defs
59
+ return jobs ? [...defs, bashDef, jobOutputDef, jobKillDef, waitDef] : [...defs, bashDef]
60
+ }
61
+
62
+ const handlers: Record<string, ToolHandler> = {
63
+ read: (args, ctx) => runRead(args as ReadArgs, ctx),
64
+ write: (args, ctx) => runWrite(args as WriteArgs, ctx),
65
+ edit: (args, ctx) => runEdit(args as EditArgs, ctx),
66
+ grep: (args, ctx) => runGrep(args as GrepArgs, ctx),
67
+ glob: (args, ctx) => runGlob(args as GlobArgs, ctx),
68
+ bash: (args, ctx) => runBash(args as BashArgs, ctx),
69
+ job_output: (args, ctx) => runJobOutput(args as JobOutputArgs, ctx),
70
+ job_kill: (args, ctx) => runJobKill(args as JobKillArgs, ctx),
71
+ wait: (args, ctx) => runWait(args as WaitArgs, ctx),
72
+ }
73
+
74
+ export async function executeTool(call: ToolCallBlock, ctx: ToolContext): Promise<ToolResult> {
75
+ if (call.error) return { text: call.error, isError: true }
76
+ const def = toolDefsFor(ctx.shell, ctx.jobs).find((item) => item.name === call.name)
77
+ const handler = handlers[call.name]
78
+ if (!def || !handler) {
79
+ if (call.name === 'bash' && !ctx.shell) {
80
+ return { text: 'bash: Git Bash was not found, the shell tool is unavailable', isError: true }
81
+ }
82
+ return { text: `Unknown tool: ${call.name}`, isError: true }
83
+ }
84
+ const invalid = validateArguments(def, call.args)
85
+ if (invalid) return { text: invalid, isError: true }
86
+ try {
87
+ return await handler(call.args as Record<string, unknown>, ctx)
88
+ } catch (error) {
89
+ return { text: error instanceof Error ? error.message : String(error), isError: true }
90
+ }
91
+ }
92
+
93
+ type PropertySchema = { type?: string; items?: PropertySchema }
94
+
95
+ export function validateArguments(def: ToolDef, args: unknown): string | null {
96
+ if (typeof args !== 'object' || args === null || Array.isArray(args)) {
97
+ return `${def.name}: arguments must be an object`
98
+ }
99
+ const schema = def.parameters as { properties?: Record<string, PropertySchema>; required?: string[] }
100
+ const values = args as Record<string, unknown>
101
+ for (const key of schema.required ?? []) {
102
+ if (values[key] === undefined) return `${def.name}: missing required argument "${key}"`
103
+ }
104
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
105
+ const value = values[key]
106
+ if (value === undefined) continue
107
+ const wrong = checkType(property, value)
108
+ if (wrong) return `${def.name}: argument "${key}" must be ${wrong}`
109
+ }
110
+ return null
111
+ }
112
+
113
+ function checkType(schema: PropertySchema, value: unknown): string | null {
114
+ const type = schema.type
115
+ if (type === 'string') return typeof value === 'string' ? null : 'a string'
116
+ if (type === 'integer') return typeof value === 'number' && Number.isInteger(value) ? null : 'an integer'
117
+ if (type === 'number') return typeof value === 'number' && Number.isFinite(value) ? null : 'a number'
118
+ if (type === 'boolean') return typeof value === 'boolean' ? null : 'a boolean'
119
+ if (type === 'array') {
120
+ const label = schema.items?.type === 'string' ? 'an array of strings' : 'an array'
121
+ if (!Array.isArray(value)) return label
122
+ if (schema.items?.type === 'string' && !value.every((item) => typeof item === 'string')) return label
123
+ return null
124
+ }
125
+ if (type === 'object') {
126
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? null : 'an object'
127
+ }
128
+ return null
129
+ }
@@ -0,0 +1,85 @@
1
+ import { realpathSync } from 'node:fs'
2
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
3
+
4
+ export type JailedPath = { abs: string; rel: string }
5
+
6
+ const windows = process.platform === 'win32'
7
+
8
+ function fold(path: string): string {
9
+ return windows ? path.toLowerCase() : path
10
+ }
11
+
12
+ function within(root: string, path: string): boolean {
13
+ const base = fold(root)
14
+ const target = fold(path)
15
+ return target === base || target.startsWith(base.endsWith(sep) ? base : base + sep)
16
+ }
17
+
18
+ function unify(input: string): string {
19
+ const path = input.replaceAll('\\', '/')
20
+ return windows && /^\/[a-zA-Z]\//.test(path) ? `${path[1]}:/${path.slice(3)}` : path
21
+ }
22
+
23
+ function realPath(path: string): string {
24
+ const missing: string[] = []
25
+ let current = path
26
+ for (;;) {
27
+ try {
28
+ return join(realpathSync.native(current), ...missing)
29
+ } catch {
30
+ const parent = dirname(current)
31
+ if (parent === current) return path
32
+ missing.unshift(basename(current))
33
+ current = parent
34
+ }
35
+ }
36
+ }
37
+
38
+ export function resolveInRoot(root: string, input: string): JailedPath {
39
+ return resolveInRoots([root], input)
40
+ }
41
+
42
+ export function isInsideRoot(root: string, path: string): boolean {
43
+ const base = resolve(root)
44
+ const target = resolve(path)
45
+ try {
46
+ return within(realPath(base), realPath(target))
47
+ } catch {
48
+ return within(base, target)
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Resolves against the first root that contains the path. The workspace is passed first, so a
54
+ * path inside the project always wins; extra roots are the harness's own read-only archives,
55
+ * which compaction writes outside the project on purpose.
56
+ */
57
+ export function resolveInRoots(roots: string[], input: string): JailedPath {
58
+ const errors: string[] = []
59
+ const unified = unify(input)
60
+ for (const [index, root] of roots.entries()) {
61
+ if (index > 0 && !isAbsolute(unified)) continue
62
+ try {
63
+ const resolved = resolveOne(root, input)
64
+ // Extra roots sit outside the workspace, so a path inside one can only be addressed
65
+ // again by its full path, never as a path relative to the workspace.
66
+ return index === 0
67
+ ? resolved
68
+ : { abs: resolved.abs, rel: resolve(root, resolved.rel).replaceAll('\\', '/') }
69
+ } catch (error) {
70
+ errors.push(error instanceof Error ? error.message : String(error))
71
+ }
72
+ }
73
+ throw new Error(errors[0] ?? `Path is outside the workspace: ${input}`)
74
+ }
75
+
76
+ function resolveOne(root: string, input: string): JailedPath {
77
+ const base = resolve(root)
78
+ const target = resolve(base, unify(input))
79
+ const deny = () => new Error(`Path is outside the workspace: ${input}`)
80
+ if (!within(base, target)) throw deny()
81
+ const realBase = realPath(base)
82
+ const realTarget = realPath(target)
83
+ if (!within(realBase, realTarget)) throw deny()
84
+ return { abs: realTarget, rel: relative(realBase, realTarget).replaceAll('\\', '/') }
85
+ }
@@ -0,0 +1,293 @@
1
+ import type { JobInfo, JobOutput, ToolDef } from '../../shared/types'
2
+ import { MAX_JOB_TIMEOUT, MAX_OUTPUT, DEFAULT_JOB_TIMEOUT, formatJobPreview, type Job } from '../jobs'
3
+ import type { ToolContext, ToolResult } from './index'
4
+
5
+ export type JobOutputArgs = { jobId?: string; offset?: number }
6
+ export type JobKillArgs = { jobId: string }
7
+ export type WaitArgs = { jobIds?: string[]; timeout?: number }
8
+
9
+ export const jobOutputDef: ToolDef = {
10
+ name: 'job_output',
11
+ description:
12
+ 'Read a background bash job. Without jobId: list this chat jobs with id, command, status, exit code and output size. With jobId: return output from the character offset (default 0), the status and exit code. Pass the returned nextOffset to read only what is new. A finished result read here is not delivered again as a job notice.',
13
+ parameters: {
14
+ type: 'object',
15
+ properties: {
16
+ jobId: { type: 'string', description: 'Job id such as j1. Omit to list the chat jobs' },
17
+ offset: {
18
+ type: 'integer',
19
+ description: 'Character offset in the job output. Default 0; use nextOffset from the previous read',
20
+ },
21
+ },
22
+ additionalProperties: false,
23
+ },
24
+ }
25
+
26
+ export const jobKillDef: ToolDef = {
27
+ name: 'job_kill',
28
+ description:
29
+ 'Kill a background bash job and its whole process tree. A job killed by the model does not raise a follow-up turn: this result is the only report.',
30
+ parameters: {
31
+ type: 'object',
32
+ properties: {
33
+ jobId: { type: 'string', description: 'Job id such as j1' },
34
+ },
35
+ required: ['jobId'],
36
+ additionalProperties: false,
37
+ },
38
+ }
39
+
40
+ export const waitDef: ToolDef = {
41
+ name: 'wait',
42
+ description:
43
+ 'Wait for background bash jobs to finish. Default: every running job in this chat. Returns statuses and the tail of each output; results read here are not delivered again as a job notice. Stops early when the user queues a message, on abort, or at the timeout (default 30 s, max 300 s).',
44
+ parameters: {
45
+ type: 'object',
46
+ properties: {
47
+ jobIds: {
48
+ type: 'array',
49
+ items: { type: 'string' },
50
+ description: 'Job ids to wait for. Omit to wait for every running job in this chat',
51
+ },
52
+ timeout: {
53
+ type: 'integer',
54
+ description: `Seconds to wait. Default ${DEFAULT_JOB_TIMEOUT}; capped at ${MAX_JOB_TIMEOUT}`,
55
+ },
56
+ },
57
+ additionalProperties: false,
58
+ },
59
+ }
60
+
61
+ export async function runJobOutput(args: JobOutputArgs, ctx: ToolContext): Promise<ToolResult> {
62
+ if (!ctx.jobs) return missingRegistry()
63
+ if (args.jobId === undefined) return listJobs(ctx)
64
+ const job = ctx.jobs.get(ctx.chatId, args.jobId)
65
+ if (!job) return unknownJob(args.jobId)
66
+ const offset = Number.isFinite(args.offset) ? Math.max(0, Math.floor(args.offset ?? 0)) : 0
67
+ const output = ctx.jobs.output(ctx.chatId, args.jobId, offset, MAX_OUTPUT)
68
+ if (!output) return unknownJob(args.jobId)
69
+ return {
70
+ text: formatOutput(output),
71
+ isError: false,
72
+ deliverJobIds: job.status === 'running' ? undefined : [args.jobId],
73
+ details: {
74
+ jobId: output.id,
75
+ command: output.command,
76
+ status: output.status,
77
+ exitCode: output.exitCode,
78
+ offset: output.offset,
79
+ requestedOffset: output.requestedOffset,
80
+ nextOffset: output.nextOffset,
81
+ outputSize: output.outputSize,
82
+ clipped: output.clipped,
83
+ truncated: output.truncated,
84
+ logPath: output.logPath,
85
+ },
86
+ }
87
+ }
88
+
89
+ export async function runJobKill(args: JobKillArgs, ctx: ToolContext): Promise<ToolResult> {
90
+ if (!ctx.jobs) return missingRegistry()
91
+ const job = ctx.jobs.get(ctx.chatId, args.jobId)
92
+ if (!job) return unknownJob(args.jobId)
93
+ if (job.status !== 'running') {
94
+ return {
95
+ text: `Job ${job.id} already stopped: ${statusText(infoOf(job))}`,
96
+ isError: false,
97
+ deliverJobIds: [job.id],
98
+ details: { jobId: job.id, status: job.status, exitCode: job.exitCode },
99
+ }
100
+ }
101
+ const result = await ctx.jobs.kill(ctx.chatId, args.jobId, 'model')
102
+ if (result === 'missing') return unknownJob(args.jobId)
103
+ if (result === 'running') {
104
+ return {
105
+ text: `Job ${args.jobId} is still running`,
106
+ isError: true,
107
+ details: { jobId: args.jobId, status: 'running' },
108
+ }
109
+ }
110
+ return {
111
+ text: result === 'already' ? `Job ${args.jobId} already stopped` : `Killed background job ${args.jobId}`,
112
+ isError: false,
113
+ deliverJobIds: [args.jobId],
114
+ details: { jobId: args.jobId, status: 'killed' },
115
+ }
116
+ }
117
+
118
+ export async function runWait(args: WaitArgs, ctx: ToolContext): Promise<ToolResult> {
119
+ if (!ctx.jobs) return missingRegistry()
120
+ const registry = ctx.jobs
121
+ const all = registry.list(ctx.chatId)
122
+ const requested = args.jobIds
123
+ let selected: JobInfo[]
124
+ if (requested === undefined) {
125
+ selected = all.filter((job) => job.status === 'running')
126
+ } else {
127
+ selected = []
128
+ for (const id of requested) {
129
+ const found = all.find((job) => job.id === id)
130
+ if (!found) return unknownJob(id)
131
+ selected.push(found)
132
+ }
133
+ }
134
+ if (selected.length === 0) {
135
+ return {
136
+ text: requested === undefined ? 'No running background jobs in this chat.' : 'No jobs selected.',
137
+ isError: false,
138
+ details: { jobs: [], timedOut: false, interrupted: false },
139
+ }
140
+ }
141
+
142
+ const running = selected
143
+ .map((item) => registry.get(ctx.chatId, item.id))
144
+ .filter((job): job is Job => job !== undefined && job.status === 'running')
145
+ const requestedTimeout = Number.isFinite(args.timeout)
146
+ ? Math.floor(args.timeout ?? DEFAULT_JOB_TIMEOUT)
147
+ : DEFAULT_JOB_TIMEOUT
148
+ const seconds = Math.min(Math.max(requestedTimeout, 1), MAX_JOB_TIMEOUT)
149
+ let interrupted: 'steer' | 'abort' | null = null
150
+ let timedOut = false
151
+ if (running.length > 0) {
152
+ const ac = new AbortController()
153
+ const onAbort = (): void => ac.abort()
154
+ if (ctx.signal?.aborted) ac.abort()
155
+ else ctx.signal?.addEventListener('abort', onAbort, { once: true })
156
+ let timer: ReturnType<typeof setTimeout> | undefined
157
+ try {
158
+ const outcome = await Promise.race([
159
+ Promise.all(running.map((job) => job.done)).then((): 'done' => 'done'),
160
+ waitForQueue(ctx, ac.signal),
161
+ new Promise<'abort'>((resolve) => {
162
+ if (ac.signal.aborted) resolve('abort')
163
+ else ac.signal.addEventListener('abort', () => resolve('abort'), { once: true })
164
+ }),
165
+ new Promise<'timeout'>((resolve) => {
166
+ timer = setTimeout(() => resolve('timeout'), seconds * 1000)
167
+ }),
168
+ ])
169
+ if (outcome === 'steer' || outcome === 'abort') interrupted = outcome
170
+ if (outcome === 'timeout') timedOut = true
171
+ } finally {
172
+ if (timer !== undefined) clearTimeout(timer)
173
+ ctx.signal?.removeEventListener('abort', onAbort)
174
+ ac.abort()
175
+ }
176
+ }
177
+
178
+ const results: JobInfo[] = []
179
+ const previews: string[] = []
180
+ const delivered: string[] = []
181
+ for (const item of selected) {
182
+ const job = registry.get(ctx.chatId, item.id)
183
+ if (!job) continue
184
+ results.push(infoOf(job))
185
+ const preview = registry.preview(ctx.chatId, item.id)
186
+ previews.push(previewText(job, preview))
187
+ if (job.status !== 'running') delivered.push(item.id)
188
+ }
189
+ const header =
190
+ interrupted === 'steer'
191
+ ? 'Wait interrupted by a queued message; the jobs keep running.'
192
+ : interrupted === 'abort'
193
+ ? 'Wait interrupted.'
194
+ : timedOut
195
+ ? `Wait timed out after ${seconds} s; the jobs keep running.`
196
+ : 'Wait finished.'
197
+ return {
198
+ text: [header, ...previews].join('\n\n'),
199
+ isError: false,
200
+ deliverJobIds: delivered,
201
+ details: { jobs: results, timedOut, interrupted },
202
+ }
203
+ }
204
+
205
+ function listJobs(ctx: ToolContext): ToolResult {
206
+ const jobs = ctx.jobs!.list(ctx.chatId)
207
+ if (jobs.length === 0) {
208
+ return { text: 'No background jobs in this chat.', isError: false, details: { jobs: [] } }
209
+ }
210
+ return {
211
+ text: jobs.map(jobLine).join('\n'),
212
+ isError: false,
213
+ details: { jobs },
214
+ }
215
+ }
216
+
217
+ function formatOutput(output: JobOutput): string {
218
+ const parts: string[] = [`Job ${output.id}: ${statusText(output)}, ${output.outputSize} chars`]
219
+ if (output.clipped) {
220
+ parts.push(`[offset ${output.requestedOffset} is no longer in the ring; showing from ${output.offset}]`)
221
+ }
222
+ if (output.truncated) {
223
+ const log = output.logPath ? `; full output: ${output.logPath}` : ''
224
+ parts.push(`[output truncated: showing last ${MAX_OUTPUT} chars${log}]`)
225
+ } else if (output.logPath && output.offset > 0) {
226
+ parts.push(`[output log: ${output.logPath}]`)
227
+ }
228
+ const body = output.text.replace(/\n+$/, '')
229
+ if (body) parts.push(body)
230
+ else parts.push(`[no new output; next offset ${output.nextOffset}]`)
231
+ const ending =
232
+ output.status === 'running'
233
+ ? `[next offset: ${output.nextOffset}]`
234
+ : output.status === 'killed'
235
+ ? '[killed]'
236
+ : `[exit code: ${output.exitCode ?? -1}]`
237
+ parts.push(ending)
238
+ return parts.join('\n')
239
+ }
240
+
241
+ function previewText(
242
+ job: Job,
243
+ preview: { text: string; total: number; logPath: string | null } | null,
244
+ ): string {
245
+ const parts = [`${job.id} ${statusText(infoOf(job))}, ${job.ring.total} chars: ${job.command}`]
246
+ const body = formatJobPreview(preview?.text ?? '', preview?.total ?? job.ring.total, preview?.logPath ?? null)
247
+ if (body) parts.push(body)
248
+ return parts.join('\n')
249
+ }
250
+
251
+ function jobLine(job: JobInfo): string {
252
+ return `${job.id} ${statusText(job)}, ${job.outputSize} chars: ${job.command}`
253
+ }
254
+
255
+ function statusText(job: JobInfo): string {
256
+ if (job.status === 'running') return 'running'
257
+ if (job.status === 'killed') return 'killed'
258
+ return `exit code ${job.exitCode ?? -1}`
259
+ }
260
+
261
+ function infoOf(job: Job): JobInfo {
262
+ const spill = job.ring.spill()
263
+ return {
264
+ id: job.id,
265
+ chatId: job.chatId,
266
+ command: job.command,
267
+ status: job.status,
268
+ exitCode: job.exitCode,
269
+ outputSize: job.ring.total,
270
+ startedAt: job.startedAt,
271
+ finishedAt: job.finishedAt,
272
+ logPath: spill?.path ?? null,
273
+ }
274
+ }
275
+
276
+ async function waitForQueue(ctx: ToolContext, signal: AbortSignal): Promise<'steer' | 'abort'> {
277
+ if (ctx.queue && ctx.queue.length > 0) return 'steer'
278
+ if (!ctx.queueWait) {
279
+ if (signal.aborted) return 'abort'
280
+ return new Promise<'abort'>((resolve) => {
281
+ signal.addEventListener('abort', () => resolve('abort'), { once: true })
282
+ })
283
+ }
284
+ return (await ctx.queueWait.wait(signal)) ? 'steer' : 'abort'
285
+ }
286
+
287
+ function missingRegistry(): ToolResult {
288
+ return { text: 'background jobs are unavailable in this chat', isError: true }
289
+ }
290
+
291
+ function unknownJob(jobId: string): ToolResult {
292
+ return { text: `Unknown background job: ${jobId}`, isError: true }
293
+ }