@miphamai/cli 0.85.36 → 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,4 +1,4 @@
1
- # Mipham Code v0.85.36
1
+ # Mipham Code v0.85.37
2
2
 
3
3
  **Multi-model open-core intelligent coding terminal** — 12 AI providers, 139 commands, 31 tools, 28 skills + marketplace, self-update. AI-assisted code generation, security auditing, MCP protocol, and extensible skills — in a single CLI.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miphamai/cli",
3
- "version": "0.85.36",
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",
@@ -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 {
@@ -457,6 +457,21 @@ async function executeCommand(
457
457
  }
458
458
  }
459
459
 
460
+ // Exit 127 is the shell's "command not found": the hook never started, so it
461
+ // never decided anything. Told apart from a normal non-zero exit (which *is*
462
+ // an answer) and routed through the same fail-closed path as a spawn
463
+ // failure — otherwise a missing interpreter is printed as a warning and a
464
+ // guard that never ran reads exactly like a guard that said yes.
465
+ if (result.status === 127) {
466
+ return failureResult(
467
+ cfg,
468
+ ctx,
469
+ `Hook error ${failingLabel(cfg.command, source)}: exit 127 — the hook's command or ` +
470
+ `interpreter was not found, so its check may not have run`,
471
+ 'exit 127: command or interpreter not found',
472
+ )
473
+ }
474
+
460
475
  const failure = spawnFailureCause(result, hookTimeoutSeconds(cfg))
