@miphamai/cli 0.85.41 → 0.85.42

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.41
1
+ # Mipham Code v0.85.42
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.41",
3
+ "version": "0.85.42",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -72,6 +72,7 @@ const BUILTIN_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
72
72
  plan: 'You are a planning sub-agent. Design implementation approaches. Return a step-by-step plan with files to modify.',
73
73
  'code-review':
74
74
  'You are a code review sub-agent. Find bugs, security issues, and code quality problems. Return findings by severity.',
75
+ fork: 'You are a forked sub-agent. You inherit the conversation so far; continue it rather than restating it.',
75
76
  }
76
77
 
77
78
  const BUILTIN_DESCRIPTIONS: Record<SubAgentType, string> = {
@@ -79,6 +80,7 @@ const BUILTIN_DESCRIPTIONS: Record<SubAgentType, string> = {
79
80
  explore: 'Read-only search agent for broad fan-out searches across files.',
80
81
  plan: 'Software architect agent for designing implementation plans.',
81
82
  'code-review': 'Code review agent for finding bugs and quality issues.',
83
+ fork: 'Sub-agent that inherits the current conversation and continues from it.',
82
84
  }
83
85
 
84
86
  export class AgentRegistry {
@@ -35,7 +35,10 @@ export class FileInboxTransport implements CrossSessionTransport {
35
35
  private initialized = false
36
36
 
37
37
  private ensureDir(dir: string): void {
38
- mkdirSync(dir, { recursive: true })
38
+ // Owner-only. The inbox carries other sessions' message bodies; the default
39
+ // 0755 directory makes them readable by every local account on a machine
40
+ // whose home directory is world-traversable.
41
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
39
42
  }
40
43
 
41
44
  /** Ensure the inbox root directory exists (call on first use). */
@@ -69,7 +72,7 @@ export class FileInboxTransport implements CrossSessionTransport {
69
72
 
70
73
  // Atomic write: temp file then rename
71
74
  const tmpPath = filePath + '.tmp'
72
- atomicWriteFileSync(tmpPath, JSON.stringify(envelope, null, 2), { mode: 0o644 })
75
+ atomicWriteFileSync(tmpPath, JSON.stringify(envelope, null, 2), { mode: 0o600 })
73
76
  renameSync(tmpPath, filePath)
74
77
 
75
78
  return true
@@ -55,6 +55,7 @@ const TYPE_SYSTEM_PROMPTS: Record<SubAgentType, string> = {
55
55
  plan: 'You are a planning sub-agent. Design implementation approaches. Return a step-by-step plan with files to modify.',
56
56
  'code-review':
57
57
  'You are a code review sub-agent. Find bugs, security issues, and code quality problems. Return findings by severity.',
58
+ fork: 'You are a forked sub-agent. You inherit the conversation so far; continue it rather than restating it.',
58
59
  }
59
60
 
60
61
  /**
@@ -2,7 +2,7 @@
2
2
 
3
3
  import type { Message, ToolContext } from '../shared/index.ts'
4
4
 
5
- export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review'
5
+ export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review' | 'fork'
6
6
 
7
7
  export interface AgentFrontmatter {
8
8
  name: string
@@ -6,10 +6,19 @@ import { SecurityGate } from '../../security/gate'
6
6
  * Well-known secret token prefixes. These are high-signal formats that must
7
7
  * never leak into output, independent of the configured patterns.
8
8
  * - GitHub: ghp_ (personal access), gho_ (OAuth), ghs_ (server), ghu_/ghr_ (user/server-to-server), github_pat_ (fine-grained)
9
- * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app)
9
+ * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app),
10
+ * glptt- (pipeline trigger), glagent- (agent), glimt- (incoming mail),
11
+ * glsoat- (SCIM OAuth), glcbt- (CI build), glft- (feed), glffct- (feature flags)
12
+ *
13
+ * GitLab "routable" tokens carry a `.` between a short routing segment and the
14
+ * secret (e.g. `glpat-abcde.0123456789abcdef`). A body class without `.` stops
15
+ * at the first segment, redacting the routing prefix and leaving the secret in
16
+ * the clear — the dot-separated tail is part of the credential, not punctuation.
17
+ * Each dot segment must be at least five characters, so a sentence-ending period
18
+ * after a token is not swallowed.
10
19
  */
11
20
  const TOKEN_REDACTION_PATTERN =
12
- /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-)[A-Za-z0-9_-]{8,}/g
21
+ /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-|glptt-|glagent-|glimt-|glsoat-|glcbt-|glft-|glffct-)[A-Za-z0-9_-]{5,}(?:\.[A-Za-z0-9_-]{5,})*/g
13
22
 
14
23
  /**
15
24
  * Credentials embedded in a URL's userinfo — `scheme://user:password@host`.
@@ -1572,6 +1572,9 @@ export class QueryEngine {
1572
1572
  llm: this.llm,
1573
1573
  readFiles: this.readFiles,
1574
1574
  readFilesComplete: this.readFilesComplete,
1575
+ // A copy: the sub-agent seeds its own context from this prefix while the
1576
+ // parent turn keeps appending to its list.
1577
+ parentMessages: this.context.getMessages().slice(),
1575
1578
  })
1576
1579
 
1577
1580
  // Track touched files for rules matching
@@ -1854,6 +1857,21 @@ export class QueryEngine {
1854
1857
  }
1855
1858
  continue
1856
1859
  }
1860
+ // Compaction has already run and the request is *still* too large.
1861
+ // Re-sending it — here or to a fallback provider — cannot change the
1862
+ // answer: the messages themselves are the oversized part and there is
1863
+ // nothing left to strip. Say why once instead of spending the retry and
1864
+ // fallback budget on a request that is guaranteed to fail the same way.
1865
+ if (compactedForOverflow && ownsFlow && isContextOverflowError(failure)) {
1866
+ yield {
1867
+ type: 'error',
1868
+ error:
1869
+ `${activeId} rejected the request as too large even after compacting — ` +
1870
+ `the conversation itself exceeds the request size limit, so retrying cannot help. ` +
1871
+ `Start a new session (/clear) or remove large attachments.`,
1872
+ }
1873
+ return
1874
+ }
1857
1875
  if (!retryable || !ownsFlow || attempt >= 1) break
1858
1876
  // `restart: true` tells the consumer to drop what the failed attempt already
1859
1877
  // yielded. Without it the retry's tool calls are *added* to the failed
package/src/mcp/oauth.ts CHANGED
@@ -16,6 +16,17 @@ const bundles: Record<string, TranslationMap> = {
16
16
  }
17
17
  const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
18
18
 
19
+ /**
20
+ * The one spelling used for both the loopback listener and its redirect URI.
21
+ *
22
+ * `localhost` is resolved by the *browser*, and on many systems that resolves
23
+ * to `::1` first while this server listens on IPv4 only — the browser then
24
+ * fails to reach the callback. Strict authorization servers also compare the
25
+ * redirect URI against the client registration byte-for-byte, and `127.0.0.1`
26
+ * is the spelling registrations use. Both sides therefore name the same host.
27
+ */
28
+ const OAUTH_CALLBACK_HOST = '127.0.0.1'
29
+
19
30
  interface TokenResponse {
20
31
  accessToken: string
21
32
  refreshToken?: string
@@ -68,7 +79,7 @@ export class OAuthClient {
68
79
 
69
80
  const code = await new Promise<string>((resolve, reject) => {
70
81
  const server: Server = createServer(async (req: IncomingMessage, res: ServerResponse) => {
71
- const url = new URL(req.url || '/', `http://localhost:${port}`)
82
+ const url = new URL(req.url || '/', `http://${OAUTH_CALLBACK_HOST}:${port}`)
72
83
  if (url.pathname === '/callback') {
73
84
  const receivedCode = url.searchParams.get('code')
74
85
  const receivedState = url.searchParams.get('state')
@@ -112,7 +123,7 @@ export class OAuthClient {
112
123
  authUrl.searchParams.set('client_id', auth.clientId)
113
124
  authUrl.searchParams.set('code_challenge', codeChallenge)
114
125
  authUrl.searchParams.set('code_challenge_method', 'S256')
115
- authUrl.searchParams.set('redirect_uri', `http://localhost:${port}/callback`)
126
+ authUrl.searchParams.set('redirect_uri', `http://${OAUTH_CALLBACK_HOST}:${port}/callback`)
116
127
  authUrl.searchParams.set('state', state)
117
128
  if (auth.scopes?.length) {
118
129
  authUrl.searchParams.set('scope', auth.scopes.join(' '))
@@ -148,7 +159,7 @@ export class OAuthClient {
148
159
  grant_type: 'authorization_code',
149
160
  code,
150
161
  code_verifier: codeVerifier,
151
- redirect_uri: `http://localhost:${port}/callback`,
162
+ redirect_uri: `http://${OAUTH_CALLBACK_HOST}:${port}/callback`,
152
163
  client_id: auth.clientId,
153
164
  }).toString(),
154
165
  })
@@ -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.41' as const
12
+ export const PACKAGE_VERSION = '0.85.42' 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 = 5064 as const
93
+ export const TEST_COUNT = 5079 as const
@@ -656,6 +656,16 @@ export interface ToolContext {
656
656
  * Absent means "no completeness tracking" and is treated as not complete.
657
657
  */
658
658
  readFilesComplete?: Set<string>
659
+ /**
660
+ * The live conversation this tool call belongs to.
661
+ *
662
+ * Set by `Engine.executeTool` on the context it hands every tool. The Agent
663
+ * tool's `fork` subagent type seeds its own context with this prefix so it can
664
+ * act on the conversation without being told about it again. Absent when a
665
+ * context is built by hand (tests, daemon stubs) — `fork` then refuses rather
666
+ * than silently behaving like `general`.
667
+ */
668
+ parentMessages?: Message[]
659
669
  /**
660
670
  * Cancellation for the turn this tool call belongs to.
661
671
  *
@@ -3,7 +3,7 @@ import { SubAgent } from '../../agent/sub-agent'
3
3
  import type { SubAgentType } from '../../agent/types'
4
4
  import { getBackgroundAgentRegistry } from '../../agent/background-registry'
5
5
 
6
- const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review']
6
+ const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review', 'fork']
7
7
 
8
8
  /** Same domain as the session-level `/effort` command (`ui/commands.ts`). */
9
9
  const VALID_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max']
@@ -38,7 +38,8 @@ export const agentTool: ToolDefinition = {
38
38
  name: 'Agent',
39
39
  description:
40
40
  'Launch a sub-agent to handle complex, multi-step tasks independently. ' +
41
- 'Available types: general (default), explore (code search), plan (design), code-review. ' +
41
+ 'Available types: general (default), explore (code search), plan (design), code-review, ' +
42
+ 'fork (inherits this conversation). ' +
42
43
  'Runs in the background by default — returns a task ID immediately; results are ' +
43
44
  'retrievable via the Task tool (output action) or Agent View. ' +
44
45
  'Set run_in_background: false to run synchronously.',
@@ -60,7 +61,8 @@ export const agentTool: ToolDefinition = {
60
61
  prompt: { type: 'string', description: 'The task for the agent to perform' },
61
62
  subagent_type: {
62
63
  type: 'string',
63
- description: 'Type: general (default), explore (code search), plan (design), code-review',
64
+ description:
65
+ 'Type: general (default), explore (code search), plan (design), code-review, fork (inherits this conversation)',
64
66
  },
65
67
  run_in_background: {
66
68
  type: 'boolean',
@@ -116,6 +118,20 @@ export const agentTool: ToolDefinition = {
116
118
 
117
119
  // Resolve agent definition from registry (custom > builtin)
118
120
  const agentDef = ctx.agentRegistry?.resolve(agentType)
121
+
122
+ // `fork` inherits the live conversation. It needs one to inherit: with no
123
+ // parent messages it would behave exactly like `general` while the caller
124
+ // reads the type as proof that context was carried over, so refuse instead.
125
+ const inheritedMessages = agentType === 'fork' ? ctx.parentMessages?.slice() : undefined
126
+ if (agentType === 'fork' && (!inheritedMessages || inheritedMessages.length === 0)) {
127
+ return {
128
+ success: false,
129
+ content: '',
130
+ error:
131
+ 'fork requires an existing conversation to inherit; this session has no messages yet.',
132
+ }
133
+ }
134
+
119
135
  const runInBackground = resolveRunInBackground(
120
136
  params.run_in_background as boolean | undefined,
121
137
  agentDef,
@@ -139,6 +155,9 @@ export const agentTool: ToolDefinition = {
139
155
  agentDef,
140
156
  runInBackground,
141
157
  effort,
158
+ // Byte-identical parent prefix (see SubAgent's `inheritContext`), so the
159
+ // fork starts from the conversation rather than from the prompt alone.
160
+ ...(inheritedMessages ? { inheritContext: { messages: inheritedMessages } } : {}),
142
161
  // Hand the caller's services down: the sub-agent keeps running the same
143
162
  // skills/agents/artifacts, and only the fields it owns are overridden.
144
163
  toolContext: ctx,
@@ -169,7 +169,11 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
169
169
  if (include) rgArgs.push('--glob', include)
170
170
  rgArgs.push(searchPath)
171
171
  try {
172
- const { stdout, timedOut, exitCode } = await runSearch(rgArgs, ctx.cwd, GREP_TIMEOUT_MS)
172
+ const { stdout, stderr, timedOut, exitCode } = await runSearch(
173
+ rgArgs,
174
+ ctx.cwd,
175
+ GREP_TIMEOUT_MS,
176
+ )
173
177
  if (timedOut) {
174
178
  return {
175
179
  success: false,
@@ -200,6 +204,19 @@ export function createGrepTool(credentialConfig?: CredentialMaskingConfig): Tool
200
204
  '\n\n(rg exited 2 — some paths unreadable; narrow scope for complete results)',
201
205
  }
202
206
  }
207
+ // The server's own reason, not a guess. A rejected pattern (a literal
208
+ // line break without multiline mode, an unbalanced bracket) is exit 2
209
+ // with empty stdout exactly like a permission error is — and telling
210
+ // the caller "likely permission denied" sends it to narrow a path when
211
+ // what it has to fix is the pattern.
212
+ const reason = stderr.trim()
213
+ if (reason) {
214
+ return {
215
+ success: false,
216
+ content: '',
217
+ error: `rg rejected the search: ${reason.slice(0, 500)}`,
218
+ }
219
+ }
203
220
  return {
204
221
  success: false,
205
222
  content: '',
@@ -50,6 +50,9 @@ function windowFromString(content: string, offset: number, limit: number): strin
50
50
  let lineNo = 0
51
51
  let start = 0
52
52
  while (out.length < limit) {
53
+ // Nothing follows a terminating newline: `"a\nb\n"` has two lines, not
54
+ // three. An empty string has no lines at all.
55
+ if (start >= content.length) break
53
56
  const nl = content.indexOf('\n', start)
54
57
  const end = nl === -1 ? content.length : nl
55
58
  if (lineNo >= offset) out.push(content.slice(start, end))
@@ -149,7 +152,16 @@ function windowFromFd(
149
152
  if (n <= 0) break
150
153
  got += n
151
154
  }
152
- return { lines: out.toString('utf-8', 0, got).split('\n'), complete }
155
+ // A file that ends with a newline has no line after it. `split('\n')` on
156
+ // `"a\nb\n"` yields `['a','b','']`, and formatting that trailing element
157
+ // printed an extra empty numbered line — the caller asked for the file, not
158
+ // for a line the file does not contain. Only the single element produced by
159
+ // the *final* newline is dropped; blank lines inside the file stay.
160
+ if (got === 0) return { lines: [], complete }
161
+ const text = out.toString('utf-8', 0, got)
162
+ const lines = text.split('\n')
163
+ if (out[got - 1] === 0x0a) lines.pop()
164
+ return { lines, complete }
153
165
  }
154
166
 
155
167
  export function createReadTool(credentialConfig?: CredentialMaskingConfig): ToolDefinition {
@@ -1,7 +1,7 @@
1
1
  import React from 'react'
2
2
  import { Box, Text } from 'ink'
3
3
  import { useI18n } from '../i18n-context'
4
- import { sanitizeInlineField } from '../shared/sanitize'
4
+ import { safeSlice, sanitizeInlineField } from '../shared/sanitize'
5
5
 
6
6
  /**
7
7
  * 页脚也是本文件通往终端的一道口 —— 且它内插的字全是**模型写出来的**:
@@ -131,7 +131,7 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
131
131
  <Box>
132
132
  <Text color={toolIndicatorColor(activeTool!.name)}>
133
133
  {' '}[{sanitizeInlineField(activeTool!.name)}{' '}
134
- {sanitizeInlineField(activeTool!.detail).slice(0, 60)}
134
+ {safeSlice(sanitizeInlineField(activeTool!.detail), 60)}
135
135
  {animatedDots(tick)}]
136
136
  </Text>
137
137
  <Box flexGrow={1} />
@@ -167,9 +167,13 @@ export function AgentFooter({ agents, tick, activeTool, agentProgress }: AgentFo
167
167
  const symbol = isRunning ? '◯' : '◼'
168
168
  const symbolColor = isRunning ? 'cyan' : undefined
169
169
 
170
- // Truncate description to keep lines readable
170
+ // Truncate description to keep lines readable. `safeSlice` refuses to end
171
+ // on the high half of a surrogate pair — a plain `slice(0, 80)` there
172
+ // printed a lone surrogate (a garbled glyph) for any emoji on the edge.
171
173
  const desc =
172
- agent.description.length > 80 ? agent.description.slice(0, 80) + '...' : agent.description
174
+ agent.description.length > 80
175
+ ? safeSlice(agent.description, 80) + '...'
176
+ : agent.description
173
177
 
174
178
  return (
175
179
  <Box key={agent.id}>
package/src/ui/chat.tsx CHANGED
@@ -123,7 +123,7 @@ const MessageRow = React.memo(
123
123
  {msg.toolMeta.name ? (
124
124
  <Text color={toolColor(msg.toolMeta.name)}>
125
125
  {msg.toolMeta.collapsed ? '⏺' : '⏺ ▼'} {sanitizeInlineField(msg.toolMeta.name)}
126
- {msg.toolMeta.input ? ` (${display(msg.toolMeta.input).slice(0, 120)})` : ''}
126
+ {msg.toolMeta.input ? ` (${safeSlice(display(msg.toolMeta.input), 120)})` : ''}
127
127
  </Text>
128
128
  ) : null}
129
129
  {/* Tool result line: ⎿ summary text */}