@miphamai/cli 0.85.27 → 0.85.28

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 CHANGED
@@ -1,4 +1,4 @@
1
- # Mipham Code v0.85.27
1
+ # Mipham Code v0.85.28
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 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/bin/mipham.ts CHANGED
@@ -1193,38 +1193,6 @@ async function main() {
1193
1193
  throw err
1194
1194
  }
1195
1195
 
1196
- // ── Disable terminal special characters ──────────────────────────────────
1197
- // Terminal intercepts Ctrl+S (XOFF), Ctrl+T (SIGINFO/status), Ctrl+R (rprnt)
1198
- // before the app sees them. Disable these so Agent Dashboard shortcuts work.
1199
- // IMPORTANT: stty needs the real terminal on stdin — 'ignore' won't work.
1200
- const { execSync } = await import('node:child_process')
1201
- let savedStty = ''
1202
- try {
1203
- savedStty = execSync('stty -g', {
1204
- encoding: 'utf-8',
1205
- stdio: ['inherit', 'pipe', 'ignore'],
1206
- }).trim()
1207
- execSync('stty -ixon stop undef start undef status undef rprnt undef', {
1208
- stdio: ['inherit', 'ignore', 'ignore'],
1209
- })
1210
- } catch {
1211
- // Non-POSIX platform (Windows) — no special chars to disable
1212
- }
1213
- // Restore original terminal settings on exit
1214
- const restoreTerminal = () => {
1215
- if (!savedStty) return
1216
- try {
1217
- execSync(`stty ${savedStty}`, {
1218
- stdio: ['inherit', 'ignore', 'ignore'],
1219
- })
1220
- } catch {
1221
- /* ignore */
1222
- }
1223
- }
1224
- process.on('exit', restoreTerminal)
1225
- process.on('SIGINT', restoreTerminal)
1226
- process.on('SIGTERM', restoreTerminal)
1227
-
1228
1196
  // ── Version: build-time constant (bundled into the compiled binary) ──
1229
1197
  const { PACKAGE_NAME, PACKAGE_VERSION } = await import('../src/shared/package-info')