461
476
  if (failure) {
462
477
  return failureResult(
@@ -1253,6 +1253,66 @@ export function variableWildcardWarning(pattern: string): string | undefined {
1253
1253
  )
1254
1254
  }
1255
1255
 
1256
+ /** Runners for which *every* invocation fetches and runs a package (`uvx`, `npx`…). */
1257
+ const ALWAYS_PACKAGE_RUNNERS = new Set(['npx', 'bunx', 'uvx'])
1258
+
1259
+ /** Runners that only do so through a named subcommand (`pnpm dlx`, `pipx run`…). */
1260
+ const PACKAGE_RUNNERS = new Set(['pnpm', 'yarn', 'npm', 'bun', 'pipx', ...ALWAYS_PACKAGE_RUNNERS])
1261
+
1262
+ /** Their subcommands that run a package the rule did not name. */
1263
+ const RUNNER_EXEC_SUBS = new Set(['dlx', 'exec', 'x'])
1264
+
1265
+ /** `pipx run <package>` — `run` is pipx's own spelling, not `npm run`'s script. */
1266
+ const PIPX_EXEC_SUBS = new Set(['run'])
1267
+
1268
+ /**
1269
+ * Does this **Bash allow** rule grant more than "the program it names"?
1270
+ *
1271
+ * `auto` mode hands everything it is unsure about to the safety classifier — but
1272
+ * an allow rule short-circuits *ahead* of that classifier, so a rule that names
1273
+ * no program at all (`Bash(*)`), names a **path or variable** instead of a
1274
+ * program (`Bash($HOME/bin/…)`, `Bash(/usr/bin/npm:*)`), or names a **package
1275
+ * runner** whose subcommand fetches and runs arbitrary code (`Bash(pnpm dlx *)`)
1276
+ * would silently disable the mode's one safety check for every command it
1277
+ * matches. The rule is still honored in every other mode; only `auto` declines
1278
+ * to read it as a grant, so its commands go to the classifier.
1279
+ *
1280
+ * Deliberately narrow: a rule that names a concrete program (`Bash(npm test:*)`)
1281
+ * keeps granting. The named shapes are ones where the *program* is not decided
1282
+ * by the rule.
1283
+ */
1284
+ export function isUnboundedBashAllowRule(pattern: string): boolean {
1285
+ const shape = /^Bash\((.+)\)$/.exec(pattern)
1286
+ if (!shape) return false
1287
+ const sub = shape[1]!.trim()
1288
+ if (sub === '' || sub === '*') return true
1289
+
1290
+ // A drive-letter path carries a colon of its own; judging the drive before the
1291
+ // `:`-as-separator split keeps `Bash(C:\tools\x.exe:*)` a path, not a program
1292
+ // called `C`.
1293
+ if (/^[A-Za-z]:[\\/]/.test(sub)) return true
1294
+
1295
+ const words = sub.split(/[:\s]+/).filter(Boolean)
1296
+ const first = words[0] ?? ''
1297
+ if (first === '' || first === '*') return true
1298
+
1299
+ // A variable or a path decides *where* a program lives (or which value is
1300
+ // used), not which program runs — and a shell wildcard inside it can make the
1301
+ // outer match accept a command the author never looked at.
1302
+ if (/^[$~]/.test(first)) return true
1303
+ if (/^\.{0,2}[\\/]/.test(first)) return true
1304
+ if (/^[A-Za-z]:[\\/]/.test(first)) return true
1305
+
1306
+ const program = first.toLowerCase()
1307
+ if (ALWAYS_PACKAGE_RUNNERS.has(program)) return true
1308
+ if (!PACKAGE_RUNNERS.has(program)) return false
1309
+ const second = words[1]?.toLowerCase()
1310
+ // `Bash(npx:*)` names the runner and nothing else; `Bash(pnpm dlx *)` names the
1311
+ // one subcommand whose entire job is "fetch this package and run it".
1312
+ if (second === undefined) return true
1313
+ return program === 'pipx' ? PIPX_EXEC_SUBS.has(second) : RUNNER_EXEC_SUBS.has(second)
1314
+ }
1315
+
1256
1316
  /**
1257
1317
  * Compile a rule pattern string into a PermissionRuleEntry.
1258
1318
  */
@@ -6,7 +6,12 @@ import type {
6
6
  PermissionRestrictions,
7
7
  } from '../shared/index.ts'
8
8
  import type { PermissionRuleEntry } from '../shared/index.ts'
9
- import { matchBashRule, compileRule, variableWildcardWarning } from './permission-rules'
9
+ import {
10
+ matchBashRule,
11
+ compileRule,
12
+ variableWildcardWarning,
13
+ isUnboundedBashAllowRule,
14
+ } from './permission-rules'
10
15
  import { detectDangerousRm } from '../security/dangerous-rm'
11
16
  import type { DangerousRm } from '../security/dangerous-rm'
12
17
  import { detectWorldWritableChmod } from '../security/world-writable-chmod'
@@ -637,11 +642,18 @@ export class PermissionSystem {
637
642
 
638
643
  // 3. Check allow rules — but an org ceiling still applies (see allowRuleDecision)
639
644
  for (const rule of this.allowRules) {
640
- if (this.ruleMatches(rule, tool, input)) {
641
- const result = this.allowRuleDecision(tool, input)
642
- this.checkCache.set(cacheKey, result)
643
- return result
645
+ if (!this.ruleMatches(rule, tool, input)) continue
646
+ // In `auto`, a rule that names no program does not stand in for the safety
647
+ // classifier. An allow rule sits *ahead* of the mode baseline, so
648
+ // `allow: ["Bash(*)"]` would otherwise make the one mode that examines
649
+ // commands examine none of them — the rule would be a universal bypass of
650
+ // the mode's entire check. The rule still grants in every other mode.
651
+ if (this.mode === 'auto' && tool.name === 'Bash' && isUnboundedBashAllowRule(rule.pattern)) {
652
+ continue
644
653
  }
654
+ const result = this.allowRuleDecision(tool, input)
655
+ this.checkCache.set(cacheKey, result)
656
+ return result
645
657
  }
646
658
 
647
659
  // 4. Legacy exact-name rules (backward compat)
@@ -56,24 +56,42 @@ function hasProperties(node: Record<string, unknown>): boolean {
56
56
  return isPlainObject(node.properties) && Object.keys(node.properties).length > 0
57
57
  }
58
58
 
59
+ interface ArgumentSurface {
60
+ properties: Record<string, unknown>
61
+ required?: string[]
62
+ }
63
+
64
+ function surfaceOf(node: Record<string, unknown>): ArgumentSurface {
65
+ const required = Array.isArray(node.required)
66
+ ? node.required.filter((name): name is string => typeof name === 'string')
67
+ : undefined
68
+ return {
69
+ properties: isPlainObject(node.properties) ? node.properties : {},
70
+ ...(required && required.length > 0 ? { required } : {}),
71
+ }
72
+ }
73
+
59
74
  /**
75
+ * Every argument surface a schema offers.
76
+ *
60
77
  * A server may put the union at the root (`anyOf`/`oneOf`). Reading only
61
78
  * `root.properties` made that tool reach the model with **no parameters at
62
- * all** — callable, but every argument invisible. Follow the first branch that
63
- * declares properties (nested unions included); keep the root when it declares
64
- * properties itself, so a schema that has both is not rewritten.
79
+ * all** — callable, but every argument invisible. Following only the *first*
80
+ * branch fixed that and introduced the next defect one step in: a branch that
81
+ * takes an id as a number and another that takes it as a string are two
82
+ * spellings of one argument, and showing only the first taught the model that
83
+ * the second was invalid. Every branch is surfaced; nested unions included.
84
+ * The root wins when it declares properties itself, so a schema that has both
85
+ * is not rewritten.
65
86
  */
66
- function schemaWithProperties(schema: unknown, depth = 0): Record<string, unknown> {
87
+ function collectSurfaces(schema: unknown, depth = 0): ArgumentSurface[] {
67
88
  const node = isPlainObject(schema) ? schema : {}
68
- if (hasProperties(node) || depth >= 8) return node
89
+ if (hasProperties(node)) return [surfaceOf(node)]
90
+ if (depth >= 8) return []
69
91
  const branches = (
70
92
  Array.isArray(node.anyOf) ? node.anyOf : Array.isArray(node.oneOf) ? node.oneOf : []
71
93
  ).filter(isPlainObject)
72
- for (const branch of branches) {
73
- const resolved = schemaWithProperties(branch, depth + 1)
74
- if (hasProperties(resolved)) return resolved
75
- }
76
- return branches[0] ?? node
94
+ return branches.flatMap((branch) => collectSurfaces(branch, depth + 1))
77
95
  }
78
96
 
79
97
  /**
@@ -94,23 +112,29 @@ export function sanitizeInputSchema(schema: unknown): {
94
112
  properties: Record<string, unknown>
95
113
  required?: string[]
96
114
  } {
97
- const root = schemaWithProperties(schema)
98
- const rawProperties = isPlainObject(root.properties) ? root.properties : {}
115
+ const surfaces = collectSurfaces(schema)
99
116
  const properties: Record<string, unknown> = {}
100
- for (const [name, property] of Object.entries(rawProperties)) {
101
- if (isPlainObject(property)) properties[name] = property
117
+ for (const surface of surfaces) {
118
+ for (const [name, property] of Object.entries(surface.properties)) {
119
+ // First spelling wins on a name collision; the later branch is another
120
+ // way to say the same argument, not a second argument.
121
+ if (isPlainObject(property) && !Object.prototype.hasOwnProperty.call(properties, name)) {
122
+ properties[name] = property
123
+ }
124
+ }
102
125
  }
103
126
 
104
- const required = Array.isArray(root.required)
105
- ? [
106
- ...new Set(
107
- root.required.filter(
108
- (name): name is string =>
109
- typeof name === 'string' && Object.prototype.hasOwnProperty.call(properties, name),
110
- ),
111
- ),
112
- ]
113
- : []
127
+ // A name is required only when **every** surface that mentions requirements
128
+ // requires it. One branch needing `id` and another not is not a reason to
129
+ // demand `id` for a call the second branch accepts.
130
+ let required = surfaces[0]?.required ? [...surfaces[0].required] : []
131
+ for (const surface of surfaces.slice(1)) {
132
+ const set = new Set(surface.required ?? [])
133
+ required = required.filter((name) => set.has(name))
134
+ }
135
+ required = [...new Set(required)].filter((name) =>
136
+ Object.prototype.hasOwnProperty.call(properties, name),
137
+ )
114
138
 
115
139
  return required.length > 0 ? { properties, required } : { properties }
116
140
  }
@@ -9,7 +9,7 @@
9
9
  export const PACKAGE_NAME = '@miphamai/cli' as const
10
10
 
11
11
  /** 当前发布版本 */
12
- export const PACKAGE_VERSION = '0.85.36' as const
12
+ export const PACKAGE_VERSION = '0.85.37' as const
13
13
 
14
14
  /** npm install 全局安装命令 */
15
15
  export const NPM_INSTALL_COMMAND = `npm install -g ${PACKAGE_NAME}` as const
@@ -90,4 +90,4 @@ export const TOOL_COUNT = 31 as const
90
90
  * —— `test/e2e/full-pipeline.test.ts` 在 Linux 上整文件 skip、在 macOS 上跑 ——
91
91
  * 但**总数相同**(两边都把被 skip 的算进去)。
92
92
  */
93
- export const TEST_COUNT = 4928 as const
93
+ export const TEST_COUNT = 4969 as const
@@ -48,6 +48,8 @@ export class SkillsLoader implements Skills {
48
48
  private skills = new Map<string, SkillDefinition>()
49
49
  /** File each loaded skill came from — so a name collision can name both sides. */
50
50
  private sources = new Map<string, string>()
51
+ /** Paths this loader has scanned, with the type they were loaded as — what `reload()` re-reads. */
52
+ private scannedDirs = new Map<string, 'standard' | 'mipham'>()
51
53
 
52
54
  loadBuiltin(basePath: string): void {
53
55
  // Load standard skills (*.SKILL.md)
@@ -97,11 +99,38 @@ export class SkillsLoader implements Skills {
97
99
  this.loadDirectory(p, 'standard')
98
100
  } else if (stat.isFile()) {
99
101
  this.tryLoad(p, 'standard')
102
+ this.scannedDirs.set(p, 'standard')
100
103
  }
101
104
  }
102
105
  }
103
106
  }
104
107
 
108
+ /**
109
+ * Re-scan every directory/file this loader already read, and return the total
110
+ * skill count.
111
+ *
112
+ * The Skill tool calls this once on a miss: a skill written **during** the
113
+ * session (by the model itself, or by a command it ran) was invisible until a
114
+ * restart or `/reload-skills`, and "not found" was the same answer whether the
115
+ * name was wrong or the file was new. Rescanning only on a miss keeps the
116
+ * happy path unchanged.
117
+ */
118
+ reload(): number {
119
+ for (const [p, type] of this.scannedDirs) {
120
+ try {
121
+ if (!existsSync(p)) continue
122
+ if (statSync(p).isDirectory()) {
123
+ this.loadDirectory(p, type)
124
+ } else {
125
+ this.tryLoad(p, type)
126
+ }
127
+ } catch {
128
+ // A path that became unreadable is not a reload failure for the rest.
129
+ }
130
+ }
131
+ return this.skills.size
132
+ }
133
+
105
134
  /** Load a single skill file by path (used by Claude plugins: `skills/<name>/SKILL.md`). */
106
135
  loadSkillFile(path: string, type: 'standard' | 'mipham' = 'standard'): void {
107
136
  this.tryLoad(path, type)
@@ -137,6 +166,7 @@ export class SkillsLoader implements Skills {
137
166
  }
138
167
 
139
168
  private loadDirectory(dir: string, type: 'standard' | 'mipham'): void {
169
+ this.scannedDirs.set(dir, type)
140
170
  try {
141
171
  const entries = readdirSync(dir)
142
172
  for (const entry of entries) {
@@ -7,6 +7,13 @@ export interface Skills {
7
7
  list(): SkillDefinition[]
8
8
  has(name: string): boolean
9
9
  buildSystemReminder(maxTokens?: number): string
10
+ /**
11
+ * Re-scan the directories this loader already knows about. Optional: the Skill
12
+ * tool calls it once when a name is not found, so a skill written during the
13
+ * session is found without restarting (`/reload-skills` still exists for a
14
+ * deliberate full reload). A provider with no on-disk sources simply omits it.
15
+ */
16
+ reload?(): number
10
17
  }
11
18
 
12
19
  /** 缝键:ctx.skills。 */
@@ -34,7 +34,7 @@ export const reportFindingsTool: ToolDefinition = {
34
34
  },
35
35
  summary: {
36
36
  type: 'string',
37
- description: 'One-sentence statement of the defect.',
37
+ description: 'Statement of the defect.',
38
38
  },
39
39
  short_summary: {
40
40
  type: 'string',
@@ -51,6 +51,14 @@ export const reportFindingsTool: ToolDefinition = {
51
51
  description:
52
52
  'Short kebab-case slug: correctness, security, performance, simplification, test-coverage, etc.',
53
53
  },
54
+ severity: {
55
+ type: 'string',
56
+ enum: ['important', 'pre_existing', 'nit'],
57
+ description:
58
+ 'Set when the review instructions ask for it. important: a bug the change adds ' +
59
+ 'or makes worse; pre_existing: a bug that was there before the change; nit: a ' +
60
+ 'minor issue.',
61
+ },
54
62
  verdict: {
55
63
  type: 'string',
56
64
  enum: ['CONFIRMED', 'PLAUSIBLE'],
@@ -104,6 +112,12 @@ export const reportFindingsTool: ToolDefinition = {
104
112
  if (f.outcome && !['fixed', 'skipped', 'no_change_needed'].includes(f.outcome as string)) {
105
113
  errors.push(`findings[${i}]: "outcome" must be fixed, skipped, or no_change_needed`)
106
114
  }
115
+ if (
116
+ f.severity !== undefined &&
117
+ !['important', 'pre_existing', 'nit'].includes(f.severity as string)
118
+ ) {
119
+ errors.push(`findings[${i}]: "severity" must be important, pre_existing, or nit`)
120
+ }
107
121
  }
108
122
 
109
123
  if (errors.length > 0) {
@@ -154,9 +168,13 @@ export const reportFindingsTool: ToolDefinition = {
154
168
  lines.push(`${icon} ${category} (${items.length}):`)
155
169
  for (const f of items) {
156
170
  const verdict = f.verdict ? ` [${f.verdict}]` : ''
171
+ // The severity is what tells a reader whether the change made this worse
172
+ // or merely inherited it; accepting it without showing it would make the
173
+ // field an inert attribute (nothing downstream reads it).
174
+ const severity = f.severity ? ` [severity: ${f.severity}]` : ''
157
175
  const outcome = f.outcome ? ` → ${f.outcome}` : ''
158
176
  const lineRef = f.line ? `:${f.line}` : ''
159
- lines.push(` • ${f.file}${lineRef}${verdict}${outcome}`)
177
+ lines.push(` • ${f.file}${lineRef}${verdict}${severity}${outcome}`)
160
178
  lines.push(` ${f.summary}`)
161
179
  if (f.failure_scenario) {
162
180
  const scenario =
@@ -26,7 +26,15 @@ export const skillTool: ToolDefinition = {
26
26
  // Try to load the skill via SkillsLoader if available
27
27
  const loader = ctx.skillsLoader
28
28
  if (loader) {
29
- const skill = loader.get(skillName)
29
+ let skill = loader.get(skillName)
30
+ if (!skill && loader.reload) {
31
+ // A skill written during this session was not in the loader's snapshot:
32
+ // before answering "not found", re-scan the directories it already
33
+ // knows. A genuinely wrong name costs one directory walk; a new file
34
+ // stops being indistinguishable from a typo.
35
+ loader.reload()
36
+ skill = loader.get(skillName)
37
+ }
30
38
  if (!skill) {
31
39
  const available = loader
32
40
  .list()
@@ -207,6 +207,49 @@ export function isBlocked(command: string): string | null {
207
207
  return null // safe
208
208
  }
209
209
 
210
+ /**
211
+ * Git commands that rewrite refs a worktree **shares with the main checkout**.
212
+ *
213
+ * A worktree is not a sandbox for `.git`: every worktree of one repository reads
214
+ * and writes the same `refs/` (and the same `packed-refs`). A subagent isolated
215
+ * in a worktree can therefore move `main` — delete it, force it, point it at a
216
+ * different commit — and the main checkout follows, without a single file in the
217
+ * worktree changing. The `cd` escape guard does not see this: the command runs
218
+ * inside the worktree and reaches out through git's own directories.
219
+ *
220
+ * Only judged for **subagents inside a worktree**: the main session in a
221
+ * worktree is the user's own checkout and keeps every command it had. This list
222
+ * is a floor of demonstrated forms; widening it costs one blocked command.
223
+ */
224
+ const SHARED_REF_REWRITES: Array<{ pattern: RegExp; description: string }> = [
225
+ { pattern: /\bupdate-ref\b/, description: 'update-ref (writes a ref directly)' },
226
+ { pattern: /\bsymbolic-ref\b/, description: 'symbolic-ref (repoints a ref)' },
227
+ {
228
+ pattern: /\bbranch\s+.*(?:-f\b|--force\b|-m\b|-M\b|--move\b|-d\b|-D\b|--delete\b)/,
229
+ description: 'branch -f/-m/-d (force-move, rename or delete a branch)',
230
+ },
231
+ { pattern: /\bcheckout\b[^;&|]*\s-B\b/, description: 'checkout -B (reset a branch)' },
232
+ { pattern: /\bswitch\b[^;&|]*\s-C\b/, description: 'switch -C (reset a branch)' },
233
+ {
234
+ pattern: /\bworktree\s+(?:remove|prune)\b/,
235
+ description: 'worktree remove/prune (removes a sibling checkout)',
236
+ },
237
+ {
238
+ pattern: /\btag\s+.*(?:-f\b|--force\b|-d\b|--delete\b)/,
239
+ description: 'tag -f/-d (force-move or delete a tag)',
240
+ },
241
+ ]
242
+
243
+ /** First shared-ref rewrite in `command`, or `null`. */
244
+ export function detectSharedRefRewrite(command: string): { description: string } | null {
245
+ // Same gate the dangerous-git scan uses: the command must actually invoke git.
246
+ if (!/(?:^|[\s;&|(])(?:sudo\s+)?git\s+/.test(command)) return null
247
+ for (const { pattern, description } of SHARED_REF_REWRITES) {
248
+ if (pattern.test(command)) return { description }
249
+ }
250
+ return null
251
+ }
252
+
210
253
  /**
211
254
  * Detect sandbox violations from stderr output.
212
255
  * Parses common OS-level error patterns indicating denied access.
@@ -604,6 +647,22 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
604
647
  `Attempted: ${escapeTarget}. Use tools within the worktree only.`,
605
648
  }
606
649
  }
650
+ // Worktrees share `refs/` with the main checkout, so "stay inside the
651
+ // directory" is not enough: `git update-ref refs/heads/main …` moves a
652
+ // branch the main checkout is standing on. A subagent gets no vote on
653
+ // shared refs; the main session in a worktree keeps its own commands.
654
+ if (ctx.isSubAgent) {
655
+ const rewrite = detectSharedRefRewrite(command)
656
+ if (rewrite) {
657
+ return {
658
+ success: false,
659
+ content: '',
660
+ error:
661
+ `Worktree isolation: "${rewrite.description}" rewrites a ref shared with the ` +
662
+ `main checkout. Ask the main session to run it if that is what you intend.`,
663
+ }
664
+ }
665
+ }
607
666
  }
608
667
 
609
668
  // Security: check command against deny list
@@ -7,6 +7,13 @@ import { validateUrl } from '../../security/url'
7
7
  /** Most characters returned in one call. Past this the caller pages with `offset`. */
8
8
  const MAX_RETURN_CHARS = 100_000
9
9
 
10
+ /**
11
+ * Longest URL accepted. 2,000 is the anchor RFC 7230 gives for "longer than any
12
+ * real address"; a URL past it is a payload, not a page, and refusing it before
13
+ * the permission prompt keeps a pathological string out of every layer below.
14
+ */
15
+ const MAX_URL_CHARS = 2_000
16
+
10
17
  interface CacheEntry {
11
18
  content: string
12
19
  timestamp: number
@@ -278,6 +285,19 @@ export const webFetchTool: ToolDefinition = {
278
285
  const rawUrl = params.url as string
279
286
  const prompt = (params.prompt as string) || ''
280
287
  const offset = Math.max(0, Number(params.offset) || 0)
288
+ // Refuse before any parsing, DNS lookup or permission prompt: past this
289
+ // length the URL is not a page address anyone can read (the length itself
290
+ // has been used to make URL parsers backtrack for minutes).
291
+ if (rawUrl.length > MAX_URL_CHARS) {
292
+ return {
293
+ success: false,
294
+ content: '',
295
+ error:
296
+ `URL is ${rawUrl.length.toLocaleString('en-US')} characters — longer than the ` +
297
+ `${MAX_URL_CHARS.toLocaleString('en-US')}-character limit. Truncate it to the address ` +
298
+ `the page actually needs (query strings can be dropped and re-added after fetching).`,
299
+ }
300
+ }
281
301
  const url = upgradeToHttps(rawUrl)
282
302
 
283
303
  // Check cache — an incomplete entry (first 100k only) cannot answer a
package/src/ui/app.tsx CHANGED
@@ -58,6 +58,7 @@ import {
58
58
  parseSlashCommand,
59
59
  unknownCommandMessage,
60
60
  handleSwitch,
61
+ runCommandHandler,
61
62
  type CommandContext,
62
63
  } from './commands'
63
64
  import { useI18n } from '../i18n-context'
@@ -1225,7 +1226,19 @@ export function App({
1225
1226
  return
1226
1227
  }
1227
1228
  if (handler) {
1228
- const result = await handler(mkCtx(), args)
1229
+ // A handler that throws is not a crash of the session — see
1230
+ // `runCommandHandler`: the failure is reported as that command's
1231
+ // answer and the session continues.
1232
+ const outcome = await runCommandHandler(handler, mkCtx(), args)
1233
+ if (!outcome.ok) {
1234
+ setMessages((prev) => [
1235
+ ...prev,
1236
+ { role: 'user', content: input },
1237
+ { role: 'system', content: `❌ ${command} failed: ${outcome.message}` },
1238
+ ])
1239
+ return
1240
+ }
1241
+ const result = outcome.result
1229
1242
  forwardToAI = result.forwardToAI
1230
1243
  // Handle API key prompt from command result
1231
1244
  if (result.needsApiKey) {
@@ -199,6 +199,31 @@ export type CommandHandler = (
199
199
  args: string[],
200
200
  ) => CommandResult | Promise<CommandResult>
201
201
 
202
+ export type CommandOutcome = { ok: true; result: CommandResult } | { ok: false; message: string }
203
+
204
+ /**
205
+ * Run a command handler, turning a throw into a value.
206
+ *
207
+ * Handlers reach the filesystem (`/permissions` writes settings.json, `/export`
208
+ * writes a file, `/resume` reads session files), so they can fail for reasons
209
+ * the user can act on — EACCES, ENOSPC, a read-only home. Before this wrapper the
210
+ * rejection escaped the submit callback: the process-wide crash handler saw an
211
+ * unhandled rejection and exited, so "the settings file could not be written"
212
+ * looked like "the command killed the CLI". A failure is that command's answer,
213
+ * and the session stays up.
214
+ */
215
+ export async function runCommandHandler(
216
+ handler: CommandHandler,
217
+ ctx: CommandContext,
218
+ args: string[],
219
+ ): Promise<CommandOutcome> {
220
+ try {
221
+ return { ok: true, result: await handler(ctx, args) }
222
+ } catch (err) {
223
+ return { ok: false, message: err instanceof Error ? err.message : String(err) }
224
+ }
225
+ }
226
+
202
227
  // ═══════════════════════════════════════════════════════════════
203
228
  // Session & Identity
204
229
  // ═══════════════════════════════════════════════════════════════