@miphamai/cli 0.85.18 → 0.85.20
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 +1 -1
- package/package.json +1 -1
- package/src/agent/agent-registry.ts +2 -0
- package/src/agent/auto-compact.ts +72 -0
- package/src/agent/sub-agent.ts +26 -1
- package/src/agent/types.ts +18 -0
- package/src/agent-view/agent-view-manager.ts +50 -0
- package/src/core/context.ts +15 -3
- package/src/core/engine.ts +52 -5
- package/src/core/instructions.ts +78 -2
- package/src/daemon/channel-message.ts +8 -1
- package/src/daemon/session-worker.ts +17 -2
- package/src/i18n-core/locales/en-US.json +13 -3
- package/src/i18n-core/locales/zh-CN.json +13 -3
- package/src/index.tsx +8 -0
- package/src/mcp/client.ts +46 -0
- package/src/mcp/instructions.ts +48 -10
- package/src/mcp/protocol.ts +69 -2
- package/src/mcp/registry.ts +2 -1
- package/src/mcp/transport.ts +70 -9
- package/src/plugin/plugin-manager.ts +29 -8
- package/src/providers/fetch-utils.ts +47 -2
- package/src/security/fd.ts +18 -0
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +6 -2
- package/src/shared/types.ts +16 -0
- package/src/skills/marketplace.ts +15 -5
- package/src/skills/registry.ts +4 -1
- package/src/tools/agent/agent.ts +24 -0
- package/src/tools/agent/skill.ts +13 -0
- package/src/tools/exec/bash.ts +10 -0
- package/src/tools/file/edit.ts +13 -2
- package/src/tools/file/grep.ts +11 -2
- package/src/tools/file/read.ts +30 -6
- package/src/tools/file/write.ts +22 -2
- package/src/tools/system/tool-search.ts +2 -1
- package/src/ui/agent-footer.tsx +16 -3
- package/src/ui/app.tsx +67 -15
- package/src/ui/chat.tsx +73 -11
- package/src/ui/commands.ts +35 -11
- package/src/ui/copy-picker.tsx +73 -0
- package/src/ui/input.tsx +137 -21
- package/src/workflow/primitives/agent.ts +24 -3
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.20
|
|
2
2
|
|
|
3
3
|
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 137 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
|
|
4
4
|
|
package/package.json
CHANGED
|
@@ -79,6 +79,8 @@ export class AgentRegistry {
|
|
|
79
79
|
: undefined,
|
|
80
80
|
background: typeof data.background === 'boolean' ? data.background : undefined,
|
|
81
81
|
memory: data.memory as 'user' | 'project' | 'local' | undefined,
|
|
82
|
+
autoCompactWindow:
|
|
83
|
+
typeof data.autoCompactWindow === 'number' ? data.autoCompactWindow : undefined,
|
|
82
84
|
source,
|
|
83
85
|
filePath: fullPath,
|
|
84
86
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Message } from '../shared/index.ts'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Ratio of the declared window at which a sub-agent shrinks its context.
|
|
5
|
+
* Kept in step with `ContextManager`'s default `compactionThreshold` so an agent
|
|
6
|
+
* that opted into `autoCompactWindow` compacts at the same fill the main session
|
|
7
|
+
* would.
|
|
8
|
+
*/
|
|
9
|
+
const SHRINK_THRESHOLD = 0.85
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Tail sizes tried, largest first. Mirrors `COMPACTION_PASSES`' shrink-to-fit:
|
|
13
|
+
* keep as much recent context as fits, and only take a shorter tail if the first
|
|
14
|
+
* candidate is still over budget. Bounded so a shrink always terminates.
|
|
15
|
+
*/
|
|
16
|
+
const KEEP_CANDIDATES = [10, 4] as const
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* True iff `msg` is a `user` turn carrying one or more `tool_result` blocks.
|
|
20
|
+
*
|
|
21
|
+
* Such a turn is meaningless without the `tool_use` it answers, and providers
|
|
22
|
+
* reject an orphaned `tool_result` — so truncation must never leave one at the
|
|
23
|
+
* head of what it keeps.
|
|
24
|
+
*/
|
|
25
|
+
export function isToolResultMessage(msg: Message): boolean {
|
|
26
|
+
return (
|
|
27
|
+
msg.role === 'user' &&
|
|
28
|
+
Array.isArray(msg.content) &&
|
|
29
|
+
msg.content.some((b) => b.type === 'tool_result')
|
|
30
|
+
)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Shrink a sub-agent's message list, preserving its task.
|
|
35
|
+
*
|
|
36
|
+
* Unlike `ContextManager.compact` (keep the last N; let a summarizer condense the
|
|
37
|
+
* front), a sub-agent has **no summarizer** and **no persistent goal-bearing
|
|
38
|
+
* system prompt** — `messages[0]` *is* the task. Keeping only a tail would strand
|
|
39
|
+
* the agent with nothing to do, so the opening message is pinned and the middle is
|
|
40
|
+
* dropped instead.
|
|
41
|
+
*
|
|
42
|
+
* Opt-in: the loop only calls this when the agent declared `autoCompactWindow`;
|
|
43
|
+
* without the field the run is byte-identical to before. No-op until the estimate
|
|
44
|
+
* exceeds `window * SHRINK_THRESHOLD`.
|
|
45
|
+
*
|
|
46
|
+
* `estimate` is threaded in rather than reimplemented, so the caller gates on the
|
|
47
|
+
* very number `ContextManager` would report — never a second, divergent estimate.
|
|
48
|
+
* Returns the input array unchanged when no shrink is needed.
|
|
49
|
+
*/
|
|
50
|
+
export function shrinkAgentMessages(
|
|
51
|
+
messages: Message[],
|
|
52
|
+
window: number,
|
|
53
|
+
estimate: (m: Message[]) => number,
|
|
54
|
+
): Message[] {
|
|
55
|
+
if (messages.length < 3) return messages
|
|
56
|
+
if (estimate(messages) <= window * SHRINK_THRESHOLD) return messages
|
|
57
|
+
|
|
58
|
+
const task = messages[0]!
|
|
59
|
+
const rest = messages.slice(1)
|
|
60
|
+
|
|
61
|
+
for (let i = 0; i < KEEP_CANDIDATES.length; i++) {
|
|
62
|
+
let tail = rest.slice(-KEEP_CANDIDATES[i]!)
|
|
63
|
+
// Drop orphaned tool_results at the head (their tool_use was cut away).
|
|
64
|
+
while (tail.length > 0 && isToolResultMessage(tail[0]!)) tail = tail.slice(1)
|
|
65
|
+
const candidate = [task, ...tail]
|
|
66
|
+
if (estimate(candidate) <= window * SHRINK_THRESHOLD || i === KEEP_CANDIDATES.length - 1) {
|
|
67
|
+
return candidate
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return messages
|
|
72
|
+
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -3,6 +3,7 @@ import type { Llm } from '../providers/llm'
|
|
|
3
3
|
import type { Message, ToolDefinition, ToolContext } from '../shared/index.ts'
|
|
4
4
|
import type { SubAgentType, SubAgentOptions, AgentDefinition } from './types'
|
|
5
5
|
import { createAgentContext } from './agent-context'
|
|
6
|
+
import { shrinkAgentMessages } from './auto-compact'
|
|
6
7
|
import { getBackgroundAgentRegistry } from './background-registry'
|
|
7
8
|
import { formatInboundMessage, getMessageBus } from './message-bus'
|
|
8
9
|
import type { HookEngine } from '../core/hooks'
|
|
@@ -380,12 +381,20 @@ export class SubAgent {
|
|
|
380
381
|
source: 'builtin',
|
|
381
382
|
}
|
|
382
383
|
const contextWindow = this.registry.findModel(finalModel)?.contextWindow
|
|
384
|
+
// `autoCompactWindow` (frontmatter) lets an agent declare a **tighter** budget
|
|
385
|
+
// than its model's native window so it compacts sooner; it can never widen the
|
|
386
|
+
// real window, so take the min. Absent the field, nothing changes — the
|
|
387
|
+
// sub-agent context is sized exactly as before.
|
|
388
|
+
const declaredWindow = agentDef?.autoCompactWindow
|
|
389
|
+
const compactWindow = declaredWindow
|
|
390
|
+
? Math.min(declaredWindow, contextWindow ?? declaredWindow)
|
|
391
|
+
: undefined
|
|
383
392
|
// 这一份**已含 agent memory**,是发出去的那个提示的唯一来源。
|
|
384
393
|
const {
|
|
385
394
|
context,
|
|
386
395
|
allowedTools,
|
|
387
396
|
systemPrompt: composedSystemPrompt,
|
|
388
|
-
} = createAgentContext(resolvedDef, this.toolRegistry, contextWindow)
|
|
397
|
+
} = createAgentContext(resolvedDef, this.toolRegistry, compactWindow ?? contextWindow)
|
|
389
398
|
|
|
390
399
|
// 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
|
|
391
400
|
// 那一份设过上下文,这里用裸提示再设一遍只会把记忆从上下文里抹掉,而请求读的又不是
|
|
@@ -507,6 +516,18 @@ export class SubAgent {
|
|
|
507
516
|
throw new DOMException('Aborted', 'AbortError')
|
|
508
517
|
}
|
|
509
518
|
|
|
519
|
+
// Opt-in shrink for agents that declared `autoCompactWindow`. The engine
|
|
520
|
+
// compacts through `ContextManager`, but this loop keeps `currentMessages`
|
|
521
|
+
// locally and never calls it — so without this line the field would be
|
|
522
|
+
// decoration. Task-pinned: `shrinkAgentMessages` never drops `messages[0]`,
|
|
523
|
+
// because here that message *is* the task (no summarizer, no system prompt
|
|
524
|
+
// restating it). Gated on the estimate `context` itself would report.
|
|
525
|
+
if (compactWindow) {
|
|
526
|
+
currentMessages = shrinkAgentMessages(currentMessages, compactWindow, (m) =>
|
|
527
|
+
context.estimateTokensForMessages(m),
|
|
528
|
+
)
|
|
529
|
+
}
|
|
530
|
+
|
|
510
531
|
// Per turn, not once per run: a peer can write while this agent is mid
|
|
511
532
|
// task, and the point of the channel is to steer the work in progress.
|
|
512
533
|
this.drainInboundMessages(agentId, currentMessages)
|
|
@@ -521,6 +542,10 @@ export class SubAgent {
|
|
|
521
542
|
systemPrompt: currentSystemPrompt,
|
|
522
543
|
tools: toolDefs,
|
|
523
544
|
maxTokens: 4096,
|
|
545
|
+
// Scales the provider's streaming idle timeout (fetch-utils
|
|
546
|
+
// `streamIdleTimeoutMs`). Omitted ⇒ 1× base, so a caller that asked for
|
|
547
|
+
// a high-effort sub-agent would otherwise get the default budget.
|
|
548
|
+
effort: options.effort,
|
|
524
549
|
})) {
|
|
525
550
|
// Check abort signal mid-stream
|
|
526
551
|
if (signal?.aborted) {
|
package/src/agent/types.ts
CHANGED
|
@@ -18,6 +18,14 @@ export interface AgentFrontmatter {
|
|
|
18
18
|
skills?: string
|
|
19
19
|
background?: boolean
|
|
20
20
|
memory?: 'user' | 'project' | 'local' // agent memory scope
|
|
21
|
+
/**
|
|
22
|
+
* Opt-in context budget (tokens) for this agent's own conversation. When set,
|
|
23
|
+
* the sub-agent shrinks its context on the first turn it crosses this window
|
|
24
|
+
* (the same 0.85 ratio the main session uses) — so a long-running agent
|
|
25
|
+
* compacts on its own terms instead of growing until `maxTurns`. Never widens
|
|
26
|
+
* the model's real window: the effective value is `min(field, modelWindow)`.
|
|
27
|
+
*/
|
|
28
|
+
autoCompactWindow?: number
|
|
21
29
|
}
|
|
22
30
|
|
|
23
31
|
export interface AgentDefinition {
|
|
@@ -35,6 +43,8 @@ export interface AgentDefinition {
|
|
|
35
43
|
source: 'builtin' | 'project' | 'user'
|
|
36
44
|
filePath?: string
|
|
37
45
|
memory?: 'user' | 'project' | 'local' // agent memory scope
|
|
46
|
+
/** Opt-in per-agent context budget; see `AgentFrontmatter.autoCompactWindow`. */
|
|
47
|
+
autoCompactWindow?: number
|
|
38
48
|
}
|
|
39
49
|
|
|
40
50
|
export interface SubAgentOptions {
|
|
@@ -43,6 +53,14 @@ export interface SubAgentOptions {
|
|
|
43
53
|
systemPrompt?: string
|
|
44
54
|
allowedTools?: string[]
|
|
45
55
|
modelOverride?: string
|
|
56
|
+
/**
|
|
57
|
+
* Reasoning effort (`low|medium|high|xhigh|max`) for this run, matching the
|
|
58
|
+
* session-level level `/effort` sets. Threaded into the provider request as
|
|
59
|
+
* `ChatRequest.effort`, where it scales the streaming idle timeout — a
|
|
60
|
+
* sub-agent left at the default would inherit the base timeout regardless of
|
|
61
|
+
* the level the caller asked for.
|
|
62
|
+
*/
|
|
63
|
+
effort?: string
|
|
46
64
|
/** Maximum tool-calling turns (default: 5) to prevent infinite loops. */
|
|
47
65
|
maxTurns?: number
|
|
48
66
|
/** When true, execute in background and return immediately with a task ID. */
|
|
@@ -126,6 +126,56 @@ export class AgentViewManager {
|
|
|
126
126
|
return session
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Mirror background-agent tasks into the panel, and return how many rows were
|
|
131
|
+
* added.
|
|
132
|
+
*
|
|
133
|
+
* Rows created by `/bg` and `/fork` used to be the only ones that existed. The
|
|
134
|
+
* Agent tool — whose sub-agents are **background by default** — registers them
|
|
135
|
+
* with the background registry and nothing else, so the ordinary way to fan out
|
|
136
|
+
* work produced no panel rows at all: the pane stayed empty the whole time the
|
|
137
|
+
* agents ran, which a viewer cannot tell apart from "nothing was spawned".
|
|
138
|
+
*
|
|
139
|
+
* Keyed on the registry's task id. `/bg` and `/fork` already link their row
|
|
140
|
+
* through `session.taskId`, so those are matched and updated rather than
|
|
141
|
+
* duplicated; anything else is a task this panel has not seen.
|
|
142
|
+
*
|
|
143
|
+
* Status is a projection, not a source: the registry owns it, and a row whose
|
|
144
|
+
* status disagrees with the registry is corrected here on the next round.
|
|
145
|
+
*/
|
|
146
|
+
syncBackgroundTasks(
|
|
147
|
+
tasks: ReadonlyArray<{ id: string; description: string; status: string }>,
|
|
148
|
+
): number {
|
|
149
|
+
const byTaskId = new Map<string, AgentSession>()
|
|
150
|
+
for (const id of this.sessionOrder) {
|
|
151
|
+
const session = this.sessions.get(id)
|
|
152
|
+
if (session?.taskId) byTaskId.set(session.taskId, session)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
let added = 0
|
|
156
|
+
for (const task of tasks) {
|
|
157
|
+
const status: SessionStatus =
|
|
158
|
+
task.status === 'running' ? 'working' : task.status === 'failed' ? 'failed' : 'completed'
|
|
159
|
+
|
|
160
|
+
const existing = byTaskId.get(task.id)
|
|
161
|
+
if (existing) {
|
|
162
|
+
if (existing.status !== status) this.updateStatus(existing.id, status)
|
|
163
|
+
continue
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const session = this.create(task.description, task.description)
|
|
167
|
+
session.taskId = task.id
|
|
168
|
+
// Not `interactive`: nobody is steering this row, and the dashboard's
|
|
169
|
+
// grouping keys off the kind as well as the status.
|
|
170
|
+
session.kind = 'unattended'
|
|
171
|
+
this.updateStatus(session.id, status)
|
|
172
|
+
byTaskId.set(task.id, session)
|
|
173
|
+
added++
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return added
|
|
177
|
+
}
|
|
178
|
+
|
|
129
179
|
/**
|
|
130
180
|
* List all sessions in creation order (newest first).
|
|
131
181
|
*/
|
package/src/core/context.ts
CHANGED
|
@@ -569,12 +569,24 @@ export class ContextManager {
|
|
|
569
569
|
|
|
570
570
|
/** 从当前消息**重算消息那半**的估值(提示那半不在这里 —— 它是读时派生的)。 */
|
|
571
571
|
private recountMessageTokens(): void {
|
|
572
|
-
this.messageTokens =
|
|
573
|
-
|
|
574
|
-
|
|
572
|
+
this.messageTokens = this.estimateTokensForMessages(this.messages)
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* 任意消息列表的 token 估值,用的就是 `recountMessageTokens` 那套逐条估计器 ——
|
|
577
|
+
* 纯函数、不碰实例状态。
|
|
578
|
+
*
|
|
579
|
+
* 存在的理由:`ContextManager` 之外的调用方(子代理循环的 `autoCompactWindow`
|
|
580
|
+
* 收缩)要**按 manager 自己会报的那个数**设闸,而不是另养一份会漂移的估计。
|
|
581
|
+
*/
|
|
582
|
+
estimateTokensForMessages(messages: Message[]): number {
|
|
583
|
+
let total = 0
|
|
584
|
+
for (const msg of messages) {
|
|
585
|
+
total += this.estimateTokens(
|
|
575
586
|
typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content),
|
|
576
587
|
)
|
|
577
588
|
}
|
|
589
|
+
return total
|
|
578
590
|
}
|
|
579
591
|
|
|
580
592
|
/** 提示那半的估值 —— 每次读数现拼现算,见 `getEstimatedTokens()`。 */
|
package/src/core/engine.ts
CHANGED
|
@@ -23,6 +23,7 @@ import type { AgentViewManager } from '../agent-view/agent-view-manager'
|
|
|
23
23
|
import type { Skills } from '../skills/seam'
|
|
24
24
|
import { getBackgroundAgentRegistry } from '../agent/background-registry'
|
|
25
25
|
import { RulesLoader } from './rules-loader'
|
|
26
|
+
import { extractBashFileAccess } from './permission-rules'
|
|
26
27
|
import type { InstructionsLoader } from './instructions'
|
|
27
28
|
import { ExperienceRuleEngine } from './rule-engine.js'
|
|
28
29
|
import { PatternAnalyzer } from '../agent/pattern-analyzer.js'
|
|
@@ -406,6 +407,19 @@ export class QueryEngine {
|
|
|
406
407
|
|
|
407
408
|
/** Track files touched by tools for rules matching. */
|
|
408
409
|
private trackTouchedFile(toolName: string, params: Record<string, unknown>): void {
|
|
410
|
+
if (toolName === 'Bash') {
|
|
411
|
+
// A single-file `cat`/`head`/`sed -n`/`grep` reads the same file the Read
|
|
412
|
+
// tool would, so the rules scoped to it have to see that path too. Reuses
|
|
413
|
+
// the extractor the permission layer already runs for Bash↔Read/Write rule
|
|
414
|
+
// bridging rather than a second, drifting spelling of "which paths did this
|
|
415
|
+
// command touch" — it already covers redirects, `$()`/backtick
|
|
416
|
+
// substitutions, `bash -c` payloads and `~`/`$HOME` expansion.
|
|
417
|
+
const command = params.command
|
|
418
|
+
if (typeof command !== 'string') return
|
|
419
|
+
const access = extractBashFileAccess(command)
|
|
420
|
+
for (const p of [...access.read, ...access.write]) this.touchedFiles.add(p)
|
|
421
|
+
return
|
|
422
|
+
}
|
|
409
423
|
const fileTools = ['Read', 'Write', 'Edit', 'Glob', 'Grep']
|
|
410
424
|
if (!fileTools.includes(toolName)) return
|
|
411
425
|
const filePath = (params.file_path || params.path || params.file) as string | undefined
|
|
@@ -414,14 +428,32 @@ export class QueryEngine {
|
|
|
414
428
|
}
|
|
415
429
|
}
|
|
416
430
|
|
|
417
|
-
/**
|
|
431
|
+
/**
|
|
432
|
+
* Inject path-scoped context for the files touched this round: matching rules
|
|
433
|
+
* (`.mipham/rules/*.md`) and any nested instruction files (`CLAUDE.md` and
|
|
434
|
+
* friends) that were not part of the startup chain.
|
|
435
|
+
*
|
|
436
|
+
* Both halves ride the same trigger on purpose — a rule file and a nested
|
|
437
|
+
* `CLAUDE.md` are the same kind of thing (the loader labels the level
|
|
438
|
+
* "Directory Rules"), and a path that activates one almost always activates
|
|
439
|
+
* the other. They also share the call-timing constraint below.
|
|
440
|
+
*
|
|
441
|
+
* Must run **after** every `tool_result` of the round has been appended:
|
|
442
|
+
* `injectContext` pushes a user message, and landing it between an assistant
|
|
443
|
+
* `tool_use` and its paired user `tool_result` breaks the pairing.
|
|
444
|
+
*/
|
|
418
445
|
private injectRules(): void {
|
|
419
|
-
if (
|
|
446
|
+
if (this.touchedFiles.size === 0) return
|
|
420
447
|
const files = Array.from(this.touchedFiles)
|
|
421
|
-
const block = this.rulesLoader.buildContextBlock(files)
|
|
422
|
-
if (!block) return
|
|
423
|
-
this.context.injectContext('rules', block)
|
|
424
448
|
this.touchedFiles.clear()
|
|
449
|
+
|
|
450
|
+
if (this.rulesLoader) {
|
|
451
|
+
const block = this.rulesLoader.buildContextBlock(files)
|
|
452
|
+
if (block) this.context.injectContext('rules', block)
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
const nested = this.instructionsLoader?.loadForPaths(files, process.cwd())
|
|
456
|
+
if (nested) this.context.injectContext('directory-rules', nested)
|
|
425
457
|
}
|
|
426
458
|
|
|
427
459
|
/**
|
|
@@ -459,6 +491,14 @@ export class QueryEngine {
|
|
|
459
491
|
const tasks = bgRegistry.list()
|
|
460
492
|
const chunks: StreamChunk[] = []
|
|
461
493
|
|
|
494
|
+
// Mirror every background task into Agent View — including the running ones,
|
|
495
|
+
// which the loop below deliberately skips. The panel previously carried only
|
|
496
|
+
// `/bg` and `/fork` rows, so a background sub-agent spawned by the Agent tool
|
|
497
|
+
// (the default) was invisible in it for its whole lifetime. Projecting from
|
|
498
|
+
// the registry rather than from each spawn site means every present and future
|
|
499
|
+
// producer is covered by one call.
|
|
500
|
+
this.agentViewManager?.syncBackgroundTasks(tasks)
|
|
501
|
+
|
|
462
502
|
for (const task of tasks) {
|
|
463
503
|
if (task.status === 'running') continue
|
|
464
504
|
|
|
@@ -801,6 +841,7 @@ export class QueryEngine {
|
|
|
801
841
|
tool_use_id: toolUse.id,
|
|
802
842
|
content: result.success ? result.content : result.error || result.content,
|
|
803
843
|
isError: !result.success,
|
|
844
|
+
notRun: result.notRun === true,
|
|
804
845
|
}
|
|
805
846
|
|
|
806
847
|
// Collect tool call record for CRSI auto-reflection
|
|
@@ -1164,6 +1205,7 @@ export class QueryEngine {
|
|
|
1164
1205
|
// —— 直接发 `content` 会让模型收到一个**空** tool_result,错误文案整个丢失。
|
|
1165
1206
|
content: result.success ? result.content : result.error || result.content,
|
|
1166
1207
|
isError: !result.success,
|
|
1208
|
+
notRun: result.notRun === true,
|
|
1167
1209
|
}
|
|
1168
1210
|
|
|
1169
1211
|
// DeepSeek V4 thinking mode requires reasoning_content on every assistant message
|
|
@@ -1223,6 +1265,10 @@ export class QueryEngine {
|
|
|
1223
1265
|
success: false,
|
|
1224
1266
|
content: '',
|
|
1225
1267
|
error: baseError + moveOnHint,
|
|
1268
|
+
// Held back, not judged: the auto-mode classifier had no usable answer.
|
|
1269
|
+
// The display says "Not run" for these instead of showing a result line
|
|
1270
|
+
// that reads as if the tool had run and returned that text (296-056).
|
|
1271
|
+
notRun: decision.retryable === true,
|
|
1226
1272
|
}
|
|
1227
1273
|
}
|
|
1228
1274
|
// P1-4: Tool allowed — reset block counter
|
|
@@ -1388,6 +1434,7 @@ export class QueryEngine {
|
|
|
1388
1434
|
success: false,
|
|
1389
1435
|
content: '',
|
|
1390
1436
|
error: this.buildDenialError(name, tool, effectiveParams, recheck),
|
|
1437
|
+
notRun: recheck.retryable === true,
|
|
1391
1438
|
}
|
|
1392
1439
|
}
|
|
1393
1440
|
}
|
package/src/core/instructions.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { readFileSync, existsSync, lstatSync } from 'node:fs'
|
|
2
|
-
import { join, resolve, relative, sep, isAbsolute } from 'node:path'
|
|
1
|
+
import { readFileSync, existsSync, lstatSync, statSync } from 'node:fs'
|
|
2
|
+
import { join, resolve, relative, sep, isAbsolute, dirname } from 'node:path'
|
|
3
3
|
import { execSync } from 'node:child_process'
|
|
4
4
|
import { parse as parseYaml } from 'yaml'
|
|
5
5
|
import type { InstructionFile } from '../shared/index.ts'
|
|
@@ -84,6 +84,12 @@ export function gitRoot(cwd: string): string {
|
|
|
84
84
|
}
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
/** True when `p` is `root` itself or sits underneath it. */
|
|
88
|
+
function isInside(root: string, p: string): boolean {
|
|
89
|
+
const rel = relative(root, p)
|
|
90
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
|
|
91
|
+
}
|
|
92
|
+
|
|
87
93
|
/** 从仓库根到 cwd 的目录链(含两端),就近(cwd)在最后。cwd 不在 root 下时退化为 [cwd]。 */
|
|
88
94
|
export function discoverDirectories(root: string, cwd: string): string[] {
|
|
89
95
|
const absRoot = resolve(root)
|
|
@@ -252,11 +258,14 @@ export class InstructionsLoader {
|
|
|
252
258
|
private instructions: InstructionFile[] = []
|
|
253
259
|
private crsiLessonSummaries: CrsiLessonSummary[] = []
|
|
254
260
|
private lessonsPath: string | null = null
|
|
261
|
+
/** Checkout root resolved at `loadAll`, reused by `loadForPaths`. */
|
|
262
|
+
private root: string | null = null
|
|
255
263
|
|
|
256
264
|
loadAll(cwd: string): void {
|
|
257
265
|
this.instructions = []
|
|
258
266
|
this.lessonsPath = null
|
|
259
267
|
const root = gitRoot(cwd)
|
|
268
|
+
this.root = root
|
|
260
269
|
|
|
261
270
|
// Tier 1: 集团/公司策略(锚定仓库根,从任意子目录启动都正确;不读 AGENTS.md)
|
|
262
271
|
this.tryLoad(join(root, '..', '..', 'CLAUDE.md'), 'group') // Rismed_Ronxin_Capital
|
|
@@ -522,6 +531,73 @@ Never omit it or present the work as purely human-authored.`)
|
|
|
522
531
|
return [...this.instructions]
|
|
523
532
|
}
|
|
524
533
|
|
|
534
|
+
/**
|
|
535
|
+
* Load the instruction files of the directories a path the model just looked at
|
|
536
|
+
* lives under, and return the text of whatever was **not** already loaded.
|
|
537
|
+
*
|
|
538
|
+
* The baseline chain is git-root → cwd, walked once at startup (`loadAll`). A
|
|
539
|
+
* file deeper than cwd (`src/parser/lex.ts`) or on a sibling branch therefore
|
|
540
|
+
* contributes nothing — even though the `CLAUDE.md` sitting next to it is
|
|
541
|
+
* precisely the rule set that governs it. Upstream reported the Bash half of
|
|
542
|
+
* this (`cat`/`head`/`sed -n`/`grep` on a single file skipped its rules); the
|
|
543
|
+
* Read tool had the same hole, so the gate here is the **path**, not the tool
|
|
544
|
+
* that produced it: "did the model see a file here".
|
|
545
|
+
*
|
|
546
|
+
* Only directories inside the checkout are considered. The tiers above it are
|
|
547
|
+
* anchored deliberately (`loadAll`), and walking the ancestors of, say,
|
|
548
|
+
* `/etc/hosts` would pull arbitrary local files into the prompt on the strength
|
|
549
|
+
* of a command — so an outside path contributes nothing by construction.
|
|
550
|
+
* Directories already visited cost one `existsSync` per candidate name.
|
|
551
|
+
*
|
|
552
|
+
* Returns `null` when nothing new was loaded, so callers can skip an empty
|
|
553
|
+
* injection. Text goes through `instructionPartText` — the same projection the
|
|
554
|
+
* system prompt uses — so `privacy: private` and `prompt-exclude` are honored
|
|
555
|
+
* here too, and the two cannot drift.
|
|
556
|
+
*/
|
|
557
|
+
loadForPaths(paths: Iterable<string>, cwd: string): string | null {
|
|
558
|
+
// Reused rather than re-resolved: `gitRoot` spawns `git rev-parse`, and this
|
|
559
|
+
// runs on the tool-execution path once per round. The fallback keeps the
|
|
560
|
+
// method correct for a caller that never ran `loadAll`.
|
|
561
|
+
const root = this.root ?? resolve(gitRoot(cwd))
|
|
562
|
+
const loaded = new Set(this.instructions.map((f) => f.path))
|
|
563
|
+
const added: InstructionFile[] = []
|
|
564
|
+
|
|
565
|
+
for (const raw of paths) {
|
|
566
|
+
let dir = resolve(cwd, raw)
|
|
567
|
+
if (!isInside(root, dir)) continue
|
|
568
|
+
// A touched path is a directory when the tool searched one (Grep's root,
|
|
569
|
+
// Glob) and a file otherwise. A path that does not exist yet is treated as
|
|
570
|
+
// a file, which is the right reading for `Write` on a new path.
|
|
571
|
+
try {
|
|
572
|
+
if (!statSync(dir).isDirectory()) dir = dirname(dir)
|
|
573
|
+
} catch {
|
|
574
|
+
dir = dirname(dir)
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
for (;;) {
|
|
578
|
+
for (const name of INSTRUCTION_FILENAMES) {
|
|
579
|
+
const file = join(dir, name)
|
|
580
|
+
if (loaded.has(file)) continue
|
|
581
|
+
loaded.add(file)
|
|
582
|
+
this.tryLoad(file, 'directory')
|
|
583
|
+
const loadedFile = this.instructions[this.instructions.length - 1]
|
|
584
|
+
if (loadedFile?.path === file) added.push(loadedFile)
|
|
585
|
+
}
|
|
586
|
+
if (dir === root) break
|
|
587
|
+
const parent = dirname(dir)
|
|
588
|
+
if (parent === dir) break
|
|
589
|
+
dir = parent
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
const parts: string[] = []
|
|
594
|
+
for (const inst of added) {
|
|
595
|
+
const text = instructionPartText(inst)
|
|
596
|
+
if (text) parts.push(text)
|
|
597
|
+
}
|
|
598
|
+
return parts.length > 0 ? parts.join('\n\n---\n\n') : null
|
|
599
|
+
}
|
|
600
|
+
|
|
525
601
|
/**
|
|
526
602
|
* How much instruction text this loader puts in the system prompt, per file.
|
|
527
603
|
*
|
|
@@ -45,7 +45,14 @@ export async function handleChannelMessage(opts: ChannelMessageOptions): Promise
|
|
|
45
45
|
await sendText(externalId, '(会话初始化失败,请稍后重试)')
|
|
46
46
|
return
|
|
47
47
|
}
|
|
48
|
-
await worker.processPrompt(text)
|
|
48
|
+
const outcome = await worker.processPrompt(text)
|
|
49
|
+
// A `busy` outcome means this turn never ran — the concurrency guard refused
|
|
50
|
+
// it. Reading `getLastAssistantContent()` here would replay the *previous*
|
|
51
|
+
// turn's reply as if it answered the message just sent, so say what happened.
|
|
52
|
+
if (!outcome.ok) {
|
|
53
|
+
await sendText(externalId, '(上一条消息仍在处理中,请稍候再发)')
|
|
54
|
+
return
|
|
55
|
+
}
|
|
49
56
|
const result = worker.getLastAssistantContent()
|
|
50
57
|
await sendText(externalId, result ? result.slice(0, maxLen) : '(无回复)')
|
|
51
58
|
} catch (err) {
|
|
@@ -51,6 +51,19 @@ export interface SessionStateSnapshot {
|
|
|
51
51
|
permissionMode: PermissionMode
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
+
// ── Prompt-processing outcome ─────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Result of a `processPrompt` call.
|
|
58
|
+
*
|
|
59
|
+
* `busy` is *reported*, not swallowed. A second message arriving mid-turn used to
|
|
60
|
+
* fall out of the concurrency guard — which only broadcasts to WS viewers — and
|
|
61
|
+
* then be answered by the caller with `getLastAssistantContent()`, i.e. the
|
|
62
|
+
* *previous* turn's reply. The user got an answer to a question they had not
|
|
63
|
+
* asked. Naming the refusal lets the channel say "still working" instead.
|
|
64
|
+
*/
|
|
65
|
+
export type ProcessPromptResult = { ok: true } | { ok: false; reason: 'busy' }
|
|
66
|
+
|
|
54
67
|
// ── SessionWorker ─────────────────────────────────────────────────────────
|
|
55
68
|
|
|
56
69
|
export class SessionWorker {
|
|
@@ -110,10 +123,10 @@ export class SessionWorker {
|
|
|
110
123
|
* 7. On interrupt: save partial content, broadcast `done` with stop_reason
|
|
111
124
|
* 'interrupted'
|
|
112
125
|
*/
|
|
113
|
-
async processPrompt(prompt: string): Promise<
|
|
126
|
+
async processPrompt(prompt: string): Promise<ProcessPromptResult> {
|
|
114
127
|
if (this.processing) {
|
|
115
128
|
this.broadcast(this.errorMessage('A prompt is already being processed'))
|
|
116
|
-
return
|
|
129
|
+
return { ok: false, reason: 'busy' }
|
|
117
130
|
}
|
|
118
131
|
|
|
119
132
|
this.processing = true
|
|
@@ -215,6 +228,8 @@ export class SessionWorker {
|
|
|
215
228
|
|
|
216
229
|
this.currentController = null
|
|
217
230
|
this.processing = false
|
|
231
|
+
|
|
232
|
+
return { ok: true }
|
|
218
233
|
}
|
|
219
234
|
|
|
220
235
|
// ── Interrupt ──────────────────────────────────────────────────────────
|
|
@@ -173,7 +173,8 @@
|
|
|
173
173
|
"copy": {
|
|
174
174
|
"confirmed": "✓ Copied {count} assistant response(s) to clipboard.",
|
|
175
175
|
"no_responses": "No assistant responses to copy.",
|
|
176
|
-
"usage": "Usage: /copy [N]\nN = number of recent assistant responses to copy (default: 1)"
|
|
176
|
+
"usage": "Usage: /copy [N]\nN = number of recent assistant responses to copy (default: 1)",
|
|
177
|
+
"pick_prompt": "Select a response to copy:"
|
|
177
178
|
},
|
|
178
179
|
"recap": {
|
|
179
180
|
"title": "── Session Recap ──",
|
|
@@ -772,6 +773,7 @@
|
|
|
772
773
|
"focus_hint": "Focus",
|
|
773
774
|
"hidden": "hidden",
|
|
774
775
|
"toggle_focus_hint": "/focus to toggle",
|
|
776
|
+
"try_focus_tip": "Long turn? Ctrl+F (or /focus) shows just the latest exchange — press it again to switch back.",
|
|
775
777
|
"expand_hint": "Ctrl+O to expand",
|
|
776
778
|
"showing_all": "showing all {count} messages",
|
|
777
779
|
"tool_outputs_folded": "{hidden} tool outputs folded ({toolCount} total tool calls)"
|
|
@@ -858,6 +860,13 @@
|
|
|
858
860
|
"unknown": "Unknown rendering error",
|
|
859
861
|
"recovery": "The terminal interface encountered a rendering issue. Auto-recovery in 5 seconds... Press Enter to attempt immediate recovery.",
|
|
860
862
|
"preserved": "Your session data and conversation history are preserved."
|
|
863
|
+
},
|
|
864
|
+
"tool": {
|
|
865
|
+
"not_run": "Not run"
|
|
866
|
+
},
|
|
867
|
+
"copy_picker": {
|
|
868
|
+
"title": "/copy",
|
|
869
|
+
"nav_help": "(↑↓ to move, Enter to copy, Esc to cancel)"
|
|
861
870
|
}
|
|
862
871
|
},
|
|
863
872
|
"tools": {
|
|
@@ -929,8 +938,8 @@
|
|
|
929
938
|
"errors": {
|
|
930
939
|
"tool_denied_deny_rule": "Tool \"{name}\" blocked by a deny rule (\"{pattern}\"). Deny rules override permission mode — try a different approach, or drop the rule with: /permissions remove \"{pattern}\"",
|
|
931
940
|
"tool_denied_ask_rule": "Tool \"{name}\" requires approval (ask rule: \"{pattern}\"). Approve when prompted, or stop being asked with: /permissions allow \"{pattern}\"",
|
|
932
|
-
"tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\")
|
|
933
|
-
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool.
|
|
941
|
+
"tool_denied_mode": "Tool \"{name}\" requires approval under \"{mode}\" mode. Press Shift+Tab to switch permission mode, or stop being asked with: /permissions allow \"{name}\" (or a narrower \"{name}(arg)\").",
|
|
942
|
+
"tool_denied_classifier": "Tool \"{name}\" was blocked in auto mode by the permission classifier ({reason}). This is a policy decision, not a failure — switching modes will not change it, and repeating the identical call returns the same ruling. Change the call so it no longer trips the rule. Note that `/permissions allow \"{name}\"` skips the classifier for every later call to this tool, not just this one, so prefer making the call acceptable over allowing the tool.",
|
|
934
943
|
"tool_denied_dangerous_rm": "Tool \"{name}\" was refused: this is a recursive rm whose target is not a path written in the command (\"{target}\"). The target is produced when the command runs, so neither an allow rule nor the permission mode can bound what it deletes. Name the directory literally instead — `rm -rf node_modules` rather than `rm -rf \"$(pwd)\"` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_DANGEROUS_RM_PROMPT=1",
|
|
935
944
|
"tool_denied_world_writable_chmod": "Tool \"{name}\" was refused: this is a recursive chmod that grants world-write to a target the command does not bound (\"{target}\"). A world-writable tree plus a target produced at run time is how permissions end up loosened far past what was asked for, and neither an allow rule nor the permission mode can bound where the grant reaches. Name the directory literally instead — `chmod -R 777 ./dist` rather than `chmod -R 777 $DIR` — and treat this refusal as covering the outcome, not only this exact spelling. To turn this check off: MIPHAM_DISABLE_CHMOD_PROMPT=1",
|
|
936
945
|
"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.",
|
|
@@ -953,6 +962,7 @@
|
|
|
953
962
|
"oauth_no_code": "No authorization code received",
|
|
954
963
|
"oauth_timeout": "OAuth flow timed out (5 minutes)",
|
|
955
964
|
"mcp_register_collision": "[mcp] Tool collision: \"{name}\" (from server \"{server}\") conflicts with existing tool. Skipping.",
|
|
965
|
+
"mcp_protocol_version_mismatch": "[mcp] Server negotiated protocol version \"{version}\", which this client does not implement (supported: {supported}). Continuing, but MCP messages may not behave as expected.",
|
|
956
966
|
"mcp_register_failed": "[mcp] Failed to register tool \"{tool}\" from server \"{server}\": {error}",
|
|
957
967
|
"max_tool_turns": "Max tool-calling turns ({max}) reached. Some tool calls were not executed.",
|
|
958
968
|
"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.",
|