@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
@@ -1085,6 +1085,13 @@ export class AgentManager {
1085
1085
  } catch (writeError) {
1086
1086
  failure = writeError
1087
1087
  }
1088
+ // The child has stopped working in its checkout, whatever keeps that
1089
+ // checkout next. Released BEFORE the parent hears the child idle: a
1090
+ // listener that removes the kept checkout must not be refused by a
1091
+ // holder that has already ended, which is what a cancelled child
1092
+ // used to leave behind — the cancellation marked the task terminal,
1093
+ // and the cleanup below it ran only after the idle event.
1094
+ await this.releaseChildWorkspace(spawnRecord)
1088
1095
  // The child's turn is over either way; its parent hears so first.
1089
1096
  await this.settleChildSession(
1090
1097
  runningTask,
@@ -2397,10 +2404,44 @@ export class AgentManager {
2397
2404
  await this.disposeChildWorkspace(spawnRecord)
2398
2405
  }
2399
2406
 
2407
+ /**
2408
+ * Tell the driver the child stopped working in its checkout.
2409
+ *
2410
+ * Every path a child ends by has to reach this before anything decides what
2411
+ * happens to that checkout: success and failure through
2412
+ * `disposeChildWorkspace`, and a cancelled child from the run's rejection,
2413
+ * before its parent hears the child idle. A driver that publishes who is
2414
+ * working in a checkout then stops naming a session that has ended, even
2415
+ * when the checkout itself is kept.
2416
+ *
2417
+ * Never throws. A release that fails is logged: the child's work is already
2418
+ * done, and a stale holding is an operator's problem, not the child's result.
2419
+ */
2420
+ private async releaseChildWorkspace(
2421
+ spawnRecord: Pick<ChildSpawnRecord, 'workspaceRef' | 'subSessionId'>,
2422
+ ): Promise<void> {
2423
+ if (!spawnRecord.workspaceRef) return
2424
+ const backend = spawnRecord.workspaceRef.meta.backend
2425
+ if (!this.deps.workspaceRegistry.has(backend)) return
2426
+ const driver = this.deps.workspaceRegistry.get(backend)
2427
+ if (!driver.release) return
2428
+ await driver.release(spawnRecord.workspaceRef).catch((releaseErr) => {
2429
+ this.log.warn('Workspace release failed', {
2430
+ 'namzu.manager.backend': backend,
2431
+ 'namzu.manager.workspace_id': spawnRecord.workspaceRef?.id,
2432
+ 'namzu.sub_session.id': spawnRecord.subSessionId,
2433
+ 'exception.message': toErrorMessage(releaseErr),
2434
+ })
2435
+ })
2436
+ }
2437
+
2400
2438
  /**
2401
2439
  * Release the workspace this manager provisioned for a child.
2402
2440
  *
2403
- * Called on every terminal path, success included. `has(backend)` before
2441
+ * Called on every terminal path, success included, and it tells the driver
2442
+ * the child stopped working in its checkout before deciding whether to keep
2443
+ * it: a checkout that is kept must not go on claiming a live holder.
2444
+ * `has(backend)` before
2404
2445
  * `get(backend)` because the registry is deny-by-default and throws on an
2405
2446
  * unknown kind — a driver deregistered mid-turn must not turn cleanup into
2406
2447
  * an exception on a child that already finished.
@@ -2414,10 +2455,17 @@ export class AgentManager {
2414
2455
  private async disposeChildWorkspace(
2415
2456
  spawnRecord: Pick<ChildSpawnRecord, 'workspaceRef' | 'workspaceRetention' | 'subSessionId'>,
2416
2457
  ): Promise<void> {
2417
- if (spawnRecord.workspaceRetention === 'retain') return
2418
2458
  if (!spawnRecord.workspaceRef) return
2419
2459
  const backend = spawnRecord.workspaceRef.meta.backend
2420
2460
  if (!this.deps.workspaceRegistry.has(backend)) return
2461
+ const driver = this.deps.workspaceRegistry.get(backend)
2462
+ // The child has ended, so it stops working in its checkout whatever this
2463
+ // does with that checkout next. Told here, BEFORE the retention returns
2464
+ // below: both of those keep the checkout, and a kept checkout must not go
2465
+ // on claiming a holder that finished — that is a removal refused later for
2466
+ // a session that is gone.
2467
+ await this.releaseChildWorkspace(spawnRecord)
2468
+ if (spawnRecord.workspaceRetention === 'retain') return
2421
2469
  if (spawnRecord.workspaceRetention === 'retain-changed') {
2422
2470
  // Keep the checkout unless it provably holds nothing. A look that fails,
2423
2471
  // or a backend that cannot say whether it moved, keeps it too.
@@ -2435,17 +2483,14 @@ export class AgentManager {
2435
2483
  if (!seen) return
2436
2484
  if (seen.exists && (seen.isDirty || seen.hasNewCommits !== false)) return
2437
2485
  }
2438
- await this.deps.workspaceRegistry
2439
- .get(backend)
2440
- .dispose(spawnRecord.workspaceRef)
2441
- .catch((disposeErr) => {
2442
- this.log.warn('Workspace dispose failed', {
2443
- 'namzu.manager.backend': backend,
2444
- 'namzu.manager.workspace_id': spawnRecord.workspaceRef?.id,
2445
- 'namzu.sub_session.id': spawnRecord.subSessionId,
2446
- 'exception.message': toErrorMessage(disposeErr),
2447
- })
2486
+ await driver.dispose(spawnRecord.workspaceRef).catch((disposeErr) => {
2487
+ this.log.warn('Workspace dispose failed', {
2488
+ 'namzu.manager.backend': backend,
2489
+ 'namzu.manager.workspace_id': spawnRecord.workspaceRef?.id,
2490
+ 'namzu.sub_session.id': spawnRecord.subSessionId,
2491
+ 'exception.message': toErrorMessage(disposeErr),
2448
2492
  })
2493
+ })
2449
2494
  }
2450
2495
 
2451
2496
  private markCanceled(taskId: TaskId, cause?: CancelCause): void {
@@ -68,11 +68,14 @@ export {
68
68
  } from './shell-hook-tool-names.js'
69
69
  export type {
70
70
  HttpHookEntry,
71
+ McpToolHookEntry,
71
72
  PromptHookEntry,
72
73
  ShellHookEntry,
73
74
  ShellHookEvent,
74
75
  ShellHookHandler,
75
76
  ShellHookJudge,
77
+ ShellHookMcpToolAnswer,
78
+ ShellHookMcpToolCaller,
76
79
  ShellHookOnFailure,
77
80
  ShellHookCall,
78
81
  ShellHookInput,
@@ -351,8 +351,22 @@ export interface PromptHookEntry extends ShellHookEntryBase {
351
351
  readonly prompt: string
352
352
  }
353
353
 
354
+ /** One call to a tool on a connected tool server, at one event. */
355
+ export interface McpToolHookEntry extends ShellHookEntryBase {
356
+ readonly type: 'mcp_tool'
357
+ /** The server to call, by its name in the tool-server config. */
358
+ readonly server: string
359
+ /** The tool to call, by the name the server itself reports (no `mcp__` prefix). */
360
+ readonly tool: string
361
+ /**
362
+ * The arguments the tool is called with, as one JSON object. Absent, the
363
+ * tool is called with none.
364
+ */
365
+ readonly arguments?: Readonly<Record<string, unknown>>
366
+ }
367
+
354
368
  /** Any hook entry a config may carry. */
355
- export type ShellHookHandler = ShellHookEntry | HttpHookEntry | PromptHookEntry
369
+ export type ShellHookHandler = ShellHookEntry | HttpHookEntry | PromptHookEntry | McpToolHookEntry
356
370
 
357
371
  /** Event → entries, the shape a host's config file carries. */
358
372
  export type ShellHooksConfig = {
@@ -2027,10 +2041,11 @@ export function shellHookVerdict(
2027
2041
  }
2028
2042
  }
2029
2043
 
2030
- /** A short name for a hook in logs: its command, its url, or the start of its prompt. */
2044
+ /** A short name for a hook in logs: its command, its url, the tool it calls, or the start of its prompt. */
2031
2045
  export function describeShellHook(entry: ShellHookHandler): string {
2032
2046
  if (entry.type === 'http') return entry.url
2033
2047
  if (entry.type === 'prompt') return `prompt: ${entry.prompt.slice(0, 80)}`
2048
+ if (entry.type === 'mcp_tool') return `mcp: ${entry.server}/${entry.tool}`
2034
2049
  return entry.command
2035
2050
  }
2036
2051
 
@@ -2052,9 +2067,40 @@ export type ShellHookJudge = (request: {
2052
2067
  readonly signal: AbortSignal
2053
2068
  }) => Promise<string | undefined>
2054
2069
 
2070
+ /**
2071
+ * What one `mcp_tool` call came back with. `ok` false is a call the server
2072
+ * refused or that failed; `output` is the text of a successful one, read
2073
+ * exactly as a command hook's stdout is (its JSON answer included).
2074
+ */
2075
+ export interface ShellHookMcpToolAnswer {
2076
+ readonly ok: boolean
2077
+ readonly output: string
2078
+ readonly error?: string
2079
+ }
2080
+
2081
+ /**
2082
+ * Calls one tool on one connected tool server and returns its answer, or
2083
+ * `undefined` when no connected server has that tool. The host supplies it:
2084
+ * the kernel does not own the servers a session is connected to. It should
2085
+ * honour `signal`.
2086
+ */
2087
+ export type ShellHookMcpToolCaller = (request: {
2088
+ readonly server: string
2089
+ readonly tool: string
2090
+ readonly arguments: Readonly<Record<string, unknown>>
2091
+ readonly sessionId: string
2092
+ readonly turnId?: string
2093
+ readonly signal: AbortSignal
2094
+ }) => Promise<ShellHookMcpToolAnswer | undefined>
2095
+
2055
2096
  export interface ShellHookOptions {
2056
2097
  /** Answers `prompt` hooks. Without it a `prompt` hook is logged and lets the action go ahead. */
2057
2098
  readonly judge?: ShellHookJudge
2099
+ /**
2100
+ * Calls the tool an `mcp_tool` hook names. Without it such a hook is
2101
+ * reported as a failure, which `onFailure: block` counts as a refusal.
2102
+ */
2103
+ readonly mcpToolCall?: ShellHookMcpToolCaller
2058
2104
  /** Where the command runs and what `cwd` says on stdin. */
2059
2105
  readonly cwd: string
2060
2106
  readonly log?: Logger
@@ -2220,11 +2266,79 @@ function readJudgement(reply: string): { ok: boolean; reason: string } | undefin
2220
2266
  }
2221
2267
  }
