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

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 ? "f13d08263df6a24da9d6766eebfbfc7cac237235" : void 0) ?? "unknown";
36915
+ const commitShort = readInjected(true ? "f13d0826" : void 0) ?? (commit !== "unknown" ? commit.slice(0, 7) : "unknown");
36916
+ const version2 = readInjected(true ? "1.0.58-rc.47" : void 0) ?? readInjected(typeof process !== "undefined" ? process.env?.ADHDEV_PKG_VERSION : void 0) ?? "unknown";
36917
+ const builtAt = readInjected(true ? "2026-08-30T09:04:38.562Z" : 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;
41536
41547
  }
41537
- function baseUrl4(env2) {
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;
41576
+ }
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);
@@ -73985,6 +74031,96 @@ ${rendered}`, "utf-8");
73985
74031
  return { status: "failed", attemptId: presentation.attemptId, stage };
73986
74032
  }
73987
74033
  }
74034
+ function pushTerminalBucket(buckets, key2, terminal) {
74035
+ if (!key2) return;
74036
+ let bucket2 = buckets.get(key2);
74037
+ if (!bucket2) {
74038
+ bucket2 = { real: [], approval: [] };
74039
+ buckets.set(key2, bucket2);
74040
+ }
74041
+ (terminal.entry.kind === "task_approval_needed" ? bucket2.approval : bucket2.real).push(terminal);
74042
+ }
74043
+ function pushTerminalQuery(queries, key2, query) {
74044
+ if (!key2) return;
74045
+ const existing = queries.get(key2);
74046
+ if (existing) existing.push(query);
74047
+ else queries.set(key2, [query]);
74048
+ }
74049
+ function earlierTerminal(a, b) {
74050
+ if (!a) return b;
74051
+ if (!b) return a;
74052
+ return a.order <= b.order ? a : b;
74053
+ }
74054
+ function buildMeshActiveWorkLedgerSnapshot(ledgerEntries, options = {}) {
74055
+ const timestampByEntry = /* @__PURE__ */ new Map();
74056
+ for (const entry of ledgerEntries) timestampByEntry.set(entry, new Date(entry.timestamp).getTime());
74057
+ const entries = ledgerEntries.slice().sort((a, b) => timestampByEntry.get(a) - timestampByEntry.get(b));
74058
+ const taskBuckets = /* @__PURE__ */ new Map();
74059
+ const sessionBuckets = /* @__PURE__ */ new Map();
74060
+ const nodeBuckets = /* @__PURE__ */ new Map();
74061
+ let order = 0;
74062
+ for (const entry of entries) {
74063
+ if (!TERMINAL_LEDGER_KINDS.has(entry.kind) && entry.kind !== "task_approval_needed") continue;
74064
+ const timestampMs = timestampByEntry.get(entry);
74065
+ if (!Number.isFinite(timestampMs)) continue;
74066
+ const indexed = { entry, timestampMs, order: order++ };
74067
+ const taskId = readString7(entry.payload?.taskId);
74068
+ if (taskId) {
74069
+ pushTerminalBucket(taskBuckets, taskId, indexed);
74070
+ } else {
74071
+ pushTerminalBucket(sessionBuckets, readString7(entry.sessionId), indexed);
74072
+ pushTerminalBucket(nodeBuckets, machineCoreFromDaemonId(entry.nodeId), indexed);
74073
+ }
74074
+ }
74075
+ return {
74076
+ entries,
74077
+ matchDirectDispatchTerminals(dispatches) {
74078
+ const sortedDispatches = dispatches.slice().sort((a, b) => timestampByEntry.get(a) - timestampByEntry.get(b));
74079
+ const taskQueries = /* @__PURE__ */ new Map();
74080
+ const sessionQueries = /* @__PURE__ */ new Map();
74081
+ const nodeQueries = /* @__PURE__ */ new Map();
74082
+ for (const dispatch of sortedDispatches) {
74083
+ const timestampMs = timestampByEntry.get(dispatch) ?? new Date(dispatch.timestamp).getTime();
74084
+ if (!Number.isFinite(timestampMs)) continue;
74085
+ const query = { dispatch, timestampMs };
74086
+ pushTerminalQuery(taskQueries, directDispatchTaskId(dispatch), query);
74087
+ const sessionId = readString7(dispatch.sessionId);
74088
+ if (dispatch.sessionId) pushTerminalQuery(sessionQueries, sessionId, query);
74089
+ else pushTerminalQuery(nodeQueries, machineCoreFromDaemonId(dispatch.nodeId), query);
74090
+ }
74091
+ const realByDispatch = /* @__PURE__ */ new Map();
74092
+ const approvalByDispatch = /* @__PURE__ */ new Map();
74093
+ const resolve32 = (queries, buckets, bucketKind, output) => {
74094
+ for (const [key2, bucketQueries] of queries) {
74095
+ const terminals = buckets.get(key2)?.[bucketKind];
74096
+ if (!terminals?.length) continue;
74097
+ let cursor = 0;
74098
+ for (const query of bucketQueries) {
74099
+ while (cursor < terminals.length) {
74100
+ options.onTerminalProbe?.();
74101
+ if (terminals[cursor].timestampMs >= query.timestampMs) break;
74102
+ cursor += 1;
74103
+ }
74104
+ const candidate = terminals[cursor];
74105
+ if (candidate) output.set(query.dispatch, earlierTerminal(output.get(query.dispatch), candidate));
74106
+ }
74107
+ }
74108
+ };
74109
+ resolve32(taskQueries, taskBuckets, "real", realByDispatch);
74110
+ resolve32(sessionQueries, sessionBuckets, "real", realByDispatch);
74111
+ resolve32(nodeQueries, nodeBuckets, "real", realByDispatch);
74112
+ resolve32(taskQueries, taskBuckets, "approval", approvalByDispatch);
74113
+ resolve32(sessionQueries, sessionBuckets, "approval", approvalByDispatch);
74114
+ resolve32(nodeQueries, nodeBuckets, "approval", approvalByDispatch);
74115
+ const result = /* @__PURE__ */ new Map();
74116
+ for (const dispatch of sortedDispatches) {
74117
+ const selected = realByDispatch.get(dispatch) || approvalByDispatch.get(dispatch);
74118
+ if (selected) result.set(dispatch, selected.entry);
74119
+ }
74120
+ return result;
74121
+ }
74122
+ };
74123
+ }
73988
74124
  function readString7(value) {
73989
74125
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
73990
74126
  }
@@ -74056,13 +74192,6 @@ ${rendered}`, "utf-8");
74056
74192
  function directDispatchTaskId(entry) {
74057
74193
  return readString7(entry.payload?.taskId) || entry.id;
74058
74194
  }
74059
- function terminalMatchesDispatch(terminal, dispatch, taskId) {
74060
- const terminalTaskId = readString7(terminal.payload?.taskId);
74061
- if (terminalTaskId && terminalTaskId === taskId) return true;
74062
- if (terminalTaskId && terminalTaskId !== taskId) return false;
74063
- if (dispatch.sessionId && sessionIdsEquivalent(terminal.sessionId, dispatch.sessionId)) return true;
74064
- return Boolean(dispatch.nodeId && daemonIdsEquivalent(terminal.nodeId, dispatch.nodeId) && !dispatch.sessionId);
74065
- }
74066
74195
  function statusFromTerminal(entry) {
74067
74196
  if (entry.kind === "task_approval_needed") return "awaiting_approval";
74068
74197
  if (entry.kind === "task_question_pending") return "awaiting_choice";
@@ -74079,8 +74208,7 @@ ${rendered}`, "utf-8");
74079
74208
  }
74080
74209
  function buildLedgerDirectDispatchRecord(dispatch, ctx) {
74081
74210
  const taskId = directDispatchTaskId(dispatch);
74082
- const matching = ctx.terminals.filter((entry) => new Date(entry.timestamp).getTime() >= new Date(dispatch.timestamp).getTime()).filter((entry) => terminalMatchesDispatch(entry, dispatch, taskId));
74083
- const terminal = matching.find((entry) => entry.kind !== "task_approval_needed") || matching[0];
74211
+ const terminal = ctx.terminal;
74084
74212
  const terminalStatus = terminal ? statusFromTerminal(terminal) : void 0;
74085
74213
  const live = sessionStatusFromNodes(ctx.nodes, dispatch.nodeId, dispatch.sessionId);
74086
74214
  const status = terminalStatus || live.status || "assigned";
@@ -74181,6 +74309,8 @@ ${rendered}`, "utf-8");
74181
74309
  }
