@namzu/sdk 71.0.1 → 71.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 (100) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/dist/authorization/readonly-commands.d.ts +9 -1
  3. package/dist/authorization/readonly-commands.d.ts.map +1 -1
  4. package/dist/authorization/readonly-commands.js +70 -4
  5. package/dist/authorization/readonly-commands.js.map +1 -1
  6. package/dist/authorization/shell-paths.d.ts.map +1 -1
  7. package/dist/authorization/shell-paths.js +68 -16
  8. package/dist/authorization/shell-paths.js.map +1 -1
  9. package/dist/compaction/model-summary.d.ts.map +1 -1
  10. package/dist/compaction/model-summary.js +44 -5
  11. package/dist/compaction/model-summary.js.map +1 -1
  12. package/dist/config/registry.d.ts +2 -0
  13. package/dist/config/registry.d.ts.map +1 -1
  14. package/dist/config/registry.js +76 -5
  15. package/dist/config/registry.js.map +1 -1
  16. package/dist/connector/mcp/adapter.d.ts +8 -0
  17. package/dist/connector/mcp/adapter.d.ts.map +1 -1
  18. package/dist/connector/mcp/adapter.js +131 -1
  19. package/dist/connector/mcp/adapter.js.map +1 -1
  20. package/dist/connector/mcp/stdio.d.ts +12 -0
  21. package/dist/connector/mcp/stdio.d.ts.map +1 -1
  22. package/dist/connector/mcp/stdio.js +49 -5
  23. package/dist/connector/mcp/stdio.js.map +1 -1
  24. package/dist/constants/mcp/index.d.ts +29 -0
  25. package/dist/constants/mcp/index.d.ts.map +1 -1
  26. package/dist/constants/mcp/index.js +29 -0
  27. package/dist/constants/mcp/index.js.map +1 -1
  28. package/dist/manager/agent/lifecycle.d.ts +18 -1
  29. package/dist/manager/agent/lifecycle.d.ts.map +1 -1
  30. package/dist/manager/agent/lifecycle.js +52 -7
  31. package/dist/manager/agent/lifecycle.js.map +1 -1
  32. package/dist/plugin/index.d.ts +1 -1
  33. package/dist/plugin/index.d.ts.map +1 -1
  34. package/dist/plugin/index.js.map +1 -1
  35. package/dist/plugin/shell-hook.d.ts +44 -2
  36. package/dist/plugin/shell-hook.d.ts.map +1 -1
  37. package/dist/plugin/shell-hook.js +74 -5
  38. package/dist/plugin/shell-hook.js.map +1 -1
  39. package/dist/public-runtime.d.ts +2 -2
  40. package/dist/public-runtime.d.ts.map +1 -1
  41. package/dist/public-runtime.js +1 -1
  42. package/dist/public-runtime.js.map +1 -1
  43. package/dist/public-types.d.ts +2 -2
  44. package/dist/public-types.d.ts.map +1 -1
  45. package/dist/runtime/query/path-escalation.d.ts.map +1 -1
  46. package/dist/runtime/query/path-escalation.js +90 -17
  47. package/dist/runtime/query/path-escalation.js.map +1 -1
  48. package/dist/runtime/query/steering.d.ts +15 -0
  49. package/dist/runtime/query/steering.d.ts.map +1 -1
  50. package/dist/runtime/query/steering.js +27 -3
  51. package/dist/runtime/query/steering.js.map +1 -1
  52. package/dist/session/workspace/driver.d.ts +12 -0
  53. package/dist/session/workspace/driver.d.ts.map +1 -1
  54. package/dist/session/workspace/git-worktree.d.ts +16 -0
  55. package/dist/session/workspace/git-worktree.d.ts.map +1 -1
  56. package/dist/session/workspace/git-worktree.js +35 -0
  57. package/dist/session/workspace/git-worktree.js.map +1 -1
  58. package/dist/session/workspace/holds.d.ts +78 -0
  59. package/dist/session/workspace/holds.d.ts.map +1 -0
  60. package/dist/session/workspace/holds.js +150 -0
  61. package/dist/session/workspace/holds.js.map +1 -0
  62. package/dist/session/workspace/index.d.ts +3 -1
  63. package/dist/session/workspace/index.d.ts.map +1 -1
  64. package/dist/session/workspace/index.js +2 -1
  65. package/dist/session/workspace/index.js.map +1 -1
  66. package/dist/store/config/index.d.ts +3 -0
  67. package/dist/store/config/index.d.ts.map +1 -1
  68. package/dist/store/config/index.js +3 -0
  69. package/dist/store/config/index.js.map +1 -1
  70. package/dist/tools/builtins/grep.d.ts.map +1 -1
  71. package/dist/tools/builtins/grep.js +57 -0
  72. package/dist/tools/builtins/grep.js.map +1 -1
  73. package/dist/tools/builtins/lsp.d.ts.map +1 -1
  74. package/dist/tools/builtins/lsp.js +41 -4
  75. package/dist/tools/builtins/lsp.js.map +1 -1
  76. package/dist/types/code-navigation/index.d.ts +34 -4
  77. package/dist/types/code-navigation/index.d.ts.map +1 -1
  78. package/package.json +1 -1
  79. package/src/authorization/readonly-commands.ts +72 -4
  80. package/src/authorization/shell-paths.ts +75 -18
  81. package/src/compaction/model-summary.ts +45 -5
  82. package/src/config/registry.ts +87 -5
  83. package/src/connector/mcp/adapter.ts +137 -1
  84. package/src/connector/mcp/stdio.ts +56 -5
  85. package/src/constants/mcp/index.ts +31 -0
  86. package/src/manager/agent/lifecycle.ts +57 -12
  87. package/src/plugin/index.ts +3 -0
  88. package/src/plugin/shell-hook.ts +131 -6
  89. package/src/public-runtime.ts +5 -0
  90. package/src/public-types.ts +7 -0
  91. package/src/runtime/query/path-escalation.ts +102 -16
  92. package/src/runtime/query/steering.ts +38 -3
  93. package/src/session/workspace/driver.ts +12 -0
  94. package/src/session/workspace/git-worktree.ts +49 -0
  95. package/src/session/workspace/holds.ts +201 -0
  96. package/src/session/workspace/index.ts +13 -1
  97. package/src/store/config/index.ts +6 -0
  98. package/src/tools/builtins/grep.ts +52 -0
  99. package/src/tools/builtins/lsp.ts +47 -4
  100. package/src/types/code-navigation/index.ts +48 -4
