@miphamai/cli 0.85.22 → 0.85.23

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.
@@ -128,6 +128,42 @@ export const exitWorktreeTool: ToolDefinition = {
128
128
  // Branch detection is best-effort
129
129
  }
130
130
 
131
+ // Unmerged-commit guard. `status --porcelain` above only sees the working
132
+ // tree: a clean worktree whose branch holds commits that exist nowhere
133
+ // else passes it, and `git worktree remove` succeeds too — then the
134
+ // `git branch -D` below silently destroys those commits. Ask git what the
135
+ // branch has that HEAD and every remote do not.
136
+ let branchSafeToDelete = true
137
+ if (!discardChanges && branchName && branchName !== 'HEAD') {
138
+ try {
139
+ const countProc = Bun.spawn(
140
+ ['git', 'rev-list', '--count', branchName, '--not', 'HEAD', '--remotes'],
141
+ { cwd, stdout: 'pipe', stderr: 'pipe' },
142
+ )
143
+ const countText = (await new Response(countProc.stdout).text()).trim()
144
+ const countExit = await countProc.exited
145
+ if (countExit !== 0) {
146
+ // Can't prove it is safe ⇒ keep the branch (never delete blind).
147
+ branchSafeToDelete = false
148
+ } else {
149
+ const unmerged = Number.parseInt(countText, 10)
150
+ if (Number.isFinite(unmerged) && unmerged > 0) {
151
+ return {
152
+ success: false,
153
+ content: '',
154
+ error:
155
+ `Branch "${branchName}" has ${unmerged} commit(s) not on HEAD or any remote:\n\n` +
156
+ `Removing the worktree would delete them (git branch -D).\n\n` +
157
+ `Set discard_changes: true to force removal and discard these commits.\n` +
158
+ `Or merge/push the branch first, then retry.`,
159
+ }
160
+ }
161
+ }
162
+ } catch {
163
+ branchSafeToDelete = false
164
+ }
165
+ }
166
+
131
167
  // Remove the worktree
132
168
  const removeArgs = discardChanges
133
169
  ? ['git', 'worktree', 'remove', '--force', worktreePath]
@@ -149,27 +185,32 @@ export const exitWorktreeTool: ToolDefinition = {
149
185
  }
150
186
  }
151
187
 