74182
74310
  function buildMeshActiveWork(opts) {
74183
74311
  const now = opts.now ?? Date.now();
74312
+ const ledgerSnapshot = opts.ledgerSnapshot ?? buildMeshActiveWorkLedgerSnapshot(opts.ledgerEntries || []);
74313
+ const ledgerEntries = ledgerSnapshot.entries;
74184
74314
  const records = [];
74185
74315
  const staleDirectWork = [];
74186
74316
  const terminalDirectWork = [];
@@ -74191,7 +74321,7 @@ ${rendered}`, "utf-8");
74191
74321
  const queueNodeId = task.assignedNodeId || task.targetNodeId;
74192
74322
  const queueSessionId = task.assignedSessionId || task.targetSessionId;
74193
74323
  const queueLive = task.status === "assigned" ? sessionStatusFromNodes(opts.nodes, queueNodeId ?? void 0, queueSessionId ?? void 0) : {};
74194
- const queueTerminalAuthority = task.status === "assigned" && hasTerminalLedgerAuthorityForTask(opts.ledgerEntries, task.id);
74324
+ const queueTerminalAuthority = task.status === "assigned" && hasTerminalLedgerAuthorityForTask(ledgerEntries, task.id);
74195
74325
  let queueStatus = !queueTerminalAuthority && (queueLive.status === "awaiting_approval" || queueLive.status === "awaiting_choice" || queueLive.status === "generating") ? queueLive.status : task.status;
74196
74326
  const turnOverlay = task.status === "assigned" ? turnProjectionActiveWorkStatus(opts.meshId, task.id) : null;
74197
74327
  if (turnOverlay) queueStatus = turnOverlay.status;
@@ -74221,7 +74351,7 @@ ${rendered}`, "utf-8");
74221
74351
  const dbStatus = dispatch.status;
74222
74352
  const isTerminal = dbStatus === "completed" || dbStatus === "failed" || dbStatus === "stale";
74223
74353
  const turnOverlay = isTerminal ? null : turnProjectionActiveWorkStatus(opts.meshId, dispatch.taskId);
74224
- const directTerminalAuthority = !isTerminal && hasTerminalLedgerAuthorityForTask(opts.ledgerEntries, dispatch.taskId);
74354
+ const directTerminalAuthority = !isTerminal && hasTerminalLedgerAuthorityForTask(ledgerEntries, dispatch.taskId);
74225
74355
  const liveStatus = directTerminalAuthority ? void 0 : live.status;
74226
74356
  const status = isTerminal ? dbStatus === "completed" ? "idle" : "failed" : turnOverlay?.status || liveStatus || (dbStatus === "acked" ? "generating" : "assigned");
74227
74357
  const { ledgerOnlyStaleReason, isFreshUnacknowledged } = classifyDirectDispatch({
@@ -74265,12 +74395,12 @@ ${rendered}`, "utf-8");
74265
74395
  }
74266
74396
  records.push(record2);
74267
74397
  }
74268
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
74269
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
74270
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
74398
+ const ledgerDispatches = ledgerEntries.filter(isDirectDispatch);
74399
+ const terminalByDispatch = ledgerSnapshot.matchDirectDispatchTerminals(ledgerDispatches);
74400
+ for (const dispatch of ledgerDispatches) {
74271
74401
  if (dbTaskIds.has(directDispatchTaskId(dispatch))) continue;
74272
74402
  if (queueTaskIds.has(directDispatchTaskId(dispatch))) continue;
74273
- const { record: record2, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminals, nodes: opts.nodes, now });
74403
+ const { record: record2, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminal: terminalByDispatch.get(dispatch), nodes: opts.nodes, now });
74274
74404
  if (terminalRow) {
74275
74405
  terminalDirectWork.push(record2);
74276
74406
  if (opts.includeTerminalDirect !== true) continue;
@@ -74282,11 +74412,11 @@ ${rendered}`, "utf-8");
74282
74412
  records.push(record2);
74283
74413
  }
