@miphamai/cli 0.85.43 → 0.85.44
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.
- package/README.md +3 -3
- package/package.json +1 -1
- package/src/agent/agent-context.ts +49 -0
- package/src/agent/agent-registry.ts +6 -0
- package/src/agent/sub-agent.ts +5 -0
- package/src/core/engine.ts +117 -7
- package/src/core/hooks-executor.ts +11 -1
- package/src/core/permission-rules.ts +168 -29
- package/src/core/permission.ts +20 -0
- package/src/core/session-log.ts +39 -1
- package/src/core/session-store.ts +33 -1
- package/src/core/tool-gate.ts +7 -1
- package/src/daemon/engine-capabilities.ts +4 -0
- package/src/i18n-core/locales/en-US.json +6 -1
- package/src/i18n-core/locales/zh-CN.json +6 -1
- package/src/index.tsx +6 -1
- package/src/mcp/registry.ts +11 -3
- package/src/mcp/types.ts +6 -0
- package/src/providers/anthropic.ts +14 -1
- package/src/providers/bootstrap.ts +13 -0
- package/src/providers/openai-compat.ts +6 -1
- package/src/shared/package-info.ts +3 -3
- package/src/shared/types.ts +9 -0
- package/src/skills/loader.ts +30 -0
- package/src/tools/file/glob.ts +58 -6
- package/src/tools/file/grep.ts +9 -1
- package/src/ui/app.tsx +41 -21
- package/src/ui/command-picker.tsx +2 -5
- package/src/ui/commands.ts +79 -4
- package/src/ui/input.tsx +21 -8
- package/src/ui/picker.tsx +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdirSync, readdirSync, unlinkSync, existsSync, statSync } from 'node:fs'
|
|
1
|
+
import { mkdirSync, readdirSync, unlinkSync, existsSync, statSync, renameSync } from 'node:fs'
|
|
2
2
|
import { join } from 'node:path'
|
|
3
3
|
import { createHash } from 'node:crypto'
|
|
4
4
|
import type { Message } from '../shared/types'
|
|
@@ -333,6 +333,38 @@ export class SessionStore {
|
|
|
333
333
|
atomicWriteFileSync(INDEX_FILE, JSON.stringify(index, null, 2), { mode: 0o600 })
|
|
334
334
|
}
|
|
335
335
|
|
|
336
|
+
/**
|
|
337
|
+
* Move a session's **index entry** (and its saved summary) to a new name.
|
|
338
|
+
*
|
|
339
|
+
* `/rename` renames the transcript file via `SessionLog.rename`; the index is a
|
|
340
|
+
* separate store, and leaving the old row behind makes `/resume last` point at
|
|
341
|
+
* a file that no longer exists. Returns false when there is no old entry or the
|
|
342
|
+
* new name is already taken — in both cases *nothing* is changed, so a caller
|
|
343
|
+
* that reports failure is telling the truth.
|
|
344
|
+
*/
|
|
345
|
+
static renameEntry(oldName: string, newName: string): boolean {
|
|
346
|
+
ensureDir()
|
|
347
|
+
const index = SessionStore.loadIndexRaw()
|
|
348
|
+
const entry = index.find((e) => e.name === oldName)
|
|
349
|
+
if (!entry) return false
|
|
350
|
+
if (index.some((e) => e.name === newName)) return false
|
|
351
|
+
entry.name = newName
|
|
352
|
+
atomicWriteFileSync(INDEX_FILE, JSON.stringify(index, null, 2), { mode: 0o600 })
|
|
353
|
+
|
|
354
|
+
// The summary file is named after the session, so it has to follow too —
|
|
355
|
+
// otherwise the renamed session silently loses the recap the user generated.
|
|
356
|
+
const oldSummary = join(SUMMARIES_DIR, `${sanitizeSessionName(oldName)}.md`)
|
|
357
|
+
const newSummary = join(SUMMARIES_DIR, `${sanitizeSessionName(newName)}.md`)
|
|
358
|
+
if (oldSummary !== newSummary && existsSync(oldSummary) && !existsSync(newSummary)) {
|
|
359
|
+
try {
|
|
360
|
+
renameSync(oldSummary, newSummary)
|
|
361
|
+
} catch {
|
|
362
|
+
// Summary is a cache; a failed move must not fail the rename.
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return true
|
|
366
|
+
}
|
|
367
|
+
|
|
336
368
|
/**
|
|
337
369
|
* Persist an LLM-generated summary for a session.
|
|
338
370
|
* Writes a markdown file to .summaries/ and updates the index entry.
|
package/src/core/tool-gate.ts
CHANGED
|
@@ -95,10 +95,16 @@ export async function runPreToolGate(
|
|
|
95
95
|
// key name. `defer` (and an absent decision) means "no override", which is
|
|
96
96
|
// exactly what happens when we do nothing.
|
|
97
97
|
if (preResult.permissionDecision === 'ask' || preResult.permissionDecision === 'deny') {
|
|
98
|
+
// A hook that also supplied `updatedInput` proposed a rewrite; there is no
|
|
99
|
+
// approval path to carry it through, so we refuse — but say the rewrite
|
|
100
|
+
// existed. Silently discarding it is the failure mode this note removes.
|
|
101
|
+
const rewriteNote = preResult.modifiedInput
|
|
102
|
+
? ` ${t('errors.tool_hook_ask_rewrite', { name })}`
|
|
103
|
+
: ''
|
|
98
104
|
return {
|
|
99
105
|
ok: false,
|
|
100
106
|
content: '',
|
|
101
|
-
error: preResult.reason || t('errors.tool_hook_ask', { name }),
|
|
107
|
+
error: (preResult.reason || t('errors.tool_hook_ask', { name })) + rewriteNote,
|
|
102
108
|
notRun: true,
|
|
103
109
|
}
|
|
104
110
|
}
|
|
@@ -79,6 +79,10 @@ function skillsFor(cwd: string, paths?: string[]): SkillsLoader {
|
|
|
79
79
|
loader.loadBuiltinFromPackage()
|
|
80
80
|
if (!isSafeMode()) {
|
|
81
81
|
loader.loadUserSkills()
|
|
82
|
+
// Project scope follows the workspace (`<cwd>/.mipham/skills`), same as the
|
|
83
|
+
// CLI — the two entry points must load the same set or a skill works in one
|
|
84
|
+
// and silently not in the other.
|
|
85
|
+
loader.loadProjectSkills(cwd)
|
|
82
86
|
if (paths && paths.length > 0) loader.loadExternal(paths)
|
|
83
87
|
}
|
|
84
88
|
skillsCache.set(cwd, loader)
|
|
@@ -92,7 +92,8 @@
|
|
|
92
92
|
"rename": {
|
|
93
93
|
"usage": "Usage: /rename <session-name>\nExample: /rename Bug Fix Session",
|
|
94
94
|
"confirmed": "✓ Session renamed to \"{name}\"",
|
|
95
|
-
"unsaved": "⚠ Session title set to \"{name}\" for this run, but it could not be saved to the session registry — the name may not last."
|
|
95
|
+
"unsaved": "⚠ Session title set to \"{name}\" for this run, but it could not be saved to the session registry — the name may not last.",
|
|
96
|
+
"log_conflict": "⚠ Title set to \"{name}\", but a saved session already uses that name — the transcript stays under \"{old}\" (/resume {old})."
|
|
96
97
|
},
|
|
97
98
|
"plan": {
|
|
98
99
|
"entered": "Entered plan mode.",
|
|
@@ -960,6 +961,7 @@
|
|
|
960
961
|
"tool_denied_classifier_unavailable": "Tool \"{name}\" was held back because the auto-mode classifier could not be reached or its answer could not be read ({reason}). This is NOT a policy decision — the call was never judged, and retrying is appropriate. If this keeps happening, switch modes with Shift+Tab.",
|
|
961
962
|
"tool_blocked": "Tool \"{name}\" blocked by hook",
|
|
962
963
|
"tool_hook_ask": "Tool \"{name}\" was marked by a hook as needing approval, and this environment has no interactive prompt — so it is refused. A repository-supplied hook may narrow the gate but not approve a call; if this hook is your own, make it block outright or relax it.",
|
|
964
|
+
"tool_hook_ask_rewrite": "The hook also proposed a rewritten input for \"{name}\"; it was discarded, because a refusal has no approval path to carry it through.",
|
|
963
965
|
"user_input_blocked": "User input blocked by hook.",
|
|
964
966
|
"dlp_blocked": "Request blocked by DLP policy.",
|
|
965
967
|
"model_error": "Error: {error}",
|
|
@@ -985,6 +987,9 @@
|
|
|
985
987
|
"max_tool_turns_warning": "You've reached the maximum of {max} tool-calling rounds. {pending} tool call(s) were not executed. Please summarize what you found so far and any next steps the user should take.",
|
|
986
988
|
"turn_timeout": "Task produced no substantial output for {minutes} minutes and was stopped. Break the task into smaller steps or clarify the next step, then retry.",
|
|
987
989
|
"turn_truncated": "The response was cut off mid-turn, not finished — the provider stopped at its output limit or the connection closed. If you reach the provider through a proxy or a corporate gateway, check that first; otherwise check your VPN and firewall rules.",
|
|
990
|
+
"turn_continuing": "The reply hit the model's output limit — continuing automatically.",
|
|
991
|
+
"turn_truncated_limit": "The reply hit the model's output limit and was cut off; this turn will not be continued further.",
|
|
992
|
+
"continuation_prompt": "Your previous reply was cut off at the output limit. Continue exactly where it stopped — do not repeat anything already written.",
|
|
988
993
|
"turn_refused": "The model declined this request and did not answer. This is not a failure — resending it to the same model will usually be declined again.",
|
|
989
994
|
"turn_refused_reason": "The model declined this request: {reason}",
|
|
990
995
|
"stop_hook_budget_spent": "The Stop hook asked for more work (\"{reason}\"), but this turn has used all {max} of its tool-calling rounds — stopping here. Send another message to continue.",
|
|
@@ -92,7 +92,8 @@
|
|
|
92
92
|
"rename": {
|
|
93
93
|
"usage": "用法: /rename <session-name>\n示例: /rename 修复 Bug 的会话",
|
|
94
94
|
"confirmed": "✓ 会话重命名为 \"{name}\"",
|
|
95
|
-
"unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。"
|
|
95
|
+
"unsaved": "⚠ 本次会话已改名为 \"{name}\",但没能写入会话登记表 —— 这个名字可能不会保留。",
|
|
96
|
+
"log_conflict": "⚠ 标题已改为 \"{name}\",但已存在同名会话存档 —— 对话记录仍保存在 \"{old}\" 下(可用 /resume {old} 找回)。"
|
|
96
97
|
},
|
|
97
98
|
"plan": {
|
|
98
99
|
"entered": "已进入计划模式。",
|
|
@@ -960,6 +961,7 @@
|
|
|
960
961
|
"tool_denied_classifier_unavailable": "工具 \"{name}\" 被暂缓:auto 模式的分类器不可达,或其回复无法解析({reason})。这**不是**策略裁决 —— 该调用从未被裁决,重试是恰当的。若持续发生,按 Shift+Tab 切换模式。",
|
|
961
962
|
"tool_blocked": "工具 \"{name}\" 被钩子拦截",
|
|
962
963
|
"tool_hook_ask": "工具 \"{name}\" 被钩子标为需要批准,而本环境没有交互批准 —— 已按拒绝处理。仓库带来的钩子只能收紧闸门、不能放行;若这是你自己的钩子,请让它直接拦截,或放宽它。",
|
|
964
|
+
"tool_hook_ask_rewrite": "该钩子同时为 \"{name}\" 提出了改写后的输入;因为本次是拒绝、没有批准通道可以承接它,改写已丢弃。",
|
|
963
965
|
"user_input_blocked": "用户输入被钩子拦截。",
|
|
964
966
|
"dlp_blocked": "请求被 DLP 策略阻止。",
|
|
965
967
|
"model_error": "错误:{error}",
|
|
@@ -985,6 +987,9 @@
|
|
|
985
987
|
"max_tool_turns_warning": "已达到最大 {max} 轮工具调用。{pending} 个工具调用未执行。请总结当前发现及后续步骤。",
|
|
986
988
|
"turn_timeout": "任务已超过 {minutes} 分钟无实质产出,已自动停止。建议拆分任务或明确下一步后重新发起。",
|
|
987
989
|
"turn_truncated": "回复写到一半就断了,不是正常写完 —— 提供商到了输出上限,或连接被关闭。如果是经代理或公司网关访问提供商,先查那一层;否则检查 VPN 与防火墙规则。",
|
|
990
|
+
"turn_continuing": "回复到达模型输出上限 —— 正在自动续写。",
|
|
991
|
+
"turn_truncated_limit": "回复到达模型输出上限,已被截断;本轮不再继续续写。",
|
|
992
|
+
"continuation_prompt": "你上一条回复在输出上限处被截断了。请从断掉的地方原样接着写 —— 不要重复已经写过的内容。",
|
|
988
993
|
"turn_refused": "模型拒绝了这次请求,没有作答。这不是故障:重发给同一个模型通常还是会被拒。",
|
|
989
994
|
"turn_refused_reason": "模型拒绝了这次请求:{reason}",
|
|
990
995
|
"stop_hook_budget_spent": "Stop 钩子要求继续({reason}),但本轮 {max} 轮工具调用已用尽 —— 就此停下。再发一条消息即可继续。",
|
package/src/index.tsx
CHANGED
|
@@ -554,6 +554,8 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
554
554
|
skillsLoader.loadBuiltinFromPackage()
|
|
555
555
|
if (!safeMode) {
|
|
556
556
|
skillsLoader.loadUserSkills()
|
|
557
|
+
// The documented project scope (`.mipham/skills/`) — see `loadProjectSkills`.
|
|
558
|
+
skillsLoader.loadProjectSkills(process.cwd())
|
|
557
559
|
if (config.skills?.paths) {
|
|
558
560
|
skillsLoader.loadExternal(config.skills.paths)
|
|
559
561
|
}
|
|
@@ -987,7 +989,10 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
987
989
|
if (context.getMessageCount() === 0) return
|
|
988
990
|
const log = context.getLog()
|
|
989
991
|
if (log) {
|
|
990
|
-
|
|
992
|
+
// `/rename` moves the transcript file; the index entry must follow the
|
|
993
|
+
// log's *current* name, not the one this process started with — otherwise
|
|
994
|
+
// the row points at a file that was just renamed away.
|
|
995
|
+
SessionStore.saveLog(log.getName(), log, {
|
|
991
996
|
provider: defaultProvider,
|
|
992
997
|
model: defaultModel,
|
|
993
998
|
cwd: process.cwd(),
|
package/src/mcp/registry.ts
CHANGED
|
@@ -222,7 +222,7 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
|
|
|
222
222
|
ctx.signal,
|
|
223
223
|
)
|
|
224
224
|
|
|
225
|
-
const text = result.content
|
|
225
|
+
const text = (result.content ?? [])
|
|
226
226
|
.map((c) => {
|
|
227
227
|
if (c.type === 'text' && c.text) return c.text
|
|
228
228
|
if (c.type === 'image') return `[Image: ${c.mimeType || 'unknown'}]`
|
|
@@ -230,10 +230,18 @@ export function convertMcpTool(serverName: string, mcpTool: McpToolDefinition):
|
|
|
230
230
|
})
|
|
231
231
|
.join('\n')
|
|
232
232
|
|
|
233
|
+
// A server may answer only in `structuredContent` (MCP 2025-06). Dropping
|
|
234
|
+
// it turned a real payload into "(empty result)" — indistinguishable from
|
|
235
|
+
// a tool that genuinely returned nothing.
|
|
236
|
+
const structured =
|
|
237
|
+
text === '' && result.structuredContent !== undefined
|
|
238
|
+
? JSON.stringify(result.structuredContent, null, 2)
|
|
239
|
+
: ''
|
|
240
|
+
|
|
233
241
|
return {
|
|
234
242
|
success: !result.isError,
|
|
235
|
-
content: text || '(empty result)',
|
|
236
|
-
error: result.isError ? text : undefined,
|
|
243
|
+
content: text || structured || '(empty result)',
|
|
244
|
+
error: result.isError ? text || structured : undefined,
|
|
237
245
|
}
|
|
238
246
|
},
|
|
239
247
|
}
|
package/src/mcp/types.ts
CHANGED
|
@@ -83,6 +83,12 @@ export interface ToolCallContent {
|
|
|
83
83
|
|
|
84
84
|
export interface ToolCallResult {
|
|
85
85
|
content: ToolCallContent[]
|
|
86
|
+
/**
|
|
87
|
+
* MCP 2025-06 `structuredContent`: a machine-readable payload some servers
|
|
88
|
+
* return *instead of* (or alongside) text blocks. Ignoring it made such a
|
|
89
|
+
* server look like it answered nothing at all.
|
|
90
|
+
*/
|
|
91
|
+
structuredContent?: unknown
|
|
86
92
|
isError?: boolean
|
|
87
93
|
}
|
|
88
94
|
|
|
@@ -121,6 +121,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
121
121
|
// off at the output ceiling rather than ended by the model.
|
|
122
122
|
let truncated = false
|
|
123
123
|
|
|
124
|
+
// Why it was cut. `'max_tokens'` is recoverable (ask the model to continue);
|
|
125
|
+
// a stream that ends without `message_stop` is not (re-asking re-writes the
|
|
126
|
+
// fragment). Same terminal stop either way — this is the only distinction the
|
|
127
|
+
// provider can supply, so it has to travel with the chunk.
|
|
128
|
+
let truncationCause: 'max_tokens' | 'connection' | undefined
|
|
129
|
+
|
|
124
130
|
// Set when the provider reports `stop_reason: 'refusal'`. A refusal is a
|
|
125
131
|
// **successful** response (HTTP 200) that declines to answer, and it may carry
|
|
126
132
|
// an empty content array — so without this the turn ends as a blank screen,
|
|
@@ -142,6 +148,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
142
148
|
const terminalStop = (): StreamChunk => ({
|
|
143
149
|
type: 'stop',
|
|
144
150
|
...(truncated ? { truncated: true } : {}),
|
|
151
|
+
...(truncationCause ? { truncationCause } : {}),
|
|
145
152
|
...(refusal ? { refusal } : {}),
|
|
146
153
|
})
|
|
147
154
|
|
|
@@ -376,6 +383,7 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
376
383
|
const stopReason = event.delta?.stop_reason
|
|
377
384
|
if (stopReason === 'max_tokens') {
|
|
378
385
|
truncated = true
|
|
386
|
+
truncationCause = 'max_tokens'
|
|
379
387
|
}
|
|
380
388
|
// A refusal is a successful response that declines to answer, and
|
|
381
389
|
// it can arrive with no content at all. Capture the provider's own
|
|
@@ -414,7 +422,12 @@ export class AnthropicProvider implements ProviderInstance {
|
|
|
414
422
|
// The stream ran out without `message_stop`. Whatever stopped it, the turn is
|
|
415
423
|
// incomplete — and this is the only place that knows, because a cleanly
|
|
416
424
|
// closed connection and a finished response are otherwise the same stream.
|
|
417
|
-
if (!sawTerminalEvent)
|
|
425
|
+
if (!sawTerminalEvent) {
|
|
426
|
+
truncated = true
|
|
427
|
+
// A `max_tokens` stop seen earlier is the real cause; only an otherwise
|
|
428
|
+
// ordinary stream that just dies is a connection cut.
|
|
429
|
+
truncationCause ??= 'connection'
|
|
430
|
+
}
|
|
418
431
|
|
|
419
432
|
yield terminalStop()
|
|
420
433
|
} finally {
|
|
@@ -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
|
}
|
|
@@ -266,7 +266,12 @@ export class OpenAICompatProvider implements ProviderInstance {
|
|
|
266
266
|
// their JSON is incomplete. Drop them rather than dispatching a broken
|
|
267
267
|
// call, and clear the map so the `[DONE]` handler can't emit them either.
|
|
268
268
|
pendingToolCalls.clear()
|
|
269
|
-
yield {
|
|
269
|
+
yield {
|
|
270
|
+
type: 'stop',
|
|
271
|
+
reasoning_content: reasoningContent,
|
|
272
|
+
truncated: true,
|
|
273
|
+
truncationCause: 'max_tokens',
|
|
274
|
+
}
|
|
270
275
|
}
|
|
271
276
|
} catch {
|
|
272
277
|
// skip unparseable chunks
|
|
@@ -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.
|
|
12
|
+
export const PACKAGE_VERSION = '0.85.44' 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 =
|
|
78
|
+
export const SLASH_COMMAND_COUNT = 140 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 =
|
|
93
|
+
export const TEST_COUNT = 5171 as const
|
package/src/shared/types.ts
CHANGED
|
@@ -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
|
package/src/skills/loader.ts
CHANGED
|
@@ -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() ?? ''
|
package/src/tools/file/glob.ts
CHANGED
|
@@ -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:
|
|
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
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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)
|
package/src/tools/file/grep.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
977
|
-
|
|
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={
|
|
@@ -2,7 +2,7 @@ import React, { useState, useMemo, useEffect } from 'react'
|
|
|
2
2
|
import { Box, Text, useInput } from 'ink'
|
|
3
3
|
import TextInput from 'ink-text-input'
|
|
4
4
|
import { useI18n } from '../i18n-context'
|
|
5
|
-
import { getCommandList } from './commands.js'
|
|
5
|
+
import { getCommandList, rankCommandMatches } from './commands.js'
|
|
6
6
|
import { commandToken, hasInlineArgs } from './command-token.js'
|
|
7
7
|
import { useKeyState } from './use-key-state'
|
|
8
8
|
|
|
@@ -68,10 +68,7 @@ export function CommandPicker({
|
|
|
68
68
|
// full line — so "/loop 60s echo hello" still matches "/loop").
|
|
69
69
|
const filtered = useMemo(() => {
|
|
70
70
|
const q = commandToken(filter)
|
|
71
|
-
|
|
72
|
-
return allCommands.filter(
|
|
73
|
-
(cmd) => cmd.name.toLowerCase().includes(q) || cmd.description.toLowerCase().includes(q),
|
|
74
|
-
)
|
|
71
|
+
return rankCommandMatches(allCommands, q)
|
|
75
72
|
}, [filter, allCommands])
|
|
76
73
|
|
|
77
74
|
// Reset cursor when filter changes
|