@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.
- 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/commands/git.ts +149 -1
- package/src/core/engine.ts +132 -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 +12 -2
- package/src/i18n-core/locales/zh-CN.json +12 -2
- package/src/index.tsx +6 -1
- package/src/mcp/registry.ts +11 -3
- package/src/mcp/transport.ts +24 -4
- package/src/mcp/types.ts +6 -0
- package/src/providers/anthropic.ts +62 -5
- package/src/providers/bootstrap.ts +13 -0
- package/src/providers/openai-compat.ts +64 -20
- package/src/providers/registry.ts +41 -0
- package/src/shared/constants.ts +11 -0
- package/src/shared/package-info.ts +3 -3
- package/src/shared/sanitize.ts +17 -0
- 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/chat.tsx +8 -4
- package/src/ui/command-picker.tsx +2 -5
- package/src/ui/commands.ts +123 -7
- package/src/ui/input.tsx +21 -8
- package/src/ui/picker.tsx +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.45
|
|
2
2
|
|
|
3
|
-
**Multi-model open-core intelligent coding terminal** — 12 AI providers,
|
|
3
|
+
**Multi-model open-core intelligent coding terminal** — 12 AI providers, 141 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
|
|
|
5
5
|
Built by [One Mipham Corporation](https://onemipham.com) (北京华安麦逄科技有限公司) | Brand: MiphamAI
|
|
6
6
|
|
|
@@ -16,7 +16,7 @@ Requirements: **Bun 1.2+** (recommended) or **Node.js 22+**
|
|
|
16
16
|
## Features
|
|
17
17
|
|
|
18
18
|
- **12 AI Providers** — Anthropic Claude · OpenAI GPT · DeepSeek · Kimi (Moonshot) · Google Gemini · Doubao 豆包 · Tencent Hunyuan 混元 · Qwen 通义千问 · MiniMax(国内 / 国际)· Ollama(本地)· MiphamAI
|
|
19
|
-
- **
|
|
19
|
+
- **141 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
|
|
20
20
|
- **31 Built-in Tools** — File ops, shell execution, agent dispatch, MCP integration, web search
|
|
21
21
|
- **28 Skills + Marketplace** — 22 standard + 6 Mipham-exclusive skills. `/browse-skills` `/install-skill` community marketplace
|
|
22
22
|
- **Self-Update** — `mipham update` / `/upgrade` — one command to check, backup config, upgrade, restore. API keys preserved
|
package/package.json
CHANGED
|
@@ -10,6 +10,7 @@ import { AgentExperience } from './agent-experience'
|
|
|
10
10
|
import { ExperienceRuleExtractor } from './experience-rules.js'
|
|
11
11
|
import { miphamHome } from '../core/paths.ts'
|
|
12
12
|
import { MIPHAM_DIR } from '../shared/constants.ts'
|
|
13
|
+
import { sanitizeSkillBody } from '../skills/sanitizer'
|
|
13
14
|
|
|
14
15
|
export interface AgentContextResult {
|
|
15
16
|
context: ContextManager
|
|
@@ -104,11 +105,55 @@ function loadAgentMemory(
|
|
|
104
105
|
* Agent memory: if agentDef.memory is set, loads memory files from the
|
|
105
106
|
* appropriate scope and injects them into the system prompt.
|
|
106
107
|
*/
|
|
108
|
+
/** The slice of `SkillsLoader` this module needs (kept structural so the agent
|
|
109
|
+
* layer does not import the skills loader just for a type). */
|
|
110
|
+
export interface DeclaredSkillLookup {
|
|
111
|
+
get(name: string): { name: string; description: string; body?: string } | undefined
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Render the skills an agent declared in its frontmatter into its system prompt.
|
|
116
|
+
*
|
|
117
|
+
* `skills:` was parsed into `AgentDefinition` but read by nobody, so an agent
|
|
118
|
+
* that declared skills ran without their instructions — the field was
|
|
119
|
+
* advertised and never applied. Unknown names are reported once (to stderr,
|
|
120
|
+
* like the loader's other warnings) rather than silently dropped: a typo and a
|
|
121
|
+
* missing file are the same thing to the agent, and both mean the same thing
|
|
122
|
+
* to the user.
|
|
123
|
+
*/
|
|
124
|
+
function loadDeclaredSkills(
|
|
125
|
+
agentName: string,
|
|
126
|
+
names: string[],
|
|
127
|
+
lookup: DeclaredSkillLookup | undefined,
|
|
128
|
+
): string {
|
|
129
|
+
if (!lookup) {
|
|
130
|
+
process.stderr.write(
|
|
131
|
+
`⚠️ Agent "${agentName}": declares skills (${names.join(', ')}) but no skills loader is available — skipped.\n`,
|
|
132
|
+
)
|
|
133
|
+
return ''
|
|
134
|
+
}
|
|
135
|
+
const blocks: string[] = []
|
|
136
|
+
for (const name of names) {
|
|
137
|
+
const skill = lookup.get(name)
|
|
138
|
+
if (!skill) {
|
|
139
|
+
process.stderr.write(
|
|
140
|
+
`⚠️ Agent "${agentName}": declared skill "${name}" not found — skipped.\n`,
|
|
141
|
+
)
|
|
142
|
+
continue
|
|
143
|
+
}
|
|
144
|
+
const body = skill.body ? sanitizeSkillBody(skill.body).text : ''
|
|
145
|
+
blocks.push([`## ${skill.name}`, skill.description, body].filter(Boolean).join('\n'))
|
|
146
|
+
}
|
|
147
|
+
if (blocks.length === 0) return ''
|
|
148
|
+
return ['[Agent Skills — declared in frontmatter]', ...blocks].join('\n\n')
|
|
149
|
+
}
|
|
150
|
+
|
|
107
151
|
export function createAgentContext(
|
|
108
152
|
agentDef: AgentDefinition,
|
|
109
153
|
toolRegistry: Map<string, ToolDefinition>,
|
|
110
154
|
contextWindow?: number,
|
|
111
155
|
crsiConfig?: Partial<CrsiConfig>,
|
|
156
|
+
skills?: DeclaredSkillLookup,
|
|
112
157
|
): AgentContextResult {
|
|
113
158
|
// Create isolated context, sized to the resolved model's window when known.
|
|
114
159
|
// Passing contextWindow (not just maxTokens) enables adaptive thresholds.
|
|
@@ -127,6 +172,10 @@ export function createAgentContext(
|
|
|
127
172
|
systemPrompt = `${systemPrompt}\n\n---\n\n${memory}`
|
|
128
173
|
}
|
|
129
174
|
}
|
|
175
|
+
if (agentDef.skills?.length) {
|
|
176
|
+
const declared = loadDeclaredSkills(agentDef.name, agentDef.skills, skills)
|
|
177
|
+
if (declared) systemPrompt = `${systemPrompt}\n\n---\n\n${declared}`
|
|
178
|
+
}
|
|
130
179
|
|
|
131
180
|
context.setSystemPrompt(systemPrompt)
|
|
132
181
|
|
|
@@ -170,6 +170,12 @@ export class AgentRegistry {
|
|
|
170
170
|
name: builtinType,
|
|
171
171
|
description: BUILTIN_DESCRIPTIONS[builtinType],
|
|
172
172
|
systemPrompt: BUILTIN_SYSTEM_PROMPTS[builtinType],
|
|
173
|
+
// `explore` is advertised as a "Read-only search agent". Without an
|
|
174
|
+
// explicit list `selectAgentTools` hands it the whole registry, and an
|
|
175
|
+
// exploration run can Write/Edit — which is how the "unwanted .md
|
|
176
|
+
// investigation files" this builtin exists to avoid get created. The
|
|
177
|
+
// description and the grant must name the same set.
|
|
178
|
+
...(builtinType === 'explore' ? { tools: 'Read,Grep,Glob' } : {}),
|
|
173
179
|
model: 'inherit',
|
|
174
180
|
permissionMode: 'inherit',
|
|
175
181
|
source: 'builtin',
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -416,6 +416,11 @@ export class SubAgent {
|
|
|
416
416
|
resolvedDef,
|
|
417
417
|
this.toolRegistry,
|
|
418
418
|
compactWindow ?? contextWindow,
|
|
419
|
+
undefined,
|
|
420
|
+
// `skills:` in agent frontmatter is applied here — the loader is already
|
|
421
|
+
// inherited through `options.toolContext` (it is how the Skill tool works
|
|
422
|
+
// one level down), so the declared skills resolve against the same set.
|
|
423
|
+
options.toolContext?.skillsLoader,
|
|
419
424
|
)
|
|
420
425
|
|
|
421
426
|
// 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
|
package/src/commands/git.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import type { CommandHandler } from '../ui/commands.js'
|
|
8
8
|
|
|
9
|
-
export { commitCmd, pushCmd, prCmd, issueCmd }
|
|
9
|
+
export { commitCmd, pushCmd, prCmd, issueCmd, shipCmd }
|
|
10
10
|
|
|
11
11
|
/**
|
|
12
12
|
* Run a git command asynchronously — avoids blocking the TUI event loop.
|
|
@@ -189,6 +189,154 @@ const issueCmd: CommandHandler = async (_ctx, args) => {
|
|
|
189
189
|
}
|
|
190
190
|
}
|
|
191
191
|
|
|
192
|
+
// ═══════════════════════════════════════════════════════════════
|
|
193
|
+
// /ship — the whole after-you-write-it loop (Claude Ship beta borrow)
|
|
194
|
+
// ═══════════════════════════════════════════════════════════════
|
|
195
|
+
|
|
196
|
+
export interface ShipContext {
|
|
197
|
+
branch: string
|
|
198
|
+
defaultBranch: string
|
|
199
|
+
staged: number
|
|
200
|
+
unstaged: number
|
|
201
|
+
untracked: number
|
|
202
|
+
ahead: string
|
|
203
|
+
gh: boolean
|
|
204
|
+
/** Whatever the user typed after `/ship` (e.g. `--draft`). */
|
|
205
|
+
args: string
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The plan `/ship` hands to the model.
|
|
210
|
+
*
|
|
211
|
+
* Split out from the handler so the parts that are policy — never commit to the
|
|
212
|
+
* default branch, never merge, report an undo command after each push — can be
|
|
213
|
+
* asserted without spawning git or gh. The handler only gathers facts.
|
|
214
|
+
*/
|
|
215
|
+
export function buildShipPlan(c: ShipContext): { content: string; forwardToAI?: string } {
|
|
216
|
+
if (!c.branch) {
|
|
217
|
+
return {
|
|
218
|
+
content:
|
|
219
|
+
'── Ship ──\n\n' +
|
|
220
|
+
'HEAD is detached, so there is no branch to ship. Check out a branch first, then run /ship again.',
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const onDefault = c.branch === c.defaultBranch
|
|
225
|
+
// Only a known zero means nothing is ahead. An empty string means the
|
|
226
|
+
// upstream count could not be read (no origin, or no upstream branch) — that
|
|
227
|
+
// is "unknown", not "nothing", and the loop must not claim there is no work.
|
|
228
|
+
const nothingToDo = c.staged === 0 && c.unstaged === 0 && c.untracked === 0 && c.ahead === '0'
|
|
229
|
+
|
|
230
|
+
const header = [
|
|
231
|
+
'── Ship ──',
|
|
232
|
+
'',
|
|
233
|
+
`Branch: ${c.branch}${onDefault ? ` (the default branch)` : ''}`,
|
|
234
|
+
`Changes: ${c.staged} staged, ${c.unstaged} unstaged, ${c.untracked} untracked`,
|
|
235
|
+
`Ahead: ${c.ahead || 'unknown'} commit(s) of origin/${c.branch}`,
|
|
236
|
+
`gh: ${c.gh ? 'available' : 'not found'}`,
|
|
237
|
+
].join('\n')
|
|
238
|
+
|
|
239
|
+
if (nothingToDo) {
|
|
240
|
+
return {
|
|
241
|
+
content:
|
|
242
|
+
`${header}\n\n` + `Nothing to ship: no changes and nothing ahead of origin/${c.branch}.`,
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const forwardToAI = `Ship this branch end-to-end with the git and Bash tools. Every push and PR step is permission-checked — do not bypass that layer.
|
|
247
|
+
|
|
248
|
+
Context:
|
|
249
|
+
- Branch: ${c.branch}
|
|
250
|
+
- Default branch: ${c.defaultBranch}
|
|
251
|
+
- Staged / unstaged / untracked: ${c.staged} / ${c.unstaged} / ${c.untracked}
|
|
252
|
+
- Commits ahead of origin/${c.branch}: ${c.ahead || '0'}
|
|
253
|
+
- gh CLI: ${c.gh ? 'available' : 'not found'}
|
|
254
|
+
- User arguments: ${c.args || '(none)'}
|
|
255
|
+
|
|
256
|
+
Steps:
|
|
257
|
+
1. Inspect git status, the diff, and the commits ahead of ${c.defaultBranch}. Never discard the user's uncommitted work.
|
|
258
|
+
2. If HEAD is on ${c.defaultBranch} or detached, create a feature branch named mipham/ship-<short-slug> first. Never commit directly to ${c.defaultBranch}.
|
|
259
|
+
3. Stage only the intended changes and write a Conventional Commits message. If there is nothing to commit, skip this step.
|
|
260
|
+
4. Push the branch you are on with \`git push -u origin <branch>\` (the feature branch from step 2 if you created one).
|
|
261
|
+
5. If gh is available and authenticated, open a pull request with \`gh pr create --base ${c.defaultBranch} --head <branch>\`; use --draft if the user asked for one. If gh is missing or not authenticated, stop after the push and say the PR was not opened.
|
|
262
|
+
6. Review the PR diff with the code-review skill. Report findings with severity (important / pre_existing / nit) and file:line. If CI checks fail, read the failing logs (\`gh pr checks <n>\`, \`gh run view --log-failed\`) and fix the cause; if the branch conflicts with the base, bring the base in and resolve the conflicts carefully.
|
|
263
|
+
7. Fix only defects that are safe and in scope; push each round. Never force-push.
|
|
264
|
+
8. After every push, state what changed and the exact undo command (\`git revert <sha>\`).
|
|
265
|
+
9. Finish with: the PR URL, what was reviewed and fixed, and anything that needs a human decision.
|
|
266
|
+
|
|
267
|
+
Never merge, approve, or change branch protection. If a step fails, stop and name the step and its error. Do not claim a step succeeded unless its command exited 0.`
|
|
268
|
+
|
|
269
|
+
const notes = [
|
|
270
|
+
onDefault
|
|
271
|
+
? 'On the default branch — Claude will create a feature branch before committing.'
|
|
272
|
+
: '',
|
|
273
|
+
c.gh ? '' : 'gh not found — Claude will stop after pushing; no PR will be opened.',
|
|
274
|
+
].filter(Boolean)
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
content: notes.length ? `${header}\n\n${notes.map((n) => `• ${n}`).join('\n')}` : header,
|
|
278
|
+
forwardToAI,
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** `gh --version` with a short bound; a hung binary must not hang the command. */
|
|
283
|
+
async function commandExists(command: string): Promise<boolean> {
|
|
284
|
+
try {
|
|
285
|
+
const proc = Bun.spawn([command, '--version'], { stdout: 'pipe', stderr: 'pipe' })
|
|
286
|
+
const exitCode = await Promise.race([
|
|
287
|
+
proc.exited,
|
|
288
|
+
new Promise<number>((resolve) => setTimeout(() => resolve(143), 2000)),
|
|
289
|
+
])
|
|
290
|
+
if (exitCode === 143) {
|
|
291
|
+
proc.kill()
|
|
292
|
+
return false
|
|
293
|
+
}
|
|
294
|
+
return exitCode === 0
|
|
295
|
+
} catch {
|
|
296
|
+
return false
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const shipCmd: CommandHandler = async (_ctx, args) => {
|
|
301
|
+
try {
|
|
302
|
+
// `git()` maps every failure to '', so "not a repository" and "detached
|
|
303
|
+
// HEAD" would otherwise print the same thing. Ask explicitly.
|
|
304
|
+
const inside = await git(['rev-parse', '--is-inside-work-tree'], 3000)
|
|
305
|
+
if (inside !== 'true') {
|
|
306
|
+
return {
|
|
307
|
+
content: '── Ship ──\n\nNot a git repository. Run /ship from a repository checkout.',
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const branch = await git(['branch', '--show-current'], 3000)
|
|
311
|
+
const remote = await git(['remote', 'show', 'origin'], 3000)
|
|
312
|
+
const defaultBranch = remote.match(/HEAD branch:\s*(\S+)/)?.[1] || 'main'
|
|
313
|
+
|
|
314
|
+
const [stagedRaw, unstagedRaw, untrackedRaw, aheadRaw] = await Promise.all([
|
|
315
|
+
git(['diff', '--cached', '--name-only'], 3000),
|
|
316
|
+
git(['diff', '--name-only'], 3000),
|
|
317
|
+
git(['ls-files', '--others', '--exclude-standard'], 3000),
|
|
318
|
+
branch ? git(['rev-list', '--count', `origin/${branch}..HEAD`], 3000) : Promise.resolve(''),
|
|
319
|
+
])
|
|
320
|
+
|
|
321
|
+
const count = (s: string): number => s.split('\n').filter(Boolean).length
|
|
322
|
+
|
|
323
|
+
return buildShipPlan({
|
|
324
|
+
branch,
|
|
325
|
+
defaultBranch,
|
|
326
|
+
staged: count(stagedRaw),
|
|
327
|
+
unstaged: count(unstagedRaw),
|
|
328
|
+
untracked: count(untrackedRaw),
|
|
329
|
+
ahead: aheadRaw || '0',
|
|
330
|
+
gh: await commandExists('gh'),
|
|
331
|
+
args: args.join(' ').trim(),
|
|
332
|
+
})
|
|
333
|
+
} catch {
|
|
334
|
+
return {
|
|
335
|
+
content: '── Ship ──\n\nCould not inspect the repository. Are you in a git repository?',
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
192
340
|
// ═══════════════════════════════════════════════════════════════
|
|
193
341
|
// Code Quality — bridge slash commands to skills (Claude Code parity)
|
|
194
342
|
// ═══════════════════════════════════════════════════════════════
|
package/src/core/engine.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
ContentBlock,
|
|
10
10
|
} from '../shared/index.ts'
|
|
11
11
|
import { ProviderRegistry } from '../providers/registry'
|
|
12
|
+
import { UNNAMED_TOOL_CALL } from '../shared/constants'
|
|
12
13
|
import { createAwakeTimer } from '../providers/fetch-utils'
|
|
13
14
|
import type { ChatRequest } from '../providers/registry'
|
|
14
15
|
import type { Llm } from '../providers/llm'
|
|
@@ -832,6 +833,9 @@ export class QueryEngine {
|
|
|
832
833
|
let assistantContent = ''
|
|
833
834
|
let reasoningContent = ''
|
|
834
835
|
let thinkingContent = ''
|
|
836
|
+
// 本轮为什么被截断。`'max_tokens'` 可续写,`'connection'`/未知不可 —— 见
|
|
837
|
+
// `continueMaxTokensTurn`。
|
|
838
|
+
let truncationCause: 'max_tokens' | 'connection' | undefined
|
|
835
839
|
let turnApiInputTokens = 0
|
|
836
840
|
let turnApiOutputTokens = 0
|
|
837
841
|
const turnStart = Date.now()
|
|
@@ -859,6 +863,7 @@ export class QueryEngine {
|
|
|
859
863
|
reasoningContent = ''
|
|
860
864
|
thinkingContent = ''
|
|
861
865
|
toolUses.length = 0
|
|
866
|
+
truncationCause = undefined
|
|
862
867
|
// Usage is part of "everything": a provider reports tokens as the
|
|
863
868
|
// stream runs, so the attempt that failed had already added its
|
|
864
869
|
// share before `restart` arrived. Keeping it charges the retried
|
|
@@ -904,6 +909,25 @@ export class QueryEngine {
|
|
|
904
909
|
turnApiInputTokens += chunk.inputTokens
|
|
905
910
|
turnApiOutputTokens += chunk.outputTokens || 0
|
|
906
911
|
}
|
|
912
|
+
|
|
913
|
+
if (chunk.type === 'stop' && chunk.truncated) {
|
|
914
|
+
// Absent cause = the provider cannot tell; treat it as a connection cut.
|
|
915
|
+
truncationCause = chunk.truncationCause ?? 'connection'
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// Output-limit cut: ask once for the rest, then commit the joined text.
|
|
920
|
+
// Only when nothing else already ended the round — a cut with tool calls
|
|
921
|
+
// pending has a half-formed call, and a hit budget has its own notice.
|
|
922
|
+
if (truncationCause === 'max_tokens' && !budget.hit && !signal?.aborted) {
|
|
923
|
+
if (toolUses.length === 0 && assistantContent) {
|
|
924
|
+
yield { type: 'warning', content: t('errors.turn_continuing') }
|
|
925
|
+
const acc = { text: assistantContent, reasoning: reasoningContent }
|
|
926
|
+
yield* this.continueMaxTokensTurn(messages, systemPrompt, acc, budget, signal)
|
|
927
|
+
assistantContent = acc.text
|
|
928
|
+
} else {
|
|
929
|
+
yield { type: 'warning', content: t('errors.turn_truncated_limit') }
|
|
930
|
+
}
|
|
907
931
|
}
|
|
908
932
|
|
|
909
933
|
// Commit the assistant turn **once, after the stream** — not on each `stop`
|
|
@@ -1304,6 +1328,7 @@ export class QueryEngine {
|
|
|
1304
1328
|
let assistantContent = ''
|
|
1305
1329
|
let reasoningContent = ''
|
|
1306
1330
|
let thinkingContent = ''
|
|
1331
|
+
let truncationCause: 'max_tokens' | 'connection' | undefined
|
|
1307
1332
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
1308
1333
|
|
|
1309
1334
|
try {
|
|
@@ -1325,6 +1350,7 @@ export class QueryEngine {
|
|
|
1325
1350
|
reasoningContent = ''
|
|
1326
1351
|
thinkingContent = ''
|
|
1327
1352
|
toolUses.length = 0
|
|
1353
|
+
truncationCause = undefined
|
|
1328
1354
|
}
|
|
1329
1355
|
if (chunk.type === 'error') return
|
|
1330
1356
|
if (chunk.type === 'text' && chunk.content) {
|
|
@@ -1348,6 +1374,10 @@ export class QueryEngine {
|
|
|
1348
1374
|
input: chunk.toolUse.input,
|
|
1349
1375
|
})
|
|
1350
1376
|
}
|
|
1377
|
+
|
|
1378
|
+
if (chunk.type === 'stop' && chunk.truncated) {
|
|
1379
|
+
truncationCause = chunk.truncationCause ?? 'connection'
|
|
1380
|
+
}
|
|
1351
1381
|
}
|
|
1352
1382
|
} catch (err) {
|
|
1353
1383
|
if (isAbortError(err)) {
|
|
@@ -1373,6 +1403,18 @@ export class QueryEngine {
|
|
|
1373
1403
|
return
|
|
1374
1404
|
}
|
|
1375
1405
|
|
|
1406
|
+
// Output-limit cut — same bounded continuation as the first round.
|
|
1407
|
+
if (truncationCause === 'max_tokens' && !budget.hit && !signal?.aborted) {
|
|
1408
|
+
if (toolUses.length === 0 && assistantContent) {
|
|
1409
|
+
yield { type: 'warning', content: t('errors.turn_continuing') }
|
|
1410
|
+
const acc = { text: assistantContent, reasoning: reasoningContent }
|
|
1411
|
+
yield* this.continueMaxTokensTurn(messages, systemPrompt, acc, budget, signal)
|
|
1412
|
+
assistantContent = acc.text
|
|
1413
|
+
} else {
|
|
1414
|
+
yield { type: 'warning', content: t('errors.turn_truncated_limit') }
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1376
1418
|
if (assistantContent || reasoningContent || thinkingContent) {
|
|
1377
1419
|
const contentBlocks: import('../shared/types').ContentBlock[] = []
|
|
1378
1420
|
if (thinkingContent) {
|
|
@@ -1476,6 +1518,20 @@ export class QueryEngine {
|
|
|
1476
1518
|
getMetrics().toolCalls.inc({ tool_name: name })
|
|
1477
1519
|
const tool = this.tools.get(name)
|
|
1478
1520
|
if (!tool) {
|
|
1521
|
+
// A provider that sends a tool call with no name is not a tool lookup
|
|
1522
|
+
// failure the model can guess its way out of. Say what happened; the
|
|
1523
|
+
// result goes back as a normal tool_result, so the turn continues and the
|
|
1524
|
+
// model can re-issue the call (331-038).
|
|
1525
|
+
if (name === UNNAMED_TOOL_CALL) {
|
|
1526
|
+
return {
|
|
1527
|
+
success: false,
|
|
1528
|
+
content: '',
|
|
1529
|
+
error:
|
|
1530
|
+
'The provider returned a tool call with no name, so the call was not dispatched. ' +
|
|
1531
|
+
'Re-issue the call with a tool name and its arguments.',
|
|
1532
|
+
notRun: true,
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1479
1535
|
// P2-4: Provide a more helpful error for unavailable tools
|
|
1480
1536
|
const isMcpTool = name.startsWith('mcp__')
|
|
1481
1537
|
const hint = isMcpTool
|
|
@@ -1692,12 +1748,18 @@ export class QueryEngine {
|
|
|
1692
1748
|
}
|
|
1693
1749
|
|
|
1694
1750
|
private getToolDefinitions(): Record<string, unknown>[] {
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
|
|
1751
|
+
// A tool named by a bare deny rule can never run, so it must not be offered:
|
|
1752
|
+
// the model sees a tool it can call, calls it, and the gate refuses — every
|
|
1753
|
+
// time. Input-scoped rules (`Bash(rm:*)`) are NOT filtered here; they deny
|
|
1754
|
+
// some invocations, and the tool itself is still usable.
|
|
1755
|
+
return Array.from(this.tools.values())
|
|
1756
|
+
.filter((t) => !this.permission.isToolNameDenied(t.name))
|
|
1757
|
+
.map((t) => ({
|
|
1758
|
+
name: t.name,
|
|
1759
|
+
description: t.description,
|
|
1760
|
+
parameters: t.parameters,
|
|
1761
|
+
input_schema: t.parameters, // Anthropic-style naming
|
|
1762
|
+
}))
|
|
1701
1763
|
}
|
|
1702
1764
|
|
|
1703
1765
|
getContext(): ContextManager {
|
|
@@ -1740,7 +1802,11 @@ export class QueryEngine {
|
|
|
1740
1802
|
*/
|
|
1741
1803
|
private async *llmChat(req: ChatRequest): AsyncGenerator<StreamChunk> {
|
|
1742
1804
|
for await (const chunk of (this.llm ?? this.registry).chat(req)) {
|
|
1743
|
-
if (chunk.type === 'stop' && chunk.truncated) {
|
|
1805
|
+
if (chunk.type === 'stop' && chunk.truncated && chunk.truncationCause !== 'max_tokens') {
|
|
1806
|
+
// An output-limit cut is handled by the caller: it may continue the turn
|
|
1807
|
+
// (`continueMaxTokensTurn`), and then "check your proxy/VPN" would be
|
|
1808
|
+
// both alarming and wrong. Connection cuts have no recovery — this is
|
|
1809
|
+
// the only place that says so.
|
|
1744
1810
|
yield { type: 'warning', content: t('errors.turn_truncated') }
|
|
1745
1811
|
}
|
|
1746
1812
|
if (chunk.type === 'stop' && chunk.refusal) {
|
|
@@ -1754,6 +1820,65 @@ export class QueryEngine {
|
|
|
1754
1820
|
}
|
|
1755
1821
|
}
|
|
1756
1822
|
|
|
1823
|
+
/**
|
|
1824
|
+
* 有界续写:一轮因**输出上限**(`max_tokens`)被切断后,追问一次「接着写」。
|
|
1825
|
+
*
|
|
1826
|
+
* 只续一次,且只由调用方在「没有工具调用、没有撞上回合预算、未被中断」时调用。
|
|
1827
|
+
* 连接中断**不**续:那里没有「接着写」可言,重发只会让模型把同一段残句重写一遍。
|
|
1828
|
+
*
|
|
1829
|
+
* 续写的正文并进**同一个** assistant 消息(`acc.text`),而不是再提交一条 ——
|
|
1830
|
+
* 否则历史里会出现两条连续的 assistant 消息,渲染成两个气泡,而用户看到的
|
|
1831
|
+
* 明明是一段话。
|
|
1832
|
+
*/
|
|
1833
|
+
private async *continueMaxTokensTurn(
|
|
1834
|
+
messages: import('../shared/types').Message[],
|
|
1835
|
+
systemPrompt: string,
|
|
1836
|
+
acc: { text: string; reasoning: string },
|
|
1837
|
+
budget: TurnBudget,
|
|
1838
|
+
signal?: AbortSignal,
|
|
1839
|
+
): AsyncGenerator<StreamChunk> {
|
|
1840
|
+
const continuation: import('../shared/types').Message[] = [
|
|
1841
|
+
...messages,
|
|
1842
|
+
{ role: 'assistant', content: acc.text },
|
|
1843
|
+
{ role: 'user', content: t('errors.continuation_prompt') },
|
|
1844
|
+
]
|
|
1845
|
+
let added = ''
|
|
1846
|
+
let cutAgain = false
|
|
1847
|
+
try {
|
|
1848
|
+
for await (const chunk of this.streamUnderTurnBudget(budget, signal, (innerSignal) =>
|
|
1849
|
+
// No tools on a continuation: this request asks the model to *finish the
|
|
1850
|
+
// sentence*, and a tool call produced here would have no execution path
|
|
1851
|
+
// (the round's tool loop has already ended) — it would render as a call
|
|
1852
|
+
// that silently never runs.
|
|
1853
|
+
this.chatWithFallback(continuation, systemPrompt, undefined, innerSignal),
|
|
1854
|
+
)) {
|
|
1855
|
+
yield chunk
|
|
1856
|
+
// A retried continuation re-streams: drop what the failed attempt added.
|
|
1857
|
+
if (chunk.restart) {
|
|
1858
|
+
added = ''
|
|
1859
|
+
continue
|
|
1860
|
+
}
|
|
1861
|
+
if (chunk.type === 'error') return
|
|
1862
|
+
if (chunk.type === 'text' && chunk.content) {
|
|
1863
|
+
added += chunk.content
|
|
1864
|
+
this.context.recordChunk(chunk.content)
|
|
1865
|
+
}
|
|
1866
|
+
if (chunk.type === 'stop' && chunk.truncated && chunk.truncationCause === 'max_tokens') {
|
|
1867
|
+
cutAgain = true
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
} catch (err) {
|
|
1871
|
+
acc.text += added
|
|
1872
|
+
if (isAbortError(err)) return
|
|
1873
|
+
yield { type: 'error', error: String(err) }
|
|
1874
|
+
return
|
|
1875
|
+
}
|
|
1876
|
+
acc.text += added
|
|
1877
|
+
// Bounded: a second ceiling hit ends the turn. Say it plainly — the user is
|
|
1878
|
+
// looking at text that stops mid-sentence.
|
|
1879
|
+
if (cutAgain) yield { type: 'warning', content: t('errors.turn_truncated_limit') }
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1757
1882
|
/**
|
|
1758
1883
|
* Stream a chat response with graceful provider fallback (v2.1.229 alignment).
|
|
1759
1884
|
*
|
|
@@ -148,7 +148,17 @@ function parseHookStdoutFields(stdout: string | null | undefined, _ctx: HookCont
|
|
|
148
148
|
if (decision === 'ask') {
|
|
149
149
|
// The engine stops the call on `ask` and prints `reason`, so the hook's
|
|
150
150
|
// `permissionDecisionReason` is the only place its explanation can land.
|
|
151
|
-
|
|
151
|
+
// `updatedInput` travels too even though this CLI treats `ask` as a hard
|
|
152
|
+
// refusal: the gate reports that a rewrite was *proposed and discarded*,
|
|
153
|
+
// which is information the operator can act on. Dropping it here made the
|
|
154
|
+
// hook's rewrite invisible rather than unexecutable.
|
|
155
|
+
return {
|
|
156
|
+
allowed: true,
|
|
157
|
+
permissionDecision: 'ask',
|
|
158
|
+
reason,
|
|
159
|
+
additionalContext,
|
|
160
|
+
modifiedInput: updatedInput,
|
|
161
|
+
}
|
|
152
162
|
}
|
|
153
163
|
if (decision === 'defer') {
|
|
154
164
|
return { allowed: true, permissionDecision: 'defer', additionalContext }
|