2222
2268
 
2269
+ /**
2270
+ * An `mcp_tool` hook: the host calls the named tool on the named server, and
2271
+ * its answer is read exactly as a command hook's stdout is. A call that
2272
+ * cannot be made — no caller, no such server or tool, a refused or failed
2273
+ * call, the deadline — is the hook's own failure, which `onFailure: block`
2274
+ * counts as a refusal.
2275
+ */
2276
+ async function runMcpToolHook(
2277
+ entry: McpToolHookEntry,
2278
+ input: ShellHookInput,
2279
+ call: ShellHookMcpToolCaller | undefined,
2280
+ signal: AbortSignal | undefined,
2281
+ log: Logger,
2282
+ ): Promise<ShellHookOutcome> {
2283
+ const where = describeShellHook(entry)
2284
+ if (call === undefined) {
2285
+ return {
2286
+ exitCode: null,
2287
+ timedOut: false,
2288
+ stdout: '',
2289
+ stderr: '',
2290
+ spawnError: `no connected tool server is reachable, so ${where} was not called`,
2291
+ }
2292
+ }
2293
+ const deadline = AbortSignal.timeout(hookTimeout(entry))
2294
+ const combined = signal ? AbortSignal.any([signal, deadline]) : deadline
2295
+ let answer: ShellHookMcpToolAnswer | undefined
2296
+ try {
2297
+ answer = await call({
2298
+ server: entry.server,
2299
+ tool: entry.tool,
2300
+ arguments: entry.arguments ?? {},
2301
+ sessionId: input.sessionId,
2302
+ ...(input.turnId !== undefined ? { turnId: input.turnId } : {}),
2303
+ signal: combined,
2304
+ })
2305
+ } catch (error) {
2306
+ log.warn('mcp tool hook failed', {
2307
+ 'namzu.hook.event': input.event,
2308
+ 'namzu.hook.command': where,
2309
+ 'namzu.hook.error': error instanceof Error ? error.message : String(error),
2310
+ })
2311
+ return {
2312
+ exitCode: 1,
2313
+ timedOut: deadline.aborted,
2314
+ stdout: '',
2315
+ stderr: error instanceof Error ? error.message : String(error),
2316
+ }
2317
+ }
2318
+ if (answer === undefined) {
2319
+ return {
2320
+ exitCode: 1,
2321
+ timedOut: deadline.aborted,
2322
+ stdout: '',
2323
+ stderr: `no connected server named ${entry.server} offers a tool named ${entry.tool}`,
2324
+ }
2325
+ }
2326
+ if (!answer.ok) {
2327
+ return {
2328
+ exitCode: 1,
2329
+ timedOut: deadline.aborted,
2330
+ stdout: '',
2331
+ stderr: answer.error ?? 'the tool call failed',
2332
+ }
2333
+ }
2334
+ return { exitCode: 0, timedOut: false, stdout: answer.output, stderr: '' }
2335
+ }
2336
+
2223
2337
  /**
2224
2338
  * One run of a `worktree_create` or `worktree_remove` hook, to its answer. It
2225
2339
  * is always awaited (an `async` flag cannot make a hook that does the work run
2226
- * out of sight), and a `prompt` hook cannot do it at all, which is said as a
2227
- * failure rather than skipped.
2340
+ * out of sight), and a `prompt` or `mcp_tool` hook cannot do it at all, which
2341
+ * is said as a failure rather than skipped.
2228
2342
  */
