@miphamai/cli 0.85.24 → 0.85.26

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.
Files changed (45) hide show
  1. package/README.md +3 -3
  2. package/bin/mipham.ts +34 -24
  3. package/package.json +1 -1
  4. package/src/agent/agent-context.ts +23 -3
  5. package/src/agent/sub-agent.ts +29 -15
  6. package/src/artifacts/server.ts +5 -1
  7. package/src/commands/git.ts +9 -1
  8. package/src/commands/project.ts +34 -17
  9. package/src/core/context-token.ts +55 -3
  10. package/src/core/context.ts +54 -42
  11. package/src/core/crsi-sandbox.ts +5 -1
  12. package/src/core/engine.ts +91 -10
  13. package/src/core/instructions.ts +130 -18
  14. package/src/core/permission-rule-ack.ts +67 -0
  15. package/src/core/permission-rules.ts +141 -25
  16. package/src/daemon/remote-engine.ts +11 -5
  17. package/src/daemon/schedule-manager.ts +32 -3
  18. package/src/daemon/server.ts +6 -0
  19. package/src/i18n-core/locales/en-US.json +1 -1
  20. package/src/i18n-core/locales/zh-CN.json +1 -1
  21. package/src/index.tsx +34 -4
  22. package/src/mcp/client.ts +37 -2
  23. package/src/mcp/http-transport.ts +20 -1
  24. package/src/mcp/protocol.ts +13 -5
  25. package/src/mcp/registry.ts +8 -3
  26. package/src/mcp/transport.ts +40 -3
  27. package/src/plugin/plugin-manager.ts +23 -2
  28. package/src/providers/anthropic.ts +3 -1
  29. package/src/providers/fetch-utils.ts +40 -6
  30. package/src/providers/openai-compat.ts +2 -1
  31. package/src/providers/registry.ts +23 -1
  32. package/src/shared/git-env.ts +18 -0
  33. package/src/shared/package-info.ts +3 -3
  34. package/src/shared/sanitize.ts +21 -0
  35. package/src/shared/types.ts +9 -0
  36. package/src/skills/loader.ts +14 -0
  37. package/src/tools/exec/bash.ts +168 -6
  38. package/src/tools/exec/enter-worktree.ts +26 -2
  39. package/src/tools/exec/task.ts +144 -21
  40. package/src/tools/network/web-fetch.ts +7 -7
  41. package/src/tools/network/web-search.ts +6 -5
  42. package/src/ui/app.tsx +22 -7
  43. package/src/ui/chat.tsx +3 -2
  44. package/src/ui/commands.ts +65 -5
  45. package/src/workflow/primitives/agent.ts +17 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
- # Mipham Code v0.85.24
1
+ # Mipham Code v0.85.26
2
2
 
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.
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
 
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
- - **137 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **138 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/bin/mipham.ts CHANGED
@@ -346,6 +346,22 @@ async function runUpdate(): Promise<boolean> {
346
346
  process.exit(0)
347
347
  }
348
348
 
349
+ /**
350
+ * One shape for "the daemon is not answering".
351
+ *
352
+ * Twelve call sites used to print the raw fetch error and exit. The error says
353
+ * what failed and nothing about what to do, and it is the same situation every
354
+ * time — so it gets one message: whether it is still running, and how to bring
355
+ * it back. (The config lives at a fixed `~/.mipham/daemon.pid`, i.e. there is
356
+ * exactly one daemon per user, so there is nothing to disambiguate between.)
357
+ */
358
+ function reportDaemonUnreachable(port: number, err: unknown): never {
359
+ console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
360
+ console.error('Check whether it is still running: mipham daemon status')
361
+ console.error('Start it again: mipham daemon start')
362
+ process.exit(1)
363
+ }
364
+
349
365
  // ── Daemon lifecycle commands ──────────────────────────────────────────────────
350
366
 