1230
1198
  const APP_VERSION = PACKAGE_VERSION
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.27",
3
+ "version": "0.85.28",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -11,7 +11,7 @@ import { PACKAGE_VERSION } from '../shared/index.ts'
11
11
  export const DEFAULT_CONFIG: MiphamConfig = {
12
12
  version: PACKAGE_VERSION,
13
13
  defaultProvider: 'deepseek',
14
- defaultModel: 'deepseek-v4-pro',
14
+ defaultModel: 'deepseek-v4-flash',
15
15
  permission: 'default',
16
16
  showThinking: 'off',
17
17
  showSchedulingNotices: false,
@@ -9,6 +9,7 @@ import type {
9
9
  ContentBlock,
10
10
  } from '../shared/index.ts'
11
11
  import { ProviderRegistry } from '../providers/registry'
12
+ import { createAwakeTimer } from '../providers/fetch-utils'
12
13
  import type { ChatRequest } from '../providers/registry'
13
14
  import type { Llm } from '../providers/llm'
14
15
  import { ContextManager } from './context'
@@ -80,6 +81,23 @@ const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as Translat
80
81
  */
81
82
  const MAX_TOOL_TURNS = 100
82
83
 
84
+ /**
85
+ * How long a turn may go without producing anything it can act on (a text
86
+ * delta, a tool call, a tool result) before it is declared stalled.
87
+ *
88
+ * Measured against `performance.now()`, which is monotonic and does *not*
89
+ * advance while the machine is suspended: a laptop that sleeps mid-turn would
90
+ * otherwise wake up to "no activity for 8 hours" and kill a turn that was never
91
+ * stalled.
92
+ */
93
+ const TURN_TIMEOUT_MS = 15 * 60 * 1000
94
+
95
+ /** The turn's stall clock: when it last moved, and whether it ran out. */
96
+ interface TurnBudget {
97
+ last: number
98
+ hit: boolean
99
+ }
100
+
83
101
  /**
84
102
  * Drop inbound messages whose timestamp is older than the dialog-expiry TTL.
85
103
  * A stale message's approval dialog is no longer relevant, so it's discarded
@@ -760,13 +778,17 @@ export class QueryEngine {
760
778
  const turnStart = Date.now()
761
779
  const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
762
780
 
763
- // Stream model response
781
+ // Stream model response — under the same turn budget the continuation rounds
782
+ // use, so the *first* request of a turn cannot outlive it either.
783
+ const budget: TurnBudget = { last: performance.now(), hit: false }
764
784
  try {
765
- for await (const chunk of this.chatWithFallback(
766
- messages,
767
- systemPrompt,
768
- toolDefs.length > 0 ? toolDefs : undefined,
769
- signal,
785
+ for await (const chunk of this.streamUnderTurnBudget(budget, signal, (innerSignal) =>
786
+ this.chatWithFallback(
787
+ messages,
788
+ systemPrompt,
789
+ toolDefs.length > 0 ? toolDefs : undefined,
790
+ innerSignal,
791
+ ),
770
792
  )) {
771
793
  yield chunk
772
794
 
@@ -871,6 +893,11 @@ export class QueryEngine {
871
893
  return
872
894
  }
873
895
 
896
+ // The round was cut short by the turn budget. The partial answer is already
897
+ // committed above; the warning and `stop` are already on the wire, so nothing
898
+ // may follow them — least of all a tool call from an interrupted round.
899
+ if (budget.hit) return
900
+
874
901
  // Record the provider's cached prefix (all messages except the newest)
875
902
  // for cache-aware microcompaction.
876
903
  if (messages.length >= 2) {
@@ -1079,6 +1106,77 @@ export class QueryEngine {
1079
1106
  }
1080
1107
  }
1081
1108
 
1109
+ /**
1110
+ * Stream one model round under the turn's stall budget — and *interrupt* it
1111
+ * when the budget runs out.
1112
+ *
1113
+ * The budget used to be a plain `if` at the top of the round loop, so it could
1114
+ * only ever fire *between* rounds. A request that never returns — no error, no
1115
+ * read timeout, nothing — therefore had nothing above it, and the turn waited
1116
+ * forever with the user looking at a spinner. Nothing below this layer bounds
1117
+ * it either: the provider's read timeout measures socket silence, and a
1118
+ * gateway that keeps the socket warm defeats it.
1119
+ *
1120
+ * A stalled round is not a failure: it is the same `stop` the user's own
1121
+ * Ctrl+C produces, preceded by a warning that says which wait ran out. So the
1122
+ * caller keeps its existing abort handling untouched.
1123
+ */
1124
+ private async *streamUnderTurnBudget(
1125
+ budget: TurnBudget,
1126
+ signal: AbortSignal | undefined,
1127
+ run: (signal?: AbortSignal) => AsyncGenerator<StreamChunk>,
1128
+ ): AsyncGenerator<StreamChunk> {
1129
+ const expired = new AbortController()
1130
+ let cancelTimer: (() => void) | undefined
1131
+ const arm = (): void => {
1132
+ cancelTimer?.()
1133
+ const remainingMs = Math.max(0, budget.last + TURN_TIMEOUT_MS - performance.now())
1134
+ cancelTimer = createAwakeTimer(remainingMs, () => {
1135
+ budget.hit = true
1136
+ // Abort rather than merely stop reading: the request is what has to be
1137
+ // let go of, or every stalled round leaves a socket behind.
1138
+ expired.abort()
1139
+ })
1140
+ }
1141
+ const effectiveSignal = signal ? AbortSignal.any([signal, expired.signal]) : expired.signal
1142
+
1143
+ const stalled: StreamChunk[] = [
1144
+ {
1145
+ type: 'warning',
1146
+ content: t('errors.turn_timeout', {
1147
+ minutes: String(Math.round(TURN_TIMEOUT_MS / 60000)),
1148
+ }),
1149
+ },
1150
+ { type: 'stop' },
1151
+ ]
1152
+
1153
+ arm()
1154
+ try {
1155
+ for await (const chunk of run(effectiveSignal)) {
1156
+ // The same set the round loops call "activity": something the turn can
1157
+ // act on. A stream that is merely alive never produces one of these.
1158
+ if (chunk.type === 'text' || chunk.type === 'thinking' || chunk.type === 'tool_use') {
1159
+ budget.last = performance.now()
1160
+ arm()
1161
+ }
1162
+ yield chunk
1163
+ }
1164
+ } catch (err) {
1165
+ // A real failure still wins: only the abort *this* timer caused is turned
1166
+ // into a stall, or a provider error that happens to land at the deadline
1167
+ // would be reported as "took too long".
1168
+ if (!budget.hit || !isAbortError(err)) throw err
1169
+ for (const chunk of stalled) yield chunk
1170
+ return
1171
+ } finally {
1172
+ cancelTimer?.()
1173
+ }
1174
+
1175
+ // The request ended at the same moment the budget did. The warning still
1176
+ // belongs on screen — otherwise the turn looks like it finished normally.
1177
+ if (budget.hit) for (const chunk of stalled) yield chunk
1178
+ }
1179
+
1082
1180
  private async *continueWithTools(
1083
1181
  signal?: AbortSignal,
1084
1182
  roundsLeft: number = MAX_TOOL_TURNS,
@@ -1086,19 +1184,15 @@ export class QueryEngine {
1086
1184
  // Task-level stall guard: a turn that produces no text or tool result for
1087
1185
  // this long is considered stalled and stopped (prevents ~40-min idle spins).
1088
1186
  //
1089
- // The clock is `performance.now()` (monotonic, and it does not advance while
1090
- // the machine is suspended) rather than `Date.now()` (wall clock). A laptop
1091
- // that sleeps mid-turn jumps the wall clock forward by the whole nap, which
1092
- // reads as "no activity for 8 hours" and kills a turn that was never stalled
1093
- // — the failure shows up as a spurious timeout, exactly when the user
1094
- // returns to their desk.
1095
- const TURN_TIMEOUT_MS = 15 * 60 * 1000
1096
- const monotonicNow = (): number => performance.now()
1097
- let lastActivity = monotonicNow()
1187
+ // Two places enforce it, because they see different moments: this check
1188
+ // covers the gap *between* rounds, and `streamUnderTurnBudget` covers a round
1189
+ // that is still in flight. Keeping only this one is what let a hung request
1190
+ // wait without any bound at all.
1191
+ const budget: TurnBudget = { last: performance.now(), hit: false }
1098
1192
  const toolDefs = this.getToolDefinitions()
1099
1193
 
1100
1194
  for (let turn = 0; turn < roundsLeft; turn++) {
1101
- if (monotonicNow() - lastActivity > TURN_TIMEOUT_MS) {
1195
+ if (performance.now() - budget.last > TURN_TIMEOUT_MS) {
1102
1196
  yield {
1103
1197
  type: 'warning',
1104
1198
  content: t('errors.turn_timeout', {
@@ -1139,11 +1233,13 @@ export class QueryEngine {
1139
1233
  const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
1140
1234
 
1141
1235
  try {
1142
- for await (const chunk of this.chatWithFallback(
1143
- messages,
1144
- systemPrompt,
1145
- toolDefs.length > 0 ? toolDefs : undefined,
1146
- signal,
1236
+ for await (const chunk of this.streamUnderTurnBudget(budget, signal, (innerSignal) =>
1237
+ this.chatWithFallback(
1238
+ messages,
1239
+ systemPrompt,
1240
+ toolDefs.length > 0 ? toolDefs : undefined,
1241
+ innerSignal,
1242
+ ),
1147
1243
  )) {
1148
1244
  yield chunk
1149
1245
 
@@ -1160,7 +1256,7 @@ export class QueryEngine {
1160
1256
  if (chunk.type === 'text' && chunk.content) {
1161
1257
  assistantContent += chunk.content
1162
1258
  this.context.recordChunk(chunk.content)
1163
- lastActivity = monotonicNow()
1259
+ budget.last = performance.now()
1164
1260
  }
1165
1261
 
1166
1262
  if (chunk.reasoning_content) {
@@ -1219,6 +1315,10 @@ export class QueryEngine {
1219
1315
  this.context.addMessage(msg)
1220
1316
  }
1221
1317
 
1318
+ // The round was cut short by the turn budget: the partial answer is
1319
+ // committed above, and the warning + `stop` already ended the turn.
1320
+ if (budget.hit) return
1321
+
1222
1322
  // Safety: when max turns reached with pending tools, ask model to summarize
1223
1323
  if (turn === roundsLeft - 1 && toolUses.length > 0) {
1224
1324
  this.context.addMessage({
@@ -1260,7 +1360,7 @@ export class QueryEngine {
1260
1360
  for (const toolUse of toolUses) {
1261
1361
  const result = await this.executeTool(toolUse.name, toolUse.input, signal)
1262
1362
  if (!result.success) this.pendingToolFailure = true
1263
- lastActivity = monotonicNow()
1363
+ budget.last = performance.now()
1264
1364
  yield {
1265
1365
  type: 'tool_result',
1266
1366
  tool_use_id: toolUse.id,
@@ -57,6 +57,26 @@ export function stripSections(content: string, excluded: string[]): string {
57
57
  return out.join('\n')
58
58
  }
59
59
 
60
+ /**
61
+ * Strip the leading metadata blockquote — the `> **项目** / > **版本** / > **最后更新** …`
62
+ * header that precedes the first `##` section. These lines are document metadata for
63
+ * human readers (the model's identity and version come from MIPHAM.md and the
64
+ * provenance comment). Gated by the `prompt-exclude-header` frontmatter key — not by
65
+ * `prompt-exclude`, whose entries are title-exact and whose integrity guard rejects any
66
+ * entry that matches no heading.
67
+ */
68
+ export function stripLeadingBlockquote(content: string): string {
69
+ const lines = content.split('\n')
70
+ const out: string[] = []
71
+ let seenSection = false
72
+ for (const line of lines) {
73
+ if (!seenSection && /^##\s/.test(line)) seenSection = true
74
+ if (!seenSection && /^>\s/.test(line)) continue
75
+ out.push(line)
76
+ }
77
+ return out.join('\n')
78
+ }
79
+
60
80
  /** Normalize a `prompt-exclude` frontmatter value (YAML list or single string). */
61
81
  export function parsePromptExclude(value: unknown): string[] {
62
82
  if (Array.isArray(value)) return value.map((v) => String(v))
@@ -223,10 +243,10 @@ const LEVEL_LABELS: Record<string, string> = {
223
243
  */
224
244
  function instructionPartText(inst: InstructionFile): string | null {
225
245
  if (inst.privacy === 'private') return null
226
- const content = stripSections(
227
- inst.content,
228
- parsePromptExclude(inst.frontmatter['prompt-exclude']),
229
- )
246
+ let content = stripSections(inst.content, parsePromptExclude(inst.frontmatter['prompt-exclude']))
247
+ if (inst.frontmatter['prompt-exclude-header']) {
248
+ content = stripLeadingBlockquote(content)
249
+ }
230
250
  return `<!-- ${LEVEL_LABELS[inst.level] || inst.level} (${inst.path}) -->\n${content}`
231
251
  }
232
252
 
@@ -219,6 +219,14 @@ export class AnthropicProvider implements ProviderInstance {
219
219
  // passes aren't mistaken for a stalled connection.
220
220
  const STREAM_READ_TIMEOUT_MS = streamIdleTimeoutMs(req.effort)
221
221
 
222
+ // The budget restarts on *progress*, not on any byte. It used to be armed
223
+ // fresh for every `reader.read()`, and this API sends a `ping` event every
224
+ // ~30s on a long request — so the guard could never fire at all while the
225
+ // answer was still silent. Anything the answer can use advances the clock;
226
+ // `ping` is the API saying "still here", which is exactly the thing that
227
+ // must not count as progress.
228
+ let lastProgress = performance.now()
229
+
222
230
  // The read loop and the trailing stop share one reader, and that reader owns
223
231
  // the connection. `engine.ts` breaks out of this generator on the ordinary
224
232
  // `stop` chunk, and a sub-agent throws mid-stream on abort — both call
@@ -230,14 +238,16 @@ export class AnthropicProvider implements ProviderInstance {
230
238
  while (true) {
231
239
  let readResult: Awaited<ReturnType<typeof reader.read>>
232
240
  let cancelIdle: (() => void) | undefined
241
+ // What is left of the budget since the last frame the answer could use.
242
+ const remaining = Math.max(0, lastProgress + STREAM_READ_TIMEOUT_MS - performance.now())
233
243
  try {
234
244
  readResult = await Promise.race([
235
245
  reader.read(),
236
246
  new Promise<never>((_, reject) => {
237
- cancelIdle = createAwakeTimer(STREAM_READ_TIMEOUT_MS, () =>
247
+ cancelIdle = createAwakeTimer(remaining, () =>
238
248
  reject(
239
249
  new Error(
240
- `Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
250
+ `Stream read timeout — no progress for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
241
251
  ),
242
252
  ),
243
253
  )
@@ -264,6 +274,11 @@ export class AnthropicProvider implements ProviderInstance {
264
274
  try {
265
275
  const event = JSON.parse(data) as AnthropicSSEEvent
266
276
 
277
+ // Progress = an event whose payload the answer can use. `ping` carries
278
+ // nothing and arrives on a fixed schedule, so counting it would make
279
+ // the budget unreachable by construction.
280
+ if (event.type !== 'ping') lastProgress = performance.now()
281
+
267
282
  switch (event.type) {
268
283
  case 'content_block_start': {
269
284
  const cb = event.content_block
@@ -82,6 +82,12 @@ export class OpenAICompatProvider implements ProviderInstance {
82
82
  // (DeepSeek V4 / reasoning models) aren't mistaken for a stalled connection.
83
83
  const STREAM_READ_TIMEOUT_MS = streamIdleTimeoutMs(req.effort)
84
84
 
85
+ // The budget restarts on *progress*, not on any byte. It used to be armed
86
+ // fresh for every `reader.read()`, so a gateway that keeps the socket warm
87
+ // with SSE comment frames (`: keep-alive`) while the answer never starts fed
88
+ // the guard forever — no timeout, no error, the turn waits with no bound.
89
+ let lastProgress = performance.now()
90
+
85
91
  // The read loop and the fallback stop share one reader, and that reader owns
86
92
  // the connection. `engine.ts` breaks out of this generator on the ordinary
87
93
  // `stop` chunk, and a sub-agent throws mid-stream on abort — both call
@@ -93,14 +99,16 @@ export class OpenAICompatProvider implements ProviderInstance {
93
99
  while (true) {
94
100
  let readResult: Awaited<ReturnType<typeof reader.read>>
95
101
  let cancelIdle: (() => void) | undefined
102
+ // What is left of the budget since the last frame the answer could use.
103
+ const remaining = Math.max(0, lastProgress + STREAM_READ_TIMEOUT_MS - performance.now())
96
104
  try {
97
105
  readResult = await Promise.race([
98
106
  reader.read(),
99
107
  new Promise<never>((_, reject) => {
100
- cancelIdle = createAwakeTimer(STREAM_READ_TIMEOUT_MS, () =>
108
+ cancelIdle = createAwakeTimer(remaining, () =>
101
109
  reject(
102
110
  new Error(
103
- `Stream read timeout — no data for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
111
+ `Stream read timeout — no progress for ${Math.round(STREAM_READ_TIMEOUT_MS / 1000)}s`,
104
112
  ),
105
113
  ),
106
114
  )
@@ -172,6 +180,10 @@ export class OpenAICompatProvider implements ProviderInstance {
172
180
  return
173
181
  }
174
182
 
183
+ // Progress = a frame the answer can use: `choices` carries text /
184
+ // tool-call deltas / finish_reason, and `usage` only arrives from a
185
+ // server that is answering. Everything else is liveness, not progress.
186
+ if (choice || parsed.usage) lastProgress = performance.now()
175
187
  if (!choice) continue
176
188
 
177
189
  const delta = choice.delta
@@ -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.27' as const
12
+ export const PACKAGE_VERSION = '0.85.28' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` 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 = 4585 as const
93
+ export const TEST_COUNT = 4593 as const