charness 3.13.0 → 3.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/DEVELOPMENT.md +2 -1
  3. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
  4. package/dist/adapters/claudeCliAdapter.js +8 -15
  5. package/dist/adapters/claudeCliAdapter.js.map +1 -1
  6. package/dist/adapters/claudeJsonStreamAdapter.d.ts +29 -10
  7. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  8. package/dist/adapters/claudeJsonStreamAdapter.js +72 -27
  9. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  10. package/dist/adapters/openCodeAdapter.d.ts +74 -11
  11. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  12. package/dist/adapters/openCodeAdapter.js +215 -42
  13. package/dist/adapters/openCodeAdapter.js.map +1 -1
  14. package/dist/bot.d.ts.map +1 -1
  15. package/dist/bot.js +28 -11
  16. package/dist/bot.js.map +1 -1
  17. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  18. package/dist/connectors/telegram/commands/compaction.js +12 -0
  19. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  20. package/dist/legacyNames.d.ts +8 -0
  21. package/dist/legacyNames.d.ts.map +1 -1
  22. package/dist/legacyNames.js +9 -1
  23. package/dist/legacyNames.js.map +1 -1
  24. package/dist/mcpConfig.d.ts +4 -1
  25. package/dist/mcpConfig.d.ts.map +1 -1
  26. package/dist/mcpConfig.js +27 -2
  27. package/dist/mcpConfig.js.map +1 -1
  28. package/dist/runnerUtility/launcher.d.ts.map +1 -1
  29. package/dist/runnerUtility/launcher.js +11 -3
  30. package/dist/runnerUtility/launcher.js.map +1 -1
  31. package/dist/scheduler/injection.d.ts +7 -3
  32. package/dist/scheduler/injection.d.ts.map +1 -1
  33. package/dist/scheduler/injection.js +7 -3
  34. package/dist/scheduler/injection.js.map +1 -1
  35. package/dist/scheduler/mcpBoot.d.ts +10 -1
  36. package/dist/scheduler/mcpBoot.d.ts.map +1 -1
  37. package/dist/scheduler/mcpBoot.js +6 -1
  38. package/dist/scheduler/mcpBoot.js.map +1 -1
  39. package/dist/scheduler/mcpSurface.js +1 -1
  40. package/dist/scheduler/mcpSurface.js.map +1 -1
  41. package/dist/scheduler/workerActivity.d.ts.map +1 -1
  42. package/dist/scheduler/workerActivity.js +2 -1
  43. package/dist/scheduler/workerActivity.js.map +1 -1
  44. package/dist/state.d.ts +1 -1
  45. package/dist/stateFile.d.ts.map +1 -1
  46. package/dist/stateFile.js +2 -1
  47. package/dist/stateFile.js.map +1 -1
  48. package/dist/testTimings.d.ts +3 -2
  49. package/dist/testTimings.d.ts.map +1 -1
  50. package/dist/testTimings.js +8 -1
  51. package/dist/testTimings.js.map +1 -1
  52. package/dist/types.d.ts +11 -8
  53. package/dist/types.d.ts.map +1 -1
  54. package/dist/utils/adoptReplayGate.d.ts +7 -5
  55. package/dist/utils/adoptReplayGate.d.ts.map +1 -1
  56. package/dist/utils/adoptReplayGate.js +7 -5
  57. package/dist/utils/adoptReplayGate.js.map +1 -1
  58. package/dist/utils/checkIsRecord.d.ts +6 -0
  59. package/dist/utils/checkIsRecord.d.ts.map +1 -0
  60. package/dist/utils/checkIsRecord.js +11 -0
  61. package/dist/utils/checkIsRecord.js.map +1 -0
  62. package/dist/utils/claudeCompactSummary.js +4 -4
  63. package/dist/utils/claudeCompactSummary.js.map +1 -1
  64. package/dist/utils/claudeMcpHeal.d.ts +18 -3
  65. package/dist/utils/claudeMcpHeal.d.ts.map +1 -1
  66. package/dist/utils/claudeMcpHeal.js +19 -4
  67. package/dist/utils/claudeMcpHeal.js.map +1 -1
  68. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
  69. package/dist/utils/claudeRuntimeInfo.js +4 -6
  70. package/dist/utils/claudeRuntimeInfo.js.map +1 -1
  71. package/dist/utils/claudeStreamJson.d.ts +0 -3
  72. package/dist/utils/claudeStreamJson.d.ts.map +1 -1
  73. package/dist/utils/claudeStreamJson.js +21 -26
  74. package/dist/utils/claudeStreamJson.js.map +1 -1
  75. package/dist/utils/claudeSubagentTail.d.ts.map +1 -1
  76. package/dist/utils/claudeSubagentTail.js +4 -11
  77. package/dist/utils/claudeSubagentTail.js.map +1 -1
  78. package/dist/utils/claudeUsage.d.ts.map +1 -1
  79. package/dist/utils/claudeUsage.js +8 -10
  80. package/dist/utils/claudeUsage.js.map +1 -1
  81. package/dist/utils/openCodeUsage.d.ts.map +1 -1
  82. package/dist/utils/openCodeUsage.js +8 -10
  83. package/dist/utils/openCodeUsage.js.map +1 -1
  84. package/dist/utils/telegramError.d.ts.map +1 -1
  85. package/dist/utils/telegramError.js +5 -7
  86. package/dist/utils/telegramError.js.map +1 -1
  87. package/npm-shrinkwrap.json +2 -2
  88. package/package.json +1 -1
