@miphamai/cli 0.36.2 → 0.38.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 +1 -1
- package/src/agent/agent-registry.ts +1 -2
- package/src/agent/cross-session/discovery.ts +45 -1
- package/src/agent/cross-session/file-inbox.ts +15 -0
- package/src/agent/message-router.ts +59 -12
- package/src/agent/sub-agent.ts +7 -0
- package/src/agent/types.ts +6 -1
- package/src/core/context-token.ts +44 -0
- package/src/core/context.ts +16 -0
- package/src/core/credential-masker/output-scrub.ts +13 -0
- package/src/core/engine.ts +25 -2
- package/src/core/red-team.ts +16 -1
- package/src/core/workspace-trust.ts +25 -2
- package/src/i18n-core/locales/en-US.json +4 -0
- package/src/i18n-core/locales/zh-CN.json +4 -0
- package/src/index.tsx +11 -2
- package/src/mcp/client.ts +56 -17
- package/src/providers/anthropic.ts +25 -3
- package/src/tools/agent/agent.ts +20 -4
- package/src/tools/agent/send-message.ts +2 -2
- package/src/tools/exec/bash.ts +15 -1
- package/src/tools/exec/git.ts +1 -1
- package/src/ui/app.tsx +36 -0
- package/src/ui/commands.ts +12 -1
- package/src/ui/input.tsx +21 -0
package/package.json
CHANGED
|
@@ -73,7 +73,7 @@ export class AgentRegistry {
|
|
|
73
73
|
.split(',')
|
|
74
74
|
.map((s) => s.trim())
|
|
75
75
|
: undefined,
|
|
76
|
-
background:
|
|
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
|
}
|
|
@@ -5,6 +5,7 @@ import {
|
|
|
5
5
|
existsSync,
|
|
6
6
|
mkdirSync,
|
|
7
7
|
unlinkSync,
|
|
8
|
+
statSync,
|
|
8
9
|
} from 'node:fs'
|
|
9
10
|
import { join } from 'node:path'
|
|
10
11
|
import { homedir, hostname } from 'node:os'
|
|
@@ -13,6 +14,9 @@ import type { SessionInfo } from '../../shared/types'
|
|
|
13
14
|
const MIPHAM_HOME = join(homedir(), '.mipham')
|
|
14
15
|
const ACTIVE_SESSIONS_DIR = join(MIPHAM_HOME, '.active-sessions')
|
|
15
16
|
|
|
17
|
+
/** A session whose heartbeat file hasn't been touched in this long is dead. */
|
|
18
|
+
const STALE_SESSION_TTL_MS = 10 * 60 * 1000 // 10 min — heartbeat is 30s
|
|
19
|
+
|
|
16
20
|
/**
|
|
17
21
|
* Register the current session as active.
|
|
18
22
|
* Writes a SessionInfo JSON file + updates mtime for heartbeat.
|
|
@@ -56,11 +60,19 @@ export function discoverSessions(): SessionInfo[] {
|
|
|
56
60
|
|
|
57
61
|
try {
|
|
58
62
|
const files = readdirSync(ACTIVE_SESSIONS_DIR).filter((f) => f.endsWith('.json'))
|
|
63
|
+
const now = Date.now()
|
|
59
64
|
|
|
60
65
|
const sessions: SessionInfo[] = []
|
|
61
66
|
for (const file of files) {
|
|
67
|
+
const filePath = join(ACTIVE_SESSIONS_DIR, file)
|
|
62
68
|
try {
|
|
63
|
-
|
|
69
|
+
// Prune stale session files (crashed without unregistering). A live
|
|
70
|
+
// session's 30s heartbeat keeps mtime fresh; 10 min of silence = dead.
|
|
71
|
+
if (now - statSync(filePath).mtimeMs > STALE_SESSION_TTL_MS) {
|
|
72
|
+
unlinkSync(filePath)
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
const raw = readFileSync(filePath, 'utf-8')
|
|
64
76
|
const info = JSON.parse(raw) as SessionInfo
|
|
65
77
|
sessions.push(info)
|
|
66
78
|
} catch {
|
|
@@ -97,3 +109,35 @@ export function createSessionInfo(
|
|
|
97
109
|
model,
|
|
98
110
|
}
|
|
99
111
|
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Return a unique session name among active sessions. If `preferred` is taken
|
|
115
|
+
* by another session (excluding `selfId`), append `-2`, `-3`, … until free.
|
|
116
|
+
* Pure with respect to `existing` — no filesystem access, so it's unit-testable.
|
|
117
|
+
*/
|
|
118
|
+
export function ensureUniqueSessionName(
|
|
119
|
+
preferred: string,
|
|
120
|
+
existing: SessionInfo[],
|
|
121
|
+
selfId?: string,
|
|
122
|
+
): string {
|
|
123
|
+
const taken = new Set(existing.filter((s) => s.id !== selfId).map((s) => s.name))
|
|
124
|
+
if (!taken.has(preferred)) return preferred
|
|
125
|
+
let i = 2
|
|
126
|
+
while (taken.has(`${preferred}-${i}`)) i++
|
|
127
|
+
return `${preferred}-${i}`
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Rename an active session in the registry. Enforces uniqueness against other
|
|
132
|
+
* live sessions (excluding self). Returns null if the session isn't registered.
|
|
133
|
+
*/
|
|
134
|
+
export function renameActiveSession(sessionId: string, newName: string): string | null {
|
|
135
|
+
const filePath = join(ACTIVE_SESSIONS_DIR, `${sessionId}.json`)
|
|
136
|
+
if (!existsSync(filePath)) return null
|
|
137
|
+
const raw = readFileSync(filePath, 'utf-8')
|
|
138
|
+
const info = JSON.parse(raw) as SessionInfo
|
|
139
|
+
const others = discoverSessions().filter((s) => s.id !== sessionId)
|
|
140
|
+
info.name = ensureUniqueSessionName(newName, others)
|
|
141
|
+
writeFileSync(filePath, JSON.stringify(info, null, 2), 'utf-8')
|
|
142
|
+
return info.name
|
|
143
|
+
}
|
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
unlinkSync,
|
|
7
7
|
existsSync,
|
|
8
8
|
renameSync,
|
|
9
|
+
lstatSync,
|
|
9
10
|
} from 'node:fs'
|
|
10
11
|
import { join } from 'node:path'
|
|
11
12
|
import { homedir } from 'node:os'
|
|
@@ -16,6 +17,15 @@ import type { SessionInfo } from '../../shared/types'
|
|
|
16
17
|
const MIPHAM_HOME = join(homedir(), '.mipham')
|
|
17
18
|
const INBOX_DIR = join(MIPHAM_HOME, 'inbox')
|
|
18
19
|
|
|
20
|
+
/** True if a path exists and is a symbolic link (symlink-attack guard). */
|
|
21
|
+
function isSymlink(path: string): boolean {
|
|
22
|
+
try {
|
|
23
|
+
return lstatSync(path).isSymbolicLink()
|
|
24
|
+
} catch {
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
19
29
|
/**
|
|
20
30
|
* Filesystem-based cross-session transport.
|
|
21
31
|
*
|
|
@@ -43,6 +53,9 @@ export class FileInboxTransport implements CrossSessionTransport {
|
|
|
43
53
|
const inboxDir = join(INBOX_DIR, toSessionId)
|
|
44
54
|
this.ensureDir(inboxDir)
|
|
45
55
|
|
|
56
|
+
// Symlink guard: refuse to write through a symlinked inbox directory.
|
|
57
|
+
if (isSymlink(INBOX_DIR) || isSymlink(inboxDir)) return false
|
|
58
|
+
|
|
46
59
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
47
60
|
const filename = `${timestamp}-${msg.id}.json`
|
|
48
61
|
const filePath = join(inboxDir, filename)
|
|
@@ -71,6 +84,8 @@ export class FileInboxTransport implements CrossSessionTransport {
|
|
|
71
84
|
this.ensureInboxRoot()
|
|
72
85
|
const inboxDir = join(INBOX_DIR, sessionId)
|
|
73
86
|
if (!existsSync(inboxDir)) return []
|
|
87
|
+
// Symlink guard: refuse to read through a symlinked inbox directory.
|
|
88
|
+
if (isSymlink(INBOX_DIR) || isSymlink(inboxDir)) return []
|
|
74
89
|
|
|
75
90
|
try {
|
|
76
91
|
const files = readdirSync(inboxDir)
|
|
@@ -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,53 @@ 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
|
+
|
|
43
|
+
export interface MentionParse {
|
|
44
|
+
name: string
|
|
45
|
+
message: string
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Parse a user-input `@name message` mention. Returns null when the input does
|
|
50
|
+
* not start with an @mention. The message may be empty — callers decide whether
|
|
51
|
+
* an empty body is valid. Used by the input bar to route a direct cross-session
|
|
52
|
+
* message without going through the AI.
|
|
53
|
+
*/
|
|
54
|
+
export function parseMention(input: string): MentionParse | null {
|
|
55
|
+
const trimmed = input.trim()
|
|
56
|
+
const m = /^@(\S+)(?:\s+([\s\S]+))?$/.exec(trimmed)
|
|
57
|
+
if (!m) return null
|
|
58
|
+
return { name: m[1]!, message: (m[2] ?? '').trim() }
|
|
59
|
+
}
|
|
60
|
+
|
|
13
61
|
/**
|
|
14
62
|
* MessageRouter decides how to deliver a message based on the recipient.
|
|
15
63
|
*
|
|
@@ -33,27 +81,26 @@ export class MessageRouter {
|
|
|
33
81
|
}
|
|
34
82
|
}
|
|
35
83
|
|
|
36
|
-
// Cross-session routing
|
|
84
|
+
// Cross-session routing (by session ID or bare name)
|
|
37
85
|
const sessions = discoverSessions()
|
|
38
|
-
const
|
|
86
|
+
const resolution = resolveRecipientSession(sessions, to)
|
|
39
87
|
|
|
40
|
-
if (
|
|
41
|
-
return {
|
|
42
|
-
success: false,
|
|
43
|
-
routedTo: 'unknown',
|
|
44
|
-
error: `No active session found with ID "${to}". Use ListAgents to discover available sessions.`,
|
|
45
|
-
}
|
|
88
|
+
if (resolution.error) {
|
|
89
|
+
return { success: false, routedTo: 'unknown', error: resolution.error }
|
|
46
90
|
}
|
|
91
|
+
const targetSession = resolution.session!
|
|
47
92
|
|
|
48
|
-
// Get sender info
|
|
49
|
-
|
|
93
|
+
// Get sender info — resolve the human-readable name when the sender is a
|
|
94
|
+
// registered session, else fall back to the raw id (e.g. non-session senders).
|
|
95
|
+
const senderName = discoverSessions().find((s) => s.id === from)?.name ?? from
|
|
96
|
+
const senderSession = createSessionInfo(from, senderName)
|
|
50
97
|
|
|
51
98
|
try {
|
|
52
99
|
const transport = getFileInboxTransport()
|
|
53
100
|
const msg: AgentMessage = {
|
|
54
101
|
id: `xmsg-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`,
|
|
55
102
|
from,
|
|
56
|
-
to,
|
|
103
|
+
to: targetSession.id,
|
|
57
104
|
summary: summary.slice(0, 200),
|
|
58
105
|
message,
|
|
59
106
|
timestamp: new Date(),
|
|
@@ -61,7 +108,7 @@ export class MessageRouter {
|
|
|
61
108
|
type: 'message',
|
|
62
109
|
}
|
|
63
110
|
|
|
64
|
-
const delivered = await transport.send(senderSession,
|
|
111
|
+
const delivered = await transport.send(senderSession, targetSession.id, msg)
|
|
65
112
|
if (!delivered) {
|
|
66
113
|
return { success: false, routedTo: 'inbox', error: 'Failed to write message to inbox.' }
|
|
67
114
|
}
|
package/src/agent/sub-agent.ts
CHANGED
|
@@ -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()
|
package/src/agent/types.ts
CHANGED
|
@@ -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
|
|
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
|
*
|
package/src/core/context.ts
CHANGED
|
@@ -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
|
package/src/core/engine.ts
CHANGED
|
@@ -35,7 +35,7 @@ import { SelfCritique } from './self-critique.js'
|
|
|
35
35
|
import { UsageTracker } from './usage-tracker'
|
|
36
36
|
import { buildRequest, sendInferenceCheck, isInferenceHookEnabled } from './inference-hook'
|
|
37
37
|
import { getFileInboxTransport } from '../agent/cross-session/file-inbox'
|
|
38
|
-
import { getMessageBus } from '../agent/message-bus'
|
|
38
|
+
import { getMessageBus, type AgentMessage } from '../agent/message-bus'
|
|
39
39
|
import { createT } from '../i18n-core/t'
|
|
40
40
|
import enUS from '../i18n-core/locales/en-US.json'
|
|
41
41
|
import zhCN from '../i18n-core/locales/zh-CN.json'
|
|
@@ -47,6 +47,20 @@ const bundles: Record<string, TranslationMap> = {
|
|
|
47
47
|
}
|
|
48
48
|
const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
|
|
49
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Drop inbound messages whose timestamp is older than the dialog-expiry TTL.
|
|
52
|
+
* A stale message's approval dialog is no longer relevant, so it's discarded
|
|
53
|
+
* before forwarding. Pure — unit-testable without touching the inbox.
|
|
54
|
+
*/
|
|
55
|
+
export function filterExpiredMessages(
|
|
56
|
+
messages: AgentMessage[],
|
|
57
|
+
dialogExpirySeconds: number,
|
|
58
|
+
now = Date.now(),
|
|
59
|
+
): AgentMessage[] {
|
|
60
|
+
const maxAgeMs = dialogExpirySeconds * 1000
|
|
61
|
+
return messages.filter((m) => now - new Date(m.timestamp).getTime() <= maxAgeMs)
|
|
62
|
+
}
|
|
63
|
+
|
|
50
64
|
export class QueryEngine {
|
|
51
65
|
private hookEngine?: HookEngine
|
|
52
66
|
private artifactServer?: ArtifactServer
|
|
@@ -131,8 +145,11 @@ export class QueryEngine {
|
|
|
131
145
|
const transport = getFileInboxTransport()
|
|
132
146
|
const messages = await transport.poll(this.sessionId)
|
|
133
147
|
if (messages.length > 0) {
|
|
148
|
+
// dialogExpiry: discard messages older than the approval-dialog TTL
|
|
149
|
+
const fresh = filterExpiredMessages(messages, this.crossSessionConfig.dialogExpiry)
|
|
150
|
+
if (fresh.length === 0) return
|
|
134
151
|
const bus = getMessageBus()
|
|
135
|
-
for (const msg of
|
|
152
|
+
for (const msg of fresh) {
|
|
136
153
|
// P2-1: Trigger Notification hook for cross-session messages
|
|
137
154
|
if (this.hookEngine) {
|
|
138
155
|
this.hookEngine
|
|
@@ -532,6 +549,12 @@ export class QueryEngine {
|
|
|
532
549
|
return
|
|
533
550
|
}
|
|
534
551
|
|
|
552
|
+
// Record the provider's cached prefix (all messages except the newest)
|
|
553
|
+
// for cache-aware microcompaction.
|
|
554
|
+
if (messages.length >= 2) {
|
|
555
|
+
this.context.markCached(messages.slice(0, -1))
|
|
556
|
+
}
|
|
557
|
+
|
|
535
558
|
// Track last assistant content for goal checking
|
|
536
559
|
if (assistantContent) {
|
|
537
560
|
this.lastAssistantContent = assistantContent
|
package/src/core/red-team.ts
CHANGED
|
@@ -19,6 +19,7 @@
|
|
|
19
19
|
import type { ConstitutionLoader } from './constitution-loader.js'
|
|
20
20
|
import type { PreFlightChecker } from './preflight-checker.js'
|
|
21
21
|
import type { ErrorSignatureDB } from './error-signature-db.js'
|
|
22
|
+
import { isBlocked } from '../tools/exec/bash'
|
|
22
23
|
|
|
23
24
|
// ── Types ──
|
|
24
25
|
|
|
@@ -262,7 +263,21 @@ export class RedTeam {
|
|
|
262
263
|
}
|
|
263
264
|
}
|
|
264
265
|
|
|
265
|
-
// 3.
|
|
266
|
+
// 3. Check the real Bash tool's isBlocked — ground-truth defense, not just
|
|
267
|
+
// the constitution/preflight abstraction. Catches e.g. `git push --force`.
|
|
268
|
+
if (attack.toolName === 'Bash' && typeof attack.params.command === 'string') {
|
|
269
|
+
const blockedReason = isBlocked(attack.params.command)
|
|
270
|
+
if (blockedReason) {
|
|
271
|
+
return {
|
|
272
|
+
attack,
|
|
273
|
+
blocked: true,
|
|
274
|
+
caughtBy: 'bash-tool',
|
|
275
|
+
message: blockedReason,
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// 4. Not caught — security gap
|
|
266
281
|
return {
|
|
267
282
|
attack,
|
|
268
283
|
blocked: false,
|
|
@@ -25,6 +25,26 @@ function realPath(dir: string): string {
|
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
|
|
28
|
+
/**
|
|
29
|
+
* True if a `.git` file or directory exists anywhere strictly between `dir` and
|
|
30
|
+
* its trusted ancestor `ancestor`. A `.git` marks the root of a separate
|
|
31
|
+
* repository — trust does not cross that boundary (nested-repo isolation).
|
|
32
|
+
*/
|
|
33
|
+
function hasGitBoundary(dir: string, ancestor: string): boolean {
|
|
34
|
+
let cur = dir
|
|
35
|
+
// Case-insensitive termination matches isTrusted's `toLowerCase()` ancestor
|
|
36
|
+
// check — otherwise a path referenced with different casing than when it was
|
|
37
|
+
// trusted would walk past the ancestor and miss the boundary.
|
|
38
|
+
const targetLower = ancestor.toLowerCase()
|
|
39
|
+
while (cur.toLowerCase() !== targetLower && cur.length > ancestor.length) {
|
|
40
|
+
if (existsSync(join(cur, '.git'))) return true
|
|
41
|
+
const parent = dirname(cur)
|
|
42
|
+
if (parent === cur) break
|
|
43
|
+
cur = parent
|
|
44
|
+
}
|
|
45
|
+
return false
|
|
46
|
+
}
|
|
47
|
+
|
|
28
48
|
/**
|
|
29
49
|
* Manages the workspace trust store.
|
|
30
50
|
*
|
|
@@ -82,8 +102,11 @@ export class WorkspaceTrust {
|
|
|
82
102
|
const trustedLower = trusted.toLowerCase()
|
|
83
103
|
// Exact match
|
|
84
104
|
if (resolvedLower === trustedLower) return true
|
|
85
|
-
// Ancestor match: trusted dir is a parent of the target
|
|
86
|
-
|
|
105
|
+
// Ancestor match: trusted dir is a parent of the target. Trust does not
|
|
106
|
+
// cross a nested git-repository boundary (vendored/submodule isolation).
|
|
107
|
+
if (resolvedLower.startsWith(trustedLower + '/') && !hasGitBoundary(resolved, trusted)) {
|
|
108
|
+
return true
|
|
109
|
+
}
|
|
87
110
|
}
|
|
88
111
|
|
|
89
112
|
return false
|
|
@@ -682,6 +682,10 @@
|
|
|
682
682
|
"count": "{shown} of {total}",
|
|
683
683
|
"all": "all"
|
|
684
684
|
},
|
|
685
|
+
"mention_hints": {
|
|
686
|
+
"label": "Sessions:",
|
|
687
|
+
"empty": "No active sessions"
|
|
688
|
+
},
|
|
685
689
|
"picker": {
|
|
686
690
|
"title": "Select Model",
|
|
687
691
|
"nav_help": "←→ navigate · ↑↓ move · Enter select · Esc close",
|
package/src/index.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import React from 'react'
|
|
2
|
-
import { join } from 'node:path'
|
|
2
|
+
import { join, basename } from 'node:path'
|
|
3
3
|
import { homedir } from 'node:os'
|
|
4
4
|
import { existsSync } from 'node:fs'
|
|
5
5
|
import { render } from 'ink'
|
|
@@ -16,11 +16,14 @@ import {
|
|
|
16
16
|
heartbeatSession,
|
|
17
17
|
unregisterSession,
|
|
18
18
|
createSessionInfo,
|
|
19
|
+
ensureUniqueSessionName,
|
|
20
|
+
discoverSessions,
|
|
19
21
|
} from './agent/cross-session/discovery'
|
|
20
22
|
import { bootstrapProviders } from './providers/bootstrap'
|
|
21
23
|
import { InstructionsLoader } from './core/instructions'
|
|
22
24
|
import { loadSessionMemories, getMemoryManager } from './core/memory/memory-loader'
|
|
23
25
|
import { ContextManager } from './core/context'
|
|
26
|
+
import { PrefixCacheTracker } from './core/context-token'
|
|
24
27
|
import { QueryEngine } from './core/engine'
|
|
25
28
|
import { ExperienceRuleEngine } from './core/rule-engine.js'
|
|
26
29
|
import { SessionStore } from './core/session-store'
|
|
@@ -325,6 +328,8 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
325
328
|
compactionThreshold: 0.9,
|
|
326
329
|
contextWindow: adaptiveThresholds ? modelContextWindow : undefined,
|
|
327
330
|
})
|
|
331
|
+
// Cache-aware microcompaction: track the provider's prompt-cache prefix.
|
|
332
|
+
context.setCacheTracker(new PrefixCacheTracker())
|
|
328
333
|
|
|
329
334
|
// Adaptive memory budget: scale with model's context window
|
|
330
335
|
getMemoryManager().setContextWindow(modelContextWindow)
|
|
@@ -512,9 +517,13 @@ export async function runApp(options: RunOptions): Promise<void> {
|
|
|
512
517
|
|
|
513
518
|
// ── Cross-session messaging: register session, heartbeat, shutdown ──
|
|
514
519
|
engine.setSessionId(sessionName)
|
|
520
|
+
// Human-readable, cross-session-addressable name. Defaults to the cwd basename
|
|
521
|
+
// so `@mipham-code` can address this session; uniqueness is enforced against
|
|
522
|
+
// other live sessions (suffix -2, -3, …). The id stays a stable `session-<ts>`.
|
|
523
|
+
const defaultName = basename(process.cwd()) || 'session'
|
|
515
524
|
const sessionInfo = createSessionInfo(
|
|
516
525
|
sessionName,
|
|
517
|
-
|
|
526
|
+
ensureUniqueSessionName(defaultName, discoverSessions()),
|
|
518
527
|
process.cwd(),
|
|
519
528
|
defaultProvider,
|
|
520
529
|
defaultModel,
|
package/src/mcp/client.ts
CHANGED
|
@@ -22,6 +22,15 @@ const bundles: Record<string, TranslationMap> = {
|
|
|
22
22
|
}
|
|
23
23
|
const t = createT(bundles['en-US'] || (enUS as TranslationMap), enUS as TranslationMap)
|
|
24
24
|
|
|
25
|
+
// Connect-handshake timeout: a hung MCP server should fail startup fast rather
|
|
26
|
+
// than block on the per-request 60s timeout. Overridable via env for tests.
|
|
27
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 15_000
|
|
28
|
+
|
|
29
|
+
function connectTimeoutMs(): number {
|
|
30
|
+
const env = Number(process.env.MIPHAM_MCP_CONNECT_TIMEOUT_MS)
|
|
31
|
+
return Number.isFinite(env) && env > 0 ? env : DEFAULT_CONNECT_TIMEOUT_MS
|
|
32
|
+
}
|
|
33
|
+
|
|
25
34
|
interface ActiveConnection {
|
|
26
35
|
config: McpServerConfig
|
|
27
36
|
transport: Transport
|
|
@@ -167,33 +176,63 @@ export class McpClient {
|
|
|
167
176
|
this.connections.set(config.name, connection)
|
|
168
177
|
|
|
169
178
|
try {
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
179
|
+
await this.withConnectTimeout(config.name, async () => {
|
|
180
|
+
// Start the transport (transport-specific), then perform the handshake.
|
|
181
|
+
if (transport instanceof HttpTransport) {
|
|
182
|
+
await transport.start(config.url ?? '', config.headers, config.env)
|
|
183
|
+
} else {
|
|
184
|
+
await transport.start(config.command ?? '', config.args ?? [], config.env)
|
|
185
|
+
}
|
|
186
|
+
const initResult: InitializeResult = await protocol.initialize()
|
|
177
187
|
|
|
178
|
-
|
|
179
|
-
|
|
188
|
+
connection.status = 'connected'
|
|
189
|
+
connection.serverInfo = initResult.serverInfo
|
|
180
190
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
191
|
+
// Wire tools-changed notification
|
|
192
|
+
protocol.on('tools-changed', async () => {
|
|
193
|
+
await this.onToolsChanged(config.name)
|
|
194
|
+
})
|
|
185
195
|
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
196
|
+
// Discover tools
|
|
197
|
+
if (initResult.capabilities.tools) {
|
|
198
|
+
connection.tools = await protocol.listTools()
|
|
199
|
+
}
|
|
200
|
+
})
|
|
190
201
|
} catch (err) {
|
|
191
202
|
connection.status = 'error'
|
|
192
203
|
connection.error = String(err)
|
|
204
|
+
try {
|
|
205
|
+
await transport.close()
|
|
206
|
+
} catch {
|
|
207
|
+
// Best-effort cleanup on a failed connect
|
|
208
|
+
}
|
|
193
209
|
throw err
|
|
194
210
|
}
|
|
195
211
|
}
|
|
196
212
|
|
|
213
|
+
/** Race the connect handshake against a timeout so a hung server fails fast. */
|
|
214
|
+
private async withConnectTimeout<T>(name: string, fn: () => Promise<T>): Promise<T> {
|
|
215
|
+
const timeoutMs = connectTimeoutMs()
|
|
216
|
+
let timer: ReturnType<typeof setTimeout> | null = null
|
|
217
|
+
// Swallow a late rejection: if the timeout wins, transport.close() in the
|
|
218
|
+
// caller's catch makes fn()'s pending request reject after we've moved on.
|
|
219
|
+
const work = fn()
|
|
220
|
+
work.catch(() => {})
|
|
221
|
+
try {
|
|
222
|
+
return await Promise.race([
|
|
223
|
+
work,
|
|
224
|
+
new Promise<never>((_, reject) => {
|
|
225
|
+
timer = setTimeout(
|
|
226
|
+
() => reject(new Error(`MCP connect timed out for "${name}" after ${timeoutMs}ms`)),
|
|
227
|
+
timeoutMs,
|
|
228
|
+
)
|
|
229
|
+
}),
|
|
230
|
+
])
|
|
231
|
+
} finally {
|
|
232
|
+
if (timer) clearTimeout(timer)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
197
236
|
/**
|
|
198
237
|
* Disconnect an MCP server and return the names of its registered tools
|
|
199
238
|
* so the caller can unregister them from the central tool registry.
|
|
@@ -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
|
|
62
|
+
messages,
|
|
60
63
|
}
|
|
61
64
|
|
|
62
65
|
if (req.systemPrompt) {
|
|
63
|
-
|
|
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
|
-
|
|
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
|
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -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
|
-
'
|
|
14
|
-
'
|
|
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
|
|
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',
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -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
|
|
@@ -103,7 +104,7 @@ function normalizeEscapes(command: string): string {
|
|
|
103
104
|
)
|
|
104
105
|
}
|
|
105
106
|
|
|
106
|
-
function isBlocked(command: string): string | null {
|
|
107
|
+
export function isBlocked(command: string): string | null {
|
|
107
108
|
// Normalize ANSI-C escape sequences for defense-in-depth
|
|
108
109
|
const normalized = normalizeEscapes(command)
|
|
109
110
|
// P0-1: Also sanitize for permission check (strips invisible chars, normalizes homoglyphs)
|
|
@@ -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)) {
|
package/src/tools/exec/git.ts
CHANGED
|
@@ -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)' },
|
package/src/ui/app.tsx
CHANGED
|
@@ -11,6 +11,8 @@ import { setPreference } from '../config/preferences'
|
|
|
11
11
|
import { saveProviderApiKey } from '../config/loader'
|
|
12
12
|
import { AgentRegistry } from '../agent/agent-registry'
|
|
13
13
|
import { getBackgroundAgentRegistry } from '../agent/background-registry'
|
|
14
|
+
import { getMessageRouter, parseMention, resolveRecipientSession } from '../agent/message-router'
|
|
15
|
+
import { discoverSessions } from '../agent/cross-session/discovery'
|
|
14
16
|
import { ChatPanel } from './chat'
|
|
15
17
|
import { InputBar } from './input'
|
|
16
18
|
import { ModelPicker } from './picker'
|
|
@@ -325,6 +327,40 @@ export function App({
|
|
|
325
327
|
async (input: string) => {
|
|
326
328
|
if (!input.trim()) return
|
|
327
329
|
|
|
330
|
+
// ── @mention: direct cross-session message — only when the name resolves
|
|
331
|
+
// to a live session; otherwise fall through to normal AI processing so a
|
|
332
|
+
// leading `@word` (e.g. "@bob please review") isn't hijacked as a send. ──
|
|
333
|
+
const mention = parseMention(input)
|
|
334
|
+
if (mention && resolveRecipientSession(discoverSessions(), mention.name).session) {
|
|
335
|
+
if (!mention.message) {
|
|
336
|
+
setMessages((prev) => [
|
|
337
|
+
...prev,
|
|
338
|
+
{ role: 'user', content: input },
|
|
339
|
+
{ role: 'system', content: 'Usage: @session-name <message>' },
|
|
340
|
+
])
|
|
341
|
+
return
|
|
342
|
+
}
|
|
343
|
+
const mentionSummary =
|
|
344
|
+
mention.message.length > 50 ? mention.message.slice(0, 47) + '...' : mention.message
|
|
345
|
+
const result = await getMessageRouter().route(
|
|
346
|
+
sessionId || 'main',
|
|
347
|
+
mention.name,
|
|
348
|
+
mentionSummary,
|
|
349
|
+
mention.message,
|
|
350
|
+
)
|
|
351
|
+
setMessages((prev) => [
|
|
352
|
+
...prev,
|
|
353
|
+
{ role: 'user', content: input },
|
|
354
|
+
{
|
|
355
|
+
role: 'system',
|
|
356
|
+
content: result.success
|
|
357
|
+
? `── Message sent to ${mention.name} ──${result.messageId ? `\nID: ${result.messageId}` : ''}`
|
|
358
|
+
: `❌ Failed to send to ${mention.name}: ${result.error}`,
|
|
359
|
+
},
|
|
360
|
+
])
|
|
361
|
+
return
|
|
362
|
+
}
|
|
363
|
+
|
|
328
364
|
// ── Slash command dispatch ──
|
|
329
365
|
if (looksLikeSlashCommand(input)) {
|
|
330
366
|
const { command, args } = parseSlashCommand(input)
|
package/src/ui/commands.ts
CHANGED
|
@@ -12,6 +12,7 @@ import type { Message } from '../shared/types.js'
|
|
|
12
12
|
import { McpClient } from '../mcp/client'
|
|
13
13
|
import { NPM_UPDATE_COMMAND, PACKAGE_VERSION } from '../shared/index.ts'
|
|
14
14
|
import { getPreference } from '../config/preferences'
|
|
15
|
+
import { loadCrossSessionConfig } from '../config/loader'
|
|
15
16
|
import { stripIndent } from './strip-indent.js'
|
|
16
17
|
import { createT } from '../i18n-core/t'
|
|
17
18
|
import type { TranslationMap } from '../i18n-core/types'
|
|
@@ -43,6 +44,7 @@ import { keysCmd } from '../commands/keys'
|
|
|
43
44
|
import { workflowViewCmd, workflowWatchCmd } from '../commands/workflow-view.js'
|
|
44
45
|
import { execSync } from 'node:child_process'
|
|
45
46
|
import { OLLAMA_PRESET_MODELS } from '../shared/constants'
|
|
47
|
+
import { renameActiveSession } from '../agent/cross-session/discovery'
|
|
46
48
|
|
|
47
49
|
export interface CommandContext {
|
|
48
50
|
engine: QueryEngine
|
|
@@ -517,12 +519,16 @@ const switchCmd: CommandHandler = (ctx, args) => {
|
|
|
517
519
|
const configCmd: CommandHandler = (ctx) => {
|
|
518
520
|
const t = resolveT(ctx)
|
|
519
521
|
const c = ctx.config
|
|
522
|
+
const xs = loadCrossSessionConfig(process.cwd())
|
|
520
523
|
const lines = [
|
|
521
524
|
`version: ${c.version}`,
|
|
522
525
|
`defaultProvider: ${c.defaultProvider}`,
|
|
523
526
|
`defaultModel: ${c.defaultModel}`,
|
|
524
527
|
`permission: ${c.permission}`,
|
|
525
528
|
`providers: ${c.providers.length} configured`,
|
|
529
|
+
'',
|
|
530
|
+
`crossSessionInbound: ${xs.crossSessionInbound}`,
|
|
531
|
+
`dialogExpiry: ${xs.dialogExpiry}s`,
|
|
526
532
|
]
|
|
527
533
|
return {
|
|
528
534
|
content: `${t('commands.config.title')}\n${lines.join('\n')}\n\n${t('commands.config.edit')}`,
|
|
@@ -1588,7 +1594,10 @@ const renameCmd: CommandHandler = (ctx, args) => {
|
|
|
1588
1594
|
return { content: t('commands.rename.usage') }
|
|
1589
1595
|
}
|
|
1590
1596
|
ctx.setSessionTitle(name.trim())
|
|
1591
|
-
|
|
1597
|
+
// Persist to the cross-session registry so `@name` can address this session.
|
|
1598
|
+
// Returns the (possibly uniquified) final name — surface that to the user.
|
|
1599
|
+
const finalName = renameActiveSession(ctx.sessionId, name.trim())
|
|
1600
|
+
return { content: t('commands.rename.confirmed', { name: finalName ?? name.trim() }) }
|
|
1592
1601
|
}
|
|
1593
1602
|
|
|
1594
1603
|
const goalCmd: CommandHandler = (ctx, args) => {
|
|
@@ -4041,8 +4050,10 @@ const forkCmd: CommandHandler = async (ctx, args) => {
|
|
|
4041
4050
|
ctx.engine.getTools(),
|
|
4042
4051
|
ctx.engine.getPermission(),
|
|
4043
4052
|
)
|
|
4053
|
+
const parentContext = ctx.engine.getContext()
|
|
4044
4054
|
const result = await sa.execute(prompt, 'fork: ' + prompt.slice(0, 60), {
|
|
4045
4055
|
worktreePath: wtPath,
|
|
4056
|
+
inheritContext: { messages: parentContext.getMessages() },
|
|
4046
4057
|
})
|
|
4047
4058
|
try {
|
|
4048
4059
|
const { execSync: ex } = await import('node:child_process')
|
package/src/ui/input.tsx
CHANGED
|
@@ -5,6 +5,7 @@ import { VimMotionEngine, type VimMode } from './vim-motions.js'
|
|
|
5
5
|
import { getCommandList } from './commands.js'
|
|
6
6
|
import { CommandPicker } from './command-picker.js'
|
|
7
7
|
import { useI18n } from '../i18n-context'
|
|
8
|
+
import { discoverSessions } from '../agent/cross-session/discovery'
|
|
8
9
|
|
|
9
10
|
interface InputBarProps {
|
|
10
11
|
onSubmit: (input: string) => void
|
|
@@ -107,6 +108,15 @@ export function InputBar({
|
|
|
107
108
|
return allCommands.filter((c) => c.name.toLowerCase().includes(filter)).slice(0, 8)
|
|
108
109
|
}, [value, allCommands])
|
|
109
110
|
|
|
111
|
+
// ── @mention hints (cross-session recipients) ──
|
|
112
|
+
const mentionHints = useMemo(() => {
|
|
113
|
+
if (!value.startsWith('@')) return []
|
|
114
|
+
const filter = value.slice(1).toLowerCase()
|
|
115
|
+
const names = discoverSessions().map((s) => s.name)
|
|
116
|
+
if (!filter) return names.slice(0, 12)
|
|
117
|
+
return names.filter((n) => n.toLowerCase().includes(filter)).slice(0, 8)
|
|
118
|
+
}, [value])
|
|
119
|
+
|
|
110
120
|
// Rotate gerunds while loading — use tRef to avoid re-running when i18n context re-renders
|
|
111
121
|
useEffect(() => {
|
|
112
122
|
if (!isLoading) return
|
|
@@ -448,6 +458,17 @@ export function InputBar({
|
|
|
448
458
|
</Text>
|
|
449
459
|
</Box>
|
|
450
460
|
)}
|
|
461
|
+
{/* @mention hints — active sessions (cross-session messaging) */}
|
|
462
|
+
{mentionHints.length > 0 && vimMode === 'insert' && !pickerActive && (
|
|
463
|
+
<Box marginTop={1} flexDirection="column" gap={1}>
|
|
464
|
+
<Text dimColor>{t('ui.mention_hints.label')} </Text>
|
|
465
|
+
{mentionHints.map((name) => (
|
|
466
|
+
<Text key={name} color="green">
|
|
467
|
+
{name}
|
|
468
|
+
</Text>
|
|
469
|
+
))}
|
|
470
|
+
</Box>
|
|
471
|
+
)}
|
|
451
472
|
</Box>
|
|
452
473
|
)
|
|
453
474
|
}
|