2229
2343
  async function runWorktreeHook(
2230
2344
  event: 'worktree_create' | 'worktree_remove',
@@ -2234,10 +2348,10 @@ async function runWorktreeHook(
2234
2348
  reportTimeout: (timedOut: boolean) => void,
2235
2349
  ): Promise<PluginHookResult> {
2236
2350
  const label = describeShellHook(entry)
2237
- if (entry.type === 'prompt') {
2351
+ if (entry.type === 'prompt' || entry.type === 'mcp_tool') {
2238
2352
  return {
2239
2353
  action: 'error',
2240
- message: `The ${event} hook \`${label}\` is a prompt, and a prompt cannot make or remove a worktree. Use a command or an http hook.`,
2354
+ message: `The ${event} hook \`${label}\` is a ${entry.type} hook, and it cannot make or remove a worktree. Use a command or an http hook.`,
2241
2355
  }
2242
2356
  }
2243
2357
  if (entry.type === 'http') {
@@ -2499,6 +2613,17 @@ export function createShellHook(
2499
2613
  if (entry.type === 'prompt') {
2500
2614
  return judgePromptHook(event, entry, hookInput, options.judge, context.signal, log)
2501
2615
  }
2616
+ if (entry.type === 'mcp_tool') {
2617
+ const outcome = await runMcpToolHook(
2618
+ entry,
2619
+ hookInput,
2620
+ options.mcpToolCall,
2621
+ context.signal,
2622
+ log,
2623
+ )
2624
+ reportTimeout(outcome.timedOut)
2625
+ return shellHookVerdict(event, entry, outcome, log, verdictCall)
2626
+ }
2502
2627
  if (entry.async === true) {
2503
2628
  // Started and left running: it decides nothing, so nothing waits
2504
2629
  // for it and its own failure is only written down.
@@ -96,6 +96,7 @@ export type {
96
96
 
97
97
  export type {
98
98
  CodeNavigationProvider,
99
+ CodeNavigationRequestOptions,
99
100
  CodeNavigationResult,
100
101
  HoverResult,
101
102
  SourceLocation,
@@ -1398,6 +1399,10 @@ export type { VaultInstrumentationOptions } from './vault/instrumentation.js'
1398
1399
 
1399
1400
  export {
1400
1401
  GitWorktreeDriver,
1402
+ DiskWorkspaceHoldStore,
1403
+ WorkspaceInUseError,
1404
+ defaultWorkspaceHoldsDir,
1405
+ defaultWorktreesDir,
1401
1406
  HookedWorkspaceDriver,
1402
1407
  WorktreeHookError,
1403
1408
  worktreeHookHost,
@@ -243,11 +243,14 @@ export type {
243
243
  } from './agents/file-definitions.js'
244
244
  export type {
245
245
  HttpHookEntry,
246
+ McpToolHookEntry,
246
247
  PromptHookEntry,
247
248
  ShellHookEntry,
248
249
  ShellHookEvent,
249
250
  ShellHookHandler,
250
251
  ShellHookJudge,
252
+ ShellHookMcpToolAnswer,
253
+ ShellHookMcpToolCaller,
251
254
  ShellHookOnFailure,
252
255
  ShellHookCall,
253
256
  ShellHookInput,
@@ -284,6 +287,10 @@ export type {
284
287
  export type {
285
288
  RegisterSharedSessionPlanInput,
286
289
  SharedSessionWorkspaceConfig,
290
+ DiskWorkspaceHoldStoreOptions,
291
+ WorkspaceHold,
292
+ WorkspaceHoldRequest,
293
+ WorkspaceHoldStore,
287
294
  } from './session/workspace/index.js'
288
295
 
289
296
  export type {
@@ -22,6 +22,7 @@ import { homedir } from 'node:os'
22
22
  import { dirname, isAbsolute, relative, resolve, sep } from 'node:path'
23
23
 
24
24
  import { isProtectedPath } from '../../authorization/protected-paths.js'
25
+ import { isReadOnlyCommandLine } from '../../authorization/readonly-commands.js'
25
26
  import { dangerousRemoval } from '../../authorization/removal.js'
26
27
  import type { ShellDialect } from '../../authorization/shell-lexer.js'
27
28
  import { readShellLine, shellPathAccess } from '../../authorization/shell-paths.js'
@@ -178,29 +179,83 @@ export function expandBraces(value: string, limit = 16): string[] {
178
179
  return out
179
180
  }
180
181
 
181
- /** The path a use names with `~` and `$HOME` read as the home directory, or why it cannot be. */
182
+ /**
183
+ * `$PWD` or `${PWD}` inside a word. The lookahead keeps `$PWDfoo` a variable of
184
+ * its own, and the braced form carries its own braces, so `${PWD:-x}` — which
185
+ * decides its value at run time — matches neither.
186
+ */
187
+ const WORKING_DIRECTORY_VARIABLE = /\$(?:\{PWD\}|PWD(?![A-Za-z0-9_]))/
188
+
189
+ /** A directory whose every character an unquoted expansion leaves as it is: no space, glob character or backslash. */
190
+ const PLAIN_DIRECTORY = /^[A-Za-z0-9._/@%+,:=~-]*$/
191
+
192
+ /** Whether `$PWD` or `${PWD}` appears outside double and single quotes. */
193
+ function hasUnquotedWorkingDirectory(line: string): boolean {
194
+ let single = false
195
+ let double = false
196
+ for (let i = 0; i < line.length; i += 1) {
197
+ const c = line[i] as string
198
+ if (c === '\\' && !single) {
199
+ i += 1
200
+ continue
201
+ }
202
+ if (c === "'" && !double) single = !single
203
+ else if (c === '"' && !single) double = !double
204
+ else if (c === '$' && !single && !double) {
205
+ if (/^\$(?:\{PWD\}|PWD(?![A-Za-z0-9_]))/.test(line.slice(i))) return true
206
+ }
207
+ }
208
+ return false
209
+ }
210
+
211
+ /**
212
+ * The path a use names with `~` and the variables whose value is known before
213
+ * the line runs, or why it cannot be.
214
+ *
215
+ * `$NAMZU_SCRATCH` names the session's scratch folder; `$PWD` and `${PWD}` name
216
+ * the directory the line starts in. A word resolved from one of those carries
217
+ * `resolved`, so the caller does not treat it as decided at run time; anything
218
+ * else that expands has no path.
219
+ */
182
220
  function settle(
183
221
  value: string,
184
222
  home: string,
185
- scratch?: string,
223
+ scratch: string | undefined,
224
+ startDirectory: string | undefined,
186
225
  ):
187
226
  | { readonly path: string }
188
- | { readonly unresolved: true; readonly scratch?: never }
189
- | { readonly path: string; readonly scratch: true } {
227
+ | { readonly unresolved: true; readonly resolved?: never }
228
+ | { readonly path: string; readonly resolved: true } {
190
229
  if (scratch !== undefined) {
191
230
  const named = /^\$(?:\{NAMZU_SCRATCH\}|NAMZU_SCRATCH)(?=\/|$)/.exec(value)
192
231
  const rest = named === null ? undefined : value.slice(named[0].length)
193
232
  if (rest !== undefined && !/[$`~*?[{]/.test(rest)) {
194
- return { path: resolve(scratch, `.${rest}`), scratch: true }
233
+ return { path: resolve(scratch, `.${rest}`), resolved: true }
195
234
  }
196
235
  }
197
- if (value === '~') return { path: home }
198
- if (value.startsWith('~/')) return { path: resolve(home, value.slice(2)) }
199
- if (value.startsWith('~')) return { unresolved: true }
200
- const variable = /^\$(?:\{HOME\}|HOME)(?=\/|$)/.exec(value)
201
- if (variable !== null) return { path: resolve(home, `.${value.slice(variable[0].length)}`) }
202
- if (/[$`]/.test(value)) return { unresolved: true }
203
- return { path: value }
236
+ // `$PWD` and `${PWD}` name the directory the line starts in, which the shell
237
+ // fixes before the line runs, so a word carrying one reads as the same word
238
+ // with that directory spelled out. Every other expansion leaves a `$` behind
239
+ // and is therefore decided at run time.
240
+ const spelled =
241
+ startDirectory === undefined
242
+ ? value
243
+ : value.replace(new RegExp(WORKING_DIRECTORY_VARIABLE, 'g'), () => startDirectory)
244
+ const spelledOut = spelled !== value
245
+ if (spelledOut && /[$`]/.test(spelled)) return { unresolved: true }
246
+ if (spelled === '~') return spelledOut ? { path: home, resolved: true } : { path: home }
247
+ if (spelled.startsWith('~/')) {
248
+ const path = resolve(home, spelled.slice(2))
249
+ return spelledOut ? { path, resolved: true } : { path }
250
+ }
251
+ if (spelled.startsWith('~')) return { unresolved: true }
252
+ const variable = /^\$(?:\{HOME\}|HOME)(?=\/|$)/.exec(spelled)
253
+ if (variable !== null) {
254
+ const path = resolve(home, `.${spelled.slice(variable[0].length)}`)
255
+ return spelledOut ? { path, resolved: true } : { path }
256
+ }
257
+ if (/[$`]/.test(spelled)) return { unresolved: true }
258
+ return spelledOut ? { path: spelled, resolved: true } : { path: spelled }
204
259
  }
205
260
 
206
261
  /** The part of a glob path before the first segment that holds a glob character. */
@@ -242,6 +297,23 @@ export async function shellEscalations(
242
297
  const reads =
243
298
  line.split('$NAMZU_SCRATCH').length - 1 + (line.split('${NAMZU_SCRATCH}').length - 1)
244
299
  const scratch = mentions === reads ? context.scratchpadDirectory : undefined
300
+ // `$PWD` is read as the start directory only for a line the read-only
301
+ // recogniser accepts: every command on it is a known reader, it assigns
302
+ // nothing, and it never runs `cd`, `eval`, `source` or a function, so
303
+ // nothing before the use can have changed the variable. Any other line
304
+ // keeps `$PWD` as a word decided at run time, so a write through it is
305
+ // asked about. An unquoted use is resolved only when every character of
306
+ // the directory is one the shell leaves alone in an expanded word; any
307
+ // other (a space, a glob character, a backslash that a glob reads as an
308
+ // escape) would let splitting or globbing change which paths the word
309
+ // names, so the use stays unresolved and, on a read-only line, is asked
310
+ // about rather than left to run.
311
+ const readOnlyWithPwd =
312
+ cwd !== undefined &&
313
+ WORKING_DIRECTORY_VARIABLE.test(line) &&
314
+ isReadOnlyCommandLine(line, dialect)
315
+ const pwdHeld =
316
+ readOnlyWithPwd && (PLAIN_DIRECTORY.test(cwd) || !hasUnquotedWorkingDirectory(line))
245
317
  if (cwd !== undefined) {
246
318
  // A link made earlier in this very line leads somewhere that cannot be
247
319
  // read before the line runs: `ln -s /etc l && cd l && echo x > passwd`
@@ -255,9 +327,16 @@ export async function shellEscalations(
255
327
  .map((value) => resolve(cwd, value))
256
328
  for (const use of access.uses) {
257
329
  for (const spelled of expandBraces(use.path)) {
258
- const settled = settle(spelled, home, scratch)
330
+ // After a `cd` the shell holds another directory, so `$PWD` no longer
331
+ // names the one the line started in and is left to run time.
332
+ const settled = settle(
333
+ spelled,
334
+ home,
335
+ scratch,
336
+ use.directory === undefined && pwdHeld ? cwd : undefined,
337
+ )
259
338
  const unresolved =
260
- ('scratch' in settled ? false : use.unresolved) || 'unresolved' in settled
339
+ ('resolved' in settled ? false : use.unresolved) || 'unresolved' in settled
261
340
  const base = 'path' in settled ? settled.path : spelled
262
341
  // Where a relative path may start from. Usually the directory the
263
342
  // line began in; after a literal `cd <relative>` also the directory
@@ -291,8 +370,15 @@ export async function shellEscalations(
291
370
  if (!context.reviewOutside) continue
292
371
  if (unresolved) {
293
372
  // A write whose target is decided at runtime cannot be checked; a
294
- // read of one is left alone.
295
- if (use.access === 'write') outside.add(spelled)
373
+ // read of one is left alone. The exception is a read through
374
+ // `$PWD` on a line accepted as read-only only because `$PWD` was
375
+ // expected to name the start directory: left alone, it would run
376
+ // unasked wherever the shell's splitting or globbing took it.
377
+ if (
378
+ use.access === 'write' ||
379
+ (readOnlyWithPwd && WORKING_DIRECTORY_VARIABLE.test(spelled))
380
+ )
381
+ outside.add(spelled)
296
382
  continue
297
383
  }
298
384
  if (
@@ -120,6 +120,28 @@ export class SteeringBinding implements SteeringChannel {
120
120
  */
121
121
  export const JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES = 2048
122
122
 
123
+ /**
124
+ * The most of a job's command line an exit notice quotes. The notice is
125
+ * carried into every later session that learns the job ended, so an unbounded
126
+ * command would be pasted into each of them; the whole line stays in the job's
127
+ * own record, which the job tool lists.
128
+ */
129
+ export const JOB_NOTICE_COMMAND_MAX_CHARS = 300
130
+
131
+ /**
132
+ * A job's command as its exit notice quotes it: the whole of it when it fits
133
+ * {@link JOB_NOTICE_COMMAND_MAX_CHARS}, otherwise its first and last stretch
134
+ * with the number of characters left out between them — the same head-and-tail
135
+ * summary a value is cut with elsewhere in the kernel. The full line is not
136
+ * lost, only the notice does not carry it.
137
+ */
138
+ export function boundJobNoticeCommand(
139
+ command: string,
140
+ max: number = JOB_NOTICE_COMMAND_MAX_CHARS,
141
+ ): string {
142
+ return cutMiddle(command, max, inlineCutMarker)
143
+ }
144
+
123
145
  /**
124
146
  * One job's exit as the text the model reads. The output is inlined only when
125
147
  * the whole of it fits {@link JOB_NOTICE_INLINE_OUTPUT_MAX_BYTES} and none was
@@ -145,7 +167,7 @@ export function formatJobExitNotice(
145
167
  ? ` after ${formatMonitorDuration(Math.max(0, job.exitedAt - job.startedAt))}`
146
168
  : ''
147
169
  const saved = job.outputFile === undefined ? '' : ` Its output is saved to ${job.outputFile}.`
148
- const head = `Background job ${job.id} (${job.command}) ${outcome}${endedAt}${ran}.${saved}`
170
+ const head = `Background job ${job.id} (${boundJobNoticeCommand(job.command)}) ${outcome}${endedAt}${ran}.${saved}`
149
171
  if (
150
172
  output === undefined ||
151
173
  output.chunk.length === 0 ||
@@ -334,9 +356,22 @@ export function capMonitorContent(
334
356
  return text.length <= max ? text : cutMiddle(text, max)
335
357
  }
336
358
 
337
- function cutMiddle(text: string, max: number): string {
359
+ /** The cut a multi-line block gets: the marker stands on a line of its own. */
360
+ function multilineCutMarker(omitted: number): string {
361
+ return `\n...[${omitted} characters omitted]...\n`
362
+ }
363
+
364
+ /** The cut a value inside a line gets: no newline, so the line stays one line. */
365
+ function inlineCutMarker(omitted: number): string {
366
+ return `…[${omitted} characters omitted]…`
367
+ }
368
+
369
+ function cutMiddle(
370
+ text: string,
371
+ max: number,
372
+ marker: (omitted: number) => string = multilineCutMarker,
373
+ ): string {
338
374
  if (text.length <= max) return text
339
- const marker = (omitted: number) => `\n...[${omitted} characters omitted]...\n`
340
375
  // Reserve room for the marker itself so the result never exceeds `max`.
341
376
  const room = Math.max(0, max - marker(text.length).length)
342
377
  const head = Math.ceil(room / 2)
@@ -69,6 +69,18 @@ export interface WorkspaceBackendDriver {
69
69
  branch(source: WorkspaceRef, params: BranchWorkspaceParams): Promise<WorkspaceRef>
70
70
  dispose(ref: WorkspaceRef): Promise<void>
71
71
  inspect(ref: WorkspaceRef): Promise<WorkspaceInspection>
72
+ /**
73
+ * The child that worked in `ref` has ended: let go of whatever claim this
74
+ * driver still makes on that checkout, whether or not the checkout is kept.
75
+ *
76
+ * A checkout provisioned with `retain`, or with `retain-changed` when the
77
+ * child left something behind, is never passed to {@link dispose}, so without
78
+ * this the backend would go on reporting a checkout as in use by a session
79
+ * that has already finished. A driver that claims nothing can leave it out.
80
+ *
81
+ * Called on every terminal path of a child, before the retention decision.
82
+ */
83
+ release?(ref: WorkspaceRef): Promise<void>
72
84
  }
73
85
 
74
86
  export type { WorkspaceBackendKind } from '../../types/workspace/ref.js'