@miphamai/cli 0.36.2 → 0.37.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.36.2",
3
+ "version": "0.37.0",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -73,7 +73,7 @@ export class AgentRegistry {
73
73
  .split(',')
74
74
  .map((s) => s.trim())
75
75
  : undefined,
76
- background: (data.background as boolean) || false,
76
+ background: typeof data.background === 'boolean' ? data.background : undefined,
77
77
  memory: data.memory as 'user' | 'project' | 'local' | undefined,
78
78
  source,
79
79
  filePath: fullPath,
@@ -125,7 +125,6 @@ export class AgentRegistry {
125
125
  systemPrompt: BUILTIN_SYSTEM_PROMPTS[builtinType],
126
126
  model: 'inherit',
127
127
  permissionMode: 'inherit',
128
- background: false,
129
128
  source: 'builtin',
130
129
  }
131
130
  }
@@ -2,6 +2,7 @@ import { getMessageBus } from './message-bus'
2
2
  import { getFileInboxTransport } from './cross-session/file-inbox'
3
3
  import { discoverSessions, createSessionInfo } from './cross-session/discovery'
4
4
  import type { AgentMessage } from './message-bus'
5
+ import type { SessionInfo } from '../shared/types'
5
6
 
6
7
  export interface RouteResult {
7
8
  success: boolean
@@ -10,6 +11,35 @@ export interface RouteResult {
10
11
  messageId?: string
11
12
  }
12
13
 
14
+ export interface SessionResolution {
15
+ session?: SessionInfo
16
+ error?: string
17
+ }
18
+
19
+ /**
20
+ * Resolve a recipient among live sessions by bare name — session ID first,
21
+ * then session name. A name must uniquely match exactly one session; ambiguity
22
+ * and non-matches are reported as errors.
23
+ */
24
+ export function resolveRecipientSession(sessions: SessionInfo[], to: string): SessionResolution {
25
+ const byId = sessions.find((s) => s.id === to)
26
+ if (byId) return { session: byId }
27
+
28
+ const byName = sessions.filter((s) => s.name === to)
29
+ if (byName.length === 1) return { session: byName[0] }
30
+ if (byName.length > 1) {
31
+ return {
32
+ error:
33
+ `Ambiguous session name "${to}" matches ${byName.length} live sessions. ` +
34
+ `Use a session ID to disambiguate (ListAgents).`,
35
+ }
36
+ }
37
+
38
+ return {
39
+ error: `No active session found matching "${to}". Use ListAgents to discover available sessions.`,
40
+ }
41
+ }
42
+
13
43
  /**
14
44
  * MessageRouter decides how to deliver a message based on the recipient.
15
45
  *
@@ -33,17 +63,14 @@ export class MessageRouter {
33
63
  }
34
64
  }
35
65
 
36
- // Cross-session routing
66
+ // Cross-session routing (by session ID or bare name)
37
67
  const sessions = discoverSessions()
38
- const targetSession = sessions.find((s) => s.id === to)
68
+ const resolution = resolveRecipientSession(sessions, to)
39
69
 
40
- if (!targetSession) {
41
- return {
42
- success: false,
43
- routedTo: 'unknown',
44
- error: `No active session found with ID "${to}". Use ListAgents to discover available sessions.`,
45
- }
70
+ if (resolution.error) {
71
+ return { success: false, routedTo: 'unknown', error: resolution.error }
46
72
  }
73
+ const targetSession = resolution.session!
47
74
 
48
75
  // Get sender info
49
76
  const senderSession = createSessionInfo(from, from)
@@ -53,7 +80,7 @@ export class MessageRouter {
53
80
  const msg: AgentMessage = {
54
81
  id: `xmsg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
55
82
  from,
56
- to,
83
+ to: targetSession.id,
57
84
  summary: summary.slice(0, 200),
58
85
  message,
59
86
  timestamp: new Date(),
@@ -61,7 +88,7 @@ export class MessageRouter {
61
88
  type: 'message',
62
89
  }
63
90
 
64
- const delivered = await transport.send(senderSession, to, msg)
91
+ const delivered = await transport.send(senderSession, targetSession.id, msg)
65
92
  if (!delivered) {
66
93
  return { success: false, routedTo: 'inbox', error: 'Failed to write message to inbox.' }
67
94
  }
@@ -270,6 +270,13 @@ export class SubAgent {
270
270
  )
271
271
 
272
272
  context.setSystemPrompt(systemPrompt)
273
+
274
+ // Seed inherited parent conversation (fork inheritance) as a byte-identical
275
+ // prefix so the provider prompt cache is reused.
276
+ if (options.inheritContext && options.inheritContext.messages.length > 0) {
277
+ context.seedMessages(options.inheritContext.messages)
278
+ }
279
+
273
280
  context.addMessage({ role: 'user', content: prompt })
274
281
 
275
282
  const messages = context.getMessages()
@@ -1,5 +1,7 @@
1
1
  // apps/cli/src/agent/types.ts
2
2
 
3
+ import type { Message } from '../shared/index.ts'
4
+
3
5
  export type SubAgentType = 'general' | 'explore' | 'plan' | 'code-review'
4
6
 
5
7
  export interface AgentFrontmatter {
@@ -26,7 +28,8 @@ export interface AgentDefinition {
26
28
  permissionMode: string
27
29
  maxTurns?: number
28
30
  skills?: string[]
29
- background: boolean
31
+ /** Force background (true) or sync (false) execution. Unset inherits the tool default. */
32
+ background?: boolean
30
33
  source: 'builtin' | 'project' | 'user'
31
34
  filePath?: string
32
35
  memory?: 'user' | 'project' | 'local' // agent memory scope
@@ -47,6 +50,8 @@ export interface SubAgentOptions {
47
50
  onProgress?: (chunk: string) => void
48
51
  /** When set, tool executions use this path as cwd (git worktree isolation). */
49
52
  worktreePath?: string
53
+ /** Seed the sub-agent with a parent conversation prefix (e.g., fork inheritance). */
54
+ inheritContext?: { messages: Message[] }
50
55
  /** CRSI: when false, skip pattern analysis after agent execution. Default true. */
51
56
  autoPatternAnalysis?: boolean
52
57
  }
@@ -12,6 +12,8 @@ export interface CacheTracker {
12
12
  isInCache(msg: Message): boolean
13
13
  /** Returns a snapshot of the cache state for metrics / logging. */
14
14
  getStatus(): CacheStatus
15
+ /** Record the set of messages currently held in the provider prompt cache. */
16
+ markCached?(messages: Message[]): void
15
17
  /** Clear the tracker state (does NOT evict from provider cache). */
16
18
  invalidate(): void
17
19
  }
@@ -41,11 +43,53 @@ export class NoopCacheTracker implements CacheTracker {
41
43
  this.messageCount = messages.length
42
44
  }
43
45
 
46
+ markCached(_messages: Message[]): void {
47
+ // No-op — prompt caching is disabled with this tracker.
48
+ }
49
+
44
50
  invalidate(): void {
45
51
  this.messageCount = 0
46
52
  }
47
53
  }
