claudish 14.30.0 → 14.30.1

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.
Files changed (2) hide show
  1. package/dist/index.js +1201 -1678
  2. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -5557,7 +5557,7 @@ var init_env_placeholder = __esm(() => {
5557
5557
  });
5558
5558
 
5559
5559
  // src/version.ts
5560
- var VERSION = "14.30.0";
5560
+ var VERSION = "14.30.1";
5561
5561
 
5562
5562
  // src/redact.ts
5563
5563
  function isPlaceholder(value) {
@@ -10342,12 +10342,15 @@ function resolveClassifierConfig(config, env = process.env) {
10342
10342
  const envProvider = env.CLAUDISH_CLASSIFIER_PROVIDER?.trim().toLowerCase();
10343
10343
  const envModel = env.CLAUDISH_CLASSIFIER_MODEL?.trim();
10344
10344
  const enabled = !!flagModel || flagProvider === "anthropic" || envProvider === "anthropic" || !!envModel;
10345
- return { enabled, model: flagModel || envModel || DEFAULT_CLASSIFIER_MODEL };
10345
+ return { enabled, model: flagModel || envModel || undefined };
10346
10346
  }
10347
10347
  function classifierPassthroughEnabled(config, env = process.env) {
10348
10348
  return resolveClassifierConfig(config, env).enabled;
10349
10349
  }
10350
- var CLASSIFIER_SYSTEM_MARKER = "You are a security monitor for autonomous AI coding agents.", DEFAULT_CLASSIFIER_MODEL = "claude-sonnet-5";
10350
+ var CLASSIFIER_SYSTEM_MARKER = "You are a security monitor for autonomous AI coding agents.", NO_CLASSIFIER_MODEL_MESSAGE;
10351
+ var init_classifier_passthrough = __esm(() => {
10352
+ NO_CLASSIFIER_MODEL_MESSAGE = "claudish cannot choose a model for the auto-mode permission classifier: the cloud models " + "catalog is not loaded or lists no Sonnet. Name one with --classifier-model <model> or " + "CLAUDISH_CLASSIFIER_MODEL.";
10353
+ });
10351
10354
 
10352
10355
  // src/tui/runtime/can-draw-tui.ts
10353
10356
  function canDrawTui() {
@@ -14138,7 +14141,7 @@ var init_bundled_recommended_list = __esm(() => {
14138
14141
  }
14139
14142
  }
14140
14143
  },
14141
- fetchedAt: "2026-11-29T05:56:08.350Z",
14144
+ fetchedAt: "2026-11-30T07:09:14.415Z",
14142
14145
  format: 1,
14143
14146
  recommendations: {
14144
14147
  contractVersion: 3,
@@ -14244,11 +14247,11 @@ var init_bundled_recommended_list = __esm(() => {
14244
14247
  tier: "luxury"
14245
14248
  }
14246
14249
  ],
14247
- generationId: "g-20261128161534886-d7094101"
14250
+ generationId: "g-20261129161514060-092a94cb"
14248
14251
  },
14249
14252
  source: "https://us-central1-claudish-6da10.cloudfunctions.net"
14250
14253
  },
