@miphamai/cli 0.85.24 → 0.85.25

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.
@@ -247,38 +247,145 @@ const LEADING_ASSIGNMENT_RE = /^[A-Za-z_][A-Za-z0-9_]*=/
247
247
  * 不剥尾随符号(`rm -rf x )` 里的 `)`):`wildcardMatch` 的 `*` 已经吃掉它。
248
248
  */
249
249
  export function stripLeadingShellNoise(segment: string): string {
250
- let tokens = segment.trim().split(/\s+/).filter(Boolean)
250
+ const n = segment.length
251
+ let i = 0
251
252
  let stripped = false
252
- let skipFlags = false
253
- for (;;) {
254
- const head = tokens[0]
255
- if (!head) break
256
- if (skipFlags && /^--?[A-Za-z]/.test(head)) {
257
- tokens = tokens.slice(1)
258
- stripped = true
259
- continue
253
+ const skipSpace = (): void => {
254
+ while (i < n && /\s/.test(segment[i]!)) i++
255
+ }
256
+
257
+ /**
258
+ * Consume one `NAME=value`, returning the index just past the value.
259
+ *
260
+ * Splitting on whitespace was the bug: `X="a b" rm …` became the tokens
261
+ * `['X="a', 'b"', 'rm', …]`, so stripping the first "assignment" left
262
+ * `b" rm …` — and the real command vanished from every gate that reads this
263
+ * normalized form (parameterized deny rules, dangerous `rm`, world-writable
264
+ * `chmod`). Values therefore have to be scanned with shell quoting rules,
265
+ * not tokenized by spaces.
266
+ */
267
+ const consumeAssignment = (start: number): number | null => {
268
+ const m = LEADING_ASSIGNMENT_RE.exec(segment.slice(start))
269
+ if (!m) return null
270
+ let j = start + m[0].length
271
+ while (j < n) {
272
+ const c = segment[j]!
273
+ if (/\s/.test(c)) break
274
+ if (c === '\\') {
275
+ j += 2
276
+ continue
277
+ }
278
+ if (c === "'") {
279
+ j++
280
+ while (j < n && segment[j] !== "'") j++
281
+ if (j < n) j++
282
+ continue
283
+ }
284
+ if (c === '"') {
285
+ j++
286
+ while (j < n) {
287
+ if (segment[j] === '\\') {
288
+ j += 2
289
+ continue
290
+ }
291
+ if (segment[j] === '"') {
292
+ j++
293
+ break
294
+ }
295
+ j++
296
+ }
297
+ continue
298
+ }
299
+ if (c === '`') {
300
+ j++
301
+ while (j < n && segment[j] !== '`') {
302
+ if (segment[j] === '\\') j++
303
+ j++
304
+ }
305
+ if (j < n) j++
306
+ continue
307
+ }
308
+ if (c === '$' && segment[j + 1] === '(') {
309
+ j += 2
310
+ let depth = 1
311
+ while (j < n && depth > 0) {
312
+ if (segment[j] === '(') depth++
313
+ else if (segment[j] === ')') depth--
314
+ j++
315
+ }
316
+ continue
317
+ }
318
+ if (c === '$' && segment[j + 1] === '{') {
319
+ j += 2
320
+ while (j < n && segment[j] !== '}') j++
321
+ if (j < n) j++
322
+ continue
323
+ }
324
+ if (c === '(') {
325
+ // Array assignment (`arr=(a b) cmd`): the whole parenthesized list is
326
+ // the value, spaces included.
327
+ let depth = 0
328
+ while (j < n) {
329
+ if (segment[j] === '(') depth++
330
+ else if (segment[j] === ')') {
331
+ depth--
332
+ if (depth === 0) {
333
+ j++
334
+ break
335
+ }
336
+ }
337
+ j++
338
+ }
339
+ continue
340
+ }
341
+ j++
260
342
  }
261
- skipFlags = false
262
- const bare = head.replace(/^[({!]+/, '') // `(!` 这类连写
263
- if (bare !== head) {
264
- tokens = bare ? [bare, ...tokens.slice(1)] : tokens.slice(1)
343
+ return j
344
+ }
345
+
346
+ for (;;) {
347
+ skipSpace()
348
+ if (i >= n) break
349
+ const c = segment[i]!
350
+
351
+ // Grouping / negation punctuation. Consume runs (`(!` / `((`).
352
+ if (LEADING_SHELL_PUNCT.has(c)) {
353
+ i++
265
354
  stripped = true
266
355
  continue
267
356
  }
268
- if (LEADING_SHELL_PUNCT.has(head) || LEADING_ASSIGNMENT_RE.test(head)) {
269
- tokens = tokens.slice(1)
270
- stripped = true
271
- continue
357
+
358
+ const word = /^[A-Za-z_][A-Za-z0-9_]*/.exec(segment.slice(i))?.[0]
359
+ if (word) {
360
+ const after = i + word.length
361
+ const atBoundary = after === n || /\s/.test(segment[after]!)
362
+ if (LEADING_SHELL_KEYWORDS.has(word) && atBoundary) {
363
+ i = after
364
+ stripped = true
365
+ // `time -p rm …` — the keyword's own bare flags are not the command.
366
+ for (;;) {
367
+ skipSpace()
368
+ if (i < n && segment[i] === '-' && /[A-Za-z]/.test(segment[i + 1] ?? '')) {
369
+ while (i < n && !/\s/.test(segment[i]!)) i++
370
+ continue
371
+ }
372
+ break
373
+ }
374
+ continue
375
+ }
272
376
  }
273
- if (LEADING_SHELL_KEYWORDS.has(head)) {
274
- tokens = tokens.slice(1)
377
+
378
+ const assignmentEnd = consumeAssignment(i)
379
+ if (assignmentEnd !== null) {
380
+ i = assignmentEnd
275
381
  stripped = true
276
- skipFlags = true // `time -p rm …` —— 关键字自己的裸 flag 不是命令
277
382
  continue
278
383
  }
384
+
279
385
  break
280
386
  }
281
- return stripped ? tokens.join(' ') : segment
387
+
388
+ return stripped ? segment.slice(i).trim() : segment
282
389
  }
283
390
 
284
391
  function uniq(items: string[]): string[] {
@@ -325,14 +432,19 @@ export function extractBashFileAccess(command: string): BashFileAccess {
325
432
  const read: string[] = []
326
433
  const write: string[] = []
327
434
 
328
- // 1. Redirect targets. Handles `> file` and `>file`, optional fd prefix
329
- // (`2>`, `&>`). Heredocs (`<<`) and fd-dup targets (`2>&1`) are skipped —
330
- // their "target" is a delimiter or file descriptor, not a path.
331
- const redirectRe = /(?:^|[\s;|&])([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
435
+ // 1. Redirect targets. Handles `> file`, `>file`, and the same operators
436
+ // right after a substitution/subshell (`(echo x)>file`, `x=$(date)>file`).
437
+ // Requiring a separator before the operator (the old shape) missed every
438
+ // no-space form, so `Edit(path)`/`Write(path)` deny rules were bypassable
439
+ // with `echo hi>path`. Heredocs (`<<`) and fd-dup targets (`2>&1`) are
440
+ // skipped — their "target" is a delimiter or file descriptor, not a path.
441
+ const redirectRe = /([0-9]*&?)?(>>|<<|<|>)\s*([^\s;|&<>]+)/g
332
442
  let m: RegExpExecArray | null
333
443
  while ((m = redirectRe.exec(command)) !== null) {
334
444
  const op = m[2]!
335
445
  if (op === '<<') continue // heredoc delimiter
446
+ // Process substitution `<(...)` / `>(...)` is not a redirect to a file.
447
+ if (m[3]!.startsWith('(')) continue
336
448
  const target = stripQuotes(m[3]!)
337
449
  if (op === '<') read.push(target)
338
450
  else write.push(target)
@@ -526,6 +638,10 @@ function scanReaderWriterCommands(
526
638
  // `sed -i` / `perl -i` read AND write their file args.
527
639
  const inPlace = args.some((a) => a === '-i' || a.startsWith('--in-place'))
528
640
  for (const arg of args) {
641
+ // Redirection operators are syntax, not paths: `cat < /etc/hosts`
642
+ // already contributed `/etc/hosts` in the redirect pass. Keeping the
643
+ // bare `<` here made it look like a read target of its own.
644
+ if (/^[0-9]*[<>]{1,2}&?[0-9-]*$/.test(arg)) continue
529
645
  if (arg.startsWith('-')) {
530
646
  // `--include=*secret*` / `--file=.env`: the option VALUE is a path the
531
647
  // reader opens, but the `-` guard used to drop the whole token, so a
@@ -345,11 +345,32 @@ export class PluginManager {
345
345
  // plugin command instead of starting empty.
346
346
  this.plugins = Array.isArray(parsed) ? (parsed as InstalledPlugin[]) : []
347
347
  if (!Array.isArray(parsed)) {
348
- this.loadWarning = `Plugin state file is not a list; starting empty (${this.statePath})`
348
+ this.quarantineState('Plugin state file is not a list;')
349
349
  }
350
350
  } catch (err) {
351
351
  this.plugins = []
352
- this.loadWarning = `Could not read plugin state (${this.statePath}): ${String(err)}`
352
+ this.quarantineState(`Could not read plugin state (${this.statePath}): ${String(err)}.`)
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Move an unusable `state.json` aside before continuing with an empty list.
358
+ *
359
+ * Warning alone is not enough: the next `saveState` persists `[]` over the
360
+ * same path, so a file we could not read becomes a file whose records are
361
+ * gone. Renaming keeps the bytes for hand recovery — and if the rename fails
362
+ * the warning says so, because that is exactly the case where the next save
363
+ * destroys the only copy.
364
+ */
365
+ private quarantineState(reason: string): void {
366
+ const backup = `${this.statePath}.corrupt-${Date.now()}`
367
+ try {
368
+ renameSync(this.statePath, backup)
369
+ this.loadWarning = `${reason} Moved to ${backup}; starting with an empty plugin list.`
370
+ } catch (err) {
371
+ this.loadWarning =
372
+ `${reason} Could not move it aside (${String(err)}); starting with an empty ` +
373
+ `plugin list — the next change overwrites ${this.statePath}.`
353
374
  }
354
375
  }
355
376
 
@@ -8,6 +8,9 @@ import { getMetrics } from '../core/metrics'
8
8
  * active. Exported so the permission classifier and `self-critique` pick the
9
9
  * same model — two private copies of this heuristic would drift apart silently.
10
10
  */
11
+ /** Tier shorthands an agent definition may use instead of a concrete model id. */
12
+ const MODEL_TIER_ALIASES = new Set(['haiku', 'sonnet', 'opus'])
13
+
11
14
  export function pickFastestModel(registry: ProviderRegistry): string {
12
15
  const models = registry.listModels?.() ?? []
13
16
  const flash = models.find(
@@ -120,12 +123,31 @@ export class ProviderRegistry implements Llm {
120
123
  return provider.config.models.filter((m) => m.status === 'active')
121
124
  }
122
125
 
126
+ /**
127
+ * `haiku` / `sonnet` / `opus` are **tiers, not ids** — agent definitions
128
+ * (`AgentDefinition.model`) and `--model` spell them that way to mean "the
129
+ * current model of this tier". An exact id always wins, so a provider that
130
+ * really ships a model with that name is unaffected. Otherwise the tier is
131
+ * resolved against the **active provider only**: returning another provider's
132
+ * model would pair an id with a provider that cannot serve it, since the
133
+ * caller passes the resolved id back to the active provider's `chat()`.
134
+ *
135
+ * Within the tier the **last listed** active model wins — provider configs
136
+ * enumerate a family in ascending version order (`…-sonnet-4-6` before
137
+ * `…-sonnet-5`).
138
+ */
123
139
  findModel(modelId: string): ModelInfo | undefined {
124
140
  for (const provider of this.providers.values()) {
125
141
  const model = provider.config.models.find((m) => m.id === modelId)
126
142
  if (model) return model
127
143
  }
128
- return undefined
144
+ if (!MODEL_TIER_ALIASES.has(modelId)) return undefined
145
+ const active = this.providers.get(this.activeProviderId)
146
+ if (!active) return undefined
147
+ const tier = active.config.models.filter(
148
+ (m) => m.status === 'active' && m.id.toLowerCase().includes(`-${modelId}-`),
149
+ )
150
+ return tier.at(-1)
129
151
  }
130
152
 
131
153
  /**
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Environment for git commands **this program runs on its own behalf** (creating
3
+ * a worktree, reading the branch, …) — as opposed to commands the model asked to
4
+ * run in the user's shell.
5
+ *
6
+ * `GIT_NO_REPLACE_OBJECTS=1` makes git ignore `refs/replace/*`. A replace ref
7
+ * rewrites what a commit *appears to be*: `git replace <a> <b>` makes every
8
+ * reader of `<a>` see `<b>`'s tree, so a checkout / `worktree add` produced from
9
+ * that view contains different files than the real object graph. These are local
10
+ * refs that any process in the repository can write, and this program derives no
11
+ * correctness from replaying them — the isolation boundary (`enter-worktree`,
12
+ * workflow agents, `/fork`, the CRSI sandbox) has to be built from true history.
13
+ * `git` itself still accepts the env var as an escape hatch, so nothing here
14
+ * breaks a repository that genuinely relies on replacements in a user's shell.
15
+ */
16
+ export function internalGitEnv(): NodeJS.ProcessEnv {
17
+ return { ...process.env, GIT_NO_REPLACE_OBJECTS: '1' }
18
+ }
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.24' as const
12
+ export const PACKAGE_VERSION = '0.85.25' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -75,7 +75,7 @@ export const COMPANY_SHORT = '华安麦逄科技' as const
75
75
  */
76
76
 
77
77
  /** Slash 命令总数(真源:`getCommandNames().length`,`apps/cli/src/ui/commands.ts`) */
78
- export const SLASH_COMMAND_COUNT = 137 as const
78
+ export const SLASH_COMMAND_COUNT = 138 as const
79
79
 
80
80
  /** 内置提供商总数(真源:`DEFAULT_PROVIDERS.length`,`apps/cli/src/shared/constants.ts`) */
81
81
  export const PROVIDER_COUNT = 12 as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4388 as const
93
+ export const TEST_COUNT = 4477 as const
@@ -290,6 +290,27 @@ export function stripControlCharsForDisplay(input: string): string {
290
290
  )
291
291
  }
292
292
 
293
+ /**
294
+ * `String.prototype.slice` counted in UTF-16 code units, made **surrogate-safe**.
295
+ *
296
+ * A cut that lands between the two halves of a surrogate pair leaves a lone
297
+ * surrogate behind. When that string is serialized into a JSONL transcript,
298
+ * `JSON.stringify` emits it as a bare `\uD83D` escape and strict parsers reject
299
+ * the **whole line** (`jq`: "Invalid \uXXXX\uXXXX surrogate pair escape"). In a
300
+ * terminal it renders as U+FFFD.
301
+ *
302
+ * Back off one code unit when the last kept unit is a high surrogate, so the cut
303
+ * never splits a pair. A lone surrogate that was already in the input is left
304
+ * alone — this only removes *newly created* ones.
305
+ */
306
+ export function safeSlice(text: string, max: number): string {
307
+ if (!Number.isFinite(max) || max >= text.length) return text
308
+ if (max <= 0) return ''
309
+ const last = text.charCodeAt(max - 1)
310
+ const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max
311
+ return text.slice(0, end)
312
+ }
313
+
293
314
  /**
294
315
  * Full command sanitization pipeline for permission checks.
295
316
  * Applies in order:
@@ -46,6 +46,8 @@ export function invalidSkillNameReason(name: string): string | null {
46
46
 
47
47
  export class SkillsLoader implements Skills {
48
48
  private skills = new Map<string, SkillDefinition>()
49
+ /** File each loaded skill came from — so a name collision can name both sides. */
50
+ private sources = new Map<string, string>()
49
51
 
50
52
  loadBuiltin(basePath: string): void {
51
53
  // Load standard skills (*.SKILL.md)
@@ -237,7 +239,19 @@ export class SkillsLoader implements Skills {
237
239
  requiresBins: data['requires-bins'] as string[] | undefined,
238
240
  }
239
241
 
242
+ // Two files declaring the same name is a silent last-one-wins race: the
243
+ // user edits the shadowed file, reloads, and sees no effect. Say which file
244
+ // won and which one it displaced. Re-loading the **same** path (what
245
+ // `/reload-skills` does, into this same loader) is not a collision.
246
+ const previousSource = this.sources.get(skill.name)
247
+ if (previousSource !== undefined && previousSource !== sourceName) {
248
+ process.stderr.write(
249
+ `⚠️ Skill "${skill.name}" from ${sourceName} replaces the one loaded from ` +
250
+ `${previousSource} — the later file wins; rename one of them.\n`,
251
+ )
252
+ }
240
253
  this.skills.set(skill.name, skill)
254
+ this.sources.set(skill.name, sourceName)
241
255
  } catch {
242
256
  // skip unparseable
243
257
  }
@@ -5,6 +5,7 @@ import { sanitizeCommand } from '../../shared/sanitize.ts'
5
5
  import { DANGEROUS_GIT_PATTERNS } from './git.ts'
6
6
  import { isUncOrDevicePath, isWithin } from '../../security/path.ts'
7
7
  import { findWorktreeMarker } from '../../core/paths.ts'
8
+ import { splitShellSegments, expandKnownPathVars } from '../../core/permission-rules'
8
9
  import type { Service } from '../../vajra'
9
10
  import { toolKey } from '../seam'
10
11
  import { withValidation } from '../validation'
@@ -376,16 +377,177 @@ export function resolveWorktreeEscape(
376
377
  worktreeRoot: string,
377
378
  command: string,
378
379
  ): string | null {
379
- const cdRe = /\bcd\s+(?:"([^"]+)"|'([^']+)'|([^\s;|&]+))/g
380
- for (const m of command.matchAll(cdRe)) {
381
- const target = m[1] ?? m[2] ?? m[3]
382
- if (!target) continue
383
- const resolved = resolve(cwd, target)
384
- if (!isWithin(resolved, cwd) && !isWithin(resolved, worktreeRoot)) return target
380
+ for (const segment of splitShellSegments(command)) {
381
+ for (const target of changeDirectoryTargets(shellWords(segment))) {
382
+ // `resolve` does not expand `~` or `$HOME`: `cd ~` would otherwise be
383
+ // resolved as a directory literally named `~` under the worktree, i.e.
384
+ // "inside", while the shell lands in the home directory.
385
+ const resolved = resolve(cwd, expandKnownPathVars(target))
386
+ if (!isWithin(resolved, cwd) && !isWithin(resolved, worktreeRoot)) return target
387
+ }
385
388
  }
386
389
  return null
387
390
  }
388
391
 
392
+ /** Shell structure that can precede the command word without being one. */
393
+ const LEADING_SHELL_PUNCT = new Set(['(', '{', '!', ')', '}'])
394
+ /** Keywords after which the *next* word is the command (`if cd /x; then`). */
395
+ const LEADING_SHELL_KEYWORDS = new Set([
396
+ 'if',
397
+ 'then',
398
+ 'else',
399
+ 'elif',
400
+ 'while',
401
+ 'until',
402
+ 'do',
403
+ 'for',
404
+ 'time',
405
+ 'coproc',
406
+ ])
407
+ /** Wrappers that run a command of their own; the wrapped words are re-scanned. */
408
+ const WRAPPERS = new Set(['command', 'builtin'])
409
+ const LEADING_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
410
+ const CD_COMMANDS = new Set(['cd', 'pushd'])
411
+
412
+ /**
413
+ * Quote-aware word split of one simple command, with the quotes removed.
414
+ *
415
+ * The previous implementation matched `\bcd\s+` against the raw text. A quoted
416
+ * **command word** (`'cd' /etc`, `"cd" /etc`, `\cd /etc`) is still the `cd`
417
+ * builtin to bash, but there is no word boundary followed by whitespace in
418
+ * that spelling, so the guard never saw it. Reconstructing the words first also
419
+ * lets `pushd` and `env -C` be recognized as what they are.
420
+ *
421
+ * Over-splitting is the safe direction here: a word that is not really a
422
+ * command word simply fails to match `cd`.
423
+ */
424
+ function shellWords(segment: string): string[] {
425
+ const words: string[] = []
426
+ let cur = ''
427
+ let started = false
428
+ let quote: '"' | "'" | null = null
429
+ for (let i = 0; i < segment.length; i++) {
430
+ const ch = segment[i]!
431
+ if (quote === "'") {
432
+ if (ch === "'") quote = null
433
+ else cur += ch
434
+ continue
435
+ }
436
+ if (quote === '"') {
437
+ if (ch === '"') quote = null
438
+ else if (ch === '\\' && i + 1 < segment.length) cur += segment[++i]
439
+ else cur += ch
440
+ continue
441
+ }
442
+ if (ch === "'" || ch === '"') {
443
+ quote = ch
444
+ started = true
445
+ } else if (ch === '\\' && i + 1 < segment.length) {
446
+ cur += segment[++i]
447
+ started = true
448
+ } else if (/\s/.test(ch)) {
449
+ if (started) {
450
+ words.push(cur)
451
+ cur = ''
452
+ started = false
453
+ }
454
+ } else {
455
+ cur += ch
456
+ started = true
457
+ }
458
+ }
459
+ if (started) words.push(cur)
460
+ return words
461
+ }
462
+
463
+ /**
464
+ * Every directory this simple command changes the shell's cwd to.
465
+ *
466
+ * A bare `cd` goes to `$HOME`, which is outside any worktree — it is reported
467
+ * as the home directory rather than skipped. Re-scanning wrapped words is what
468
+ * catches `env A=1 -C /etc cd /tmp`: both directories are candidates, and
469
+ * either one leaving the worktree is enough to refuse the command.
470
+ */
471
+ function changeDirectoryTargets(words: string[], depth = 0): string[] {
472
+ if (depth > 4) return []
473
+ const out: string[] = []
474
+ let i = 0
475
+ const skipNoise = (): void => {
476
+ for (;;) {
477
+ while (i < words.length && LEADING_ASSIGNMENT.test(words[i]!)) i++
478
+ const word = words[i]
479
+ if (word === undefined) return
480
+ if (LEADING_SHELL_PUNCT.has(word)) {
481
+ i++
482
+ continue
483
+ }
484
+ if (LEADING_SHELL_KEYWORDS.has(word)) {
485
+ i++
486
+ // A keyword's own flags (`time -p rm …`) are not the command word.
487
+ while (i < words.length && /^-[A-Za-z]+$/.test(words[i]!)) i++
488
+ continue
489
+ }
490
+ return
491
+ }
492
+ }
493
+
494
+ skipNoise()
495
+ const cmd = words[i]
496
+ if (cmd === undefined) return out
497
+
498
+ if (WRAPPERS.has(cmd)) {
499
+ return changeDirectoryTargets(words.slice(i + 1), depth + 1)
500
+ }
501
+
502
+ if (cmd === 'env') {
503
+ i++
504
+ while (i < words.length) {
505
+ const w = words[i]!
506
+ if (w === '-C' || w === '--chdir') {
507
+ const dir = words[i + 1]
508
+ if (dir !== undefined) out.push(dir)
509
+ i += 2
510
+ continue
511
+ }
512
+ if (w.startsWith('--chdir=')) {
513
+ out.push(w.slice('--chdir='.length))
514
+ i++
515
+ continue
516
+ }
517
+ if (w === '-u' || w === '--unset') {
518
+ i += 2 // takes an argument
519
+ continue
520
+ }
521
+ if (LEADING_ASSIGNMENT.test(w)) {
522
+ i++ // `env A=1 -C /etc cmd` — assignments may sit among the options
523
+ continue
524
+ }
525
+ if (w === '-S' || w === '--split-string' || w === '--') break
526
+ if (w.startsWith('-')) {
527
+ i++
528
+ continue
529
+ }
530
+ break
531
+ }
532
+ return out.concat(changeDirectoryTargets(words.slice(i), depth + 1))
533
+ }
534
+
535
+ if (!CD_COMMANDS.has(cmd)) return out
536
+
537
+ let j = i + 1
538
+ while (j < words.length && /^-[A-Za-z]+$/.test(words[j]!)) j++
539
+ if (words[j] === '--') j++
540
+ const target = words[j]
541
+ if (target === undefined) {
542
+ // `cd` / `pushd` alone: `cd` goes home. (`pushd` with no argument swaps the
543
+ // directory stack, which cannot leave the shell it is already in.)
544
+ if (cmd === 'cd') out.push('~')
545
+ } else {
546
+ out.push(target)
547
+ }
548
+ return out
549
+ }
550
+
389
551
  export function createBashTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
390
552
  return {
391
553
  name: 'Bash',
@@ -1,6 +1,10 @@
1
1
  import type { ToolDefinition } from '../../shared/index.ts'
2
+ import { internalGitEnv } from '../../shared/git-env'
2
3
  import { listsWorktree, worktreeRoot } from '../../core/paths.ts'
3
4
 
5
+ /** Upper bound for `git worktree add` — a hung fetch must not hang the tool. */
6
+ const WORKTREE_ADD_TIMEOUT_MS = 60_000
7
+
4
8
  export const enterWorktreeTool: ToolDefinition = {
5
9
  name: 'EnterWorktree',
6
10
  description:
@@ -78,6 +82,7 @@ export const enterWorktreeTool: ToolDefinition = {
78
82
  cwd,
79
83
  stdout: 'pipe',
80
84
  stderr: 'pipe',
85
+ env: internalGitEnv(),
81
86
  })
82
87
  const gitCheckExit = await gitCheck.exited
83
88
  if (gitCheckExit !== 0) {
@@ -93,6 +98,7 @@ export const enterWorktreeTool: ToolDefinition = {
93
98
  cwd,
94
99
  stdout: 'pipe',
95
100
  stderr: 'pipe',
101
+ env: internalGitEnv(),
96
102
  })
97
103
  const existingWorktrees = await new Response(checkProc.stdout).text()
98
104
  if (listsWorktree(existingWorktrees, worktreePath)) {
@@ -116,6 +122,7 @@ export const enterWorktreeTool: ToolDefinition = {
116
122
  cwd,
117
123
  stdout: 'pipe',
118
124
  stderr: 'pipe',
125
+ env: internalGitEnv(),
119
126
  })
120
127
  const branch = (await new Response(branchProc.stdout).text()).trim()
121
128
  resolvedBaseRef = branch || 'HEAD'
@@ -134,10 +141,27 @@ export const enterWorktreeTool: ToolDefinition = {
134
141
  // nonsense, which is what a bad base ref should do.
135
142
  const proc = Bun.spawn(
136
143
  ['git', 'worktree', 'add', '-b', branchName, worktreePath, '--', resolvedBaseRef],
137
- { cwd, stdout: 'pipe', stderr: 'pipe' },
144
+ { cwd, stdout: 'pipe', stderr: 'pipe', env: internalGitEnv() },
138
145
  )
139
146
  const _stdout = await new Response(proc.stdout).text()
140
- const exitCode = await proc.exited
147
+ // A worktree that cannot be created (a promisor remote that is gone, a
148
+ // lock from a crashed run) otherwise hangs this tool with no answer at all.
149
+ let timer: ReturnType<typeof setTimeout> | undefined
150
+ const exitCode = await Promise.race([
151
+ proc.exited,
152
+ new Promise<number>((resolve) => {
153
+ timer = setTimeout(() => resolve(-1), WORKTREE_ADD_TIMEOUT_MS)
154
+ }),
155
+ ])
156
+ clearTimeout(timer)
157
+ if (exitCode === -1) {
158
+ proc.kill()
159
+ return {
160
+ success: false,
161
+ content: '',
162
+ error: `git worktree add did not finish within ${WORKTREE_ADD_TIMEOUT_MS / 1000}s.`,
163
+ }
164
+ }
141
165
 
142
166
  if (exitCode !== 0) {
143
167
  const stderr = await new Response(proc.stderr).text()