@@ -31,6 +31,12 @@ import type {
31
31
  WorkspaceBackendDriver,
32
32
  WorkspaceInspection,
33
33
  } from './driver.js'
34
+ import {
35
+ DiskWorkspaceHoldStore,
36
+ type WorkspaceHold,
37
+ type WorkspaceHoldStore,
38
+ WorkspaceInUseError,
39
+ } from './holds.js'
34
40
 
35
41
  const execFileAsync = promisify(execFile)
36
42
 
@@ -75,6 +81,12 @@ export interface GitWorktreeDriverConfig {
75
81
  branchPrefix?: string
76
82
  /** Test-seam: inject a stub `execFile` implementation. */
77
83
  execFile?: ExecFile
84
+ /**
85
+ * Who is working in a checkout right now. `dispose` asks it before removing
86
+ * anything and refuses a path a live session or subagent still has. Absent,
87
+ * the machine's own hold directory is read.
88
+ */
89
+ holds?: WorkspaceHoldStore
78
90
  }
79
91
 
80
92
  const DEFAULT_BRANCH_PREFIX = 'namzu'
@@ -97,12 +109,14 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
97
109
  private readonly log: Logger
98
110
  private readonly exec: ExecFile
99
111
  private readonly branchPrefix: string
112
+ private readonly holds: WorkspaceHoldStore
100
113
 