48
54
 
55
+ /**
56
+ * Tracks which messages are currently held in the provider's prompt cache.
57
+ * The engine informs it of the cached prefix after each successful request
58
+ * (Anthropic caches "all messages except the newest"; DeepSeek/OpenAI auto-cache
59
+ * the same prefix). Object-identity based, so it stays valid across the
60
+ * ContextManager's shallow-copied message arrays.
61
+ */
62
+ export class PrefixCacheTracker implements CacheTracker {
63
+ private cachedMessages = new WeakSet<Message>()
64
+ private cachedCount = 0
65
+ private cachedTokens = 0
66
+
67
+ markCached(messages: Message[]): void {
68
+ this.cachedMessages = new WeakSet(messages)
69
+ this.cachedCount = messages.length
70
+ this.cachedTokens = messages.reduce((sum, m) => sum + estimateMessageTokens(m), 0)
71
+ }
72
+
73
+ isInCache(msg: Message): boolean {
74
+ return this.cachedMessages.has(msg)
75
+ }
76
+
77
+ getStatus(): CacheStatus {
78
+ return {
79
+ totalMessages: this.cachedCount,
80
+ cachedMessages: this.cachedCount,
81
+ cachedTokens: this.cachedTokens,
82
+ uncachedTokens: 0,
83
+ }
84
+ }
85
+
86
+ invalidate(): void {
87
+ this.cachedMessages = new WeakSet()
88
+ this.cachedCount = 0
89
+ this.cachedTokens = 0
90
+ }
91
+ }
92
+
49
93
  /**
50
94
  * Estimate the token count for a single message.
51
95
  *
@@ -116,6 +116,17 @@ export class ContextManager {
116
116
  this.checkCompression()
117
117
  }
118
118
 
119
+ /**
120
+ * Seed a batch of pre-existing messages (e.g., an inherited parent
121
+ * conversation). Unlike addMessage, this does not trigger compaction so the
122
+ * byte-identical prefix is preserved for prompt-cache hits.
123
+ */
124
+ seedMessages(messages: Message[]): void {
125
+ if (messages.length === 0) return
126
+ this.messages.push(...messages)
127
+ this.reEstimateTokens()
128
+ }
129
+
119
130
  getMessages(): Message[] {
120
131
  return [...this.messages]
121
132
  }