351
367
  async function runDaemonCLI(): Promise<boolean> {
@@ -386,6 +402,12 @@ async function runDaemonCLI(): Promise<boolean> {
386
402
  // process is confirmed gone; the old code printed it right after send().
387
403
  if (await terminateDaemonProcess(status.pid)) {
388
404
  console.log(`Daemon stopped (PID: ${status.pid})`)
405
+ // 说清楚这一刀的后果:在这个 daemon 里跑着的后台会话(含 attach 中的那些)
406
+ // 一起结束了。历史仍在库里 —— 重启 daemon 后重新 attach 即可接着用。
407
+ // 不写「会重启」:没有任何东西会替你重启它。
408
+ console.log(
409
+ 'Background sessions running in it have ended. Start it again with "mipham daemon start".',
410
+ )
389
411
  process.exit(0)
390
412
  }
391
413
  console.error(
@@ -507,8 +529,7 @@ async function runAttachCLI(): Promise<boolean> {
507
529
  sessions = data.data.sessions.filter((s) => s.status === 'active' || s.status === 'idle')
508
530
  }
509
531
  } catch (err) {
510
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
511
- process.exit(1)
532
+ reportDaemonUnreachable(port, err)
512
533
  }
513
534
 
514
535
  const latestFlag = args.includes('--latest')
@@ -630,8 +651,7 @@ async function runAgentCLI(): Promise<boolean> {
630
651
  }
631
652
  }
632
653
  } catch (err) {
633
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
634
- process.exit(1)
654
+ reportDaemonUnreachable(port, err)
635
655
  }
636
656
  process.exit(0)
637
657
  }
@@ -685,8 +705,7 @@ async function runAgentCLI(): Promise<boolean> {
685
705
  }
686
706
  console.log(`Message sent to agent ${agentId}`)
687
707
  } catch (err) {
688
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
689
- process.exit(1)
708
+ reportDaemonUnreachable(port, err)
690
709
  }
691
710
  process.exit(0)
692
711
  }
@@ -708,8 +727,7 @@ async function runAgentCLI(): Promise<boolean> {
708
727
  }
709
728
  console.log(`Agent ${agentId} stopped.`)
710
729
  } catch (err) {
711
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
712
- process.exit(1)
730
+ reportDaemonUnreachable(port, err)
713
731
  }
714
732
  process.exit(0)
715
733
  }
@@ -760,8 +778,7 @@ async function runAgentCLI(): Promise<boolean> {
760
778
  if (a.branch) console.log(` Branch: ${a.branch}`)
761
779
  if (a.prUrl) console.log(` PR: ${a.prUrl}`)
762
780
  } catch (err) {
763
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
764
- process.exit(1)
781
+ reportDaemonUnreachable(port, err)
765
782
  }
766
783
  process.exit(0)
767
784
  }
@@ -827,8 +844,7 @@ async function runGoalCLI(): Promise<boolean> {
827
844
  }
828
845
  }
829
846
  } catch (err) {
830
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
831
- process.exit(1)
847
+ reportDaemonUnreachable(port, err)
832
848
  }
833
849
  process.exit(0)
834
850
  }
@@ -866,8 +882,7 @@ async function runGoalCLI(): Promise<boolean> {
866
882
  }
867
883
  console.log(`Goal #${data.data!.id} created.`)
868
884
  } catch (err) {
869
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
870
- process.exit(1)
885
+ reportDaemonUnreachable(port, err)
871
886
  }
872
887
  process.exit(0)
873
888
  }
@@ -893,8 +908,7 @@ async function runGoalCLI(): Promise<boolean> {
893
908
  }
894
909
  console.log(`Goal #${goalId} marked as done.`)
895
910
  } catch (err) {
896
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
897
- process.exit(1)
911
+ reportDaemonUnreachable(port, err)
898
912
  }
899
913
  process.exit(0)
900
914
  }
@@ -920,8 +934,7 @@ async function runGoalCLI(): Promise<boolean> {
920
934
  }
921
935
  console.log(`Goal #${goalId} paused.`)
922
936
  } catch (err) {
923
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
924
- process.exit(1)
937
+ reportDaemonUnreachable(port, err)
925
938
  }
926
939
  process.exit(0)
927
940
  }
@@ -995,8 +1008,7 @@ async function runScheduleCLI(): Promise<boolean> {
995
1008
  }
996
1009
  }
997
1010
  } catch (err) {
998
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
999
- process.exit(1)
1011
+ reportDaemonUnreachable(port, err)
1000
1012
  }
1001
1013
  process.exit(0)
1002
1014
  }
@@ -1028,8 +1040,7 @@ async function runScheduleCLI(): Promise<boolean> {
1028
1040
  }
1029
1041
  console.log(`Schedule #${data.data!.id} created (cron: ${cronExpr}).`)
