@miphamai/cli 0.85.23 → 0.85.25
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/bin/mipham.ts +21 -2
- package/package.json +1 -1
- package/src/agent/agent-registry.ts +42 -2
- package/src/agent/message-router.ts +30 -0
- package/src/agent/sub-agent.ts +17 -0
- package/src/artifacts/server.ts +5 -1
- package/src/commands/git.ts +9 -1
- package/src/commands/project.ts +34 -17
- package/src/core/context-microcompact.ts +1 -1
- package/src/core/context-token.ts +55 -3
- package/src/core/context.ts +180 -43
- package/src/core/crsi-sandbox.ts +5 -1
- package/src/core/engine.ts +19 -6
- package/src/core/hooks.ts +13 -3
- package/src/core/instructions.ts +69 -2
- package/src/core/permission-rules.ts +141 -25
- package/src/i18n-core/locales/en-US.json +1 -0
- package/src/i18n-core/locales/zh-CN.json +1 -0
- package/src/mcp/client.ts +22 -8
- package/src/plugin/plugin-manager.ts +23 -2
- package/src/providers/anthropic.ts +8 -2
- package/src/providers/openai-compat.ts +14 -2
- package/src/providers/registry.ts +23 -1
- package/src/shared/arg-validation.ts +2 -1
- package/src/shared/git-env.ts +18 -0
- package/src/shared/package-info.ts +3 -3
- package/src/shared/sanitize.ts +21 -0
- package/src/skills/loader.ts +55 -3
- package/src/tools/agent/workflow.ts +9 -2
- package/src/tools/exec/bash.ts +206 -17
- package/src/tools/exec/enter-worktree.ts +26 -2
- package/src/tools/network/web-fetch.ts +11 -3
- package/src/tools/network/web-search.ts +5 -1
- package/src/tools/scheduling/schedule-wakeup.ts +3 -2
- package/src/tools/validation.ts +11 -0
- package/src/ui/app.tsx +22 -7
- package/src/ui/chat.tsx +3 -2
- package/src/ui/commands.ts +61 -7
- package/src/workflow/primitives/agent.ts +51 -6
- package/src/workflow/primitives/verify.ts +36 -20
- package/src/workflow/runtime.ts +10 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
# Mipham Code v0.85.
|
|
1
|
+
# Mipham Code v0.85.25
|
|
2
2
|
|
|
3
|
-
**Multi-model open-core intelligent coding terminal** — 12 AI providers,
|
|
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
|
-
- **
|
|
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
|
@@ -1274,6 +1274,7 @@ Usage:
|
|
|
1274
1274
|
|
|
1275
1275
|
Flags:
|
|
1276
1276
|
--dump-config Print the assembled profile tree
|
|
1277
|
+
--profile <name> Profile for --dump-config (default: default)
|
|
1277
1278
|
--safe-mode Skip custom agents, skills, hooks, plugins
|
|
1278
1279
|
--resume <name> Open a saved session (see /resume for names)
|
|
1279
1280
|
--permission <mode> Start in this mode: ${ALL_MODES.join('|')}
|
|
@@ -1295,8 +1296,17 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1295
1296
|
const { loadProfile, loadBundle, assemble, dumpConfig } = await import('../src/vajra/compose')
|
|
1296
1297
|
|
|
1297
1298
|
const profileIdx = process.argv.indexOf('--profile')
|
|
1298
|
-
|
|
1299
|
-
|
|
1299
|
+
if (profileIdx !== -1) {
|
|
1300
|
+
const value = process.argv[profileIdx + 1]
|
|
1301
|
+
// A bare `--profile` (or `--profile --safe-mode`) used to fall through to
|
|
1302
|
+
// the `default` profile — the same silent substitution as a misspelled
|
|
1303
|
+
// session name, on the one path where nothing else would catch it.
|
|
1304
|
+
if (!value || value.startsWith('-')) {
|
|
1305
|
+
console.error('Usage: mipham --dump-config --profile <name>')
|
|
1306
|
+
process.exit(1)
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
const profileName = profileIdx !== -1 ? process.argv[profileIdx + 1]! : 'default'
|
|
1300
1310
|
const dir = join(homedir(), '.mipham', 'profiles')
|
|
1301
1311
|
const profilePath = join(dir, `${profileName}.yml`)
|
|
1302
1312
|
|
|
@@ -1311,6 +1321,15 @@ npm: https://www.npmjs.com/package/@miphamai/cli`)
|
|
|
1311
1321
|
process.exit(0)
|
|
1312
1322
|
}
|
|
1313
1323
|
|
|
1324
|
+
// `--profile` only means something with `--dump-config`. Saying so beats
|
|
1325
|
+
// launching the interactive CLI with a flag that silently does nothing.
|
|
1326
|
+
if (process.argv.includes('--profile')) {
|
|
1327
|
+
console.error(
|
|
1328
|
+
'--profile <name> only applies to --dump-config:\n mipham --dump-config --profile <name>',
|
|
1329
|
+
)
|
|
1330
|
+
process.exit(1)
|
|
1331
|
+
}
|
|
1332
|
+
|
|
1314
1333
|
// ── Update / upgrade ──────────────────────────────────────────────────────
|
|
1315
1334
|
const handledUpdate = await runUpdate()
|
|
1316
1335
|
if (handledUpdate) return
|
package/package.json
CHANGED
|
@@ -24,6 +24,47 @@ function parseFrontmatter(raw: string): FrontmatterResult {
|
|
|
24
24
|
}
|
|
25
25
|
}
|
|
26
26
|
|
|
27
|
+
/** `autoCompactWindow` 的合法区间:小到 0 是「一直压」,大到超过任何窗口都是笔误。 */
|
|
28
|
+
const MIN_COMPACT_WINDOW = 1_000
|
|
29
|
+
const MAX_COMPACT_WINDOW = 2_000_000
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 解析 agent 定义里的 `autoCompactWindow`,接受 `200000`、`200k`、`1M` 三种写法。
|
|
33
|
+
*
|
|
34
|
+
* 先前只吃 `number`,字符串被**静默**丢成 `undefined` —— 于是 `autoCompactWindow: 200k`
|
|
35
|
+
* 的代理从不收缩,而且没有任何一处说它被忽略了。一个声明被吞掉时,至少要说一声。
|
|
36
|
+
*/
|
|
37
|
+
export function parseTokenWindow(value: unknown, agentName: string): number | undefined {
|
|
38
|
+
if (value === undefined || value === null) return undefined
|
|
39
|
+
|
|
40
|
+
let parsed: number | undefined
|
|
41
|
+
if (typeof value === 'number') {
|
|
42
|
+
parsed = value
|
|
43
|
+
} else if (typeof value === 'string') {
|
|
44
|
+
const m = value.trim().match(/^(\d+(?:\.\d+)?)\s*([kKmM])?$/)
|
|
45
|
+
if (m) {
|
|
46
|
+
const scale = m[2] ? (/m/i.test(m[2]) ? 1_000_000 : 1_000) : 1
|
|
47
|
+
parsed = Math.round(parseFloat(m[1]!) * scale)
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (parsed === undefined) {
|
|
52
|
+
console.warn(
|
|
53
|
+
`⚠ Agent "${agentName}": autoCompactWindow "${String(value)}" is not a number ` +
|
|
54
|
+
`(${MIN_COMPACT_WINDOW}–${MAX_COMPACT_WINDOW}, or 200k / 1M). Ignored.`,
|
|
55
|
+
)
|
|
56
|
+
return undefined
|
|
57
|
+
}
|
|
58
|
+
if (parsed < MIN_COMPACT_WINDOW || parsed > MAX_COMPACT_WINDOW) {
|
|
59
|
+
console.warn(
|
|
60
|
+
`⚠ Agent "${agentName}": autoCompactWindow ${parsed} is outside ` +
|
|
61
|
+
`${MIN_COMPACT_WINDOW}–${MAX_COMPACT_WINDOW}. Ignored.`,
|
|
62
|
+
)
|
|
63
|
+
return undefined
|
|
64
|
+
}
|
|
65
|
+
return parsed
|
|
66
|
+
}
|
|
67
|
+
|
|
27
68
|
const BUILTIN_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
|
|
28
69
|
general: 'You are a focused sub-agent. Complete the assigned task thoroughly and return results.',
|
|
29
70
|
explore:
|
|
@@ -79,8 +120,7 @@ export class AgentRegistry {
|
|
|
79
120
|
: undefined,
|
|
80
121
|
background: typeof data.background === 'boolean' ? data.background : undefined,
|
|
81
122
|
memory: data.memory as 'user' | 'project' | 'local' | undefined,
|
|
82
|
-
autoCompactWindow:
|
|
83
|
-
typeof data.autoCompactWindow === 'number' ? data.autoCompactWindow : undefined,
|
|
123
|
+
autoCompactWindow: parseTokenWindow(data.autoCompactWindow, name),
|
|
84
124
|
source,
|
|
85
125
|
filePath: fullPath,
|
|
86
126
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { getMessageBus } from './message-bus'
|
|
2
|
+
import { getBackgroundAgentRegistry } from './background-registry'
|
|
2
3
|
import { getFileInboxTransport } from './cross-session/file-inbox'
|
|
3
4
|
import { discoverSessions, createSessionInfo } from './cross-session/discovery'
|
|
4
5
|
import type { AgentMessage } from './message-bus'
|
|
@@ -82,6 +83,35 @@ export class MessageRouter {
|
|
|
82
83
|
async route(from: string, to: string, summary: string, message: string): Promise<RouteResult> {
|
|
83
84
|
// Same-process routing: "main" or background task IDs
|
|
84
85
|
if (to === 'main' || to.startsWith('bg-') || to.startsWith('sub-agent-')) {
|
|
86
|
+
// A message is only delivered if something is still reading the address.
|
|
87
|
+
// Background and sub-agent ids are drained from inside their own turn
|
|
88
|
+
// loop (`sub-agent.ts` `drainInboundMessages`), so once that loop has
|
|
89
|
+
// exited the queue entry is never looked at again — posting anyway and
|
|
90
|
+
// reporting success tells the caller to expect a reply from an agent that
|
|
91
|
+
// will never run. The registry is the liveness record; "main" has no id
|
|
92
|
+
// in it and is always drainable by the parent engine.
|
|
93
|
+
if (to !== 'main') {
|
|
94
|
+
const task = getBackgroundAgentRegistry().get(to)
|
|
95
|
+
if (!task) {
|
|
96
|
+
return {
|
|
97
|
+
success: false,
|
|
98
|
+
routedTo: 'bus',
|
|
99
|
+
error:
|
|
100
|
+
`No live agent "${to}" in this process. A background agent is only ` +
|
|
101
|
+
`addressable by its task ID while it is still running.`,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (task.status !== 'running') {
|
|
105
|
+
return {
|
|
106
|
+
success: false,
|
|
107
|
+
routedTo: 'bus',
|
|
108
|
+
error:
|
|
109
|
+
`Agent "${to}" is ${task.status} and is no longer reading messages, ` +
|
|
110
|
+
`so this message would never be seen. Its final result is available ` +
|
|
111
|
+
`through the Task tool; start a new agent to continue the work.`,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
85
115
|
try {
|
|
86
116
|
const bus = getMessageBus()
|
|
87
117
|
const msgId = bus.post(from, to, summary, message)
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -509,6 +509,11 @@ export class SubAgent {
|
|
|
509
509
|
artifactSessionId: `${options.toolContext?.sessionId ?? 'main'}:sub:${agentDef?.name || agentType}`,
|
|
510
510
|
}
|
|
511
511
|
|
|
512
|
+
// Whether the *last* turn ended because the model hit its output ceiling.
|
|
513
|
+
// Kept outside the loop because the answer the caller receives is the last
|
|
514
|
+
// turn's text, so that is the turn whose completeness matters.
|
|
515
|
+
let lastTurnTruncated = false
|
|
516
|
+
|
|
512
517
|
try {
|
|
513
518
|
for (let turn = 0; turn < MAX_TOOL_TURNS; turn++) {
|
|
514
519
|
// Check abort signal
|
|
@@ -535,6 +540,10 @@ export class SubAgent {
|
|
|
535
540
|
const toolUses: Array<{ id: string; name: string; input: Record<string, unknown> }> = []
|
|
536
541
|
let turnText = ''
|
|
537
542
|
let streamError: string | null = null
|
|
543
|
+
// The provider says so on the stop chunk when the model ran out of output
|
|
544
|
+
// budget (`max_tokens`). The answer is real but cut off mid-thought, and
|
|
545
|
+
// nothing downstream could tell that from a finished one.
|
|
546
|
+
let turnTruncated = false
|
|
538
547
|
|
|
539
548
|
for await (const chunk of (this.llm ?? this.registry).chat({
|
|
540
549
|
model: finalModel,
|
|
@@ -577,6 +586,7 @@ export class SubAgent {
|
|
|
577
586
|
break
|
|
578
587
|
}
|
|
579
588
|
if (chunk.type === 'stop') {
|
|
589
|
+
if (chunk.truncated) turnTruncated = true
|
|
580
590
|
break
|
|
581
591
|
}
|
|
582
592
|
if (chunk.type === 'usage') {
|
|
@@ -586,6 +596,7 @@ export class SubAgent {
|
|
|
586
596
|
}
|
|
587
597
|
|
|
588
598
|
chunks.push(turnText)
|
|
599
|
+
lastTurnTruncated = turnTruncated
|
|
589
600
|
|
|
590
601
|
// Nothing came back at all, so there is no partial response to continue
|
|
591
602
|
// from — that is a genuine failure and is reported as one.
|
|
@@ -771,6 +782,12 @@ export class SubAgent {
|
|
|
771
782
|
}
|
|
772
783
|
|
|
773
784
|
const result = chunks.join('')
|
|
785
|
+
// Ran out of output budget rather than finished. Saying so is the whole
|
|
786
|
+
// point: the text looks like a complete answer, so a caller with no marker
|
|
787
|
+
// treats a half-sentence conclusion as the agent's verdict.
|
|
788
|
+
if (!hitMaxTurns && lastTurnTruncated) {
|
|
789
|
+
return `[partial result — sub-agent hit the model's output limit; answer may be cut off]\n\n${result}`
|
|
790
|
+
}
|
|
774
791
|
if (hitMaxTurns) {
|
|
775
792
|
// Only advertise the SendMessage route where a route exists. A background
|
|
776
793
|
// agent has an address (`bg-…`, minted by the registry and handed to the
|
package/src/artifacts/server.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
})
|
package/src/commands/git.ts
CHANGED
|
@@ -8,11 +8,19 @@ import type { CommandHandler } from '../ui/commands.js'
|
|
|
8
8
|
|
|
9
9
|
export { commitCmd, pushCmd, prCmd, issueCmd }
|
|
10
10
|
|
|
11
|
-
/**
|
|
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,
|
package/src/commands/project.ts
CHANGED
|
@@ -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
|
-
|
|
899
|
-
|
|
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
|
|
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: `✓
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
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
|
|
|
@@ -72,7 +72,7 @@ function countToolPairs(messages: Message[]): number {
|
|
|
72
72
|
return count
|
|
73
73
|
}
|
|
74
74
|
|
|
75
|
-
function isToolResultUserMessage(msg: Message): boolean {
|
|
75
|
+
export function isToolResultUserMessage(msg: Message): boolean {
|
|
76
76
|
if (msg.role !== 'user') return false
|
|
77
77
|
if (!Array.isArray(msg.content)) return false
|
|
78
78
|
return msg.content.some(
|
|
@@ -123,11 +123,52 @@ function extractMessageText(msg: Message): string {
|
|
|
123
123
|
return ''
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
-
|
|
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
|
-
|
|
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
|
}
|