@@ -54,6 +54,8 @@ exports.checkIsValidProviderId = checkIsValidProviderId;
54
54
  exports.getLatestOpenCodeParentAssistantContext = getLatestOpenCodeParentAssistantContext;
55
55
  exports.buildProviderAuthPath = buildProviderAuthPath;
56
56
  exports.checkNeedsSchedulerMcpReregister = checkNeedsSchedulerMcpReregister;
57
+ exports.checkNeedsLegacySchedulerMcpDisconnect = checkNeedsLegacySchedulerMcpDisconnect;
58
+ exports.getOpenCodeConfigMcpLookup = getOpenCodeConfigMcpLookup;
57
59
  exports.getSchedulerMcpRetryDelayMs = getSchedulerMcpRetryDelayMs;
58
60
  exports.getOpenCodeServerRestartRetryDelayMs = getOpenCodeServerRestartRetryDelayMs;
59
61
  exports.buildProviderApiAuthPayload = buildProviderApiAuthPayload;
@@ -77,6 +79,8 @@ const resumeContext_1 = require("../resumeContext");
77
79
  const threadContextPreamble_1 = require("../threadContextPreamble");
78
80
  const openCodeOpenQuestion_1 = require("../openCodeOpenQuestion");
79
81
  const injection_1 = require("../scheduler/injection");
82
+ const legacyNames_1 = require("../legacyNames");
83
+ const checkIsRecord_1 = require("../utils/checkIsRecord");
80
84
  const openCodeSessionTitle_1 = require("../openCodeSessionTitle");
81
85
  const effortLevels_1 = require("../effortLevels");
82
86
  const providerDisconnectPlan_1 = require("../utils/providerDisconnectPlan");