74284
74414
  } else {
74285
- const ledgerEntries = (opts.ledgerEntries || []).slice().sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
74286
- const terminals = ledgerEntries.filter((entry) => TERMINAL_LEDGER_KINDS.has(entry.kind) || entry.kind === "task_approval_needed");
74287
- for (const dispatch of ledgerEntries.filter(isDirectDispatch)) {
74415
+ const ledgerDispatches = ledgerEntries.filter(isDirectDispatch);
74416
+ const terminalByDispatch = ledgerSnapshot.matchDirectDispatchTerminals(ledgerDispatches);
74417
+ for (const dispatch of ledgerDispatches) {
74288
74418
  if (queueTaskIds.has(directDispatchTaskId(dispatch))) continue;
74289
- const { record: record2, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminals, nodes: opts.nodes, now });
74419
+ const { record: record2, terminalRow } = buildLedgerDirectDispatchRecord(dispatch, { terminal: terminalByDispatch.get(dispatch), nodes: opts.nodes, now });
74290
74420
  if (terminalRow) {
74291
74421
  terminalDirectWork.push(record2);
74292
74422
  if (opts.includeTerminalDirect !== true) continue;
@@ -74328,6 +74458,7 @@ ${rendered}`, "utf-8");
74328
74458
  meshId: opts.meshId,
74329
74459
  queue: opts.queue,
74330
74460
  ledgerEntries: opts.ledgerEntries,
74461
+ ledgerSnapshot: opts.ledgerSnapshot,
74331
74462
  directDispatches: opts.directDispatches,
74332
74463
  nodes: opts.nodes,
74333
74464
  now,
@@ -74480,13 +74611,13 @@ ${rendered}`, "utf-8");
74480
74611
  ${lines.join("\n")}
74481
74612
  The mesh has no work in flight. For each mission, decide its outcome: continue it (enqueue/dispatch the remaining work) or close it with mesh_mission_upsert(mission_id, status: "completed" | "abandoned"). Do not leave a finished mission in 'active'. This is a one-time reminder.`;
74482
74613
  }
74483
- function maybeInjectIdleActiveMissionReminder(meshId, coordinator, policy, now = Date.now(), instanceManager) {
74614
+ function maybeInjectIdleActiveMissionReminder(meshId, coordinator, policy, now = Date.now(), instanceManager, sharedLedgerSnapshot) {
74484
74615
  try {
74485
74616
  if (!coordinator) return false;
74486
74617
  if (policy?.idleActiveMissionReminder === false) return false;
74487
74618
  const activeMissions = getMeshMissions(meshId, ["active"]);
74488
74619
  if (activeMissions.length === 0) return false;
74489
- const ledgerEntries = readLedgerEntriesByKind(meshId, [
74620
+ const ledgerEntries = sharedLedgerSnapshot?.entries ?? readLedgerEntriesByKind(meshId, [
74490
74621
  "task_dispatched",
74491
74622
  "task_completed",
74492
74623
  "task_failed",
@@ -74499,6 +74630,7 @@ The mesh has no work in flight. For each mission, decide its outcome: continue i
74499
74630
  queue: getQueue(meshId),
74500
74631
  directDispatches: getActiveDirectDispatches(meshId),
74501
74632
  ledgerEntries,
74633
+ ledgerSnapshot: sharedLedgerSnapshot,
74502
74634
  now
74503
74635
  }).summary;
74504
74636
  if (summary.totalActiveCount !== 0 || summary.generatingCount !== 0) return false;
@@ -82142,6 +82274,25 @@ ${block2.text}`,
82142
82274
  launchedByCoordinator: true,
82143
82275
  autoLaunchedForQueueTaskId: task.id
82144
82276
  };
82277
+ const requiredTags = Array.isArray(task.requiredTags) ? task.requiredTags.filter((t) => !!t) : [];
82278
+ const buildRoutingDecision = () => buildAutoLaunchRoutingDecision({
82279
+ node,
82280
+ meshId,
82281
+ task: { difficulty: task.difficulty, requiredTags: task.requiredTags },
82282
+ resolved,
82283
+ quotaRouting: mesh?.policy?.quotaRouting ?? null,
82284
+ quotaFactsContext: quotaFactsContextForLiveRouting(mesh, isLocalAutoLaunchNode, components.providerLoader),
82285
+ skippedCandidates,
82286
+ requiredTagsResult: {
82287
+ required: requiredTags,
82288
+ satisfied: !requiredTags.length || nodeSatisfiesRequiredTags(requiredTags, buildMeshNodeCapabilityTags(node, effectiveProviderType)),
82289
+ missing: requiredTags.filter((t) => !buildMeshNodeCapabilityTags(node, effectiveProviderType).includes(t))
82290
+ },
82291
+ effectiveModel,
82292
+ effectiveThinkingLevel,
82293
+ executedSlot: slotDecision.slot,
82294
+ demotionReason
82295
+ });
82145
82296
  if (launchTarget.mode === "remote") {
82146
82297
  const remoteSettings = {
82147
82298
  ...launchSettings,
@@ -82185,7 +82336,15 @@ ${block2.text}`,
82185
82336
  await waitForRemoteSessionReady(meshId, nodeId, remoteSessionId, {
82186
82337
  isReady: remoteSessionReadyProbe(meshId, nodeId, remoteSessionId)
82187
82338
  }).catch(() => false);
82188
- claimAfterRemoteAutoLaunch(components, meshId, nodeId, remoteSessionId, effectiveProviderType, tryAssignQueueTask);
82339
+ const routingDecision2 = buildRoutingDecision();
82340
+ claimAfterRemoteAutoLaunch(
82341
+ components,
82342
+ meshId,
82343
+ nodeId,
82344
+ remoteSessionId,
82345
+ effectiveProviderType,
82346
+ (c, m, n, s2, p) => tryAssignQueueTask(c, m, n, s2, p, routingDecision2, void 0, "auto_launch")
82347
+ );
82189
82348
  }
82190
82349
  return true;
82191
82350
  }
@@ -82217,25 +82376,7 @@ ${block2.text}`,
82217
82376
  markAutoLaunch(meshId, task.id, { status: "completed", nodeId, providerType: effectiveProviderType, sessionId, ...effectiveModel ? { model: effectiveModel } : {}, ...effectiveThinkingLevel ? { thinkingLevel: effectiveThinkingLevel } : {} });
82218
82377
  logAutoLaunchQuotaFallbackSuccess(resolved, task.id, nodeId, sessionId);
82219
82378
  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
- });
82379
+ const routingDecision = buildRoutingDecision();
82239
82380
  tryAssignQueueTask(components, meshId, nodeId, sessionId, effectiveProviderType, routingDecision, void 0, "auto_launch");
82240
82381
  return true;
82241
82382
  } catch (e) {
@@ -86996,6 +87137,7 @@ ${cleanBody}`;
86996
87137
  }
86997
87138
  var DEFAULT_RECONCILE_INTERVAL_MS;
86998
87139
  var DEFAULT_AUTO_PRUNE_MIN_AGE_MS;
87140
+ var DEFAULT_AUTO_PRUNE_INTERVAL_MS;
86999
87141
  var DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS;
87000
87142
  var init_mesh_reconcile_config = __esm2({
87001
87143
  "src/mesh/mesh-reconcile-config.ts"() {
@@ -87004,28 +87146,80 @@ ${cleanBody}`;
87004
87146
  init_mesh_reconcile_acked_hold();
87005
87147
  DEFAULT_RECONCILE_INTERVAL_MS = 4e3;
87006
87148
  DEFAULT_AUTO_PRUNE_MIN_AGE_MS = 24 * 60 * 6e4;
87149
+ DEFAULT_AUTO_PRUNE_INTERVAL_MS = 6e4;
87007
87150
  DEFAULT_PENDING_HELD_DRAIN_ESCALATE_MS = 12e3;
87008
87151
  }
87009
87152
  });
87153
+ function resolveRemotePullBackoffMs(backoffRound) {
87154
+ const shift = Math.max(0, Math.min(backoffRound - 1, 8));
87155
+ return Math.min(REMOTE_PULL_BACKOFF_MAX_MS, REMOTE_PULL_BACKOFF_BASE_MS * 2 ** shift);
87156
+ }
87157
+ function pullBackoffKey(meshId, daemonId) {
87158
+ return `${meshId}::${canonicalDaemonId(daemonId) ?? daemonId}`;
87159
+ }
87160
+ function isRemotePullBackedOff(meshId, daemonId, nowMs) {
87161
+ const state = remotePullBackoffByDaemon.get(pullBackoffKey(meshId, daemonId));
87162
+ return !!state && nowMs < state.nextPullAtMs;
87163
+ }
87164
+ function noteRemotePullResult(meshId, daemonId, result, nowMs) {
87165
+ const key2 = pullBackoffKey(meshId, daemonId);
87166
+ if (result.received > 0) {
87167
+ remotePullBackoffByDaemon.delete(key2);
87168
+ return;
87169
+ }
87170
+ if (!result.reached) return;
87171
+ const prev = remotePullBackoffByDaemon.get(key2);
87172
+ const emptyRounds = (prev?.emptyRounds ?? 0) + 1;
87173
+ const backoffRound = emptyRounds - REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF + 1;
87174
+ remotePullBackoffByDaemon.set(key2, {
87175
+ emptyRounds,
87176
+ nextPullAtMs: emptyRounds >= REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF ? nowMs + resolveRemotePullBackoffMs(backoffRound) : 0
87177
+ });
87178
+ }
87010
87179
  async function pullRemoteNodeQueues(components, mesh, localDaemonId, candidateDaemonIds) {
87011
87180
  const dispatchMeshCommand = components.dispatchMeshCommand;
87012
87181
  if (!dispatchMeshCommand) return;
87013
87182
  const meshId = mesh.id;
87014
87183
  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)));
87184
+ const uniqueNodes = [];
87185
+ const seenDaemonIds = /* @__PURE__ */ new Set();
87186
+ for (const node of mesh.nodes) {
87187
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
87188
+ if (!nodeDaemonId) continue;
87189
+ const daemonKey = canonicalDaemonId(nodeDaemonId) ?? nodeDaemonId;
87190
+ if (seenDaemonIds.has(daemonKey)) continue;
87191
+ seenDaemonIds.add(daemonKey);
87192
+ uniqueNodes.push(node);
87193
+ }
87194
+ await Promise.allSettled(uniqueNodes.map((node) => (async () => {
87195
+ const nodeDaemonId = readNonEmptyString(node.daemonId);
87196
+ if (nodeDaemonId && isRemotePullBackedOff(meshId, nodeDaemonId, Date.now())) return;
87197
+ const result = await pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls);
87198
+ if (nodeDaemonId) noteRemotePullResult(meshId, nodeDaemonId, result, Date.now());
87199
+ })()));
87016
87200
  }
