@adhdev/daemon-standalone 1.0.58-rc.45 → 1.0.58-rc.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31672,9 +31672,9 @@ var require_streamx = __commonJS({
31672
31672
  }
31673
31673
  });
31674
31674
 
31675
- // ../../node_modules/tar-stream/node_modules/b4a/index.js
31675
+ // ../daemon-core/node_modules/b4a/index.js
31676
31676
  var require_b4a2 = __commonJS({
31677
- "../../node_modules/tar-stream/node_modules/b4a/index.js"(exports2, module2) {
31677
+ "../daemon-core/node_modules/b4a/index.js"(exports2, module2) {
31678
31678
  "use strict";
31679
31679
  function isBuffer(value) {
31680
31680
  return Buffer.isBuffer(value) || value instanceof Uint8Array;
@@ -31830,9 +31830,9 @@ var require_b4a2 = __commonJS({
31830
31830
  }
31831
31831
  });
31832
31832
 
31833
- // ../../node_modules/tar-stream/headers.js
31833
+ // ../daemon-core/node_modules/tar-stream/headers.js
31834
31834
  var require_headers = __commonJS({
31835
- "../../node_modules/tar-stream/headers.js"(exports2) {
31835
+ "../daemon-core/node_modules/tar-stream/headers.js"(exports2) {
31836
31836
  "use strict";
31837
31837
  var b4a = require_b4a2();
31838
31838
  var ZEROS = "0000000000000000000";
@@ -32093,9 +32093,9 @@ var require_headers = __commonJS({
32093
32093
  }
32094
32094
  });
32095
32095
 
32096
- // ../../node_modules/tar-stream/extract.js
32096
+ // ../daemon-core/node_modules/tar-stream/extract.js
32097
32097
  var require_extract = __commonJS({
32098
- "../../node_modules/tar-stream/extract.js"(exports2, module2) {
32098
+ "../daemon-core/node_modules/tar-stream/extract.js"(exports2, module2) {
32099
32099
  "use strict";
32100
32100
  var { Writable, Readable, getStreamError } = require_streamx();
32101
32101
  var FIFO = require_fast_fifo();
@@ -32438,9 +32438,9 @@ var require_extract = __commonJS({
32438
32438
  }
32439
32439
  });
32440
32440
 
32441
- // ../../node_modules/tar-stream/constants.js
32441
+ // ../daemon-core/node_modules/tar-stream/constants.js
32442
32442
  var require_constants = __commonJS({
32443
- "../../node_modules/tar-stream/constants.js"(exports2, module2) {
32443
+ "../daemon-core/node_modules/tar-stream/constants.js"(exports2, module2) {
32444
32444
  "use strict";
32445
32445
  var constants = {
32446
32446
  // just for envs without fs
@@ -32459,9 +32459,9 @@ var require_constants = __commonJS({
32459
32459
  }
32460
32460
  });
32461
32461
 
32462
- // ../../node_modules/tar-stream/pack.js
32462
+ // ../daemon-core/node_modules/tar-stream/pack.js
32463
32463
  var require_pack = __commonJS({
32464
- "../../node_modules/tar-stream/pack.js"(exports2, module2) {
32464
+ "../daemon-core/node_modules/tar-stream/pack.js"(exports2, module2) {
32465
32465
  "use strict";
32466
32466
  var { Readable, Writable, getStreamError } = require_streamx();
32467
32467
  var b4a = require_b4a2();
@@ -32694,9 +32694,9 @@ var require_pack = __commonJS({
32694
32694
  }
32695
32695
  });
32696
32696
 
32697
- // ../../node_modules/tar-stream/index.js
32697
+ // ../daemon-core/node_modules/tar-stream/index.js
32698
32698
  var require_tar_stream = __commonJS({
32699
- "../../node_modules/tar-stream/index.js"(exports2) {
32699
+ "../daemon-core/node_modules/tar-stream/index.js"(exports2) {
32700
32700
  "use strict";
32701
32701
  exports2.extract = require_extract();
32702
32702
  exports2.pack = require_pack();
@@ -32939,9 +32939,9 @@ var require_pump = __commonJS({
32939
32939
  }
32940
32940
  });
32941
32941
 
32942
- // ../../node_modules/tar-fs/index.js
32942
+ // ../daemon-core/node_modules/tar-fs/index.js
32943
32943
  var require_tar_fs = __commonJS({
32944
- "../../node_modules/tar-fs/index.js"(exports2) {
32944
+ "../daemon-core/node_modules/tar-fs/index.js"(exports2) {
32945
32945
  "use strict";
32946
32946
  var tar = require_tar_stream();
32947
32947
  var pump = require_pump();
@@ -36911,10 +36911,10 @@ var require_dist3 = __commonJS({
36911
36911
  }
36912
36912
  function getDaemonBuildInfo() {
36913
36913
  if (cached2) return cached2;
36914
- const commit = readInjected(true ? "f678a3c56c08e7876a714abda968b9e6a8787841" : void 0) ?? "unknown";
36915
- const commitShort = readInjected(true ? "f678a3c5" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36916
- const version2 = readInjected(true ? "1.0.58-rc.45" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36917
- const builtAt = readInjected(true ? "2026-08-30T01:11:37.487Z" : void 0);
36914
+ const commit = readInjected(true ? "a03baab8130d59d9dfaca9173cddefd7f052d6a4" : void 0) ?? "unknown";
36915
+ const commitShort = readInjected(true ? "a03baab8" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36916
+ const version2 = readInjected(true ? "1.0.58-rc.46" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36917
+ const builtAt = readInjected(true ? "2026-08-30T06:41:16.415Z" : void 0);
36918
36918
  cached2 = builtAt ? { commit, commitShort, version: version2, builtAt } : { commit, commitShort, version: version2 };
36919
36919
  return cached2;
36920
36920
  }
@@ -41531,12 +41531,57 @@ child.on('exit', () => process.exit(0));
41531
41531
  const override = env2.KIMI_CODE_HOME?.trim();
41532
41532
  return override ? override : path11.join(os8.homedir(), ".kimi-code");
41533
41533
  }
41534
- function credentialsPath(env2) {
41535
- return path11.join(kimiHome(env2), "credentials", "kimi-code.json");
41534
+ function tomlStringValue(line, key2) {
41535
+ const escapedKey = key2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41536
+ const basic = line.match(new RegExp(`^\\s*${escapedKey}\\s*=\\s*("(?:\\\\.|[^"\\\\])*")\\s*(?:#.*)?$`));
41537
+ if (basic?.[1]) {
41538
+ try {
41539
+ const value = JSON.parse(basic[1]);
41540
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
41541
+ } catch {
41542
+ return void 0;
41543
+ }
41544
+ }
41545
+ const literal2 = line.match(new RegExp(`^\\s*${escapedKey}\\s*=\\s*'([^']*)'\\s*(?:#.*)?$`));
41546
+ return literal2?.[1]?.trim() || void 0;
41547
+ }
41548
+ function readManagedKimiSettings(env2) {
41549
+ let raw;
41550
+ try {
41551
+ raw = fs9.readFileSync(path11.join(kimiHome(env2), "config.toml"), "utf-8");
41552
+ } catch {
41553
+ return {};
41554
+ }
41555
+ let section = null;
41556
+ const settings = {};
41557
+ for (const line of raw.split(/\r?\n/)) {
41558
+ const header = line.trim().match(/^\[\s*(.*?)\s*\](?:\s*#.*)?$/)?.[1];
41559
+ if (header !== void 0) {
41560
+ if (/^providers\s*\.\s*["']managed:kimi-code["']\s*$/.test(header)) {
41561
+ section = "provider";
41562
+ } else if (/^providers\s*\.\s*["']managed:kimi-code["']\s*\.\s*oauth\s*$/.test(header)) {
41563
+ section = "oauth";
41564
+ } else {
41565
+ section = null;
41566
+ }
41567
+ continue;
41568
+ }
41569
+ if (section === "provider") {
41570
+ settings.baseUrl = tomlStringValue(line, "base_url") ?? settings.baseUrl;
41571
+ } else if (section === "oauth") {
41572
+ settings.oauthKey = tomlStringValue(line, "key") ?? settings.oauthKey;
41573
+ }
41574
+ }
41575
+ return settings;
41536
41576
  }
41537
- function baseUrl4(env2) {
41577
+ function credentialsPath(env2, oauthKey) {
41578
+ const configuredName = oauthKey?.replace(/^oauth\//, "").split("/").at(-1)?.trim();
41579
+ const name = configuredName && configuredName !== "." && configuredName !== ".." && path11.basename(configuredName) === configuredName ? configuredName : "kimi-code";
41580
+ return path11.join(kimiHome(env2), "credentials", `${name}.json`);
41581
+ }
41582
+ function baseUrl4(env2, configured) {
41538
41583
  const override = env2.KIMI_CODE_BASE_URL?.trim();
41539
- return (override ? override : DEFAULT_BASE_URL4).replace(/\/+$/, "");
41584
+ return (override || configured || DEFAULT_BASE_URL4).replace(/\/+$/, "");
41540
41585
  }
41541
41586
  function parseCredentials3(raw) {
41542
41587
  let parsed;
@@ -41557,8 +41602,8 @@ child.on('exit', () => process.exit(0));
41557
41602
  const expiresAt = typeof expiresAtRaw === "number" && Number.isFinite(expiresAtRaw) ? expiresAtRaw : null;
41558
41603
  return { kind: "ok", credentials: { accessToken, expiresAt } };
41559
41604
  }
41560
- function readCredentials4(deps) {
41561
- const file2 = credentialsPath(deps.env);
41605
+ function readCredentials4(deps, oauthKey) {
41606
+ const file2 = credentialsPath(deps.env, oauthKey);
41562
41607
  let raw;
41563
41608
  try {
41564
41609
  raw = fs9.readFileSync(file2, "utf-8");
@@ -41683,7 +41728,8 @@ child.on('exit', () => process.exit(0));
41683
41728
  async function fetchKimiQuota2(overrides = {}) {
41684
41729
  assertInjectedNetworkFetchInTest(overrides, "fetchKimiQuota");
41685
41730
  const deps = resolveDeps(overrides);
41686
- const credentialsResult = readCredentials4(deps);
41731
+ const settings = readManagedKimiSettings(deps.env);
41732
+ const credentialsResult = readCredentials4(deps, settings.oauthKey);
41687
41733
  if (credentialsResult.kind === "missing") {
41688
41734
  return quotaFailure("kimi", "unavailable", "Not signed in to Kimi Code", {
41689
41735
  source: "oauth",
@@ -41706,7 +41752,7 @@ child.on('exit', () => process.exit(0));
41706
41752
  );
41707
41753
  }
41708
41754
  try {
41709
- const response = await deps.fetch(`${baseUrl4(deps.env)}/usages`, {
41755
+ const response = await deps.fetch(`${baseUrl4(deps.env, settings.baseUrl)}/usages`, {
41710
41756
  headers: {
41711
41757
  Authorization: `Bearer ${credentials.accessToken}`,
41712
41758
  Accept: "application/json"
@@ -51820,7 +51866,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
51820
51866
  }
51821
51867
  });
51822
51868
  var require_canonicalize = __commonJS2({
51823
- "../../vendor/seqscribe/node_modules/canonicalize/lib/canonicalize.js"(exports22, module22) {
51869
+ "../../node_modules/canonicalize/lib/canonicalize.js"(exports22, module22) {
51824
51870
  "use strict";
51825
51871
  module22.exports = function serialize(object2) {
51826
51872
  if (typeof object2 === "number" && isNaN(object2)) {
@@ -51930,7 +51976,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
51930
51976
  var hexes;
51931
51977
  var Hash;
51932
51978
  var init_utils = __esm2({
51933
- "../../vendor/seqscribe/node_modules/@noble/hashes/esm/utils.js"() {
51979
+ "../../node_modules/@noble/hashes/esm/utils.js"() {
51934
51980
  "use strict";
51935
51981
  hasHexBuiltin = /* @__PURE__ */ (() => (
51936
51982
  // @ts-ignore
@@ -51962,7 +52008,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
51962
52008
  var HashMD;
51963
52009
  var SHA256_IV;
51964
52010
  var init_md = __esm2({
51965
- "../../vendor/seqscribe/node_modules/@noble/hashes/esm/_md.js"() {
52011
+ "../../node_modules/@noble/hashes/esm/_md.js"() {
51966
52012
  "use strict";
51967
52013
  init_utils();
51968
52014
  HashMD = class extends Hash {
@@ -52072,7 +52118,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
52072
52118
  var SHA256;
52073
52119
  var sha256;
52074
52120
  var init_sha2 = __esm2({
52075
- "../../vendor/seqscribe/node_modules/@noble/hashes/esm/sha2.js"() {
52121
+ "../../node_modules/@noble/hashes/esm/sha2.js"() {
52076
52122
  "use strict";
52077
52123
  init_md();
52078
52124
  init_utils();
@@ -52218,7 +52264,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
52218
52264
  });
52219
52265
  var sha2562;
52220
52266
  var init_sha256 = __esm2({
52221
- "../../vendor/seqscribe/node_modules/@noble/hashes/esm/sha256.js"() {
52267
+ "../../node_modules/@noble/hashes/esm/sha256.js"() {
52222
52268
  "use strict";
52223
52269
  init_sha2();
52224
52270
  sha2562 = sha256;
@@ -52957,7 +53003,7 @@ The instruction it carried was never delivered to anyone. If it still matters, r
52957
53003
  var HMAC;
52958
53004
  var hmac;
52959
53005
  var init_hmac = __esm2({
52960
- "../../vendor/seqscribe/node_modules/@noble/hashes/esm/hmac.js"() {
53006
+ "../../node_modules/@noble/hashes/esm/hmac.js"() {
52961
53007
  "use strict";
52962
53008
  init_utils();
52963
53009
  HMAC = class extends Hash {
@@ -63592,8 +63638,8 @@ CREATE TABLE IF NOT EXISTS sq_archive (
63592
63638
  const branch = readStringValue(node.worktreeBranch, node.worktree_branch);
63593
63639
  if (branch) return `\u2387 ${branch}`;
63594
63640
  const workspace = readStringValue(node.workspace, node.repoRoot, node.repo_root);
63595
- const basename21 = workspace ? workingDirBasename(workspace) : void 0;
63596
- return basename21 || (nodeId ? nodeId.slice(0, 8) : "node");
63641
+ const basename22 = workspace ? workingDirBasename(workspace) : void 0;
63642
+ return basename22 || (nodeId ? nodeId.slice(0, 8) : "node");
63597
63643
  }
63598
63644
  function buildMeshNodeDisplayLabel(node, nodeId, _providerPriority) {
63599
63645
  return buildMeshNodeMachineLabel(node, nodeId);
@@ -82142,6 +82188,25 @@ ${block2.text}`,
82142
82188
  launchedByCoordinator: true,
82143
82189
  autoLaunchedForQueueTaskId: task.id
82144
82190
  };
82191
+ const requiredTags = Array.isArray(task.requiredTags) ? task.requiredTags.filter((t) => !!t) : [];
82192
+ const buildRoutingDecision = () => buildAutoLaunchRoutingDecision({
82193
+ node,
82194
+ meshId,
82195
+ task: { difficulty: task.difficulty, requiredTags: task.requiredTags },
82196
+ resolved,
82197
+ quotaRouting: mesh?.policy?.quotaRouting ?? null,
82198
+ quotaFactsContext: quotaFactsContextForLiveRouting(mesh, isLocalAutoLaunchNode, components.providerLoader),
82199
+ skippedCandidates,
82200
+ requiredTagsResult: {
82201
+ required: requiredTags,
82202
+ satisfied: !requiredTags.length || nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, effectiveProviderType)),
82203
+ missing: requiredTags.filter((t) => !buildMeshNodeCapabilityTags(node, effectiveProviderType).includes(t))
82204
+ },
82205
+ effectiveModel,
82206
+ effectiveThinkingLevel,
82207
+ executedSlot: slotDecision.slot,
82208
+ demotionReason
82209
+ });
82145
82210
  if (launchTarget.mode === "remote") {
82146
82211
  const remoteSettings = {
82147
82212
  ...launchSettings,
@@ -82185,7 +82250,15 @@ ${block2.text}`,
82185
82250
  await waitForRemoteSessionReady(meshId, nodeId, remoteSessionId, {
82186
82251
  isReady: remoteSessionReadyProbe(meshId, nodeId, remoteSessionId)
82187
82252
  }).catch(() => false);
82188
- claimAfterRemoteAutoLaunch(components, meshId, nodeId, remoteSessionId, effectiveProviderType, tryAssignQueueTask);
82253
+ const routingDecision2 = buildRoutingDecision();
82254
+ claimAfterRemoteAutoLaunch(
82255
+ components,
82256
+ meshId,
82257
+ nodeId,
82258
+ remoteSessionId,
82259
+ effectiveProviderType,
82260
+ (c, m, n, s2, p) => tryAssignQueueTask(c, m, n, s2, p, routingDecision2, void 0, "auto_launch")
82261
+ );
82189
82262
  }
82190
82263
  return true;
82191
82264
  }
@@ -82217,25 +82290,7 @@ ${block2.text}`,
82217
82290
  markAutoLaunch(meshId, task.id, { status: "completed", nodeId, providerType: effectiveProviderType, sessionId, ...effectiveModel ? { model: effectiveModel } : {}, ...effectiveThinkingLevel ? { thinkingLevel: effectiveThinkingLevel } : {} });
82218
82291
  logAutoLaunchQuotaFallbackSuccess(resolved, task.id, nodeId, sessionId);
82219
82292
  await waitForLocalSessionReady(components, sessionId);
82220
- const requiredTags = Array.isArray(task.requiredTags) ? task.requiredTags.filter((t) => !!t) : [];
82221
- const routingDecision = buildAutoLaunchRoutingDecision({
82222
- node,
82223
- meshId,
82224
- task: { difficulty: task.difficulty, requiredTags: task.requiredTags },
82225
- resolved,
82226
- quotaRouting: mesh?.policy?.quotaRouting ?? null,
82227
- quotaFactsContext: quotaFactsContextForLiveRouting(mesh, isLocalAutoLaunchNode, components.providerLoader),
82228
- skippedCandidates,
82229
- requiredTagsResult: {
82230
- required: requiredTags,
82231
- satisfied: !requiredTags.length || nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, effectiveProviderType)),
82232
- missing: requiredTags.filter((t) => !buildMeshNodeCapabilityTags(node, effectiveProviderType).includes(t))
82233
- },
82234
- effectiveModel,
82235
- effectiveThinkingLevel,
82236
- executedSlot: slotDecision.slot,
82237
- demotionReason
82238
- });
82293
+ const routingDecision = buildRoutingDecision();
82239
82294
  tryAssignQueueTask(components, meshId, nodeId, sessionId, effectiveProviderType, routingDecision, void 0, "auto_launch");
82240
82295
  return true;
82241
82296
  } catch (e) {
@@ -87007,25 +87062,76 @@ ${cleanBody}`;
87007
87062
  DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS = 12e3;
87008
87063
  }
87009
87064
  });
87065
+ function resolveRemotePullBackoffMs(backoffRound) {
87066
+ const shift = Math.max(0, Math.min(backoffRound - 1, 8));
87067
+ return Math.min(REMOTE_PULL_BACKOFF_MAX_MS, REMOTE_PULL_BACKOFF_BASE_MS * 2 ** shift);
87068
+ }
87069
+ function pullBackoffKey(meshId, daemonId) {
87070
+ return `${meshId}::${canonicalDaemonId(daemonId) ?? daemonId}`;
87071
+ }
87072
+ function isRemotePullBackedOff(meshId, daemonId, nowMs) {
87073
+ const state = remotePullBackoffByDaemon.get(pullBackoffKey(meshId, daemonId));
87074
+ return !!state && nowMs < state.nextPullAtMs;
87075
+ }
87076
+ function noteRemotePullResult(meshId, daemonId, result, nowMs) {
87077
+ const key2 = pullBackoffKey(meshId, daemonId);
87078
+ if (result.received > 0) {
87079
+ remotePullBackoffByDaemon.delete(key2);
87080
+ return;
87081
+ }
87082
+ if (!result.reached) return;
87083
+ const prev = remotePullBackoffByDaemon.get(key2);
87084
+ const emptyRounds = (prev?.emptyRounds ?? 0) + 1;
87085
+ const backoffRound = emptyRounds - REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF + 1;
87086
+ remotePullBackoffByDaemon.set(key2, {
87087
+ emptyRounds,
87088
+ nextPullAtMs: emptyRounds >= REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF ? nowMs + resolveRemotePullBackoffMs(backoffRound) : 0
87089
+ });
87090
+ }
87010
87091
  async function pullRemoteNodeQueues(components, mesh, localDaemonId, candidateDaemonIds) {
87011
87092
  const dispatchMeshCommand = components.dispatchMeshCommand;
87012
87093
  if (!dispatchMeshCommand) return;
87013
87094
  const meshId = mesh.id;
87014
87095
  const pulls = candidateDaemonIds.length > 0 ? candidateDaemonIds.map((id) => ({ meshId, coordinatorDaemonId: id })) : [{ meshId }];
87015
- await Promise.allSettled(mesh.nodes.map((node) => pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls)));
87096
+ const uniqueNodes = [];
87097
+ const seenDaemonIds = /* @__PURE__ */ new Set();
87098
+ for (const node of mesh.nodes) {
87099
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
87100
+ if (!nodeDaemonId) continue;
87101
+ const daemonKey = canonicalDaemonId(nodeDaemonId) ?? nodeDaemonId;
87102
+ if (seenDaemonIds.has(daemonKey)) continue;
87103
+ seenDaemonIds.add(daemonKey);
87104
+ uniqueNodes.push(node);
87105
+ }
87106
+ await Promise.allSettled(uniqueNodes.map((node) => (async () => {
87107
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
87108
+ if (nodeDaemonId && isRemotePullBackedOff(meshId, nodeDaemonId, Date.now())) return;
87109
+ const result = await pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls);
87110
+ if (nodeDaemonId) noteRemotePullResult(meshId, nodeDaemonId, result, Date.now());
87111
+ })()));
87016
87112
  }
87017
- async function pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls) {
87113
+ async function pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls, opts) {
87018
87114
  const dispatchMeshCommand = components.dispatchMeshCommand;
87019
- if (!dispatchMeshCommand) return;
87115
+ if (!dispatchMeshCommand) return NOT_REACHED;
87020
87116
  const nodeDaemonId = readNonEmptyString(node.daemonId);
87021
- if (!nodeDaemonId) return;
87022
- if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) return;
87023
- if (daemonIdListIncludes(candidateDaemonIds, nodeDaemonId)) return;
87117
+ if (!nodeDaemonId) return NOT_REACHED;
87118
+ if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) return NOT_REACHED;
87119
+ if (daemonIdListIncludes(candidateDaemonIds, nodeDaemonId)) return NOT_REACHED;
87024
87120
  const getPeerStatus = components.getMeshPeerConnectionStatus;
87025
87121
  if (getPeerStatus) {
87026
87122
  const peerSnapshot = getPeerStatus(nodeDaemonId);
87027
- if (!peerSnapshot || String(peerSnapshot.state) !== "connected") return;
87123
+ if (!peerSnapshot || String(peerSnapshot.state) !== "connected") return NOT_REACHED;
87124
+ }
87125
+ const throttleKey = pullBackoffKey(meshId, nodeDaemonId);
87126
+ if (opts?.minIntervalSinceLastPullMs) {
87127
+ const lastPullAt = lastRedrivePullAtMs.get(throttleKey);
87128
+ if (lastPullAt !== void 0 && Date.now() - lastPullAt < opts.minIntervalSinceLastPullMs) {
87129
+ return NOT_REACHED;
87130
+ }
87028
87131
  }
87132
+ let received = 0;
87133
+ let completedPulls = 0;
87134
+ if (opts?.minIntervalSinceLastPullMs) lastRedrivePullAtMs.set(throttleKey, Date.now());
87029
87135
  for (const pendingEventArgs of pulls) {
87030
87136
  let events;
87031
87137
  try {
@@ -87033,7 +87139,11 @@ ${cleanBody}`;
87033
87139
  } catch {
87034
87140
  break;
87035
87141
  }
87036
- const list = extractPendingEvents(events).filter((e) => readNonEmptyString(e?.meshId) === meshId);
87142
+ const extracted = extractPendingEventsResult(events);
87143
+ if (!extracted.confirmed) break;
87144
+ completedPulls++;
87145
+ received += extracted.events.length;
87146
+ const list = extracted.events.filter((e) => readNonEmptyString(e?.meshId) === meshId);
87037
87147
  for (const event of list) {
87038
87148
  const payload = buildForwardPayloadFromPending(event);
87039
87149
  if (!payload.event || !payload.meshId) continue;
@@ -87043,6 +87153,7 @@ ${cleanBody}`;
87043
87153
  }
87044
87154
  }
87045
87155
  }
87156
+ return { received, reached: completedPulls === pulls.length };
87046
87157
  }
87047
87158
  function unwrapReadChatPayload(raw) {
87048
87159
  let cursor = raw;
@@ -87150,12 +87261,13 @@ ${cleanBody}`;
87150
87261
  }
87151
87262
  return [];
87152
87263
  }
87153
- function extractPendingEvents(raw) {
87264
+ function extractPendingEventsResult(raw) {
87154
87265
  let cursor = raw;
87155
87266
  for (let depth = 0; depth < 4 && cursor && typeof cursor === "object"; depth++) {
87156
- if (Array.isArray(cursor)) return cursor;
87267
+ if (Array.isArray(cursor)) return { events: cursor, confirmed: true };
87157
87268
  const record2 = cursor;
87158
- if (Array.isArray(record2.events)) return record2.events;
87269
+ if (record2.success === false) return { events: [], confirmed: false };
87270
+ if (Array.isArray(record2.events)) return { events: record2.events, confirmed: true };
87159
87271
  if (record2.payload && typeof record2.payload === "object") {
87160
87272
  cursor = record2.payload;
87161
87273
  continue;
@@ -87170,7 +87282,7 @@ ${cleanBody}`;
87170
87282
  }
87171
87283
  break;
87172
87284
  }
87173
- return [];
87285
+ return { events: [], confirmed: false };
87174
87286
  }
87175
87287
  function buildForwardPayloadFromPending(event) {
87176
87288
  const metadata = event?.metadataEvent && typeof event.metadataEvent === "object" ? event.metadataEvent : {};
@@ -87210,6 +87322,13 @@ ${cleanBody}`;
87210
87322
  ...serializeV2EnvelopeToWire(event)
87211
87323
  };
87212
87324
  }
87325
+ var REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF;
87326
+ var REMOTE_PULL_BACKOFF_BASE_MS;
87327
+ var REMOTE_PULL_BACKOFF_MAX_MS;
87328
+ var REDRIVE_PULL_MIN_INTERVAL_MS;
87329
+ var remotePullBackoffByDaemon;
87330
+ var lastRedrivePullAtMs;
87331
+ var NOT_REACHED;
87213
87332
  var init_mesh_remote_event_pull = __esm2({
87214
87333
  "src/mesh/mesh-remote-event-pull.ts"() {
87215
87334
  "use strict";
@@ -87218,6 +87337,13 @@ ${cleanBody}`;
87218
87337
  init_mesh_events_utils();
87219
87338
  init_dist();
87220
87339
  init_mesh_reconcile_identity();
87340
+ REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF = 3;
87341
+ REMOTE_PULL_BACKOFF_BASE_MS = 8e3;
87342
+ REMOTE_PULL_BACKOFF_MAX_MS = 3e4;
87343
+ REDRIVE_PULL_MIN_INTERVAL_MS = 2e3;
87344
+ remotePullBackoffByDaemon = /* @__PURE__ */ new Map();
87345
+ lastRedrivePullAtMs = /* @__PURE__ */ new Map();
87346
+ NOT_REACHED = { received: 0, reached: false };
87221
87347
  }
87222
87348
  });
87223
87349
  function formatBytes(bytes) {
@@ -90639,7 +90765,8 @@ ${cleanBody}`;
90639
90765
  assignedNode,
90640
90766
  localDaemonId,
90641
90767
  selfIds,
90642
- selfIds.length > 0 ? selfIds.map((id) => ({ meshId, coordinatorDaemonId: id })) : [{ meshId }]
90768
+ selfIds.length > 0 ? selfIds.map((id) => ({ meshId, coordinatorDaemonId: id })) : [{ meshId }],
90769
+ { minIntervalSinceLastPullMs: REDRIVE_PULL_MIN_INTERVAL_MS }
90643
90770
  );
90644
90771
  } catch {
90645
90772
  }
@@ -93797,6 +93924,14 @@ ${cleanBody}`;
93797
93924
  },
93798
93925
  description: "Template for expanding an initialModel selection into launch args. '{{model}}' is substituted with the model string (e.g. ['--model', '{{model}}'] \u2192 --model opus). Applied at launch when a model is requested for this CLI provider (MAGI kind-panel model axis). Absent \u2192 no launch-time model selection."
93799
93926
  },
93927
+ modelLaunchValueMap: {
93928
+ type: "object",
93929
+ additionalProperties: {
93930
+ type: "string",
93931
+ minLength: 1
93932
+ },
93933
+ description: "Optional map from user-facing model labels to provider-specific CLI values used to fill {{model}} in modelLaunchArgs. A model absent from the map passes through unchanged."
93934
+ },
93800
93935
  modelOptions: {
93801
93936
  type: "array",
93802
93937
  items: {
@@ -95737,6 +95872,23 @@ ${tail}`;
95737
95872
  DEFAULT_REFINE_VITEST_MAX_WORKERS = 2;
95738
95873
  }
95739
95874
  });
95875
+ function sanitizeRefineGateChildEnv(env2 = process.env) {
95876
+ const sanitized = {};
95877
+ for (const [key2, value] of Object.entries(env2)) {
95878
+ if (key2.startsWith(ADHDEV_ENV_PREFIX) && !REFINE_GATE_ENV_ALLOWLIST.has(key2)) continue;
95879
+ sanitized[key2] = value;
95880
+ }
95881
+ return sanitized;
95882
+ }
95883
+ var ADHDEV_ENV_PREFIX;
95884
+ var REFINE_GATE_ENV_ALLOWLIST;
95885
+ var init_mesh_refine_env_sanitize = __esm2({
95886
+ "src/mesh/mesh-refine-env-sanitize.ts"() {
95887
+ "use strict";
95888
+ ADHDEV_ENV_PREFIX = "ADHDEV_";
95889
+ REFINE_GATE_ENV_ALLOWLIST = /* @__PURE__ */ new Set([]);
95890
+ }
95891
+ });
95740
95892
  function classifySubmoduleDivergence(submoduleRepoPath, baseCommit, branchCommit) {
95741
95893
  if (!baseCommit || !branchCommit) return "undeterminable";
95742
95894
  if (baseCommit === branchCommit) return "not_diverged";
@@ -97046,7 +97198,7 @@ ${mergeTreeErr?.stderr || ""}`;
97046
97198
  windowsHide: true,
97047
97199
  timeout,
97048
97200
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
97049
- env: { ...process.env, CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97201
+ env: { ...sanitizeRefineGateChildEnv(), CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97050
97202
  ...spawn7.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
97051
97203
  });
97052
97204
  summary.bootstrapCommandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -97092,7 +97244,7 @@ ${mergeTreeErr?.stderr || ""}`;
97092
97244
  windowsHide: true,
97093
97245
  timeout,
97094
97246
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
97095
- env: { ...process.env, CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97247
+ env: { ...sanitizeRefineGateChildEnv(), CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97096
97248
  ...spawn7.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
97097
97249
  });
97098
97250
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -97154,6 +97306,7 @@ ${mergeTreeErr?.stderr || ""}`;
97154
97306
  import_node_child_process11 = require("child_process");
97155
97307
  init_resolve_executable();
97156
97308
  init_mesh_refine_worker_cap();
97309
+ init_mesh_refine_env_sanitize();
97157
97310
  init_mesh_refine_gitlink_utils();
97158
97311
  init_mesh_refine_submodule_converge();
97159
97312
  init_mesh_refine_gitlink_utils();
@@ -97349,12 +97502,38 @@ ${mergeTreeErr?.stderr || ""}`;
97349
97502
  };
97350
97503
  }
97351
97504
  });
97505
+ async function execChangeAreaGit(callSite, gitArgs, cwd, inputs) {
97506
+ try {
97507
+ return await execFileAsync6(GIT3, gitArgs, { cwd, encoding: "utf8" });
97508
+ } catch (error48) {
97509
+ LOG2.warn("Mesh", `[Refinery] Change-area git call failed: ${JSON.stringify({
97510
+ callSite,
97511
+ gitArgs,
97512
+ cwd,
97513
+ cwdExists: (0, import_node_fs7.existsSync)(cwd),
97514
+ code: error48?.code ?? null,
97515
+ syscall: error48?.syscall ?? null,
97516
+ path: error48?.path ?? null,
97517
+ inputs
97518
+ })}`);
97519
+ throw error48;
97520
+ }
97521
+ }
97352
97522
  function topLevel(path64) {
97353
97523
  const slash = path64.indexOf("/");
97354
97524
  return slash === -1 ? path64 : path64.slice(0, slash);
97355
97525
  }
97356
97526
  async function analyzeMeshRefineNodeChangeArea(args) {
97357
- const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
97527
+ const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, repoRoot, submodulePaths } = args;
97528
+ const diagnosticInputs = {
97529
+ nodeId,
97530
+ workspace,
97531
+ repoRoot: repoRoot ?? null,
97532
+ branch,
97533
+ baseRef,
97534
+ branchRef,
97535
+ submodulePaths: [...submodulePaths]
97536
+ };
97358
97537
  const base = {
97359
97538
  nodeId,
97360
97539
  workspace,
@@ -97368,21 +97547,28 @@ ${mergeTreeErr?.stderr || ""}`;
97368
97547
  try {
97369
97548
  let mergeBase = baseRef;
97370
97549
  try {
97371
- const { stdout } = await execFileAsync6(GIT3, ["merge-base", baseRef, branchRef], { cwd: diffCwd, encoding: "utf8" });
97550
+ const { stdout } = await execChangeAreaGit(
97551
+ "analyzeMeshRefineNodeChangeArea.mergeBase",
97552
+ ["merge-base", baseRef, branchRef],
97553
+ diffCwd,
97554
+ diagnosticInputs
97555
+ );
97372
97556
  const resolved = stdout.trim();
97373
97557
  if (resolved) mergeBase = resolved;
97374
97558
  } catch {
97375
97559
  }
97376
- const { stdout: countStdout } = await execFileAsync6(
97377
- GIT3,
97560
+ const { stdout: countStdout } = await execChangeAreaGit(
97561
+ "analyzeMeshRefineNodeChangeArea.aheadCount",
97378
97562
  ["rev-list", "--count", `${mergeBase}..${branchRef}`],
97379
- { cwd: diffCwd, encoding: "utf8" }
97563
+ diffCwd,
97564
+ { ...diagnosticInputs, mergeBase }
97380
97565
  );
97381
97566
  base.aheadCount = Number.parseInt(countStdout.trim(), 10) || 0;
97382
- const { stdout: nameStdout } = await execFileAsync6(
97383
- GIT3,
97567
+ const { stdout: nameStdout } = await execChangeAreaGit(
97568
+ "analyzeMeshRefineNodeChangeArea.changedFiles",
97384
97569
  ["diff", "--name-only", `${mergeBase}..${branchRef}`],
97385
- { cwd: diffCwd, encoding: "utf8" }
97570
+ diffCwd,
97571
+ { ...diagnosticInputs, mergeBase }
97386
97572
  );
97387
97573
  const files = nameStdout.split("\n").map((line) => line.trim()).filter(Boolean).slice(0, MAX_CHANGED_FILES2);
97388
97574
  base.changedFiles = files;
@@ -97431,6 +97617,7 @@ ${mergeTreeErr?.stderr || ""}`;
97431
97617
  return { order: ranked.map((a) => a.nodeId), changeAreas: areaById, rationale };
97432
97618
  }
97433
97619
  var import_node_child_process14;
97620
+ var import_node_fs7;
97434
97621
  var import_node_util7;
97435
97622
  var execFileAsync6;
97436
97623
  var GIT3;
@@ -97439,8 +97626,10 @@ ${mergeTreeErr?.stderr || ""}`;
97439
97626
  "src/mesh/mesh-refine-batch.ts"() {
97440
97627
  "use strict";
97441
97628
  import_node_child_process14 = require("child_process");
97629
+ import_node_fs7 = require("fs");
97442
97630
  import_node_util7 = require("util");
97443
97631
  init_resolve_executable();
97632
+ init_logger();
97444
97633
  execFileAsync6 = (0, import_node_util7.promisify)(import_node_child_process14.execFile);
97445
97634
  GIT3 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
97446
97635
  MAX_CHANGED_FILES2 = 500;
@@ -97465,7 +97654,7 @@ ${mergeTreeErr?.stderr || ""}`;
97465
97654
  }
97466
97655
  async function assessScope(cwd, path64, baseRef, branchRef) {
97467
97656
  try {
97468
- if (!(0, import_node_fs7.existsSync)(cwd)) return { path: path64, verdict: "unknown", error: `path does not exist: ${cwd}` };
97657
+ if (!(0, import_node_fs8.existsSync)(cwd)) return { path: path64, verdict: "unknown", error: `path does not exist: ${cwd}` };
97469
97658
  const liveBaseHead = await git2(cwd, ["rev-parse", baseRef]);
97470
97659
  const branchHead = await git2(cwd, ["rev-parse", branchRef]);
97471
97660
  if (!liveBaseHead || !branchHead) {
@@ -97558,7 +97747,7 @@ ${mergeTreeErr?.stderr || ""}`;
97558
97747
  var import_node_child_process15;
97559
97748
  var import_node_util8;
97560
97749
  var import_node_path5;
97561
- var import_node_fs7;
97750
+ var import_node_fs8;
97562
97751
  var execFileAsync7;
97563
97752
  var GIT4;
97564
97753
  var init_mesh_refine_base_divergence = __esm2({
@@ -97567,7 +97756,7 @@ ${mergeTreeErr?.stderr || ""}`;
97567
97756
  import_node_child_process15 = require("child_process");
97568
97757
  import_node_util8 = require("util");
97569
97758
  import_node_path5 = require("path");
97570
- import_node_fs7 = require("fs");
97759
+ import_node_fs8 = require("fs");
97571
97760
  init_resolve_executable();
97572
97761
  init_mesh_refine_batch();
97573
97762
  execFileAsync7 = (0, import_node_util8.promisify)(import_node_child_process15.execFile);
@@ -97792,7 +97981,7 @@ ${mergeTreeErr?.stderr || ""}`;
97792
97981
  function refineWorktreeVanishedOutcome(ctx, nextStage) {
97793
97982
  const workspace = ctx?.node?.workspace;
97794
97983
  if (typeof workspace !== "string" || !workspace) return null;
97795
- if ((0, import_node_fs8.existsSync)(workspace)) return null;
97984
+ if ((0, import_node_fs9.existsSync)(workspace)) return null;
97796
97985
  recordMeshRefineStage(ctx.refineStages, nextStage, "failed", Date.now(), {
97797
97986
  workspace,
97798
97987
  workspaceMissing: true,
@@ -97812,12 +98001,12 @@ ${mergeTreeErr?.stderr || ""}`;
97812
98001
  }
97813
98002
  };
97814
98003
  }
97815
- var import_node_fs8;
98004
+ var import_node_fs9;
97816
98005
  var REFINE_INFLIGHT_FRESHNESS_MS;
97817
98006
  var init_mesh_refine_inflight = __esm2({
97818
98007
  "src/mesh/mesh-refine-inflight.ts"() {
97819
98008
  "use strict";
97820
- import_node_fs8 = require("fs");
98009
+ import_node_fs9 = require("fs");
97821
98010
  init_mesh_refine_zombie_sweep();
97822
98011
  init_mesh_refine_landing();
97823
98012
  init_mesh_refine_gates();
@@ -98644,7 +98833,7 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
98644
98833
  if (!node.isLocalWorktree || !node.workspace) {
98645
98834
  return { kind: "terminal", result: { success: false, error: `Refinery requires a local worktree node`, refineStages } };
98646
98835
  }
98647
- if (!(0, import_node_fs9.existsSync)(node.workspace)) {
98836
+ if (!(0, import_node_fs10.existsSync)(node.workspace)) {
98648
98837
  recordMeshRefineStage(refineStages, "resolve_refs", "failed", Date.now(), {
98649
98838
  workspace: node.workspace,
98650
98839
  workspaceMissing: true
@@ -99876,6 +100065,7 @@ ${e?.stderr || ""}`;
99876
100065
  baseRef,
99877
100066
  branchRef,
99878
100067
  diffCwd: node.workspace,
100068
+ repoRoot,
99879
100069
  submodulePaths: submodulePathsByRepoRoot.get(repoRoot)
99880
100070
  }));
99881
100071
  }
@@ -100349,13 +100539,13 @@ ${e?.stderr || ""}`;
100349
100539
  return handle;
100350
100540
  }
100351
100541
  var import_node_child_process16;
100352
- var import_node_fs9;
100542
+ var import_node_fs10;
100353
100543
  var RETRYABLE_BASE_MOVEMENT_CODES;
100354
100544
  var init_router_refine = __esm2({
100355
100545
  "src/commands/router-refine.ts"() {
100356
100546
  "use strict";
100357
100547
  import_node_child_process16 = require("child_process");
100358
- import_node_fs9 = require("fs");
100548
+ import_node_fs10 = require("fs");
100359
100549
  init_logger();
100360
100550
  init_debug_trace();
100361
100551
  init_dist();
@@ -117724,17 +117914,17 @@ ${marker}`,
117724
117914
  this.logShadowDivergence(ev);
117725
117915
  if (ev.fired) {
117726
117916
  this.commitTransition(ev.fired, now, ev);
117917
+ this.maybeMarkReady();
117727
117918
  this.emitStateChanged(forceEmit);
117728
117919
  this.scheduleWakeForState();
117729
117920
  this.scheduleStallWatchdog();
117730
- this.maybeMarkReady();
117731
117921
  this.drainPendingSends();
117732
117922
  return;
117733
117923
  }
117924
+ this.maybeMarkReady();
117734
117925
  this.emitStateChanged(forceEmit);
117735
117926
  this.scheduleWakeForState();
117736
117927
  this.scheduleStallWatchdog();
117737
- this.maybeMarkReady();
117738
117928
  this.drainPendingSends();
117739
117929
  }
117740
117930
  commitTransition(fired, now, ev) {
@@ -118005,7 +118195,6 @@ ${marker}`,
118005
118195
  if (!st) return;
118006
118196
  if (!st.initial && statusForState(st) === "idle") {
118007
118197
  this.readySeenOnce = true;
118008
- this.drainPendingSends();
118009
118198
  }
118010
118199
  }
118011
118200
  // ────────────────────────────────────────────────────────────────────
@@ -120240,17 +120429,17 @@ ${marker}`,
120240
120429
  }
120241
120430
  function readSession(sessionPath) {
120242
120431
  if (!sessionPath || !path40.isAbsolute(sessionPath)) return null;
120243
- const basename21 = path40.basename(sessionPath, ".jsonl");
120244
- if (!isSafeSessionId(basename21)) return null;
120432
+ const basename22 = path40.basename(sessionPath, ".jsonl");
120433
+ if (!isSafeSessionId(basename22)) return null;
120245
120434
  if (!fs33.existsSync(sessionPath)) return null;
120246
120435
  const sourceMtimeMs = statMtimeMs(sessionPath);
120247
- const { messages, usageRecords } = parseTranscriptFile(sessionPath, basename21);
120436
+ const { messages, usageRecords } = parseTranscriptFile(sessionPath, basename22);
120248
120437
  if (messages.length === 0) return null;
120249
120438
  const firstSystem = messages.find((m) => m.kind === "session_start");
120250
120439
  const workspace = firstSystem?.workspace || firstSystem?.content || void 0;
120251
120440
  const session = {
120252
120441
  messages,
120253
- providerSessionId: basename21,
120442
+ providerSessionId: basename22,
120254
120443
  source: "provider-native",
120255
120444
  sourcePath: sessionPath,
120256
120445
  sourceMtimeMs,
@@ -120259,7 +120448,7 @@ ${marker}`,
120259
120448
  };
120260
120449
  if (usageRecords.length > 0) {
120261
120450
  session.usage = foldUsageRecords(usageRecords, {
120262
- providerSessionId: basename21,
120451
+ providerSessionId: basename22,
120263
120452
  agent: "claude-cli"
120264
120453
  });
120265
120454
  }
@@ -120553,8 +120742,8 @@ ${marker}`,
120553
120742
  if (!fs34.existsSync(sessionPath)) return null;
120554
120743
  const meta3 = readSessionMeta(sessionPath);
120555
120744
  const metaId = String(meta3?.id ?? "").trim();
120556
- const basename21 = path41.basename(sessionPath, ".jsonl");
120557
- const uuidMatch = basename21.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
120745
+ const basename22 = path41.basename(sessionPath, ".jsonl");
120746
+ const uuidMatch = basename22.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i);
120558
120747
  const filenameUuid2 = uuidMatch ? uuidMatch[1] : "";
120559
120748
  if (metaId && filenameUuid2 && metaId !== filenameUuid2) return null;
120560
120749
  const sessionId = metaId || filenameUuid2;
@@ -123015,10 +123204,21 @@ ${text}` : text;
123015
123204
  ...sessionFields
123016
123205
  };
123017
123206
  }
123207
+ const readySeen = this.driver.hasSeenReady?.();
123208
+ if (readySeen === false) {
123209
+ return {
123210
+ status: "starting",
123211
+ messages: [],
123212
+ activeModal: null,
123213
+ activeInteractivePrompt: this.activeInteractivePrompt,
123214
+ fsmReadySeen: false,
123215
+ ...sessionFields
123216
+ };
123217
+ }
123018
123218
  if (state.status === "generating") {
123019
123219
  return { status: "generating", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
123020
123220
  }
123021
- return { status: "idle", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, fsmReadySeen: this.driver.hasSeenReady?.() ?? false, ...sessionFields };
123221
+ return { status: "idle", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, fsmReadySeen: readySeen === true, ...sessionFields };
123022
123222
  }
123023
123223
  maybeRefreshNativeHistory() {
123024
123224
  }
@@ -126411,7 +126611,9 @@ ${buttons.join("\n")}`;
126411
126611
  host.scheduleCompletedDebounceFlush(flushDelay);
126412
126612
  }
126413
126613
  } else if (newStatus === "idle" && host.lastStatus === "starting") {
126414
- host.emitAgentReadyOnce(chatTitle, now);
126614
+ if (adapterStatus.fsmReadySeen !== false) {
126615
+ host.emitAgentReadyOnce(chatTitle, now);
126616
+ }
126415
126617
  if (host.startupGraceCollapseAt === null) host.startupGraceCollapseAt = now;
126416
126618
  host.maybeSynthesizeStartupGraceCollapse(chatTitle, now, "startup_grace_fast_collapse");
126417
126619
  } else if (newStatus === "error") {
@@ -130753,6 +130955,12 @@ ${rawInput}` : rawInput;
130753
130955
  return managedBy === managerTag;
130754
130956
  }
130755
130957
  init_auto_approve_modes();
130958
+ function expandModelLaunchArgs(template, model, valueMap = void 0) {
130959
+ const requested = typeof model === "string" ? model.trim() : "";
130960
+ if (!requested || !Array.isArray(template) || template.length === 0) return void 0;
130961
+ const mapped = typeof valueMap?.[requested] === "string" && valueMap[requested].trim() ? valueMap[requested].trim() : requested;
130962
+ return template.map((part) => part.includes("{{model}}") ? part.split("{{model}}").join(mapped) : part);
130963
+ }
130756
130964
  function isExplicitCommand(command) {
130757
130965
  const trimmed = command.trim();
130758
130966
  return path50.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
@@ -131005,11 +131213,6 @@ ${rawInput}` : rawInput;
131005
131213
  return expanded;
131006
131214
  });
131007
131215
  }
131008
- function expandModelLaunchArgs(template, model) {
131009
- const m = typeof model === "string" ? model.trim() : "";
131010
- if (!m || !Array.isArray(template) || template.length === 0) return void 0;
131011
- return template.map((part) => part.includes("{{model}}") ? part.split("{{model}}").join(m) : part);
131012
- }
131013
131216
  function expandThinkingLaunchArgs(template, level, levelMap) {
131014
131217
  const raw = typeof level === "string" ? level.trim() : "";
131015
131218
  if (!raw || !Array.isArray(template) || template.length === 0) return void 0;
@@ -131506,7 +131709,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
131506
131709
  const autoApproveLaunch = applyAutoApproveModeLaunchArgs(versionResolvedProvider, cliArgs, launchSettings);
131507
131710
  const launchProvider = autoApproveLaunch.provider || provider;
131508
131711
  const cliArgsWithAutoApprove = autoApproveLaunch.cliArgs;
131509
- const modelLaunchArgs = expandModelLaunchArgs(launchProvider?.modelLaunchArgs, initialModel);
131712
+ const modelLaunchArgs = expandModelLaunchArgs(
131713
+ launchProvider?.modelLaunchArgs,
131714
+ initialModel,
131715
+ launchProvider?.modelLaunchValueMap
131716
+ );
131510
131717
  const cliArgsWithModel = modelLaunchArgs ? [...modelLaunchArgs, ...cliArgsWithAutoApprove || []] : cliArgsWithAutoApprove;
131511
131718
  if (initialModel && !modelLaunchArgs) {
131512
131719
  LOG2.warn("CLI", `[${normalizedType}] initialModel='${initialModel}' requested but provider declares no modelLaunchArgs template \u2014 launching without model selection.`);
@@ -132583,6 +132790,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
132583
132790
  "details",
132584
132791
  "autoApproveModes",
132585
132792
  "modelLaunchArgs",
132793
+ "modelLaunchValueMap",
132586
132794
  "modelOptions",
132587
132795
  "thinkingLaunchArgs",
132588
132796
  "thinkingLevelMap",
@@ -136828,7 +137036,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
136828
137036
  normalizeRepoMeshDeclarativeConfig: normalizeRepoMeshDeclarativeConfig2,
136829
137037
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
136830
137038
  } = await Promise.resolve().then(() => (init_mesh_json_config(), mesh_json_config_exports));
136831
- const { existsSync: existsSync75, readFileSync: readFileSync59, mkdirSync: mkdirSync35, writeFileSync: writeFileSync33 } = await import("fs");
137039
+ const { existsSync: existsSync76, readFileSync: readFileSync59, mkdirSync: mkdirSync35, writeFileSync: writeFileSync33 } = await import("fs");
136832
137040
  const { dirname: dirname26, join: join75 } = await import("path");
136833
137041
  const yaml6 = await Promise.resolve().then(() => (init_js_yaml(), js_yaml_exports));
136834
137042
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
@@ -136837,7 +137045,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
136837
137045
  let existedAsYaml = false;
136838
137046
  for (const relative8 of MESH_JSON_CONFIG_LOCATIONS2) {
136839
137047
  const candidate = join75(workspace, relative8);
136840
- if (!existsSync75(candidate)) continue;
137048
+ if (!existsSync76(candidate)) continue;
136841
137049
  try {
136842
137050
  const text = readFileSync59(candidate, "utf-8");
136843
137051
  const parsed = /\.json$/i.test(candidate) ? JSON.parse(text) : yaml6.load(text);
@@ -139410,7 +139618,7 @@ ${ptyResult.output.slice(-2e3)}`);
139410
139618
  workspace
139411
139619
  };
139412
139620
  }
139413
- const { existsSync: existsSync75, readFileSync: readFileSync59, writeFileSync: writeFileSync33, copyFileSync: copyFileSync4, mkdirSync: mkdirSync35 } = await import("fs");
139621
+ const { existsSync: existsSync76, readFileSync: readFileSync59, writeFileSync: writeFileSync33, copyFileSync: copyFileSync4, mkdirSync: mkdirSync35 } = await import("fs");
139414
139622
  const { dirname: dirname26 } = await import("path");
139415
139623
  const mcpConfigPath = coordinatorSetup.configPath;
139416
139624
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -139455,7 +139663,7 @@ ${ptyResult.output.slice(-2e3)}`);
139455
139663
  if (hermesManualFallback) return returnManualFallback(message);
139456
139664
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
139457
139665
  }
139458
- const hadExistingMcpConfig = existsSync75(mcpConfigPath);
139666
+ const hadExistingMcpConfig = existsSync76(mcpConfigPath);
139459
139667
  let existingMcpConfig = hermesBaseConfig?.config || {};
139460
139668
  if (hermesBaseConfig) {
139461
139669
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname26(mcpConfigPath));
@@ -140273,7 +140481,7 @@ ${ptyResult.output.slice(-2e3)}`);
140273
140481
  const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
140274
140482
  const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
140275
140483
  const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
140276
- const { existsSync: existsSync75 } = await import("fs");
140484
+ const { existsSync: existsSync76 } = await import("fs");
140277
140485
  const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
140278
140486
  const mesh = meshRecord?.mesh;
140279
140487
  if (!mesh) return { success: false, error: "Mesh not found" };
@@ -140292,7 +140500,7 @@ ${ptyResult.output.slice(-2e3)}`);
140292
140500
  const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
140293
140501
  for (const item of derivation.items) {
140294
140502
  const workspace = item.workspace;
140295
- if (!workspace || !existsSync75(workspace)) continue;
140503
+ if (!workspace || !existsSync76(workspace)) continue;
140296
140504
  const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
140297
140505
  try {
140298
140506
  const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
@@ -153946,10 +154154,10 @@ ${upgradeFailureNotice.notice}${supersededHint}`);
153946
154154
  init_fsm_evaluator();
153947
154155
  init_fsm_loader();
153948
154156
  var crypto9 = __toESM2(require("crypto"));
153949
- var import_node_fs10 = require("fs");
154157
+ var import_node_fs11 = require("fs");
153950
154158
  var import_node_path6 = require("path");
153951
154159
  init_provider_cli_shared();
153952
- var import_node_fs11 = require("fs");
154160
+ var import_node_fs12 = require("fs");
153953
154161
  var import_node_path7 = require("path");
153954
154162
  init_manifest();
153955
154163
  var V1_PRIMITIVE_CATALOG = Object.freeze({