@miphamai/cli 0.85.35 → 0.85.37

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,6 +1,6 @@
1
- # Mipham Code v0.85.35
1
+ # Mipham Code v0.85.37
2
2
 
3
- **Multi-model open-core intelligent coding terminal** — 12 AI providers, 138 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
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
 
5
5
  Built by [One Mipham Corporation](https://onemipham.com) (北京华安麦逄科技有限公司) | Brand: MiphamAI
6
6
 
@@ -16,7 +16,7 @@ Requirements: **Bun 1.2+** (recommended) or **Node.js 22+**
16
16
  ## Features
17
17
 
18
18
  - **12 AI Providers** — Anthropic Claude · OpenAI GPT · DeepSeek · Kimi (Moonshot) · Google Gemini · Doubao 豆包 · Tencent Hunyuan 混元 · Qwen 通义千问 · MiniMax(国内 / 国际)· Ollama(本地)· MiphamAI
19
- - **138 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
19
+ - **139 Slash Commands** — Interactive command picker (↑↓ Enter Esc), intuitive command interface, zero re-learning
20
20
  - **31 Built-in Tools** — File ops, shell execution, agent dispatch, MCP integration, web search
21
21
  - **28 Skills + Marketplace** — 22 standard + 6 Mipham-exclusive skills. `/browse-skills` `/install-skill` community marketplace
22
22
  - **Self-Update** — `mipham update` / `/upgrade` — one command to check, backup config, upgrade, restore. API keys preserved
@@ -59,7 +59,7 @@ mipham update
59
59
  | Category | Commands |
60
60
  | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
61
61
  | Session | `/help` `/version` `/clear` `/exit` `/quit` `/compact` `/context` `/status` `/cost` `/rename` `/goal` `/recap` `/export` `/doctor` `/resume` |
62
- | Model | `/pick` `/model` `/models` `/provider` `/providers` `/switch` `/effort` `/theme` `/upgrade` |
62
+ | Model | `/pick` `/model` `/models` `/provider` `/providers` `/switch` `/effort` `/upgrade` |
63
63
  | Skills | `/skills` `/browse-skills` `/install-skill` `/remove-skill` `/reload-skills` |
64
64
  | Tools | `/tools` `/commands` `/mcp` |
65
65
  | Workflow | `/plan` `/no-plan` `/review` `/diff` `/todos` `/tasks` `/workflows` `/loop` `/agents` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.35",
3
+ "version": "0.85.37",
4
4
  "description": "Mipham Code — Multi-model open-core intelligent coding terminal by MiphamAI",
5
5
  "keywords": [
6
6
  "ai",
@@ -2,44 +2,13 @@
2
2
  * Mipham Code — Environment Slash Commands
3
3
  *
4
4
  * Extracted from ui/commands.ts (2026-08-06).
5
- * Handlers for: /theme, /release-notes, /ide, /terminal-setup
5
+ * Handlers for: /release-notes, /ide, /terminal-setup
6
6
  */
7
7
  import type { CommandHandler } from '../ui/commands.js'
8
- import { NPM_INSTALL_COMMAND } from '../shared/index.ts'
8
+ import { NPM_INSTALL_COMMAND, PACKAGE_VERSION } from '../shared/index.ts'
9
9
  import { miphamHome } from '../core/paths.ts'
10
10
 
11
- export { themeCmd, releaseNotesCmd, ideCmd, terminalSetupCmd }
12
-
13
- const themeCmd: CommandHandler = (_ctx, args) => {
14
- const theme = args[0]?.toLowerCase()
15
- const validThemes = ['dark', 'light', 'auto'] as const
16
-
17
- if (!theme || !validThemes.includes(theme as (typeof validThemes)[number])) {
18
- return {
19
- content: `── Theme ──
20
-
21
- Terminal color themes (set in .mipham/config.yml):
22
-
23
- theme: dark — dark background (default, recommended for terminals)
24
- theme: light — light background
25
- theme: auto — follow system preference
26
-
27
- Usage: /theme dark | light | auto
28
-
29
- Current: auto (follows terminal)`,
30
- }
31
- }
32
-
33
- return {
34
- content: `✓ Theme set to "${theme}".
35
-
36
- Add to ~/.mipham/config.yml to persist:
37
- theme: ${theme}
38
-
39
- Terminal themes affect syntax highlighting and UI accents.
40
- Full theme customization is available in the Web UI at https://mipham.ai/code/dashboard`,
41
- }
42
- }
11
+ export { releaseNotesCmd, ideCmd, terminalSetupCmd }
43
12
 
44
13
  // ═══════════════════════════════════════════════════════════════
45
14
  // Add-Dir — add a directory to workspace permissions
@@ -56,32 +25,13 @@ Full theme customization is available in the Web UI at https://mipham.ai/code/da
56
25
  const releaseNotesCmd: CommandHandler = () => ({
57
26
  content: `── Release Notes ──
58
27
 
59
- v0.1.2 (2026-06-09) — Current
60
- • 48 slash commands (up from 20)
61
- • /setup guided project initialization wizard
62
- • Checkpoint/rewind mechanism
63
- • Focus mode (last exchange view)
64
- • 3-level MIPHAM.md architecture
65
- • /doctor system diagnostics
66
- • /export conversation to file
67
- • /review and /pr-comments code review workflows
68
- • /memory management
69
- • /upgrade instructions
70
- • Clipboard support (macOS/Windows)
28
+ Current: Mipham Code v${PACKAGE_VERSION}
71
29
 
72
- v0.1.1 (2026-06-02)
73
- • Inline shared module for standalone builds
74
- • Bin path fix for npm compatibility
30
+ This build does not embed the full changelog. See:
31
+ • /changelog recent release tags in this clone
32
+ • https://mipham.ai/code/releases full release notes
75
33
 
76
- v0.1.0 (2026-06-01)
77
- • Initial release
78
- • Multi-model support (7 providers)
79
- • 16 built-in tools
80
- • 11 skills (9 standard + 2 mipham)
81
- • Ctrl+P interactive model picker
82
- • SSE streaming support
83
-
84
- Full changelog: https://mipham.ai/code/releases`,
34
+ Install / upgrade: ${NPM_INSTALL_COMMAND}`,
85
35
  })
86
36
 
87
37
  // ═══════════════════════════════════════════════════════════════
@@ -111,23 +61,46 @@ const ideCmd: CommandHandler = async (_ctx) => {
111
61
  // Use default
112
62
  }
113
63
 
64
+ // Write helpers that MERGE instead of clobbering. These are the user's editor
65
+ // settings: overwriting the file to add one profile destroys every other key
66
+ // (and `keybindings.json` is commonly JSONC, so an unparseable file must be
67
+ // left alone rather than replaced).
68
+ const { readRegularFileSync } = await import('../shared/regular-file')
69
+ const readJson = (path: string): unknown => {
70
+ const raw = readRegularFileSync(path)
71
+ if (raw === null) return undefined
72
+ try {
73
+ return JSON.parse(raw)
74
+ } catch {
75
+ return undefined // JSONC / hand-edited — refuse to rewrite
76
+ }
77
+ }
78
+ const isObject = (v: unknown): v is Record<string, unknown> =>
79
+ v !== null && typeof v === 'object' && !Array.isArray(v)
80
+
114
81
  // ── settings.json: terminal profile ──
115
82
  const settingsPath = join(vscodeDir, 'settings.json')
116
- const settings = {
117
- 'terminal.integrated.profiles.osx': {
118
- mipham: {
119
- path: bunPath,
120
- args: ['run', 'mipham'],
121
- cwd: '${workspaceFolder}',
122
- },
123
- },
83
+ const existingSettings = readJson(settingsPath)
84
+ const settings: Record<string, unknown> = isObject(existingSettings) ? existingSettings : {}
85
+ const profiles = isObject(settings['terminal.integrated.profiles.osx'])
86
+ ? (settings['terminal.integrated.profiles.osx'] as Record<string, unknown>)
87
+ : {}
88
+ profiles.mipham = {
89
+ path: bunPath,
90
+ args: ['run', 'mipham'],
91
+ cwd: '${workspaceFolder}',
124
92
  }
93
+ settings['terminal.integrated.profiles.osx'] = profiles
125
94
  atomicWriteFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n', { mode: 0o644 })
126
95
  files.push('.vscode/settings.json')
127
96
 
128
97
  // ── keybindings.json: Cmd+Esc launch ──
129
98
  const keybindingsPath = join(vscodeDir, 'keybindings.json')
130
- const keybindings = [
99
+ const existingKeybindings = readJson(keybindingsPath)
100
+ const keybindings: Record<string, unknown>[] = Array.isArray(existingKeybindings)
101
+ ? (existingKeybindings as Record<string, unknown>[])
102
+ : []
103
+ const wanted = [
131
104
  {
132
105
  key: 'cmd+escape',
133
106
  command: 'workbench.action.terminal.focus',
@@ -138,14 +111,25 @@ const ideCmd: CommandHandler = async (_ctx) => {
138
111
  command: 'workbench.action.terminal.new',
139
112
  },
140
113
  ]
114
+ for (const entry of wanted) {
115
+ if (!keybindings.some((k) => k.key === entry.key && k.command === entry.command)) {
116
+ keybindings.push(entry)
117
+ }
118
+ }
141
119
  atomicWriteFileSync(keybindingsPath, JSON.stringify(keybindings, null, 2) + '\n', { mode: 0o644 })
142
120
  files.push('.vscode/keybindings.json')
143
121
 
144
122
  // ── extensions.json: recommended ──
145
123
  const extensionsPath = join(vscodeDir, 'extensions.json')
146
- const extensions = {
147
- recommendations: ['miphamai.mipham-code'],
124
+ const existingExtensions = readJson(extensionsPath)
125
+ const extensions: Record<string, unknown> = isObject(existingExtensions) ? existingExtensions : {}
126
+ const recommendations = Array.isArray(extensions.recommendations)
127
+ ? (extensions.recommendations as unknown[])
128
+ : []
129
+ if (!recommendations.includes('miphamai.mipham-code')) {
130
+ recommendations.push('miphamai.mipham-code')
148
131
  }
132
+ extensions.recommendations = recommendations
149
133
  atomicWriteFileSync(extensionsPath, JSON.stringify(extensions, null, 2) + '\n', { mode: 0o644 })
150
134
  files.push('.vscode/extensions.json')
151
135
 
@@ -34,6 +34,15 @@ async function git(args: string[], timeoutMs = 5000): Promise<string> {
34
34
  return exitCode === 0 ? stdout.trim() : ''
35
35
  }
36
36
 
37
+ /** Diffs can be arbitrarily large; the prompt carries a bounded prefix. */
38
+ const MAX_PROMPT_DIFF = 12_000
39
+
40
+ function promptWithDiff(intro: string, diff: string): string {
41
+ const body =
42
+ diff.length > MAX_PROMPT_DIFF ? `${diff.slice(0, MAX_PROMPT_DIFF)}\n… (truncated)` : diff
43
+ return `${intro}\n\n${body}`
44
+ }
45
+
37
46
  const commitCmd: CommandHandler = async () => {
38
47
  try {
39
48
  const diff = await git(['diff', '--cached', '--stat'])
@@ -50,11 +59,13 @@ const commitCmd: CommandHandler = async () => {
50
59
  .join('\n') +
51
60
  '\n\n'
52
61
  }
53
- msg +=
54
- 'Run: git add <files> to stage changes first.\nOr type: "commit these changes" for AI assistance.'
62
+ msg += 'Run: git add <files> to stage changes first.'
55
63
  return { content: msg }
56
64
  }
57
65
 
66
+ // The command says "generate a commit message", so it must actually
67
+ // generate one. It used to print instructions to type a sentence in chat.
68
+ const full = await git(['diff', '--cached'], 8000)
58
69
  return {
59
70
  content: [
60
71
  '── Git Commit ──',
@@ -62,11 +73,13 @@ const commitCmd: CommandHandler = async () => {
62
73
  'Staged changes:',
63
74
  diff,
64
75
  '',
65
- 'To generate a commit message, type: "write a commit message for these changes"',
66
- 'To commit: git commit -m "your message"',
67
- '',
68
- 'Tip: Use Conventional Commits format (feat:, fix:, chore:, docs:)',
76
+ 'Drafting a Conventional Commits message from these changes.',
77
+ 'To commit: git commit -m "<the message>"',
69
78
  ].join('\n'),
79
+ forwardToAI: promptWithDiff(
80
+ 'Write a Conventional Commits message for the staged diff below. Output only the commit message (subject ≤72 chars, then a blank line and a body if useful). Do not run git.',
81
+ full,
82
+ ),
70
83
  }
71
84
  } catch {
72
85
  return { content: '── Git Commit ──\n\nCould not run git. Are you in a git repository?' }
@@ -90,7 +103,10 @@ const pushCmd: CommandHandler = async () => {
90
103
  ? `Ready to push ${ahead} commit(s). Run: git push origin ${branch}`
91
104
  : 'Nothing to push (up to date).',
92
105
  '',
93
- 'Or type: "push my changes" for AI assistance.',
106
+ // Pushing is an outward-facing action and slash commands bypass the
107
+ // permission layer, so this command only reports. Saying that out loud
108
+ // is the difference between a status view and a fake "push".
109
+ 'This command only reports; it never pushes.',
94
110
  ].join('\n'),
95
111
  }
96
112
  } catch {
@@ -112,6 +128,10 @@ const prCmd: CommandHandler = async () => {
112
128
  (await git(['log', '--oneline', `origin/${mainBranch}..HEAD`], 5000)) ||
113
129
  (await git(['log', '--oneline', `${mainBranch}..HEAD`], 5000))
114
130
 
131
+ const fullDiff =
132
+ (await git(['diff', `origin/${mainBranch}...HEAD`], 8000)) ||
133
+ (await git(['diff', `${mainBranch}...HEAD`], 8000))
134
+
115
135
  return {
116
136
  content: [
117
137
  '── Create Pull Request ──',
@@ -127,28 +147,45 @@ const prCmd: CommandHandler = async () => {
127
147
  '',
128
148
  diff ? `Changes:\n${diff}` : '',
129
149
  '',
130
- 'To create PR: type "create a pull request" for AI assistance.',
131
- 'Or use: gh pr create --base ' + mainBranch + ' --head ' + branch,
150
+ 'Drafting a PR title and body from these commits.',
151
+ 'To open it: gh pr create --base ' + mainBranch + ' --head ' + branch,
132
152
  ].join('\n'),
153
+ forwardToAI: promptWithDiff(
154
+ `Draft a pull request title and body for the branch "${branch}" targeting "${mainBranch}". Commits:\n${commits || '(none)'}\n\nOutput only the title and body. Do not run gh or create the PR.`,
155
+ fullDiff,
156
+ ),
133
157
  }
134
158
  } catch {
135
159
  return { content: '── Create Pull Request ──\n\nCould not determine PR context.' }
136
160
  }
137
161
  }
138
162
 
139
- const issueCmd: CommandHandler = async () => {
163
+ const issueCmd: CommandHandler = async (_ctx, args) => {
164
+ const description = args.join(' ').trim()
165
+ if (!description) {
166
+ return {
167
+ content: [
168
+ '── GitHub Issues ──',
169
+ '',
170
+ 'Describe the issue after the command:',
171
+ ' /issue <what went wrong and what you expected>',
172
+ '',
173
+ 'Quick commands:',
174
+ ' gh issue create --title "..." --body "..."',
175
+ ' gh issue list',
176
+ ].join('\n'),
177
+ }
178
+ }
179
+
140
180
  return {
141
181
  content: [
142
182
  '── GitHub Issues ──',
143
183
  '',
144
- 'To file an issue, type: "create a GitHub issue for [description]"',
145
- '',
146
- 'Quick commands:',
147
- ' gh issue create --title "..." --body "..."',
148
- ' gh issue list',
184
+ 'Drafting an issue from your description.',
149
185
  '',
150
- 'Use /github-ops skill for advanced GitHub automation.',
186
+ 'To file it: gh issue create --title "..." --body "..."',
151
187
  ].join('\n'),
188
+ forwardToAI: `Draft a GitHub issue title and body for: ${description}\n\nOutput only the title and body. Do not run gh or create the issue.`,
152
189
  }
153
190
  }
154
191
 
@@ -14,24 +14,35 @@ export const keysCmd: CommandHandler = async (_ctx, args) => {
14
14
  content: 'Usage: /keys rotate <provider>\n\nExample: /keys rotate deepseek',
15
15
  }
16
16
  }
17
- // Interactive: prompt user to provide new key via follow-up chat message
18
- return {
19
- content: [
20
- '── Key Rotation ──',
21
- '',
22
- `Provider: ${provider}`,
23
- '',
24
- 'To complete rotation, the new API key must be provided.',
25
- 'Type your new key in chat and the AI will handle rotation securely.',
26
- '',
27
- 'The old key will be backed up to ~/.mipham/keys/<provider>.backup (chmod 600).',
28
- ].join('\n'),
29
- forwardToAI: `The user wants to rotate the API key for provider "${provider}". Ask them to provide the new key value, then:
30
- 1. Call KeyManager.rotate("${provider}", newKey) with the provided key
31
- 2. The new key should be stored in ~/.mipham/config.json (or appropriate config)
32
- 3. Confirm rotation count and backup location
33
- 4. Remind them the old key is backed up at ~/.mipham/keys/${provider}.backup`,
17
+
18
+ // The key is read from the environment, never from chat: a key typed into
19
+ // the prompt becomes part of the conversation transcript and the model
20
+ // context. Per-provider variable first, generic one as the fallback.
21
+ const envName = `MIPHAM_ROTATE_KEY_${provider.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`
22
+ const newKey = process.env[envName] ?? process.env.MIPHAM_ROTATE_KEY
23
+ if (!newKey) {
24
+ return {
25
+ content: [
26
+ '── Key Rotation ──',
27
+ '',
28
+ `Provider: ${provider}`,
29
+ '',
30
+ 'No key supplied.',
31
+ `Set ${envName} (or MIPHAM_ROTATE_KEY) and rerun:`,
32
+ '',
33
+ ` ${envName}=... /keys rotate ${provider}`,
34
+ '',
35
+ 'The key is read from the environment so it never enters the conversation transcript.',
36
+ 'The old rotation metadata is backed up to ~/.mipham/keys/<provider>.backup (chmod 600).',
37
+ ].join('\n'),
38
+ }
39
+ }
40
+
41
+ const result = manager.rotate(provider, newKey)
42
+ if (!result.success) {
43
+ return { content: `── Key Rotation ──\n\n✗ ${result.message}` }
34
44
  }
45
+ return { content: `── Key Rotation ──\n\n✅ ${result.message}` }
35
46
  }
36
47
 
37
48
  // /keys audit
@@ -806,10 +806,9 @@ Built-in skills (${counts.total} total):
806
806
  Mipham (${counts.mipham}): ${miphamNames.join(', ')}
807
807
 
808
808
  Community skills:
809
- Coming soon — the Mipham Code skills marketplace will let you
810
- browse and install community-contributed skills.
809
+ Browse and install with /browse-skills and /install-skill.
811
810
 
812
- For now, add custom skills manually:
811
+ Or add custom skills manually:
813
812
  1. Create a .SKILL.md file in .mipham/skills/
814
813
  2. Use /reload-skills to load it
815
814
 
@@ -845,12 +844,7 @@ To persist one for a project, .mipham/config.yml:
845
844
  allow: ["Bash(npm test)"] # or: /permissions allow "Bash(npm test)"
846
845
  deny: ["Bash(rm *)"]
847
846
 
848
- Available tools (${ctx.engine.getTools().size}):
849
- File: read, write, edit, glob, grep
850
- Exec: bash, git, task
851
- Agent: agent, memory, plan, skill
852
- Net: web-fetch, web-search
853
- Sys: config, mcp
847
+ Available tools (${ctx.engine.getTools().size}) — run /tools for the full list.
854
848
 
855
849
  Next: /setup 6 for shell integration`,
856
850
  }
@@ -869,8 +863,8 @@ Add Mipham Code to your shell:
869
863
  alias mipham='mipham'
870
864
 
871
865
  IDE Integration:
872
- VS Code — coming soon (extension marketplace)
873
- JetBrains — coming soon (plugin)
866
+ VS Code — extension published (search "Mipham Code" in the marketplace)
867
+ JetBrains — plugin published (search "Mipham Code")
874
868
  Terminal — run \`mipham\` in any terminal
875
869
 
876
870
  Quick launch:
@@ -1252,19 +1246,18 @@ const securityCmd: CommandHandler = async () => {
1252
1246
  }
1253
1247
  }
1254
1248
 
1255
- // 3. Check for TLS in dependencies
1256
- if (existsSync(join(cwd, 'package.json'))) {
1257
- ok.push('package.json present — dependencies manageable')
1258
- }
1249
+ // Note: there is deliberately no "TLS in dependencies" step. The old check was
1250
+ // `existsSync(package.json)` — it reported a security pass for the presence of
1251
+ // a file, not for TLS. A scan that cannot answer the question must not claim it.
1259
1252
 
1260
- // 4. Check for license
1253
+ // 3. Check for license
1261
1254
  if (existsSync(join(cwd, 'LICENSE'))) {
1262
1255
  ok.push('LICENSE file present')
1263
1256
  } else {
1264
1257
  findings.push('No LICENSE file — add Apache 2.0 or appropriate license')
1265
1258
  }
1266
1259
 
1267
- // 5. CI/CD
1260
+ // 4. CI/CD
1268
1261
  if (existsSync(join(cwd, '.github', 'workflows'))) {
1269
1262
  ok.push('CI/CD workflows configured')
1270
1263
  } else {
@@ -1,5 +1,6 @@
1
1
  import type { CommandHandler } from '../ui/commands.js'
2
2
  import { listRuns, loadJournal } from '../workflow/journal.js'
3
+ import { getEventBus } from '../workflow/event-bus.js'
3
4
 
4
5
  export const workflowViewCmd: CommandHandler = async (_ctx, args) => {
5
6
  const runId = args[0]
@@ -57,15 +58,32 @@ export const workflowViewCmd: CommandHandler = async (_ctx, args) => {
57
58
  }
58
59
 
59
60
  export const workflowWatchCmd: CommandHandler = async (_ctx, _args) => {
60
- // /workflow watch — monitor the currently active workflow
61
- // This is a hint: the actual rendering is handled by WorkflowProgress component
62
- // which auto-detects active workflows. This command just confirms watch mode.
61
+ // The event bus is the only place that knows whether a run is live in this
62
+ // process. Reading it makes the answer a fact instead of a fixed sentence.
63
+ const active = getEventBus().getActiveRunId()
64
+ const runs = listRuns().sort()
65
+
66
+ if (active) {
67
+ return {
68
+ content: [
69
+ '── Workflow Watch ──',
70
+ '',
71
+ `Active run: ${active}`,
72
+ 'Progress streams automatically in the workflow panel.',
73
+ '',
74
+ `Replay so far: /workflow view ${active}`,
75
+ ].join('\n'),
76
+ }
77
+ }
78
+
63
79
  return {
64
80
  content: [
65
- '── Workflow Watch Mode ──',
81
+ '── Workflow Watch ──',
66
82
  '',
67
- 'Workflow progress is displayed automatically when a workflow is running.',
68
- 'No active workflow detected.',
83
+ 'No workflow is running in this process.',
84
+ runs.length > 0
85
+ ? `Recorded runs: ${runs.length} (latest: ${runs[runs.length - 1]})`
86
+ : 'No recorded runs yet.',
69
87
  '',
70
88
  'Use /workflow list to see past runs.',
71
89
  'Use /workflow view <id> to replay a completed run.',
@@ -613,6 +613,9 @@ export function loadSettingsJson(
613
613
  ]
614
614
 
615
615
  for (const { path, readHooks, isProject } of searchPaths) {
616
+ // Kept outside the `try` so the parse-failure message can name the line and
617
+ // column, not just V8/Bun's byte offset.
618
+ let rawForError = ''
616
619
  try {
617
620
  // `readRegularFileSync` folds "absent" and "present but unreadable"
618
621
  // (EACCES, a directory, a FIFO) into the same `null`. Absent is the ordinary
@@ -622,6 +625,7 @@ export function loadSettingsJson(
622
625
  // **looser**. A security-relevant file must not fail open in silence.
623
626
  const present = existsSync(path)
624
627
  const raw = readRegularFileSync(path)
628
+ rawForError = raw ?? ''
625
629
  if (raw === null) {
626
630
  if (present) {
627
631
  process.stderr.write(
@@ -740,7 +744,7 @@ export function loadSettingsJson(
740
744
  // Malformed JSON is the other half of the same problem: the file exists and
741
745
  // declares a `deny` list we cannot see. Say so, with the parse reason, the
742
746
  // same way `safeParseYaml` does for `config.yml`.
743
- const msg = err instanceof Error ? err.message : String(err)
747
+ const msg = jsonErrorDetail(rawForError, err)
744
748
  process.stderr.write(
745
749
  `⚠ Mipham Code: failed to parse settings file (${path}): ${msg} — ignoring it.\n`,
746
750
  )
@@ -794,6 +798,70 @@ export function projectFilePath(name: string, cwd: string = process.cwd()): stri
794
798
  return resolve(dir) === resolve(MIPHAM_HOME) ? null : join(dir, name)
795
799
  }
796
800
 
801
+ /**
802
+ * Values nested deeper than this are dropped when a settings file is read.
803
+ *
804
+ * Not a style preference: `JSON.parse` accepts a value nested hundreds of
805
+ * thousands of levels, and `JSON.stringify` on the *same* value throws
806
+ * `RangeError: Maximum call stack size exceeded`. The write path
807
+ * (`readSettingsDoc` → mutate → `writeSettingsDoc`) therefore used to crash on a
808
+ * file that had parsed fine — a document we cannot rewrite, reported as an
809
+ * unhandled rejection. Nothing we read lives past a few levels, so the cap costs
810
+ * no real setting and keeps the file rewritable.
811
+ */
812
+ const MAX_SETTINGS_DEPTH = 64
813
+
814
+ const DROPPED = Symbol('dropped')
815
+
816
+ /** Drop values deeper than `MAX_SETTINGS_DEPTH`, counting what went. */
817
+ function capSettingsDepth(value: unknown): { value: unknown; dropped: number } {
818
+ let dropped = 0
819
+ const walk = (v: unknown, depth: number): unknown => {
820
+ if (depth > MAX_SETTINGS_DEPTH) {
821
+ dropped++
822
+ return DROPPED
823
+ }
824
+ if (Array.isArray(v)) {
825
+ const out: unknown[] = []
826
+ for (const item of v) {
827
+ const next = walk(item, depth + 1)
828
+ // JSON has no `undefined`, so a hole can only mean "dropped": leaving it
829
+ // in would serialize as `null` — a different value than the one removed.
830
+ if (next !== DROPPED) out.push(next)
831
+ }
832
+ return out
833
+ }
834
+ if (v && typeof v === 'object') {
835
+ const out: Record<string, unknown> = {}
836
+ for (const [key, item] of Object.entries(v)) {
837
+ const next = walk(item, depth + 1)
838
+ if (next !== DROPPED) out[key] = next
839
+ }
840
+ return out
841
+ }
842
+ return v
843
+ }
844
+ return { value: walk(value, 0), dropped }
845
+ }
846
+
847
+ /**
848
+ * `JSON.parse`'s message plus a line/column, derived from the byte offset it
849
+ * reports. Node 22 reports an offset (`… at position 14`), which locates the
850
+ * break in a multi-hundred-line settings file; Bun's message carries no offset
851
+ * at all, so there the runtime's own text is returned unchanged. The addition is
852
+ * therefore per-runtime, and deliberately says nothing it cannot compute.
853
+ */
854
+ function jsonErrorDetail(raw: string, err: unknown): string {
855
+ const message = err instanceof Error ? err.message : String(err)
856
+ const at = /position (\d+)/.exec(message)
857
+ if (!at) return message
858
+ const pos = Math.min(Number(at[1]), raw.length)
859
+ const before = raw.slice(0, pos)
860
+ const line = before.split('\n').length
861
+ const column = pos - before.lastIndexOf('\n')
862
+ return `${message} (line ${line}, column ${column})`
863
+ }
864
+
797
865
  /**
798
866
  * Read a settings.json as a plain object, preserving any key we don't model
799
867
  * (hooks, and anything a future version adds). A malformed file is an error,
@@ -805,13 +873,22 @@ export function readSettingsDoc(path: string): Record<string, unknown> {
805
873
  let parsed: unknown
806
874
  try {
807
875
  parsed = JSON.parse(raw)
808
- } catch {
809
- throw new Error(`${path} is not valid JSON. Fix or remove it, then retry.`)
876
+ } catch (err) {
877
+ throw new Error(
878
+ `${path} is not valid JSON — ${jsonErrorDetail(raw, err)}. Fix or remove it, then retry.`,
879
+ )
810
880
  }
811
881
  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
812
882
  throw new Error(`${path} does not contain a JSON object. Fix or remove it, then retry.`)
813
883
  }
814
- return parsed as Record<string, unknown>
884
+ const capped = capSettingsDepth(parsed)
885
+ if (capped.dropped > 0) {
886
+ process.stderr.write(
887
+ `⚠ Mipham Code: ${path}: dropped ${capped.dropped} value(s) nested deeper than ` +
888
+ `${MAX_SETTINGS_DEPTH} levels.\n`,
889
+ )
890
+ }
891
+ return capped.value as Record<string, unknown>
815
892
  }
816
893
 
817
894
  export function writeSettingsDoc(path: string, doc: Record<string, unknown>): void {