@@ -252,6 +263,11 @@ export class ContextManager {
252
263
  this.cacheTracker = tracker
253
264
  }
254
265
 
266
+ /** Mark a set of messages as cached by the provider (called after a request). */
267
+ markCached(messages: Message[]): void {
268
+ this.cacheTracker.markCached?.(messages)
269
+ }
270
+
255
271
  /** Get a snapshot of the provider prompt-cache state. */
256
272
  getCacheStatus(): CacheStatus {
257
273
  return this.cacheTracker.getStatus()
@@ -1,6 +1,15 @@
1
1
  import { CREDENTIAL_SENTINEL } from './types'
2
2
  import type { CredentialMaskingConfig } from '../../shared/index.ts'
3
3
 
4
+ /**
5
+ * Well-known secret token prefixes. These are high-signal formats that must
6
+ * never leak into output, independent of the configured patterns.
7
+ * - GitHub: ghp_ (personal access), gho_ (OAuth), ghs_ (server), ghu_/ghr_ (user/server-to-server), github_pat_ (fine-grained)
8
+ * - GitLab: glpat- (personal access), gldt- (deploy), glrt- (runner), gloas- (OAuth app)
9
+ */
10
+ const TOKEN_REDACTION_PATTERN =
11
+ /\b(?:ghp_|gho_|ghs_|ghu_|ghr_|github_pat_|glpat-|gldt-|glrt-|gloas-)[A-Za-z0-9_-]{8,}/g
12
+
4
13
  /**
5
14
  * Scrub credential patterns from stdout/stderr output.
6
15
  * Uses the configured output_scrubbing patterns to detect and replace
@@ -10,6 +19,10 @@ export function maskOutput(output: string, config: CredentialMaskingConfig): str
10
19
  if (!config.enabled || !config.output_scrubbing.enabled) return output
11
20
 
12
21
  let masked = output
22
+
23
+ // Redact bare secret tokens by prefix (always on, independent of config patterns).
24
+ masked = masked.replace(TOKEN_REDACTION_PATTERN, CREDENTIAL_SENTINEL)
25
+
13
26
  for (const pattern of config.output_scrubbing.patterns) {
14
27
  try {
15
28
  // Strip (?i) inline flags — JS uses the 'i' flag instead
@@ -532,6 +532,12 @@ export class QueryEngine {
532
532
  return
533
533
  }
534
534
 
535
+ // Record the provider's cached prefix (all messages except the newest)
536
+ // for cache-aware microcompaction.
537
+ if (messages.length >= 2) {
538
+ this.context.markCached(messages.slice(0, -1))
539
+ }
540
+
535
541
  // Track last assistant content for goal checking
536
542
  if (assistantContent) {
537
543
  this.lastAssistantContent = assistantContent
package/src/index.tsx CHANGED
@@ -21,6 +21,7 @@ import { bootstrapProviders } from './providers/bootstrap'
21
21
  import { InstructionsLoader } from './core/instructions'
22
22
  import { loadSessionMemories, getMemoryManager } from './core/memory/memory-loader'
23
23
  import { ContextManager } from './core/context'
24
+ import { PrefixCacheTracker } from './core/context-token'
24
25
  import { QueryEngine } from './core/engine'
25
26
  import { ExperienceRuleEngine } from './core/rule-engine.js'
26
27
  import { SessionStore } from './core/session-store'
@@ -325,6 +326,8 @@ export async function runApp(options: RunOptions): Promise<void> {
325
326
  compactionThreshold: 0.9,
326
327
  contextWindow: adaptiveThresholds ? modelContextWindow : undefined,
327
328
  })
329
+ // Cache-aware microcompaction: track the provider's prompt-cache prefix.
330
+ context.setCacheTracker(new PrefixCacheTracker())
328
331
 
329
332
  // Adaptive memory budget: scale with model's context window
330
333
  getMemoryManager().setContextWindow(modelContextWindow)
@@ -52,15 +52,20 @@ export class AnthropicProvider implements ProviderInstance {
52
52
  let currentToolId = ''
53
53
  let accumulatedToolInput = ''
54
54
 
55
+ const messages = this.convertMessages(req.messages)
56
+ this.markPrefixCacheBreakpoint(messages)
57
+
55
58
  const body: Record<string, unknown> = {
56
59
  model: req.model,
57
60
  max_tokens: req.maxTokens || 4096,
58
61
  stream: true,
59
- messages: this.convertMessages(req.messages),
62
+ messages,
60
63
  }
61
64
 
62
65
  if (req.systemPrompt) {
63
- body.system = req.systemPrompt
66
+ // Mark the system prompt for prompt caching — it's the largest stable
67
+ // block and byte-identical across turns, so it always hits the cache.
68
+ body.system = [{ type: 'text', text: req.systemPrompt, cache_control: { type: 'ephemeral' } }]
64
69
  }
65
70
 
66
71
  if (req.temperature !== undefined) {
@@ -68,11 +73,14 @@ export class AnthropicProvider implements ProviderInstance {
68
73
  }
69
74
 
70
75
  if (req.tools && req.tools.length > 0) {
71
- body.tools = req.tools.map((t) => ({
76
+ const tools: Record<string, unknown>[] = req.tools.map((t) => ({
72
77
  name: t.name,
73
78
  description: t.description,
74
79
  input_schema: t.parameters || t.input_schema || { type: 'object', properties: {} },
75
80
  }))
81
+ // Cache the tools: mark the last tool definition as a breakpoint.
82
+ tools[tools.length - 1]!.cache_control = { type: 'ephemeral' }
83
+ body.tools = tools
76
84
  }
77
85
 
78
86
  const response = await fetchWithRetry(`${this.baseUrl}/messages`, {
@@ -239,6 +247,20 @@ export class AnthropicProvider implements ProviderInstance {
239
247
  return apiKey.length > 0 && apiKey.startsWith('sk-ant-')
240
248
  }
241
249
 
250
+ /**
251
+ * Mark the stable conversation prefix for prompt caching. The breakpoint is
252
+ * placed on the last block of the second-to-last message, leaving only the
253
+ * newest message uncached.
254
+ */
255
+ private markPrefixCacheBreakpoint(messages: Record<string, unknown>[]): void {
256
+ if (messages.length < 2) return
257
+ const boundary = messages[messages.length - 2]!
258
+ const content = boundary.content
259
+ if (!Array.isArray(content) || content.length === 0) return
260
+ const lastBlock = content[content.length - 1] as Record<string, unknown>
261
+ lastBlock.cache_control = { type: 'ephemeral' }
262
+ }
263
+
242
264
  private convertMessages(messages: Message[]): Record<string, unknown>[] {
243
265
  const result: Record<string, unknown>[] = []
244
266
 
@@ -5,13 +5,26 @@ import { getBackgroundAgentRegistry } from '../../agent/background-registry'
5
5
 
6
6
  const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review']
7
7
 
8
+ /**
9
+ * Resolve whether a sub-agent should run in the background.
10
+ * Precedence: explicit `run_in_background` param > agent frontmatter
11
+ * `background` field > default (background, Claude Code 2.1.232 parity).
12
+ */
13
+ export function resolveRunInBackground(
14
+ runInBackground: boolean | undefined,
15
+ agentDef?: { background?: boolean },
16
+ ): boolean {
17
+ return runInBackground ?? agentDef?.background ?? true
18
+ }
19
+
8
20
  export const agentTool: ToolDefinition = {
9
21
  name: 'Agent',
10
22
  description:
11
23
  'Launch a sub-agent to handle complex, multi-step tasks independently. ' +
12
24
  'Available types: general (default), explore (code search), plan (design), code-review. ' +
13
- 'Set run_in_background: true to execute asynchronously — returns a task ID immediately; ' +
14
- 'results are retrievable via the Task tool (output action) or Agent View.',
25
+ 'Runs in the background by default — returns a task ID immediately; results are ' +
26
+ 'retrievable via the Task tool (output action) or Agent View. ' +
27
+ 'Set run_in_background: false to run synchronously.',
15
28
  category: 'agent',
16
29
  permission: 'ask',
17
30
  parameters: {
@@ -26,7 +39,7 @@ export const agentTool: ToolDefinition = {
26
39
  run_in_background: {
27
40
  type: 'boolean',
28
41
  description:
29
- 'When true, execute asynchronously and return a task ID immediately. Use Task output to retrieve results. Default: false.',
42
+ 'When false, execute synchronously and return the result directly. Default: true (background).',
30
43
  },
31
44
  },
32
45
  required: ['description', 'prompt'],
@@ -35,7 +48,6 @@ export const agentTool: ToolDefinition = {
35
48
  const description = params.description as string
36
49
  const prompt = params.prompt as string
37
50
  const agentType = (params.subagent_type as SubAgentType) || 'general'
38
- const runInBackground = params.run_in_background === true
39
51
 
40
52
  if (!VALID_TYPES.includes(agentType)) {
41
53
  return {
@@ -58,6 +70,10 @@ export const agentTool: ToolDefinition = {
58
70
 
59
71
  // Resolve agent definition from registry (custom > builtin)
60
72
  const agentDef = ctx.agentRegistry?.resolve(agentType)
73
+ const runInBackground = resolveRunInBackground(
74
+ params.run_in_background as boolean | undefined,
75
+ agentDef,
76
+ )
61
77
 
62
78
  try {
63
79
  const sub = new SubAgent(
@@ -6,7 +6,7 @@ export const sendMessageTool: ToolDefinition = {
6
6
  description:
7
7
  'Send a message to another agent or session. ' +
8
8
  'Use "main" for the parent conversation, a background task ID for same-process agents, ' +
9
- 'or a session ID for cross-session messaging (use ListAgents to discover sessions).',
9
+ 'or a session ID (or unique session name) for cross-session messaging (use ListAgents to discover sessions).',
10
10
  category: 'agent',
11
11
  permission: 'auto',
12
12
  parameters: {
@@ -15,7 +15,7 @@ export const sendMessageTool: ToolDefinition = {
15
15
  to: {
16
16
  type: 'string',
17
17
  description:
18
- 'Recipient: "main" for the parent conversation, a background task ID, or a session ID for cross-session messaging.',
18
+ 'Recipient: "main" for the parent conversation, a background task ID, or a session ID / unique session name for cross-session messaging.',
19
19
  },
20
20
  summary: {
21
21
  type: 'string',
@@ -1,5 +1,6 @@
1
1
  import type { ToolDefinition, CredentialMaskingConfig } from '../../shared/index.ts'
2
2
  import { sanitizeCommand } from '../../shared/sanitize.ts'
3
+ import { DANGEROUS_GIT_PATTERNS } from './git.ts'
3
4
 
4
5
  // Injected at startup — set via index.tsx
5
6
  let credentialConfig: CredentialMaskingConfig | undefined
@@ -124,6 +125,19 @@ function isBlocked(command: string): string | null {
124
125
  return `Command "${sanitizedFirstWord}" rejected by security policy.`
125
126
  }
126
127
 
128
+ // Detect dangerous git operations invoked via Bash. The Git tool guards these,
129
+ // but shelling out with `git push --force` would bypass it — apply the same
130
+ // pattern list to any Bash command that starts with a git invocation.
131
+ const gitInvocation = normalized.trim().match(/^(?:sudo\s+)?git(?:\s+|$)(.*)$/i)
132
+ if (gitInvocation) {
133
+ const subcommand = gitInvocation[1] || ''
134
+ for (const { pattern, description } of DANGEROUS_GIT_PATTERNS) {
135
+ if (pattern.test(subcommand)) {
136
+ return `Dangerous git command blocked: "${description}". Run manually if intended.`
137
+ }
138
+ }
139
+ }
140
+
127
141
  // Check dangerous patterns (on original, normalized, and sanitized)
128
142
  for (const pattern of BLOCKED_PATTERNS) {
129
143
  if (pattern.test(command) || pattern.test(normalized) || pattern.test(sanitized)) {
@@ -2,7 +2,7 @@ import type { ToolDefinition } from '../../shared/index.ts'
2
2
 
3
3
  // P0-4 (v2.1.222 alignment): Regex-based word-boundary patterns replace
4
4
  // fragile substring matching. Each pattern describes what it blocks.
5
- const DANGEROUS_GIT_PATTERNS: Array<{ pattern: RegExp; description: string }> = [
5
+ export const DANGEROUS_GIT_PATTERNS: Array<{ pattern: RegExp; description: string }> = [
6
6
  // Destructive push
7
7
  { pattern: /\bpush\s+.*--force(?:-with-lease)?\b/, description: 'push --force' },
8
8
  { pattern: /\bpush\s+.*-[fF]\b/, description: 'push -f (force)' },
@@ -4041,8 +4041,10 @@ const forkCmd: CommandHandler = async (ctx, args) => {
4041
4041
  ctx.engine.getTools(),
4042
4042
  ctx.engine.getPermission(),
4043
4043
  )
4044
+ const parentContext = ctx.engine.getContext()
4044
4045
  const result = await sa.execute(prompt, 'fork: ' + prompt.slice(0, 60), {
4045
4046
  worktreePath: wtPath,
4047
+ inheritContext: { messages: parentContext.getMessages() },
4046
4048
  })
4047
4049
  try {
4048
4050
  const { execSync: ex } = await import('node:child_process')