@miphamai/cli 0.85.43 → 0.85.45

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.
@@ -5,7 +5,8 @@ import type {
5
5
  StreamChunk,
6
6
  ContentBlock,
7
7
  } from '../shared/index.ts'
8
- import type { ProviderInstance, ChatRequest } from './registry'
8
+ import type { ProviderInstance, ChatRequest, ConnectivityProbe } from './registry'
9
+ import { UNNAMED_TOOL_CALL } from '../shared/constants'
9
10
  import {
10
11
  fetchWithRetry,
11
12
  streamIdleTimeoutMs,
@@ -121,6 +122,12 @@ export class AnthropicProvider implements ProviderInstance {
121
122
  // off at the output ceiling rather than ended by the model.
122
123
  let truncated = false
123
124
 
125
+ // Why it was cut. `'max_tokens'` is recoverable (ask the model to continue);
126
+ // a stream that ends without `message_stop` is not (re-asking re-writes the
127
+ // fragment). Same terminal stop either way — this is the only distinction the
128
+ // provider can supply, so it has to travel with the chunk.
129
+ let truncationCause: 'max_tokens' | 'connection' | undefined
130
+
124
131
  // Set when the provider reports `stop_reason: 'refusal'`. A refusal is a
125
132
  // **successful** response (HTTP 200) that declines to answer, and it may carry
126
133
  // an empty content array — so without this the turn ends as a blank screen,
@@ -142,6 +149,7 @@ export class AnthropicProvider implements ProviderInstance {
142
149
  const terminalStop = (): StreamChunk => ({
143
150
  type: 'stop',
144
151
  ...(truncated ? { truncated: true } : {}),
152
+ ...(truncationCause ? { truncationCause } : {}),
145
153
  ...(refusal ? { refusal } : {}),
146
154
  })
147
155
 
@@ -319,7 +327,12 @@ export class AnthropicProvider implements ProviderInstance {
319
327
  // tool_calls 落在同一个响应体里)。**这是有意的不对称,不是漏做**:
320
328
  // 要在这里丢弃,就得把 `tool_use` 缓冲到 `message_stop` 再发 ——
321
329
  // 那是一次行为变更,不属本次范围。
322
- if (currentToolId && currentToolName && accumulatedToolInput) {
330
+ // A named call needs accumulated input (the old shape). A *nameless*
331
+ // block is malformed on its own, so it is emitted regardless of
332
+ // whether any input arrived: dropping it left the turn as a silent
333
+ // short answer with nothing for the model to correct (331-038).
334
+ const nameless = !!currentToolId && !currentToolName
335
+ if ((currentToolId && currentToolName && accumulatedToolInput) || nameless) {
323
336
  // A replayed block carries the id it was first sent with, so the
324
337
  // id is what tells a second call apart from the same call twice.
325
338
  if (!emittedToolIds.has(currentToolId)) {
@@ -327,7 +340,7 @@ export class AnthropicProvider implements ProviderInstance {
327
340
 
328
341
  let parsedInput: Record<string, unknown> = {}
329
342
  try {
330
- parsedInput = JSON.parse(accumulatedToolInput)
343
+ parsedInput = accumulatedToolInput ? JSON.parse(accumulatedToolInput) : {}
331
344
  } catch (err) {
332
345
  // Same tag as the OpenAI-compatible path: a bare fragment
333
346
  // reaches the validator as "missing required parameter",
@@ -343,7 +356,7 @@ export class AnthropicProvider implements ProviderInstance {
343
356
  toolUse: {
344
357
  type: 'tool_use',
345
358
  id: currentToolId,
346
- name: currentToolName,
359
+ name: currentToolName || UNNAMED_TOOL_CALL,
347
360
  input: parsedInput,
348
361
  },
349
362
  }
@@ -376,6 +389,7 @@ export class AnthropicProvider implements ProviderInstance {
376
389
  const stopReason = event.delta?.stop_reason
377
390
  if (stopReason === 'max_tokens') {
378
391
  truncated = true
392
+ truncationCause = 'max_tokens'
379
393
  }
380
394
  // A refusal is a successful response that declines to answer, and
381
395
  // it can arrive with no content at all. Capture the provider's own
@@ -414,7 +428,12 @@ export class AnthropicProvider implements ProviderInstance {
414
428
  // The stream ran out without `message_stop`. Whatever stopped it, the turn is
415
429
  // incomplete — and this is the only place that knows, because a cleanly
416
430
  // closed connection and a finished response are otherwise the same stream.
417
- if (!sawTerminalEvent) truncated = true
431
+ if (!sawTerminalEvent) {
432
+ truncated = true
433
+ // A `max_tokens` stop seen earlier is the real cause; only an otherwise
434
+ // ordinary stream that just dies is a connection cut.
435
+ truncationCause ??= 'connection'
436
+ }
418
437
 
419
438
  yield terminalStop()
420
439
  } finally {
@@ -433,6 +452,44 @@ export class AnthropicProvider implements ProviderInstance {
433
452
  return apiKey.length > 0 && apiKey.startsWith('sk-ant-')
434
453
  }
435
454
 
455
+ /**
456
+ * Detailed reachability for `/doctor` (331-003).
457
+ *
458
+ * `healthCheck` above only inspects the key's shape — it never touches the
459
+ * network, so the "reachable" it backs is really "configured". This probe
460
+ * asks the API: any HTTP answer (200, 401, 404) proves the endpoint is there,
461
+ * and the status tells the user which problem they have.
462
+ */
463
+ async probeConnectivity(): Promise<ConnectivityProbe> {
464
+ const apiKey = this.resolveApiKey(this.config.apiKey)
465
+ if (!apiKey) return { tested: false, ok: false, detail: 'no API key configured' }
466
+ const url = `${this.baseUrl}/models`
467
+ try {
468
+ const res = await fetchWithRetry(
469
+ url,
470
+ {
471
+ headers: {
472
+ 'x-api-key': apiKey,
473
+ 'anthropic-version': '2023-06-01',
474
+ },
475
+ },
476
+ { timeout: 5000, maxRetries: 0 },
477
+ )
478
+ try {
479
+ await res.body?.cancel()
480
+ } catch {
481
+ /* body already gone */
482
+ }
483
+ return { tested: true, ok: true, detail: `HTTP ${res.status} from ${url}` }
484
+ } catch (err) {
485
+ return {
486
+ tested: true,
487
+ ok: false,
488
+ detail: `${err instanceof Error ? err.message : String(err)} (${url})`,
489
+ }
490
+ }
491
+ }
492
+
436
493
  /**
437
494
  * Mark the stable conversation prefix for prompt caching. The breakpoint is
438
495
  * placed on the last block of the second-to-last message, leaving only the
@@ -34,5 +34,18 @@ export function bootstrapProviders(
34
34
  }
35
35
  }
36
36
 
37
+ // Resolve a tier alias (`haiku` / `sonnet` / `opus`) to the concrete model id
38
+ // **before** anything reads the active model.
39
+ //
40
+ // `findModel` already resolves these against the active provider, but it was
41
+ // only consulted when sizing the context window: the registry kept the raw
42
+ // string, so `--model haiku` sent the literal id "haiku" to the provider and
43
+ // matched no row in the model picker. Doing it here gives the CLI, the daemon
44
+ // and the bin entry the same answer from one place.
45
+ const resolved = registry.findModel(defaultModel)
46
+ if (resolved && resolved.id !== defaultModel) {
47
+ registry.switchProvider(defaultProvider, resolved.id)
48
+ }
49
+
37
50
  return registry
38
51
  }
@@ -1,6 +1,6 @@
1
1
  import { execSync } from 'node:child_process'
2
2
  import type { ProviderConfig, ModelInfo, Message, StreamChunk } from '../shared/index.ts'
3
- import type { ProviderInstance, ChatRequest } from './registry'
3
+ import type { ProviderInstance, ChatRequest, ConnectivityProbe } from './registry'
4
4
  import {
5
5
  fetchWithRetry,
6
6
  streamIdleTimeoutMs,
@@ -8,7 +8,7 @@ import {
8
8
  createAwakeTimer,
9
9
  readErrorBody,
10
10
  } from './fetch-utils'
11
- import { OLLAMA_PRESET_MODELS } from '../shared/constants'
11
+ import { OLLAMA_PRESET_MODELS, UNNAMED_TOOL_CALL } from '../shared/constants'
12
12
  import { toWellFormed } from '../shared/sanitize'
13
13
 
14
14
  /**
@@ -160,14 +160,17 @@ export class OpenAICompatProvider implements ProviderInstance {
160
160
  const data = trimmed.slice(6)
161
161
  if (data === '[DONE]') {
162
162
  // Emit any pending tool calls before stopping
163
- for (const [, tc] of pendingToolCalls) {
164
- if (!tc.name) continue // drop malformed tool call (missing name)
163
+ for (const [idx, tc] of pendingToolCalls) {
164
+ // A nameless call is still a call the model wrote. Dropping it made
165
+ // the turn end as a short answer with no explanation; the synthetic
166
+ // name reaches the engine's unknown-tool path, which returns an
167
+ // error result the model can act on (331-038).
165
168
  yield {
166
169
  type: 'tool_use',
167
170
  toolUse: {
168
171
  type: 'tool_use',
169
- id: tc.id || `call_${Date.now()}`,
170
- name: tc.name,
172
+ id: tc.id || `call_${Date.now()}_${idx}`,
173
+ name: tc.name || UNNAMED_TOOL_CALL,
171
174
  input: this.safeParseJson(tc.arguments),
172
175
  },
173
176
  }
@@ -242,14 +245,15 @@ export class OpenAICompatProvider implements ProviderInstance {
242
245
 
243
246
  if (choice.finish_reason === 'tool_calls') {
244
247
  // Emit fully accumulated tool calls
245
- for (const [, tc] of pendingToolCalls) {
246
- if (!tc.name) continue // drop malformed tool call (missing name)
248
+ for (const [idx, tc] of pendingToolCalls) {
249
+ // Same treatment as the `[DONE]` path above: a nameless call gets
250
+ // the synthetic name instead of being dropped on the floor.
247
251
  yield {
248
252
  type: 'tool_use',
249
253
  toolUse: {
250
254
  type: 'tool_use',
251
- id: tc.id || `call_${Date.now()}`,
252
- name: tc.name,
255
+ id: tc.id || `call_${Date.now()}_${idx}`,
256
+ name: tc.name || UNNAMED_TOOL_CALL,
253
257
  input: this.safeParseJson(tc.arguments),
254
258
  },
255
259
  }
@@ -266,7 +270,12 @@ export class OpenAICompatProvider implements ProviderInstance {
266
270
  // their JSON is incomplete. Drop them rather than dispatching a broken
267
271
  // call, and clear the map so the `[DONE]` handler can't emit them either.
268
272
  pendingToolCalls.clear()
269
- yield { type: 'stop', reasoning_content: reasoningContent, truncated: true }
273
+ yield {
274
+ type: 'stop',
275
+ reasoning_content: reasoningContent,
276
+ truncated: true,
277
+ truncationCause: 'max_tokens',
278
+ }
270
279
  }
271
280
  } catch {
272
281
  // skip unparseable chunks
@@ -335,16 +344,9 @@ export class OpenAICompatProvider implements ProviderInstance {
335
344
 
336
345
  async healthCheck(): Promise<boolean> {
337
346
  try {
338
- const rawBase = (this.config as any).baseUrl || (this.config as any).baseURL
339
- const baseUrl =
340
- this.resolveEnvTemplate(
341
- rawBase?.replace(/\/+$/, '') || '',
342
- 'OpenAI-compatible provider: baseUrl',
343
- ) || 'https://api.openai.com/v1'
344
- const apiKey = this.resolveApiKey(this.config.apiKey)
345
- // 5s timeout so a down endpoint doesn't hang health checks (v2.1.229 alignment)
347
+ const { url, apiKey } = this.modelsEndpoint()
346
348
  const res = await fetchWithRetry(
347
- `${baseUrl}/models`,
349
+ url,
348
350
  { headers: { Authorization: `Bearer ${apiKey}` } },
349
351
  { timeout: 5000, maxRetries: 0 },
350
352
  )
@@ -354,6 +356,48 @@ export class OpenAICompatProvider implements ProviderInstance {
354
356
  }
355
357
  }
356
358
 
359
+ /**
360
+ * Detailed reachability for `/doctor`. Unlike `healthCheck`, any HTTP answer
361
+ * counts as reachable: a 401 from a live endpoint means "the endpoint is
362
+ * here and refused this key", which is a different problem from "nothing
363
+ * answered".
364
+ */
365
+ async probeConnectivity(): Promise<ConnectivityProbe> {
366
+ const { url, apiKey } = this.modelsEndpoint()
367
+ if (!apiKey) return { tested: false, ok: false, detail: 'no API key configured' }
368
+ try {
369
+ // 5s timeout so a down endpoint doesn't hang the doctor screen.
370
+ const res = await fetchWithRetry(
371
+ url,
372
+ { headers: { Authorization: `Bearer ${apiKey}` } },
373
+ { timeout: 5000, maxRetries: 0 },
374
+ )
375
+ try {
376
+ await res.body?.cancel()
377
+ } catch {
378
+ /* body already gone */
379
+ }
380
+ return { tested: true, ok: true, detail: `HTTP ${res.status} from ${url}` }
381
+ } catch (err) {
382
+ return {
383
+ tested: true,
384
+ ok: false,
385
+ detail: `${err instanceof Error ? err.message : String(err)} (${url})`,
386
+ }
387
+ }
388
+ }
389
+
390
+ /** `/models` on the configured base — the one endpoint both checks share. */
391
+ private modelsEndpoint(): { url: string; apiKey: string } {
392
+ const rawBase = (this.config as any).baseUrl || (this.config as any).baseURL
393
+ const baseUrl =
394
+ this.resolveEnvTemplate(
395
+ rawBase?.replace(/\/+$/, '') || '',
396
+ 'OpenAI-compatible provider: baseUrl',
397
+ ) || 'https://api.openai.com/v1'
398
+ return { url: `${baseUrl}/models`, apiKey: this.resolveApiKey(this.config.apiKey) }
399
+ }
400
+
357
401
  private convertMessages(messages: Message[], systemPrompt?: string): Record<string, unknown>[] {
358
402
  const result: Record<string, unknown>[] = []
359
403
 
@@ -43,11 +43,27 @@ export function resolveClassifierModel(
43
43
  return choice
44
44
  }
45
45
 
46
+ /**
47
+ * Detail behind a reachability check, for `/doctor` (331-003).
48
+ *
49
+ * `healthCheck` answers a boolean the status line consumes; it cannot say *what*
50
+ * happened. This shape can: `tested: false` means the check was skipped and
51
+ * `detail` is the reason (no key, no endpoint), never a silent "unreachable".
52
+ */
53
+ export interface ConnectivityProbe {
54
+ tested: boolean
55
+ /** Reachability, not authentication: any HTTP response means the endpoint answered. */
56
+ ok: boolean
57
+ detail: string
58
+ }
59
+
46
60
  export interface ProviderInstance {
47
61
  config: ProviderConfig
48
62
  chat(req: ChatRequest): AsyncGenerator<StreamChunk>
49
63
  listModels(): Promise<ModelInfo[]>
50
64
  healthCheck(): Promise<boolean>
65
+ /** Optional detailed probe; `healthCheck` remains the only required contract. */
66
+ probeConnectivity?(): Promise<ConnectivityProbe>
51
67
  }
52
68
 
53
69
  export interface ChatRequest {
@@ -164,6 +180,31 @@ export class ProviderRegistry implements Llm {
164
180
  }
165
181
  }
166
182
 
183
+ /**
184
+ * Detailed reachability for `/doctor`. Falls back to the boolean health check
185
+ * when a provider has no probe, and says so — "reachable" with no detail is
186
+ * still information; "unreachable" invented from a missing method is not.
187
+ */
188
+ async probeConnectivity(id: string): Promise<ConnectivityProbe | undefined> {
189
+ const provider = this.providers.get(id)
190
+ if (!provider) return undefined
191
+ if (provider.probeConnectivity) {
192
+ try {
193
+ return await provider.probeConnectivity()
194
+ } catch (err) {
195
+ return {
196
+ tested: true,
197
+ ok: false,
198
+ detail: err instanceof Error ? err.message : String(err),
199
+ }
200
+ }
201
+ }
202
+ const ok = await this.healthStatus(id)
203
+ return ok === undefined
204
+ ? undefined
205
+ : { tested: false, ok, detail: 'this provider has no detailed probe' }
206
+ }
207
+
167
208
  /**
168
209
  * Health of all registered providers, checked concurrently.
169
210
  * Returns a Map of provider id → reachable boolean.
@@ -1,6 +1,17 @@
1
1
  import type { ProviderConfig, ModelInfo } from './types'
2
2
  import miphamModelsSnapshot from './mipham-models.json' with { type: 'json' }
3
3
 
4
+ /**
5
+ * Synthetic tool name for a provider response that carried a tool call with no
6
+ * name (a custom endpoint, or a malformed stream).
7
+ *
8
+ * Dropping such a call silently left the turn looking like a short answer: the
9
+ * model wrote a call, nothing dispatched, and the user got no explanation. Give
10
+ * it a name so the ordinary "Unknown tool" path hands the model an error result
11
+ * it can correct on the next round — the turn continues instead of vanishing.
12
+ */
13
+ export const UNNAMED_TOOL_CALL = '(tool call without a name)'
14
+
4
15
  // Build MiphamAI provider from synced model definitions.
5
16
  // Source of truth: Engine GET /v1/mipham-models → packages/shared/src/mipham-models.json
6
17
  // Run `bun run scripts/sync-mipham-models.ts` to update from Engine.
@@ -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.43' as const
12
+ export const PACKAGE_VERSION = '0.85.45' 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 = 139 as const
78
+ export const SLASH_COMMAND_COUNT = 141 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 = 5122 as const
93
+ export const TEST_COUNT = 5195 as const
@@ -311,6 +311,23 @@ export function safeSlice(text: string, max: number): string {
311
311
  return text.slice(0, end)
312
312
  }
313
313
 
314
+ /**
315
+ * `safeSlice` for **display only** — appends `…` when it actually cut something.
316
+ *
317
+ * A bare `safeSlice` at a render site leaves a long tool result looking like the
318
+ * whole output: the reader has no way to tell "the tool said this" from "the
319
+ * tool said more and we stopped". Never use this where the string is stored or
320
+ * sent (session JSONL, tool arguments, prompts) — the ellipsis would become part
321
+ * of the data. `safeSlice` remains the right call there.
322
+ */
323
+ export function safeSliceWithEllipsis(text: string, max: number): string {
324
+ const clipped = safeSlice(text, max)
325
+ // `max <= 0` means "show nothing", not "show an ellipsis" — and an empty input
326
+ // cannot have been cut.
327
+ if (max <= 0 || clipped === text) return clipped
328
+ return `${clipped}…`
329
+ }
330
+
314
331
  /**
315
332
  * Replace lone UTF-16 surrogates with U+FFFD, leaving valid pairs untouched.
316
333
  *
@@ -179,6 +179,15 @@ export interface StreamChunk {
179
179
  * either way, and tool calls cut off mid-arguments are dropped silently.
180
180
  */
181
181
  truncated?: boolean
182
+ /**
183
+ * Why the turn was cut, when the provider can tell.
184
+ *
185
+ * `'max_tokens'` means the model hit its output ceiling — there is more to say
186
+ * and asking it to continue is meaningful. `'connection'` (or absent) means the
187
+ * stream died; continuing would re-ask the model to write the same fragment
188
+ * again, so the engine must not auto-continue on it.
189
+ */
190
+ truncationCause?: 'max_tokens' | 'connection'
182
191
  /**
183
192
  * Set on the `warning` chunk a retried turn emits just before it re-streams
184
193
  * (`chatWithFallback`). Everything the failed attempt already yielded is on
@@ -332,6 +332,36 @@ export class SkillsLoader implements Skills {
332
332
  this.loadExternal([userSkillsPath])
333
333
  }
334
334
 
335
+ /**
336
+ * Load skills from `<base>/.mipham/skills/` — the project scope.
337
+ *
338
+ * This path is what the product tells users to use: `/project` ("Create a
339
+ * .SKILL.md file in .mipham/skills/"), the Skill tool's not-found message, and
340
+ * `loop-scaffold` (which creates `.mipham/skills/<domain>/`). Until now nothing
341
+ * scanned it, so a skill written exactly where the instructions said was never
342
+ * loaded and `/reload-skills` reported an unchanged count.
343
+ *
344
+ * One level of subdirectories is scanned on purpose: the scaffold's layout is
345
+ * `<domain>/<name>.SKILL.md`, and the Claude-plugin shape is
346
+ * `<name>/SKILL.md`. Symlinked directories are skipped — following them can
347
+ * loop, and the flat `loadDirectory` deliberately does not recurse for the
348
+ * same reason.
349
+ */
350
+ loadProjectSkills(basePath: string = process.cwd()): void {
351
+ const projectDir = join(basePath, '.mipham', 'skills')
352
+ if (!existsSync(projectDir)) return
353
+ this.loadDirectory(projectDir, 'standard')
354
+ try {
355
+ for (const entry of readdirSync(projectDir, { withFileTypes: true })) {
356
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
357
+ this.loadDirectory(join(projectDir, entry.name), 'standard')
358
+ }
359
+ }
360
+ } catch {
361
+ // Unreadable directory: the flat scan above already ran.
362
+ }
363
+ }
364
+
335
365
  private nameFromPath(path: string): string {
336
366
  const parts = path.split('/').filter(Boolean)
337
367
  const base = parts.pop() ?? ''
@@ -1,4 +1,5 @@
1
1
  import { Glob } from 'bun'
2
+ import { spawnSync } from 'node:child_process'
2
3
  import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
3
4
  import { resolveSafe } from '../../security/path'
4
5
  import type { Service } from '../../vajra'
@@ -10,10 +11,45 @@ import { maskGlobOutput } from '../../core/credential-masker'
10
11
  * 与 Grep 的 `truncateGrepOutput` 同一约定)。 */
11
12
  const GLOB_MAX_RESULTS = 500
12
13
 
14
+ /** 每批向 `git check-ignore` 询问的路径数(一次进程,摊薄启动成本)。 */
15
+ const GLOB_IGNORE_BATCH = 500
16
+
17
+ /**
18
+ * Drop the paths git would ignore.
19
+ *
20
+ * `Bun.Glob` knows nothing about `.gitignore`, so `Glob **\/*` in a repository
21
+ * returned `node_modules/…` and build output alongside real sources. This asks
22
+ * git itself (`check-ignore --stdin -z`, paths echoed verbatim), so the answer
23
+ * is the repository's own rule set — nested `.gitignore` files, negations,
24
+ * core.excludesFile and all.
25
+ *
26
+ * Fail-open by design: outside a work tree, when git is missing, or when the
27
+ * call errors (status 1 = "nothing ignored", 128 = fatal), every path is kept.
28
+ * Filtering is a convenience; silently returning *nothing* because git could
29
+ * not answer would be indistinguishable from "no matches".
30
+ */
31
+ export function filterGitIgnored(paths: string[], cwd: string): string[] {
32
+ if (paths.length === 0) return paths
33
+ const ignored = new Set<string>()
34
+ for (let i = 0; i < paths.length; i += GLOB_IGNORE_BATCH) {
35
+ const batch = paths.slice(i, i + GLOB_IGNORE_BATCH)
36
+ const res = spawnSync('git', ['check-ignore', '--stdin', '-z'], {
37
+ cwd,
38
+ input: batch.join('\0') + '\0',
39
+ maxBuffer: 16 * 1024 * 1024,
40
+ })
41
+ // status 0 = at least one ignored; 1 = none; null/128 = not a repo or no git.
42
+ if (res.status !== 0 || !res.stdout) continue
43
+ for (const p of res.stdout.toString().split('\0')) if (p) ignored.add(p)
44
+ }
45
+ return paths.filter((p) => !ignored.has(p))
46
+ }
47
+
13
48
  export function createGlobTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
14
49
  return {
15
50
  name: 'Glob',
16
- description: 'Find files matching a glob pattern.',
51
+ description:
52
+ 'Find files matching a glob pattern. Inside a git repository, files ignored by .gitignore are excluded.',
17
53
  category: 'file',
18
54
  permission: 'self',
19
55
  parameters: {
@@ -30,14 +66,30 @@ export function createGlobTool(credentialConfig?: CredentialMaskingConfig): Tool
30
66
  const glob = new Glob(pattern)
31
67
  const results: string[] = []
32
68
  let truncated = false
69
+ let pending: string[] = []
70
+ // 过滤放在**取满 500 之前**:先收 500 个再过滤,忽略项多的树会只剩几十条
71
+ // 却仍报「截断到 500」;反过来先过滤再数,截断标记描述的才是真实结果集。
72
+ const keep = (batch: string[]) => {
73
+ if (batch.length === 0) return
74
+ for (const p of filterGitIgnored(batch, basePath)) results.push(p)
75
+ }
33
76
  for await (const file of glob.scan({ cwd: basePath, absolute: true })) {
34
- if (results.length >= GLOB_MAX_RESULTS) {
35
- // 只有真的还有第 501 个匹配时才叫截断 —— 恰好 500 个匹配是完整结果。
36
- truncated = true
37
- break
77
+ pending.push(file)
78
+ if (pending.length >= GLOB_IGNORE_BATCH) {
79
+ keep(pending)
80
+ pending = []
81
+ if (results.length > GLOB_MAX_RESULTS) {
82
+ // 只有真的还有第 501 个**未被忽略**的匹配时才叫截断 —— 恰好 500 个是完整结果。
83
+ truncated = true
84
+ break
85
+ }
38
86
  }
39
- results.push(file)
40
87
  }
88
+ if (!truncated) {
89
+ keep(pending)
90
+ truncated = results.length > GLOB_MAX_RESULTS
91
+ }
92
+ results.length = Math.min(results.length, GLOB_MAX_RESULTS)
41
93
  // 先掩码正文、再拼注解:`maskGlobOutput` 是**逐行当路径**去比对的
42
94
  // (每行都过 `matchCredentialFile`),注解不是路径,不该喂给它。
43
95
  const content = maskGlobOutput(results.join('\n') || '(no matches)', credentialConfig)
@@ -34,7 +34,15 @@ export async function runSearch(
34
34
  // Same reasoning as `internalGitEnv`: this search is ours, not the user's
35
35
  // shell — ripgrep never needs an API key, and handing one down only makes it
36
36
  // reachable from a config file or a `--pre` child of the search.
37
- const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe', env: internalProcessEnv() })
37
+ //
38
+ // `RIPGREP_CONFIG_PATH` is the user's *global* ripgrep configuration: it can
39
+ // inject `--glob` / `--type` / `--ignore-file` flags that silently change or
40
+ // empty every search this tool performs. The args here are fixed, so the
41
+ // config file is the only other input — a search must answer for the
42
+ // repository being searched, not for a file the user forgot about.
43
+ const env = internalProcessEnv()
44
+ delete env.RIPGREP_CONFIG_PATH
45
+ const proc = Bun.spawn(cmd, { cwd, stdout: 'pipe', stderr: 'pipe', env })
38
46
  let timedOut = false
39
47
  const timers: ReturnType<typeof setTimeout>[] = []
40
48
  timers.push(
package/src/ui/app.tsx CHANGED
@@ -108,6 +108,40 @@ export interface ChatMessage {
108
108
  toolMeta?: ToolMeta
109
109
  }
110
110
 
111
+ /**
112
+ * Compose the transcript line for a background-task notification.
113
+ *
114
+ * `chat.tsx` renders `toolMeta.output` *before* `msg.content`, so a completed
115
+ * task that carried the raw output preview made its own composed line
116
+ * (`◼ <desc> · finished`) unreachable — the user saw a truncated raw-output row
117
+ * and no completion statement. Running/failed tasks keep the preview (that is
118
+ * the live signal); a completed one reports cleanly.
119
+ */
120
+ export function taskNotificationMessage(tn: {
121
+ status: 'started' | 'completed' | 'failed'
122
+ description: string
123
+ content?: string
124
+ error?: string
125
+ }): ChatMessage {
126
+ const isDone = tn.status === 'completed'
127
+ const symbol = isDone ? '◼' : '✳'
128
+ const preview = tn.content
129
+ ? tn.content.slice(0, 120) + (tn.content.length > 120 ? '...' : '')
130
+ : tn.error
131
+ ? `Error: ${tn.error.slice(0, 120)}`
132
+ : '(no output)'
133
+ return {
134
+ role: 'system',
135
+ content: `${symbol} ${tn.description}${isDone ? ` · finished` : ''}`,
136
+ toolMeta: {
137
+ name: isDone ? '' : 'task',
138
+ input: tn.description || '',
139
+ ...(isDone ? {} : { output: preview }),
140
+ collapsed: false,
141
+ },
142
+ }
143
+ }
144
+
111
145
  interface AgentProgress {
112
146
  name: string
113
147
  description: string
@@ -350,6 +384,9 @@ export function App({
350
384
  // 卸载(pickerOpen 三元 / apiKeyPrompt 早退 / Ctrl+G),组件内 state 随之清零,
351
385
  // 于是「开一次模型选择器,历史就没了」(ROADMAP D7)。
352
386
  const [inputHistory, setInputHistory] = useState<string[]>([])
387
+ // The draft lives here for the same reason history does (see the note above):
388
+ // InputBar is unmounted by the picker / API-key prompt / agent view.
389
+ const [inputDraft, setInputDraft] = useState('')
353
390
  const [updateStatus, setUpdateStatus] = useState<UpdateStatus | null>(null)
354
391
  // Current git branch — read once at mount (not a git repo → null).
355
392
  // `stdio` 显式给:默认下 git 的 stderr 是继承的,「不是仓库」这个正常路径会把
@@ -973,27 +1010,8 @@ export function App({
973
1010
  }
974
1011
 
975
1012
  if (chunk.type === 'task_notification' && chunk.taskNotification) {
976
- const tn = chunk.taskNotification
977
- const isDone = tn.status === 'completed'
978
- const symbol = isDone ? '◼' : '✳'
979
- const preview = tn.content
980
- ? tn.content.slice(0, 120) + (tn.content.length > 120 ? '...' : '')
981
- : tn.error
982
- ? `Error: ${tn.error.slice(0, 120)}`
983
- : '(no output)'
984
- setMessages((prev) => [
985
- ...prev,
986
- {
987
- role: 'system',
988
- content: `${symbol} ${tn.description}${isDone ? ` · finished` : ''}`,
989
- toolMeta: {
990
- name: isDone ? '' : 'task',
991
- input: tn.description || '',
992
- output: preview,
993
- collapsed: isDone,
994
- },
995
- },
996
- ])
1013
+ const notification = chunk.taskNotification
1014
+ setMessages((prev) => [...prev, taskNotificationMessage(notification)])
997
1015
  // Sync agent footer — mark completed background agents
998
1016
  syncBgAgents()
999
1017
  }
@@ -1599,6 +1617,8 @@ export function App({
1599
1617
  isLoading={isLoading}
1600
1618
  history={inputHistory}
1601
1619
  onHistoryAppend={(v) => setInputHistory((prev) => [...prev, v])}
1620
+ draft={inputDraft}
1621
+ onDraftChange={setInputDraft}
1602
1622
  llm={autocompleteLlm}
1603
1623
  recentMessages={recentMessages}
1604
1624
  autocompleteEnabled={