87017
- async function pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls) {
87201
+ async function pullPendingEventsFromNode(components, meshId, node, localDaemonId, candidateDaemonIds, pulls, opts) {
87018
87202
  const dispatchMeshCommand = components.dispatchMeshCommand;
87019
- if (!dispatchMeshCommand) return;
87203
+ if (!dispatchMeshCommand) return NOT_REACHED;
87020
87204
  const nodeDaemonId = readNonEmptyString(node.daemonId);
87021
- if (!nodeDaemonId) return;
87022
- if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) return;
87023
- if (daemonIdListIncludes(candidateDaemonIds, nodeDaemonId)) return;
87205
+ if (!nodeDaemonId) return NOT_REACHED;
87206
+ if (daemonIdsEquivalent(nodeDaemonId, localDaemonId)) return NOT_REACHED;
87207
+ if (daemonIdListIncludes(candidateDaemonIds, nodeDaemonId)) return NOT_REACHED;
87024
87208
  const getPeerStatus = components.getMeshPeerConnectionStatus;
87025
87209
  if (getPeerStatus) {
87026
87210
  const peerSnapshot = getPeerStatus(nodeDaemonId);
87027
- if (!peerSnapshot || String(peerSnapshot.state) !== "connected") return;
87211
+ if (!peerSnapshot || String(peerSnapshot.state) !== "connected") return NOT_REACHED;
87212
+ }
87213
+ const throttleKey = pullBackoffKey(meshId, nodeDaemonId);
87214
+ if (opts?.minIntervalSinceLastPullMs) {
87215
+ const lastPullAt = lastRedrivePullAtMs.get(throttleKey);
87216
+ if (lastPullAt !== void 0 && Date.now() - lastPullAt < opts.minIntervalSinceLastPullMs) {
87217
+ return NOT_REACHED;
87218
+ }
87028
87219
  }
87220
+ let received = 0;
87221
+ let completedPulls = 0;
87222
+ if (opts?.minIntervalSinceLastPullMs) lastRedrivePullAtMs.set(throttleKey, Date.now());
87029
87223
  for (const pendingEventArgs of pulls) {
87030
87224
  let events;
87031
87225
  try {
@@ -87033,7 +87227,11 @@ ${cleanBody}`;
87033
87227
  } catch {
87034
87228
  break;
87035
87229
  }
87036
- const list = extractPendingEvents(events).filter((e) => readNonEmptyString(e?.meshId) === meshId);
87230
+ const extracted = extractPendingEventsResult(events);
87231
+ if (!extracted.confirmed) break;
87232
+ completedPulls++;
87233
+ received += extracted.events.length;
87234
+ const list = extracted.events.filter((e) => readNonEmptyString(e?.meshId) === meshId);
87037
87235
  for (const event of list) {
87038
87236
  const payload = buildForwardPayloadFromPending(event);
87039
87237
  if (!payload.event || !payload.meshId) continue;
@@ -87043,6 +87241,7 @@ ${cleanBody}`;
87043
87241
  }
87044
87242
  }
87045
87243
  }
87244
+ return { received, reached: completedPulls === pulls.length };
87046
87245
  }
87047
87246
  function unwrapReadChatPayload(raw) {
87048
87247
  let cursor = raw;
@@ -87150,12 +87349,13 @@ ${cleanBody}`;
87150
87349
  }
87151
87350
  return [];
87152
87351
  }
87153
- function extractPendingEvents(raw) {
87352
+ function extractPendingEventsResult(raw) {
87154
87353
  let cursor = raw;
87155
87354
  for (let depth = 0; depth < 4 && cursor && typeof cursor === "object"; depth++) {
87156
- if (Array.isArray(cursor)) return cursor;
87355
+ if (Array.isArray(cursor)) return { events: cursor, confirmed: true };
87157
87356
  const record2 = cursor;
87158
- if (Array.isArray(record2.events)) return record2.events;
87357
+ if (record2.success === false) return { events: [], confirmed: false };
87358
+ if (Array.isArray(record2.events)) return { events: record2.events, confirmed: true };
87159
87359
  if (record2.payload && typeof record2.payload === "object") {
87160
87360
  cursor = record2.payload;
87161
87361
  continue;
@@ -87170,7 +87370,7 @@ ${cleanBody}`;
87170
87370
  }
87171
87371
  break;
87172
87372
  }
87173
- return [];
87373
+ return { events: [], confirmed: false };
87174
87374
  }
87175
87375
  function buildForwardPayloadFromPending(event) {
87176
87376
  const metadata = event?.metadataEvent && typeof event.metadataEvent === "object" ? event.metadataEvent : {};
@@ -87210,6 +87410,13 @@ ${cleanBody}`;
87210
87410
  ...serializeV2EnvelopeToWire(event)
87211
87411
  };
87212
87412
  }
87413
+ var REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF;
87414
+ var REMOTE_PULL_BACKOFF_BASE_MS;
87415
+ var REMOTE_PULL_BACKOFF_MAX_MS;
87416
+ var REDRIVE_PULL_MIN_INTERVAL_MS;
87417
+ var remotePullBackoffByDaemon;
87418
+ var lastRedrivePullAtMs;
87419
+ var NOT_REACHED;
87213
87420
  var init_mesh_remote_event_pull = __esm2({
87214
87421
  "src/mesh/mesh-remote-event-pull.ts"() {
87215
87422
  "use strict";
@@ -87218,6 +87425,13 @@ ${cleanBody}`;
87218
87425
  init_mesh_events_utils();
87219
87426
  init_dist();
87220
87427
  init_mesh_reconcile_identity();
87428
+ REMOTE_PULL_EMPTY_ROUNDS_BEFORE_BACKOFF = 3;
87429
+ REMOTE_PULL_BACKOFF_BASE_MS = 8e3;
87430
+ REMOTE_PULL_BACKOFF_MAX_MS = 3e4;
87431
+ REDRIVE_PULL_MIN_INTERVAL_MS = 2e3;
87432
+ remotePullBackoffByDaemon = /* @__PURE__ */ new Map();
87433
+ lastRedrivePullAtMs = /* @__PURE__ */ new Map();
87434
+ NOT_REACHED = { received: 0, reached: false };
87221
87435
  }
87222
87436
  });
87223
87437
  function formatBytes(bytes) {
@@ -89658,10 +89872,18 @@ ${cleanBody}`;
89658
89872
  }
89659
89873
  }
89660
89874
  }
89661
- async function autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs) {
89875
+ async function autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs, sharedLedgerSnapshot) {
89662
89876
  const directDispatches = getActiveDirectDispatches(mesh.id);
89663
- if (directDispatches.length === 0) return;
89877
+ if (directDispatches.length === 0) return void 0;
89664
89878
  const liveNodes = await collectLiveNodesWithSessions(components, mesh, selfIds, localDaemonId);
89879
+ const ledgerSnapshot = sharedLedgerSnapshot ?? buildMeshActiveWorkLedgerSnapshot(readLedgerEntriesByKind(mesh.id, [
89880
+ "task_dispatched",
89881
+ "task_completed",
89882
+ "task_failed",
89883
+ "task_stalled",
89884
+ "task_approval_needed",
89885
+ "task_question_pending"
89886
+ ]));
89665
89887
  const result = pruneStaleDirectDispatches({
89666
89888
  meshId: mesh.id,
89667
89889
  queue: getQueue(mesh.id),
@@ -89670,14 +89892,8 @@ ${cleanBody}`;
89670
89892
  // tail:500 window can be crowded out by unrelated mesh traffic while a still-active
89671
89893
  // dispatch's ledger evidence falls out of the window, risking a live dispatch being
89672
89894
  // misclassified as an orphan and pruned.
89673
- ledgerEntries: readLedgerEntriesByKind(mesh.id, [
89674
- "task_dispatched",
89675
- "task_completed",
89676
- "task_failed",
89677
- "task_stalled",
89678
- "task_approval_needed",
89679
- "task_question_pending"
89680
- ]),
89895
+ ledgerEntries: ledgerSnapshot.entries,
89896
+ ledgerSnapshot,
89681
89897
  directDispatches,
89682
89898
  nodes: liveNodes,
89683
89899
  execute: true,
@@ -89687,6 +89903,7 @@ ${cleanBody}`;
89687
89903
  if (result.prunedCount > 0) {
89688
89904
  LOG2.info("MeshReconcile", `Auto-pruned ${result.prunedCount} orphaned direct dispatch record(s) for mesh ${mesh.id}`);
89689
89905
  }
89906
+ return ledgerSnapshot;
89690
89907
  }
89691
89908
  async function fetchAssignedTaskChatTail(components, mesh, row, tailLimit = 10) {
89692
89909
  const sessionId = readNonEmptyString(row.assignedSessionId);
@@ -90639,7 +90856,8 @@ ${cleanBody}`;
90639
90856
  assignedNode,
90640
90857
  localDaemonId,
90641
90858
  selfIds,
90642
- selfIds.length > 0 ? selfIds.map((id) => ({ meshId, coordinatorDaemonId: id })) : [{ meshId }]
90859
+ selfIds.length > 0 ? selfIds.map((id) => ({ meshId, coordinatorDaemonId: id })) : [{ meshId }],
90860
+ { minIntervalSinceLastPullMs: REDRIVE_PULL_MIN_INTERVAL_MS }
90643
90861
  );