14251
- catalogGenerationId: "g-20261128161534886-d7094101",
14254
+ catalogGenerationId: "g-20261129161514060-092a94cb",
14252
14255
  entries: [
14253
14256
  {
14254
14257
  aggregators: [
@@ -15015,9 +15018,9 @@ var init_bundled_recommended_list = __esm(() => {
15015
15018
  aliases: [
15016
15019
  "anthropic/claude-sonnet-5.5",
15017
15020
  "claude-sonnet-5.5",
15018
- "claude-sonnet-5-5-high",
15019
- "claude-sonnet-5-5-medium",
15020
15021
  "claude-sonnet-5-5-low",
15022
+ "claude-sonnet-5-5-medium",
15023
+ "claude-sonnet-5-5-high",
15021
15024
  "claude-sonnet-5-5-max",
15022
15025
  "claude-sonnet-5-5-xhigh"
15023
15026
  ],
@@ -15436,10 +15439,10 @@ var init_bundled_recommended_list = __esm(() => {
15436
15439
  ],
15437
15440
  aliases: [
15438
15441
  "google/gemini-4-hydrogen",
15439
- "gemini-4-hydrogen-xhigh",
15440
- "gemini-4-hydrogen-low",
15441
15442
  "gemini-4-hydrogen-medium",
15442
- "gemini-4-hydrogen-high"
15443
+ "gemini-4-hydrogen-high",
15444
+ "gemini-4-hydrogen-xhigh",
15445
+ "gemini-4-hydrogen-low"
15443
15446
  ],
15444
15447
  contextWindow: 1048576,
15445
15448
  contractVersion: 3,
@@ -15591,10 +15594,10 @@ var init_bundled_recommended_list = __esm(() => {
15591
15594
  ],
15592
15595
  aliases: [
15593
15596
  "google/gemini-4-neon",
15594
- "gemini-4-neon-xhigh",
15595
- "gemini-4-neon-low",
15597
+ "gemini-4-neon-medium",
15596
15598
  "gemini-4-neon-high",
15597
- "gemini-4-neon-medium"
15599
+ "gemini-4-neon-xhigh",
15600
+ "gemini-4-neon-low"
15598
15601
  ],
15599
15602
  contextWindow: 1048576,
15600
15603
  contractVersion: 3,
@@ -18321,7 +18324,7 @@ var init_bundled_recommended_list = __esm(() => {
18321
18324
  videoOutput: false
18322
18325
  }
18323
18326
  ],
18324
- lastUpdated: "2026-11-28T16:15:34.886Z",
18327
+ lastUpdated: "2026-11-29T16:15:14.060Z",
18325
18328
  models: [],
18326
18329
  plans: [
18327
18330
  {
@@ -18982,34 +18985,24 @@ var init_bundled_recommended_list = __esm(() => {
18982
18985
  id: "google-antigravity",
18983
18986
  inclusions: [
18984
18987
  {
18985
- externalModelId: "gemini-4-hydrogen-xhigh",
18986
- kind: "provider_model",
18987
- provider: "antigravity",
18988
- resolution: {
18989
- modelId: "gemini-4-hydrogen",
18990
- status: "mapped"
18991
- },
18992
- sourceText: "gemini-4-hydrogen-xhigh"
18993
- },
18994
- {
18995
- externalModelId: "gemini-4-carbon-medium",
18988
+ externalModelId: "claude-opus-5-5-low",
18996
18989
  kind: "provider_model",
18997
18990
  provider: "antigravity",
18998
18991
  resolution: {
18999
- modelId: "gemini-4-carbon",
18992
+ modelId: "claude-opus-5-5",
19000
18993
  status: "mapped"
19001
18994
  },
19002
- sourceText: "gemini-4-carbon-medium"
18995
+ sourceText: "claude-opus-5-5-low"
19003
18996
  },
19004
18997
  {
19005
- externalModelId: "claude-opus-5-5-low",
18998
+ externalModelId: "claude-sonnet-5-5-low",
19006
18999
  kind: "provider_model",
19007
19000
  provider: "antigravity",
19008
19001
  resolution: {
19009
- modelId: "claude-opus-5-5",
19002
+ modelId: "claude-sonnet-5-5",
19010
19003
  status: "mapped"
19011
19004
  },
19012
- sourceText: "claude-opus-5-5-low"
19005
+ sourceText: "claude-sonnet-5-5-low"
19013
19006
  },
19014
19007
  {
19015
19008
  externalModelId: "claude-opus-5-5-high",
@@ -19022,24 +19015,24 @@ var init_bundled_recommended_list = __esm(() => {
19022
19015
  sourceText: "claude-opus-5-5-high"
19023
19016
  },
19024
19017
  {
19025
- externalModelId: "gemini-4-neon-xhigh",
19018
+ externalModelId: "gemini-4-hydrogen-medium",
19026
19019
  kind: "provider_model",
19027
19020
  provider: "antigravity",
19028
19021
  resolution: {
19029
- modelId: "gemini-4-neon",
19022
+ modelId: "gemini-4-hydrogen",
19030
19023
  status: "mapped"
19031
19024
  },
19032
- sourceText: "gemini-4-neon-xhigh"
19025
+ sourceText: "gemini-4-hydrogen-medium"
19033
19026
  },
19034
19027
  {
19035
- externalModelId: "gemini-4-neon-low",
19028
+ externalModelId: "claude-sonnet-5-5-medium",
19036
19029
  kind: "provider_model",
19037
19030
  provider: "antigravity",
19038
19031
  resolution: {
19039
- modelId: "gemini-4-neon",
19032
+ modelId: "claude-sonnet-5-5",
19040
19033
  status: "mapped"
19041
19034
  },
19042
- sourceText: "gemini-4-neon-low"
19035
+ sourceText: "claude-sonnet-5-5-medium"
19043
19036
  },
19044
19037
  {
19045
19038
  externalModelId: "claude-sonnet-5-5-high",
@@ -19052,14 +19045,14 @@ var init_bundled_recommended_list = __esm(() => {
19052
19045
  sourceText: "claude-sonnet-5-5-high"
19053
19046
  },
19054
19047
  {
19055
- externalModelId: "gemini-4-neon-high",
19048
+ externalModelId: "gemini-4-neon-medium",
19056
19049
  kind: "provider_model",
19057
19050
  provider: "antigravity",
19058
19051
  resolution: {
19059
19052
  modelId: "gemini-4-neon",
19060
19053
  status: "mapped"
19061
19054
  },
19062
- sourceText: "gemini-4-neon-high"
19055
+ sourceText: "gemini-4-neon-medium"
19063
19056
  },
19064
19057
  {
19065
19058
  externalModelId: "claude-opus-5-5-medium",
@@ -19072,54 +19065,54 @@ var init_bundled_recommended_list = __esm(() => {
19072
19065
  sourceText: "claude-opus-5-5-medium"
19073
19066
  },
19074
19067
  {
19075
- externalModelId: "gemini-4-carbon-high",
19068
+ externalModelId: "gemini-4-carbon-medium",
19076
19069
  kind: "provider_model",
19077
19070
  provider: "antigravity",
19078
19071
  resolution: {
19079
19072
  modelId: "gemini-4-carbon",
19080
19073
  status: "mapped"
19081
19074
  },
19082
- sourceText: "gemini-4-carbon-high"
19075
+ sourceText: "gemini-4-carbon-medium"
19083
19076
  },
19084
19077
  {
19085
- externalModelId: "claude-sonnet-5-5-medium",
19078
+ externalModelId: "gemini-4-neon-high",
19086
19079
  kind: "provider_model",
19087
19080
  provider: "antigravity",
19088
19081
  resolution: {
19089
- modelId: "claude-sonnet-5-5",
19082
+ modelId: "gemini-4-neon",
19090
19083
  status: "mapped"
19091
19084
  },
19092
- sourceText: "claude-sonnet-5-5-medium"
19085
+ sourceText: "gemini-4-neon-high"
19093
19086
  },
19094
19087
  {
19095
- externalModelId: "gemini-4-neon-medium",
19088
+ externalModelId: "gemini-4-neon-xhigh",
19096
19089
  kind: "provider_model",
19097
19090
  provider: "antigravity",
19098
19091
  resolution: {
19099
19092
  modelId: "gemini-4-neon",
19100
19093
  status: "mapped"
19101
19094
  },
19102
- sourceText: "gemini-4-neon-medium"
19095
+ sourceText: "gemini-4-neon-xhigh"
19103
19096
  },
19104
19097
  {
19105
- externalModelId: "claude-sonnet-5-5-low",
19098
+ externalModelId: "gemini-4-carbon-high",
19106
19099
  kind: "provider_model",
19107
19100
  provider: "antigravity",
19108
19101
  resolution: {
19109
- modelId: "claude-sonnet-5-5",
19102
+ modelId: "gemini-4-carbon",
19110
19103
  status: "mapped"
19111
19104
  },
19112
- sourceText: "claude-sonnet-5-5-low"
19105
+ sourceText: "gemini-4-carbon-high"
19113
19106
  },
19114
19107
  {
19115
- externalModelId: "gemini-4-hydrogen-low",
19108
+ externalModelId: "gemini-4-hydrogen-high",
19116
19109
  kind: "provider_model",
19117
19110
  provider: "antigravity",
19118
19111
  resolution: {
19119
19112
  modelId: "gemini-4-hydrogen",
19120
19113
  status: "mapped"
19121
19114
  },
19122
- sourceText: "gemini-4-hydrogen-low"
19115
+ sourceText: "gemini-4-hydrogen-high"
19123
19116
  },
19124
19117
  {
19125
19118
  externalModelId: "gemini-4-carbon-low",
@@ -19132,24 +19125,34 @@ var init_bundled_recommended_list = __esm(() => {
19132
19125
  sourceText: "gemini-4-carbon-low"
19133
19126
  },
19134
19127
  {
19135
- externalModelId: "gemini-4-hydrogen-medium",
19128
+ externalModelId: "gemini-4-neon-low",
19129
+ kind: "provider_model",
19130
+ provider: "antigravity",
19131
+ resolution: {
19132
+ modelId: "gemini-4-neon",
19133
+ status: "mapped"
19134
+ },
19135
+ sourceText: "gemini-4-neon-low"
19136
+ },
19137
+ {
19138
+ externalModelId: "gemini-4-hydrogen-xhigh",
19136
19139
  kind: "provider_model",
19137
19140
  provider: "antigravity",
19138
19141
  resolution: {
19139
19142
  modelId: "gemini-4-hydrogen",
19140
19143
  status: "mapped"
19141
19144
  },
19142
- sourceText: "gemini-4-hydrogen-medium"
19145
+ sourceText: "gemini-4-hydrogen-xhigh"
19143
19146
  },
19144
19147
  {
19145
- externalModelId: "gemini-4-hydrogen-high",
19148
+ externalModelId: "gemini-4-hydrogen-low",
19146
19149
  kind: "provider_model",
19147
19150
  provider: "antigravity",
19148
19151
  resolution: {
19149
19152
  modelId: "gemini-4-hydrogen",
19150
19153
  status: "mapped"
19151
19154
  },
19152
- sourceText: "gemini-4-hydrogen-high"
19155
+ sourceText: "gemini-4-hydrogen-low"
19153
19156
  }
19154
19157
  ],
19155
19158
  modelDiscovery: "client",
@@ -19493,14 +19496,14 @@ var init_bundled_recommended_list = __esm(() => {
19493
19496
  id: "ollama-cloud",
19494
19497
  inclusions: [
19495
19498
  {
19496
- externalModelId: "deepseek-v4.1-flash",
19499
+ externalModelId: "mimo-v2.6-flash",
19497
19500
  kind: "provider_model",
19498
19501
  provider: "ollamacloud",
19499
19502
  resolution: {
19500
- modelId: "deepseek-v4.1-flash",
19503
+ modelId: "mimo-v2.6-flash",
19501
19504
  status: "mapped"
19502
19505
  },
19503
- sourceText: "deepseek-v4.1-flash"
19506
+ sourceText: "mimo-v2.6-flash"
19504
19507
  },
19505
19508
  {
19506
19509
  externalModelId: "glm-5.3",
@@ -19513,54 +19516,54 @@ var init_bundled_recommended_list = __esm(() => {
19513
19516
  sourceText: "glm-5.3"
19514
19517
  },
19515
19518
  {
19516
- externalModelId: "mimo-v2.6-flash",
19519
+ externalModelId: "minimax-m3.1-flash",
19517
19520
  kind: "provider_model",
19518
19521
  provider: "ollamacloud",
19519
19522
  resolution: {
19520
- modelId: "mimo-v2.6-flash",
19523
+ modelId: "minimax-m3.1-flash",
19521
19524
  status: "mapped"
19522
19525
  },
19523
- sourceText: "mimo-v2.6-flash"
19526
+ sourceText: "minimax-m3.1-flash"
19524
19527
  },
19525
19528
  {
19526
- externalModelId: "kimi-k3.1-pro",
19529
+ externalModelId: "glm-5.3-flash",
19527
19530
  kind: "provider_model",
19528
19531
  provider: "ollamacloud",
19529
19532
  resolution: {
19530
- modelId: "kimi-k3.1-pro",
19533
+ modelId: "glm-5.3-flash",
19531
19534
  status: "mapped"
19532
19535
  },
19533
- sourceText: "kimi-k3.1-pro"
19536
+ sourceText: "glm-5.3-flash"
19534
19537
  },
19535
19538
  {
19536
- externalModelId: "glm-5.3-flash",
19539
+ externalModelId: "mimo-v2.6-pro",
19537
19540
  kind: "provider_model",
19538
19541
  provider: "ollamacloud",
19539
19542
  resolution: {
19540
- modelId: "glm-5.3-flash",
19543
+ modelId: "mimo-v2.6-pro",
19541
19544
  status: "mapped"
19542
19545
  },
19543
- sourceText: "glm-5.3-flash"
19546
+ sourceText: "mimo-v2.6-pro"
19544
19547
  },
19545
19548
  {
19546
- externalModelId: "minimax-m3.1-flash",
19549
+ externalModelId: "deepseek-v4.1-flash",
19547
19550
  kind: "provider_model",
19548
19551
  provider: "ollamacloud",
19549
19552
  resolution: {
19550
- modelId: "minimax-m3.1-flash",
19553
+ modelId: "deepseek-v4.1-flash",
19551
19554
  status: "mapped"
19552
19555
  },
19553
- sourceText: "minimax-m3.1-flash"
19556
+ sourceText: "deepseek-v4.1-flash"
19554
19557
  },
19555
19558
  {
19556
- externalModelId: "mimo-v2.6-pro",
19559
+ externalModelId: "kimi-k3.1-pro",
19557
19560
  kind: "provider_model",
19558
19561
  provider: "ollamacloud",
19559
19562
  resolution: {
19560
- modelId: "mimo-v2.6-pro",
19563
+ modelId: "kimi-k3.1-pro",
19561
19564
  status: "mapped"
19562
19565
  },
19563
- sourceText: "mimo-v2.6-pro"
19566
+ sourceText: "kimi-k3.1-pro"
19564
19567
  }
19565
19568
  ],
19566
19569
  modelDiscovery: "catalog",
@@ -19815,7 +19818,7 @@ var init_bundled_recommended_list = __esm(() => {
19815
19818
  }
19816
19819
  ],
19817
19820
  routeRegistry: {
19818
- generationId: "g-20261128161534886-d7094101",
19821
+ generationId: "g-20261129161514060-092a94cb",
19819
19822
  registry: {
19820
19823
  contractVersion: 3,
19821
19824
  registryVersion: "3.7.0",
@@ -37636,13 +37639,13 @@ function getCatalogEntries() {
37636
37639
  function catalogOrigin() {
37637
37640
  return getCatalogSnapshot()?.origin ?? "none";
37638
37641
  }
37639
- function latestAnthropicTierModelId(tier, accept = () => true) {
37642
+ function latestAnthropicTierEntry(tier, accept) {
37640
37643
  const snapshot = getCatalogSnapshot();
37641
37644
  if (snapshot?.origin !== "disk")
37642
37645
  return null;
37643
37646
  const { entries } = snapshot;
37644
37647
  const family = new RegExp(`^claude-${tier}-`, "i");
37645
- const matches = entries.filter((entry) => family.test(entry.modelId) && accept(entry.modelId));
37648
+ const matches = entries.filter((entry) => family.test(entry.modelId) && accept(entry));
37646
37649
  if (matches.length === 0)
37647
37650
  return null;
37648
37651
  matches.sort((a, b) => {
@@ -37655,7 +37658,13 @@ function latestAnthropicTierModelId(tier, accept = () => true) {
37655
37658
  return aFast - bFast;
37656
37659
  return b.modelId.localeCompare(a.modelId);
37657
37660
  });
37658
- return matches[0].modelId;
37661
+ return matches[0];
37662
+ }
37663
+ function latestAnthropicTierModelId(tier, accept = () => true) {
37664
+ return latestAnthropicTierEntry(tier, (entry) => accept(entry.modelId, entry))?.modelId ?? null;
37665
+ }
37666
+ function implicitAnthropicTierEntry(tier, accept = () => true) {
37667
+ return latestAnthropicTierEntry(tier, (entry) => !isOptInWireId(entry.modelId) && accept(entry));
37659
37668
  }
37660
37669
  function isCatalogWarm() {
37661
37670
  return _memCache !== null && _memCache.entries.length > 0;
@@ -63575,76 +63584,9 @@ var init_wire_markers = __esm(() => {
63575
63584
  };
63576
63585
  });
63577
63586
 
63578
- // src/providers/catalog-query.ts
63579
- import { statSync as statSync11 } from "fs";
63580
- function project(entry) {
63581
- return {
63582
- modelId: entry.modelId,
63583
- aliases: entry.aliases,
63584
- supportsVision: entry.supportsVision,
63585
- contextWindow: entry.contextWindow,
63586
- releaseDate: entry.releaseDate,
63587
- aggregators: entry.aggregators
63588
- };
63589
- }
63590
- function getCachedEntries() {
63591
- let mtimeMs;
63592
- try {
63593
- mtimeMs = statSync11(ALL_MODELS_CACHE_PATH).mtimeMs;
63594
- } catch {
63595
- return null;
63596
- }
63597
- if (mtimeMs === _memoMtimeMs && _memoEntries !== null) {
63598
- return _memoEntries;
63599
- }
63600
- const cache = readAllModelsCache();
63601
- if (!cache)
63602
- return null;
63603
- _memoEntries = cache.entries;
63604
- _memoMtimeMs = mtimeMs;
63605
- return _memoEntries;
63606
- }
63607
- function findEntryByAlias(alias, accept = () => true) {
63608
- const entries = getCachedEntries();
63609
- if (!entries || entries.length === 0)
63610
- return null;
63611
- for (const entry of entries) {
63612
- if (entry.aliases.includes(alias) && accept(entry.modelId)) {
63613
- return project(entry);
63614
- }
63615
- }
63616
- return null;
63617
- }
63618
- function findEntryByModelId(modelId) {
63619
- const entries = getCachedEntries();
63620
- if (!entries || entries.length === 0)
63621
- return null;
63622
- for (const entry of entries) {
63623
- if (entry.modelId === modelId) {
63624
- return project(entry);
63625
- }
63626
- }
63627
- return null;
63628
- }
63629
- function findVisionAlias(alias) {
63630
- const entries = getCachedEntries();
63631
- if (!entries || entries.length === 0)
63632
- return null;
63633
- for (const entry of entries) {
63634
- if (entry.supportsVision === true && entry.aliases.includes(alias) && !isOptInWireId(entry.modelId)) {
63635
- return project(entry);
63636
- }
63637
- }
63638
- return null;
63639
- }
63640
- var _memoEntries = null, _memoMtimeMs = -1;
63641
- var init_catalog_query = __esm(() => {
63642
- init_all_models_cache();
63643
- });
63644
-
63645
63587
  // src/services/vision-proxy.ts
63646
63588
  function getVisionModel() {
63647
- return findVisionAlias("sonnet")?.modelId ?? "claude-sonnet-4-6";
63589
+ return implicitAnthropicTierEntry("sonnet", (entry) => entry.supportsVision === true)?.modelId ?? null;
63648
63590
  }
63649
63591
  function parseDataUrl(dataUrl) {
63650
63592
  if (!dataUrl.startsWith("data:"))
@@ -63662,7 +63604,7 @@ function parseDataUrl(dataUrl) {
63662
63604
  return null;
63663
63605
  return { mediaType, data };
63664
63606
  }
63665
- async function describeImage(image, auth) {
63607
+ async function describeImage(image, auth, model) {
63666
63608
  const parsed = parseDataUrl(image.image_url.url);
63667
63609
  if (!parsed) {
63668
63610
  log("[VisionProxy] Skipping image: malformed or non-base64 data URL");
@@ -63670,7 +63612,7 @@ async function describeImage(image, auth) {
63670
63612
  }
63671
63613
  const { mediaType, data } = parsed;
63672
63614
  const requestBody = {
63673
- model: getVisionModel(),
63615
+ model,
63674
63616
  max_tokens: MAX_TOKENS_PER_IMAGE,
63675
63617
  stream: false,
63676
63618
  messages: [
@@ -63735,7 +63677,12 @@ async function describeImages(images, auth) {
63735
63677
  if (images.length === 0)
63736
63678
  return [];
63737
63679
  try {
63738
- const results = await Promise.all(images.map((img) => describeImage(img, auth)));
63680
+ const model = getVisionModel();
63681
+ if (model === null) {
63682
+ log("[VisionProxy] No Sonnet with vision in the cloud models catalog; no image description requested");
63683
+ return null;
63684
+ }
63685
+ const results = await Promise.all(images.map((img) => describeImage(img, auth, model)));
63739
63686
  if (results.some((r) => r === null)) {
63740
63687
  log("[VisionProxy] One or more image descriptions failed, falling back");
63741
63688
  return null;
@@ -63759,7 +63706,7 @@ var MAX_TOKENS_PER_IMAGE = 1024, VISION_ENDPOINT = "https://api.anthropic.com/v1
63759
63706
  Be comprehensive - this description will be the only information the model has about the image.`;
63760
63707
  var init_vision_proxy = __esm(() => {
63761
63708
  init_logger();
63762
- init_catalog_query();
63709
+ init_catalog_client();
63763
63710
  });
63764
63711
 
63765
63712
  // src/auth/claude-code-facts.ts
@@ -63893,7 +63840,7 @@ function reduceEvent(state, event) {
63893
63840
  }
63894
63841
 
63895
63842
  // src/session-events/transcript-tailer.ts
63896
- import { closeSync as closeSync10, openSync as openSync10, readSync as readSync3, statSync as statSync12 } from "fs";
63843
+ import { closeSync as closeSync10, openSync as openSync10, readSync as readSync3, statSync as statSync11 } from "fs";
63897
63844
 
63898
63845
  class TranscriptTailer {
63899
63846
  filePath;
@@ -63938,7 +63885,7 @@ class TranscriptTailer {
63938
63885
  if (this.disposed)
63939
63886
  return;
63940
63887
  try {
63941
- const size = statSync12(this.filePath).size;
63888
+ const size = statSync11(this.filePath).size;
63942
63889
  if (size < this.offset) {
63943
63890
  this.offset = 0;
63944
63891
  this.buffer = "";
@@ -73747,6 +73694,62 @@ var init_poe = __esm(() => {
73747
73694
  init_provider_model_discovery();
73748
73695
  });
73749
73696
 
73697
+ // src/providers/catalog-query.ts
73698
+ import { statSync as statSync12 } from "fs";
73699
+ function project(entry) {
73700
+ return {
73701
+ modelId: entry.modelId,
73702
+ aliases: entry.aliases,
73703
+ supportsVision: entry.supportsVision,
73704
+ contextWindow: entry.contextWindow,
73705
+ releaseDate: entry.releaseDate,
73706
+ aggregators: entry.aggregators
73707
+ };
73708
+ }
73709
+ function getCachedEntries() {
73710
+ let mtimeMs;
73711
+ try {
73712
+ mtimeMs = statSync12(ALL_MODELS_CACHE_PATH).mtimeMs;
73713
+ } catch {
73714
+ return null;
73715
+ }
73716
+ if (mtimeMs === _memoMtimeMs && _memoEntries !== null) {
73717
+ return _memoEntries;
73718
+ }
73719
+ const cache = readAllModelsCache();
73720
+ if (!cache)
73721
+ return null;
73722
+ _memoEntries = cache.entries;
73723
+ _memoMtimeMs = mtimeMs;
73724
+ return _memoEntries;
73725
+ }
73726
+ function findEntryByAlias(alias, accept = () => true) {
73727
+ const entries = getCachedEntries();
73728
+ if (!entries || entries.length === 0)
73729
+ return null;
73730
+ for (const entry of entries) {
73731
+ if (entry.aliases.includes(alias) && accept(entry.modelId)) {
73732
+ return project(entry);
73733
+ }
73734
+ }
73735
+ return null;
73736
+ }
73737
+ function findEntryByModelId(modelId) {
73738
+ const entries = getCachedEntries();
73739
+ if (!entries || entries.length === 0)
73740
+ return null;
73741
+ for (const entry of entries) {
73742
+ if (entry.modelId === modelId) {
73743
+ return project(entry);
73744
+ }
73745
+ }
73746
+ return null;
73747
+ }
73748
+ var _memoEntries = null, _memoMtimeMs = -1;
73749
+ var init_catalog_query = __esm(() => {
73750
+ init_all_models_cache();
73751
+ });
73752
+
73750
73753
  // src/providers/transport/vertex-discovery.ts
73751
73754
  import { readFile as readFile6 } from "fs/promises";
73752
73755
  function _clearVertexDiscoveryCache() {
@@ -111015,8 +111018,13 @@ ${plan.hint}` : `[Route] ${plan.reason}`;
111015
111018
  log(`[RequestMeta] model=${body.model} output_config=${JSON.stringify(body.output_config) ?? "(none)"} metadata=${JSON.stringify(body.metadata) ?? "(none)"} anthropic-beta=${c.req.header("anthropic-beta") ?? "(none)"}`);
111016
111019
  maybeCaptureClassifierRequest(c, body);
111017
111020
  if (!monitorMode && options.classifier?.enabled && isAutoModeClassifierRequest(body)) {
111018
- log(`[Classifier] auto-mode permission classifier \u2192 native Anthropic (model ${body.model} \u2192 ${options.classifier.model})`);
111019
- rewriteClassifierForNative(body, options.classifier.model);
111021
+ const classifierModel = options.classifier.model ?? implicitAnthropicTierEntry("sonnet")?.modelId;
111022
+ if (!classifierModel) {
111023
+ log("[Classifier] refused: no model named and no Sonnet in the cloud models catalog");
111024
+ return c.json(wrapAnthropicError(400, NO_CLASSIFIER_MODEL_MESSAGE, "invalid_request_error"), 400);
111025
+ }
111026
+ log(`[Classifier] auto-mode permission classifier \u2192 native Anthropic (model ${body.model} \u2192 ${classifierModel})`);
111027
+ rewriteClassifierForNative(body, classifierModel);
111020
111028
  const classifierSigning = defaultRequestSigning(body.model);
111021
111029
  setNativeSigning(c, classifierSigning);
111022
111030
  return await withAdvisor(nativeHandler, classifierSigning).handle(c, body);
@@ -111092,6 +111100,7 @@ var init_proxy_server = __esm(() => {
111092
111100
  init_cors();
111093
111101
  init_base_api_format();
111094
111102
  init_authority();
111103
+ init_classifier_passthrough();
111095
111104
  init_policy();
111096
111105
  init_advisor_decorator();
111097
111106
  init_advisor_panel_gateway();
@@ -116448,6 +116457,7 @@ var init_claude_runner = __esm(() => {
116448
116457
  init_model_catalog();
116449
116458
  init_claude_code_facts();
116450
116459
  init_claude_code_login();
116460
+ init_classifier_passthrough();
116451
116461
  init_config();
116452
116462
  init_anthropic_forward();
116453
116463
  init_harness_gateway();
@@ -119105,231 +119115,14 @@ var init_team_orchestrator = __esm(() => {
119105
119115
  CANCELLED_DETAIL = `Stopped on the caller's instruction via team(mode:"cancel"). ` + "Whatever the child had written up to that point is in its response file.";
119106
119116
  });
119107
119117
 
119108
- // src/mcp-session/probe-launch-vars.ts
119109
- var PROBE_PLUGIN_VARS, PROBE_MODE_VARS, CALLER_LAUNCH_ENV_KEYS, PROBE_COWORK_SWITCH = "CLAUDE_CODE_USE_COWORK_PLUGINS", PROBE_REFUSAL_ENV_KEYS, HOST_READ_ENV_KEYS;
119110
- var init_probe_launch_vars = __esm(() => {
119111
- PROBE_PLUGIN_VARS = [
119112
- "CLAUDE_CODE_PLUGIN_CACHE_DIR",
119113
- "CLAUDE_CODE_PLUGIN_SEED_DIR",
119114
- "CLAUDE_CODE_PLUGIN_DIRS",
119115
- "CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE"
119116
- ];
119117
- PROBE_MODE_VARS = [
119118
- "CLAUDE_CODE_RESTRICTED",
119119
- "CLAUDE_CODE_SAFE_MODE",
119120
- "CLAUDE_CODE_SIMPLE",
119121
- "CLAUDE_CODE_RESTRICT_PERSONAL_CONFIG",
119122
- "CLAUDE_CODE_DISABLE_BUNDLED_SKILLS",
119123
- "CLAUDE_CODE_DISABLE_POLICY_SKILLS",
119124
- "CLAUDE_CODE_DISABLE_CLAUDE_API_SKILL",
119125
- "CLAUDE_CODE_DISABLE_CLAUDE_CODE_SKILL",
119126
- "CLAUDE_CODE_SKIP_PLUGIN_MCP_SERVERS",
119127
- "CLAUDE_CODE_SKIP_PLUGIN_MCP_SERVERS_EXCEPT",
119128
- "CLAUDE_CODE_SKIP_PLUGIN_LOCAL_MCP_SERVERS",
119129
- "CLAUDE_CODE_SKIP_PLUGIN_MCP_BUNDLES",
119130
- "ENABLE_CLAUDEAI_MCP_SERVERS"
119131
- ];
119132
- CALLER_LAUNCH_ENV_KEYS = [
119133
- "CLAUDE_CONFIG_DIR",
119134
- ...PROBE_PLUGIN_VARS,
119135
- ...PROBE_MODE_VARS
119136
- ];
119137
- PROBE_REFUSAL_ENV_KEYS = [PROBE_COWORK_SWITCH];
119138
- HOST_READ_ENV_KEYS = [...CALLER_LAUNCH_ENV_KEYS, ...PROBE_REFUSAL_ENV_KEYS];
119139
- });
119140
-
119141
- // src/mcp-session/host-launch.ts
119142
- import { readFileSync as readFileSync45, readlinkSync } from "fs";
119143
- function bindDarwin() {
119144
- const { dlopen, FFIType, ptr } = __require("bun:ffi");
119145
- const lib = dlopen("libSystem.B.dylib", {
119146
- sysctl: {
119147
- args: [FFIType.ptr, FFIType.u32, FFIType.ptr, FFIType.ptr, FFIType.ptr, FFIType.u64],
119148
- returns: FFIType.i32
119149
- },
119150
- proc_pidinfo: {
119151
- args: [FFIType.i32, FFIType.i32, FFIType.u64, FFIType.ptr, FFIType.i32],
119152
- returns: FFIType.i32
119153
- }
119154
- });
119155
- const sysctl = (name, out, len) => lib.symbols.sysctl(ptr(name), name.length, ptr(out), ptr(len), null, 0n);
119156
- return {
119157
- argmax() {
119158
- const out = new Int32Array(1);
119159
- const len = new BigUint64Array([4n]);
119160
- return sysctl(new Int32Array([CTL_KERN, KERN_ARGMAX]), out, len) === 0 ? out[0] : null;
119161
- },
119162
- procargs(pid, size) {
119163
- const buf = Buffer.alloc(size);
119164
- const len = new BigUint64Array([BigInt(size)]);
119165
- if (sysctl(new Int32Array([CTL_KERN, KERN_PROCARGS2, pid]), buf, len) !== 0)
119166
- return null;
119167
- return buf.subarray(0, Number(len[0]));
119168
- },
119169
- cwd(pid) {
119170
- const buf = Buffer.alloc(VNODEPATHINFO_BYTES);
119171
- const got = lib.symbols.proc_pidinfo(pid, PROC_PIDVNODEPATHINFO, 0n, ptr(buf), buf.length);
119172
- if (got !== buf.length)
119173
- return null;
119174
- return cwdOfVnodePathInfo(buf);
119175
- }
119176
- };
119177
- }
119178
- function cwdOfVnodePathInfo(buf) {
119179
- if (buf.length !== VNODEPATHINFO_BYTES)
119180
- return null;
119181
- const field = buf.subarray(VNODE_INFO_BYTES, VNODE_INFO_BYTES + MAXPATHLEN);
119182
- const end = field.indexOf(0);
119183
- if (end <= 0)
119184
- return null;
119185
- return field.toString("utf8", 0, end);
119186
- }
119187
- function darwin() {
119188
- if (darwinBinding !== undefined)
119189
- return darwinBinding;
119190
- try {
119191
- darwinBinding = bindDarwin();
119192
- } catch {
119193
- darwinBinding = null;
119194
- }
119195
- return darwinBinding;
119196
- }
119197
- function argvOfProcargs(buf) {
119198
- return procargsLayout(buf)?.argv ?? null;
119199
- }
119200
- function procargsLayout(buf) {
119201
- if (buf.length < 4)
119202
- return null;
119203
- const argc = buf.readInt32LE(0);
119204
- if (argc < 1)
119205
- return null;
119206
- const pathEnd = buf.indexOf(0, 4);
119207
- if (pathEnd < 0)
119208
- return null;
119209
- let i = 4 + Math.ceil((pathEnd - 4 + 1) / EXEC_PATH_ALIGN) * EXEC_PATH_ALIGN;
119210
- if (i >= buf.length || buf[i] === 0)
119211
- return null;
119212
- for (let pad = pathEnd;pad < i; pad++)
119213
- if (buf[pad] !== 0)
119214
- return null;
119215
- const argv = [];
119216
- for (let k = 0;k < argc; k++) {
119217
- const end = buf.indexOf(0, i);
119218
- if (end < 0)
119219
- return null;
119220
- argv.push(buf.toString("utf8", i, end));
119221
- i = end + 1;
119222
- }
119223
- return { argv, end: i };
119224
- }
119225
- function hostEnvOf(entries) {
119226
- const env = {};
119227
- for (const key of HOST_ENV_KEYS) {
119228
- const prefix = Buffer.from(`${key}=`);
119229
- const entry = entries.find((e) => e.subarray(0, prefix.length).equals(prefix));
119230
- if (entry === undefined)
119231
- continue;
119232
- const raw = entry.subarray(prefix.length);
119233
- const value = raw.toString("utf8");
119234
- if (!Buffer.from(value, "utf8").equals(raw))
119235
- return null;
119236
- env[key] = value;
119237
- }
119238
- return env;
119239
- }
119240
- function hostEnvOfProcargs(buf) {
119241
- const layout = procargsLayout(buf);
119242
- if (!layout)
119243
- return null;
119244
- const entries = [];
119245
- for (let i = layout.end;; ) {
119246
- const end = buf.indexOf(0, i);
119247
- if (end < 0)
119248
- return null;
119249
- if (end === i)
119250
- break;
119251
- entries.push(buf.subarray(i, end));
119252
- i = end + 1;
119253
- }
119254
- return hostEnvOf(entries);
119255
- }
119256
- function hostEnvOfEnviron(raw) {
119257
- if (raw.length === 0 || raw[raw.length - 1] !== 0)
119258
- return null;
119259
- const entries = [];
119260
- for (let i = 0;i < raw.length; ) {
119261
- const end = raw.indexOf(0, i);
119262
- entries.push(raw.subarray(i, end));
119263
- i = end + 1;
119264
- }
119265
- return hostEnvOf(entries);
119266
- }
119267
- function readDarwin(pid) {
119268
- const binding = darwin();
119269
- if (!binding)
119270
- return null;
119271
- const size = binding.argmax();
119272
- if (size === null || size <= 0)
119273
- return null;
119274
- const raw = binding.procargs(pid, size);
119275
- const argv = raw ? argvOfProcargs(raw) : null;
119276
- const cwd = binding.cwd(pid);
119277
- if (!raw || !argv || !cwd)
119278
- return null;
119279
- return { argv, cwd, env: hostEnvOfProcargs(raw) };
119280
- }
119281
- function argvOfCmdline(raw) {
119282
- if (raw.length === 0 || raw[raw.length - 1] !== 0)
119283
- return null;
119284
- const argv = raw.toString("utf8", 0, raw.length - 1).split("\x00");
119285
- if (argv.length > 1 && argv.slice(1).every((arg) => arg === ""))
119286
- return null;
119287
- return argv;
119288
- }
119289
- function readLinux(pid) {
119290
- try {
119291
- const argv = argvOfCmdline(readFileSync45(`/proc/${pid}/cmdline`));
119292
- if (!argv)
119293
- return null;
119294
- const cwd = readlinkSync(`/proc/${pid}/cwd`);
119295
- let env;
119296
- try {
119297
- env = hostEnvOfEnviron(readFileSync45(`/proc/${pid}/environ`));
119298
- } catch {
119299
- env = null;
119300
- }
119301
- return { argv, cwd, env };
119302
- } catch {
119303
- return null;
119304
- }
119305
- }
119306
- var HOST_ENV_KEYS, CTL_KERN = 1, KERN_ARGMAX = 8, KERN_PROCARGS2 = 49, PROC_PIDVNODEPATHINFO = 9, VNODE_INFO_BYTES = 152, MAXPATHLEN = 1024, VNODEPATHINFO_BYTES, darwinBinding, EXEC_PATH_ALIGN = 8, PID_MAX, readHostLaunch = (pid) => {
119307
- if (!Number.isInteger(pid) || pid <= 1 || pid > PID_MAX)
119308
- return null;
119309
- try {
119310
- if (process.platform === "darwin")
119311
- return readDarwin(pid);
119312
- if (process.platform === "linux")
119313
- return readLinux(pid);
119314
- } catch {}
119315
- return null;
119316
- };
119317
- var init_host_launch = __esm(() => {
119318
- init_probe_launch_vars();
119319
- HOST_ENV_KEYS = HOST_READ_ENV_KEYS;
119320
- VNODEPATHINFO_BYTES = 2 * (VNODE_INFO_BYTES + MAXPATHLEN);
119321
- PID_MAX = 2 ** 31 - 1;
119322
- });
119323
-
119324
119118
  // src/mcp-session/inherited-settings.ts
119325
119119
  import { spawnSync as spawnSync3 } from "child_process";
119326
119120
  import {
119327
119121
  chmodSync as chmodSync7,
119328
119122
  closeSync as closeSync16,
119329
119123
  existsSync as existsSync40,
119330
- lstatSync as lstatSync9,
119331
119124
  openSync as openSync16,
119332
- readFileSync as readFileSync46,
119125
+ readFileSync as readFileSync45,
119333
119126
  readSync as readSync7,
119334
119127
  readdirSync as readdirSync12,
119335
119128
  realpathSync as realpathSync8,
@@ -119417,7 +119210,7 @@ function readSettingsValue(value) {
119417
119210
  }
119418
119211
  let text;
119419
119212
  try {
119420
- text = readFileSync46(value, "utf-8");
119213
+ text = readFileSync45(value, "utf-8");
119421
119214
  } catch (err) {
119422
119215
  throw new Error(`invalid_args: settings ${value} cannot be read (${err.message})`);
119423
119216
  }
@@ -119454,9 +119247,6 @@ function settingsFilesFor(setupReal, sources) {
119454
119247
  ...loads("local") ? localSettingsFiles(setupReal, readText, regularPathKind).map(([file]) => file) : []
119455
119248
  ];
119456
119249
  }
119457
- function launchSettingsFiles(dir) {
119458
- return settingsFilesFor(realOrResolved(dir), null);
119459
- }
119460
119250
  function launchSettingsFilesByTier(dir, sources) {
119461
119251
  const real = realOrResolved(dir);
119462
119252
  const loads = (source) => sources === null || sources.has(source);
@@ -119466,7 +119256,7 @@ function launchSettingsFilesByTier(dir, sources) {
119466
119256
  };
119467
119257
  }
119468
119258
  function readText(path) {
119469
- return readFileSync46(path, "utf-8");
119259
+ return readFileSync45(path, "utf-8");
119470
119260
  }
119471
119261
  function realOrResolved(path) {
119472
119262
  const missing = [];
@@ -119643,11 +119433,6 @@ function remoteSettingsPath(managed, env, cwd) {
119643
119433
  }
119644
119434
  return managed.remoteSettingsFile;
119645
119435
  }
119646
- function hybridSettingsDirOf(managed, env, cwd) {
119647
- if (managed.hybridSettingsDir === null)
119648
- return join58(claudeCodeConfigDir(env, cwd), "state");
119649
- return managed.hybridSettingsDir;
119650
- }
119651
119436
  function readManagedPolicy(managed, env, cwd) {
119652
119437
  const objects = [];
119653
119438
  const oversize = [];
@@ -119675,57 +119460,6 @@ function readManagedPolicy(managed, env, cwd) {
119675
119460
  }
119676
119461
  return { objects, oversize };
119677
119462
  }
119678
- function pathPresent(path) {
119679
- try {
119680
- lstatSync9(path);
119681
- return true;
119682
- } catch (err) {
119683
- const code = err.code;
119684
- return code !== "ENOENT" && code !== "ENOTDIR";
119685
- }
119686
- }
119687
- function presentEntries(dir, keep) {
119688
- if (!pathPresent(dir))
119689
- return [];
119690
- try {
119691
- return readdirSync12(dir).filter(keep).sort().map((name) => join58(dir, name));
119692
- } catch {
119693
- return [dir];
119694
- }
119695
- }
119696
- function remoteSettingsSetsNothing(path) {
119697
- try {
119698
- const stat = lstatSync9(path);
119699
- if (!stat.isFile() || stat.size > REMOTE_SETTINGS_MAX_BYTES)
119700
- return false;
119701
- const parsed = JSON.parse(readText(path));
119702
- return isPlainObject7(parsed) && Object.keys(parsed).every((key) => key.startsWith("$"));
119703
- } catch {
119704
- return false;
119705
- }
119706
- }
119707
- function managedPolicySourcePresent(managed, env, cwd) {
119708
- const remote = remoteSettingsPath(managed, env, cwd);
119709
- if (remote !== undefined && pathPresent(remote) && !remoteSettingsSetsNothing(remote)) {
119710
- return remote;
119711
- }
119712
- const files = [...managed.managedPreferencePlists ?? [], managed.managedSettingsFile];
119713
- for (const path of files)
119714
- if (path !== undefined && pathPresent(path))
119715
- return path;
119716
- const dropInDir = managed.managedSettingsDropInDir;
119717
- const dropIn = dropInDir ? presentEntries(dropInDir, () => true)[0] : undefined;
119718
- if (dropIn !== undefined)
119719
- return dropIn;
119720
- if (managed.managedMcpFile !== undefined && pathPresent(managed.managedMcpFile)) {
119721
- return managed.managedMcpFile;
119722
- }
119723
- const hybridDir = hybridSettingsDirOf(managed, env, cwd);
119724
- const hybrid = hybridDir ? presentEntries(hybridDir, (n) => n.startsWith("hybrid-settings") && n.endsWith(".json"))[0] : undefined;
119725
- if (hybrid !== undefined)
119726
- return hybrid;
119727
- return managed.registryPolicyKeys?.[0];
119728
- }
119729
119463
  function sideloadFlagsDisabledBy(policy) {
119730
119464
  return policy.objects.find(({ value }) => value.disableSideloadFlags === true)?.path;
119731
119465
  }
@@ -119751,16 +119485,21 @@ function registryPolicyState(answer) {
119751
119485
  return "absent";
119752
119486
  return "unknown";
119753
119487
  }
119754
- function registryPolicyBlocksMcpConfig(managed) {
119488
+ function unreadRegistryPolicy(managed) {
119755
119489
  const read = managed.readRegistry ?? regQuery;
119756
119490
  for (const key of managed.registryPolicyKeys ?? []) {
119757
119491
  const state = registryPolicyState(read(key));
119758
- if (state === "absent")
119759
- continue;
119760
- log(state === "present" ? `[mcp-session] no MCP server handed over: the policy key ${key} holds a Settings value, which claudish does not read` : `[mcp-session] no MCP server handed over: the policy key ${key} could not be queried, so claudish cannot tell whether it is present`);
119761
- return true;
119492
+ if (state !== "absent")
119493
+ return { key, state };
119762
119494
  }
119763
- return false;
119495
+ return;
119496
+ }
119497
+ function registryPolicyBlocksMcpConfig(managed) {
119498
+ const unread = unreadRegistryPolicy(managed);
119499
+ if (unread === undefined)
119500
+ return false;
119501
+ log(unread.state === "present" ? `[mcp-session] no MCP server handed over: the policy key ${unread.key} holds a Settings value, which claudish does not read` : `[mcp-session] no MCP server handed over: the policy key ${unread.key} could not be queried, so claudish cannot tell whether it is present`);
119502
+ return true;
119764
119503
  }
119765
119504
  function comparableServerName(name) {
119766
119505
  return name.replace(/[^a-zA-Z0-9_-]/g, "_");
@@ -119797,7 +119536,6 @@ function realManagedPaths(platform = process.platform) {
119797
119536
  managedMcpFile: join58(dir, "managed-mcp.json"),
119798
119537
  managedPreferencePlists: platform === "darwin" ? managedPreferencePlistsFor(currentUsername()) : [],
119799
119538
  remoteSettingsFile: null,
119800
- hybridSettingsDir: null,
119801
119539
  registryPolicyKeys: platform === "win32" ? [...WINDOWS_POLICY_KEYS] : []
119802
119540
  };
119803
119541
  }
@@ -119991,977 +119729,499 @@ var init_parent_session = __esm(() => {
119991
119729
  CLAUDE_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
119992
119730
  });
119993
119731
 
119994
- // src/mcp-session/plugin-probe.ts
119995
- import { spawn as spawn4 } from "child_process";
119996
- import {
119997
- constants as constants5,
119998
- closeSync as closeSync17,
119999
- fstatSync as fstatSync5,
120000
- lstatSync as lstatSync10,
120001
- mkdtempSync as mkdtempSync4,
120002
- openSync as openSync17,
120003
- readFileSync as readFileSync47,
120004
- readdirSync as readdirSync13,
120005
- rmSync as rmSync15,
120006
- statSync as statSync24
120007
- } from "fs";
120008
- import { tmpdir as tmpdir3 } from "os";
120009
- import { basename as basename9, isAbsolute as isAbsolute5, join as join60, resolve as resolve9 } from "path";
120010
- function passes(flags, flag) {
120011
- return flags.some((t) => t === flag || t.startsWith(`${flag}=`));
120012
- }
120013
- function passesBeforeEnd(flags, flag) {
120014
- const at = flags.indexOf(flag);
120015
- const end = flags.indexOf("--");
120016
- return at !== -1 && (end === -1 || at < end);
120017
- }
120018
- function pluginLoadingFlags(flags, base) {
120019
- const out = [];
120020
- const push = (flag, value) => out.push(flag, PLUGIN_PATH_FLAGS.includes(flag) ? resolve9(base, value) : value);
120021
- const takesValue = (flag) => PLUGIN_PATH_FLAGS.includes(flag) || PLUGIN_VALUE_FLAGS.includes(flag);
120022
- for (let i = 0;i < flags.length; i++) {
120023
- const token = flags[i];
120024
- if (PLUGIN_BOOLEAN_FLAGS.includes(token)) {
120025
- out.push(token);
120026
- continue;
120027
- }
120028
- if (takesValue(token)) {
120029
- const value = flags[i + 1];
120030
- if (value !== undefined)
120031
- push(token, value);
120032
- i++;
120033
- continue;
120034
- }
120035
- const eq = token.indexOf("=");
120036
- const flag = eq > 0 ? token.slice(0, eq) : "";
120037
- if (takesValue(flag))
120038
- push(flag, token.slice(eq + 1));
120039
- }
120040
- return out;
120041
- }
120042
- function pluginProbeArgs(settingsFile, launchFlags, base) {
120043
- const quiet = QUIET_FLAGS.map((flag) => flag === "<settings file>" ? settingsFile : flag);
120044
- return [...quiet, ...pluginLoadingFlags(launchFlags, base), "-p", "/effort"];
120045
- }
120046
- function isProbeParentVar(key) {
120047
- return PROBE_PARENT_VARS.includes(key) || /^LC_[A-Z]+$/.test(key);
120048
- }
120049
- function pluginProbeEnv(parentEnv) {
120050
- const env = {};
120051
- for (const [key, value] of Object.entries(parentEnv)) {
120052
- if (value !== undefined && isProbeParentVar(key))
120053
- env[key] = value;
120054
- }
120055
- env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = "1";
120056
- env[PROBE_HOST_MANAGED_MARKER] = "1";
120057
- env.ANTHROPIC_BASE_URL = PLUGIN_PROBE_BASE_URL;
120058
- return env;
120059
- }
120060
- function isPlainObject8(value) {
120061
- return typeof value === "object" && value !== null && !Array.isArray(value);
120062
- }
120063
- function pluginProbeSettings(layer) {
120064
- const base = structuredClone(layer ?? {});
120065
- for (const key of ["hooks", ...COMMAND_SETTINGS])
120066
- delete base[key];
120067
- if (isPlainObject8(base.env)) {
120068
- const closed = new Set(Object.keys(PROBE_SETTINGS_ENV));
120069
- base.env = Object.fromEntries(Object.entries(base.env).filter(([key]) => !closed.has(key.toUpperCase())));
120070
- } else {
120071
- delete base.env;
120072
- }
120073
- return mergeSettingsLayers(base, { disableAllHooks: true, env: { ...PROBE_SETTINGS_ENV } });
120074
- }
120075
- function readRegularFile(path) {
119732
+ // src/mcp-session/bounded-read.ts
119733
+ import { constants as constants5, closeSync as closeSync17, fstatSync as fstatSync5, openSync as openSync17, readSync as readSync8 } from "fs";
119734
+ function readBoundedText(path, maxBytes) {
120076
119735
  let fd;
120077
119736
  try {
120078
119737
  fd = openSync17(path, constants5.O_RDONLY | constants5.O_NONBLOCK);
119738
+ const stat = fstatSync5(fd);
119739
+ if (!stat.isFile())
119740
+ return "not_file";
119741
+ if (stat.size > maxBytes)
119742
+ return "oversize";
119743
+ const parts = [];
119744
+ let total = 0;
119745
+ for (;; ) {
119746
+ const room = Math.min(CHUNK, maxBytes + 1 - total);
119747
+ const chunk = Buffer.allocUnsafe(room);
119748
+ const n = readSync8(fd, chunk, 0, room, null);
119749
+ if (n === 0)
119750
+ break;
119751
+ total += n;
119752
+ if (total > maxBytes)
119753
+ return "oversize";
119754
+ parts.push(chunk.subarray(0, n));
119755
+ }
119756
+ return { text: Buffer.concat(parts, total).toString("utf-8"), mode: stat.mode & 511 };
120079
119757
  } catch (err) {
120080
- const code = err.code;
120081
- return code === "ENOENT" || code === "ENOTDIR" ? null : "unreadable";
120082
- }
120083
- try {
120084
- if (!fstatSync5(fd).isFile())
120085
- return "unreadable";
120086
- return readFileSync47(fd, "utf-8");
120087
- } catch {
120088
- return "unreadable";
119758
+ const code = err?.code;
119759
+ return code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable";
120089
119760
  } finally {
120090
- closeSync17(fd);
120091
- }
120092
- }
120093
- function commandSettingIn(paths, keys) {
120094
- for (const path of paths) {
120095
- const text = readRegularFile(path);
120096
- if (text === null)
120097
- continue;
120098
- if (text === "unreadable")
120099
- return { path };
120100
- let parsed;
120101
- try {
120102
- parsed = JSON.parse(text);
120103
- } catch {
120104
- return { path };
120105
- }
120106
- if (!isPlainObject8(parsed))
120107
- return { path };
120108
- const key = keys.find((k) => parsed[k] !== undefined && parsed[k] !== null);
120109
- if (key !== undefined)
120110
- return { path, key };
120111
- }
120112
- return;
120113
- }
120114
- function initPluginsOf(event) {
120115
- const list = isPlainObject8(event) ? event.plugins : undefined;
120116
- if (!Array.isArray(list))
120117
- return null;
120118
- const plugins = [];
120119
- for (const item of list) {
120120
- if (!isPlainObject8(item))
120121
- return null;
120122
- const { name, path, source, version } = item;
120123
- if (typeof name !== "string" || typeof path !== "string" || typeof source !== "string") {
120124
- return null;
120125
- }
120126
- if (version !== undefined && typeof version !== "string")
120127
- return null;
120128
- plugins.push({ name, path, source, ...version !== undefined ? { version } : {} });
120129
- }
120130
- return plugins;
120131
- }
120132
- function manifestNames(path, name) {
120133
- const manifest = join60(path, ".claude-plugin", "plugin.json");
120134
- try {
120135
- if (!statSync24(manifest).isFile())
120136
- return false;
120137
- const parsed = JSON.parse(readFileSync47(manifest, "utf-8"));
120138
- return isPlainObject8(parsed) && parsed.name === name;
120139
- } catch {
120140
- return false;
120141
- }
120142
- }
120143
- function pluginsToHandOver(caller, child) {
120144
- const childPaths = new Map(child.map((p) => [p.source, p.path]));
120145
- const childInline = new Set(child.filter((p) => p.source.endsWith("@inline")).map((p) => p.name));
120146
- const seen = new Set;
120147
- const plugins = [];
120148
- for (const p of caller) {
120149
- if (p.source.endsWith("@inline") || !isAbsolute5(p.path))
120150
- continue;
120151
- if (childPaths.get(p.source) === p.path || seen.has(p.path))
120152
- continue;
120153
- if (childInline.has(p.name)) {
120154
- log(`[mcp-session] plugin ${p.source} not handed over: the child loads ${p.name} from its own --plugin-dir`);
120155
- continue;
120156
- }
120157
- if (!manifestNames(p.path, p.name)) {
120158
- log(`[mcp-session] plugin ${p.source} not handed over: its copy has no .claude-plugin/plugin.json naming it ${p.name}`);
120159
- continue;
119761
+ if (fd !== undefined) {
119762
+ try {
119763
+ closeSync17(fd);
119764
+ } catch {}
120160
119765
  }
120161
- seen.add(p.path);
120162
- plugins.push({ id: p.source, version: p.version, path: p.path });
120163
119766
  }
120164
- return plugins;
120165
119767
  }
120166
- function withoutLayerDisabled(plugins, layer) {
120167
- const enabled = isPlainObject8(layer?.enabledPlugins) ? layer.enabledPlugins : {};
120168
- return plugins.filter((p) => {
120169
- if (!Object.hasOwn(enabled, p.id) || enabled[p.id] === true)
120170
- return true;
120171
- log(`[mcp-session] plugin ${p.id} not handed over: the child's settings turn it off`);
120172
- return false;
120173
- });
120174
- }
120175
- function probeLineEvent(line, afterInit) {
120176
- let event;
119768
+ function readBoundedJson(path, maxBytes) {
119769
+ const read = readBoundedText(path, maxBytes);
119770
+ if (typeof read === "string")
119771
+ return read;
120177
119772
  try {
120178
- event = JSON.parse(line);
119773
+ return { value: JSON.parse(read.text) };
120179
119774
  } catch {
120180
- return null;
120181
- }
120182
- if (!isPlainObject8(event))
120183
- return null;
120184
- if (event.type === "assistant") {
120185
- if (!afterInit)
120186
- return { kind: "fail", cause: "assistant_before_init" };
120187
- const model = isPlainObject8(event.message) ? event.message.model : undefined;
120188
- return model === "<synthetic>" ? null : { kind: "fail", cause: "turns" };
120189
- }
120190
- if (event.type === "result") {
120191
- const success = event.subtype === "success" && event.is_error === false;
120192
- return { kind: "result", success, turns: event.num_turns };
120193
- }
120194
- if (event.type !== "system" || event.subtype !== "init" || afterInit)
120195
- return null;
120196
- const plugins = initPluginsOf(event);
120197
- return plugins ? { kind: "init", plugins } : { kind: "fail", cause: "plugins_malformed" };
120198
- }
120199
- function groupAlive(pgid) {
120200
- try {
120201
- process.kill(-pgid, 0);
120202
- return true;
120203
- } catch (err) {
120204
- return err.code === "EPERM";
119775
+ return "unreadable";
120205
119776
  }
120206
119777
  }
120207
- function killProbe(child) {
120208
- try {
120209
- if (child.pid !== undefined)
120210
- process.kill(-child.pid, "SIGKILL");
120211
- } catch {
120212
- try {
120213
- child.kill("SIGKILL");
120214
- } catch {}
120215
- }
119778
+ var CHUNK;
119779
+ var init_bounded_read = __esm(() => {
119780
+ CHUNK = 64 * 1024;
119781
+ });
119782
+
119783
+ // src/mcp-session/plugin-handover.ts
119784
+ import { readFileSync as readFileSync46 } from "fs";
119785
+ import { homedir as homedir41 } from "os";
119786
+ import { basename as basename9, delimiter as delimiter3, join as join60, resolve as resolve9 } from "path";
119787
+ function isPlainObject8(value) {
119788
+ return typeof value === "object" && value !== null && !Array.isArray(value);
120216
119789
  }
120217
- async function lookupBinary(findBinary, env, stopMs, hardMs, signal) {
120218
- const stop = new AbortController;
120219
- const timer = setTimeout(() => stop.abort(), Math.max(0, stopMs));
120220
- const onAbort = () => stop.abort();
120221
- signal?.addEventListener("abort", onAbort, { once: true });
120222
- let hardTimer;
120223
- const outlived = new Promise((settle) => {
120224
- hardTimer = setTimeout(() => settle("outlived"), Math.max(0, hardMs));
120225
- });
120226
- let binary;
120227
- try {
120228
- const found = Promise.resolve().then(() => findBinary(env, stop.signal)).catch(() => null);
120229
- binary = await Promise.race([found, outlived]);
120230
- } finally {
120231
- clearTimeout(timer);
120232
- clearTimeout(hardTimer);
120233
- signal?.removeEventListener("abort", onAbort);
120234
- }
120235
- if (binary === "outlived") {
120236
- stop.abort();
120237
- log("[mcp-session] the plugin probe's binary lookup outlived the probe's deadline after it was stopped; the probe answers without it");
120238
- }
120239
- if (signal?.aborted)
120240
- return "aborted";
120241
- if (stop.signal.aborted)
120242
- return "timeout";
120243
- return binary === "outlived" ? "timeout" : binary;
120244
- }
120245
- function pluginProbeRunner(findBinary, serverDir = () => process.cwd()) {
120246
- return async (request) => {
120247
- const { signal } = request;
120248
- const deadline = Date.now() + request.timeoutMs;
120249
- const killAt = deadline - Math.min(PROBE_REAP_MS, Math.floor(request.timeoutMs / 4));
120250
- if (signal?.aborted)
120251
- return { ok: false, cause: "aborted" };
120252
- const base = serverDir();
120253
- const named = request.env.CLAUDE_PATH;
120254
- const claudePath = named ? startablePath(base, named) : undefined;
120255
- if (claudePath === null)
120256
- return { ok: false, cause: "no_claude_binary" };
120257
- const env = claudePath ? { ...request.env, CLAUDE_PATH: claudePath } : request.env;
120258
- const binary = await lookupBinary(findBinary, env, killAt - Date.now(), deadline - Date.now(), signal);
120259
- if (binary === "timeout" || binary === "aborted")
120260
- return { ok: false, cause: binary };
120261
- const path = binary ? startablePath(base, binary) : null;
120262
- if (path === null)
120263
- return { ok: false, cause: "no_claude_binary" };
120264
- return runProbe(path, request, deadline, killAt);
120265
- };
120266
- }
120267
- function startablePath(base, named) {
120268
- return isAbsolute5(named) ? named : claudePathIn(base, named);
120269
- }
120270
- function runProbe(binary, request, deadline, killAt) {
120271
- const { signal } = request;
120272
- return new Promise((settle) => {
120273
- let child;
120274
- try {
120275
- child = spawn4(binary, request.args, {
120276
- cwd: request.cwd,
120277
- env: request.env,
120278
- stdio: ["ignore", "pipe", "ignore"],
120279
- detached: true
120280
- });
120281
- } catch {
120282
- settle({ ok: false, cause: "spawn_failed" });
120283
- return;
119790
+ function flagValues(flags, flag) {
119791
+ const values = [];
119792
+ for (let i = 0;i < flags.length; i++) {
119793
+ const token = flags[i];
119794
+ if (token === flag) {
119795
+ const value = flags[i + 1];
119796
+ if (value !== undefined)
119797
+ values.push(value);
119798
+ i++;
119799
+ } else if (token.startsWith(`${flag}=`)) {
119800
+ values.push(token.slice(flag.length + 1));
120284
119801
  }
120285
- const pgid = child.pid;
120286
- let plugins = null;
120287
- let turns = null;
120288
- let failure = null;
120289
- let exitCode = null;
120290
- let exited = false;
120291
- let stdoutDone = false;
120292
- let pending = "";
120293
- let bytes = 0;
120294
- let settled = false;
120295
- let poll;
120296
- const verdict = () => {
120297
- if (failure)
120298
- return { ok: false, cause: failure };
120299
- if (!plugins)
120300
- return { ok: false, cause: "exited_before_init" };
120301
- if (exitCode !== 0)
120302
- return { ok: false, cause: "nonzero_exit" };
120303
- if (!turns)
120304
- return { ok: false, cause: "no_result" };
120305
- if (turns.value !== 0)
120306
- return { ok: false, cause: "turns" };
120307
- return { ok: true, plugins };
120308
- };
120309
- const finish = () => {
120310
- if (settled)
120311
- return;
120312
- settled = true;
120313
- clearTimeout(killTimer);
120314
- clearTimeout(deadlineTimer);
120315
- clearInterval(poll);
120316
- signal?.removeEventListener("abort", onAbort);
120317
- child.stdout?.destroy();
120318
- settle(verdict());
120319
- };
120320
- const settleWhenGone = () => {
120321
- if (settled || !exited || !stdoutDone)
120322
- return;
120323
- if (pgid === undefined || !groupAlive(pgid))
120324
- return finish();
120325
- if (!poll) {
120326
- poll = setInterval(() => {
120327
- if (pgid === undefined || !groupAlive(pgid))
120328
- finish();
120329
- }, GROUP_POLL_MS);
120330
- }
120331
- };
120332
- const fail = (cause) => {
120333
- failure ??= cause;
120334
- killProbe(child);
120335
- stdoutDone = true;
120336
- settleWhenGone();
120337
- };
120338
- const readLine = (line) => {
120339
- const event = probeLineEvent(line, plugins !== null);
120340
- if (!event)
120341
- return;
120342
- if (event.kind === "fail")
120343
- return fail(event.cause);
120344
- if (event.kind === "init") {
120345
- plugins = event.plugins;
120346
- return;
120347
- }
120348
- if (plugins === null || turns !== null || !event.success)
120349
- return fail("bad_result");
120350
- turns = { value: event.turns };
120351
- };
120352
- const onAbort = () => fail("aborted");
120353
- const killTimer = setTimeout(() => fail("timeout"), Math.max(0, killAt - Date.now()));
120354
- const deadlineTimer = setTimeout(() => {
120355
- failure ??= "timeout";
120356
- finish();
120357
- }, Math.max(0, deadline - Date.now()));
120358
- signal?.addEventListener("abort", onAbort, { once: true });
120359
- child.stdout?.setEncoding("utf8");
120360
- child.stdout?.on("data", (chunk) => {
120361
- if (failure)
120362
- return;
120363
- bytes += Buffer.byteLength(chunk);
120364
- if (bytes > PROBE_OUTPUT_MAX_BYTES)
120365
- return fail("output_too_large");
120366
- pending += chunk;
120367
- for (let nl = pending.indexOf(`
120368
- `);nl >= 0 && !failure; nl = pending.indexOf(`
120369
- `)) {
120370
- readLine(pending.slice(0, nl));
120371
- pending = pending.slice(nl + 1);
120372
- }
120373
- });
120374
- child.stdout?.on("close", () => {
120375
- if (!failure && pending)
120376
- readLine(pending);
120377
- pending = "";
120378
- stdoutDone = true;
120379
- settleWhenGone();
120380
- });
120381
- child.on("error", () => {
120382
- if (child.pid === undefined) {
120383
- failure ??= "spawn_failed";
120384
- exited = true;
120385
- stdoutDone = true;
120386
- finish();
120387
- }
120388
- });
120389
- child.on("exit", (code) => {
120390
- exitCode = code;
120391
- exited = true;
120392
- killProbe(child);
120393
- settleWhenGone();
120394
- });
120395
- });
120396
- }
120397
- function policyPlatformOf(platform, env, readProcVersion) {
120398
- if (platform === "win32")
120399
- return "windows";
120400
- if (platform !== "linux")
120401
- return "other";
120402
- if (env.WSL_DISTRO_NAME || env.WSL_INTEROP)
120403
- return "wsl";
120404
- try {
120405
- const version = readProcVersion().toLowerCase();
120406
- return version.includes("microsoft") || version.includes("wsl") ? "wsl" : "other";
120407
- } catch {
120408
- return "other";
120409
119802
  }
119803
+ return values;
120410
119804
  }
120411
- function hostPolicyPlatform(env) {
120412
- return policyPlatformOf(process.platform, env, () => readFileSync47("/proc/version", "utf-8"));
120413
- }
120414
- function isClaudeProgram(program) {
120415
- const name = basename9(program);
120416
- return name === "claude" || name === "claude.exe" || /[/\\]claude[/\\]versions[/\\][^/\\]+$/.test(program);
120417
- }
120418
- function callerLaunchFlags(argv) {
120419
- const program = argv[0];
120420
- if (program === undefined)
120421
- return null;
120422
- let flags;
120423
- if (isClaudeProgram(program)) {
120424
- flags = argv.slice(1);
120425
- } else if (/^(node|nodejs|bun)(\.exe)?$/.test(basename9(program))) {
120426
- const script = argv[1];
120427
- if (!script || !/[/\\]@anthropic-ai[/\\]claude-code[/\\]cli\.m?js$/.test(script))
120428
- return null;
120429
- flags = argv.slice(2);
120430
- } else {
120431
- return null;
120432
- }
120433
- if (FLAGLESS_SUBCOMMANDS.includes(flags[0] ?? ""))
120434
- return null;
120435
- if (flags.some((t) => t.startsWith("--bg-")))
120436
- return null;
120437
- return flags;
119805
+ function passes(flags, flag) {
119806
+ return flags.some((token) => token === flag || token.startsWith(`${flag}=`));
120438
119807
  }
120439
119808
  function claudeEnvTrue(value) {
120440
119809
  if (!value)
120441
119810
  return false;
120442
119811
  return ["1", "true", "yes", "on"].includes(value.toLowerCase().trim());
120443
119812
  }
120444
- function callerModeRefusal(flags, effective) {
120445
- const beforeEnd = (flag) => passesBeforeEnd(flags, flag);
120446
- const mode = (on, name) => on ? {
120447
- outcome: "caller_mode_unmodelled",
120448
- line: `the caller runs in ${name}, which keeps its plugin list but runs none of those plugins' commands or skills, so a copy handed over would give the child what the caller does not run`
120449
- } : undefined;
120450
- if (effective.everOn(PROBE_COWORK_SWITCH) || beforeEnd("--cowork")) {
120451
- return coworkRefusal("the caller's");
120452
- }
120453
- if (effective.movesConfigDir) {
120454
- return {
120455
- outcome: "caller_mode_unmodelled",
120456
- line: "a settings env block of the caller sets CLAUDE_CONFIG_DIR, which moves the settings Claude Code reads after they were read, and claudish does not model that"
120457
- };
120458
- }
120459
- if (effective.movesRestricted) {
120460
- return {
120461
- outcome: "caller_mode_unmodelled",
120462
- line: "a settings env block of the caller sets CLAUDE_CODE_RESTRICTED other than its launch did, after the launch chose its setting sources, and a probe booted with that value could choose others"
120463
- };
120464
- }
120465
- return mode(effective.mayBeOn("CLAUDE_CODE_SAFE_MODE") || beforeEnd("--safe-mode"), "safe mode") ?? mode(effective.mayBeOn("CLAUDE_CODE_SIMPLE") || beforeEnd("--bare"), "bare mode");
119813
+ function expandHome(value, env, cwd) {
119814
+ const home = env.HOME || homedir41();
119815
+ if (value === "~")
119816
+ return home;
119817
+ if (value.startsWith("~/"))
119818
+ return join60(home, value.slice(2));
119819
+ return resolve9(cwd, value);
120466
119820
  }
120467
- function envStringsOf(layer) {
120468
- if (layer.env === undefined)
119821
+ function coworkMode(env) {
119822
+ return claudeEnvTrue(env.CLAUDE_CODE_USE_COWORK_PLUGINS);
119823
+ }
119824
+ function envBlockOf(layer) {
119825
+ if (!layer || !isPlainObject8(layer.env))
120469
119826
  return {};
120470
- if (!isPlainObject8(layer.env))
120471
- return;
120472
- const env = {};
119827
+ const out = {};
120473
119828
  for (const [key, value] of Object.entries(layer.env)) {
120474
119829
  if (typeof value === "string")
120475
- env[key] = value;
120476
- else if (typeof value === "number" || typeof value === "boolean")
120477
- env[key] = String(value);
119830
+ out[key] = value;
120478
119831
  }
120479
- return env;
119832
+ return out;
120480
119833
  }
120481
- function envOfSettingsFile(path) {
120482
- const text = readRegularFile(path);
120483
- if (text === null || text === "unreadable")
120484
- return text;
120485
- try {
120486
- const parsed = JSON.parse(text);
120487
- if (!isPlainObject8(parsed))
120488
- return "unreadable";
120489
- return envStringsOf(parsed) ?? "unreadable";
120490
- } catch {
119834
+ function pluginsDirFor(env, cwd) {
119835
+ const cache = env.CLAUDE_CODE_PLUGIN_CACHE_DIR;
119836
+ if (cache)
119837
+ return expandHome(cache, env, cwd);
119838
+ return join60(claudeCodeConfigDir(env, cwd), coworkMode(env) ? "cowork_plugins" : "plugins");
119839
+ }
119840
+ function userSettingsPath(env, cwd) {
119841
+ const name = coworkMode(env) ? "cowork_settings.json" : "settings.json";
119842
+ return join60(claudeCodeConfigDir(env, cwd), name);
119843
+ }
119844
+ function readSettingsFile(path) {
119845
+ const read = readBoundedJson(path, MAX_CONFIG_READ_BYTES);
119846
+ if (read === "missing" || read === "not_file")
119847
+ return {};
119848
+ if (typeof read === "string")
119849
+ return "unreadable";
119850
+ return isPlainObject8(read.value) ? read.value : "unreadable";
119851
+ }
119852
+ function readInstalledPlugins(dir) {
119853
+ const read = readBoundedJson(join60(dir, "installed_plugins.json"), MAX_CONFIG_READ_BYTES);
119854
+ if (read === "missing")
119855
+ return {};
119856
+ if (typeof read === "string")
120491
119857
  return "unreadable";
119858
+ const parsed = read.value;
119859
+ if (!isPlainObject8(parsed) || parsed.version !== 2 || !isPlainObject8(parsed.plugins)) {
119860
+ return "unreadable";
119861
+ }
119862
+ const plugins = {};
119863
+ for (const [id, rows] of Object.entries(parsed.plugins)) {
119864
+ if (!Array.isArray(rows))
119865
+ continue;
119866
+ plugins[id] = rows.flatMap((row) => {
119867
+ if (!isPlainObject8(row))
119868
+ return [];
119869
+ const { scope, projectPath, installPath, version } = row;
119870
+ if (typeof scope !== "string" || typeof installPath !== "string")
119871
+ return [];
119872
+ return [
119873
+ {
119874
+ scope,
119875
+ installPath,
119876
+ ...typeof projectPath === "string" ? { projectPath } : {},
119877
+ ...typeof version === "string" ? { version } : {}
119878
+ }
119879
+ ];
119880
+ });
120492
119881
  }
119882
+ return plugins;
120493
119883
  }
120494
- function projectAndLocalFiles(cwd, flags, sources) {
120495
- const root = lastFlagValue(flags, "--project-config-root");
120496
- const dirs = [cwd, ...root && root !== "missing" ? [resolve9(cwd, root)] : []];
120497
- const tiers = dirs.map((dir) => launchSettingsFilesByTier(dir, sources));
120498
- return [...tiers.flatMap((t) => t.project), ...tiers.flatMap((t) => t.local)];
119884
+ function mainCheckoutOf(dir) {
119885
+ const root = mainCheckoutRoot(dir, (path) => readFileSync46(path, "utf-8"), statPathKind);
119886
+ return root === undefined ? null : realOrResolved(root).normalize("NFC");
120499
119887
  }
120500
- function callerEffectiveEnv(launch, home) {
120501
- const { flags, cwd, hostEnv } = launch;
120502
- const restricted = passesBeforeEnd(flags, "--restricted") || claudeEnvTrue(hostEnv.CLAUDE_CODE_RESTRICTED);
120503
- const sources = restricted ? new Set : enabledSettingSources(flags);
120504
- const unreadable = (what) => ({
120505
- outcome: "caller_settings_unreadable",
120506
- line: `${what} cannot be read or parsed, so claudish cannot tell which launch mode its env block sets for the caller`
120507
- });
120508
- const layers = [];
120509
- if (sources === null || sources.has("user")) {
120510
- const file = userSettingsFile(hostEnv.CLAUDE_CONFIG_DIR, home, cwd);
120511
- const env = envOfSettingsFile(file);
120512
- if (env === "unreadable")
120513
- return unreadable(`the caller's user settings ${file}`);
120514
- if (env)
120515
- layers.push({ env, mayBeDropped: false });
120516
- }
120517
- for (const file of projectAndLocalFiles(cwd, flags, sources)) {
120518
- const env = envOfSettingsFile(file);
120519
- if (env === "unreadable")
120520
- return unreadable(`the caller's settings ${file}`);
120521
- if (env)
120522
- layers.push({ env, mayBeDropped: true });
120523
- }
120524
- if (launch.layer) {
120525
- const env = envStringsOf(launch.layer);
120526
- if (env === undefined)
120527
- return unreadable("the caller's own --settings");
120528
- layers.push({ env, mayBeDropped: false });
120529
- }
120530
- const passed = {};
120531
- for (const key of CALLER_LAUNCH_ENV_KEYS) {
120532
- let value = hostEnv[key];
120533
- if (!LAUNCH_ONLY_KEYS.includes(key)) {
120534
- for (const layer of layers)
120535
- if (!layer.mayBeDropped && key in layer.env)
120536
- value = layer.env[key];
120537
- }
120538
- if (value !== undefined)
120539
- passed[key] = value;
120540
- }
120541
- const valuesOf = (env, key) => Object.entries(env).filter(([k]) => k.toUpperCase() === key);
120542
- const mayBeOn = (key) => {
120543
- let possible = new Set([hostEnv[key]]);
120544
- for (const layer of layers) {
120545
- const set = valuesOf(layer.env, key).map(([, v]) => v);
120546
- if (set.length === 0)
120547
- continue;
120548
- possible = layer.mayBeDropped ? new Set([...possible, ...set]) : new Set(set);
120549
- }
120550
- return [...possible].some(claudeEnvTrue);
119888
+ function applicableInstall(rows, cwd) {
119889
+ const here = cwd.normalize("NFC");
119890
+ let ownCheckout;
119891
+ const checkoutOfCwd = () => {
119892
+ if (ownCheckout === undefined)
119893
+ ownCheckout = mainCheckoutOf(here);
119894
+ return ownCheckout;
120551
119895
  };
120552
- const everOn = (key) => claudeEnvTrue(hostEnv[key]) || layers.some((layer) => valuesOf(layer.env, key).some(([, v]) => claudeEnvTrue(v)));
120553
- const movesConfigDir = layers.some((layer) => valuesOf(layer.env, "CLAUDE_CONFIG_DIR").some(([, v]) => v !== hostEnv.CLAUDE_CONFIG_DIR));
120554
- const movesRestricted = layers.some((layer) => valuesOf(layer.env, "CLAUDE_CODE_RESTRICTED").some(([, v]) => claudeEnvTrue(v) !== restricted));
120555
- return { passed, mayBeOn, everOn, movesConfigDir, movesRestricted };
120556
- }
120557
- function childCoworkRefusal(input, childReal) {
120558
- const on = (env) => Object.entries(env ?? {}).some(([k, v]) => k.toUpperCase() === PROBE_COWORK_SWITCH && typeof v === "string" && claudeEnvTrue(v));
120559
- const sources = enabledSettingSources(input.childFlags);
120560
- const files = [
120561
- ...sources === null || sources.has("user") ? [userSettingsFile(input.env.CLAUDE_CONFIG_DIR, input.env.HOME ?? "", childReal)] : [],
120562
- ...projectAndLocalFiles(childReal, input.childFlags, sources)
120563
- ];
120564
- const layerEnv = isPlainObject8(input.layer?.env) ? envStringsOf(input.layer) : undefined;
120565
- const found = passes(input.childFlags, "--cowork") || on(input.env) || on(layerEnv) || files.some((file) => {
120566
- const env = envOfSettingsFile(file);
120567
- return env !== null && env !== "unreadable" && on(env);
119896
+ const applies = rows.filter((row) => {
119897
+ if (row.scope === "user" || row.scope === "managed")
119898
+ return true;
119899
+ if (!row.projectPath)
119900
+ return false;
119901
+ if (row.projectPath === here)
119902
+ return true;
119903
+ if (realOrResolved(row.projectPath).normalize("NFC") === here)
119904
+ return true;
119905
+ const checkout = checkoutOfCwd();
119906
+ return checkout !== null && mainCheckoutOf(row.projectPath) === checkout;
120568
119907
  });
120569
- return found ? coworkRefusal("the child's") : undefined;
119908
+ if (applies.length <= 1)
119909
+ return applies[0];
119910
+ return applies.find((row) => statPathKind(resolve9(here, row.installPath)) === "dir") ?? applies[0];
120570
119911
  }
120571
- function coworkRefusal(whose) {
120572
- return {
120573
- outcome: "caller_mode_unmodelled",
120574
- line: `${whose} launch selects cowork plugins mode (CLAUDE_CODE_USE_COWORK_PLUGINS or --cowork), whose cowork_plugins folder and cowork_settings.json claudish does not model`
120575
- };
119912
+ function enabledOf(layer) {
119913
+ return layer && isPlainObject8(layer.enabledPlugins) ? layer.enabledPlugins : {};
120576
119914
  }
120577
- function launchFlagRefusal(flags, whose) {
120578
- if (passes(flags, "--managed-settings")) {
120579
- return {
120580
- outcome: "managed_policy_present",
120581
- line: `${whose} launch passes --managed-settings, a managed policy source`
120582
- };
120583
- }
120584
- if (passes(flags, "--plugin-url")) {
120585
- return {
120586
- outcome: "plugin_url",
120587
- line: `${whose} launch passes --plugin-url, which the plugin probe never downloads, so it cannot tell which marketplace copies that plugin shadows`
120588
- };
120589
- }
120590
- const initialize = INITIALIZE_FLAGS.find((flag) => passes(flags, flag));
120591
- if (initialize !== undefined) {
120592
- return {
120593
- outcome: "await_initialize",
120594
- line: `${whose} launch passes ${initialize}, under which Claude Code reads settings, plugins or MCP servers from its stdin, which the plugin probe never sees`
120595
- };
119915
+ function managedEnabled(managed) {
119916
+ const word = new Map;
119917
+ for (const object of managed) {
119918
+ for (const [id, value] of Object.entries(enabledOf(object))) {
119919
+ if (value !== true)
119920
+ word.set(id, false);
119921
+ else if (!word.has(id))
119922
+ word.set(id, true);
119923
+ }
120596
119924
  }
120597
- return;
119925
+ return word;
120598
119926
  }
120599
- function managedPolicyRefusal(input, probes) {
120600
- if (input.policyPlatform !== "other") {
120601
- const where = input.policyPlatform === "windows" ? "Windows" : "WSL";
119927
+ function pluginsLoadedAt(launch) {
119928
+ const { cwd, env, flags } = launch;
119929
+ const restricted = passes(flags, "--restricted") || claudeEnvTrue(env.CLAUDE_CODE_RESTRICTED);
119930
+ const sources = restricted ? new Set : enabledSettingSources(flags);
119931
+ const loads = (tier) => sources === null || sources.has(tier);
119932
+ const files = [
119933
+ ...loads("user") ? [userSettingsPath(env, cwd)] : [],
119934
+ ...Object.values(launchSettingsFilesByTier(cwd, sources)).flat()
119935
+ ];
119936
+ let merged = {};
119937
+ let settingsEnv = {};
119938
+ const userFile = loads("user") ? userSettingsPath(env, cwd) : undefined;
119939
+ for (const file of files) {
119940
+ const layer = readSettingsFile(file);
119941
+ if (layer === "unreadable")
119942
+ return { ok: false, outcome: "settings_unreadable", file };
119943
+ merged = mergeSettingsLayers(merged, { enabledPlugins: enabledOf(layer) });
119944
+ if (file === userFile)
119945
+ settingsEnv = { ...settingsEnv, ...envBlockOf(layer) };
119946
+ }
119947
+ merged = mergeSettingsLayers(merged, { enabledPlugins: enabledOf(launch.layer) });
119948
+ settingsEnv = { ...settingsEnv, ...envBlockOf(launch.layer) };
119949
+ const enabled = new Map(Object.entries(enabledOf(merged)));
119950
+ for (const [id, on] of managedEnabled(launch.managed))
119951
+ enabled.set(id, on);
119952
+ const pluginEnv = { ...env, ...settingsEnv };
119953
+ const dir = pluginsDirFor(pluginEnv, cwd);
119954
+ const installed = readInstalledPlugins(dir);
119955
+ if (installed === "unreadable") {
120602
119956
  return {
120603
- outcome: "managed_policy_present",
120604
- line: `claudish does not read the managed policy on ${where}, so no plugin probe runs there`
119957
+ ok: false,
119958
+ outcome: "installed_plugins_unreadable",
119959
+ file: join60(dir, "installed_plugins.json")
120605
119960
  };
120606
119961
  }
120607
- let present;
120608
- for (const { cwd, env } of probes) {
120609
- present ??= managedPolicySourcePresent(input.managed, env, cwd);
120610
- }
120611
- if (present === undefined)
119962
+ const found = new Map;
119963
+ for (const [id, value] of enabled) {
119964
+ if (value !== true || !Object.hasOwn(installed, id))
119965
+ continue;
119966
+ const row = applicableInstall(installed[id] ?? [], cwd);
119967
+ if (row)
119968
+ found.set(id, { path: resolve9(cwd, row.installPath), version: row.version });
119969
+ }
119970
+ const inline = childInlineNames(flags, pluginEnv, cwd);
119971
+ const loaded = withoutUnmetDependencies(found, inline);
119972
+ return { ok: true, enabled, found, loaded, inline };
119973
+ }
119974
+ function marketplaceOf(id) {
119975
+ const at = id.lastIndexOf("@");
119976
+ return at > 0 ? id.slice(at + 1) : undefined;
119977
+ }
119978
+ function dependencyId(dependency, dependant) {
119979
+ if (marketplaceOf(dependency))
119980
+ return dependency;
119981
+ const market = marketplaceOf(dependant);
119982
+ if (!market || market === "inline")
119983
+ return dependency;
119984
+ return `${dependency}@${market}`;
119985
+ }
119986
+ function readManifest(path) {
119987
+ const read = readBoundedJson(join60(path, ".claude-plugin", "plugin.json"), MAX_CONFIG_READ_BYTES);
119988
+ if (typeof read === "string")
120612
119989
  return;
120613
- return {
120614
- outcome: "managed_policy_present",
120615
- line: `the managed policy source ${present} exists, and no plugin probe runs beside a managed policy`
120616
- };
119990
+ return isPlainObject8(read.value) ? read.value : undefined;
120617
119991
  }
120618
- function workDirRefusal(childReal, childFlags) {
120619
- const found = projectCommandSetting(childReal, childFlags, COMMAND_SETTINGS);
120620
- if (found === undefined)
120621
- return;
120622
- return {
120623
- outcome: "work_dir_command_setting",
120624
- line: found.key === undefined ? `${found.path} cannot be parsed, so claudish cannot tell whether it defines a command the work_dir probe would run` : `${found.path} sets ${found.key}, a command the work_dir probe would run without the trust dialog`
120625
- };
119992
+ function manifestDependencies(path) {
119993
+ const manifest = readManifest(path);
119994
+ if (!manifest || !Array.isArray(manifest.dependencies))
119995
+ return [];
119996
+ return manifest.dependencies.flatMap((entry) => {
119997
+ if (typeof entry === "string")
119998
+ return [{ name: entry }];
119999
+ if (isPlainObject8(entry) && typeof entry.name === "string") {
120000
+ return [
120001
+ typeof entry.version === "string" ? { name: entry.name, version: entry.version } : { name: entry.name }
120002
+ ];
120003
+ }
120004
+ return [];
120005
+ });
120626
120006
  }
120627
- function projectCommandSetting(cwd, flags, keys) {
120628
- const root = lastFlagValue(flags, "--project-config-root");
120629
- const dirs = [cwd, ...root && root !== "missing" ? [resolve9(cwd, root)] : []];
120630
- let found;
120631
- for (const dir of dirs)
120632
- found ??= commandSettingIn(launchSettingsFiles(dir), keys);
120633
- return found;
120007
+ function versionMeets(copy, range) {
120008
+ const version = copy.version ?? readManifest(copy.path)?.version;
120009
+ if (typeof version !== "string")
120010
+ return false;
120011
+ try {
120012
+ return Bun.semver.satisfies(version, range);
120013
+ } catch {
120014
+ return false;
120015
+ }
120634
120016
  }
120635
- function callerProjectRefusal(callerReal, flags) {
120636
- const found = projectCommandSetting(callerReal, flags, USER_STARTUP_HELPERS);
120637
- if (found === undefined)
120638
- return;
120639
- return {
120640
- outcome: "caller_command_setting",
120641
- line: found.key === undefined ? `${found.path} cannot be parsed, so claudish cannot tell whether the caller probe would run a helper from it` : `${found.path} sets ${found.key}, a helper the caller probe's boot can run before any model turn`
120017
+ function withoutUnmetDependencies(found, inline) {
120018
+ const loaded = new Map(found);
120019
+ const needs = new Map;
120020
+ for (const [id, copy] of found) {
120021
+ needs.set(id, manifestDependencies(copy.path).map((dep) => ({ ...dep, id: dependencyId(dep.name, id) })));
120022
+ }
120023
+ const met = (dep) => {
120024
+ const copy = loaded.get(dep.id);
120025
+ if (copy)
120026
+ return dep.version === undefined || versionMeets(copy, dep.version);
120027
+ return inline.has(pluginName(dep.id));
120642
120028
  };
120029
+ for (let changed = true;changed; ) {
120030
+ changed = false;
120031
+ for (const id of [...loaded.keys()]) {
120032
+ if ((needs.get(id) ?? []).every(met))
120033
+ continue;
120034
+ loaded.delete(id);
120035
+ changed = true;
120036
+ }
120037
+ }
120038
+ return loaded;
120643
120039
  }
120644
- function userSettingsRefusal(probes) {
120645
- const files = probes.flatMap(({ cwd, flags, env }) => {
120646
- const sources = enabledSettingSources(flags);
120647
- if (sources !== null && !sources.has("user"))
120648
- return [];
120649
- return [userSettingsFile(env.CLAUDE_CONFIG_DIR, env.HOME ?? "", cwd)];
120650
- });
120651
- const found = commandSettingIn([...new Set(files)], USER_STARTUP_HELPERS);
120652
- if (found === undefined)
120653
- return;
120654
- return {
120655
- outcome: "user_command_setting",
120656
- line: found.key === undefined ? `the user settings ${found.path} cannot be parsed, so claudish cannot tell whether a probe would run a helper from them` : `the user settings ${found.path} set ${found.key}, a helper a probe boot can run before any model turn`
120657
- };
120040
+ function inlinePluginName(dir) {
120041
+ const name = readManifest(dir)?.name;
120042
+ return typeof name === "string" ? name : basename9(dir).replace(/\.zip$/i, "");
120658
120043
  }
120659
- function lastFlagValue(flags, flag) {
120660
- let value;
120661
- for (let i = 0;i < flags.length; i++) {
120662
- const token = flags[i];
120663
- if (token === flag) {
120664
- value = flags[i + 1] ?? "missing";
120665
- i++;
120666
- } else if (token.startsWith(`${flag}=`)) {
120667
- value = token.slice(flag.length + 1);
120044
+ function pluginName(id) {
120045
+ const at = id.lastIndexOf("@");
120046
+ return at > 0 ? id.slice(0, at) : id;
120047
+ }
120048
+ function manifestNames(path, name) {
120049
+ return readManifest(path)?.name === name;
120050
+ }
120051
+ function childInlineNames(flags, env, cwd) {
120052
+ const dirs = [
120053
+ ...flagValues(flags, "--plugin-dir"),
120054
+ ...flagValues(flags, "--plugin-dir-no-mcp")
120055
+ ].map((dir) => expandHome(dir, env, cwd));
120056
+ const fromEnv = env.CLAUDE_CODE_PLUGIN_DIRS?.trim();
120057
+ if (fromEnv) {
120058
+ for (const dir of fromEnv.split(delimiter3)) {
120059
+ if (dir.trim())
120060
+ dirs.push(expandHome(dir.trim(), env, cwd));
120668
120061
  }
120669
120062
  }
120670
- return value;
120063
+ return new Set(dirs.map(inlinePluginName));
120671
120064
  }
120672
- function readCallerLaunch(input) {
120673
- const { setupReal } = input;
120674
- let launch;
120675
- try {
120676
- launch = input.readHostLaunch(input.hostPid);
120677
- } catch {
120678
- launch = null;
120065
+ function managedObjectsOf(input, cwds) {
120066
+ const unread = unreadRegistryPolicy(input.managed);
120067
+ if (unread !== undefined) {
120068
+ log(`[mcp-session] no plugin handed over: the policy key ${unread.key} ${unread.state === "present" ? "holds a Settings value, which claudish does not read" : "could not be queried"}`);
120069
+ return "registry_policy_unread";
120679
120070
  }
120680
- const flags = launch ? callerLaunchFlags(launch.argv) : null;
120681
- if (!launch || !flags) {
120682
- return {
120683
- outcome: "caller_argv_unreadable",
120684
- line: `the launch of the caller's process ${input.hostPid} cannot be read as a Claude Code argv, so the caller probe cannot be started with the caller's flags`
120685
- };
120686
- }
120687
- const refusal = launchFlagRefusal(flags, "the caller's");
120688
- if (refusal)
120689
- return refusal;
120690
- const hostEnv = launch.env;
120691
- if (!hostEnv) {
120692
- return {
120693
- outcome: "caller_env_unreadable",
120694
- line: `the launch environment of the caller's process ${input.hostPid} cannot be read, so the caller probe cannot be given the caller's CLAUDE_CONFIG_DIR, plugin variables and launch mode switches`
120695
- };
120071
+ const objects = [];
120072
+ const seen = new Set;
120073
+ for (const cwd of cwds) {
120074
+ const policy = readManagedPolicy(input.managed, input.env, cwd);
120075
+ const oversize = policy.oversize[0];
120076
+ if (oversize !== undefined) {
120077
+ log(`[mcp-session] no plugin handed over: ${oversize} is larger than claudish reads`);
120078
+ return "managed_settings_oversize";
120079
+ }
120080
+ const sideload = sideloadFlagsDisabledBy(policy);
120081
+ if (sideload !== undefined) {
120082
+ log(`[mcp-session] no plugin handed over: ${sideload} sets disableSideloadFlags, and Claude Code exits on --plugin-dir while it does`);
120083
+ return "sideload_flags_disabled";
120084
+ }
120085
+ for (const { path, value } of policy.objects) {
120086
+ if (seen.has(path))
120087
+ continue;
120088
+ seen.add(path);
120089
+ objects.push(value);
120090
+ }
120696
120091
  }
120697
- const settings = lastFlagValue(flags, "--settings");
120698
- let layer = null;
120699
- if (settings !== undefined) {
120092
+ for (const value of flagValues(input.childFlags, "--managed-settings")) {
120093
+ let parsed;
120700
120094
  try {
120701
- if (settings === "missing")
120702
- throw new Error("no value");
120703
- const inline = settings.trim().startsWith("{");
120704
- layer = readSettingsValue(inline ? settings : resolve9(launch.cwd, settings));
120095
+ parsed = JSON.parse(value);
120705
120096
  } catch {
120706
- return {
120707
- outcome: "caller_settings_unreadable",
120708
- line: "the caller's own --settings cannot be read or parsed, so claudish cannot tell which plugins it turns off"
120709
- };
120097
+ parsed = undefined;
120710
120098
  }
120099
+ if (!isPlainObject8(parsed)) {
120100
+ log("[mcp-session] no plugin handed over: the child's --managed-settings is not a JSON object");
120101
+ return "managed_settings_unreadable";
120102
+ }
120103
+ if (parsed.disableSideloadFlags === true) {
120104
+ log("[mcp-session] no plugin handed over: the child's --managed-settings sets disableSideloadFlags, and Claude Code exits on --plugin-dir while it does");
120105
+ return "sideload_flags_disabled";
120106
+ }
120107
+ objects.push(parsed);
120711
120108
  }
120712
- const effective = callerEffectiveEnv({ flags, cwd: launch.cwd, layer, hostEnv }, input.env.HOME ?? "");
120713
- if ("outcome" in effective)
120714
- return effective;
120715
- const unmodelled = callerModeRefusal(flags, effective);
120716
- if (unmodelled)
120717
- return unmodelled;
120718
- if (setupReal !== undefined && !sharesMainCheckout(setupReal, launch.cwd)) {
120719
- return {
120720
- outcome: "setup_from_not_caller",
120721
- line: "setup_from and the caller's launch directory do not share a main checkout, so a probe in setup_from would not load what the caller loads"
120722
- };
120109
+ const marketplaceKey = MARKETPLACE_RULE_KEYS.find((key) => objects.some((o) => o[key] !== undefined));
120110
+ if (marketplaceKey) {
120111
+ log(`[mcp-session] no plugin handed over: a managed ${marketplaceKey} applies, and a --plugin-dir copy is not held to it`);
120112
+ return "marketplace_policy";
120723
120113
  }
120724
- return { flags, cwd: launch.cwd, layer, hostEnv: effective.passed };
120114
+ return objects;
120725
120115
  }
120726
- function callerEnvOf(env, hostEnv) {
120727
- const out = { ...env };
120728
- for (const key of CALLER_LAUNCH_ENV_KEYS) {
120729
- const value = hostEnv[key];
120730
- if (value === undefined)
120731
- delete out[key];
120732
- else
120733
- out[key] = value;
120116
+ function childLaunchRefusal(input) {
120117
+ const flags = input.childFlags;
120118
+ if (passes(flags, "--plugin-url")) {
120119
+ log("[mcp-session] no plugin handed over: the child's flags pass --plugin-url");
120120
+ return "plugin_url";
120734
120121
  }
120735
- return out;
120736
- }
120737
- function refused(refusal) {
120738
- log(`[mcp-session] no plugin handed over: ${refusal.line}`);
120739
- return { plugins: [], outcome: refusal.outcome };
120740
- }
120741
- function pidAlive2(pid) {
120742
- try {
120743
- process.kill(pid, 0);
120744
- return true;
120745
- } catch (err) {
120746
- return err.code === "EPERM";
120122
+ const initialize = INITIALIZE_FLAGS.find((flag) => passes(flags, flag));
120123
+ if (initialize) {
120124
+ log(`[mcp-session] no plugin handed over: the child's flags pass ${initialize}`);
120125
+ return "initialize_flags";
120747
120126
  }
120748
- }
120749
- function sweepStaleProbeDirs(sweep = {}) {
120750
- const root = sweep.root ?? tmpdir3();
120751
- const now = sweep.now ?? Date.now();
120752
- const alive = sweep.alive ?? pidAlive2;
120753
- let names;
120754
- try {
120755
- names = readdirSync13(root);
120756
- } catch {
120757
- return;
120127
+ if (passes(flags, "--project-config-root")) {
120128
+ log("[mcp-session] no plugin handed over: the child's flags pass --project-config-root");
120129
+ return "project_config_root";
120758
120130
  }
120759
- const uid = process.getuid?.();
120760
- for (const name of names) {
120761
- const match = PROBE_DIR_NAME.exec(name);
120762
- if (!match)
120763
- continue;
120764
- const path = join60(root, name);
120765
- try {
120766
- const stat = lstatSync10(path);
120767
- if (!stat.isDirectory() || uid !== undefined && stat.uid !== uid)
120768
- continue;
120769
- const pid = match[1] === undefined ? undefined : Number(match[1]);
120770
- const ownerGone = pid !== undefined && pid > 0 && !alive(pid);
120771
- if (!ownerGone && now - stat.mtimeMs <= STALE_PROBE_DIR_MS)
120772
- continue;
120773
- rmSync15(path, { recursive: true, force: true });
120774
- } catch {}
120131
+ const safe = passes(flags, "--safe-mode") || claudeEnvTrue(input.env.CLAUDE_CODE_SAFE_MODE);
120132
+ const bare = passes(flags, "--bare") || claudeEnvTrue(input.env.CLAUDE_CODE_SIMPLE);
120133
+ if (safe || bare) {
120134
+ log(`[mcp-session] no plugin handed over: the child runs in ${safe ? "safe" : "bare"} mode, which loads no installed plugin`);
120135
+ return "plugins_off";
120775
120136
  }
120137
+ return;
120776
120138
  }
120777
- async function inheritedPluginsFor(input) {
120139
+ function refused(outcome) {
120140
+ return { plugins: [], outcome };
120141
+ }
120142
+ function inheritedPluginsFor(input) {
120778
120143
  const { setupReal } = input;
120779
120144
  if (!setupReal)
120780
120145
  return null;
120781
120146
  const childReal = realOrResolved(input.childCwd);
120782
120147
  if (sharesMainCheckout(setupReal, childReal))
120783
120148
  return null;
120784
- const early = launchFlagRefusal(input.childFlags, "the child's") ?? managedPolicyRefusal(input, [
120785
- { cwd: setupReal, env: input.env },
120786
- { cwd: childReal, env: input.env }
120787
- ]) ?? childCoworkRefusal(input, childReal);
120788
- const caller = early ?? readCallerLaunch(input);
120789
- if ("outcome" in caller)
120790
- return refused(caller);
120791
- const callerReal = realOrResolved(caller.cwd);
120792
- const callerEnv = callerEnvOf(input.env, caller.hostEnv);
120793
- const refusal = managedPolicyRefusal(input, [{ cwd: callerReal, env: callerEnv }]) ?? workDirRefusal(childReal, input.childFlags) ?? callerProjectRefusal(callerReal, caller.flags) ?? userSettingsRefusal([
120794
- { cwd: callerReal, flags: caller.flags, env: callerEnv },
120795
- { cwd: childReal, flags: input.childFlags, env: input.env }
120796
- ]);
120797
- if (refusal)
120798
- return refused(refusal);
120799
- const launch = caller;
120800
- const runner = input.runner ?? spawnPluginProbe;
120801
- const root = input.probeTmpRoot ?? tmpdir3();
120802
- sweepStaleProbeDirs({ root, ...input.pidAlive ? { alive: input.pidAlive } : {} });
120803
- let dir;
120804
- let results;
120805
- try {
120806
- dir = mkdtempSync4(join60(root, `${PROBE_DIR_PREFIX}${process.pid}-`));
120807
- const callerSettings = join60(dir, "caller-settings.json");
120808
- const childSettings = join60(dir, "child-settings.json");
120809
- writePrivateJson(callerSettings, pluginProbeSettings(launch.layer));
120810
- writePrivateJson(childSettings, pluginProbeSettings(input.layer));
120811
- const request = (cwd, args, env) => ({
120812
- cwd,
120813
- args,
120814
- env: pluginProbeEnv(env),
120815
- timeoutMs: input.timeoutMs ?? PLUGIN_PROBE_TIMEOUT_MS,
120816
- ...input.signal ? { signal: input.signal } : {}
120817
- });
120818
- const settled = await Promise.allSettled([
120819
- runner(request(callerReal, pluginProbeArgs(callerSettings, launch.flags, callerReal), callerEnv)),
120820
- runner(request(childReal, pluginProbeArgs(childSettings, input.childFlags, childReal), input.env))
120821
- ]);
120822
- results = settled.map((s) => s.status === "fulfilled" ? s.value : { ok: false, cause: "spawn_failed" });
120823
- } catch {
120824
- results = [{ ok: false, cause: "spawn_failed" }];
120825
- } finally {
120826
- if (dir)
120827
- rmSync15(dir, { recursive: true, force: true });
120828
- }
120829
- const [callerResult, childResult] = results;
120830
- const failed = results.find((r) => !r.ok);
120831
- if (failed || !callerResult?.ok || !childResult?.ok) {
120832
- const cause = failed?.cause ?? "spawn_failed";
120833
- log(`[mcp-session] no plugin handed over: the plugin probe failed (${cause})`);
120834
- return { plugins: [], outcome: cause };
120149
+ const early = childLaunchRefusal(input);
120150
+ if (early)
120151
+ return refused(early);
120152
+ const managed = managedObjectsOf(input, [setupReal, childReal]);
120153
+ if (typeof managed === "string")
120154
+ return refused(managed);
120155
+ const at = (cwd) => pluginsLoadedAt({ cwd, env: input.env, flags: input.childFlags, layer: input.layer, managed });
120156
+ const caller = at(setupReal);
120157
+ const child = caller.ok ? at(childReal) : caller;
120158
+ for (const side of [caller, child]) {
120159
+ if (!side.ok) {
120160
+ log(`[mcp-session] no plugin handed over: ${side.file} cannot be read`);
120161
+ return refused(side.outcome);
120162
+ }
120163
+ }
120164
+ if (!caller.ok || !child.ok)
120165
+ return refused("settings_unreadable");
120166
+ const { inline } = child;
120167
+ const seen = new Set;
120168
+ const plugins = [];
120169
+ for (const id of [...caller.loaded.keys()].sort()) {
120170
+ const copy = caller.loaded.get(id);
120171
+ const name = pluginName(id);
120172
+ if (child.found.get(id)?.path === copy.path || seen.has(copy.path))
120173
+ continue;
120174
+ if (child.enabled.has(id) && child.enabled.get(id) !== true) {
120175
+ log(`[mcp-session] plugin ${id} not handed over: the work_dir's own settings turn it off`);
120176
+ continue;
120177
+ }
120178
+ if (inline.has(name)) {
120179
+ log(`[mcp-session] plugin ${id} not handed over: the child loads ${name} from its own --plugin-dir`);
120180
+ continue;
120181
+ }
120182
+ if (statPathKind(copy.path) !== "dir") {
120183
+ log(`[mcp-session] plugin ${id} not handed over: its copy ${copy.path} does not exist`);
120184
+ continue;
120185
+ }
120186
+ if (!manifestNames(copy.path, name)) {
120187
+ log(`[mcp-session] plugin ${id} not handed over: its copy has no .claude-plugin/plugin.json naming it ${name}`);
120188
+ continue;
120189
+ }
120190
+ seen.add(copy.path);
120191
+ plugins.push({ id, version: copy.version, path: copy.path });
120835
120192
  }
120836
- const plugins = pluginsToHandOver(callerResult.plugins, childResult.plugins);
120837
- return { plugins: withoutLayerDisabled(plugins, input.layer), outcome: "ok" };
120193
+ return { plugins: survivingInTheChild(plugins, child.found, inline), outcome: "ok" };
120838
120194
  }
120839
- var PLUGIN_PROBE_TIMEOUT_MS = 1e4, PLUGIN_PROBE_BASE_URL = "http://127.0.0.1:9", PROBE_OUTPUT_MAX_BYTES, PROBE_REAP_MS = 2000, GROUP_POLL_MS = 20, QUIET_FLAGS, PLUGIN_PATH_FLAGS, INITIALIZE_FLAGS, PLUGIN_VALUE_FLAGS, PLUGIN_BOOLEAN_FLAGS, PROBE_PROVIDER_SWITCHES, PROVIDER_BASE_URLS, PROBE_STARTUP_HELPER_SWITCHES, PROBE_FIRST_PARTY_SWITCHES, PROBE_HOST_MANAGED_MARKER = "CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST", PROBE_HOST_HANDOFF_VARS, PROBE_SETTINGS_EMPTY_VARS, PROBE_PARENT_VARS, PROBE_SETTINGS_ENV, COMMAND_SETTINGS, USER_STARTUP_HELPERS, spawnPluginProbe, FLAGLESS_SUBCOMMANDS, LAUNCH_ONLY_KEYS, PROBE_DIR_PREFIX = "claudish-plugin-probe-", PROBE_DIR_NAME, STALE_PROBE_DIR_MS;
120840
- var init_plugin_probe = __esm(() => {
120195
+ function survivingInTheChild(candidates, childFound, inline) {
120196
+ const effective = new Map(childFound);
120197
+ for (const { id, path, version } of candidates)
120198
+ effective.set(id, { path, version });
120199
+ const loads = withoutUnmetDependencies(effective, inline);
120200
+ return candidates.filter(({ id }) => {
120201
+ if (loads.has(id))
120202
+ return true;
120203
+ log(`[mcp-session] plugin ${id} not handed over: a dependency it requires does not load in the child`);
120204
+ return false;
120205
+ });
120206
+ }
120207
+ var MAX_CONFIG_READ_BYTES, INITIALIZE_FLAGS, MARKETPLACE_RULE_KEYS;
120208
+ var init_plugin_handover = __esm(() => {
120209
+ init_claude_code_facts();
120841
120210
  init_claude_runner();
120842
120211
  init_logger();
120843
- init_pane_launch();
120212
+ init_bounded_read();
120844
120213
  init_inherited_settings();
120845
- init_probe_launch_vars();
120846
- PROBE_OUTPUT_MAX_BYTES = 32 * 1024 * 1024;
120847
- QUIET_FLAGS = [
120848
- "--output-format",
120849
- "stream-json",
120850
- "--verbose",
120851
- "--settings",
120852
- "<settings file>",
120853
- "--strict-mcp-config",
120854
- "--no-session-persistence"
120855
- ];
120856
- PLUGIN_PATH_FLAGS = ["--plugin-dir", "--plugin-dir-no-mcp", "--project-config-root"];
120214
+ MAX_CONFIG_READ_BYTES = 16 * 1024 * 1024;
120857
120215
  INITIALIZE_FLAGS = [
120858
120216
  "--await-initialize",
120859
120217
  "--initialize-fields",
120860
120218
  "--managed-settings-in-initialize"
120861
120219
  ];
120862
- PLUGIN_VALUE_FLAGS = ["--setting-sources"];
120863
- PLUGIN_BOOLEAN_FLAGS = ["--safe-mode", "--bare", "--restricted"];
120864
- PROBE_PROVIDER_SWITCHES = [
120865
- "CLAUDE_CODE_USE_BEDROCK",
120866
- "CLAUDE_CODE_USE_VERTEX",
120867
- "CLAUDE_CODE_USE_FOUNDRY",
120868
- "CLAUDE_CODE_USE_ANTHROPIC_AWS",
120869
- "CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD",
120870
- "CLAUDE_CODE_USE_MANTLE",
120871
- "CLAUDE_CODE_USE_GATEWAY"
120872
- ];
120873
- PROVIDER_BASE_URLS = [
120874
- "ANTHROPIC_BEDROCK_BASE_URL",
120875
- "ANTHROPIC_VERTEX_BASE_URL",
120876
- "ANTHROPIC_FOUNDRY_BASE_URL",
120877
- "ANTHROPIC_AWS_BASE_URL",
120878
- "ANTHROPIC_GOOGLE_CLOUD_BASE_URL",
120879
- "ANTHROPIC_BEDROCK_MANTLE_BASE_URL"
120880
- ];
120881
- PROBE_STARTUP_HELPER_SWITCHES = [
120882
- "CLAUDE_CODE_ENABLE_PROXY_AUTH_HELPER",
120883
- "CLAUDE_CODE_ENABLE_TELEMETRY"
120884
- ];
120885
- PROBE_FIRST_PARTY_SWITCHES = [
120886
- "_CLAUDE_CODE_ASSUME_FIRST_PARTY_BASE_URL",
120887
- "CLAUDE_CODE_CLIENT_DATA_URL"
120888
- ];
120889
- PROBE_HOST_HANDOFF_VARS = [
120890
- "CLAUDE_CODE_HOST_CREDS_FILE",
120891
- "CLAUDE_CODE_HOST_AUTH_ENV_VAR",
120892
- "CLAUDE_CODE_HOST_AUTH_ASK_AT_START",
120893
- "CLAUDE_CODE_HOST_AUTH_REFRESH_TIMEOUT_MS",
120894
- "CLAUDE_CODE_SDK_HAS_HOST_AUTH_REFRESH",
120895
- "CLAUDE_CODE_LAUNCHER_RUNS_API_KEY_HELPER",
120896
- "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
120897
- "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR",
120898
- "CLAUDE_CODE_GATEWAY_TOKEN_FILE_DESCRIPTOR",
120899
- "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR",
120900
- "CLAUDE_BG_AUTH_SNAPSHOT_PATH",
120901
- "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
120902
- "CLAUDE_CODE_SESSION_ACCESS_TOKEN",
120903
- "CLAUDE_SESSION_INGRESS_TOKEN_FILE"
120220
+ MARKETPLACE_RULE_KEYS = [
120221
+ "strictKnownMarketplaces",
120222
+ "allowedMarketplaces",
120223
+ "blockedMarketplaces"
120904
120224
  ];
120905
- PROBE_SETTINGS_EMPTY_VARS = [
120906
- "ANTHROPIC_API_KEY",
120907
- "ANTHROPIC_AUTH_TOKEN",
120908
- "CLAUDE_CODE_OAUTH_TOKEN",
120909
- ...PROBE_HOST_HANDOFF_VARS,
120910
- ...PROBE_PROVIDER_SWITCHES,
120911
- ...PROVIDER_BASE_URLS,
120912
- ...PROBE_STARTUP_HELPER_SWITCHES,
120913
- ...PROBE_FIRST_PARTY_SWITCHES,
120914
- PROBE_HOST_MANAGED_MARKER
120915
- ];
120916
- PROBE_PARENT_VARS = [
120917
- "PATH",
120918
- "HOME",
120919
- "USER",
120920
- "LOGNAME",
120921
- "SHELL",
120922
- "TMPDIR",
120923
- "LANG",
120924
- "TERM",
120925
- "XDG_CONFIG_HOME",
120926
- "XDG_DATA_HOME",
120927
- "XDG_CACHE_HOME",
120928
- "CLAUDE_CONFIG_DIR",
120929
- "CLAUDE_PATH",
120930
- ...PROBE_PLUGIN_VARS,
120931
- ...PROBE_MODE_VARS
120932
- ];
120933
- PROBE_SETTINGS_ENV = {
120934
- ANTHROPIC_BASE_URL: PLUGIN_PROBE_BASE_URL,
120935
- ...Object.fromEntries(PROBE_SETTINGS_EMPTY_VARS.map((key) => [key, ""])),
120936
- [PROBE_HOST_MANAGED_MARKER]: "1"
120937
- };
120938
- COMMAND_SETTINGS = [
120939
- "apiKeyHelper",
120940
- "awsAuthRefresh",
120941
- "awsCredentialExport",
120942
- "fileSuggestion",
120943
- "gcpAuthRefresh",
120944
- "otelHeadersHelper",
120945
- "processWrapper",
120946
- "policyHelpers",
120947
- "proxyAuthHelper",
120948
- "statusLine",
120949
- "subagentStatusLine"
120950
- ];
120951
- USER_STARTUP_HELPERS = [
120952
- "apiKeyHelper",
120953
- "awsAuthRefresh",
120954
- "awsCredentialExport",
120955
- "gcpAuthRefresh",
120956
- "otelHeadersHelper",
120957
- "policyHelpers",
120958
- "proxyAuthHelper"
120959
- ];
120960
- spawnPluginProbe = pluginProbeRunner(findClaudeBinary);
120961
- FLAGLESS_SUBCOMMANDS = ["bg-spare", "bg-pty-host", "daemon"];
120962
- LAUNCH_ONLY_KEYS = ["CLAUDE_CONFIG_DIR", "CLAUDE_CODE_RESTRICTED"];
120963
- PROBE_DIR_NAME = /^claudish-plugin-probe-(?:(\d{1,10})-)?[A-Za-z0-9]{6}$/;
120964
- STALE_PROBE_DIR_MS = 10 * 60000;
120965
120225
  });
120966
120226
 
120967
120227
  // src/mcp-session/scrollback-buffer.ts
@@ -121021,23 +120281,296 @@ var init_scrollback_buffer = __esm(() => {
121021
120281
  ANSI_RE3 = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\].*?\x07|\x1b[()][AB012]|\x1b[>=<]|\x0f|\x0e/g;
121022
120282
  });
121023
120283
 
120284
+ // src/mcp-session/work-dir-trust.ts
120285
+ import * as fs from "fs";
120286
+ import { homedir as homedir42 } from "os";
120287
+ import { basename as basename10, dirname as dirname24, join as join61 } from "path";
120288
+ function isPlainObject9(value) {
120289
+ return typeof value === "object" && value !== null && !Array.isArray(value);
120290
+ }
120291
+ function gitRootOf(dir) {
120292
+ let current = dir;
120293
+ for (;; ) {
120294
+ if (statPathKind(join61(current, ".git")) !== undefined)
120295
+ return current;
120296
+ const parent = dirname24(current);
120297
+ if (parent === current)
120298
+ return null;
120299
+ current = parent;
120300
+ }
120301
+ }
120302
+ function recordTrusts(config, key) {
120303
+ const projects = config.projects;
120304
+ if (!isPlainObject9(projects))
120305
+ return false;
120306
+ const entry = projects[key];
120307
+ return isPlainObject9(entry) && Boolean(entry.hasTrustDialogAccepted);
120308
+ }
120309
+ function trustedBy(config, real) {
120310
+ const here = real.normalize("NFC");
120311
+ const checkout = mainCheckoutRoot(here, (path) => readFileSync47(path, "utf-8"), statPathKind);
120312
+ if (checkout !== undefined) {
120313
+ const key = realOrResolved(checkout).normalize("NFC");
120314
+ if (recordTrusts(config, key))
120315
+ return key;
120316
+ }
120317
+ const stop = gitRootOf(here);
120318
+ let current = here;
120319
+ for (;; ) {
120320
+ if (recordTrusts(config, current))
120321
+ return current;
120322
+ if (current === stop)
120323
+ return null;
120324
+ const parent = dirname24(current);
120325
+ if (parent === current)
120326
+ return null;
120327
+ current = parent;
120328
+ }
120329
+ }
120330
+ function globalConfigFile(env, cwd) {
120331
+ const file = claudeCodeGlobalConfigPath(env, cwd);
120332
+ if (!env.CLAUDE_CODE_CUSTOM_OAUTH_URL)
120333
+ return file;
120334
+ return join61(dirname24(file), ".claude-custom-oauth.json");
120335
+ }
120336
+ function errorCode2(err) {
120337
+ return err?.code;
120338
+ }
120339
+ function siblingName(path, tag) {
120340
+ const unique = `${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
120341
+ return join61(dirname24(path), `.${basename10(path)}.claudish-${tag}-${unique}`);
120342
+ }
120343
+ function identityOf(path) {
120344
+ try {
120345
+ const { dev, ino, mtimeMs } = lstatSync9(path);
120346
+ return { dev, ino, mtimeMs };
120347
+ } catch {
120348
+ return;
120349
+ }
120350
+ }
120351
+ function sameLock(a, b) {
120352
+ return a !== undefined && b !== undefined && a.dev === b.dev && a.ino === b.ino && a.mtimeMs === b.mtimeMs;
120353
+ }
120354
+ async function takeConfigLock(lockPath, waitMs) {
120355
+ const deadline = Date.now() + waitMs;
120356
+ for (;; ) {
120357
+ try {
120358
+ mkdirSync27(lockPath);
120359
+ let mine = identityOf(lockPath);
120360
+ return {
120361
+ lease: () => {
120362
+ if (!sameLock(identityOf(lockPath), mine))
120363
+ return;
120364
+ const now = new Date;
120365
+ utimesSync(lockPath, now, now);
120366
+ mine = identityOf(lockPath);
120367
+ },
120368
+ release: () => {
120369
+ if (!sameLock(identityOf(lockPath), mine))
120370
+ return;
120371
+ try {
120372
+ rmdirSync3(lockPath);
120373
+ } catch {}
120374
+ }
120375
+ };
120376
+ } catch (err) {
120377
+ const code = errorCode2(err);
120378
+ if (code === "ENOENT" || code === "ENOTDIR")
120379
+ return "config_missing";
120380
+ if (code !== "EEXIST")
120381
+ return "config_unreadable";
120382
+ }
120383
+ if (Date.now() >= deadline)
120384
+ return "lock_busy";
120385
+ await Bun.sleep(25 + Math.floor(Math.random() * 50));
120386
+ }
120387
+ }
120388
+ function replaceFile(target, text, mode) {
120389
+ const temp = siblingName(target, "write");
120390
+ const bytes = Buffer.from(text, "utf-8");
120391
+ let fd;
120392
+ try {
120393
+ fd = openSync18(temp, "wx", mode);
120394
+ for (let written = 0;written < bytes.length; ) {
120395
+ const n = fs.writeSync(fd, bytes, written, bytes.length - written);
120396
+ if (n <= 0)
120397
+ throw new Error("short write");
120398
+ written += n;
120399
+ }
120400
+ fsyncSync4(fd);
120401
+ const open = fd;
120402
+ fd = undefined;
120403
+ closeSync18(open);
120404
+ chmodSync8(temp, mode);
120405
+ renameSync10(temp, target);
120406
+ return true;
120407
+ } catch {
120408
+ if (fd !== undefined) {
120409
+ try {
120410
+ closeSync18(fd);
120411
+ } catch {}
120412
+ }
120413
+ try {
120414
+ fs.unlinkSync(temp);
120415
+ } catch {}
120416
+ return false;
120417
+ }
120418
+ }
120419
+ function ignoresPersistedTrust(input) {
120420
+ return claudeEnvTrue(input.env.CLAUDE_CODE_IGNORE_PERSISTED_TRUST) || (input.childFlags ?? []).includes("--ignore-persisted-trust");
120421
+ }
120422
+ async function ensureWorkDirTrust(input) {
120423
+ let real = input.workDir;
120424
+ const done = (outcome, detail) => {
120425
+ try {
120426
+ log(`[mcp-session] work_dir trust ${outcome}: ${real} (${detail})`);
120427
+ } catch {}
120428
+ return outcome;
120429
+ };
120430
+ try {
120431
+ if (input.workDir.trim() === "")
120432
+ return done("not_a_directory", "work_dir is empty");
120433
+ real = realOrResolved(input.workDir).normalize("NFC");
120434
+ return await writeTrust(input, real, done);
120435
+ } catch {
120436
+ return done("write_failed", "an unexpected error; the file is as it was");
120437
+ }
120438
+ }
120439
+ async function writeTrust(input, real, done) {
120440
+ const { env } = input;
120441
+ const stopped = () => input.shouldStop?.() === true;
120442
+ if (stopped())
120443
+ return done("cancelled", "asked to stop before the write");
120444
+ if (claudeEnvTrue(env.CLAUDE_CODE_SANDBOXED)) {
120445
+ return done("sandboxed", "CLAUDE_CODE_SANDBOXED is on");
120446
+ }
120447
+ if (ignoresPersistedTrust(input)) {
120448
+ return done("ignored_trust", "the child reads no trust record");
120449
+ }
120450
+ if (statPathKind(real) !== "dir")
120451
+ return done("not_a_directory", "not an existing folder");
120452
+ if (real === dirname24(real))
120453
+ return done("filesystem_root", "never recorded");
120454
+ if (real === realOrResolved(env.HOME || homedir42()).normalize("NFC")) {
120455
+ return done("home_dir", "Claude Code keeps the home folder's trust for one session only");
120456
+ }
120457
+ const legacy = join61(claudeCodeConfigDir(env, real), ".config.json");
120458
+ if (statPathKind(legacy) !== undefined) {
120459
+ return done("legacy_config", `${legacy} exists, which Claude Code may read instead`);
120460
+ }
120461
+ const file = globalConfigFile(env, real);
120462
+ const lock = await takeConfigLock(`${file}.lock`, input.lockWaitMs ?? LOCK_WAIT_MS);
120463
+ if (lock === "lock_busy")
120464
+ return done("lock_busy", `${file}.lock is held or cannot be taken`);
120465
+ if (lock === "config_missing")
120466
+ return done("config_missing", `${dirname24(file)} does not exist`);
120467
+ if (lock === "config_unreadable") {
120468
+ return done("config_unreadable", `${file}.lock cannot be created`);
120469
+ }
120470
+ try {
120471
+ if (statPathKind(real) !== "dir") {
120472
+ return done("not_a_directory", "no longer an existing folder");
120473
+ }
120474
+ let target;
120475
+ try {
120476
+ target = realpathSync9(file);
120477
+ } catch (err) {
120478
+ if (errorCode2(err) === "ENOENT")
120479
+ return done("config_missing", `${file} does not exist`);
120480
+ return done("config_unreadable", `${file} cannot be read`);
120481
+ }
120482
+ const read = readBoundedText(target, input.maxConfigBytes ?? MAX_CONFIG_BYTES);
120483
+ if (read === "missing")
120484
+ return done("config_missing", `${file} does not exist`);
120485
+ if (read === "not_file")
120486
+ return done("config_unreadable", `${file} is not a regular file`);
120487
+ if (read === "oversize")
120488
+ return done("config_unreadable", `${file} is larger than claudish reads`);
120489
+ if (read === "unreadable")
120490
+ return done("config_unreadable", `${file} cannot be read`);
120491
+ const { text, mode } = read;
120492
+ let config;
120493
+ try {
120494
+ config = JSON.parse(text);
120495
+ } catch {
120496
+ return done("config_unreadable", `${file} is not valid JSON`);
120497
+ }
120498
+ if (!isPlainObject9(config))
120499
+ return done("config_not_object", `${file} is not a JSON object`);
120500
+ const projects = config.projects ?? {};
120501
+ if (!isPlainObject9(projects)) {
120502
+ return done("config_not_object", `${file} has a projects value that is not an object`);
120503
+ }
120504
+ const by = trustedBy(config, real);
120505
+ if (by !== null)
120506
+ return done("already_trusted", `by the record for ${by}`);
120507
+ const entry = projects[real];
120508
+ projects[real] = isPlainObject9(entry) ? { ...entry, hasTrustDialogAccepted: true } : { ...NEW_PROJECT_ENTRY };
120509
+ config.projects = projects;
120510
+ const next = `${JSON.stringify(config, null, 2)}
120511
+ `;
120512
+ if (stopped())
120513
+ return done("cancelled", "asked to stop before the write");
120514
+ lock.lease();
120515
+ if (!replaceFile(target, next, mode)) {
120516
+ return done("write_failed", `${file} could not be replaced`);
120517
+ }
120518
+ return done("written", `projects[${real}].hasTrustDialogAccepted in ${file}`);
120519
+ } finally {
120520
+ lock.release();
120521
+ }
120522
+ }
120523
+ var chmodSync8, closeSync18, fsyncSync4, lstatSync9, mkdirSync27, openSync18, readFileSync47, realpathSync9, renameSync10, rmdirSync3, utimesSync, NEW_PROJECT_ENTRY, LOCK_WAIT_MS = 3000, MAX_CONFIG_BYTES;
120524
+ var init_work_dir_trust = __esm(() => {
120525
+ init_claude_code_facts();
120526
+ init_claude_runner();
120527
+ init_logger();
120528
+ init_bounded_read();
120529
+ init_inherited_settings();
120530
+ init_plugin_handover();
120531
+ ({
120532
+ chmodSync: chmodSync8,
120533
+ closeSync: closeSync18,
120534
+ fsyncSync: fsyncSync4,
120535
+ lstatSync: lstatSync9,
120536
+ mkdirSync: mkdirSync27,
120537
+ openSync: openSync18,
120538
+ readFileSync: readFileSync47,
120539
+ realpathSync: realpathSync9,
120540
+ renameSync: renameSync10,
120541
+ rmdirSync: rmdirSync3,
120542
+ utimesSync
120543
+ } = fs);
120544
+ NEW_PROJECT_ENTRY = {
120545
+ allowedTools: [],
120546
+ mcpContextUris: [],
120547
+ mcpServers: {},
120548
+ enabledMcpjsonServers: [],
120549
+ disabledMcpjsonServers: [],
120550
+ hasTrustDialogAccepted: true,
120551
+ hasClaudeMdExternalIncludesApproved: false,
120552
+ hasClaudeMdExternalIncludesWarningShown: false
120553
+ };
120554
+ MAX_CONFIG_BYTES = 64 * 1024 * 1024;
120555
+ });
120556
+
121024
120557
  // src/mcp-session/session-manager.ts
121025
120558
  import { randomUUID as randomUUID9 } from "crypto";
121026
120559
  import {
121027
120560
  appendFileSync as appendFileSync7,
121028
- closeSync as closeSync18,
120561
+ closeSync as closeSync19,
121029
120562
  createWriteStream,
121030
120563
  existsSync as existsSync41,
121031
- mkdirSync as mkdirSync27,
121032
- openSync as openSync18,
120564
+ mkdirSync as mkdirSync28,
120565
+ openSync as openSync19,
121033
120566
  readFileSync as readFileSync48,
121034
- readSync as readSync8,
121035
- renameSync as renameSync10,
121036
- rmSync as rmSync16,
121037
- statSync as statSync25,
120567
+ readSync as readSync9,
120568
+ renameSync as renameSync11,
120569
+ rmSync as rmSync15,
120570
+ statSync as statSync24,
121038
120571
  writeFileSync as writeFileSync23
121039
120572
  } from "fs";
121040
- import { join as join61, resolve as resolve10, sep as sep3 } from "path";
120573
+ import { join as join62, resolve as resolve10, sep as sep3 } from "path";
121041
120574
  function normaliseTimeoutSeconds(raw) {
121042
120575
  const n = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : raw;
121043
120576
  if (typeof n !== "number" || !Number.isFinite(n))
@@ -121057,7 +120590,7 @@ function pluginRecordOf(handover) {
121057
120590
  const { plugins, outcome } = handover;
121058
120591
  return {
121059
120592
  ...plugins.length > 0 ? { inheritedPlugins: plugins.map(({ id, version }) => ({ id, version })) } : {},
121060
- pluginProbe: outcome
120593
+ pluginHandover: outcome
121061
120594
  };
121062
120595
  }
121063
120596
  function pluginDirFlags(handover) {
@@ -121065,9 +120598,9 @@ function pluginDirFlags(handover) {
121065
120598
  }
121066
120599
  function writeInheritedFiles(sessionDir, layer, mcp) {
121067
120600
  if (layer)
121068
- writePrivateJson(join61(sessionDir, INHERITED_SETTINGS), layer);
120601
+ writePrivateJson(join62(sessionDir, INHERITED_SETTINGS), layer);
121069
120602
  if (mcp)
121070
- writePrivateJson(join61(sessionDir, INHERITED_MCP), mcp);
120603
+ writePrivateJson(join62(sessionDir, INHERITED_MCP), mcp);
121071
120604
  }
121072
120605
  function sessionEventFor(snap) {
121073
120606
  switch (snap.state) {
@@ -121160,7 +120693,7 @@ function toMetaRecord(info, cwd) {
121160
120693
  function writeJsonAtomic(path, value) {
121161
120694
  const tmp = `${path}.tmp`;
121162
120695
  writeFileSync23(tmp, JSON.stringify(value, null, 2), "utf-8");
121163
- renameSync10(tmp, path);
120696
+ renameSync11(tmp, path);
121164
120697
  }
121165
120698
  function anomalyKey(a) {
121166
120699
  const at = a.lastIndexOf(" \xD7");
@@ -121169,21 +120702,21 @@ function anomalyKey(a) {
121169
120702
  function readTailText(path, maxBytes) {
121170
120703
  let fd = null;
121171
120704
  try {
121172
- const size = statSync25(path).size;
120705
+ const size = statSync24(path).size;
121173
120706
  if (size === 0)
121174
120707
  return { text: "", truncated: false };
121175
120708
  const start = Math.max(0, size - maxBytes);
121176
120709
  const length = size - start;
121177
120710
  const buf = Buffer.alloc(length);
121178
- fd = openSync18(path, "r");
121179
- readSync8(fd, buf, 0, length, start);
120711
+ fd = openSync19(path, "r");
120712
+ readSync9(fd, buf, 0, length, start);
121180
120713
  return { text: buf.toString("utf-8"), truncated: start > 0 };
121181
120714
  } catch {
121182
120715
  return null;
121183
120716
  } finally {
121184
120717
  if (fd !== null) {
121185
120718
  try {
121186
- closeSync18(fd);
120719
+ closeSync19(fd);
121187
120720
  } catch {}
121188
120721
  }
121189
120722
  }
@@ -121200,7 +120733,7 @@ function readTailLines2(path, maxBytes) {
121200
120733
  }
121201
120734
  function fileSize2(path) {
121202
120735
  try {
121203
- return statSync25(path).size;
120736
+ return statSync24(path).size;
121204
120737
  } catch {
121205
120738
  return 0;
121206
120739
  }
@@ -121235,7 +120768,7 @@ function dropLeadingFragment(tail) {
121235
120768
  return firstBreak === -1 ? tail.text : tail.text.slice(firstBreak + 1);
121236
120769
  }
121237
120770
  function diskAccounting(sessionDir) {
121238
- const stats = readTokenStatsAt(join61(sessionDir, "tokens.json"));
120771
+ const stats = readTokenStatsAt(join62(sessionDir, "tokens.json"));
121239
120772
  return {
121240
120773
  tokensIn: stats?.billed_input_tokens ?? null,
121241
120774
  tokensOut: stats?.output_tokens ?? null,
@@ -121295,7 +120828,6 @@ class SessionManager {
121295
120828
  paneTimings;
121296
120829
  starting = 0;
121297
120830
  pendingStarts = new Set;
121298
- startAbort = new AbortController;
121299
120831
  shuttingDown = false;
121300
120832
  _hostPid;
121301
120833
  _launcherPid;
@@ -121308,10 +120840,6 @@ class SessionManager {
121308
120840
  feed;
121309
120841
  claims;
121310
120842
  managedPaths;
121311
- pluginProbe;
121312
- pluginProbeTimeoutMs;
121313
- readHostLaunch;
121314
- pluginPolicyPlatform;
121315
120843
  constructor(options) {
121316
120844
  const host = options?.hostPid !== undefined ? { hostPid: options.hostPid } : hostPidFrom(process.env, process.ppid);
121317
120845
  this._hostPid = host.hostPid;
@@ -121329,10 +120857,6 @@ class SessionManager {
121329
120857
  this.feed = options?.feed;
121330
120858
  this.claims = options?.claims;
121331
120859
  this.managedPaths = options?.managedPaths ?? realManagedPaths();
121332
- this.pluginProbe = options?.pluginProbe;
121333
- this.pluginProbeTimeoutMs = options?.pluginProbeTimeoutMs;
121334
- this.readHostLaunch = options?.readHostLaunch ?? readHostLaunch;
121335
- this.pluginPolicyPlatform = options?.pluginPolicyPlatform;
121336
120860
  }
121337
120861
  hookEngine() {
121338
120862
  if (!this.hookEnginePromise)
@@ -121346,14 +120870,14 @@ class SessionManager {
121346
120870
  return this._launcherPid;
121347
120871
  }
121348
120872
  recordTeamRun(opts) {
121349
- mkdirSync27(this.sessionsDir, { recursive: true });
120873
+ mkdirSync28(this.sessionsDir, { recursive: true });
121350
120874
  let id = "";
121351
120875
  let dir = "";
121352
120876
  for (let attempt = 0;; attempt++) {
121353
120877
  id = `team-${randomUUID9().replace(/-/g, "").slice(0, 8)}`;
121354
- dir = join61(this.sessionsDir, id);
120878
+ dir = join62(this.sessionsDir, id);
121355
120879
  try {
121356
- mkdirSync27(dir);
120880
+ mkdirSync28(dir);
121357
120881
  break;
121358
120882
  } catch (err) {
121359
120883
  if (err?.code !== "EEXIST" || attempt >= 4)
@@ -121383,9 +120907,9 @@ class SessionManager {
121383
120907
  if (dir === null)
121384
120908
  throw new Error("not a record id");
121385
120909
  const completedAt = new Date().toISOString();
121386
- const startedAt = this.teamRunStarts.get(record) ?? metaString(readJsonObject(join61(dir, "spawn.json"), META_READ_LIMIT)?.startedAt) ?? completedAt;
120910
+ const startedAt = this.teamRunStarts.get(record) ?? metaString(readJsonObject(join62(dir, "spawn.json"), META_READ_LIMIT)?.startedAt) ?? completedAt;
121387
120911
  const elapsedMs = Date.parse(completedAt) - Date.parse(startedAt);
121388
- writeJsonAtomic(join61(dir, "meta.json"), {
120912
+ writeJsonAtomic(join62(dir, "meta.json"), {
121389
120913
  kind: "team",
121390
120914
  status: outcome.status,
121391
120915
  startedAt,
@@ -121417,7 +120941,7 @@ class SessionManager {
121417
120941
  startedAt,
121418
120942
  ...rest
121419
120943
  };
121420
- writeJsonAtomic(join61(dir, "spawn.json"), body);
120944
+ writeJsonAtomic(join62(dir, "spawn.json"), body);
121421
120945
  }
121422
120946
  refuseWhileShuttingDown() {
121423
120947
  if (this.shuttingDown)
@@ -121445,6 +120969,14 @@ class SessionManager {
121445
120969
  }
121446
120970
  const parentEnv = opts.parentEnv ?? this.parentEnv;
121447
120971
  const childCwd = opts.cwd ?? process.cwd();
120972
+ const plugins = inheritedPluginsFor({
120973
+ setupReal,
120974
+ childCwd,
120975
+ layer: inherited.layer,
120976
+ childFlags: callerFlags,
120977
+ env: parentEnv,
120978
+ managed: this.managedPaths
120979
+ });
121448
120980
  const inheritedMcp = inheritedMcpFor(setupReal, childCwd, inherited.layer, callerFlags, parentEnv, this.managedPaths);
121449
120981
  this.starting++;
121450
120982
  let counted = true;
@@ -121453,7 +120985,6 @@ class SessionManager {
121453
120985
  this.starting--;
121454
120986
  counted = false;
121455
120987
  };
121456
- const { signal } = this.startAbort;
121457
120988
  let releaseStart = () => {};
121458
120989
  const tracked = new Promise((done) => {
121459
120990
  releaseStart = done;
@@ -121462,35 +120993,27 @@ class SessionManager {
121462
120993
  try {
121463
120994
  await assertMagmuxAvailable(this.magmuxBinary);
121464
120995
  this.refuseWhileShuttingDown();
121465
- const plugins = await inheritedPluginsFor({
121466
- setupReal,
121467
- childCwd,
121468
- layer: inherited.layer,
121469
- childFlags: callerFlags,
121470
- env: parentEnv,
121471
- managed: this.managedPaths,
121472
- hostPid: this._hostPid,
121473
- readHostLaunch: this.readHostLaunch,
121474
- policyPlatform: this.pluginPolicyPlatform ?? hostPolicyPlatform(parentEnv),
121475
- runner: this.pluginProbe,
121476
- timeoutMs: this.pluginProbeTimeoutMs,
121477
- signal
121478
- });
121479
- this.refuseWhileShuttingDown();
121480
120996
  reservePanes(1, sockRootFor(parentEnv));
121481
120997
  let entry;
121482
120998
  try {
121483
- entry = this.recordSession(opts, inherited.layer, inheritedMcp, plugins);
120999
+ const workDirTrust = opts.cwd !== undefined ? await ensureWorkDirTrust({
121000
+ workDir: opts.cwd,
121001
+ env: parentEnv,
121002
+ childFlags: callerFlags,
121003
+ shouldStop: () => this.shuttingDown
121004
+ }) : undefined;
121005
+ this.refuseWhileShuttingDown();
121006
+ entry = this.recordSession(opts, inherited.layer, inheritedMcp, plugins, workDirTrust);
121484
121007
  } catch (err) {
121485
121008
  releasePaneReservations(1);
121486
121009
  throw err;
121487
121010
  }
121488
121011
  if (inherited.layer) {
121489
- flags = [...inherited.restFlags, "--settings", join61(entry.sessionDir, INHERITED_SETTINGS)];
121012
+ flags = [...inherited.restFlags, "--settings", join62(entry.sessionDir, INHERITED_SETTINGS)];
121490
121013
  }
121491
121014
  flags = [...pluginDirFlags(plugins), ...flags];
121492
121015
  if (inheritedMcp)
121493
- flags = ["--mcp-config", join61(entry.sessionDir, INHERITED_MCP), ...flags];
121016
+ flags = ["--mcp-config", join62(entry.sessionDir, INHERITED_MCP), ...flags];
121494
121017
  this.sessions.set(entry.info.sessionId, entry);
121495
121018
  uncount();
121496
121019
  await this.startPane(entry, opts, { flags, readAvailable, parentEnv });
@@ -121501,16 +121024,16 @@ class SessionManager {
121501
121024
  uncount();
121502
121025
  }
121503
121026
  }
121504
- recordSession(opts, inheritedLayer, inheritedMcp, plugins) {
121027
+ recordSession(opts, inheritedLayer, inheritedMcp, plugins, workDirTrust) {
121505
121028
  const sessionId = opts.sessionId ?? randomUUID9().slice(0, 8);
121506
121029
  const claudeSessionId = randomUUID9();
121507
121030
  const timeout = normaliseTimeoutSeconds(opts.timeoutSeconds);
121508
121031
  const agentRequested = requestedAgentOf(opts.claudishFlags ?? []);
121509
121032
  const startedAt = new Date().toISOString();
121510
- const sessionDir = opts.sessionDir ?? join61(this.sessionsDir, sessionId);
121511
- mkdirSync27(sessionDir, { recursive: true });
121033
+ const sessionDir = opts.sessionDir ?? join62(this.sessionsDir, sessionId);
121034
+ mkdirSync28(sessionDir, { recursive: true });
121512
121035
  if (opts.prompt)
121513
- writeFileSync23(join61(sessionDir, "prompt.md"), opts.prompt, "utf-8");
121036
+ writeFileSync23(join62(sessionDir, "prompt.md"), opts.prompt, "utf-8");
121514
121037
  this.writeSpawnRecord(sessionDir, {
121515
121038
  kind: "session",
121516
121039
  sessionId,
@@ -121522,6 +121045,7 @@ class SessionManager {
121522
121045
  ...opts.setupFrom ? { setupFrom: opts.setupFrom } : {},
121523
121046
  inheritedMcpServers: inheritedMcp ? Object.keys(inheritedMcp.mcpServers) : undefined,
121524
121047
  ...pluginRecordOf(plugins),
121048
+ ...workDirTrust ? { workDirTrust } : {},
121525
121049
  ...agentRequested ? { agentRequested } : {},
121526
121050
  taskType: opts.taskType
121527
121051
  });
@@ -121529,7 +121053,7 @@ class SessionManager {
121529
121053
  const cwd = opts.cwd ?? process.cwd();
121530
121054
  const parentEnv = opts.parentEnv ?? this.parentEnv;
121531
121055
  const spawnModel = opts.spawnModel ?? null;
121532
- const tokenFile = opts.tokenFile ?? join61(sessionDir, "tokens.json");
121056
+ const tokenFile = opts.tokenFile ?? join62(sessionDir, "tokens.json");
121533
121057
  return {
121534
121058
  info: {
121535
121059
  sessionId,
@@ -121568,18 +121092,18 @@ class SessionManager {
121568
121092
  },
121569
121093
  session: null,
121570
121094
  scrollback: new ScrollbackBuffer(this.scrollbackCapacity),
121571
- outputLogStream: createWriteStream(join61(sessionDir, "output.log")),
121095
+ outputLogStream: createWriteStream(join62(sessionDir, "output.log")),
121572
121096
  sessionDir,
121573
121097
  cwd,
121574
121098
  tokenFile,
121575
- eventLogPath: join61(sessionDir, "events.jsonl"),
121099
+ eventLogPath: join62(sessionDir, "events.jsonl"),
121576
121100
  eventLogBytes: 0,
121577
- upstreamErrorLogPath: join61(sessionDir, "upstream-errors.jsonl"),
121101
+ upstreamErrorLogPath: join62(sessionDir, "upstream-errors.jsonl"),
121578
121102
  eventRing: [],
121579
121103
  proseBytes: 0,
121580
121104
  answeredTurns: new Map,
121581
121105
  inboxPath: null,
121582
- waitLogPath: join61(sessionDir, "waits.jsonl"),
121106
+ waitLogPath: join62(sessionDir, "waits.jsonl"),
121583
121107
  waitLogBytes: 0,
121584
121108
  waitSince: null,
121585
121109
  ended: false,
@@ -121687,7 +121211,7 @@ class SessionManager {
121687
121211
  if (!entry.inboxPath)
121688
121212
  return;
121689
121213
  try {
121690
- rmSync16(entry.inboxPath, { force: true });
121214
+ rmSync15(entry.inboxPath, { force: true });
121691
121215
  } catch {}
121692
121216
  }
121693
121217
  failNeverSpawned(entry, err) {
@@ -121791,7 +121315,7 @@ class SessionManager {
121791
121315
  try {
121792
121316
  const text = screenLines.join(`
121793
121317
  `).replace(/\s+$/, "");
121794
- writeFileSync23(join61(entry.sessionDir, "screen.txt"), `${redactSecrets(text)}
121318
+ writeFileSync23(join62(entry.sessionDir, "screen.txt"), `${redactSecrets(text)}
121795
121319
  `, "utf-8");
121796
121320
  } catch {}
121797
121321
  }
@@ -121805,7 +121329,7 @@ class SessionManager {
121805
121329
  entry.waitSince = null;
121806
121330
  }
121807
121331
  try {
121808
- writeJsonAtomic(join61(entry.sessionDir, "meta.json"), toMetaRecord(entry.info, entry.cwd));
121332
+ writeJsonAtomic(join62(entry.sessionDir, "meta.json"), toMetaRecord(entry.info, entry.cwd));
121809
121333
  } catch (err) {
121810
121334
  process.stderr.write(`[claudish] session ${entry.info.sessionId}: could not write meta.json: ` + `${err instanceof Error ? err.message : String(err)}
121811
121335
  `);
@@ -122070,13 +121594,13 @@ class SessionManager {
122070
121594
  if (sessionDir === null)
122071
121595
  return null;
122072
121596
  try {
122073
- if (!statSync25(sessionDir).isDirectory())
121597
+ if (!statSync24(sessionDir).isDirectory())
122074
121598
  return null;
122075
121599
  } catch {
122076
121600
  return null;
122077
121601
  }
122078
- const spawnPath = join61(sessionDir, "spawn.json");
122079
- const metaPath = join61(sessionDir, "meta.json");
121602
+ const spawnPath = join62(sessionDir, "spawn.json");
121603
+ const metaPath = join62(sessionDir, "meta.json");
122080
121604
  const spawnRecord = readJsonObject(spawnPath, META_READ_LIMIT);
122081
121605
  if (spawnRecord?.kind === "team")
122082
121606
  return null;
@@ -122167,11 +121691,10 @@ class SessionManager {
122167
121691
  if (!record)
122168
121692
  return null;
122169
121693
  const info = record.info;
122170
- return sessionRowOf(info, upstreamRecordsFor(info, join61(record.sessionDir, "upstream-errors.jsonl")));
121694
+ return sessionRowOf(info, upstreamRecordsFor(info, join62(record.sessionDir, "upstream-errors.jsonl")));
122171
121695
  }
122172
121696
  async shutdownAll() {
122173
121697
  this.shuttingDown = true;
122174
- this.startAbort.abort();
122175
121698
  await Promise.all([...this.pendingStarts]);
122176
121699
  const pending = [];
122177
121700
  for (const entry of this.sessions.values()) {
@@ -122200,7 +121723,7 @@ class SessionManager {
122200
121723
  return null;
122201
121724
  const root = resolve10(this.sessionsDir);
122202
121725
  const dir = resolve10(root, sessionId);
122203
- if (dir !== join61(root, sessionId))
121726
+ if (dir !== join62(root, sessionId))
122204
121727
  return null;
122205
121728
  if (!dir.startsWith(root + sep3))
122206
121729
  return null;
@@ -122212,17 +121735,17 @@ class SessionManager {
122212
121735
  return null;
122213
121736
  let dirMtimeMs;
122214
121737
  try {
122215
- const stat = statSync25(sessionDir);
121738
+ const stat = statSync24(sessionDir);
122216
121739
  if (!stat.isDirectory())
122217
121740
  return null;
122218
121741
  dirMtimeMs = stat.mtimeMs;
122219
121742
  } catch {
122220
121743
  return null;
122221
121744
  }
122222
- const spawnRecord = readJsonObject(join61(sessionDir, "spawn.json"), META_READ_LIMIT);
121745
+ const spawnRecord = readJsonObject(join62(sessionDir, "spawn.json"), META_READ_LIMIT);
122223
121746
  if (spawnRecord?.kind === "team")
122224
121747
  return null;
122225
- const meta = readJsonObject(join61(sessionDir, "meta.json"), META_READ_LIMIT);
121748
+ const meta = readJsonObject(join62(sessionDir, "meta.json"), META_READ_LIMIT);
122226
121749
  if (meta?.kind === "team")
122227
121750
  return null;
122228
121751
  const partial = meta === null;
@@ -122244,7 +121767,7 @@ class SessionManager {
122244
121767
  return stored;
122245
121768
  }
122246
121769
  diskOutput(record, tailLines) {
122247
- const tail = readTailText(join61(record.sessionDir, "output.log"), OUTPUT_TAIL_BYTES);
121770
+ const tail = readTailText(join62(record.sessionDir, "output.log"), OUTPUT_TAIL_BYTES);
122248
121771
  const buffer = new ScrollbackBuffer(this.scrollbackCapacity);
122249
121772
  if (tail?.text)
122250
121773
  buffer.append(dropLeadingFragment(tail));
@@ -122264,12 +121787,12 @@ class SessionManager {
122264
121787
  }
122265
121788
  diskDiagnostics(record, limit) {
122266
121789
  const { sessionDir, info } = record;
122267
- const eventLogPath = join61(sessionDir, "events.jsonl");
122268
- const upstreamErrorLogPath = join61(sessionDir, "upstream-errors.jsonl");
122269
- const outputLogPath = join61(sessionDir, "output.log");
121790
+ const eventLogPath = join62(sessionDir, "events.jsonl");
121791
+ const upstreamErrorLogPath = join62(sessionDir, "upstream-errors.jsonl");
121792
+ const outputLogPath = join62(sessionDir, "output.log");
122270
121793
  const events = readTailLines2(eventLogPath, EVENT_TAIL_BYTES);
122271
121794
  const outputTail = readTailText(outputLogPath, OUTPUT_TAIL_BYTES);
122272
- const screen = readTailText(join61(sessionDir, "screen.txt"), SCREEN_READ_BYTES);
121795
+ const screen = readTailText(join62(sessionDir, "screen.txt"), SCREEN_READ_BYTES);
122273
121796
  return {
122274
121797
  sessionId: info.sessionId,
122275
121798
  state: info.state,
@@ -122541,11 +122064,11 @@ var init_session_manager = __esm(() => {
122541
122064
  init_token_watch();
122542
122065
  init_view_claims();
122543
122066
  init_home_dir();
122544
- init_host_launch();
122545
122067
  init_inherited_settings();
122546
122068
  init_parent_session();
122547
- init_plugin_probe();
122069
+ init_plugin_handover();
122548
122070
  init_scrollback_buffer();
122071
+ init_work_dir_trust();
122549
122072
  TERMINAL_RETENTION_MS = 30 * 60000;
122550
122073
  EVENT_LOG_LIMIT = 4 * 1024 * 1024;
122551
122074
  WAIT_LOG_LIMIT = 1024 * 1024;
@@ -122577,8 +122100,8 @@ var init_session_manager = __esm(() => {
122577
122100
  });
122578
122101
 
122579
122102
  // src/view/history.ts
122580
- import { closeSync as closeSync19, openSync as openSync19, readSync as readSync9, readdirSync as readdirSync14, statSync as statSync26 } from "fs";
122581
- import { join as join62 } from "path";
122103
+ import { closeSync as closeSync20, openSync as openSync20, readSync as readSync10, readdirSync as readdirSync13, statSync as statSync25 } from "fs";
122104
+ import { join as join63 } from "path";
122582
122105
  function finishedDetail(promptSummary) {
122583
122106
  return {
122584
122107
  prompt_summary: promptSummary,
@@ -122599,28 +122122,28 @@ function readJson(path) {
122599
122122
  function readHead(path, bytes) {
122600
122123
  let fd = null;
122601
122124
  try {
122602
- fd = openSync19(path, "r");
122125
+ fd = openSync20(path, "r");
122603
122126
  const buf = Buffer.alloc(bytes);
122604
- const n = readSync9(fd, buf, 0, bytes, 0);
122127
+ const n = readSync10(fd, buf, 0, bytes, 0);
122605
122128
  return buf.subarray(0, n).toString("utf8");
122606
122129
  } catch {
122607
122130
  return null;
122608
122131
  } finally {
122609
122132
  if (fd !== null)
122610
- closeSync19(fd);
122133
+ closeSync20(fd);
122611
122134
  }
122612
122135
  }
122613
122136
  function runDirs(sessionsDir) {
122614
122137
  let names;
122615
122138
  try {
122616
- names = readdirSync14(sessionsDir);
122139
+ names = readdirSync13(sessionsDir);
122617
122140
  } catch {
122618
122141
  return [];
122619
122142
  }
122620
122143
  const dated = [];
122621
122144
  for (const name of names) {
122622
122145
  try {
122623
- const st = statSync26(join62(sessionsDir, name));
122146
+ const st = statSync25(join63(sessionsDir, name));
122624
122147
  if (st.isDirectory())
122625
122148
  dated.push({ name, mtimeMs: st.mtimeMs });
122626
122149
  } catch {}
@@ -122657,7 +122180,7 @@ function teamItems(spawn) {
122657
122180
  return { runId: run.run_id, items };
122658
122181
  }
122659
122182
  function runItems(sessions, dir, name, seenRuns) {
122660
- const spawn = readJson(join62(dir, "spawn.json"));
122183
+ const spawn = readJson(join63(dir, "spawn.json"));
122661
122184
  if (spawn?.kind === "team" || name.startsWith("team-")) {
122662
122185
  const team = spawn ? teamItems(spawn) : null;
122663
122186
  if (!team || seenRuns.has(team.runId) || team.items.length === 0)
@@ -122665,12 +122188,12 @@ function runItems(sessions, dir, name, seenRuns) {
122665
122188
  seenRuns.add(team.runId);
122666
122189
  return team.items;
122667
122190
  }
122668
- if (!spawn && readJson(join62(dir, "meta.json")) === null)
122191
+ if (!spawn && readJson(join63(dir, "meta.json")) === null)
122669
122192
  return null;
122670
122193
  const row = sessions.diskSessionRow(name);
122671
122194
  if (!row)
122672
122195
  return null;
122673
- const prompt = readHead(join62(dir, "prompt.md"), PROMPT_HEAD_BYTES);
122196
+ const prompt = readHead(join63(dir, "prompt.md"), PROMPT_HEAD_BYTES);
122674
122197
  return [sessionItem(row, prompt ? promptSummaryOf(prompt) : null)];
122675
122198
  }
122676
122199
  function readHistory(o = {}) {
@@ -122683,7 +122206,7 @@ function readHistory(o = {}) {
122683
122206
  for (const name of runDirs(sessionsDir)) {
122684
122207
  if (runs >= limit)
122685
122208
  break;
122686
- const items = runItems(sessions, join62(sessionsDir, name), name, seenRuns);
122209
+ const items = runItems(sessions, join63(sessionsDir, name), name, seenRuns);
122687
122210
  if (!items)
122688
122211
  continue;
122689
122212
  out.push(...items);
@@ -122698,15 +122221,15 @@ function findRecordedItem(target, o = {}) {
122698
122221
  const id = target.slice(2);
122699
122222
  if (!id || id.includes("/") || id.startsWith("."))
122700
122223
  return null;
122701
- const items = runItems(sessions, join62(sessionsDir, id), id, new Set);
122224
+ const items = runItems(sessions, join63(sessionsDir, id), id, new Set);
122702
122225
  return items?.find((i) => i.target === target) ?? null;
122703
122226
  }
122704
122227
  if (!target.startsWith("t:"))
122705
122228
  return null;
122706
122229
  const seenRuns = new Set;
122707
122230
  for (const name of runDirs(sessionsDir)) {
122708
- const dir = join62(sessionsDir, name);
122709
- if (!name.startsWith("team-") && readJson(join62(dir, "spawn.json"))?.kind !== "team")
122231
+ const dir = join63(sessionsDir, name);
122232
+ if (!name.startsWith("team-") && readJson(join63(dir, "spawn.json"))?.kind !== "team")
122710
122233
  continue;
122711
122234
  const found = runItems(sessions, dir, name, seenRuns)?.find((i) => i.target === target);
122712
122235
  if (found)
@@ -122758,7 +122281,7 @@ class LineBuffer {
122758
122281
 
122759
122282
  // src/view/view-client.ts
122760
122283
  import { connect } from "net";
122761
- import { basename as basename10 } from "path";
122284
+ import { basename as basename11 } from "path";
122762
122285
  function dial(path) {
122763
122286
  return new Promise((resolve, reject) => {
122764
122287
  const sock = connect(path);
@@ -122908,7 +122431,7 @@ class ViewClient {
122908
122431
  }
122909
122432
  async redial() {
122910
122433
  let wait = RECONNECT_FIRST_MS;
122911
- const name = basename10(this.path);
122434
+ const name = basename11(this.path);
122912
122435
  while (!this.ended) {
122913
122436
  if (!endpointOwnerAlive(name, await readProcessTableAsync())) {
122914
122437
  this.end("server_gone");
@@ -122957,10 +122480,10 @@ var init_view_client = __esm(() => {
122957
122480
  });
122958
122481
 
122959
122482
  // src/view/feed-relay.ts
122960
- import { chmodSync as chmodSync8, readFileSync as readFileSync49, renameSync as renameSync11, rmSync as rmSync17, writeFileSync as writeFileSync24 } from "fs";
122961
- import { dirname as dirname24, join as join63 } from "path";
122483
+ import { chmodSync as chmodSync9, readFileSync as readFileSync49, renameSync as renameSync12, rmSync as rmSync16, writeFileSync as writeFileSync24 } from "fs";
122484
+ import { dirname as dirname25, join as join64 } from "path";
122962
122485
  function defaultFeedPath(root) {
122963
- return join63(root, FEED_DIR, FEED_FILE);
122486
+ return join64(root, FEED_DIR, FEED_FILE);
122964
122487
  }
122965
122488
  function ownStamp() {
122966
122489
  return {
@@ -123028,7 +122551,7 @@ class FeedRelay {
123028
122551
  }
123029
122552
  async start() {
123030
122553
  ensureSockRoot(this.o.root);
123031
- if (dirname24(this.path) === join63(this.o.root, FEED_DIR))
122554
+ if (dirname25(this.path) === join64(this.o.root, FEED_DIR))
123032
122555
  ensurePrivateSubdir(this.o.root, FEED_DIR);
123033
122556
  const other = readFeedStamp(this.path);
123034
122557
  if (other && !this.isOwn(other) && stampAlive(other, await readProcessTableAsync()))
@@ -123055,10 +122578,10 @@ class FeedRelay {
123055
122578
  for (const s of this.servers.values())
123056
122579
  s.conn.close();
123057
122580
  this.servers.clear();
123058
- rmSync17(this.tmpPath(), { force: true });
122581
+ rmSync16(this.tmpPath(), { force: true });
123059
122582
  const stamp = readFeedStamp(this.path);
123060
122583
  if (stamp && this.isOwn(stamp))
123061
- rmSync17(this.path, { force: true });
122584
+ rmSync16(this.path, { force: true });
123062
122585
  }
123063
122586
  nextWrite() {
123064
122587
  return new Promise((resolve) => {
@@ -123231,8 +122754,8 @@ class FeedRelay {
123231
122754
  const tmp = this.tmpPath();
123232
122755
  writeFileSync24(tmp, `${JSON.stringify(file)}
123233
122756
  `, { mode: 384 });
123234
- chmodSync8(tmp, 384);
123235
- renameSync11(tmp, this.path);
122757
+ chmodSync9(tmp, 384);
122758
+ renameSync12(tmp, this.path);
123236
122759
  this.lastKey = key;
123237
122760
  this.lastWriteAt = this.now();
123238
122761
  this.writes += 1;
@@ -123284,16 +122807,16 @@ import {
123284
122807
  constants as constants6,
123285
122808
  accessSync as accessSync4,
123286
122809
  existsSync as existsSync42,
123287
- lstatSync as lstatSync11,
122810
+ lstatSync as lstatSync10,
123288
122811
  readFileSync as readFileSync50,
123289
- readdirSync as readdirSync15,
123290
- renameSync as renameSync12,
123291
- rmSync as rmSync18,
123292
- rmdirSync as rmdirSync3,
123293
- unlinkSync as unlinkSync12,
122812
+ readdirSync as readdirSync14,
122813
+ renameSync as renameSync13,
122814
+ rmSync as rmSync17,
122815
+ rmdirSync as rmdirSync4,
122816
+ unlinkSync as unlinkSync13,
123294
122817
  writeFileSync as writeFileSync25
123295
122818
  } from "fs";
123296
- import { dirname as dirname25, join as join64 } from "path";
122819
+ import { dirname as dirname26, join as join65 } from "path";
123297
122820
  function ownerStartOfSelf() {
123298
122821
  if (ownStart)
123299
122822
  return ownStart;
@@ -123314,14 +122837,14 @@ function ownerAlive(owner, table) {
123314
122837
  return !minted || startedAt(row, minted.startMs);
123315
122838
  }
123316
122839
  function recordsDir(root) {
123317
- return join64(root, "panes");
122840
+ return join65(root, "panes");
123318
122841
  }
123319
122842
  function writeRecord(root, rec) {
123320
122843
  const p = recordPathOf(root, rec.paneId);
123321
122844
  const tmp = `${p}.tmp-${process.pid}`;
123322
122845
  writeFileSync25(tmp, `${JSON.stringify(rec)}
123323
122846
  `, { mode: 384 });
123324
- renameSync12(tmp, p);
122847
+ renameSync13(tmp, p);
123325
122848
  }
123326
122849
  function readRecord2(root, paneId) {
123327
122850
  if (!isValidPaneId(paneId))
@@ -123339,7 +122862,7 @@ function updateRecord(root, paneId, patch) {
123339
122862
  }
123340
122863
  function deleteRecord(root, paneId) {
123341
122864
  try {
123342
- unlinkSync12(recordPathOf(root, paneId));
122865
+ unlinkSync13(recordPathOf(root, paneId));
123343
122866
  } catch {}
123344
122867
  }
123345
122868
  function validRecord(v, stem) {
@@ -123384,7 +122907,7 @@ function validForkRef(v) {
123384
122907
  function readRecords(root) {
123385
122908
  let names;
123386
122909
  try {
123387
- names = readdirSync15(recordsDir(root)).filter((n) => n.endsWith(".json"));
122910
+ names = readdirSync14(recordsDir(root)).filter((n) => n.endsWith(".json"));
123388
122911
  } catch {
123389
122912
  return [];
123390
122913
  }
@@ -123398,39 +122921,39 @@ function readRecords(root) {
123398
122921
  }
123399
122922
  function readGroupFile(ctlDir) {
123400
122923
  try {
123401
- return parseGroupFile(readFileSync50(join64(ctlDir, "group"), "utf8"));
122924
+ return parseGroupFile(readFileSync50(join65(ctlDir, "group"), "utf8"));
123402
122925
  } catch {
123403
122926
  return null;
123404
122927
  }
123405
122928
  }
123406
122929
  function writeGroupFile(ctlDir, snap) {
123407
- const p = join64(ctlDir, "group");
122930
+ const p = join65(ctlDir, "group");
123408
122931
  const tmp = `${p}.tmp`;
123409
122932
  try {
123410
122933
  writeFileSync25(tmp, formatGroupFile(snap), { mode: 384 });
123411
- renameSync12(tmp, p);
122934
+ renameSync13(tmp, p);
123412
122935
  } catch {}
123413
122936
  }
123414
122937
  function removeForkRecord(fork, forkUuid) {
123415
122938
  if (!isForkRecordPath(fork.projectsRoot, fork.path, forkUuid))
123416
122939
  return;
123417
122940
  try {
123418
- rmSync18(fork.path, { force: true });
122941
+ rmSync17(fork.path, { force: true });
123419
122942
  if (fork.removeProjectDir)
123420
- rmdirSync3(dirname25(fork.path));
122943
+ rmdirSync4(dirname26(fork.path));
123421
122944
  } catch {}
123422
122945
  }
123423
122946
  function removePaneFiles(root, f) {
123424
122947
  if (f.fork && f.sessionUuid)
123425
122948
  removeForkRecord(f.fork, f.sessionUuid);
123426
122949
  if (isPaneSockPath(root, f.sockPath, f.paneId))
123427
- rmSync18(f.sockPath, { force: true });
122950
+ rmSync17(f.sockPath, { force: true });
123428
122951
  const view = viewSockPathOf(root, f.paneId);
123429
122952
  if (isPaneViewSockPath(root, view, f.paneId))
123430
- rmSync18(view, { force: true });
122953
+ rmSync17(view, { force: true });
123431
122954
  for (const d of [f.launcherDir, f.turnDir])
123432
122955
  if (d && isLaunchDirPath(root, d))
123433
- rmSync18(d, { recursive: true, force: true });
122956
+ rmSync17(d, { recursive: true, force: true });
123434
122957
  const rec = recordPathOf(root, f.paneId);
123435
122958
  if (isPaneRecordPath(root, rec, f.paneId))
123436
122959
  deleteRecord(root, f.paneId);
@@ -123653,7 +123176,7 @@ function dialErrno(reported, sockPath) {
123653
123176
  return reported;
123654
123177
  let isSocket;
123655
123178
  try {
123656
- isSocket = lstatSync11(sockPath).isSocket();
123179
+ isSocket = lstatSync10(sockPath).isSocket();
123657
123180
  } catch (e) {
123658
123181
  return e.code ?? "unknown";
123659
123182
  }
@@ -123698,11 +123221,11 @@ async function sweepRecordlessSocket(root, name, out) {
123698
123221
  const owner = ownerOfSocketId(id);
123699
123222
  if (!owner || ownerAlive(owner, table))
123700
123223
  return;
123701
- const sockPath = join64(root, name);
123224
+ const sockPath = join65(root, name);
123702
123225
  const magmuxMayLive = !table || table.some((r) => isPaneMagmuxCommand(r.command, id));
123703
123226
  const probe = await probeSocket(sockPath, magmuxMayLive);
123704
123227
  if (probe.state === "stale") {
123705
- rmSync18(sockPath, { force: true });
123228
+ rmSync17(sockPath, { force: true });
123706
123229
  out.cleaned.push(id);
123707
123230
  return;
123708
123231
  }
@@ -123728,13 +123251,13 @@ async function sweepRecordlessSocket(root, name, out) {
123728
123251
  if (mag)
123729
123252
  signal(mag.pid, "SIGKILL");
123730
123253
  await Bun.sleep(300);
123731
- rmSync18(sockPath, { force: true });
123254
+ rmSync17(sockPath, { force: true });
123732
123255
  (mag ? out.reaped : out.kept).push(id);
123733
123256
  }
123734
123257
  function sweepRecordlessViewSockets(root, out) {
123735
123258
  let names = [];
123736
123259
  try {
123737
- names = readdirSync15(root).filter((n) => /^magmux-c\d+-[A-Za-z0-9_-]+\.view$/.test(n));
123260
+ names = readdirSync14(root).filter((n) => /^magmux-c\d+-[A-Za-z0-9_-]+\.view$/.test(n));
123738
123261
  } catch {
123739
123262
  return;
123740
123263
  }
@@ -123752,7 +123275,7 @@ function sweepRecordlessViewSockets(root, out) {
123752
123275
  const view = viewSockPathOf(root, id);
123753
123276
  if (!isPaneViewSockPath(root, view, id))
123754
123277
  continue;
123755
- rmSync18(view, { force: true });
123278
+ rmSync17(view, { force: true });
123756
123279
  out.cleaned.push(id);
123757
123280
  }
123758
123281
  }
@@ -123767,7 +123290,7 @@ function sweepDeadFeed(root, out) {
123767
123290
  const now = readFeedStamp(path);
123768
123291
  if (!now || now.pid !== stamp.pid || now.start36 !== stamp.start36 || now.started_at !== stamp.started_at)
123769
123292
  return;
123770
- rmSync18(path, { force: true });
123293
+ rmSync17(path, { force: true });
123771
123294
  out.cleaned.push("feed/feed.json");
123772
123295
  }
123773
123296
  async function ensureSwept(root) {
@@ -123786,7 +123309,7 @@ async function sweepOrphanPanes(root = sockRootFor()) {
123786
123309
  const known = new Set(readRecords(root).map((r) => r.paneId));
123787
123310
  let names = [];
123788
123311
  try {
123789
- names = readdirSync15(root).filter((n) => /^magmux-c\d+-[A-Za-z0-9_-]+\.sock$/.test(n));
123312
+ names = readdirSync14(root).filter((n) => /^magmux-c\d+-[A-Za-z0-9_-]+\.sock$/.test(n));
123790
123313
  } catch {
123791
123314
  names = [];
123792
123315
  }
@@ -123848,20 +123371,20 @@ var init_exit_evidence = __esm(() => {
123848
123371
  });
123849
123372
 
123850
123373
  // src/pane/gate-binding.ts
123851
- import { realpathSync as realpathSync9 } from "fs";
123852
- import { basename as basename11, dirname as dirname26, join as join65, resolve as resolve11 } from "path";
123374
+ import { realpathSync as realpathSync10 } from "fs";
123375
+ import { basename as basename12, dirname as dirname27, join as join66, resolve as resolve11 } from "path";
123853
123376
  function normaliseTranscriptPath(p) {
123854
123377
  const abs = resolve11(p);
123855
123378
  const tail = [];
123856
123379
  let cur = abs;
123857
123380
  for (;; ) {
123858
123381
  try {
123859
- return tail.length ? join65(realpathSync9(cur), ...tail.reverse()) : realpathSync9(cur);
123382
+ return tail.length ? join66(realpathSync10(cur), ...tail.reverse()) : realpathSync10(cur);
123860
123383
  } catch {
123861
- const parent = dirname26(cur);
123384
+ const parent = dirname27(cur);
123862
123385
  if (parent === cur)
123863
123386
  return abs;
123864
- tail.push(basename11(cur));
123387
+ tail.push(basename12(cur));
123865
123388
  cur = parent;
123866
123389
  }
123867
123390
  }
@@ -123950,7 +123473,7 @@ async function captureGroupBeforeReap(h) {
123950
123473
  }
123951
123474
  refreshGroupOf(h, table);
123952
123475
  }
123953
- async function groupAlive2(h) {
123476
+ async function groupAlive(h) {
123954
123477
  if (!h.group)
123955
123478
  return false;
123956
123479
  const table = await readProcessTableAsync();
@@ -123974,7 +123497,7 @@ async function groupBackstop(h) {
123974
123497
  for (const target of targets)
123975
123498
  signalQuietly(target, sig);
123976
123499
  const end = Date.now() + (sig === "SIGTERM" ? ms(h, 2000, 500) : 1000);
123977
- while (Date.now() < end && await groupAlive2(h))
123500
+ while (Date.now() < end && await groupAlive(h))
123978
123501
  await Bun.sleep(150);
123979
123502
  }
123980
123503
  }
@@ -123992,7 +123515,7 @@ async function endWatcher(h) {
123992
123515
  w.kill("SIGKILL");
123993
123516
  }
123994
123517
  async function verifyAndClean(h) {
123995
- const groupGone = !await groupAlive2(h);
123518
+ const groupGone = !await groupAlive(h);
123996
123519
  const magGone = !alive(h.magmux());
123997
123520
  h.client()?.close();
123998
123521
  if (groupGone && magGone) {
@@ -124078,8 +123601,8 @@ var init_scroll_input = __esm(() => {
124078
123601
  });
124079
123602
 
124080
123603
  // src/pane/session-registry.ts
124081
- import { readFileSync as readFileSync51, readdirSync as readdirSync16 } from "fs";
124082
- import { join as join66 } from "path";
123604
+ import { readFileSync as readFileSync51, readdirSync as readdirSync15 } from "fs";
123605
+ import { join as join67 } from "path";
124083
123606
  function parseRegistryRecord(raw) {
124084
123607
  let parsed;
124085
123608
  try {
@@ -124106,7 +123629,7 @@ function parseRegistryRecord(raw) {
124106
123629
  version: typeof r.version === "string" ? r.version : null
124107
123630
  };
124108
123631
  }
124109
- function pidAlive3(pid) {
123632
+ function pidAlive2(pid) {
124110
123633
  try {
124111
123634
  process.kill(pid, 0);
124112
123635
  return true;
@@ -124124,9 +123647,9 @@ class SessionRegistry {
124124
123647
  isAlive;
124125
123648
  constructor(o) {
124126
123649
  this.o = o;
124127
- this.dir = join66(o.configDir, "sessions");
123650
+ this.dir = join67(o.configDir, "sessions");
124128
123651
  this.now = o.now ?? Date.now;
124129
- this.isAlive = o.isAlive ?? pidAlive3;
123652
+ this.isAlive = o.isAlive ?? pidAlive2;
124130
123653
  }
124131
123654
  read() {
124132
123655
  if (this.pid !== null) {
@@ -124141,7 +123664,7 @@ class SessionRegistry {
124141
123664
  this.lastScanAt = now;
124142
123665
  let names;
124143
123666
  try {
124144
- names = readdirSync16(this.dir);
123667
+ names = readdirSync15(this.dir);
124145
123668
  } catch {
124146
123669
  return null;
124147
123670
  }
@@ -124160,7 +123683,7 @@ class SessionRegistry {
124160
123683
  readPid(pid) {
124161
123684
  let raw;
124162
123685
  try {
124163
- raw = readFileSync51(join66(this.dir, `${pid}.json`), "utf8");
123686
+ raw = readFileSync51(join67(this.dir, `${pid}.json`), "utf8");
124164
123687
  } catch {
124165
123688
  return null;
124166
123689
  }
@@ -124309,8 +123832,8 @@ var init_view_socket = __esm(() => {
124309
123832
  });
124310
123833
 
124311
123834
  // src/pane/pane-session.ts
124312
- import { readFileSync as readFileSync52, realpathSync as realpathSync10, rmSync as rmSync19, statSync as statSync27, writeFileSync as writeFileSync26 } from "fs";
124313
- import { join as join67 } from "path";
123835
+ import { readFileSync as readFileSync52, realpathSync as realpathSync11, rmSync as rmSync18, statSync as statSync26, writeFileSync as writeFileSync26 } from "fs";
123836
+ import { join as join68 } from "path";
124314
123837
  function clearKeyCount(line, attempts, cols) {
124315
123838
  const cells = 2 * Math.max(1, attempts) * Bun.stringWidth(line);
124316
123839
  const halfRow = Math.max(1, Math.floor((cols - 4) / 2));
@@ -124493,7 +124016,7 @@ class PaneSessionImpl {
124493
124016
  });
124494
124017
  this.secondaryQuietMs = o.timings?.secondaryQuietMs ?? SECONDARY_QUIET_MS;
124495
124018
  this.corroborationMs = o.timings?.corroborationMs ?? CORROBORATION_MS;
124496
- this.follower = new TranscriptFollower(o.transcriptPath, join67(o.transcriptPath.replace(/\.jsonl$/, ""), "subagents"));
124019
+ this.follower = new TranscriptFollower(o.transcriptPath, join68(o.transcriptPath.replace(/\.jsonl$/, ""), "subagents"));
124497
124020
  this.registry = new SessionRegistry({
124498
124021
  configDir: claudeCodeConfigDir(o.parentEnv ?? process.env, o.cwd),
124499
124022
  sessionUuid: o.sessionUuid
@@ -124540,7 +124063,7 @@ class PaneSessionImpl {
124540
124063
  return this.spawnFailed(new Error("magmux did not start"));
124541
124064
  this.magmux = proc;
124542
124065
  try {
124543
- writeFileSync26(join67(this.ctlDir, "magmux.pid"), `${proc.pid}
124066
+ writeFileSync26(join68(this.ctlDir, "magmux.pid"), `${proc.pid}
124544
124067
  `, { mode: 384 });
124545
124068
  } catch {}
124546
124069
  updateRecord(this.root, this.paneId, { magmuxPid: proc.pid });
@@ -126853,7 +126376,7 @@ ${screenTailOf(this.screen)}`
126853
126376
  if (!p)
126854
126377
  return 0;
126855
126378
  try {
126856
- return statSync27(p).size;
126379
+ return statSync26(p).size;
126857
126380
  } catch {
126858
126381
  return 0;
126859
126382
  }
@@ -127627,7 +127150,7 @@ function preparePane(o, root, parentEnv) {
127627
127150
  try {
127628
127151
  const paneId = mintPaneId(o.kind, o.label);
127629
127152
  const sockPath = sockPathOf(root, paneId);
127630
- const cwd = realpathSync10(o.cwd);
127153
+ const cwd = realpathSync11(o.cwd);
127631
127154
  const launch = o.claudishSpawn ?? resolveClaudishLaunch(parentEnv);
127632
127155
  dirs = createLaunchDirs(root);
127633
127156
  const argv = buildClaudishPaneArgv(o.spawnModel, o.sessionUuid, dirs.turnDir, o.callerFlags, o.spawnPinned === true);
@@ -127644,7 +127167,7 @@ function preparePane(o, root, parentEnv) {
127644
127167
  } catch (e) {
127645
127168
  for (const d of dirs ? [dirs.ctlDir, dirs.turnDir] : [])
127646
127169
  if (isLaunchDirPath(root, d))
127647
- rmSync19(d, { recursive: true, force: true });
127170
+ rmSync18(d, { recursive: true, force: true });
127648
127171
  if (e.code)
127649
127172
  throw e;
127650
127173
  throw new PaneStartError("pane_lost", e instanceof Error ? e.message : String(e));
@@ -127781,8 +127304,8 @@ var init_pane_session = __esm(() => {
127781
127304
  });
127782
127305
 
127783
127306
  // src/pane/replay-pane.ts
127784
- import { rmSync as rmSync20, writeFileSync as writeFileSync27 } from "fs";
127785
- import { join as join68 } from "path";
127307
+ import { rmSync as rmSync19, writeFileSync as writeFileSync27 } from "fs";
127308
+ import { join as join69 } from "path";
127786
127309
  async function waitUntil(pred, ms) {
127787
127310
  const end = Date.now() + ms;
127788
127311
  while (!pred() && Date.now() < end)
@@ -127895,7 +127418,7 @@ class ReplayPane {
127895
127418
  return failed(new Error("magmux did not start"));
127896
127419
  this.magmuxProc = proc;
127897
127420
  try {
127898
- writeFileSync27(join68(this.ctlDir, "magmux.pid"), `${proc.pid}
127421
+ writeFileSync27(join69(this.ctlDir, "magmux.pid"), `${proc.pid}
127899
127422
  `, { mode: 384 });
127900
127423
  } catch {}
127901
127424
  updateRecord(this.root, this.paneId, { magmuxPid: proc.pid });
@@ -128367,7 +127890,7 @@ async function startReplayPane(o) {
128367
127890
  } catch (e) {
128368
127891
  for (const d of dirs ? [dirs.ctlDir, dirs.turnDir] : [])
128369
127892
  if (isLaunchDirPath(root, d))
128370
- rmSync20(d, { recursive: true, force: true });
127893
+ rmSync19(d, { recursive: true, force: true });
128371
127894
  throw e;
128372
127895
  }
128373
127896
  const pane = new ReplayPane(o, {
@@ -128813,17 +128336,17 @@ var init_transcript_redaction = __esm(() => {
128813
128336
  // src/pane/transcript-page.ts
128814
128337
  import {
128815
128338
  constants as constants7,
128816
- closeSync as closeSync20,
128339
+ closeSync as closeSync21,
128817
128340
  fstatSync as fstatSync6,
128818
- lstatSync as lstatSync12,
128819
- openSync as openSync20,
128820
- readSync as readSync10,
128821
- readdirSync as readdirSync17,
128822
- readlinkSync as readlinkSync2,
128823
- realpathSync as realpathSync11,
128824
- statSync as statSync28
128341
+ lstatSync as lstatSync11,
128342
+ openSync as openSync21,
128343
+ readSync as readSync11,
128344
+ readdirSync as readdirSync16,
128345
+ readlinkSync,
128346
+ realpathSync as realpathSync12,
128347
+ statSync as statSync27
128825
128348
  } from "fs";
128826
- import { basename as basename12, dirname as dirname27, join as join69, sep as sep4 } from "path";
128349
+ import { basename as basename13, dirname as dirname28, join as join70, sep as sep4 } from "path";
128827
128350
  function isUuid(v) {
128828
128351
  return typeof v === "string" && UUID_RE.test(v);
128829
128352
  }
@@ -128870,7 +128393,7 @@ class LineScanner {
128870
128393
  return null;
128871
128394
  const n = Math.min(READ_CHUNK, this.size - at);
128872
128395
  const b = Buffer.alloc(n);
128873
- const got = readSync10(this.fd, b, 0, n, at);
128396
+ const got = readSync11(this.fd, b, 0, n, at);
128874
128397
  if (got <= 0)
128875
128398
  return null;
128876
128399
  this.chunk = got < n ? b.subarray(0, got) : b;
@@ -128905,7 +128428,7 @@ function absentPage(from) {
128905
128428
  }
128906
128429
  function closeQuietly(fd) {
128907
128430
  try {
128908
- closeSync20(fd);
128431
+ closeSync21(fd);
128909
128432
  } catch {}
128910
128433
  }
128911
128434
  function readTranscriptPageFd(fd, from, limits) {
@@ -128918,7 +128441,7 @@ function readTranscriptPageFd(fd, from, limits) {
128918
128441
  throw new ContractErrorException("invalid_args", "'since' is past the end of the transcript");
128919
128442
  if (from.offset > 0) {
128920
128443
  const b = Buffer.alloc(1);
128921
- const got = readSync10(fd, b, 0, 1, from.offset - 1);
128444
+ const got = readSync11(fd, b, 0, 1, from.offset - 1);
128922
128445
  if (got !== 1 || b[0] !== 10)
128923
128446
  throw new ContractErrorException("invalid_args", "'since' is not at a line start");
128924
128447
  }
@@ -128967,15 +128490,15 @@ function locateTranscriptByUuid(projectsRoot, uuid) {
128967
128490
  return null;
128968
128491
  let dirs;
128969
128492
  try {
128970
- dirs = readdirSync17(projectsRoot);
128493
+ dirs = readdirSync16(projectsRoot);
128971
128494
  } catch {
128972
128495
  return null;
128973
128496
  }
128974
128497
  let hit = null;
128975
128498
  for (const d of dirs) {
128976
- const p = join69(projectsRoot, d, `${uuid}.jsonl`);
128499
+ const p = join70(projectsRoot, d, `${uuid}.jsonl`);
128977
128500
  try {
128978
- if (!statSync28(p).isFile())
128501
+ if (!statSync27(p).isFile())
128979
128502
  continue;
128980
128503
  } catch {
128981
128504
  continue;
@@ -129003,7 +128526,7 @@ function writerLiveness(pid) {
129003
128526
  }
129004
128527
  function fileAgeMs(path, now = Date.now()) {
129005
128528
  try {
129006
- return now - statSync28(path).mtimeMs;
128529
+ return now - statSync27(path).mtimeMs;
129007
128530
  } catch {
129008
128531
  return null;
129009
128532
  }
@@ -129028,15 +128551,15 @@ function errText(e) {
129028
128551
  return e instanceof Error ? e.message : String(e);
129029
128552
  }
129030
128553
  function openContainedTranscript(path, uuid, projectsRoot) {
129031
- if (basename12(path) !== `${uuid}.jsonl`) {
128554
+ if (basename13(path) !== `${uuid}.jsonl`) {
129032
128555
  logRejection(path, "basename is not the session uuid");
129033
128556
  return null;
129034
128557
  }
129035
128558
  let real;
129036
128559
  let root;
129037
128560
  try {
129038
- real = realpathSync11(path);
129039
- root = realpathSync11(projectsRoot);
128561
+ real = realpathSync12(path);
128562
+ root = realpathSync12(projectsRoot);
129040
128563
  } catch (e) {
129041
128564
  if (!isEnoent(e))
129042
128565
  logRejection(path, errText(e));
@@ -129048,7 +128571,7 @@ function openContainedTranscript(path, uuid, projectsRoot) {
129048
128571
  }
129049
128572
  let fd;
129050
128573
  try {
129051
- fd = openSync20(real, OPEN_FLAGS);
128574
+ fd = openSync21(real, OPEN_FLAGS);
129052
128575
  } catch (e) {
129053
128576
  if (e?.code === "ELOOP")
129054
128577
  logRejection(path, "the transcript became a symlink");
@@ -129063,9 +128586,9 @@ function openContainedTranscript(path, uuid, projectsRoot) {
129063
128586
  closeQuietly(fd);
129064
128587
  return null;
129065
128588
  }
129066
- const parent = dirname27(real);
129067
- const named = lstatSync12(real);
129068
- if (realpathSync11(parent) !== parent || !named.isFile() || named.dev !== st.dev || named.ino !== st.ino || !kernelPathMatches(fd, real)) {
128589
+ const parent = dirname28(real);
128590
+ const named = lstatSync11(real);
128591
+ if (realpathSync12(parent) !== parent || !named.isFile() || named.dev !== st.dev || named.ino !== st.ino || !kernelPathMatches(fd, real)) {
129069
128592
  logRejection(path, "the opened file is not the one under the projects directory");
129070
128593
  closeQuietly(fd);
129071
128594
  return null;
@@ -129083,7 +128606,7 @@ function kernelPathMatches(fd, real) {
129083
128606
  return true;
129084
128607
  let kernel;
129085
128608
  try {
129086
- kernel = readlinkSync2(`/proc/self/fd/${fd}`);
128609
+ kernel = readlinkSync(`/proc/self/fd/${fd}`);
129087
128610
  } catch {
129088
128611
  return true;
129089
128612
  }
@@ -129096,7 +128619,7 @@ function transcriptHeadCwd(path, uuid, projectsRoot) {
129096
128619
  let text;
129097
128620
  try {
129098
128621
  const buf = Buffer.alloc(HEAD_CWD_MAX_BYTES);
129099
- const n = readSync10(fd, buf, 0, HEAD_CWD_MAX_BYTES, 0);
128622
+ const n = readSync11(fd, buf, 0, HEAD_CWD_MAX_BYTES, 0);
129100
128623
  text = buf.toString("utf8", 0, n);
129101
128624
  } catch {
129102
128625
  return null;
@@ -129208,7 +128731,7 @@ var init_pane = __esm(() => {
129208
128731
  });
129209
128732
 
129210
128733
  // src/view/kernel-lock.ts
129211
- import { constants as constants8, closeSync as closeSync21, fstatSync as fstatSync7, openSync as openSync21, statSync as statSync29, unlinkSync as unlinkSync13 } from "fs";
128734
+ import { constants as constants8, closeSync as closeSync22, fstatSync as fstatSync7, openSync as openSync22, statSync as statSync28, unlinkSync as unlinkSync14 } from "fs";
129212
128735
  function bindFlock() {
129213
128736
  const library = process.platform === "darwin" ? "libSystem.B.dylib" : process.platform === "linux" ? "libc.so.6" : null;
129214
128737
  if (!library)
@@ -129251,7 +128774,7 @@ function lockOf(fd, path) {
129251
128774
  return;
129252
128775
  open = false;
129253
128776
  try {
129254
- closeSync21(fd);
128777
+ closeSync22(fd);
129255
128778
  } catch {}
129256
128779
  }
129257
128780
  };
@@ -129261,23 +128784,23 @@ function tryAcquire(path) {
129261
128784
  if (!lib)
129262
128785
  throw new KernelLockUnavailable("flock is not available in this process");
129263
128786
  for (let attempt = 0;attempt < 5; attempt++) {
129264
- const fd = openSync21(path, constants8.O_RDWR | constants8.O_CREAT | O_CLOEXEC, 384);
128787
+ const fd = openSync22(path, constants8.O_RDWR | constants8.O_CREAT | O_CLOEXEC, 384);
129265
128788
  if (lib.flock(fd, LOCK_EX | LOCK_NB) !== 0) {
129266
128789
  const errno = lib.errno();
129267
- closeSync21(fd);
128790
+ closeSync22(fd);
129268
128791
  if (errno === EWOULDBLOCK)
129269
128792
  return null;
129270
128793
  throw new KernelLockUnavailable(`flock ${path}: errno ${errno}`);
129271
128794
  }
129272
128795
  let same = false;
129273
128796
  try {
129274
- same = fstatSync7(fd).ino === statSync29(path).ino;
128797
+ same = fstatSync7(fd).ino === statSync28(path).ino;
129275
128798
  } catch {
129276
128799
  same = false;
129277
128800
  }
129278
128801
  if (same)
129279
128802
  return lockOf(fd, path);
129280
- closeSync21(fd);
128803
+ closeSync22(fd);
129281
128804
  }
129282
128805
  throw new KernelLockUnavailable(`flock ${path}: the file keeps being replaced`);
129283
128806
  }
@@ -129302,7 +128825,7 @@ function removeIfFree(path) {
129302
128825
  if (!lock)
129303
128826
  return false;
129304
128827
  try {
129305
- unlinkSync13(path);
128828
+ unlinkSync14(path);
129306
128829
  return true;
129307
128830
  } catch {
129308
128831
  return false;
@@ -129467,8 +128990,8 @@ var init_peer_link = __esm(() => {
129467
128990
 
129468
128991
  // src/view/replay-registry.ts
129469
128992
  import { randomBytes as randomBytes18 } from "crypto";
129470
- import { readFileSync as readFileSync53, readdirSync as readdirSync18, renameSync as renameSync13, rmSync as rmSync21, writeFileSync as writeFileSync28 } from "fs";
129471
- import { join as join70 } from "path";
128993
+ import { readFileSync as readFileSync53, readdirSync as readdirSync17, renameSync as renameSync14, rmSync as rmSync20, writeFileSync as writeFileSync28 } from "fs";
128994
+ import { join as join71 } from "path";
129472
128995
  function parseEntry(raw) {
129473
128996
  let v;
129474
128997
  try {
@@ -129506,14 +129029,14 @@ class ReplayRegistry {
129506
129029
  constructor(root, log = () => {}) {
129507
129030
  this.root = root;
129508
129031
  this.log = log;
129509
- this.dir = join70(root, REPLAYS_DIR);
129032
+ this.dir = join71(root, REPLAYS_DIR);
129510
129033
  }
129511
129034
  ensure() {
129512
129035
  ensureSockRoot(this.root);
129513
129036
  return ensurePrivateSubdir(this.root, REPLAYS_DIR);
129514
129037
  }
129515
129038
  lockPathOf(uuid) {
129516
- return join70(this.dir, `${this.key(uuid)}.lock`);
129039
+ return join71(this.dir, `${this.key(uuid)}.lock`);
129517
129040
  }
129518
129041
  tryLock(uuid) {
129519
129042
  this.ensure();
@@ -129528,7 +129051,7 @@ class ReplayRegistry {
129528
129051
  }
129529
129052
  async withLock(fn, waitMs = REGISTRY_LOCK_WAIT_MS) {
129530
129053
  this.ensure();
129531
- const lock = await waitAcquire(join70(this.dir, "registry.lock"), waitMs);
129054
+ const lock = await waitAcquire(join71(this.dir, "registry.lock"), waitMs);
129532
129055
  if (!lock)
129533
129056
  return null;
129534
129057
  try {
@@ -129543,9 +129066,9 @@ class ReplayRegistry {
129543
129066
  writeFileSync28(tmp, `${JSON.stringify(entry)}
129544
129067
  `, { mode: 384, flag: "wx" });
129545
129068
  try {
129546
- renameSync13(tmp, path);
129069
+ renameSync14(tmp, path);
129547
129070
  } catch (e) {
129548
- rmSync21(tmp, { force: true });
129071
+ rmSync20(tmp, { force: true });
129549
129072
  throw e;
129550
129073
  }
129551
129074
  }
@@ -129566,7 +129089,7 @@ class ReplayRegistry {
129566
129089
  const e = this.read(uuid);
129567
129090
  if (!e || e.replay_id !== replayId)
129568
129091
  return false;
129569
- rmSync21(this.entryPathOf(uuid), { force: true });
129092
+ rmSync20(this.entryPathOf(uuid), { force: true });
129570
129093
  return true;
129571
129094
  });
129572
129095
  if (!done)
@@ -129576,7 +129099,7 @@ class ReplayRegistry {
129576
129099
  async sweep() {
129577
129100
  let names;
129578
129101
  try {
129579
- names = readdirSync18(this.dir);
129102
+ names = readdirSync17(this.dir);
129580
129103
  } catch {
129581
129104
  return [];
129582
129105
  }
@@ -129590,7 +129113,7 @@ class ReplayRegistry {
129590
129113
  if (!held)
129591
129114
  continue;
129592
129115
  try {
129593
- await this.withLock(() => rmSync21(this.entryPathOf(uuid), { force: true }));
129116
+ await this.withLock(() => rmSync20(this.entryPathOf(uuid), { force: true }));
129594
129117
  } finally {
129595
129118
  held.close();
129596
129119
  }
@@ -129600,18 +129123,18 @@ class ReplayRegistry {
129600
129123
  await this.withLock(() => {
129601
129124
  let now;
129602
129125
  try {
129603
- now = readdirSync18(this.dir);
129126
+ now = readdirSync17(this.dir);
129604
129127
  } catch {
129605
129128
  return;
129606
129129
  }
129607
129130
  for (const name of now)
129608
129131
  if (name.endsWith(".tmp"))
129609
- rmSync21(join70(this.dir, name), { force: true });
129132
+ rmSync20(join71(this.dir, name), { force: true });
129610
129133
  });
129611
129134
  return swept;
129612
129135
  }
129613
129136
  entryPathOf(uuid) {
129614
- return join70(this.dir, `${this.key(uuid)}.json`);
129137
+ return join71(this.dir, `${this.key(uuid)}.json`);
129615
129138
  }
129616
129139
  key(uuid) {
129617
129140
  const k = uuid.toLowerCase();
@@ -129632,8 +129155,8 @@ var init_replay_registry = __esm(() => {
129632
129155
 
129633
129156
  // src/mcp-session/replay-manager.ts
129634
129157
  import { randomBytes as randomBytes19, randomUUID as randomUUID10 } from "crypto";
129635
- import { constants as constants9, accessSync as accessSync5, closeSync as closeSync22, existsSync as existsSync43, realpathSync as realpathSync12, statSync as statSync30 } from "fs";
129636
- import { dirname as dirname28, resolve as resolve12 } from "path";
129158
+ import { constants as constants9, accessSync as accessSync5, closeSync as closeSync23, existsSync as existsSync43, realpathSync as realpathSync13, statSync as statSync29 } from "fs";
129159
+ import { dirname as dirname29, resolve as resolve12 } from "path";
129637
129160
  function unavailable2(reason, message) {
129638
129161
  return new ContractErrorException("replay_unavailable", message, reason);
129639
129162
  }
@@ -129646,17 +129169,17 @@ function elsewhere(endpoint, replayId) {
129646
129169
  function replayCwd(own) {
129647
129170
  if (own) {
129648
129171
  try {
129649
- if (statSync30(own).isDirectory())
129650
- return realpathSync12(own);
129172
+ if (statSync29(own).isDirectory())
129173
+ return realpathSync13(own);
129651
129174
  } catch {}
129652
129175
  }
129653
- return realpathSync12(process.cwd());
129176
+ return realpathSync13(process.cwd());
129654
129177
  }
129655
129178
  async function replayClaudeBinary(env) {
129656
129179
  const named = env.CLAUDE_PATH ? resolve12(env.CLAUDE_PATH) : "";
129657
129180
  if (named) {
129658
129181
  try {
129659
- if (!statSync30(named).isFile())
129182
+ if (!statSync29(named).isFile())
129660
129183
  throw new Error("not a file");
129661
129184
  accessSync5(named, constants9.X_OK);
129662
129185
  } catch {
@@ -129674,7 +129197,7 @@ function callerOf(opener) {
129674
129197
  }
129675
129198
  function isRecordGone(path) {
129676
129199
  try {
129677
- statSync30(path);
129200
+ statSync29(path);
129678
129201
  return false;
129679
129202
  } catch (e) {
129680
129203
  return e.code === "ENOENT";
@@ -129985,8 +129508,8 @@ class ReplayManager {
129985
129508
  cwd,
129986
129509
  projectsRoot,
129987
129510
  forkPath,
129988
- removeProjectDir: !existsSync43(dirname28(forkPath)),
129989
- configDir: dirname28(projectsRoot),
129511
+ removeProjectDir: !existsSync43(dirname29(forkPath)),
129512
+ configDir: dirname29(projectsRoot),
129990
129513
  cols: size.cols ?? DEFAULT_PANE_COLS,
129991
129514
  rows: size.rows ?? DEFAULT_PANE_ROWS
129992
129515
  });
@@ -130287,7 +129810,7 @@ class ReplayManager {
130287
129810
  const fd = openContainedTranscript(path, uuid, target.projectsRoot);
130288
129811
  if (fd === null)
130289
129812
  throw noRecord("the session's Claude Code record is gone");
130290
- closeSync22(fd);
129813
+ closeSync23(fd);
130291
129814
  return uuid;
130292
129815
  }
130293
129816
  itemOf(e) {
@@ -130960,6 +130483,7 @@ function noticeLines(notices) {
130960
130483
  var CLAUDE_API_PROVIDER3 = "anthropic", TIER_FIELDS;
130961
130484
  var init_claude_launch = __esm(() => {
130962
130485
  init_claude_code_login();
130486
+ init_classifier_passthrough();
130963
130487
  init_claude_runner();
130964
130488
  init_anthropic_forward();
130965
130489
  init_child_env();
@@ -130979,10 +130503,10 @@ var init_claude_launch = __esm(() => {
130979
130503
  });
130980
130504
 
130981
130505
  // src/mcp/run-prompt-claude-code.ts
130982
- import { spawn as spawn5 } from "child_process";
130983
- import { mkdirSync as mkdirSync28, mkdtempSync as mkdtempSync5, rmSync as rmSync22, writeFileSync as writeFileSync29 } from "fs";
130984
- import { tmpdir as tmpdir4 } from "os";
130985
- import { join as join71 } from "path";
130506
+ import { spawn as spawn4 } from "child_process";
130507
+ import { mkdirSync as mkdirSync29, mkdtempSync as mkdtempSync4, rmSync as rmSync21, writeFileSync as writeFileSync29 } from "fs";
130508
+ import { tmpdir as tmpdir3 } from "os";
130509
+ import { join as join72 } from "path";
130986
130510
  function claudeCodePrintArgv(model, systemPromptFile, opts = {}) {
130987
130511
  const head = [
130988
130512
  PRINT_FLAGS[0],
@@ -131118,13 +130642,13 @@ async function runPromptViaClaudeCode(model, prompt, systemPrompt, opts = {}) {
131118
130642
  } catch (e) {
131119
130643
  throw new Error(`cannot start claudish (${parentEnv.CLAUDISH_BIN?.trim() || "claudish"}): ${e instanceof Error ? e.message : String(e)}`);
131120
130644
  }
131121
- const root = mkdtempSync5(join71(tmpdir4(), "claudish-run-prompt-"));
130645
+ const root = mkdtempSync4(join72(tmpdir3(), "claudish-run-prompt-"));
131122
130646
  try {
131123
- const cwd = join71(root, "cwd");
131124
- mkdirSync28(cwd, { mode: 448 });
130647
+ const cwd = join72(root, "cwd");
130648
+ mkdirSync29(cwd, { mode: 448 });
131125
130649
  let systemPromptFile;
131126
130650
  if (typeof systemPrompt === "string" && systemPrompt.length > 0) {
131127
- systemPromptFile = join71(root, "system-prompt.txt");
130651
+ systemPromptFile = join72(root, "system-prompt.txt");
131128
130652
  writeFileSync29(systemPromptFile, systemPrompt, { mode: 384 });
131129
130653
  }
131130
130654
  const argv = claudeCodePrintArgv(model, systemPromptFile, {
@@ -131155,14 +130679,14 @@ async function runPromptViaClaudeCode(model, prompt, systemPrompt, opts = {}) {
131155
130679
  answer.auth = auth;
131156
130680
  return answer;
131157
130681
  } finally {
131158
- rmSync22(root, { recursive: true, force: true });
130682
+ rmSync21(root, { recursive: true, force: true });
131159
130683
  }
131160
130684
  }
131161
130685
  function runChild(launch, argv, cwd, env, prompt, signal) {
131162
130686
  return new Promise((resolvePromise, reject) => {
131163
130687
  let proc;
131164
130688
  try {
131165
- proc = spawn5(launch.command, [...launch.prefixArgs, ...argv], {
130689
+ proc = spawn4(launch.command, [...launch.prefixArgs, ...argv], {
131166
130690
  cwd,
131167
130691
  env,
131168
130692
  stdio: ["pipe", "pipe", "pipe"],
@@ -131235,7 +130759,7 @@ var init_run_prompt_claude_code = __esm(() => {
131235
130759
  ENV.CLAUDISH_PANE_CHILD
131236
130760
  ];
131237
130761
  inFlight5 = new Set;
131238
- EMPTY_PRINT_CWD = join71(tmpdir4(), "claudish-run-prompt-settings-check");
130762
+ EMPTY_PRINT_CWD = join72(tmpdir3(), "claudish-run-prompt-settings-check");
131239
130763
  });
131240
130764
 
131241
130765
  // src/providers/bundled-list.ts
@@ -132233,9 +131757,9 @@ var init_view_server = __esm(() => {
132233
131757
  });
132234
131758
 
132235
131759
  // src/mcp-server.ts
132236
- import { existsSync as existsSync44, readFileSync as readFileSync54, readdirSync as readdirSync19 } from "fs";
132237
- import { homedir as homedir41 } from "os";
132238
- import { dirname as dirname29, join as join72, resolve as resolve13 } from "path";
131760
+ import { existsSync as existsSync44, readFileSync as readFileSync54, readdirSync as readdirSync18 } from "fs";
131761
+ import { homedir as homedir43 } from "os";
131762
+ import { dirname as dirname30, join as join73, resolve as resolve13 } from "path";
132239
131763
  import { fileURLToPath as fileURLToPath3 } from "url";
132240
131764
  async function loadAllModels(forceRefresh = false) {
132241
131765
  if (!forceRefresh && existsSync44(OPENROUTER_MODELS_CACHE_PATH)) {
@@ -133709,26 +133233,26 @@ This searched OpenRouter's listing only. Subscription wire ids and catalog alias
133709
133233
  const sp = session_path;
133710
133234
  for (const file of ["status.json", "manifest.json", "input.md"]) {
133711
133235
  try {
133712
- sessionData[file] = readFileSync54(join72(sp, file), "utf-8");
133236
+ sessionData[file] = readFileSync54(join73(sp, file), "utf-8");
133713
133237
  } catch {}
133714
133238
  }
133715
133239
  try {
133716
- const errorDir = join72(sp, "errors");
133240
+ const errorDir = join73(sp, "errors");
133717
133241
  if (existsSync44(errorDir)) {
133718
- for (const f of readdirSync19(errorDir)) {
133242
+ for (const f of readdirSync18(errorDir)) {
133719
133243
  if (f.endsWith(".log")) {
133720
133244
  try {
133721
- sessionData[`errors/${f}`] = readFileSync54(join72(errorDir, f), "utf-8");
133245
+ sessionData[`errors/${f}`] = readFileSync54(join73(errorDir, f), "utf-8");
133722
133246
  } catch {}
133723
133247
  }
133724
133248
  }
133725
133249
  }
133726
133250
  } catch {}
133727
133251
  try {
133728
- for (const f of readdirSync19(sp)) {
133252
+ for (const f of readdirSync18(sp)) {
133729
133253
  if (f.startsWith("response-") && f.endsWith(".md")) {
133730
133254
  try {
133731
- const content = readFileSync54(join72(sp, f), "utf-8");
133255
+ const content = readFileSync54(join73(sp, f), "utf-8");
133732
133256
  sessionData[f] = content.slice(0, 200) + (content.length > 200 ? "... (truncated)" : "");
133733
133257
  } catch {}
133734
133258
  }
@@ -133737,7 +133261,7 @@ This searched OpenRouter's listing only. Subscription wire ids and catalog alias
133737
133261
  }
133738
133262
  let version = "unknown";
133739
133263
  try {
133740
- const pkgPath = join72(__dirname3, "../package.json");
133264
+ const pkgPath = join73(__dirname3, "../package.json");
133741
133265
  if (existsSync44(pkgPath)) {
133742
133266
  version = JSON.parse(readFileSync54(pkgPath, "utf-8")).version;
133743
133267
  }
@@ -133902,7 +133426,7 @@ Report manually at https://github.com/anthropics/claudish/issues${autoSendHint}`
133902
133426
  },
133903
133427
  work_dir: {
133904
133428
  type: "string",
133905
- description: "Working directory for the session (default: current directory)"
133429
+ description: "Working directory for the session (default: current directory). A folder Claude Code has not trusted yet is marked trusted in your Claude Code config (.claude.json) before the session starts, so the session does not stop at the trust dialog."
133906
133430
  },
133907
133431
  setup_from: {
133908
133432
  type: ["string", "null"],
@@ -134357,7 +133881,6 @@ async function main() {
134357
133881
  const viewFeed = new ViewFeed;
134358
133882
  const viewClaims = new ViewClaims({ notify: (target) => viewFeed.changed(target, true) });
134359
133883
  const sessionManager = new SessionManager({ feed: viewFeed, claims: viewClaims });
134360
- sweepStaleProbeDirs();
134361
133884
  replays.setViewServices({ feed: viewFeed, claims: viewClaims });
134362
133885
  setViewServices({ feed: viewFeed, claims: viewClaims });
134363
133886
  const progressIntervalMs = resolveProgressIntervalMs();
@@ -134508,7 +134031,6 @@ var init_mcp_server = __esm(() => {
134508
134031
  init_mcp_session();
134509
134032
  init_inherited_settings();
134510
134033
  init_parent_session();
134511
- init_plugin_probe();
134512
134034
  init_nested_mode();
134513
134035
  init_progress_heartbeat();
134514
134036
  init_run_prompt_claude_code();
@@ -134543,9 +134065,9 @@ var init_mcp_server = __esm(() => {
134543
134065
  init_view_server();
134544
134066
  init_preflight_chain();
134545
134067
  __filename3 = fileURLToPath3(import.meta.url);
134546
- __dirname3 = dirname29(__filename3);
134547
- CLAUDISH_CACHE_DIR = join72(homedir41(), ".claudish");
134548
- OPENROUTER_MODELS_CACHE_PATH = join72(CLAUDISH_CACHE_DIR, "openrouter-models.json");
134068
+ __dirname3 = dirname30(__filename3);
134069
+ CLAUDISH_CACHE_DIR = join73(homedir43(), ".claudish");
134070
+ OPENROUTER_MODELS_CACHE_PATH = join73(CLAUDISH_CACHE_DIR, "openrouter-models.json");
134549
134071
  NEXT_STEP = {
134550
134072
  cancelled: "you stopped this slot; nothing is wrong with it. Re-run it if you still want its vote",
134551
134073
  timeout: "grid mode only \u2014 magmux ended the pane. The orchestrator has no deadline",
@@ -134707,9 +134229,9 @@ var init_serve_command = __esm(() => {
134707
134229
  var HOOKS_AMBIENT_DTS = '// claudish hook types \u2014 written by `claudish hooks init`. Do not edit: run\n// `claudish hooks init` from a newer claudish to refresh it.\n// With this file beside your hook, `import type { HookDefinition } from\n// "claudish/hooks"` type-checks with nothing installed.\ndeclare module "claudish/hooks" {\n /**\n * claudish/hooks \u2014 the public hook contract.\n *\n * Everything a hook author can import lives here, and nothing else does. This\n * file imports nothing from the rest of claudish and has no side effects, so it\n * can be built on its own into `dist/hooks.js` + `dist/hooks.d.ts` and served to\n * user modules as the `claudish/hooks` virtual module (see `loader.ts`).\n *\n * Every internal hooks module takes its types from here, so the contract has a\n * single source.\n *\n * ## Process isolation\n *\n * A hook module\'s top-level state is PER PROCESS. In the interactive launcher,\n * proxy events (`request` \u2026 `responseEnd`, raw) and session events\n * (`sessionStart` \u2026 `sessionEnd`) run in one process. In `create_session` and\n * team children they do not: proxy events run in the pane child, and session\n * events run in the MCP server or the CLI process that drives the pane. Pass\n * per-turn data from a proxy event to `sessionIdle` with `annotateTurn`, never\n * with module variables.\n *\n * ## Execution: a hook chain\n *\n * The hooks of one event run one after another, in effective order. Each hook\'s\n * actions are applied before the next hook is called, so `ctx.request`,\n * `ctx.tool.args` and `ctx.response` show what the earlier hooks did, and\n * `ctx.prior` lists it. A warn-severity or failing hook changes nothing for the\n * next one. Each event has a budget for all its hooks together; a hook\'s timeout\n * is cut to what is left of it.\n *\n * ## Output\n *\n * Log with `ctx.log`. `console.*` and `process.stdout`/`stderr` writes made by a\n * hook are routed to claudish\'s debug log, never to the terminal or the MCP\n * protocol stream.\n */\n export const HOOK_API_VERSION = 1;\n export type Severity = "off" | "warn" | "fix";\n export type HookOrder = "pre" | "normal" | "post";\n /** native = RouteInfo.native true; foreign = RouteInfo.native false; all = both */\n export type RouteScope = "foreign" | "native" | "all";\n export type HostMode = "interactive" | "pane-child" | "serve" | "mcp" | "other";\n export type JsonValue = string | number | boolean | null | ReadonlyArray<JsonValue> | {\n readonly [k: string]: JsonValue;\n };\n export interface HarnessFacts {\n readonly planModeActive: boolean;\n readonly planFilePath?: string;\n readonly planDir?: string;\n /** Claude Code session id from request metadata */\n readonly sessionId?: string;\n /** empty = no listing found, not "no skills" */\n readonly skills?: ReadonlyArray<{\n name: string;\n description: string;\n }>;\n }\n export interface RouteInfo {\n /** bare model name the handler serves, e.g. "glm-5" */\n readonly modelId: string;\n /** claudish provider name, e.g. "openrouter"; "anthropic" for native */\n readonly provider: string;\n /**\n * true when the request is served by the native Anthropic handler, OR when\n * !forceForeignModel && (/^claude[-.]/i.test(modelId) || provider === "anthropic")\n * where forceForeignModel is the provider profile\'s opt-in override. This is the exact\n * rule the plan-mode built-in has always used (a claude-* uid on an aggregator that sets\n * forceForeignModel is foreign).\n */\n readonly native: boolean;\n }\n export interface ClaudeTool {\n name: string;\n description?: string;\n input_schema?: unknown;\n }\n /** A Claude-format content block. Only `text` blocks are editable by closed actions. */\n export type ClaudeContentBlock = {\n type: "text";\n text: string;\n } | {\n type: "tool_use";\n id: string;\n name: string;\n input: unknown;\n } | {\n type: "tool_result";\n tool_use_id: string;\n content?: unknown;\n is_error?: boolean;\n } | {\n type: "thinking";\n thinking: string;\n signature?: string;\n } | {\n type: string;\n [k: string]: unknown;\n };\n export interface ClaudeMessage {\n role: "user" | "assistant";\n content: string | ReadonlyArray<ClaudeContentBlock>;\n }\n /**\n * In `request`, the request as the earlier steps of the hook chain left it. On\n * the response side and in `claims()`, the request chain\'s final view.\n */\n export interface RequestFacts {\n /** as Claude Code asked for it; frozen */\n readonly model: string;\n /** frozen */\n readonly stream: boolean;\n /** system prompt flattened to text, after earlier steps */\n readonly systemText: string;\n /** read-only view after earlier steps; change it through actions */\n readonly messages: ReadonlyArray<ClaudeMessage>;\n /**\n * read-only view after earlier steps; `description` includes earlier description actions as\n * stage B will apply them to the Claude-format tool (the provider copy may be summarised)\n */\n readonly tools: ReadonlyArray<ClaudeTool>;\n }\n /** Which session a proxy event belongs to, when claudish knows. */\n export interface ProxySessionRef {\n readonly kind: SessionKind;\n readonly id: string;\n readonly role: "slot" | "judge" | null;\n }\n /** One action an earlier step of this hook chain applied or handed on. */\n export interface PriorAction {\n readonly hookId: string;\n readonly action: HookAction;\n }\n interface BaseContext {\n readonly hookId: string;\n /** "warn" or "fix" (an "off" hook is never called) */\n readonly severity: Severity;\n /** writes to claudish\'s debug log; never to the terminal */\n log(message: string): void;\n /**\n * this step\'s own signal: aborted when its step timeout elapses (its own timeout, or the\n * event budget left, whichever is shorter) or when the dispatch is aborted. Never shared\n * with another hook\'s step.\n */\n readonly signal: AbortSignal;\n /**\n * actions earlier steps of this hook chain applied (or, for responseEnd/sessionStart/\n * sessionIdle, handed on), in order. Empty for the first step and in claims()/the toolCall\n * predicate. Never lists warn actions or anything a warn-severity hook returned.\n */\n readonly prior: ReadonlyArray<PriorAction>;\n }\n export interface ProxyContext extends BaseContext {\n readonly host: {\n mode: HostMode;\n };\n readonly route: RouteInfo;\n readonly request: RequestFacts;\n readonly harness: HarnessFacts;\n readonly session: ProxySessionRef | null;\n }\n export interface RequestContext extends ProxyContext {\n readonly event: "request";\n }\n export interface ToolCallContext extends ProxyContext {\n readonly event: "toolCall";\n readonly tool: {\n id: string;\n name: string;\n /** the arguments after every repair earlier hooks in the chain applied */\n args: Readonly<Record<string, unknown>>;\n /** the argument JSON exactly as the model produced it; never rewritten */\n rawArgs: string;\n };\n }\n export type ResponseBlock = {\n type: "text";\n text: string;\n } | {\n type: "thinking";\n thinking: string;\n } | {\n type: "tool_use";\n id: string;\n name: string;\n input: unknown;\n } | {\n type: "other";\n blockType: string;\n };\n export interface ResponseView {\n blocks: ReadonlyArray<ResponseBlock>;\n /** every text block, joined with "\\n\\n" */\n text: string;\n /** every thinking block, joined with "\\n\\n" */\n reasoning: string;\n toolNames: ReadonlyArray<string>;\n /** "tool_use" = an intermediate step of a tool loop; the turn continues after the tool runs */\n stopReason: string | null;\n }\n /** response = the held response after every text action earlier hooks in the chain applied */\n export interface ResponseRewriteContext extends ProxyContext {\n readonly event: "responseRewrite";\n readonly response: ResponseView;\n }\n /** response = the final bytes the client received: after any rewrite AND any raw `response` replacement */\n export interface ResponseEndContext extends ProxyContext {\n readonly event: "responseEnd";\n readonly response: ResponseView;\n }\n export type SessionKind = "interactive" | "channel" | "team";\n export interface SessionInfo {\n kind: SessionKind;\n /** team only; null otherwise */\n role: "slot" | "judge" | null;\n /** channel: the 8-hex session_id \xB7 team: "<run_id>:<slot id>" \xB7 interactive: the Claude Code session id */\n id: string;\n claudeSessionId: string | null;\n /** as the caller asked for it */\n model: string;\n cwd: string;\n /** a one-shot session stays "one-shot" through a hook-extended turn chain */\n shape: "interactive" | "one-shot";\n injection: "available" | "unavailable";\n }\n export interface SessionStartContext extends BaseContext {\n readonly event: "sessionStart";\n readonly session: SessionInfo;\n }\n export interface TurnAnnotation {\n hookId: string;\n key: string;\n value: JsonValue;\n }\n export interface SessionIdleContext extends BaseContext {\n readonly event: "sessionIdle";\n readonly session: SessionInfo;\n readonly turn: {\n /** 1-based within the session; a re-woken turn keeps its index */\n index: number;\n /** this turn\'s assistant text; "" when `answerWithheld` */\n answer: string;\n /**\n * the turn\'s prompt went as a task file, and the model\'s Read tool calls in the main\n * conversation did not return all of it: `answer` is "" whatever the model wrote. Reading\n * it another way (a shell `cat`, a subagent) does not count as reading it.\n */\n answerWithheld: boolean;\n stopReason: string | null;\n apiError: boolean;\n /** this turn was started by an injection */\n hookCaused: boolean;\n /** annotateTurn actions from this turn\'s responses, in arrival order */\n annotations: ReadonlyArray<TurnAnnotation>;\n };\n readonly consecutiveHookTurns: number;\n /** caller/human input is queued; an injection returned now will be dropped as stale */\n readonly callerInputPending: boolean;\n }\n export interface SessionBlockedContext extends BaseContext {\n readonly event: "sessionBlocked";\n readonly session: SessionInfo;\n readonly block: {\n kind: "question" | "permission";\n text: string;\n };\n }\n export interface SessionEndContext extends BaseContext {\n readonly event: "sessionEnd";\n readonly session: SessionInfo;\n readonly outcome: {\n state: string;\n reason: string | null;\n exitCode: number | null;\n };\n }\n type TextMatch = {\n find: string;\n regex?: boolean;\n flags?: string;\n };\n /** default ["user"] */\n type MessageRoles = {\n roles?: ReadonlyArray<"user" | "assistant">;\n };\n export type InjectSystemNote = {\n type: "injectSystemNote";\n text: string;\n };\n export type AppendUserText = {\n type: "appendUserText";\n text: string;\n };\n export type ReplaceMessageText = {\n type: "replaceMessageText";\n replace: string;\n } & TextMatch & MessageRoles;\n export type RemoveMessageText = {\n type: "removeMessageText";\n } & TextMatch & MessageRoles;\n export type RewriteToolDescription = {\n type: "rewriteToolDescription";\n tool: string;\n append: string;\n };\n export type ReplaceToolDescription = {\n type: "replaceToolDescription";\n tool: string;\n description: string;\n };\n export type ReplaceToolSchema = {\n type: "replaceToolSchema";\n tool: string;\n inputSchema: {\n type: "object";\n [k: string]: unknown;\n };\n };\n export type RemoveTool = {\n type: "removeTool";\n tool: string;\n };\n export type RepairToolArgs = {\n type: "repairToolArgs";\n args: Record<string, unknown>;\n reason: string;\n };\n export type AppendText = {\n type: "appendText";\n text: string;\n };\n export type PrependText = {\n type: "prependText";\n text: string;\n };\n export type ReplaceText = {\n type: "replaceText";\n replace: string;\n } & TextMatch;\n export type RemoveText = {\n type: "removeText";\n } & TextMatch;\n export type InjectUserTurn = {\n type: "injectUserTurn";\n text: string;\n };\n export type AnnotateTurn = {\n type: "annotateTurn";\n key: string;\n value: JsonValue;\n };\n export type Warn = {\n type: "warn";\n message: string;\n };\n export type RequestAction = InjectSystemNote | AppendUserText | ReplaceMessageText | RemoveMessageText | RewriteToolDescription | ReplaceToolDescription | ReplaceToolSchema | RemoveTool | Warn;\n export type ToolCallAction = RepairToolArgs | Warn;\n export type RewriteAction = AppendText | PrependText | ReplaceText | RemoveText | Warn;\n export type ResponseEndAction = InjectSystemNote | InjectUserTurn | AnnotateTurn | Warn;\n export type SessionAction = InjectUserTurn | Warn;\n export type ObserveAction = Warn;\n export type HookAction = RequestAction | ToolCallAction | RewriteAction | ResponseEndAction | SessionAction;\n export type HookResult<A> = A[] | void | Promise<A[] | void>;\n export interface HookHandlers {\n request?(ctx: RequestContext): HookResult<RequestAction>;\n toolCall?: {\n /** tool names whose completed arguments this hook sees; "*" = every tool (costs streaming of all tool input) */\n tools: ReadonlyArray<string>;\n /** synchronous, per request; default true. false = not armed for this request */\n armed?(ctx: RequestContext): boolean;\n /** true = see the call after it was forwarded; can only warn; never holds the stream */\n observe?: boolean;\n handle(ctx: ToolCallContext): HookResult<ToolCallAction>;\n };\n responseRewrite?: {\n /** synchronous, per request, evaluated before the response starts; default true */\n claims?(ctx: RequestContext): boolean;\n handle(ctx: ResponseRewriteContext): HookResult<RewriteAction>;\n };\n responseEnd?(ctx: ResponseEndContext): HookResult<ResponseEndAction>;\n sessionStart?(ctx: SessionStartContext): HookResult<SessionAction>;\n sessionIdle?(ctx: SessionIdleContext): HookResult<SessionAction>;\n sessionBlocked?(ctx: SessionBlockedContext): HookResult<ObserveAction>;\n sessionEnd?(ctx: SessionEndContext): HookResult<ObserveAction>;\n }\n export interface RawProviderRequestContext {\n readonly hookId: string;\n readonly route: RouteInfo;\n claudeRequest: any;\n messages: any[];\n tools: any[];\n }\n export interface RawProviderChunkContext {\n readonly hookId: string;\n readonly route: RouteInfo;\n /** A clone of the parsed provider event. Whatever this field holds when the call returns is\n * what the parser reads from then on, so it may be edited in place or replaced. */\n chunk: any;\n /** The delta object inside `chunk` at call time (Responses wire: `chunk` itself). Edit it in\n * place; assigning a new object to this field has no effect. */\n delta: any;\n /** per-stream, shared across this hook\'s chunk calls; never cloned */\n metadata: Map<string, unknown>;\n }\n export interface RawProviderStreamEndContext {\n readonly hookId: string;\n readonly route: RouteInfo;\n metadata: Map<string, unknown>;\n }\n export interface RawResponseContext {\n readonly hookId: string;\n readonly route: RouteInfo;\n readonly request: RequestFacts;\n /** A replay of the current Claude-format response (SSE, or JSON for stream:false), read at the\n * hook\'s own pace. claudish drains the original itself, so leaving this unread delays nothing. */\n response: Response;\n }\n export interface RawMiddleware {\n /**\n * Receives clones. They replace the live request only when this call returns (or its promise\n * resolves) within its timeout. A throw, a rejection or a timeout discards every change.\n */\n providerRequest?(ctx: RawProviderRequestContext): void | Promise<void>;\n /**\n * MUST be synchronous. Called on the parser\'s loop, on a clone of the chunk. On a normal return\n * of anything but a thenable, the clone (whatever `ctx.chunk` holds then) is committed: it\n * becomes the object the parser reads, deletions included. On a throw nothing is committed.\n * A declared `async` function is rejected at load. Any other thenable return is an invalid\n * invocation: the clone is discarded even if the hook mutated it before returning, the call is\n * journaled `invalid` (`async_return`) and counts toward the circuit breaker, and a rejection\n * handler is attached, so a rejection is journaled `error` and never becomes an\n * unhandledRejection.\n */\n providerChunk?(ctx: RawProviderChunkContext): void;\n providerStreamEnd?(ctx: RawProviderStreamEndContext): void | Promise<void>;\n /**\n * Return a replacement Response, or nothing to keep the current one. A replacement is read\n * whole and forwarded only when it completes cleanly; on any failure the original is forwarded.\n * The client never sees a partial replacement. A replacement must close within this hook\'s\n * timeout after the later of this call\'s return and the end of the original; the original\'s end\n * never depends on whether `ctx.response` is read.\n */\n response?(ctx: RawResponseContext): Response | void | Promise<Response | void>;\n }\n interface HookBase {\n apiVersion: 1;\n id: string;\n description?: string;\n /** default "fix" for user hooks */\n defaultSeverity?: Severity;\n /** default "normal" */\n order?: HookOrder;\n /** globs on RouteInfo.modelId; default "*"; proxy events only */\n models?: string | ReadonlyArray<string>;\n /** default "all"; proxy events only */\n routes?: RouteScope;\n /** per call; clamped to the event\'s maximum and to the event budget left when the hook\'s turn comes */\n timeoutMs?: number;\n on?: HookHandlers;\n }\n export interface SafeHook extends HookBase {\n unsafe?: never;\n raw?: never;\n }\n export interface UnsafeHook extends HookBase {\n unsafe: true;\n raw: RawMiddleware;\n }\n /**\n * One hook. Module-level state is per process: in `create_session` and team\n * children, proxy events run in the pane child and session events in the MCP\n * server or CLI process. Pass per-turn data from proxy events to `sessionIdle`\n * with `annotateTurn`, never with module variables.\n */\n export type HookDefinition = SafeHook | UnsafeHook;\n /** Identity function: gives editor type-checking and inference. */\n export function defineHook<const H extends HookDefinition>(hook: H): H;\n /** Action constructors (plain data; equivalent to writing the object literal). */\n export const act: {\n injectSystemNote(text: string): InjectSystemNote;\n appendUserText(text: string): AppendUserText;\n replaceMessageText(find: string, replace: string, opts?: {\n regex?: boolean;\n flags?: string;\n roles?: ReadonlyArray<"user" | "assistant">;\n }): ReplaceMessageText;\n removeMessageText(find: string, opts?: {\n regex?: boolean;\n flags?: string;\n roles?: ReadonlyArray<"user" | "assistant">;\n }): RemoveMessageText;\n rewriteToolDescription(tool: string, append: string): RewriteToolDescription;\n replaceToolDescription(tool: string, description: string): ReplaceToolDescription;\n replaceToolSchema(tool: string, inputSchema: {\n type: "object";\n [k: string]: unknown;\n }): ReplaceToolSchema;\n removeTool(tool: string): RemoveTool;\n repairToolArgs(args: Record<string, unknown>, reason: string): RepairToolArgs;\n appendText(text: string): AppendText;\n prependText(text: string): PrependText;\n replaceText(find: string, replace: string, opts?: {\n regex?: boolean;\n flags?: string;\n }): ReplaceText;\n removeText(find: string, opts?: {\n regex?: boolean;\n flags?: string;\n }): RemoveText;\n injectUserTurn(text: string): InjectUserTurn;\n annotateTurn(key: string, value: JsonValue): AnnotateTurn;\n warn(message: string): Warn;\n };\n}\n';
134708
134230
 
134709
134231
  // src/hooks/observer/corpus.ts
134710
- import { appendFileSync as appendFileSync8, readFileSync as readFileSync56, readdirSync as readdirSync20, statSync as statSync31 } from "fs";
134711
- import { homedir as homedir42 } from "os";
134712
- import { join as join73 } from "path";
134232
+ import { appendFileSync as appendFileSync8, readFileSync as readFileSync56, readdirSync as readdirSync19, statSync as statSync30 } from "fs";
134233
+ import { homedir as homedir44 } from "os";
134234
+ import { join as join74 } from "path";
134713
134235
  function directoryOf2(filePath) {
134714
134236
  const slash = filePath.lastIndexOf("/");
134715
134237
  return slash > 0 ? filePath.slice(0, slash) : undefined;
@@ -134783,18 +134305,18 @@ function listTranscripts(root) {
134783
134305
  const files = [];
134784
134306
  let projects;
134785
134307
  try {
134786
- projects = readdirSync20(root);
134308
+ projects = readdirSync19(root);
134787
134309
  } catch {
134788
134310
  return files;
134789
134311
  }
134790
134312
  for (const project of projects) {
134791
- const dir = join73(root, project);
134313
+ const dir = join74(root, project);
134792
134314
  try {
134793
- if (!statSync31(dir).isDirectory())
134315
+ if (!statSync30(dir).isDirectory())
134794
134316
  continue;
134795
- for (const f of readdirSync20(dir)) {
134317
+ for (const f of readdirSync19(dir)) {
134796
134318
  if (f.endsWith(".jsonl"))
134797
- files.push(join73(dir, f));
134319
+ files.push(join74(dir, f));
134798
134320
  }
134799
134321
  } catch {}
134800
134322
  }
@@ -134807,7 +134329,7 @@ function buildCorpus(options = {}) {
134807
134329
  for (const f of files)
134808
134330
  records.push(...replayTranscript(f));
134809
134331
  if (options.write && records.length > 0) {
134810
- const outputPath = options.outputPath ?? join73(homedir42(), ".claudish", "behavior-divergences.jsonl");
134332
+ const outputPath = options.outputPath ?? join74(homedir44(), ".claudish", "behavior-divergences.jsonl");
134811
134333
  try {
134812
134334
  appendFileSync8(outputPath, `${records.map((r) => JSON.stringify(r)).join(`
134813
134335
  `)}
@@ -134824,9 +134346,9 @@ var init_corpus = __esm(() => {
134824
134346
  });
134825
134347
 
134826
134348
  // src/hooks-command.ts
134827
- import { existsSync as existsSync46, mkdirSync as mkdirSync29, readFileSync as readFileSync57, writeFileSync as writeFileSync30 } from "fs";
134828
- import { homedir as homedir43 } from "os";
134829
- import { join as join74, resolve as resolve14 } from "path";
134349
+ import { existsSync as existsSync46, mkdirSync as mkdirSync30, readFileSync as readFileSync57, writeFileSync as writeFileSync30 } from "fs";
134350
+ import { homedir as homedir45 } from "os";
134351
+ import { join as join75, resolve as resolve14 } from "path";
134830
134352
  function severityColor(sev) {
134831
134353
  if (sev === "fix")
134832
134354
  return green(sev);
@@ -134949,10 +134471,10 @@ async function check(file, json) {
134949
134471
  return valid ? 0 : 1;
134950
134472
  }
134951
134473
  function init(dirArg) {
134952
- const dir = dirArg ? resolve14(process.cwd(), dirArg) : join74(homedir43(), ".claudish", "hooks");
134474
+ const dir = dirArg ? resolve14(process.cwd(), dirArg) : join75(homedir45(), ".claudish", "hooks");
134953
134475
  const files = [
134954
- [join74(dir, "example-hook.ts"), EXAMPLE_HOOK],
134955
- [join74(dir, "claudish-hooks.d.ts"), HOOKS_AMBIENT_DTS]
134476
+ [join75(dir, "example-hook.ts"), EXAMPLE_HOOK],
134477
+ [join75(dir, "claudish-hooks.d.ts"), HOOKS_AMBIENT_DTS]
134956
134478
  ];
134957
134479
  const existing = files.filter(([path]) => existsSync46(path)).map(([path]) => path);
134958
134480
  if (existing.length > 0) {
@@ -134960,7 +134482,7 @@ function init(dirArg) {
134960
134482
  console.error(`${path} already exists; not overwriting it.`);
134961
134483
  return 1;
134962
134484
  }
134963
- mkdirSync29(dir, { recursive: true });
134485
+ mkdirSync30(dir, { recursive: true });
134964
134486
  for (const [path, text] of files)
134965
134487
  writeFileSync30(path, text, { flag: "wx" });
134966
134488
  console.log(`
@@ -135152,10 +134674,10 @@ var init_hooks_command = __esm(() => {
135152
134674
  });
135153
134675
 
135154
134676
  // src/team-grid.ts
135155
- import { spawn as spawn6 } from "child_process";
134677
+ import { spawn as spawn5 } from "child_process";
135156
134678
  import { existsSync as existsSync47, readFileSync as readFileSync58, writeFileSync as writeFileSync31 } from "fs";
135157
134679
  import { connect as netConnect3 } from "net";
135158
- import { join as join75 } from "path";
134680
+ import { join as join76 } from "path";
135159
134681
  import { setTimeout as wait } from "timers/promises";
135160
134682
  function paneRouteLine(explanation) {
135161
134683
  const origin = describeRouteExplanation(explanation);
@@ -135305,9 +134827,9 @@ async function runWithGrid(sessionPath, models, input, opts) {
135305
134827
  const keep = opts?.keep ?? false;
135306
134828
  const manifest = setupSession(sessionPath, models, input);
135307
134829
  const startedAt = new Date().toISOString();
135308
- const gridfilePath = join75(sessionPath, "gridfile.txt");
135309
- const prompt = readFileSync58(join75(sessionPath, "input.md"), "utf-8").replace(/'/g, "'\\''").replace(/\n/g, " ");
135310
- const rawPrompt = readFileSync58(join75(sessionPath, "input.md"), "utf-8");
134830
+ const gridfilePath = join76(sessionPath, "gridfile.txt");
134831
+ const prompt = readFileSync58(join76(sessionPath, "input.md"), "utf-8").replace(/'/g, "'\\''").replace(/\n/g, " ");
134832
+ const rawPrompt = readFileSync58(join76(sessionPath, "input.md"), "utf-8");
135311
134833
  const usedBannerColors = new Set;
135312
134834
  const routeLines = mode === "interactive" ? new Map : await resolvePaneRouteLines(Object.values(manifest.models).map((entry) => entry.model));
135313
134835
  const gridLines = Object.entries(manifest.models).map(([anonId]) => {
@@ -135327,7 +134849,7 @@ async function runWithGrid(sessionPath, models, input, opts) {
135327
134849
  if (!keep && mode === "default") {
135328
134850
  spawnArgs.push("-w");
135329
134851
  }
135330
- const proc = spawn6(magmuxPath, spawnArgs, {
134852
+ const proc = spawn5(magmuxPath, spawnArgs, {
135331
134853
  stdio: "inherit",
135332
134854
  env: { ...process.env }
135333
134855
  });
@@ -135339,7 +134861,7 @@ async function runWithGrid(sessionPath, models, input, opts) {
135339
134861
  });
135340
134862
  const [{ results }] = await Promise.all([subscription, procExit]);
135341
134863
  const status = buildTeamStatus(manifest, startedAt, results?.panes ?? null);
135342
- const statusPath = join75(sessionPath, "status.json");
134864
+ const statusPath = join76(sessionPath, "status.json");
135343
134865
  writeFileSync31(statusPath, JSON.stringify(status, null, 2), "utf-8");
135344
134866
  return status;
135345
134867
  }
@@ -135360,7 +134882,7 @@ var init_team_grid = __esm(() => {
135360
134882
 
135361
134883
  // src/team-cli.ts
135362
134884
  import { readFileSync as readFileSync59 } from "fs";
135363
- import { join as join76 } from "path";
134885
+ import { join as join77 } from "path";
135364
134886
  async function runPaneTeam(sessionPath, models, input, opts) {
135365
134887
  installPaneShutdownHooks({ exitAfter: true });
135366
134888
  try {
@@ -135505,7 +135027,7 @@ async function teamCommand(args) {
135505
135027
  }
135506
135028
  case "judge": {
135507
135029
  await judgeResponses(sessionPath, { judges });
135508
- console.log(readFileSync59(join76(sessionPath, "verdict.md"), "utf-8"));
135030
+ console.log(readFileSync59(join77(sessionPath, "verdict.md"), "utf-8"));
135509
135031
  break;
135510
135032
  }
135511
135033
  case "run-and-judge": {
@@ -135521,7 +135043,7 @@ async function teamCommand(args) {
135521
135043
  });
135522
135044
  printStatus(status);
135523
135045
  await judgeResponses(sessionPath, { judges });
135524
- console.log(readFileSync59(join76(sessionPath, "verdict.md"), "utf-8"));
135046
+ console.log(readFileSync59(join77(sessionPath, "verdict.md"), "utf-8"));
135525
135047
  break;
135526
135048
  }
135527
135049
  case "status": {
@@ -137204,9 +136726,9 @@ var init_view_cli = __esm(() => {
137204
136726
 
137205
136727
  // src/herdr/herdr-cli.ts
137206
136728
  import { spawnSync as spawnSync4 } from "child_process";
137207
- import { copyFileSync as copyFileSync3, existsSync as existsSync48, mkdirSync as mkdirSync30, readdirSync as readdirSync21, renameSync as renameSync14, statSync as statSync32 } from "fs";
137208
- import { homedir as homedir44 } from "os";
137209
- import { dirname as dirname30, join as join77, resolve as resolve15 } from "path";
136729
+ import { copyFileSync as copyFileSync3, existsSync as existsSync48, mkdirSync as mkdirSync31, readdirSync as readdirSync20, renameSync as renameSync15, statSync as statSync31 } from "fs";
136730
+ import { homedir as homedir46 } from "os";
136731
+ import { dirname as dirname31, join as join78, resolve as resolve15 } from "path";
137210
136732
  function spawnHerdrApp(args) {
137211
136733
  const r = spawnSync4("herdr-app", args, { encoding: "utf-8", timeout: 1e4 });
137212
136734
  if (r.error)
@@ -137248,10 +136770,10 @@ function showPanelCommand(rest, out, deps) {
137248
136770
  function findBuiltAppMod(from = import.meta.dir) {
137249
136771
  let dir = from;
137250
136772
  for (let i = 0;i < 5; i++) {
137251
- const candidate = join77(dir, BUILT_MOD_DIR);
137252
- if (existsSync48(join77(candidate, "main.js")) && existsSync48(join77(candidate, "mod.json")))
136773
+ const candidate = join78(dir, BUILT_MOD_DIR);
136774
+ if (existsSync48(join78(candidate, "main.js")) && existsSync48(join78(candidate, "mod.json")))
137253
136775
  return candidate;
137254
- const up = dirname30(dir);
136776
+ const up = dirname31(dir);
137255
136777
  if (up === dir)
137256
136778
  break;
137257
136779
  dir = up;
@@ -137262,24 +136784,24 @@ function herdrAppHome(env) {
137262
136784
  const given = env.HERDR_APP_HOME?.trim();
137263
136785
  if (given)
137264
136786
  return resolve15(given);
137265
- return join77(env.HOME?.trim() || homedir44(), ".config", "herdr-app");
136787
+ return join78(env.HOME?.trim() || homedir46(), ".config", "herdr-app");
137266
136788
  }
137267
136789
  function isModFile(name) {
137268
136790
  return !name.startsWith(".") && name !== "jsconfig.json" && !name.endsWith(".d.ts");
137269
136791
  }
137270
136792
  function installAppMod(source, appHome) {
137271
- if (!existsSync48(join77(source, "main.js")) || !existsSync48(join77(source, "mod.json")))
136793
+ if (!existsSync48(join78(source, "main.js")) || !existsSync48(join78(source, "mod.json")))
137272
136794
  throw new Error(`${source} holds no built mod (main.js and mod.json); run \`bun run build\``);
137273
- if (!existsSync48(appHome) || !statSync32(appHome).isDirectory())
136795
+ if (!existsSync48(appHome) || !statSync31(appHome).isDirectory())
137274
136796
  throw new Error(`${appHome} does not exist: start Herdr.app once so it creates its home, then run this again`);
137275
- const dest = join77(appHome, "mods", APP_MOD_NAME);
137276
- mkdirSync30(dest, { recursive: true });
137277
- const files = readdirSync21(source).filter((f) => isModFile(f) && statSync32(join77(source, f)).isFile());
136797
+ const dest = join78(appHome, "mods", APP_MOD_NAME);
136798
+ mkdirSync31(dest, { recursive: true });
136799
+ const files = readdirSync20(source).filter((f) => isModFile(f) && statSync31(join78(source, f)).isFile());
137278
136800
  files.sort((a, b) => a === "mod.json" ? -1 : b === "mod.json" ? 1 : a.localeCompare(b));
137279
136801
  for (const f of files) {
137280
- const hidden = join77(dest, `.${f}.installing`);
137281
- copyFileSync3(join77(source, f), hidden);
137282
- renameSync14(hidden, join77(dest, f));
136802
+ const hidden = join78(dest, `.${f}.installing`);
136803
+ copyFileSync3(join78(source, f), hidden);
136804
+ renameSync15(hidden, join78(dest, f));
137283
136805
  }
137284
136806
  return dest;
137285
136807
  }
@@ -137357,7 +136879,7 @@ var init_herdr_cli = __esm(() => {
137357
136879
  ""
137358
136880
  ].join(`
137359
136881
  `);
137360
- BUILT_MOD_DIR = join77("herdr-app-mod", APP_MOD_NAME);
136882
+ BUILT_MOD_DIR = join78("herdr-app-mod", APP_MOD_NAME);
137361
136883
  });
137362
136884
 
137363
136885
  // src/auth/credentials/source.ts
@@ -139718,9 +139240,9 @@ var init_account_command = __esm(() => {
139718
139240
 
139719
139241
  // src/auth/antigravity-oauth.ts
139720
139242
  import { spawnSync as spawnSync5 } from "child_process";
139721
- import { existsSync as existsSync49, unlinkSync as unlinkSync14 } from "fs";
139722
- import { homedir as homedir45 } from "os";
139723
- import { join as join78 } from "path";
139243
+ import { existsSync as existsSync49, unlinkSync as unlinkSync15 } from "fs";
139244
+ import { homedir as homedir47 } from "os";
139245
+ import { join as join79 } from "path";
139724
139246
  async function defaultSuggestModel() {
139725
139247
  try {
139726
139248
  const token = await getValidAntigravityAccessToken();
@@ -139839,9 +139361,9 @@ No session detected yet. Starting the Antigravity CLI interactively \u2014
139839
139361
  async logout(deps) {
139840
139362
  deleteSharedAntigravityToken(deps);
139841
139363
  try {
139842
- const tokenFile = join78(homedir45(), ".gemini", "antigravity-cli", "antigravity-oauth-token");
139364
+ const tokenFile = join79(homedir47(), ".gemini", "antigravity-cli", "antigravity-oauth-token");
139843
139365
  if (existsSync49(tokenFile))
139844
- unlinkSync14(tokenFile);
139366
+ unlinkSync15(tokenFile);
139845
139367
  } catch {}
139846
139368
  log("[AntigravityOAuth] Antigravity session cleared (keychain + agy token file)");
139847
139369
  }
@@ -149254,18 +148776,18 @@ var init_model_lineup = __esm(() => {
149254
148776
  });
149255
148777
 
149256
148778
  // src/diag-output.ts
149257
- import { createWriteStream as createWriteStream2, mkdirSync as mkdirSync31, unlinkSync as unlinkSync15, writeFileSync as writeFileSync32 } from "fs";
149258
- import { homedir as homedir46 } from "os";
149259
- import { join as join79 } from "path";
148779
+ import { createWriteStream as createWriteStream2, mkdirSync as mkdirSync32, unlinkSync as unlinkSync16, writeFileSync as writeFileSync32 } from "fs";
148780
+ import { homedir as homedir48 } from "os";
148781
+ import { join as join80 } from "path";
149260
148782
  function getClaudishDir() {
149261
- const dir = join79(homedir46(), ".claudish");
148783
+ const dir = join80(homedir48(), ".claudish");
149262
148784
  try {
149263
- mkdirSync31(dir, { recursive: true });
148785
+ mkdirSync32(dir, { recursive: true });
149264
148786
  } catch {}
149265
148787
  return dir;
149266
148788
  }
149267
148789
  function getDiagLogPath() {
149268
- return join79(getClaudishDir(), `diag-${process.pid}.log`);
148790
+ return join80(getClaudishDir(), `diag-${process.pid}.log`);
149269
148791
  }
149270
148792
 
149271
148793
  class LogFileDiagOutput {
@@ -149293,7 +148815,7 @@ class LogFileDiagOutput {
149293
148815
  this.stream.end();
149294
148816
  } catch {}
149295
148817
  try {
149296
- unlinkSync15(this.logPath);
148818
+ unlinkSync16(this.logPath);
149297
148819
  } catch {}
149298
148820
  }
149299
148821
  getLogPath() {
@@ -149676,7 +149198,7 @@ var init_advisor_startup = __esm(() => {
149676
149198
  });
149677
149199
 
149678
149200
  // src/session/conversation.ts
149679
- import { closeSync as closeSync23, openSync as openSync22, readSync as readSync11, statSync as statSync33 } from "fs";
149201
+ import { closeSync as closeSync24, openSync as openSync23, readSync as readSync12, statSync as statSync32 } from "fs";
149680
149202
  import { StringDecoder } from "string_decoder";
149681
149203
  function looksLikeTurn(line) {
149682
149204
  const assistant = line.includes('"type":"assistant"');
@@ -149731,8 +149253,8 @@ function readConversation(file, opts = {}) {
149731
149253
  };
149732
149254
  let fd = null;
149733
149255
  try {
149734
- const size = statSync33(file).size;
149735
- fd = openSync22(file, "r");
149256
+ const size = statSync32(file).size;
149257
+ fd = openSync23(file, "r");
149736
149258
  const buf = Buffer.allocUnsafe(chunkBytes);
149737
149259
  const decoder = new StringDecoder("utf-8");
149738
149260
  let pending = "";
@@ -149764,7 +149286,7 @@ function readConversation(file, opts = {}) {
149764
149286
  take({ role: raw.role, text, elided });
149765
149287
  };
149766
149288
  while (pos < size) {
149767
- const n = readSync11(fd, buf, 0, Math.min(chunkBytes, size - pos), pos);
149289
+ const n = readSync12(fd, buf, 0, Math.min(chunkBytes, size - pos), pos);
149768
149290
  if (n <= 0)
149769
149291
  break;
149770
149292
  pos += n;
@@ -149788,7 +149310,7 @@ function readConversation(file, opts = {}) {
149788
149310
  } catch {} finally {
149789
149311
  if (fd !== null) {
149790
149312
  try {
149791
- closeSync23(fd);
149313
+ closeSync24(fd);
149792
149314
  } catch {}
149793
149315
  }
149794
149316
  }
@@ -151356,11 +150878,11 @@ var init_resume_picker_run = __esm(() => {
151356
150878
  });
151357
150879
 
151358
150880
  // src/launcher/model-setting-ledger-path.ts
151359
- import { homedir as homedir47 } from "os";
151360
- import { join as join80 } from "path";
150881
+ import { homedir as homedir49 } from "os";
150882
+ import { join as join81 } from "path";
151361
150883
  function modelSettingLedgerPath(env = process.env) {
151362
- const home = env.HOME && env.HOME.length > 0 ? env.HOME : homedir47();
151363
- return join80(home, ".claudish", MODEL_SETTING_LEDGER_FILE);
150884
+ const home = env.HOME && env.HOME.length > 0 ? env.HOME : homedir49();
150885
+ return join81(home, ".claudish", MODEL_SETTING_LEDGER_FILE);
151364
150886
  }
151365
150887
  var MODEL_SETTING_LEDGER_FILE = "model-setting-restore.json";
151366
150888
  var init_model_setting_ledger_path = () => {};
@@ -151368,32 +150890,32 @@ var init_model_setting_ledger_path = () => {};
151368
150890
  // src/launcher/model-setting-restore.ts
151369
150891
  import { randomUUID as randomUUID12 } from "crypto";
151370
150892
  import {
151371
- closeSync as closeSync24,
150893
+ closeSync as closeSync25,
151372
150894
  fchmodSync as fchmodSync2,
151373
- fsyncSync as fsyncSync4,
151374
- openSync as openSync23,
150895
+ fsyncSync as fsyncSync5,
150896
+ openSync as openSync24,
151375
150897
  readFileSync as readFileSync60,
151376
- readdirSync as readdirSync22,
151377
- realpathSync as realpathSync13,
151378
- renameSync as renameSync15,
151379
- rmSync as rmSync23,
151380
- statSync as statSync34,
151381
- unlinkSync as unlinkSync16,
151382
- writeSync as writeSync8
150898
+ readdirSync as readdirSync21,
150899
+ realpathSync as realpathSync14,
150900
+ renameSync as renameSync16,
150901
+ rmSync as rmSync22,
150902
+ statSync as statSync33,
150903
+ unlinkSync as unlinkSync17,
150904
+ writeSync as writeSync9
151383
150905
  } from "fs";
151384
- import { homedir as homedir48 } from "os";
151385
- import { basename as basename13, dirname as dirname31, join as join81, resolve as resolve16 } from "path";
150906
+ import { homedir as homedir50 } from "os";
150907
+ import { basename as basename14, dirname as dirname32, join as join82, resolve as resolve16 } from "path";
151386
150908
  function canonicalSettingsPath(path) {
151387
150909
  let head = resolve16(path);
151388
150910
  const rest = [];
151389
150911
  for (;; ) {
151390
150912
  try {
151391
- return join81(realpathSync13.native(head), ...rest);
150913
+ return join82(realpathSync14.native(head), ...rest);
151392
150914
  } catch {
151393
- const parent = dirname31(head);
150915
+ const parent = dirname32(head);
151394
150916
  if (parent === head)
151395
- return join81(head, ...rest);
151396
- rest.unshift(basename13(head));
150917
+ return join82(head, ...rest);
150918
+ rest.unshift(basename14(head));
151397
150919
  head = parent;
151398
150920
  }
151399
150921
  }
@@ -151414,7 +150936,7 @@ function toFileStat(s) {
151414
150936
  function sameStat(a, b) {
151415
150937
  return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.mode === b.mode;
151416
150938
  }
151417
- function writeWholeSync(fd, data, write = (f, b, o, l) => writeSync8(f, b, o, l)) {
150939
+ function writeWholeSync(fd, data, write = (f, b, o, l) => writeSync9(f, b, o, l)) {
151418
150940
  const bytes = Buffer.from(data, "utf8");
151419
150941
  let offset = 0;
151420
150942
  while (offset < bytes.length) {
@@ -151432,7 +150954,7 @@ function detectIndent(text) {
151432
150954
  const m = text.match(/^\{\s*?\n([ \t]+)\S/);
151433
150955
  return m?.[1] ? m[1] : 2;
151434
150956
  }
151435
- function isPlainObject9(value) {
150957
+ function isPlainObject10(value) {
151436
150958
  return value !== null && typeof value === "object" && !Array.isArray(value);
151437
150959
  }
151438
150960
  function restoreSettingsFile(settingsKey, entry, deps = realRestoreFs, fence = () => true) {
@@ -151456,7 +150978,7 @@ function nextSettingsText(text, entry) {
151456
150978
  } catch {
151457
150979
  return { outcome: "unparsable" };
151458
150980
  }
151459
- if (!isPlainObject9(parsed))
150981
+ if (!isPlainObject10(parsed))
151460
150982
  return { outcome: "unparsable" };
151461
150983
  const decision = restoreDecision(parsed.model, entry);
151462
150984
  if (decision.action === "leave")
@@ -151488,7 +151010,7 @@ function restoreRound(settingsKey, target, entry, deps, fence) {
151488
151010
  const planned = nextSettingsText(text, entry);
151489
151011
  if ("outcome" in planned)
151490
151012
  return planned.outcome;
151491
- const temp = join81(dirname31(target), `${TEMP_PREFIX}${deps.pid ?? process.pid}-${randomUUID12()}`);
151013
+ const temp = join82(dirname32(target), `${TEMP_PREFIX}${deps.pid ?? process.pid}-${randomUUID12()}`);
151492
151014
  try {
151493
151015
  deps.writeNew(temp, planned.next, statA.mode & 4095);
151494
151016
  } catch {
@@ -151535,7 +151057,7 @@ function readLedger2(path) {
151535
151057
  log(`[model-restore] ledger unparsable (${path}): ${err.message}`);
151536
151058
  return { ok: false, reason: "unparsable" };
151537
151059
  }
151538
- if (parsed?.version !== 1 || !isPlainObject9(parsed.entries)) {
151060
+ if (parsed?.version !== 1 || !isPlainObject10(parsed.entries)) {
151539
151061
  log(`[model-restore] ledger of unknown shape (${path})`);
151540
151062
  return { ok: false, reason: "unknown-shape" };
151541
151063
  }
@@ -151554,7 +151076,7 @@ function writeLedger(path, ledger, fence) {
151554
151076
  return false;
151555
151077
  }
151556
151078
  if (Object.keys(ledger.entries).length === 0) {
151557
- rmSync23(path, { force: true });
151079
+ rmSync22(path, { force: true });
151558
151080
  return true;
151559
151081
  }
151560
151082
  atomicWriteFileSync(path, `${JSON.stringify(ledger, null, 2)}
@@ -151659,14 +151181,14 @@ function settleEntry(ctx, ledger, key, silent, fence) {
151659
151181
  }
151660
151182
  }
151661
151183
  function removeOrphanTemps(ctx, key, table) {
151662
- const dirs = new Set([dirname31(key)]);
151184
+ const dirs = new Set([dirname32(key)]);
151663
151185
  try {
151664
- dirs.add(dirname31(ctx.fs.realpath(key)));
151186
+ dirs.add(dirname32(ctx.fs.realpath(key)));
151665
151187
  } catch {}
151666
151188
  for (const dir of dirs) {
151667
151189
  let names;
151668
151190
  try {
151669
- names = readdirSync22(dir);
151191
+ names = readdirSync21(dir);
151670
151192
  } catch {
151671
151193
  continue;
151672
151194
  }
@@ -151680,7 +151202,7 @@ function removeOrphanTemps(ctx, key, table) {
151680
151202
  if (live)
151681
151203
  continue;
151682
151204
  try {
151683
- unlinkSync16(join81(dir, name));
151205
+ unlinkSync17(join82(dir, name));
151684
151206
  } catch {}
151685
151207
  }
151686
151208
  }
@@ -151758,7 +151280,7 @@ function readOriginal(ctx, key) {
151758
151280
  }
151759
151281
  try {
151760
151282
  const parsed = JSON.parse(text);
151761
- if (!isPlainObject9(parsed))
151283
+ if (!isPlainObject10(parsed))
151762
151284
  return null;
151763
151285
  return "model" in parsed ? { present: true, value: parsed.model } : { present: false };
151764
151286
  } catch {
@@ -151771,7 +151293,7 @@ function selfStartEpochMs() {
151771
151293
  async function beginModelSettingWatch(listedSpecs, deps = {}) {
151772
151294
  const ctx = contextOf(deps);
151773
151295
  const env = deps.env ?? process.env;
151774
- const settingsFile = deps.settingsFile ?? userSettingsFile(env.CLAUDE_CONFIG_DIR, env.HOME && env.HOME.length > 0 ? env.HOME : homedir48(), deps.cwd ?? process.cwd());
151296
+ const settingsFile = deps.settingsFile ?? userSettingsFile(env.CLAUDE_CONFIG_DIR, env.HOME && env.HOME.length > 0 ? env.HOME : homedir50(), deps.cwd ?? process.cwd());
151775
151297
  const key = canonicalSettingsPath(settingsFile);
151776
151298
  const lockPath = lockPathOf(ctx.ledgerPath);
151777
151299
  const lockOpts = {
@@ -151934,21 +151456,21 @@ var init_model_setting_restore = __esm(() => {
151934
151456
  init_model_setting_ledger_path();
151935
151457
  GIVE_UP_AFTER_MS = 14 * 24 * 60 * 60 * 1000;
151936
151458
  realRestoreFs = {
151937
- realpath: (path) => realpathSync13.native(path),
151459
+ realpath: (path) => realpathSync14.native(path),
151938
151460
  readFile: (path) => readFileSync60(path),
151939
- stat: (path) => toFileStat(statSync34(path)),
151461
+ stat: (path) => toFileStat(statSync33(path)),
151940
151462
  writeNew: (path, data, mode) => {
151941
- const fd = openSync23(path, "wx", mode);
151463
+ const fd = openSync24(path, "wx", mode);
151942
151464
  try {
151943
151465
  fchmodSync2(fd, mode);
151944
151466
  writeWholeSync(fd, data);
151945
- fsyncSync4(fd);
151467
+ fsyncSync5(fd);
151946
151468
  } finally {
151947
- closeSync24(fd);
151469
+ closeSync25(fd);
151948
151470
  }
151949
151471
  },
151950
- rename: (from, to) => renameSync15(from, to),
151951
- unlink: (path) => unlinkSync16(path)
151472
+ rename: (from, to) => renameSync16(from, to),
151473
+ unlink: (path) => unlinkSync17(path)
151952
151474
  };
151953
151475
  reportedUnreadableLedgers = new Set;
151954
151476
  INERT_WATCH = {
@@ -151961,8 +151483,8 @@ var init_model_setting_restore = __esm(() => {
151961
151483
  });
151962
151484
 
151963
151485
  // src/session/baseline-pricing.ts
151964
- function resolveBaseline(alias, label) {
151965
- const entry = findEntryByAlias(alias);
151486
+ function resolveBaseline({ tier, label }) {
151487
+ const entry = implicitAnthropicTierEntry(tier);
151966
151488
  if (!entry)
151967
151489
  return null;
151968
151490
  const firstParty = entry.aggregators?.find((a) => catalogRouteMatchesProvider(a.route, FIRST_PARTY) && typeof a.pricing?.input === "number");
@@ -151975,18 +151497,18 @@ function resolveBaseline(alias, label) {
151975
151497
  return { modelId: entry.modelId, label, inputPerM: input, outputPerM: output };
151976
151498
  }
151977
151499
  function getBaselines() {
151978
- return BASELINE_ALIASES.map(({ alias, label }) => resolveBaseline(alias, label)).filter((b) => b !== null);
151500
+ return BASELINE_TIERS.map(resolveBaseline).filter((b) => b !== null);
151979
151501
  }
151980
151502
  function baselineCost(b, inputTokens, outputTokens) {
151981
151503
  return inputTokens / 1e6 * b.inputPerM + outputTokens / 1e6 * b.outputPerM;
151982
151504
  }
151983
- var BASELINE_ALIASES, FIRST_PARTY = "anthropic";
151505
+ var BASELINE_TIERS, FIRST_PARTY = "anthropic";
151984
151506
  var init_baseline_pricing = __esm(() => {
151507
+ init_catalog_client();
151985
151508
  init_catalog_route_bindings();
151986
- init_catalog_query();
151987
- BASELINE_ALIASES = [
151988
- { alias: "~anthropic/claude-sonnet-latest", label: "Sonnet" },
151989
- { alias: "~anthropic/claude-opus-latest", label: "Opus" }
151509
+ BASELINE_TIERS = [
151510
+ { tier: "sonnet", label: "Sonnet" },
151511
+ { tier: "opus", label: "Opus" }
151990
151512
  ];
151991
151513
  });
151992
151514
 
@@ -152384,10 +151906,11 @@ var droppedAtLaunch = dropAtLaunch();
152384
151906
  init_child_env();
152385
151907
  init_launch_env();
152386
151908
  init_op_source();
151909
+ init_classifier_passthrough();
152387
151910
  init_startup_trace();
152388
151911
  init_picker_cancelled();
152389
151912
  import { existsSync as existsSync50, readFileSync as readFileSync62 } from "fs";
152390
- import { join as join82, resolve as resolve17 } from "path";
151913
+ import { join as join83, resolve as resolve17 } from "path";
152391
151914
 
152392
151915
  // src/tui/runtime/should-open-picker.ts
152393
151916
  function noModelConfigured(gate) {
@@ -152404,7 +151927,7 @@ function requiresExplicitModel(gate, tty) {
152404
151927
  var autoloadDropped = [...droppedAtLaunch, ...takeLauncherDropped(process.env)];
152405
151928
  var dotenvText;
152406
151929
  try {
152407
- dotenvText = readFileSync62(join82(process.cwd(), ".env"));
151930
+ dotenvText = readFileSync62(join83(process.cwd(), ".env"));
152408
151931
  } catch {}
152409
151932
  if (dotenvText !== undefined) {
152410
151933
  await Promise.resolve().then(() => init_dotenv_allowlist());
@@ -152810,7 +152333,7 @@ async function runCli() {
152810
152333
  process.exit(1);
152811
152334
  }
152812
152335
  const mode = cliConfig.teamMode ?? "default";
152813
- const sessionPath = join82(process.cwd(), `.claudish-team-${Date.now()}`);
152336
+ const sessionPath = join83(process.cwd(), `.claudish-team-${Date.now()}`);
152814
152337
  if (mode === "json") {
152815
152338
  await Promise.resolve().then(() => init_pane());
152816
152339
  await Promise.resolve().then(() => init_team_orchestrator());
@@ -152830,7 +152353,7 @@ async function runCli() {
152830
152353
  const status = await runModels(sessionPath);
152831
152354
  const result = { ...status, responses: {} };
152832
152355
  for (const anonId of Object.keys(status.models)) {
152833
- const responsePath = join82(sessionPath, `response-${anonId}.md`);
152356
+ const responsePath = join83(sessionPath, `response-${anonId}.md`);
152834
152357
  try {
152835
152358
  const raw = readFileSync62(responsePath, "utf-8").trim();
152836
152359
  try {