@@ -883,19 +887,16 @@ function buildPromptBody(input, modelOverride, effortLevel) {
883
887
  function checkIsValidProviderId(providerId) {
884
888
  return providerIdRe.test(providerId);
885
889
  }
886
- function checkIsOpenCodeRecord(value) {
887
- return typeof value === 'object' && value !== null && !Array.isArray(value);
888
- }
889
890
  function checkIsOpenCodeTokenCount(value) {
890
891
  return typeof value === 'number' && Number.isFinite(value) && Number.isInteger(value) && value >= 0;
891
892
  }
892
893
  function getOpenCodeContextUsedTokens(usage) {
893
- if (!checkIsOpenCodeRecord(usage) || !checkIsOpenCodeTokenCount(usage.input))
894
+ if (!(0, checkIsRecord_1.checkIsRecord)(usage) || !checkIsOpenCodeTokenCount(usage.input))
894
895
  return null;
895
896
  const outputTokens = usage.output;
896
897
  const cache = usage.cache;
897
898
  if ((outputTokens !== undefined && !checkIsOpenCodeTokenCount(outputTokens)) ||
898
- (cache !== undefined && !checkIsOpenCodeRecord(cache))) {
899
+ (cache !== undefined && !(0, checkIsRecord_1.checkIsRecord)(cache))) {
899
900
  return null;
900
901
  }
901
902
  const cacheReadTokens = cache?.read;
@@ -929,7 +930,7 @@ function getLatestOpenCodeParentAssistantContext(records, sessionId) {
929
930
  return null;
930
931
  let latestContext = null;
931
932
  for (const record of records) {
932
- if (!checkIsOpenCodeRecord(record) || !checkIsOpenCodeRecord(record.info))
933
+ if (!(0, checkIsRecord_1.checkIsRecord)(record) || !(0, checkIsRecord_1.checkIsRecord)(record.info))
933
934
  continue;
934
935
  const info = record.info;
935
936
  if (info.role !== 'assistant' || typeof info.id !== 'string' || !info.id.trim())
@@ -954,11 +955,11 @@ function getLatestOpenCodeParentAssistantContext(records, sessionId) {
954
955
  }
955
956
  function getOpenCodeModelVariants(model) {
956
957
  const variants = model.variants;
957
- return checkIsOpenCodeRecord(variants) ? Object.keys(variants) : [];
958
+ return (0, checkIsRecord_1.checkIsRecord)(variants) ? Object.keys(variants) : [];
958
959
  }
959
960
  function getOpenCodeModelContextWindowTokens(model) {
960
961
  const limit = model.limit;
961
- if (!checkIsOpenCodeRecord(limit) || !checkIsOpenCodeTokenCount(limit.context))
962
+ if (!(0, checkIsRecord_1.checkIsRecord)(limit) || !checkIsOpenCodeTokenCount(limit.context))
962
963
  return null;
963
964
  return limit.context;
964
965
  }
@@ -968,7 +969,7 @@ function buildProviderAuthPath(providerId) {
968
969
  /**
969
970
  * @description Pure decision for the boot self-heal: given opencode's live
970
971
  * `GET /mcp` status map (`{ <serverName>: { status, error? }, … }`), does the
971
- * bot-owned `telegramBot` server need a (re)registration? True when the entry is
972
+ * bot-owned `charness` server need a (re)registration? True when the entry is
972
973
  * ABSENT (never registered on this server generation) or its `status` is
973
974
  * anything other than `connected` (e.g. `failed` — a stale registration to a
974
975
  * dead port left by a previous bot generation). A malformed/empty response is
@@ -976,12 +977,54 @@ function buildProviderAuthPath(providerId) {
976
977
  * server, whereas skipping a real failure would leave agents without the tools.
977
978
  */
978
979
  function checkNeedsSchedulerMcpReregister(mcpStatus) {
979
- if (!mcpStatus || typeof mcpStatus !== 'object')
980
+ if (!(0, checkIsRecord_1.checkIsRecord)(mcpStatus))
980
981
  return true;
981
982
  const entry = mcpStatus[injection_1.schedulerMcpServerName];
982
- if (!entry || typeof entry !== 'object')
983
- return true;
984
- return entry.status !== 'connected';
983
+ return !(0, checkIsRecord_1.checkIsRecord)(entry) || entry.status !== 'connected';
984
+ }
985
+ /**
986
+ * @description Pure decision for the migration from the pre-rename server name: given the same status map, is a registration still
987
+ * standing under `legacySchedulerMcpServerName` that must be disconnected so its tools do not double the bot's? True for an entry
988
+ * in any state but `disabled` (disconnecting is what makes it `disabled`, so a second boot does nothing). False for no entry and for
989
+ * a malformed answer: a name the server never had is answered with a 404, so nothing is sent on a guess.
990
+ */
991
+ function checkNeedsLegacySchedulerMcpDisconnect(mcpStatus) {
992
+ if (!(0, checkIsRecord_1.checkIsRecord)(mcpStatus))
993
+ return false;
994
+ const entry = mcpStatus[legacyNames_1.legacySchedulerMcpServerName];
995
+ return (0, checkIsRecord_1.checkIsRecord)(entry) && entry.status !== 'disabled';
996
+ }
997
+ /**
998
+ * @description Whether the operator's OpenCode config defines the MCP server `serverName`. The status map (`GET /mcp`) lists both the
999
+ * servers the operator's config defines and the ones registered at runtime, so a name found there says nothing about who made it;
1000
+ * `GET /config` lists only the config's — measured against a live server: runtime registrations never show up in it.
1001
+ */
1002
+ function getOpenCodeConfigMcpLookup(config, serverName) {
1003
+ if (!(0, checkIsRecord_1.checkIsRecord)(config))
1004
+ return 'unreadable';
1005
+ return (0, checkIsRecord_1.checkIsRecord)(config.mcp) && serverName in config.mcp ? 'defined' : 'absent';
1006
+ }
1007
+ /** The wording of a retry's two log lines: what it is retrying, and what stands when the last pause is over. */
1008
+ function describeSchedulerMcpPending(pending, directory) {
1009
+ switch (pending) {
1010
+ case 'registration':
1011
+ return {
1012
+ retrying: `the scheduler MCP registration for ${directory}`,
1013
+ gaveUp: `[OpenCode] scheduler MCP for ${directory} is still not registered; the next session start or bot boot retries`,
1014
+ };
1015
+ case 'legacyDisconnect':
1016
+ return {
1017
+ retrying: `the disconnect of the pre-rename MCP registration for ${directory}`,
1018
+ gaveUp: `[OpenCode] ${directory}: the MCP server registered under the pre-rename name ${legacyNames_1.legacySchedulerMcpServerName} is still ` +
1019
+ `connected, next to ${injection_1.schedulerMcpServerName} (its disconnect kept failing); the next session start or bot boot retries`,
1020
+ };
1021
+ case 'configRead':
1022
+ return {
1023
+ retrying: `the read of the OpenCode config of ${directory}`,
1024
+ gaveUp: `[OpenCode] ${directory}: the OpenCode config could not be read, so it is not known whether the connected ${injection_1.schedulerMcpServerName} ` +
1025
+ `is the bot's or one the operator defined; the next session start or bot boot retries`,
1026
+ };
1027
+ }
985
1028
  }
986
1029
  /**
987
1030
  * Pauses before each retry of a failed scheduler-MCP registration. A server that
@@ -1069,18 +1112,18 @@ function getFreshProvidersConfig(now = Date.now()) {
1069
1112
  }
1070
1113
  function parseProvidersResponse(raw) {
1071
1114
  const out = { providers: new Map() };
1072
- if (!checkIsOpenCodeRecord(raw))
1115
+ if (!(0, checkIsRecord_1.checkIsRecord)(raw))
1073
1116
  return out;
1074
1117
  // Two shapes seen in the wild: `{ providers: [...] }` (array, opencode
1075
1118
  // 1.15.x) and `{ providers: { <id>: {...} } }` (older bundles). Parse
1076
1119
  // both into the same flat (providerId → modelId → model config) map so
1077
1120
  // the rest of the code doesn't care which shape the server sent.
1078
1121
  const collect = (providerId, providerObj) => {
1079
- if (!checkIsOpenCodeRecord(providerObj) || !checkIsOpenCodeRecord(providerObj.models))
1122
+ if (!(0, checkIsRecord_1.checkIsRecord)(providerObj) || !(0, checkIsRecord_1.checkIsRecord)(providerObj.models))
1080
1123
  return;
1081
1124
  const modelMap = new Map();
1082
1125
  for (const [modelId, modelObj] of Object.entries(providerObj.models)) {
1083
- if (!checkIsOpenCodeRecord(modelObj)) {
1126
+ if (!(0, checkIsRecord_1.checkIsRecord)(modelObj)) {
1084
1127
  modelMap.set(modelId, { variants: [], contextWindowTokens: null });
1085
1128
  continue;
1086
1129
  }
@@ -1094,11 +1137,11 @@ function parseProvidersResponse(raw) {
1094
1137
  const providersField = raw.providers;
1095
1138
  if (Array.isArray(providersField)) {
1096
1139
  for (const item of providersField) {
1097
- if (checkIsOpenCodeRecord(item) && typeof item.id === 'string')
1140
+ if ((0, checkIsRecord_1.checkIsRecord)(item) && typeof item.id === 'string')
1098
1141
  collect(item.id, item);
1099
1142
  }
1100
1143
  }
1101
- else if (checkIsOpenCodeRecord(providersField)) {
1144
+ else if ((0, checkIsRecord_1.checkIsRecord)(providersField)) {
1102
1145
  for (const [id, value] of Object.entries(providersField)) {
1103
1146
  collect(id, value);
1104
1147
  }
@@ -1223,11 +1266,18 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1223
1266
  */
1224
1267
  registeredSchedulerMcpDirs = new Set();
1225
1268
  /**
1226
- * Directories whose scheduler-MCP registration failed and is waiting for a
1227
- * retry: the number of retries already scheduled, and the pending timer (null
1228
- * while the retry itself runs). Cleared by a registration that succeeds.
1269
+ * Directories whose scheduler-MCP job — the bot's registration and the disconnect of the pre-rename one that goes with it — is
1270
+ * waiting for a retry: the number of retries already scheduled, the pending timer (null while the retry itself runs) and what is
1271
+ * pending (the wording of its log lines). Forgotten only when the WHOLE job is done (`registerSchedulerMcpForDirectory`, the
1272
+ * reconcile's `connected` branch), never by the registration POST alone: a step that fails after it keeps the entry and its count,
1273
+ * so the retries stay bounded.
1229
1274
  */
1230
1275
  schedulerMcpRetries = new Map();
1276
+ /**
1277
+ * Per folder, which of the bot's server names the operator's OpenCode config defines — read once per folder and server generation
1278
+ * (see {@link readConfigDefinedMcpNames}). Dropped where the registrations it explains are: a server restart, an instance recreate.
1279
+ */
1280
+ configDefinedMcpNames = new Map();
1231
1281
  /**
1232
1282
  * child sessionID → parent sessionID, learned from `session.updated` events.
1233
1283
  * OpenCode runs subagents (e.g. `@explore`) in child sessions whose SSE
@@ -1409,10 +1459,9 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1409
1459
  // stale reader would only self-heal later via the stall watchdog —
1410
1460
  // closing here makes recovery deterministic and tied to the restart.
1411
1461
  this.closeGlobalStream();
1412
- // The restarted server has a fresh, empty MCP table, so every directory's
1413
- // scheduler-MCP registration died with the old generation. Clear the gate
1414
- // so connectSse re-registers each still-active directory on resume.
1415
- this.registeredSchedulerMcpDirs.clear();
1462
+ // The restarted server has a fresh, empty MCP table, so every directory's scheduler-MCP registration died with the old
1463
+ // generation: `ensureServerWithRetries` has dropped the gate (see `dropServerGenerationState`), so connectSse re-registers each
1464
+ // still-active directory on resume.
1416
1465
  // OpenCode persists sessions to disk, so the restarted server still
1417
1466
  // knows the previous session ids — that's the basis of this recovery.
1418
1467
  // For each in-memory session that was active, re-resume the SAME id
@@ -1504,6 +1553,7 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1504
1553
  else
1505
1554
  await this.serverRestartOps.ensureServer();
1506
1555
  console.log(`[OpenCode] Server is up`);
1556
+ this.dropServerGenerationState();
1507
1557
  return;
1508
1558
  }
1509
1559
  catch (e) {
@@ -1517,6 +1567,17 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1517
1567
  }
1518
1568
  }
1519
1569
  }
1570
+ /**
1571
+ * @description Forget what the bot learned about the previous OpenCode server: its runtime MCP registrations (the gate) and its
1572
+ * folders' configs. Called wherever a server was actually brought up — a restart, a session start or resume that found it down, the
1573
+ * provider sign-in — because each of those can start a new generation with an EMPTY MCP table, and a gate that still says "registered"
1574
+ * would leave every folder it names without the bot's tools until the next worker start. (A server that was already running is used
1575
+ * as it is and nothing is dropped; a fresh worker process starts with both empty.)
1576
+ */
1577
+ dropServerGenerationState() {
1578
+ this.registeredSchedulerMcpDirs.clear();
1579
+ this.configDefinedMcpNames.clear();
1580
+ }
1520
1581
  /**
1521
1582
  * @description {@link ensureServerWithRetries} for a session start or resume of
1522
1583
  * `key`: the server is brought up only when it is down, and the topic is told
@@ -3057,14 +3118,18 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3057
3118
  /**
3058
3119
  * @description Boot self-heal for the adopt path. When the bot restarts and
3059
3120
  * ADOPTS an already-running opencode (the server outlived the bot), that
3060
- * server still holds the PREVIOUS bot generation's `telegramBot` registration
3121
+ * server still holds the PREVIOUS bot generation's `charness` registration
3061
3122
  * pointing at a now-dead ephemeral port — so every session in the directory
3062
3123
  * reports the MCP `failed` and loses its scheduling / file-send tools. For
3063
3124
  * each active session's directory (de-duped — a folder can host several
3064
- * threads), read the LIVE `GET /mcp` status and, when the `telegramBot` entry
3125
+ * threads), read the LIVE `GET /mcp` status and, when the `charness` entry
3065
3126
  * is missing or not `connected`, drop the Set gate and force a fresh POST (the
3066
3127
  * server overwrites a same-name registration with the current port). A dir
3067
- * already `connected` is left untouched. Best-effort per directory: a read /
3128
+ * already `connected` is left alone with two exceptions: a registration an older
3129
+ * bot left under the pre-rename name is disconnected, and a folder whose OpenCode
3130
+ * config itself defines `charness` — the `connected` may be the operator's server —
3131
+ * gets the bot's own registered over it, once per server generation (the gate).
3132
+ * Best-effort per directory: a read /
3068
3133
  * registration error is logged and swallowed — it must never throw out of
3069
3134
  * boot. Supersedes {@link registerSchedulerMcpForActiveSessions} at the boot
3070
3135
  * call site (a not-yet-registered dir has no entry → treated as needing one).
@@ -3179,7 +3244,7 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3179
3244
  * older version keeps the older text. Installs the file, then per directory
3180
3245
  * (de-duped, concurrently) recreates the instance when it lacks the current
3181
3246
  * plugin and nothing in it is running. A recreated directory loses
3182
- * its runtime `telegramBot` registration, so its Set gate is dropped here and
3247
+ * its runtime `charness` registration, so its Set gate is dropped here and
3183
3248
  * the boot caller reconciles the MCP right after.
3184
3249
  */
3185
3250
  async activateCompactionPluginForActiveSessions() {
@@ -3213,6 +3278,7 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3213
3278
  }
3214
3279
  await this.apiRequest('POST', buildDirectoryScopedPath('/instance/dispose', directory));
3215
3280
  this.registeredSchedulerMcpDirs.delete(directory);
3281
+ this.configDefinedMcpNames.delete(directory);
3216
3282
  console.log(`[OpenCode] recreated the ${directory} instance so it loads the compaction plugin`);
3217
3283
  }
3218
3284
  catch (e) {
@@ -3221,8 +3287,12 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3221
3287
  }
3222
3288
  /**
3223
3289
  * @description Reconcile ONE directory: read the live `GET /mcp` status and,
3224
- * when `telegramBot` is missing or not `connected`, drop the Set gate and
3225
- * force a fresh POST. Best-effort — a read/registration error is logged,
3290
+ * when `charness` is missing or not `connected`, drop the Set gate and
3291
+ * force a fresh POST. A `connected` one is not simply trusted: the folder's
3292
+ * config is read ({@link readConfigDefinedMcpNames}); where it defines `charness`
3293
+ * the bot's own is registered over it unless the gate shows this server generation
3294
+ * already has it, a config that cannot be read arms a `configRead` retry, and an
3295
+ * old-name registration left in the folder is disconnected. Best-effort — a read/registration error is logged,
3226
3296
  * scheduled for a retry, and swallowed so it never rejects out of
3227
3297
  * {@link reconcileSchedulerMcpForActiveSessions}.
3228
3298
  */
@@ -3230,8 +3300,27 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3230
3300
  try {
3231
3301
  const mcpStatus = await this.apiRequest('GET', buildDirectoryScopedPath('/mcp', directory));
3232
3302
  if (!checkNeedsSchedulerMcpReregister(mcpStatus)) {
3233
- // A registration that timed out can still have landed on the server.
3234
- this.clearSchedulerMcpRetry(directory);
3303
+ // `connected` may be the operator's own server of the bot's name — a recreated instance brings the config's back and drops the
3304
+ // bot's runtime registration, and the status cannot tell the two apart. Where the config defines the name, register the bot's own.
3305
+ const definedNames = await this.readConfigDefinedMcpNames(directory);
3306
+ if (definedNames === null) {
3307
+ // Whose the connected server is stays unknown until the config is read: try again rather than leave the folder on a guess
3308
+ // that, when wrong, leaves its agents without the bot's tools until the next boot. The bot's own is most likely in place,
3309
+ // and the retry's lines say it is the READ that is pending, not the registration.
3310
+ this.scheduleSchedulerMcpRetry(directory, 'configRead');
3311
+ return;
3312
+ }
3313
+ // Register the bot's own only when the gate shows no registration in this server generation: one that is there replaced the
3314
+ // operator's server and is still in place, and a second POST would replace the live connection under an agent's running call.
3315
+ // A server restart and an instance recreate drop the gate with the registration, and a fresh process starts with it empty.
3316
+ if (definedNames.isBotNameDefined && !this.registeredSchedulerMcpDirs.has(directory)) {
3317
+ await this.registerSchedulerMcpForDirectory(directory);
3318
+ return;
3319
+ }
3320
+ // A registration that timed out can still have landed on the server. The retry stays armed while the
3321
+ // pre-rename registration could not be disconnected, so that failure is retried a bounded number of times too.
3322
+ if (await this.retireLegacySchedulerMcp(directory, mcpStatus, definedNames))
3323
+ this.clearSchedulerMcpRetry(directory);
3235
3324
  return;
3236
3325
  }
3237
3326
  // The live server contradicts the Set gate (stale entry from a prior
@@ -3252,14 +3341,18 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3252
3341
  * covers a second failure, and one that fires after the folder's last session
3253
3342
  * ended does nothing.
3254
3343
  */
3255
- scheduleSchedulerMcpRetry(directory) {
3256
- const retry = this.schedulerMcpRetries.get(directory) ?? { attempt: 0, timer: null };
3344
+ scheduleSchedulerMcpRetry(directory, pending) {
3345
+ const retry = this.schedulerMcpRetries.get(directory) ?? { attempt: 0, timer: null, pending: pending ?? 'registration' };
3346
+ // The kind is stored on the entry when it is first armed. A caller that knows what is failing now says so; the reconcile's own
3347
+ // catch (a status read that failed) names nothing and keeps what the entry already says.
3348
+ if (pending !== undefined)
3349
+ retry.pending = pending;
3257
3350
  if (retry.timer)
3258
3351
  return;
3259
3352
  const delayMs = getSchedulerMcpRetryDelayMs(retry.attempt);
3260
3353
  if (delayMs === null) {
3261
3354
  this.schedulerMcpRetries.delete(directory);
3262
- console.warn(`[OpenCode] scheduler MCP for ${directory} is still not registered; the next session start or bot boot retries`);
3355
+ console.warn(describeSchedulerMcpPending(retry.pending, directory).gaveUp);
3263
3356
  return;
3264
3357
  }
3265
3358
  retry.attempt += 1;
@@ -3274,10 +3367,13 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3274
3367
  }, delayMs);
3275
3368
  retry.timer.unref?.();
3276
3369
  this.schedulerMcpRetries.set(directory, retry);
3277
- console.log(`[OpenCode] retrying the scheduler MCP registration for ${directory} in ${Math.round(delayMs / 1000)}s ` +
3278
- `(${retry.attempt}/${exports.schedulerMcpRetryDelaysMs.length})`);
3370
+ console.log(`[OpenCode] retrying ${describeSchedulerMcpPending(retry.pending, directory).retrying} ` +
3371
+ `in ${Math.round(delayMs / 1000)}s (${retry.attempt}/${exports.schedulerMcpRetryDelaysMs.length})`);
3279
3372
  }
3280
- /** @description Forget `directory`'s pending registration retry: it is registered now. */
3373
+ /**
3374
+ * @description Forget `directory`'s pending retry: the job it was for is done — `charness` is in place and the pre-rename
3375
+ * registration, if one was left, is disconnected. Not for a registration alone (see {@link schedulerMcpRetries}).
3376
+ */
3281
3377
  clearSchedulerMcpRetry(directory) {
3282
3378
  const retry = this.schedulerMcpRetries.get(directory);
3283
3379
  if (!retry)
@@ -3376,15 +3472,92 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3376
3472
  return;
3377
3473
  if (this.registeredSchedulerMcpDirs.has(directory))
3378
3474
  return;
3475
+ let mcpStatus;
3379
3476
  try {
3380
- await this.apiRequest('POST', buildDirectoryScopedPath('/mcp', directory), registration);
3477
+ // The server answers with its whole status map, the one the pre-rename registration is read from below.
3478
+ mcpStatus = await this.apiRequest('POST', buildDirectoryScopedPath('/mcp', directory), registration);
3381
3479
  this.registeredSchedulerMcpDirs.add(directory);
3382
- this.clearSchedulerMcpRetry(directory);
3383
3480
  (0, diagLog_1.appendDiagLog)(`scheduler mcp registered dir=${directory}`);
3384
3481
  }
3385
3482
  catch (e) {
3386
3483
  console.warn(`[OpenCode] scheduler MCP registration failed for ${directory}:`, e instanceof Error ? e.message : e);
3387
- this.scheduleSchedulerMcpRetry(directory);
3484
+ this.scheduleSchedulerMcpRetry(directory, 'registration');
3485
+ return;
3486
+ }
3487
+ // The registration replaced a server of the same name that the operator's own config defines (measured against a live server); the
3488
+ // read warns, once per folder, when there is one.
3489
+ const definedNames = await this.readConfigDefinedMcpNames(directory);
3490
+ // Only after `charness` is registered: a failed registration must not also take the agent's remaining bot tools away. The pending
3491
+ // retry is forgotten only when this whole job is done: a disconnect that fails keeps the entry and its count, so the retries it
3492
+ // brings stay bounded (clearing it here would restart the count at every registration, and a reconcile that registers every time
3493
+ // — where the operator's config defines the bot's name — would then retry for ever).
3494
+ if (await this.retireLegacySchedulerMcp(directory, mcpStatus, definedNames))
3495
+ this.clearSchedulerMcpRetry(directory);
3496
+ }
3497
+ /**
3498
+ * @description Which of the bot's server names the operator's own OpenCode config defines in `directory`'s instance, from the folder's
3499
+ * `GET /config`: asked once per folder and server generation, so a reconcile never repeats the request or its log line. The status map
3500
+ * cannot say it — it lists the operator's servers and runtime registrations alike, and a `connected` charness may be the operator's.
3501
+ * The first answer that defines the bot's name warns, once, what to rename: the name is the bot's, and the bot registers its own over
3502
+ * it. `null` when the config could not be read (logged): nothing is cached and nothing is decided on it.
3503
+ */
3504
+ async readConfigDefinedMcpNames(directory) {
3505
+ const known = this.configDefinedMcpNames.get(directory);
3506
+ if (known)
3507
+ return known;
3508
+ try {
3509
+ const config = await this.apiRequest('GET', buildDirectoryScopedPath('/config', directory));
3510
+ const botLookup = getOpenCodeConfigMcpLookup(config, injection_1.schedulerMcpServerName);
3511
+ if (botLookup === 'unreadable')
3512
+ throw new Error('GET /config did not answer a config');
3513
+ const definedNames = {
3514
+ isBotNameDefined: botLookup === 'defined',
3515
+ isLegacyNameDefined: getOpenCodeConfigMcpLookup(config, legacyNames_1.legacySchedulerMcpServerName) === 'defined',
3516
+ };
3517
+ this.configDefinedMcpNames.set(directory, definedNames);
3518
+ if (definedNames.isBotNameDefined) {
3519
+ console.warn(`[OpenCode] ${directory}: the OpenCode config defines an MCP server named ${injection_1.schedulerMcpServerName} — that name belongs to the bot, ` +
3520
+ `so the bot registers its own over it; rename yours to keep it`);
3521
+ }
3522
+ if (definedNames.isLegacyNameDefined) {
3523
+ console.log(`[OpenCode] ${directory}: the OpenCode config defines an MCP server named ${legacyNames_1.legacySchedulerMcpServerName}; it is left alone`);
3524
+ }
3525
+ return definedNames;
3526
+ }
3527
+ catch (e) {
3528
+ console.warn(`[OpenCode] reading the OpenCode config of ${directory} failed:`, e instanceof Error ? e.message : e);
3529
+ return null;
3530
+ }
3531
+ }
3532
+ /**
3533
+ * @description Disconnect the registration a pre-rename bot left in `directory`'s instance under
3534
+ * `legacySchedulerMcpServerName` (`POST /mcp/<name>/disconnect`, which leaves the entry `disabled`), so an agent does not see the
3535
+ * bot's tools twice — an instance keeps its runtime registrations until its server restarts (measured against a live server), and the old one
3536
+ * is likely still connected to the bot: its port and token survive an update.
3537
+ * `mcpStatus` is a status map the server just gave, `definedNames` what the folder's config says ({@link readConfigDefinedMcpNames};
3538
+ * `null` when it could not be read). Best-effort: a failure is logged and retried through the registration retry (bounded), never
3539
+ * thrown. Returns false when the disconnect failed.
3540
+ */
3541
+ async retireLegacySchedulerMcp(directory, mcpStatus, definedNames) {
3542
+ if (!checkNeedsLegacySchedulerMcpDisconnect(mcpStatus))
3543
+ return true;
3544
+ try {
3545
+ // The status map lists the operator's own servers too: one that carries the old name in the operator's config is theirs, and
3546
+ // a config that cannot be read leaves the question open — either way nothing is disconnected on a guess.
3547
+ if (definedNames === null)
3548
+ throw new Error('the OpenCode config could not be read');
3549
+ if (definedNames.isLegacyNameDefined)
3550
+ return true;
3551
+ await this.apiRequest('POST', buildDirectoryScopedPath(`/mcp/${encodeURIComponent(legacyNames_1.legacySchedulerMcpServerName)}/disconnect`, directory));
3552
+ console.log(`[OpenCode] ${directory}: disconnected the MCP server registered under the pre-rename name ${legacyNames_1.legacySchedulerMcpServerName}; ` +
3553
+ `the bot's tools are served as ${injection_1.schedulerMcpServerName}`);
3554
+ (0, diagLog_1.appendDiagLog)(`scheduler mcp legacy disconnected dir=${directory}`);
3555
+ return true;
3556
+ }
3557
+ catch (e) {
3558
+ console.warn(`[OpenCode] disconnecting the pre-rename MCP registration failed for ${directory}:`, e instanceof Error ? e.message : e);
3559
+ this.scheduleSchedulerMcpRetry(directory, 'legacyDisconnect');
3560
+ return false;
3388
3561
  }
3389
3562
  }
3390
3563
  /**