90644
90862
  } catch {
90645
90863
  }
@@ -91544,6 +91762,7 @@ ${cleanBody}`;
91544
91762
  return void 0;
91545
91763
  }
91546
91764
  })();
91765
+ const activeWorkLedgerSnapshots = /* @__PURE__ */ new Map();
91547
91766
  if (dispatchMeshCommand) {
91548
91767
  try {
91549
91768
  await retryUnresolvedDelegateForwards(components);
@@ -91701,11 +91920,16 @@ ${cleanBody}`;
91701
91920
  }
91702
91921
  {
91703
91922
  const minAgeMs = resolveAutoPruneMinAgeMs();
91923
+ const nowMs = Date.now();
91704
91924
  for (const mesh of listMeshes()) {
91705
91925
  const selfIds = resolveCoordinatorSelfIds(mesh, drainDaemonIds);
91706
91926
  if (!daemonHostsMesh(mesh, selfIds)) continue;
91927
+ const lastRunAt = lastAutoPruneRunAtByMesh.get(mesh.id);
91928
+ if (lastRunAt !== void 0 && nowMs - lastRunAt < DEFAULT_AUTO_PRUNE_INTERVAL_MS) continue;
91929
+ lastAutoPruneRunAtByMesh.set(mesh.id, nowMs);
91707
91930
  try {
91708
- await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
91931
+ const snapshot = await autoPruneStaleDirectDispatches(components, mesh, selfIds, localDaemonId, minAgeMs);
91932
+ if (snapshot) activeWorkLedgerSnapshots.set(mesh.id, snapshot);
91709
91933
  } catch (e) {
91710
91934
  LOG2.warn("MeshReconcile", `Auto-prune stale direct failed for mesh ${mesh.id}: ${e?.message || e}`);
91711
91935
  }
@@ -91932,7 +92156,8 @@ ${cleanBody}`;
91932
92156
  targetCoordinators[0].instance,
91933
92157
  getMesh(meshId)?.policy,
91934
92158
  void 0,
91935
- components.instanceManager
92159
+ components.instanceManager,
92160
+ activeWorkLedgerSnapshots.get(meshId)
91936
92161
  );
91937
92162
  continue;
91938
92163
  }
@@ -91999,6 +92224,7 @@ ${cleanBody}`;
91999
92224
  var lastDiskRetentionRunAt;
92000
92225
  var IDLE_SESSION_REAP_INTERVAL_MS;
92001
92226
  var lastIdleSessionReapRunAt;
92227
+ var lastAutoPruneRunAtByMesh;
92002
92228
  var init_mesh_reconcile_loop = __esm2({
92003
92229
  "src/mesh/mesh-reconcile-loop.ts"() {
92004
92230
  "use strict";
@@ -92037,6 +92263,7 @@ ${cleanBody}`;
92037
92263
  init_mesh_reconcile_unresolved_forward();
92038
92264
  DISK_RETENTION_INTERVAL_MS2 = 60 * 60 * 1e3;
92039
92265
  IDLE_SESSION_REAP_INTERVAL_MS = 5 * 60 * 1e3;
92266
+ lastAutoPruneRunAtByMesh = /* @__PURE__ */ new Map();
92040
92267
  }
92041
92268
  });
92042
92269
  var mesh_events_exports = {};
@@ -93797,6 +94024,14 @@ ${cleanBody}`;
93797
94024
  },
93798
94025
  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
94026
  },
94027
+ modelLaunchValueMap: {
94028
+ type: "object",
94029
+ additionalProperties: {
94030
+ type: "string",
94031
+ minLength: 1
94032
+ },
94033
+ 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."
94034
+ },
93800
94035
  modelOptions: {
93801
94036
  type: "array",
93802
94037
  items: {
@@ -95737,6 +95972,23 @@ ${tail}`;
95737
95972
  DEFAULT_REFINE_VITEST_MAX_WORKERS = 2;
95738
95973
  }
95739
95974
  });
95975
+ function sanitizeRefineGateChildEnv(env2 = process.env) {
95976
+ const sanitized = {};
95977
+ for (const [key2, value] of Object.entries(env2)) {
95978
+ if (key2.startsWith(ADHDEV_ENV_PREFIX) && !REFINE_GATE_ENV_ALLOWLIST.has(key2)) continue;
95979
+ sanitized[key2] = value;
95980
+ }
95981
+ return sanitized;
95982
+ }
95983
+ var ADHDEV_ENV_PREFIX;
95984
+ var REFINE_GATE_ENV_ALLOWLIST;
95985
+ var init_mesh_refine_env_sanitize = __esm2({
95986
+ "src/mesh/mesh-refine-env-sanitize.ts"() {
95987
+ "use strict";
95988
+ ADHDEV_ENV_PREFIX = "ADHDEV_";
95989
+ REFINE_GATE_ENV_ALLOWLIST = /* @__PURE__ */ new Set([]);
95990
+ }
95991
+ });
95740
95992
  function classifySubmoduleDivergence(submoduleRepoPath, baseCommit, branchCommit) {
95741
95993
  if (!baseCommit || !branchCommit) return "undeterminable";
95742
95994
  if (baseCommit === branchCommit) return "not_diverged";
@@ -97046,7 +97298,7 @@ ${mergeTreeErr?.stderr || ""}`;
97046
97298
  windowsHide: true,
97047
97299
  timeout,
97048
97300
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
97049
- env: { ...process.env, CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97301
+ env: { ...sanitizeRefineGateChildEnv(), CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97050
97302
  ...spawn7.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
97051
97303
  });
97052
97304
  summary.bootstrapCommandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -97092,7 +97344,7 @@ ${mergeTreeErr?.stderr || ""}`;
97092
97344
  windowsHide: true,
97093
97345
  timeout,
97094
97346
  maxBuffer: candidate.outputLimitBytes || REFINE_VALIDATION_OUTPUT_LIMIT_BYTES,
97095
- env: { ...process.env, CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97347
+ env: { ...sanitizeRefineGateChildEnv(), CI: process.env.CI || "1", ...refineGateChildEnv(), ...candidate.env || {} },
97096
97348
  ...spawn7.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
97097
97349
  });
97098
97350
  summary.commandsRun.push(commandRecord(candidate, cwd, startedAt, result, true, { exitCode: 0 }));
@@ -97154,6 +97406,7 @@ ${mergeTreeErr?.stderr || ""}`;
97154
97406
  import_node_child_process11 = require("child_process");
97155
97407
  init_resolve_executable();
97156
97408
  init_mesh_refine_worker_cap();
97409
+ init_mesh_refine_env_sanitize();
97157
97410
  init_mesh_refine_gitlink_utils();
97158
97411
  init_mesh_refine_submodule_converge();
97159
97412
  init_mesh_refine_gitlink_utils();
@@ -97349,12 +97602,38 @@ ${mergeTreeErr?.stderr || ""}`;
97349
97602
  };
97350
97603
  }
97351
97604
  });
97605
+ async function execChangeAreaGit(callSite, gitArgs, cwd, inputs) {
97606
+ try {
97607
+ return await execFileAsync6(GIT3, gitArgs, { cwd, encoding: "utf8" });
97608
+ } catch (error48) {
97609
+ LOG2.warn("Mesh", `[Refinery] Change-area git call failed: ${JSON.stringify({
97610
+ callSite,
97611
+ gitArgs,
97612
+ cwd,
97613
+ cwdExists: (0, import_node_fs7.existsSync)(cwd),
97614
+ code: error48?.code ?? null,
97615
+ syscall: error48?.syscall ?? null,
97616
+ path: error48?.path ?? null,
97617
+ inputs
97618
+ })}`);
97619
+ throw error48;
97620
+ }
97621
+ }
97352
97622
  function topLevel(path64) {
97353
97623
  const slash = path64.indexOf("/");
97354
97624
  return slash === -1 ? path64 : path64.slice(0, slash);
97355
97625
  }
97356
97626
  async function analyzeMeshRefineNodeChangeArea(args) {
97357
- const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, submodulePaths } = args;
97627
+ const { nodeId, workspace, branch, baseRef, branchRef, diffCwd, repoRoot, submodulePaths } = args;
97628
+ const diagnosticInputs = {
97629
+ nodeId,
97630
+ workspace,
97631
+ repoRoot: repoRoot ?? null,
97632
+ branch,
97633
+ baseRef,
97634
+ branchRef,
97635
+ submodulePaths: [...submodulePaths]
97636
+ };
97358
97637
  const base = {
97359
97638
  nodeId,
97360
97639
  workspace,
@@ -97368,21 +97647,28 @@ ${mergeTreeErr?.stderr || ""}`;
97368
97647
  try {
97369
97648
  let mergeBase = baseRef;
97370
97649
  try {
97371
- const { stdout } = await execFileAsync6(GIT3, ["merge-base", baseRef, branchRef], { cwd: diffCwd, encoding: "utf8" });
97650
+ const { stdout } = await execChangeAreaGit(
97651
+ "analyzeMeshRefineNodeChangeArea.mergeBase",
97652
+ ["merge-base", baseRef, branchRef],
97653
+ diffCwd,
97654
+ diagnosticInputs
97655
+ );
97372
97656
  const resolved = stdout.trim();
97373
97657
  if (resolved) mergeBase = resolved;
97374
97658
  } catch {
97375
97659
  }
97376
- const { stdout: countStdout } = await execFileAsync6(
97377
- GIT3,
97660
+ const { stdout: countStdout } = await execChangeAreaGit(
97661
+ "analyzeMeshRefineNodeChangeArea.aheadCount",
97378
97662
  ["rev-list", "--count", `${mergeBase}..${branchRef}`],
97379
- { cwd: diffCwd, encoding: "utf8" }
97663
+ diffCwd,
97664
+ { ...diagnosticInputs, mergeBase }
97380
97665
  );
97381
97666
  base.aheadCount = Number.parseInt(countStdout.trim(), 10) || 0;
97382
- const { stdout: nameStdout } = await execFileAsync6(
97383
- GIT3,
97667
+ const { stdout: nameStdout } = await execChangeAreaGit(
97668
+ "analyzeMeshRefineNodeChangeArea.changedFiles",
97384
97669
  ["diff", "--name-only", `${mergeBase}..${branchRef}`],
97385
- { cwd: diffCwd, encoding: "utf8" }
97670
+ diffCwd,
97671
+ { ...diagnosticInputs, mergeBase }
97386
97672
  );
97387
97673
  const files = nameStdout.split("\n").map((line) => line.trim()).filter(Boolean).slice(0, MAX_CHANGED_FILES2);
97388
97674
  base.changedFiles = files;
@@ -97431,6 +97717,7 @@ ${mergeTreeErr?.stderr || ""}`;
97431
97717
  return { order: ranked.map((a) => a.nodeId), changeAreas: areaById, rationale };
97432
97718
  }
97433
97719
  var import_node_child_process14;
97720
+ var import_node_fs7;
97434
97721
  var import_node_util7;
97435
97722
  var execFileAsync6;
97436
97723
  var GIT3;
@@ -97439,8 +97726,10 @@ ${mergeTreeErr?.stderr || ""}`;
97439
97726
  "src/mesh/mesh-refine-batch.ts"() {
97440
97727
  "use strict";
97441
97728
  import_node_child_process14 = require("child_process");
97729
+ import_node_fs7 = require("fs");
97442
97730
  import_node_util7 = require("util");
97443
97731
  init_resolve_executable();
97732
+ init_logger();
97444
97733
  execFileAsync6 = (0, import_node_util7.promisify)(import_node_child_process14.execFile);
97445
97734
  GIT3 = process.platform === "win32" ? resolveWin32Executable("git") : "git";
97446
97735
  MAX_CHANGED_FILES2 = 500;
@@ -97465,7 +97754,7 @@ ${mergeTreeErr?.stderr || ""}`;
97465
97754
  }
97466
97755
  async function assessScope(cwd, path64, baseRef, branchRef) {
97467
97756
  try {
97468
- if (!(0, import_node_fs7.existsSync)(cwd)) return { path: path64, verdict: "unknown", error: `path does not exist: ${cwd}` };
97757
+ if (!(0, import_node_fs8.existsSync)(cwd)) return { path: path64, verdict: "unknown", error: `path does not exist: ${cwd}` };
97469
97758
  const liveBaseHead = await git2(cwd, ["rev-parse", baseRef]);
97470
97759
  const branchHead = await git2(cwd, ["rev-parse", branchRef]);
97471
97760
  if (!liveBaseHead || !branchHead) {
@@ -97558,7 +97847,7 @@ ${mergeTreeErr?.stderr || ""}`;
97558
97847
  var import_node_child_process15;
97559
97848
  var import_node_util8;
97560
97849
  var import_node_path5;
97561
- var import_node_fs7;
97850
+ var import_node_fs8;
97562
97851
  var execFileAsync7;
97563
97852
  var GIT4;
97564
97853
  var init_mesh_refine_base_divergence = __esm2({
@@ -97567,7 +97856,7 @@ ${mergeTreeErr?.stderr || ""}`;
97567
97856
  import_node_child_process15 = require("child_process");
97568
97857
  import_node_util8 = require("util");
97569
97858
  import_node_path5 = require("path");
97570
- import_node_fs7 = require("fs");
97859
+ import_node_fs8 = require("fs");
97571
97860
  init_resolve_executable();
97572
97861
  init_mesh_refine_batch();
97573
97862
  execFileAsync7 = (0, import_node_util8.promisify)(import_node_child_process15.execFile);
@@ -97792,7 +98081,7 @@ ${mergeTreeErr?.stderr || ""}`;
97792
98081
  function refineWorktreeVanishedOutcome(ctx, nextStage) {
97793
98082
  const workspace = ctx?.node?.workspace;
97794
98083
  if (typeof workspace !== "string" || !workspace) return null;
97795
- if ((0, import_node_fs8.existsSync)(workspace)) return null;
98084
+ if ((0, import_node_fs9.existsSync)(workspace)) return null;
97796
98085
  recordMeshRefineStage(ctx.refineStages, nextStage, "failed", Date.now(), {
97797
98086
  workspace,
97798
98087
  workspaceMissing: true,
@@ -97812,12 +98101,12 @@ ${mergeTreeErr?.stderr || ""}`;
97812
98101
  }
97813
98102
  };
97814
98103
  }
97815
- var import_node_fs8;
98104
+ var import_node_fs9;
97816
98105
  var REFINE_INFLIGHT_FRESHNESS_MS;
97817
98106
  var init_mesh_refine_inflight = __esm2({
97818
98107
  "src/mesh/mesh-refine-inflight.ts"() {
97819
98108
  "use strict";
97820
- import_node_fs8 = require("fs");
98109
+ import_node_fs9 = require("fs");
97821
98110
  init_mesh_refine_zombie_sweep();
97822
98111
  init_mesh_refine_landing();
97823
98112
  init_mesh_refine_gates();
@@ -98644,7 +98933,7 @@ ${excerpt}` : "\n--- git output ---\n(none captured)");
98644
98933
  if (!node.isLocalWorktree || !node.workspace) {
98645
98934
  return { kind: "terminal", result: { success: false, error: `Refinery requires a local worktree node`, refineStages } };
98646
98935
  }
98647
- if (!(0, import_node_fs9.existsSync)(node.workspace)) {
98936
+ if (!(0, import_node_fs10.existsSync)(node.workspace)) {
98648
98937
  recordMeshRefineStage(refineStages, "resolve_refs", "failed", Date.now(), {
98649
98938
  workspace: node.workspace,
98650
98939
  workspaceMissing: true
@@ -99876,6 +100165,7 @@ ${e?.stderr || ""}`;
99876
100165
  baseRef,
99877
100166
  branchRef,
99878
100167
  diffCwd: node.workspace,
100168
+ repoRoot,
99879
100169
  submodulePaths: submodulePathsByRepoRoot.get(repoRoot)
99880
100170
  }));
99881
100171
  }
@@ -100349,13 +100639,13 @@ ${e?.stderr || ""}`;
100349
100639
  return handle;
100350
100640
  }
100351
100641
  var import_node_child_process16;
100352
- var import_node_fs9;
100642
+ var import_node_fs10;
100353
100643
  var RETRYABLE_BASE_MOVEMENT_CODES;
100354
100644
  var init_router_refine = __esm2({
100355
100645
  "src/commands/router-refine.ts"() {
100356
100646
  "use strict";
100357
100647
  import_node_child_process16 = require("child_process");
100358
- import_node_fs9 = require("fs");
100648
+ import_node_fs10 = require("fs");
100359
100649
  init_logger();
100360
100650
  init_debug_trace();
100361
100651
  init_dist();
@@ -117724,17 +118014,17 @@ ${marker}`,
117724
118014
  this.logShadowDivergence(ev);
117725
118015
  if (ev.fired) {
117726
118016
  this.commitTransition(ev.fired, now, ev);
118017
+ this.maybeMarkReady();
117727
118018
  this.emitStateChanged(forceEmit);
117728
118019
  this.scheduleWakeForState();
117729
118020
  this.scheduleStallWatchdog();
117730
- this.maybeMarkReady();
117731
118021
  this.drainPendingSends();
117732
118022
  return;
117733
118023
  }
118024
+ this.maybeMarkReady();
117734
118025
  this.emitStateChanged(forceEmit);
117735
118026
  this.scheduleWakeForState();
117736
118027
  this.scheduleStallWatchdog();
117737
- this.maybeMarkReady();
117738
118028
  this.drainPendingSends();
117739
118029
  }
117740
118030
  commitTransition(fired, now, ev) {
@@ -118005,7 +118295,6 @@ ${marker}`,
118005
118295
  if (!st) return;
118006
118296
  if (!st.initial && statusForState(st) === "idle") {
118007
118297
  this.readySeenOnce = true;
118008
- this.drainPendingSends();
118009
118298
  }
118010
118299
  }
118011
118300
  // ────────────────────────────────────────────────────────────────────
@@ -120240,17 +120529,17 @@ ${marker}`,
120240
120529
  }
120241
120530
  function readSession(sessionPath) {
120242
120531
  if (!sessionPath || !path40.isAbsolute(sessionPath)) return null;
120243
- const basename21 = path40.basename(sessionPath, ".jsonl");
120244
- if (!isSafeSessionId(basename21)) return null;
120532
+ const basename22 = path40.basename(sessionPath, ".jsonl");
120533
+ if (!isSafeSessionId(basename22)) return null;
120245
120534
  if (!fs33.existsSync(sessionPath)) return null;
120246
120535
  const sourceMtimeMs = statMtimeMs(sessionPath);
120247
- const { messages, usageRecords } = parseTranscriptFile(sessionPath, basename21);
120536
+ const { messages, usageRecords } = parseTranscriptFile(sessionPath, basename22);
120248
120537
  if (messages.length === 0) return null;
120249
120538
  const firstSystem = messages.find((m) => m.kind === "session_start");
120250
120539
  const workspace = firstSystem?.workspace || firstSystem?.content || void 0;
120251
120540
  const session = {
120252
120541
  messages,
120253
- providerSessionId: basename21,
120542
+ providerSessionId: basename22,
120254
120543
  source: "provider-native",
120255
120544
  sourcePath: sessionPath,
120256
120545
  sourceMtimeMs,
@@ -120259,7 +120548,7 @@ ${marker}`,
120259
120548
  };
120260
120549
  if (usageRecords.length > 0) {
120261
120550
  session.usage = foldUsageRecords(usageRecords, {
120262
- providerSessionId: basename21,
120551
+ providerSessionId: basename22,
120263
120552
  agent: "claude-cli"
120264
120553
  });
120265
120554
  }
@@ -120553,8 +120842,8 @@ ${marker}`,
120553
120842
  if (!fs34.existsSync(sessionPath)) return null;
120554
120843
  const meta3 = readSessionMeta(sessionPath);
120555
120844
  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);
120845
+ const basename22 = path41.basename(sessionPath, ".jsonl");
120846
+ 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
120847
  const filenameUuid2 = uuidMatch ? uuidMatch[1] : "";
120559
120848
  if (metaId && filenameUuid2 && metaId !== filenameUuid2) return null;
120560
120849
  const sessionId = metaId || filenameUuid2;
@@ -123015,10 +123304,21 @@ ${text}` : text;
123015
123304
  ...sessionFields
123016
123305
  };
123017
123306
  }
123307
+ const readySeen = this.driver.hasSeenReady?.();
123308
+ if (readySeen === false) {
123309
+ return {
123310
+ status: "starting",
123311
+ messages: [],
123312
+ activeModal: null,
123313
+ activeInteractivePrompt: this.activeInteractivePrompt,
123314
+ fsmReadySeen: false,
123315
+ ...sessionFields
123316
+ };
123317
+ }
123018
123318
  if (state.status === "generating") {
123019
123319
  return { status: "generating", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, ...sessionFields };
123020
123320
  }
123021
- return { status: "idle", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, fsmReadySeen: this.driver.hasSeenReady?.() ?? false, ...sessionFields };
123321
+ return { status: "idle", messages: [], activeModal: null, activeInteractivePrompt: this.activeInteractivePrompt, fsmReadySeen: readySeen === true, ...sessionFields };
123022
123322
  }
123023
123323
  maybeRefreshNativeHistory() {
123024
123324
  }
@@ -126411,7 +126711,9 @@ ${buttons.join("\n")}`;
126411
126711
  host.scheduleCompletedDebounceFlush(flushDelay);
126412
126712
  }
126413
126713
  } else if (newStatus === "idle" && host.lastStatus === "starting") {
126414
- host.emitAgentReadyOnce(chatTitle, now);
126714
+ if (adapterStatus.fsmReadySeen !== false) {
126715
+ host.emitAgentReadyOnce(chatTitle, now);
126716
+ }
126415
126717
  if (host.startupGraceCollapseAt === null) host.startupGraceCollapseAt = now;
126416
126718
  host.maybeSynthesizeStartupGraceCollapse(chatTitle, now, "startup_grace_fast_collapse");
126417
126719
  } else if (newStatus === "error") {
@@ -130753,6 +131055,12 @@ ${rawInput}` : rawInput;
130753
131055
  return managedBy === managerTag;
130754
131056
  }
130755
131057
  init_auto_approve_modes();
131058
+ function expandModelLaunchArgs(template, model, valueMap = void 0) {
131059
+ const requested = typeof model === "string" ? model.trim() : "";
131060
+ if (!requested || !Array.isArray(template) || template.length === 0) return void 0;
131061
+ const mapped = typeof valueMap?.[requested] === "string" && valueMap[requested].trim() ? valueMap[requested].trim() : requested;
131062
+ return template.map((part) => part.includes("{{model}}") ? part.split("{{model}}").join(mapped) : part);
131063
+ }
130756
131064
  function isExplicitCommand(command) {
130757
131065
  const trimmed = command.trim();
130758
131066
  return path50.isAbsolute(trimmed) || trimmed.includes("/") || trimmed.includes("\\") || trimmed.startsWith("~");
@@ -131005,11 +131313,6 @@ ${rawInput}` : rawInput;
131005
131313
  return expanded;
131006
131314
  });
131007
131315
  }
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
131316
  function expandThinkingLaunchArgs(template, level, levelMap) {
131014
131317
  const raw = typeof level === "string" ? level.trim() : "";
131015
131318
  if (!raw || !Array.isArray(template) || template.length === 0) return void 0;
@@ -131506,7 +131809,11 @@ Run 'adhdev doctor' for detailed diagnostics.`
131506
131809
  const autoApproveLaunch = applyAutoApproveModeLaunchArgs(versionResolvedProvider, cliArgs, launchSettings);
131507
131810
  const launchProvider = autoApproveLaunch.provider || provider;
131508
131811
  const cliArgsWithAutoApprove = autoApproveLaunch.cliArgs;
131509
- const modelLaunchArgs = expandModelLaunchArgs(launchProvider?.modelLaunchArgs, initialModel);
131812
+ const modelLaunchArgs = expandModelLaunchArgs(
131813
+ launchProvider?.modelLaunchArgs,
131814
+ initialModel,
131815
+ launchProvider?.modelLaunchValueMap
131816
+ );
131510
131817
  const cliArgsWithModel = modelLaunchArgs ? [...modelLaunchArgs, ...cliArgsWithAutoApprove || []] : cliArgsWithAutoApprove;
131511
131818
  if (initialModel && !modelLaunchArgs) {
131512
131819
  LOG2.warn("CLI", `[${normalizedType}] initialModel='${initialModel}' requested but provider declares no modelLaunchArgs template \u2014 launching without model selection.`);
@@ -132583,6 +132890,7 @@ Run 'adhdev doctor' for detailed diagnostics.`
132583
132890
  "details",
132584
132891
  "autoApproveModes",
132585
132892
  "modelLaunchArgs",
132893
+ "modelLaunchValueMap",
132586
132894
  "modelOptions",
132587
132895
  "thinkingLaunchArgs",
132588
132896
  "thinkingLevelMap",
@@ -136828,7 +137136,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
136828
137136
  normalizeRepoMeshDeclarativeConfig: normalizeRepoMeshDeclarativeConfig2,
136829
137137
  MESH_JSON_CONFIG_LOCATIONS: MESH_JSON_CONFIG_LOCATIONS2
136830
137138
  } = 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");
137139
+ const { existsSync: existsSync76, readFileSync: readFileSync59, mkdirSync: mkdirSync35, writeFileSync: writeFileSync33 } = await import("fs");
136832
137140
  const { dirname: dirname26, join: join75 } = await import("path");
136833
137141
  const yaml6 = await Promise.resolve().then(() => (init_js_yaml(), js_yaml_exports));
136834
137142
  const relativePath = MESH_JSON_CONFIG_LOCATIONS2[0];
@@ -136837,7 +137145,7 @@ ${formatManifestValidationIssues2(validation2.issues)}`);
136837
137145
  let existedAsYaml = false;
136838
137146
  for (const relative8 of MESH_JSON_CONFIG_LOCATIONS2) {
136839
137147
  const candidate = join75(workspace, relative8);
136840
- if (!existsSync75(candidate)) continue;
137148
+ if (!existsSync76(candidate)) continue;
136841
137149
  try {
136842
137150
  const text = readFileSync59(candidate, "utf-8");
136843
137151
  const parsed = /\.json$/i.test(candidate) ? JSON.parse(text) : yaml6.load(text);
@@ -139410,7 +139718,7 @@ ${ptyResult.output.slice(-2e3)}`);
139410
139718
  workspace
139411
139719
  };
139412
139720
  }
139413
- const { existsSync: existsSync75, readFileSync: readFileSync59, writeFileSync: writeFileSync33, copyFileSync: copyFileSync4, mkdirSync: mkdirSync35 } = await import("fs");
139721
+ const { existsSync: existsSync76, readFileSync: readFileSync59, writeFileSync: writeFileSync33, copyFileSync: copyFileSync4, mkdirSync: mkdirSync35 } = await import("fs");
139414
139722
  const { dirname: dirname26 } = await import("path");
139415
139723
  const mcpConfigPath = coordinatorSetup.configPath;
139416
139724
  const hermesManualFallback = cliType === "hermes-cli" && configFormat === "hermes_config_yaml" ? createHermesManualMeshCoordinatorSetup(meshId, workspace) : null;
@@ -139455,7 +139763,7 @@ ${ptyResult.output.slice(-2e3)}`);
139455
139763
  if (hermesManualFallback) return returnManualFallback(message);
139456
139764
  return { success: false, code: "mesh_coordinator_config_write_failed", error: message, meshId, cliType, workspace };
139457
139765
  }
139458
- const hadExistingMcpConfig = existsSync75(mcpConfigPath);
139766
+ const hadExistingMcpConfig = existsSync76(mcpConfigPath);
139459
139767
  let existingMcpConfig = hermesBaseConfig?.config || {};
139460
139768
  if (hermesBaseConfig) {
139461
139769
  copyHermesCoordinatorCredentialFiles(hermesBaseConfig.sourceHome, dirname26(mcpConfigPath));
@@ -140273,7 +140581,7 @@ ${ptyResult.output.slice(-2e3)}`);
140273
140581
  const { deriveMeshReviewInboxItems: deriveMeshReviewInboxItems2 } = await Promise.resolve().then(() => (init_mesh_review_inbox(), mesh_review_inbox_exports));
140274
140582
  const { readLedgerEntries: readLedgerEntries2 } = await Promise.resolve().then(() => (init_mesh_ledger(), mesh_ledger_exports));
140275
140583
  const { getGitDiffSummary: getGitDiffSummary2 } = await Promise.resolve().then(() => (init_git_diff(), git_diff_exports));
140276
- const { existsSync: existsSync75 } = await import("fs");
140584
+ const { existsSync: existsSync76 } = await import("fs");
140277
140585
  const meshRecord = await ctx.getMeshForCommand(meshId, args?.inlineMesh, { preferInline: true });
140278
140586
  const mesh = meshRecord?.mesh;
140279
140587
  if (!mesh) return { success: false, error: "Mesh not found" };
@@ -140292,7 +140600,7 @@ ${ptyResult.output.slice(-2e3)}`);
140292
140600
  const derivation = deriveMeshReviewInboxItems2({ nodes: nodeStatuses, ledgerEntries });
140293
140601
  for (const item of derivation.items) {
140294
140602
  const workspace = item.workspace;
140295
- if (!workspace || !existsSync75(workspace)) continue;
140603
+ if (!workspace || !existsSync76(workspace)) continue;
140296
140604
  const baseRef = item.defaultBranch ? `origin/${item.defaultBranch}` : "origin/main";
140297
140605
  try {
140298
140606
  const diffResult = await getGitDiffSummary2(workspace, { baseRef, maxFiles: 100 });
@@ -153946,10 +154254,10 @@ ${upgradeFailureNotice.notice}${supersededHint}`);
153946
154254
  init_fsm_evaluator();
153947
154255
  init_fsm_loader();
153948
154256
  var crypto9 = __toESM2(require("crypto"));
153949
- var import_node_fs10 = require("fs");
154257
+ var import_node_fs11 = require("fs");
153950
154258
  var import_node_path6 = require("path");
153951
154259
  init_provider_cli_shared();
153952
- var import_node_fs11 = require("fs");
154260
+ var import_node_fs12 = require("fs");
153953
154261
  var import_node_path7 = require("path");
153954
154262
  init_manifest();
153955
154263
  var V1_PRIMITIVE_CATALOG = Object.freeze({