152
- // Clean up the branch if we have its name
153
- if (branchName && branchName !== 'HEAD') {
188
+ // Clean up the branch if we have its name and proved it is safe to delete
189
+ let branchDeleted = false
190
+ if (branchSafeToDelete && branchName && branchName !== 'HEAD') {
154
191
  try {
155
192
  const branchProc = Bun.spawn(['git', 'branch', '-D', branchName], {
156
193
  cwd,
157
194
  stdout: 'pipe',
158
195
  stderr: 'pipe',
159
196
  })
160
- await branchProc.exited
197
+ branchDeleted = (await branchProc.exited) === 0
161
198
  // Best-effort — branch cleanup failure is not fatal
162
199
  } catch {
163
200
  // Ignore branch cleanup failures
164
201
  }
165
202
  }
166
203
 
204
+ const branchLine = branchName
205
+ ? `Branch: ${branchName} (${branchDeleted ? 'deleted' : 'kept — could not prove it is safe to delete'})\n`
206
+ : ''
207
+
167
208
  return {
168
209
  success: true,
169
210
  content:
170
211
  `── Worktree Removed ──\n\n` +
171
212
  `Path: ${worktreePath}\n` +
172
- (branchName ? `Branch: ${branchName} (deleted)\n` : '') +
213
+ branchLine +
173
214
  `\nThe worktree has been removed.`,
174
215
  }
175
216
  } catch (err) {
@@ -157,9 +157,12 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
157
157
 
158
158
  // O_NOFOLLOW: fail closed if the path was swapped to a symlink after
159
159
  // resolveSafe (TOCTOU) — never follow it to read outside the workspace.
160
+ // O_NONBLOCK: opening a FIFO blocks until a writer appears, and no timer
161
+ // or signal handler can run inside a synchronous open — without this a
162
+ // `read` of a socket/FIFO would hang the CLI forever.
160
163
  let fd: number
161
164
  try {
162
- fd = openNoFollow(filePath, constants.O_RDONLY)
165
+ fd = openNoFollow(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
163
166
  } catch (err) {
164
167
  if (isSymlinkLoop(err)) {
165
168
  return { success: false, content: '', error: `Path is a symbolic link: ${filePath}` }
@@ -171,9 +174,20 @@ export function createReadTool(credentialConfig?: CredentialMaskingConfig): Tool
171
174
  }
172
175
 
173
176
  try {
174
- if (fstatSync(fd).isDirectory()) {
177
+ const stat = fstatSync(fd)
178
+ if (stat.isDirectory()) {
175
179
  return { success: false, content: '', error: `Path is a directory: ${filePath}` }
176
180
  }
181
+ // FIFOs, sockets and device nodes are not files this tool can read a
182
+ // window out of; O_NONBLOCK got us past the open, so refuse here
183
+ // instead of blocking on the first read (or streaming /dev/zero).
184
+ if (!stat.isFile()) {
185
+ return {
186
+ success: false,
187
+ content: '',
188
+ error: `Path is not a regular file (FIFO, socket or device): ${filePath}`,
189
+ }
190
+ }
177
191
 
178
192
  const offset = (params.offset as number) || 0
179
193
  const limit = (params.limit as number) || DEFAULT_LIMIT
@@ -34,7 +34,8 @@ export interface CronJob {
34
34
  sessionId?: string
35
35
  }
36
36
 
37
- function jobPath(id: string): string {
37
+ /** Location of a job's JSON file. Also the base name its claim directory uses. */
38
+ export function jobPath(id: string): string {
38
39
  return join(CRON_DIR, `${id}.json`)
39
40
  }
40
41
 
@@ -23,13 +23,27 @@ const activeTimers = new Map<string, ReturnType<typeof setTimeout>>()
23
23
  */
24
24
  const WAKEUP_DIR = miphamHome('wakeups')
25
25
 
26
- let wakeupHandler: ((sessionId: string, prompt: string, noop?: boolean) => void) | null = null
26
+ type WakeupHandler = (sessionId: string, prompt: string, noop?: boolean) => void
27
+
28
+ /**
29
+ * Handlers keyed by session — **not** a single slot.
30
+ *
31
+ * The daemon keeps one engine per session in the same process, and every engine
32
+ * construction used to overwrite the previous handler. A wakeup armed for session
33
+ * A then fired into whichever engine was built last, handing the loop prompt to a
34
+ * different conversation. The key is the session the timer was armed for, so a
35
+ * wakeup can only reach its own engine.
36
+ */
37
+ const wakeupHandlers = new Map<string, WakeupHandler>()
27
38
 
28
39
  /** 引擎在启动时注入——timer 到期后回调,把 loop prompt 交回引擎 re-invoke。 */
29
- export function registerWakeupHandler(
30
- fn: (sessionId: string, prompt: string, noop?: boolean) => void,
31
- ): void {
32
- wakeupHandler = fn
40
+ export function registerWakeupHandler(sessionId: string, fn: WakeupHandler): void {
41
+ wakeupHandlers.set(sessionId, fn)
42
+ }
43
+
44
+ /** Drop a session's handler. Call this when the engine that owns it goes away. */
45
+ export function unregisterWakeupHandler(sessionId: string): void {
46
+ wakeupHandlers.delete(sessionId)
33
47
  }
34
48
 
35
49
  /** One session's pending wakeup, as written to disk. */
@@ -98,7 +112,7 @@ function armTimer(sessionId: string, prompt: string, noop: boolean, delayMs: num
98
112
  const timeoutId = setTimeout(() => {
99
113
  activeTimers.delete(timerKey)
100
114
  clearPersistedWakeup(sessionId)
101
- wakeupHandler?.(sessionId, prompt, noop)
115
+ wakeupHandlers.get(sessionId)?.(sessionId, prompt, noop)
102
116
  }, delayMs)
103
117
  activeTimers.set(timerKey, timeoutId)
104
118
  }
package/src/ui/app.tsx CHANGED
@@ -66,6 +66,7 @@ import { recordLoopTurn, readAutoloopJournal } from '../commands/autoloop-journa
66
66
  import { cancelAllSessionTimers, resumeWakeups } from '../tools/scheduling/schedule-wakeup.js'
67
67
  import type { LostWakeup } from '../tools/scheduling/schedule-wakeup.js'
68
68
  import { startCronPoller } from '../core/cron-poller'
69
+ import { exitSession } from '../core/session-exit'
69
70
 
70
71
  interface AppProps {
71
72
  engine: QueryEngine | RemoteEngine
@@ -1075,7 +1076,7 @@ export function App({
1075
1076
  if (result.nextProvider) setProviderId(result.nextProvider)
1076
1077
  if (result.nextModel) setModelId(result.nextModel)
1077
1078
  }
1078
- if (result.exit) process.exit(0)
1079
+ if (result.exit) void exitSession(0)
1079
1080
  return
1080
1081
  }
1081
1082
 
@@ -1087,7 +1088,7 @@ export function App({
1087
1088
 
1088
1089
  // /quit and /exit are special
1089
1090
  if (command === '/exit' || command === '/quit') {
1090
- process.exit(0)
1091
+ void exitSession(0)
1091
1092
  }
1092
1093
 
1093
1094
  // /focus toggle
@@ -1125,13 +1126,13 @@ export function App({
1125
1126
  })
1126
1127
  if (result.needsApiKey) {
1127
1128
  // Don't process nextProvider/model when waiting for API key
1128
- if (result.exit) process.exit(0)
1129
+ if (result.exit) void exitSession(0)
1129
1130
  return
1130
1131
  }
1131
1132
  if (result.clearMessages) setMessages([])
1132
1133
  if (result.nextProvider) setProviderId(result.nextProvider)
1133
1134
  if (result.nextModel) setModelId(result.nextModel)
1134
- if (result.exit) process.exit(0)
1135
+ if (result.exit) void exitSession(0)
1135
1136
  if (result.clearMessages || (result.forwardedMessages?.length ?? 0) > 0) {
1136
1137
  // The conversation this session is looking at just changed (/clear,
1137
1138
  // /resume) — the read-before-write record belongs to the old one.
@@ -1276,7 +1277,7 @@ export function App({
1276
1277
  return
1277
1278
  }
1278
1279
  if (ctrlC.isArmed()) {
1279
- process.exit(0)
1280
+ void exitSession(0)
1280
1281
  }
1281
1282
  ctrlC.arm()
1282
1283
  return
@@ -2460,7 +2460,14 @@ const usageCmd: CommandHandler = (ctx) => {
2460
2460
  const estTokens = c.getEstimatedTokens()
2461
2461
  const msgs = c.getMessages()
2462
2462
  const maxTokens = c.getMaxTokens()
2463
- const pct = ((estTokens / maxTokens) * 100).toFixed(1)
2463
+ // Guard the ratio before formatting: an unknown/zero window makes it NaN or
2464
+ // Infinity, and a NaN `pct` later reaches `'░'.repeat(20 - …)` as a negative
2465
+ // or non-integer count — a RangeError that kills the whole `/usage` command.
2466
+ const maxTokensShown = Number.isFinite(maxTokens) && maxTokens > 0 ? maxTokens : 0
2467
+ const rawPct = maxTokensShown > 0 ? (estTokens / maxTokensShown) * 100 : 0
2468
+ const pctNum = Number.isFinite(rawPct) ? Math.min(100, Math.max(0, rawPct)) : 0
2469
+ const pct = pctNum.toFixed(1)
2470
+ const filledCells = Math.min(20, Math.max(0, Math.ceil(pctNum / 5)))
2464
2471
 
2465
2472
  const tracker = ctx.engine.getUsageTracker()
2466
2473
  const summary = tracker.getSummary()
@@ -2501,12 +2508,12 @@ const usageCmd: CommandHandler = (ctx) => {
2501
2508
  content: stripIndent`
2502
2509
  ${t('commands.usage.title')}
2503
2510
  ${apiLine}
2504
- ${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokens.toLocaleString(), pct })}
2511
+ ${t('commands.usage.context_line', { est: estTokens.toLocaleString(), max: maxTokensShown.toLocaleString(), pct })}
2505
2512
  ${t('commands.usage.messages_line', { count: String(msgs.length) })}
2506
2513
  ${t('commands.usage.provider_line', { provider: ctx.providerId })}
2507
2514
  ${t('commands.usage.model_line', { model: ctx.modelId })}
2508
2515
 
2509
- ${'█'.repeat(Math.ceil(Number(pct) / 5))}${'░'.repeat(20 - Math.ceil(Number(pct) / 5))} ${pct}%
2516
+ ${'█'.repeat(filledCells)}${'░'.repeat(20 - filledCells)} ${pct}%
2510
2517
  ${toolSection}${loopSection}
2511
2518
 
2512
2519
  ${t('commands.usage.hint')}