101
114
  constructor(config: GitWorktreeDriverConfig) {
102
115
  this.repoRoot = resolve(config.repoRoot)
103
116
  this.worktreesDir = resolve(config.worktreesDir ?? defaultWorktreesDir(config.repoRoot))
104
117
  this.log = config.logger.child({ [SCOPE_ATTRIBUTE]: 'session/workspace/git-worktree' })
105
118
  this.exec = config.execFile ?? defaultExecFile
119
+ this.holds = config.holds ?? new DiskWorkspaceHoldStore()
106
120
  const prefix = config.branchPrefix ?? DEFAULT_BRANCH_PREFIX
107
121
  if (!isBranchPrefix(prefix)) {
108
122
  throw new Error(
@@ -221,6 +235,20 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
221
235
  return
222
236
  }
223
237
 
238
+ // A checkout another live process has open is not this call's to remove:
239
+ // `worktree remove --force` would take that process's uncommitted files
240
+ // with it. The refusal names the folder asked for and every folder its
241
+ // holders work in, so a person can see which session to close.
242
+ const holders = await this.liveHolders(owned.worktreePath)
243
+ if (holders.length > 0) {
244
+ this.log.info('git-worktree kept; another session has it', {
245
+ [NAMZU.SESSION_ID]: ref.id,
246
+ 'namzu.session.path': owned.worktreePath,
247
+ 'namzu.session.holder_count': holders.length,
248
+ })
249
+ throw new WorkspaceInUseError(owned.worktreePath, holders)
250
+ }
251
+
224
252
  // Tolerate missing directories per roadmap Risk #3 mitigation: the
225
253
  // broadcast-rollback compensating step calls dispose on partially
226
254
  // provisioned refs and must not propagate "already gone" errors. The
@@ -276,6 +304,27 @@ export class GitWorktreeDriver implements WorkspaceBackendDriver {
276
304
  }
277
305
  }
278
306
 
307
+ /**
308
+ * Who is working in `worktreePath` right now.
309
+ *
310
+ * A hold store that cannot be read is not a "nobody": answering that on a
311
+ * guess is how an in-use checkout gets deleted, so it refuses the removal
312
+ * and says what it could not read.
313
+ */
314
+ private async liveHolders(worktreePath: string): Promise<readonly WorkspaceHold[]> {
315
+ try {
316
+ return await this.holds.holders(worktreePath)
317
+ } catch (cause) {
318
+ throw new WorkspaceBackendError({
319
+ op: 'dispose:holders',
320
+ kind: this.kind,
321
+ cause: new Error(
322
+ `The worktree ${worktreePath} was not removed: Namzu could not read who is working in it (${cause instanceof Error ? cause.message : String(cause)}).`,
323
+ ),
324
+ })
325
+ }
326
+ }
327
+
279
328
  /**
280
329
  * Did the worktree arrive despite the command reporting failure?
281
330
  *
@@ -0,0 +1,201 @@
1
+ /**
2
+ * WorkspaceHoldStore — which live session or subagent is working in a checkout.
3
+ *
4
+ * A Git worktree belongs to whoever is using it right now, not only to the ref
5
+ * a driver created it from. A driver that removes a checkout while another
6
+ * process has it open takes that process's uncommitted files with it, so a
7
+ * removal asks this store first.
8
+ *
9
+ * ## What is on disk
10
+ *
11
+ * `<root>/workspace-holds/<key>/<pid>-<token>.json`, one file per holding, so
12
+ * two holders of the same path never write over each other and neither needs a
13
+ * lock. `<key>` is a hash of the canonical path; the body carries the path
14
+ * itself, so a key that belongs to something else is never believed.
15
+ *
16
+ * ## How liveness is decided
17
+ *
18
+ * A holding is the pid of the process that took it. On this machine the pid is
19
+ * asked whether it still exists: a crashed or killed session leaves its file
20
+ * behind, and every later look unlinks it. A record from another host on a
21
+ * shared home directory cannot be checked from here, so it is treated as live —
22
+ * the same rule the stored-memory lock uses. The residual risk is the same and
23
+ * is deliberate: a pid reused by an unrelated process reads as live, and a
24
+ * checkout stays where it is rather than being removed on a guess.
25
+ */
26
+
27
+ import { createHash, randomUUID } from 'node:crypto'
28
+ import { mkdir, readFile, readdir, realpath, unlink, writeFile } from 'node:fs/promises'
29
+ import { hostname as osHostname } from 'node:os'
30
+ import { join, resolve } from 'node:path'
31
+ import { resolveNamzuHome } from '../home.js'
32
+
33
+ /** One live use of a checkout. */
34
+ export interface WorkspaceHold {
35
+ /** The managed checkout root that must not be removed. */
36
+ readonly path: string
37
+ /** The folder the holder works in, which may be below `path`. */
38
+ readonly folder: string
39
+ /** Who holds it, for a person reading the refusal or the log. */
40
+ readonly holder: string
41
+ }
42
+
43
+ export interface WorkspaceHoldRequest {
44
+ /** The checkout root, as the driver knows it. */
45
+ readonly path: string
46
+ /** The folder the holder works in. Defaults to `path`. */
47
+ readonly folder?: string
48
+ /** A short, honest description: `session:1234`, `subagent:1234:review`. */
49
+ readonly holder: string
50
+ }
51
+
52
+ /** Ask a store who is working in a checkout, and record this process doing so. */
53
+ export interface WorkspaceHoldStore {
54
+ /**
55
+ * Record a holding. Resolves with an idempotent release; the caller keeps it
56
+ * for as long as it works in the checkout and releases it before it ends.
57
+ */
58
+ add(request: WorkspaceHoldRequest): Promise<() => Promise<void>>
59
+ /** Live holdings of `path`; empty when nothing holds it. */
60
+ holders(path: string): Promise<readonly WorkspaceHold[]>
61
+ }
62
+
63
+ export interface DiskWorkspaceHoldStoreOptions {
64
+ /** Directory the holdings live in. Defaults to {@link defaultWorkspaceHoldsDir}. */
65
+ readonly root?: string
66
+ /** True when a process with this pid exists on this machine. */
67
+ readonly isPidAlive?: (pid: number) => boolean
68
+ readonly hostname?: string
69
+ }
70
+
71
+ /** The refusal a removal reports when a live session or subagent still has the checkout. */
72
+ export class WorkspaceInUseError extends Error {
73
+ override readonly name = 'WorkspaceInUseError'
74
+ constructor(
75
+ readonly path: string,
76
+ readonly holders: readonly WorkspaceHold[],
77
+ ) {
78
+ const who = holders.map((hold) => `${hold.holder}, working in ${hold.folder}`).join('; ')
79
+ super(
80
+ `The worktree ${path} was not removed: a running session or subagent still has it (${who}). Its uncommitted files are untouched. Close that session, then remove it again.`,
81
+ )
82
+ }
83
+ }
84
+
85
+ function defaultIsPidAlive(pid: number): boolean {
86
+ try {
87
+ process.kill(pid, 0)
88
+ return true
89
+ } catch (error) {
90
+ // EPERM means the process is there and belongs to somebody else.
91
+ return (error as NodeJS.ErrnoException).code !== 'ESRCH'
92
+ }
93
+ }
94
+
95
+ function isErrno(error: unknown, code: string): boolean {
96
+ return (error as NodeJS.ErrnoException | undefined)?.code === code
97
+ }
98
+
99
+ function keyFor(path: string): string {
100
+ return createHash('sha256').update(path).digest('hex').slice(0, 24)
101
+ }
102
+
103
+ interface HoldBody {
104
+ readonly v: 1
105
+ readonly path: string
106
+ readonly folder: string
107
+ readonly holder: string
108
+ readonly pid: number
109
+ readonly hostname: string
110
+ readonly startedAt: string
111
+ }
112
+
113
+ /** Resolve every existing path component, so two spellings of one folder share a key. */
114
+ async function canonical(path: string): Promise<string> {
115
+ try {
116
+ return await realpath(resolve(path))
117
+ } catch {
118
+ return resolve(path)
119
+ }
120
+ }
121
+
122
+ export class DiskWorkspaceHoldStore implements WorkspaceHoldStore {
123
+ private readonly root: string
124
+ private readonly isPidAlive: (pid: number) => boolean
125
+ private readonly hostname: string
126
+
127
+ constructor(options: DiskWorkspaceHoldStoreOptions = {}) {
128
+ this.root = resolve(options.root ?? defaultWorkspaceHoldsDir())
129
+ this.isPidAlive = options.isPidAlive ?? defaultIsPidAlive
130
+ this.hostname = options.hostname ?? osHostname()
131
+ }
132
+
133
+ private async directoryFor(path: string): Promise<string> {
134
+ return join(this.root, keyFor(await canonical(path)))
135
+ }
136
+
137
+ async add(request: WorkspaceHoldRequest): Promise<() => Promise<void>> {
138
+ const path = await canonical(request.path)
139
+ const directory = await this.directoryFor(path)
140
+ await mkdir(directory, { recursive: true, mode: 0o700 })
141
+ const body: HoldBody = {
142
+ v: 1,
143
+ path,
144
+ folder: await canonical(request.folder ?? path),
145
+ holder: request.holder,
146
+ pid: process.pid,
147
+ hostname: this.hostname,
148
+ startedAt: new Date().toISOString(),
149
+ }
150
+ const file = join(directory, `${process.pid}-${randomUUID()}.json`)
151
+ await writeFile(file, `${JSON.stringify(body)}\n`, { flag: 'wx', mode: 0o600 })
152
+ let released = false
153
+ return async () => {
154
+ if (released) return
155
+ released = true
156
+ await unlink(file).catch((error) => {
157
+ if (!isErrno(error, 'ENOENT')) throw error
158
+ })
159
+ }
160
+ }
161
+
162
+ async holders(path: string): Promise<readonly WorkspaceHold[]> {
163
+ const canonicalPath = await canonical(path)
164
+ const directory = await this.directoryFor(canonicalPath)
165
+ let names: string[]
166
+ try {
167
+ names = await readdir(directory)
168
+ } catch (error) {
169
+ if (isErrno(error, 'ENOENT')) return []
170
+ throw error
171
+ }
172
+ const found: WorkspaceHold[] = []
173
+ for (const name of names.sort()) {
174
+ if (!name.endsWith('.json')) continue
175
+ const file = join(directory, name)
176
+ let body: HoldBody
177
+ try {
178
+ body = JSON.parse(await readFile(file, 'utf8')) as HoldBody
179
+ } catch {
180
+ continue
181
+ }
182
+ if (body.v !== 1 || body.path !== canonicalPath) continue
183
+ if (body.hostname !== this.hostname) {
184
+ found.push({ path: body.path, folder: body.folder, holder: body.holder })
185
+ continue
186
+ }
187
+ if (this.isPidAlive(body.pid)) {
188
+ found.push({ path: body.path, folder: body.folder, holder: body.holder })
189
+ continue
190
+ }
191
+ // The holder is gone and its release never ran: this file is litter.
192
+ await unlink(file).catch(() => undefined)
193
+ }
194
+ return found
195
+ }
196
+ }
197
+
198
+ /** `<NAMZU_HOME>/workspace-holds`: one machine's view of who has which checkout. */
199
+ export function defaultWorkspaceHoldsDir(env: NodeJS.ProcessEnv = process.env): string {
200
+ return join(resolveNamzuHome({ env }), 'workspace-holds')
201
+ }
@@ -19,9 +19,21 @@ export type {
19
19
 
20
20
  export { WorkspaceBackendRegistry } from './registry.js'
21
21
 
22
- export { GitWorktreeDriver, parseWorktreeList } from './git-worktree.js'
22
+ export { GitWorktreeDriver, defaultWorktreesDir, parseWorktreeList } from './git-worktree.js'
23
23
  export type { ExecFile, ExecFileResult, GitWorktreeDriverConfig } from './git-worktree.js'
24
24
 
25
+ export {
26
+ DiskWorkspaceHoldStore,
27
+ defaultWorkspaceHoldsDir,
28
+ WorkspaceInUseError,
29
+ } from './holds.js'
30
+ export type {
31
+ DiskWorkspaceHoldStoreOptions,
32
+ WorkspaceHold,
33
+ WorkspaceHoldRequest,
34
+ WorkspaceHoldStore,
35
+ } from './holds.js'
36
+
25
37
  export { SharedSessionWorkspace } from './shared-session.js'
26
38
  export type {
27
39
  RegisterSharedSessionPlanInput,
@@ -21,6 +21,8 @@ export interface ConfigOverrideStore {
21
21
  load(): Record<string, unknown>
22
22
  /** Persist one namespace's accumulated override. */
23
23
  save(namespace: string, override: unknown): void
24
+ /** Where the overrides live, for a message that names the file. Absent for memory. */
25
+ location?(): string
24
26
  }
25
27
 
26
28
  /** The default: nothing survives the process, and it says so by its name. */
@@ -50,6 +52,10 @@ export class DiskConfigOverrideStore implements ConfigOverrideStore {
50
52
 
51
53
  constructor(private readonly path: string) {}
52
54
 
55
+ location(): string {
56
+ return this.path
57
+ }
58
+
53
59
  load(): Record<string, unknown> {
54
60
  if (this.cache) return { ...this.cache }
55
61
  try {
@@ -657,6 +657,10 @@ export const GrepTool = defineTool({
657
657
  if ((endState?.ignoredDirectories ?? 0) > 0 && offset === 0) {
658
658
  summary = `${summary}\n${ignoredHint(endState?.ignoredDirectories ?? 0)}`
659
659
  }
660
+ // An empty result a line break in the pattern forced is not evidence that
661
+ // the text is absent, so the pattern is named rather than left to read so.
662
+ const breakHint = totalMatches === 0 ? lineBreakHint(input.pattern, multiline) : undefined
663
+ if (breakHint !== undefined) summary = `${summary}\n${breakHint}`
660
664
  } else if (mode === 'files_with_matches') {
661
665
  body = `Found ${page.length} ${page.length === 1 ? 'file' : 'files'}${paging ? ` (${paging})` : ''}\n${page.join('\n')}`
662
666
  } else if (mode === 'count') {
@@ -721,6 +725,54 @@ function byPath(a: string, b: string): number {
721
725
  return a < b ? -1 : a > b ? 1 : 0
722
726
  }
723
727
 
728
+ /**
729
+ * Whether a pattern is written to match a line break: one in the pattern
730
+ * itself, or an escape that names one, `\n` and `\r` among them. A pattern
731
+ * like that cannot be found inside a single line, and every line is tested on
732
+ * its own while `multiline` is off.
733
+ */
734
+ function patternNeedsLineBreak(pattern: string): boolean {
735
+ for (let index = 0; index < pattern.length; index += 1) {
736
+ const char = pattern[index]
737
+ if (char === '\n' || char === '\r' || char === '\u2028' || char === '\u2029') return true
738
+ if (char === '[' && pattern[index + 1] === '^') {
739
+ // A negated class such as `[^\n]` excludes a line break; it does not ask for one.
740
+ index = skipNegatedClass(pattern, index + 2)
741
+ continue
742
+ }
743
+ if (char !== '\\') continue
744
+ const next = pattern[index + 1]
745
+ // An escaped backslash and the `n` after it are a literal `\n` in the
746
+ // text being searched, so the two are stepped over together.
747
+ if (next === '\\') {
748
+ index += 1
749
+ continue
750
+ }
751
+ if (next === 'n' || next === 'r') return true
752
+ if (next === 'u' && ['2028', '2029'].includes(pattern.slice(index + 2, index + 6))) return true
753
+ }
754
+ return false
755
+ }
756
+
757
+ /** The index of the `]` that closes a negated class whose body starts at `from`, or the end of the pattern. */
758
+ function skipNegatedClass(pattern: string, from: number): number {
759
+ for (let index = from; index < pattern.length; index += 1) {
760
+ if (pattern[index] === '\\') index += 1
761
+ else if (pattern[index] === ']') return index
762
+ }
763
+ return pattern.length
764
+ }
765
+
766
+ /**
767
+ * A sentence for the emptiest of evidence: a pattern that needs a line break,
768
+ * searched one line at a time, can only come back with nothing. Naming the
769
+ * pattern and the flag that changes that is worth more than "no matches".
770
+ */
771
+ function lineBreakHint(pattern: string, multiline: boolean): string | undefined {
772
+ if (multiline || !patternNeedsLineBreak(pattern)) return undefined
773
+ return `The pattern ${JSON.stringify(pattern)} contains a line break, and multiline is off: each line is tested on its own, so a match that spans lines cannot be found. Pass multiline: true to search across lines.`
774
+ }
775
+
724
776
  /**
725
777
  * Newest modification first; ties by path. A file that cannot be stat'ed, and
726
778
  * every file in a sandbox (which reports no modification time), sorts as
@@ -110,8 +110,22 @@ export const LspTool = defineTool({
110
110
  }
111
111
  }
112
112
 
113
+ // Checked before anything is spawned. A turn that was stopped must not
114
+ // pay for starting a language server, and the server must not be asked a
115
+ // question whose answer nobody will read.
116
+ if (context.abortSignal?.aborted) {
117
+ return interruptedResult(
118
+ input.operation,
119
+ 'The turn was stopped before the language server was asked.',
120
+ )
121
+ }
122
+ // The turn's own signal, so Esc reaches the request instead of leaving it
123
+ // to the provider's deadline: a server that is still indexing would hold
124
+ // the turn open with nothing able to end it.
125
+ const options = { signal: context.abortSignal }
126
+
113
127
  if (input.operation === 'symbols') {
114
- const result = await provider.symbols(input.query, absolute)
128
+ const result = await provider.symbols(input.query, absolute, options)
115
129
  switch (result.kind) {
116
130
  case 'symbols': {
117
131
  if (result.symbols.length === 0) {
@@ -133,11 +147,13 @@ export const LspTool = defineTool({
133
147
  return { success: false, output: '', error: unsupportedMessage(result.reason) }
134
148
  case 'failed':
135
149
  return { success: false, output: '', error: failedMessage(result.error) }
150
+ case 'interrupted':
151
+ return interruptedResult('symbols', result.reason)
136
152
  }
137
153
  }
138
154
 
139
155
  if (input.operation === 'hover') {
140
- const result = await provider.hover(absolute as string, input.line, input.character)
156
+ const result = await provider.hover(absolute as string, input.line, input.character, options)
141
157
  switch (result.kind) {
142
158
  case 'hover':
143
159
  return {
@@ -154,13 +170,15 @@ export const LspTool = defineTool({
154
170
  return { success: false, output: '', error: unsupportedMessage(result.reason) }
155
171
  case 'failed':
156
172
  return { success: false, output: '', error: failedMessage(result.error) }
173
+ case 'interrupted':
174
+ return interruptedResult('hover', result.reason)
157
175
  }
158
176
  }
159
177
 
160
178
  const result =
161
179
  input.operation === 'definition'
162
- ? await provider.definition(absolute as string, input.line, input.character)
163
- : await provider.references(absolute as string, input.line, input.character)
180
+ ? await provider.definition(absolute as string, input.line, input.character, options)
181
+ : await provider.references(absolute as string, input.line, input.character, options)
164
182
 
165
183
  switch (result.kind) {
166
184
  case 'locations': {
@@ -189,6 +207,8 @@ export const LspTool = defineTool({
189
207
  return { success: false, output: '', error: unsupportedMessage(result.reason) }
190
208
  case 'failed':
191
209
  return { success: false, output: '', error: failedMessage(result.error) }
210
+ case 'interrupted':
211
+ return interruptedResult(input.operation, result.reason)
192
212
  }
193
213
  },
194
214
  })
@@ -203,6 +223,29 @@ function failedMessage(error: string): string {
203
223
  return `Code navigation failed, so this answer is unknown rather than empty: ${error}`
204
224
  }
205
225
 
226
+ /**
227
+ * An answer nobody finished asking for.
228
+ *
229
+ * The ordinary end of a call the person stopped, and the one case that must
230
+ * not read as a broken server: the next move is to ask again, not to fall
231
+ * back to `grep` or to conclude the symbol has no callers. It says "unknown
232
+ * rather than empty" for the same reason a failure does — a model acts on the
233
+ * absence of an answer.
234
+ */
235
+ function interruptedMessage(reason: string): string {
236
+ return `The call was interrupted before the language server answered, so this answer is unknown rather than empty: ${reason} Ask again if the answer is still needed.`
237
+ }
238
+
239
+ /** Structured as well as worded, because a host renders a stopped call differently. */
240
+ function interruptedResult(operation: LspInput['operation'], reason: string): ToolResult {
241
+ return {
242
+ success: false,
243
+ output: '',
244
+ error: interruptedMessage(reason),
245
+ data: { operation, interrupted: true },
246
+ }
247
+ }
248
+
206
249
  /**
207
250
  * The tool, only when there is something for it to call.
208
251
  *
@@ -36,11 +36,19 @@ export interface SourceLocation {
36
36
  * looked, and there are none", which is a real answer and the one a
37
37
  * deletion depends on; conflating it with a failure is how an agent
38
38
  * concludes a symbol has no callers because the server never started.
39
+ *
40
+ * `interrupted` is the fourth case and it is neither of the other two: the
41
+ * caller aborted the request (the turn was stopped) before the server
42
+ * answered, so nobody finished asking. Reporting that as `failed` says the
43
+ * resolver broke, which is false and invites a retry against a server that
44
+ * is fine; reporting it as an empty list says the symbol has no callers,
45
+ * which is how a deletion gets made on an answer nobody gave.
39
46
  */
40
47
  export type CodeNavigationResult =
41
48
  | { readonly kind: 'locations'; readonly locations: readonly SourceLocation[] }
42
49
  | { readonly kind: 'unsupported'; readonly reason: string }
43
50
  | { readonly kind: 'failed'; readonly error: string }
51
+ | { readonly kind: 'interrupted'; readonly reason: string }
44
52
 
45
53
  /** A symbol found by name rather than by position. */
46
54
  export interface SymbolLocation extends SourceLocation {
@@ -63,19 +71,51 @@ export type HoverResult =
63
71
  | { readonly kind: 'hover'; readonly contents: string }
64
72
  | { readonly kind: 'unsupported'; readonly reason: string }
65
73
  | { readonly kind: 'failed'; readonly error: string }
74
+ | { readonly kind: 'interrupted'; readonly reason: string }
66
75
 
67
76
  export type SymbolSearchResult =
68
77
  | { readonly kind: 'symbols'; readonly symbols: readonly SymbolLocation[] }
69
78
  | { readonly kind: 'unsupported'; readonly reason: string }
70
79
  | { readonly kind: 'failed'; readonly error: string }
80
+ | { readonly kind: 'interrupted'; readonly reason: string }
81
+
82
+ /**
83
+ * Per-call control, passed alongside a request.
84
+ *
85
+ * `signal` is the turn's abort signal, so a Stop ends the request instead of
86
+ * leaving it to the provider's own deadline: a language server that is still
87
+ * indexing, wedged, or waiting on a binary that never became ready would
88
+ * otherwise hold the turn open with nothing able to end it. A provider that
89
+ * receives an aborted signal answers `interrupted` — never `failed`, and
90
+ * never an empty result — because the answer is unknown for a reason that
91
+ * says nothing about the server.
92
+ */
93
+ export interface CodeNavigationRequestOptions {
94
+ readonly signal?: AbortSignal
95
+ }
71
96
 
72
97
  export interface CodeNavigationProvider {
73
98
  /** Where the symbol under this position is declared. */
74
- definition(file: string, line: number, character: number): Promise<CodeNavigationResult>
99
+ definition(
100
+ file: string,
101
+ line: number,
102
+ character: number,
103
+ options?: CodeNavigationRequestOptions,
104
+ ): Promise<CodeNavigationResult>
75
105
  /** Everywhere the symbol under this position is used. */
76
- references(file: string, line: number, character: number): Promise<CodeNavigationResult>
106
+ references(
107
+ file: string,
108
+ line: number,
109
+ character: number,
110
+ options?: CodeNavigationRequestOptions,
111
+ ): Promise<CodeNavigationResult>
77
112
  /** The symbol's type and documentation, without opening the file. */
78
- hover(file: string, line: number, character: number): Promise<HoverResult>
113
+ hover(
114
+ file: string,
115
+ line: number,
116
+ character: number,
117
+ options?: CodeNavigationRequestOptions,
118
+ ): Promise<HoverResult>
79
119
  /**
80
120
  * Find a declaration by NAME, with no position.
81
121
  *
@@ -88,7 +128,11 @@ export interface CodeNavigationProvider {
88
128
  * `scope` is a file path or an extension that picks which language's
89
129
  * server answers. Absent means every configured language.
90
130
  */
91
- symbols(query: string, scope?: string): Promise<SymbolSearchResult>
131
+ symbols(
132
+ query: string,
133
+ scope?: string,
134
+ options?: CodeNavigationRequestOptions,
135
+ ): Promise<SymbolSearchResult>
92
136
  /**
93
137
  * Stop whatever backs it.
94
138
  *