1030
1042
  } catch (err) {
1031
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
1032
- process.exit(1)
1043
+ reportDaemonUnreachable(port, err)
1033
1044
  }
1034
1045
  process.exit(0)
1035
1046
  }
@@ -1051,8 +1062,7 @@ async function runScheduleCLI(): Promise<boolean> {
1051
1062
  }
1052
1063
  console.log(`Schedule #${scheduleId} removed.`)
1053
1064
  } catch (err) {
1054
- console.error(`Failed to connect to daemon at port ${port}: ${String(err)}`)
1055
- process.exit(1)
1065
+ reportDaemonUnreachable(port, err)
1056
1066
  }
1057
1067
  process.exit(0)
1058
1068
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.24",
3
+ "version": "0.85.26",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -130,7 +130,27 @@ export function createAgentContext(
130
130
 
131
131
  context.setSystemPrompt(systemPrompt)
132
132
 
133
- // Scope tools
133
+ return { context, allowedTools: selectAgentTools(agentDef, toolRegistry), systemPrompt }
134
+ }
135
+
136
+ /**
137
+ * The tools an agent definition is allowed to use, read from the **current**
138
+ * registry.
139
+ *
140
+ * Exported because the answer is not a one-time fact: MCP servers connect in the
141
+ * background, so a sub-agent that started early would otherwise be pinned to the
142
+ * tool table of the moment it started, and a server that finished connecting a
143
+ * second later could never be used by it — even though calling the tool would
144
+ * have worked (`sub-agent.ts` resolves each call against the live registry).
145
+ *
146
+ * `warnOnEmpty` is for the repeat callers: the warning is worth printing once
147
+ * per run, not once per turn.
148
+ */
149
+ export function selectAgentTools(
150
+ agentDef: AgentDefinition,
151
+ toolRegistry: Map<string, ToolDefinition>,
152
+ warnOnEmpty = true,
153
+ ): ToolDefinition[] {
134
154
  let allowedTools = Array.from(toolRegistry.values())
135
155
 
136
156
  if (agentDef.tools) {
@@ -148,7 +168,7 @@ export function createAgentContext(
148
168
  allowedTools = allowedTools.filter(
149
169
  (t) => allowSet.has(t.name) || serverPrefixes.some((p) => t.name.startsWith(p)),
150
170
  )
151
- if (allowedTools.length === 0) {
171
+ if (allowedTools.length === 0 && warnOnEmpty) {
152
172
  process.stderr.write(
153
173
  `⚠️ Agent "${agentDef.name}": tools list (${allowRules.join(', ')}) matched no registered tool — the agent will run without tools.\n`,
154
174
  )
@@ -165,5 +185,5 @@ export function createAgentContext(
165
185
  allowedTools = allowedTools.filter((t) => !denySet.has(t.name))
166
186
  }
167
187
 
168
- return { context, allowedTools, systemPrompt }
188
+ return allowedTools
169
189
  }
@@ -2,7 +2,7 @@ import type { ProviderRegistry } from '../providers/registry'
2
2
  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
- import { createAgentContext } from './agent-context'
5
+ import { createAgentContext, selectAgentTools } from './agent-context'
6
6
  import { shrinkAgentMessages } from './auto-compact'
7
7
  import { getBackgroundAgentRegistry } from './background-registry'
8
8
  import { formatInboundMessage, getMessageBus } from './message-bus'
@@ -390,11 +390,11 @@ export class SubAgent {
390
390
  ? Math.min(declaredWindow, contextWindow ?? declaredWindow)
391
391
  : undefined
392
392
  // 这一份**已含 agent memory**,是发出去的那个提示的唯一来源。
393
- const {
394
- context,
395
- allowedTools,
396
- systemPrompt: composedSystemPrompt,
397
- } = createAgentContext(resolvedDef, this.toolRegistry, compactWindow ?? contextWindow)
393
+ const { context, systemPrompt: composedSystemPrompt } = createAgentContext(
394
+ resolvedDef,
395
+ this.toolRegistry,
396
+ compactWindow ?? contextWindow,
397
+ )
398
398
 
399
399
  // 别再 `context.setSystemPrompt(systemPrompt)`:`createAgentContext` 已经拿**含记忆**的
400
400
  // 那一份设过上下文,这里用裸提示再设一遍只会把记忆从上下文里抹掉,而请求读的又不是
@@ -417,15 +417,10 @@ export class SubAgent {
417
417
  context.addMessage({ role: 'user', content: opening })
418
418
 
419
419
  const messages = context.getMessages()
420
- const toolDefs =
421
- allowedTools.length > 0
422
- ? allowedTools.map((t) => ({
423
- name: t.name,
424
- description: t.description,
425
- parameters: t.parameters,
426
- input_schema: t.parameters,
427
- }))
428
- : undefined
420
+ // 广告出去的工具表**每轮**从 registry 现算(见下面 `tools: toolDefs` 前那一段),
421
+ // 不在这里采一次:MCP server 是启动后在后台连的,这一刻的快照会让晚一秒连上的
422
+ // 工具永远进不了这个子代理 —— 而调用本身其实是通的(每轮按 `tu.name` 读的是
423
+ // **当前** registry)。声明与执行必须读同一个事实。
429
424
 
430
425
  const chunks: string[] = []
431
426
  const MAX_TOOL_TURNS = options.maxTurns || 5
@@ -493,6 +488,10 @@ export class SubAgent {
493
488
  // synchronous (see `resolveRunInBackground`). Set on the shared literal so it
494
489
  // covers the synchronous *and* background runs — both go through here.
495
490
  isSubAgent: true,
491
+ // Tools that keep per-session state (the Task list) must file it under the
492
+ // session this work belongs to, not under the literal 'sub-agent' — that
493
+ // one bucket is shared by every nested call from every session.
494
+ parentSessionId: options.toolContext?.sessionId,
496
495
  // A name a peer can hold onto. `sessionId` is the literal 'sub-agent' for
497
496
  // every sub-agent, so `SendMessage` had nothing stable to put on the
498
497
  // envelope and minted `sub-agent-<ms>` afresh per message — two messages
@@ -545,6 +544,21 @@ export class SubAgent {
545
544
  // nothing downstream could tell that from a finished one.
546
545
  let turnTruncated = false
547
546
 
547
+ // Per turn: an MCP server that finished connecting while this turn was
548
+ // running must be usable in the next one. Reading the registry here (and
549
+ // the same registry below when resolving `tu.name`) keeps the advertised
550
+ // list and the executable set from drifting apart.
551
+ const allowedNow = selectAgentTools(resolvedDef, this.toolRegistry, false)
552
+ const toolDefs =
553
+ allowedNow.length > 0
554
+ ? allowedNow.map((t) => ({
555
+ name: t.name,
556
+ description: t.description,
557
+ parameters: t.parameters,
558
+ input_schema: t.parameters,
559
+ }))
560
+ : undefined
561
+
548
562
  for await (const chunk of (this.llm ?? this.registry).chat({
549
563
  model: finalModel,
550
564
  messages: currentMessages,
@@ -124,7 +124,11 @@ export class ArtifactServer {
124
124
  socket.on('close', () => this.sockets.delete(socket))
125
125
  })
126
126
  srv.on('error', reject)
127
- srv.listen(port, () => {
127
+ // Loopback only. Without a host argument `listen()` binds **every**
128
+ // interface, so any artifact — including whatever the model just wrote —
129
+ // would be readable by the whole LAN. The URLs we hand out are
130
+ // `http://localhost:…`, which resolves here either way.
131
+ srv.listen(port, '127.0.0.1', () => {
128
132
  this.server = srv
129
133
  resolve()
130
134
  })
@@ -8,11 +8,19 @@ import type { CommandHandler } from '../ui/commands.js'
8
8
 
9
9
  export { commitCmd, pushCmd, prCmd, issueCmd }
10
10
 
11
- /** Run a git command asynchronously — avoids blocking the TUI event loop. */
11
+ /**
12
+ * Run a git command asynchronously — avoids blocking the TUI event loop.
13
+ *
14
+ * `LC_ALL=C` is load-bearing for the callers that parse output: `git remote show
15
+ * origin` prints `HEAD branch:` / `HEAD 分支:` depending on the locale, and the
16
+ * English regex then quietly falls back to `main` on a machine whose git speaks
17
+ * Chinese. Forcing the C locale makes the text we match against fixed.
18
+ */
12
19
  async function git(args: string[], timeoutMs = 5000): Promise<string> {
13
20
  const proc = Bun.spawn(['git', ...args], {
14
21
  stdout: 'pipe',
15
22
  stderr: 'pipe',
23
+ env: { ...process.env, LC_ALL: 'C', LANG: 'C' },
16
24
  })
17
25
  const exitCode = await Promise.race([
18
26
  proc.exited,
@@ -889,24 +889,30 @@ For help at any time: /help`,
889
889
  }
890
890
  }
891
891
 
892
+ // `/add-dir` 从前会回「✓ Directory registered」并把 `.mipham/config.yml` 的
893
+ // `workspace.extraDirs` 当兑现方式 —— 而那个键全仓**零读者**,命令本身也没有
894
+ // 任何状态可供后续工具查询。一句话:广告的能力没有落点。
895
+ //
896
+ // 现在它只做两件真事:校验路径存在,并如实说明访问实际由什么决定。删掉命令是
897
+ // 更省事的做法,但 `/add-dir` 是用户会去敲的名字 —— 让它给出**错的**答案,比留下
898
+ // 一个说真话的入口更坏。
892
899
  const addDirCmd: CommandHandler = async (_ctx, args) => {
893
900
  const dir = args[0]
894
901
  if (!dir) {
895
902
  return {
896
903
  content: `Usage: /add-dir <path>
897
904
 
898
- Add a directory to Mipham Code's allowed workspace paths.
899
- This grants the AI permission to read/write files in that directory.
905
+ Check a path and show how file access to it is actually decided.
906
+
907
+ This build has NO workspace-directory allowlist: running /add-dir does not
908
+ register anything and does not by itself change what the AI may read or write.
909
+ See /add-dir <path> for the mechanism.
900
910
 
901
911
  Examples:
902
912
  /add-dir ~/projects/my-api
903
913
  /add-dir /usr/local/share/data
904
914
 
905
- Current allowed directories:
906
- • ${process.cwd()} (project root, always allowed)
907
-
908
- Note: For security, tools like bash already respect .mipham/config.yml
909
- permission boundaries. Adding directories here extends read/write access.`,
915
+ Current directory: ${process.cwd()}`,
910
916
  }
911
917
  }
912
918
 
@@ -919,16 +925,27 @@ permission boundaries. Adding directories here extends read/write access.`,
919
925
  }
920
926
 
921
927
  return {
922
- content: `✓ Directory registered: ${resolved}
923
-
924
- To persist across sessions, add to .mipham/config.yml:
925
- workspace:
926
- extraDirs:
927
- - ${resolved}
928
-
929
- The AI can now access files in this directory.
930
- Permission mode: Shift+Tab cycles ${renderCycleLine()} (this session);
931
- \`permission:\` in .mipham/config.yml persists one.`,
928
+ content: `✓ Path exists: ${resolved}
929
+
930
+ Nothing was registered — this build has no workspace-directory allowlist.
931
+
932
+ How access is actually decided:
933
+ • Reads — not limited by directory. What refuses a file is a deny rule
934
+ (\`Read(<path>)\`, which also covers Bash readers like cat/head).
935
+ • Writes — gated by the permission mode (Shift+Tab cycles:
936
+ ${renderCycleLine()}).
937
+ In the default mode a Write/Edit resolves to \`ask\`, and this CLI
938
+ has no interactive approval prompt: \`ask\` is a hard refusal.
939
+
940
+ To allow writes under this directory without changing the mode, add path
941
+ allow rules to your USER settings (~/.mipham/settings.json). The project-level
942
+ allow list is deliberately ignored, because a repository must not widen its
943
+ own permissions:
944
+ {
945
+ "permissions": {
946
+ "allow": ["Write(${resolved}/**)","Edit(${resolved}/**)"]
947
+ }
948
+ }`,
932
949
  }
933
950
  }
934
951
 
@@ -123,11 +123,52 @@ function extractMessageText(msg: Message): string {
123
123
  return ''
124
124
  }
125
125
 
126
- function estimateStringTokens(text: string): number {
126
+ /**
127
+ * A run of at least this many non-space ASCII characters, with at least
128
+ * `DENSE_DISTINCT` distinct characters in it, is treated as encoded or
129
+ * unbroken payload (base64, hex, minified JSON, a single-line SVG) — text a
130
+ * BPE tokenizer splits at roughly 1.5–3 characters per token rather than the
131
+ * ~4 that prose and code average.
132
+ *
133
+ * Both halves matter:
134
+ * - the length threshold keeps ordinary identifiers (`some_long_function_name`)
135
+ * in the prose bucket;
136
+ * - the distinct-character threshold keeps `'A'.repeat(400)` there too — a
137
+ * filler run of one repeated character merges into very few tokens, and
138
+ * charging it as dense would overestimate by an order of magnitude.
139
+ *
140
+ * The divisor (`dense / 2`) is a deliberately conservative lower bound, not a
141
+ * measurement: this repository has no tokenizer, and the direction that matters
142
+ * is under-estimation (a request that is longer than the budget claimed). Being
143
+ * wrong the other way only compacts a little early.
144
+ */
145
+ const DENSE_RUN_MIN = 40
146
+ const DENSE_DISTINCT = 8
147
+
148
+ /**
149
+ * Estimate the token count for a text string.
150
+ *
151
+ * Character-class heuristic:
152
+ * - CJK / emoji: ~1.5 chars per token
153
+ * - dense ASCII runs (see above): ~2 chars per token
154
+ * - everything else (Latin, Cyrillic, Arabic, whitespace, short code): ~4
155
+ */
156
+ export function estimateStringTokens(text: string): number {
127
157
  if (!text) return 0
128
158
 
129
159
  let cjk = 0
130
160
  let latin = 0
161
+ let dense = 0
162
+ let runLength = 0
163
+ const runChars = new Set<string>()
164
+ const flushRun = (): void => {
165
+ if (runLength >= DENSE_RUN_MIN && runChars.size >= DENSE_DISTINCT) {
166
+ dense += runLength
167
+ latin -= runLength
168
+ }
169
+ runLength = 0
170
+ runChars.clear()
171
+ }
131
172
 
132
173
  for (const ch of text) {
133
174
  const cp = ch.codePointAt(0)!
@@ -141,12 +182,23 @@ function estimateStringTokens(text: string): number {
141
182
  (cp >= 0xff01 && cp <= 0xff60) || // Fullwidth
142
183
  (cp >= 0x1f300 && cp <= 0x1f9ff) // Emoji / pictographs
143
184
  ) {
185
+ flushRun()
144
186
  cjk++
187
+ } else if (cp > 0x7f) {
188
+ flushRun()
189
+ latin++
145
190
  } else {
146
191
  latin++
192
+ // Whitespace ends a run but still counts as loose text, exactly as before.
193
+ if (cp === 0x20 || cp === 0x09 || cp === 0x0a || cp === 0x0d || cp === 0x0b || cp === 0x0c) {
194
+ flushRun()
195
+ } else {
196
+ runLength++
197
+ if (runChars.size < DENSE_DISTINCT) runChars.add(ch)
198
+ }
147
199
  }
148
200
  }
201
+ flushRun()
149
202
 
150
- // CJK: ~1.5 chars/token, Latin/other: ~4 chars/token
151
- return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4))
203
+ return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4 + dense / 2))
152
204
  }
@@ -5,10 +5,12 @@ import type {
5
5
  ToolResult,
6
6
  ToolResultContent,
7
7
  } from '../shared/index.ts'
8
+ import { safeSlice } from '../shared/sanitize'
8
9
  import { snipMessages } from './context-snip'
9
10
  import { microcompact, shouldMicrocompact, isToolResultUserMessage } from './context-microcompact'
10
11
  import {
11
12
  estimateMessageTokens,
13
+ estimateStringTokens,
12
14
  NoopCacheTracker,
13
15
  type CacheTracker,
14
16
  type CacheStatus,
@@ -39,7 +41,7 @@ function shrinkText(text: string, maxTokens: number): string {
39
41
 
40
42
  let out = text
41
43
  for (let guard = 0; guard < 32 && out.length > 0 && estimate(out) > maxTokens; guard++) {
42
- out = out.slice(0, Math.floor(out.length / 2))
44
+ out = safeSlice(out, Math.floor(out.length / 2))
43
45
  }
44
46
  return `${out}\n… [truncated to fit the context budget; ${text.length - out.length} characters omitted]`
45
47
  }
@@ -128,6 +130,15 @@ export class ContextManager {
128
130
  * 组装时烘进去的话,本次会话里后连上的 server 永远进不了提示 —— 用户只能重启。
129
131
  */
130
132
  private mcpInstructionsSource: (() => string) | null = null
133
+ /**
134
+ * 重建整个系统提示的方式,由 `index.tsx` 在装提示的同时登记。
135
+ *
136
+ * 提示是启动那一刻的快照,而其中最大的那一段 —— 指令文件(`CLAUDE.md` /
137
+ * `AGENTS.md` / `USER.md`)—— 在会话中会被改。压缩之后由引擎调一次
138
+ * `refreshSystemPrompt()`,让规则按磁盘现状生效。**重建方式必须与首次组装
139
+ * 同一条路径**,否则刷新会悄悄丢掉启动时拼进去的那些段(技能提醒、记忆召回…)。
140
+ */
141
+ private systemPromptRebuilder: (() => string) | null = null
131
142
  /**
132
143
  * **消息那部分**的估值,增量累加(提示那部分见 `promptTokens()`,读时派生)。
133
144
  *
@@ -256,6 +267,29 @@ export class ContextManager {
256
267
  this.mcpInstructionsSource = fn
257
268
  }
258
269
 
270
+ /**
271
+ * 接线点(`index.tsx`):重建系统提示的方式。
272
+ *
273
+ * 传 `null` 撤销。**不接**时 `refreshSystemPrompt()` 是空操作 —— daemon 等路径
274
+ * 从不设置系统提示,凭空造一份出来会改变它们每个请求的形状。
275
+ */
276
+ setSystemPromptRebuilder(fn: (() => string) | null): void {
277
+ this.systemPromptRebuilder = fn
278
+ }
279
+
280
+ /**
281
+ * 用登记好的重建器重刷系统提示。返回是否真的重刷了。
282
+ *
283
+ * 调用点是压缩之后(`Engine.compactWithHooks`):对话刚被换成摘要,而指令文件
284
+ * 那一段还是启动那一刻的拷贝。重建器在里面先回读磁盘(`InstructionsLoader.refresh`),
285
+ * 所以这里拿到的是当前磁盘上的规则。
286
+ */
287
+ refreshSystemPrompt(): boolean {
288
+ if (!this.systemPromptRebuilder) return false
289
+ this.systemPrompt = this.systemPromptRebuilder()
290
+ return true
291
+ }
292
+
259
293
  /**
260
294
  * 存储的提示 + 读时派生的段(权限 / MCP instructions)。
261
295
  *
@@ -431,14 +465,6 @@ export class ContextManager {
431
465
  const dropped = this.messages.slice(0, cut)
432
466
  let kept = this.messages.slice(cut)
433
467
 
434
- // 一条消息自己就超预算(单条巨型结果 / 整篇文档)⇒ 没有可丢的,只能截内容。
435
- // 每条分到的是它自己那份预算,不是整份额度 —— 否则几条各占三分之一的消息谁也
436
- // 没超,削完还是超。
437
- if (dropped.length === 0 && kept.length > 0) {
438
- const perMessage = Math.max(1, Math.floor(target / kept.length))
439
- kept = kept.map((m) => truncateToBudget(m, perMessage))
440
- }
441
-
442
468
  const omittedNotice = (n: number): Message => ({
443
469
  role: 'user',
444
470
  content:
@@ -447,6 +473,21 @@ export class ContextManager {
447
473
  `they said.]`,
448
474
  })
449
475
 
476
+ // 幸存的那半自己就超预算(单条巨型结果 / 整篇文档)⇒ 没有可再丢的,只能截内容。
477
+ //
478
+ // 判据必须是**量出来的**「这份超没超」,不能是 `dropped.length === 0`:
479
+ // 只要有**一条**前面的消息被丢掉,那个条件就为假,而超额的恰恰可以是最后那条
480
+ // (丢弃循环对最后一条无条件保留)—— 于是「削完还超」,下一轮再进这里做同一个
481
+ // 空操作。通知自己也要占预算,所以按去掉通知后的额度分。
482
+ // 每条分到的是它自己那份,不是整份额度 —— 否则几条各占三分之一的消息谁也没超,
483
+ // 削完还是超。
484
+ const noticeTokens = dropped.length > 0 ? est(omittedNotice(dropped.length)) : 0
485
+ const bodyTarget = Math.max(1, target - noticeTokens)
486
+ if (kept.length > 0 && this.estimateTokensForMessages(kept) > bodyTarget) {
487
+ const perMessage = Math.max(1, Math.floor(bodyTarget / kept.length))
488
+ kept = kept.map((m) => truncateToBudget(m, perMessage))
489
+ }
490
+
450
491
  // 通知自己也占预算,所以头部再补削,直到**含通知**的整份落进预算。少了这一步,
451
492
  // 「刚好削到线内」的会话会因多出这一条而重新超线 —— 下一轮再削一次,逐轮掉消息。
452
493
  // 顺带保住配对:若补削后的第一条是 `tool_result`,它的调用已在被丢的那半里,
@@ -760,40 +801,11 @@ export class ContextManager {
760
801
  /**
761
802
  * Estimate token count for a text string.
762
803
  *
763
- * Uses a character-class-aware heuristic:
764
- * - CJK / emoji: ~1.5 chars per token
765
- * - Other scripts (Latin, Cyrillic, Arabic): ~4 chars per token
766
- * - Whitespace-heavy (code): ~3 chars per token
767
- *
768
- * This is ~30-40% more accurate than flat 4 chars/token for mixed-language text.
804
+ * Delegates to `estimateStringTokens` — the same function the message counter
805
+ * uses. Two copies of the formula are two chances for the budget and the
806
+ * compaction trigger to disagree about the same text.
769
807
  */
770
808
  private estimateTokens(text: string): number {
771
- if (!text) return 0
772
-
773
- let cjk = 0
774
- let latin = 0
775
-
776
- for (const ch of text) {
777
- const cp = ch.codePointAt(0)!
778
- // CJK Unified Ideographs, Hangul, Kana, CJK Extensions, fullwidth forms
779
- if (
780
- (cp >= 0x4e00 && cp <= 0x9fff) || // CJK Unified
781
- (cp >= 0x3400 && cp <= 0x4dbf) || // CJK Ext-A
782
- (cp >= 0x20000 && cp <= 0x2a6df) || // CJK Ext-B
783
- (cp >= 0xac00 && cp <= 0xd7af) || // Hangul
784
- (cp >= 0x3040 && cp <= 0x30ff) || // Hiragana + Katakana
785
- (cp >= 0xff01 && cp <= 0xff60) || // Fullwidth
786
- (cp >= 0x1f300 && cp <= 0x1f9ff) // Emoji / pictographs
787
- ) {
788
- cjk++
789
- } else if (cp > 0x7f) {
790
- latin++
791
- } else {
792
- latin++
793
- }
794
- }
795
-
796
- // CJK: ~1.5 chars/token, Latin/other: ~4 chars/token
797
- return Math.max(1, Math.ceil(cjk / 1.5 + latin / 4))
809
+ return estimateStringTokens(text)
798
810
  }
799
811
  }
@@ -25,6 +25,7 @@ import {
25
25
  realpathSync,
26
26
  } from 'node:fs'
27
27
  import { atomicWriteFileSync } from '../shared/atomic-write'
28
+ import { internalGitEnv } from '../shared/git-env'
28
29
  import { join, resolve, sep, posix } from 'node:path'
29
30
  import { tmpdir } from 'node:os'
30
31
  import { randomUUID } from 'node:crypto'
@@ -296,7 +297,7 @@ function shq(s: string): string {
296
297
  * 对象字面量怎么变都动不了它们。下面那个字面量被抹成 `{}` 只会丢掉超时与编码,
297
298
  * 丢不掉「哪棵树」。**有意不再传 `cwd`** —— 留着它,下一个人会以为承重的是它。
298
299
  *
299
- * 守卫 `test/integrity/crsi-sandbox-command-root.test.ts` 静态钉住这个形状。
300
+ * 守卫 `test/integrity/crsi-sandbox-root.test.ts` 静态钉住这个形状。
300
301
  */
301
302
  function runIn(
302
303
  root: string,
@@ -309,6 +310,9 @@ function runIn(
309
310
  return execSync(rooted, {
310
311
  timeout: opts.timeoutMs ?? 10_000,
311
312
  encoding: 'utf-8',
313
+ // The sandbox derives its worktree from `HEAD`; a `refs/replace/*` entry
314
+ // would make that tree differ from the object graph the user actually has.
315
+ env: internalGitEnv(),
312
316
  ...(opts.quiet ? { stdio: ['ignore', 'pipe', 'ignore'] as StdioOptions } : {}),
313
317
  })
314
318
  }