charness 3.12.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 (295) hide show
  1. package/.env.example +5 -0
  2. package/CHANGELOG.md +40 -0
  3. package/DEVELOPMENT.md +80 -16
  4. package/README.md +2 -1
  5. package/SETUP.md +65 -20
  6. package/agent-plugin/skills/charness-delegate-claude/SKILL.md +14 -5
  7. package/dist/accessControl.d.ts +43 -0
  8. package/dist/accessControl.d.ts.map +1 -1
  9. package/dist/accessControl.js +50 -1
  10. package/dist/accessControl.js.map +1 -1
  11. package/dist/adapters/claudeCliAdapter.d.ts.map +1 -1
  12. package/dist/adapters/claudeCliAdapter.js +17 -19
  13. package/dist/adapters/claudeCliAdapter.js.map +1 -1
  14. package/dist/adapters/claudeJsonStreamAdapter.d.ts +29 -10
  15. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  16. package/dist/adapters/claudeJsonStreamAdapter.js +73 -28
  17. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  18. package/dist/adapters/claudePlatformFlags.d.ts +4 -3
  19. package/dist/adapters/claudePlatformFlags.d.ts.map +1 -1
  20. package/dist/adapters/claudePlatformFlags.js +4 -3
  21. package/dist/adapters/claudePlatformFlags.js.map +1 -1
  22. package/dist/adapters/openCodeAdapter.d.ts +111 -24
  23. package/dist/adapters/openCodeAdapter.d.ts.map +1 -1
  24. package/dist/adapters/openCodeAdapter.js +288 -83
  25. package/dist/adapters/openCodeAdapter.js.map +1 -1
  26. package/dist/adapters/terminalAdapter.d.ts.map +1 -1
  27. package/dist/adapters/terminalAdapter.js +5 -3
  28. package/dist/adapters/terminalAdapter.js.map +1 -1
  29. package/dist/agentLogin/agentLogin.d.ts.map +1 -1
  30. package/dist/agentLogin/agentLogin.js +2 -14
  31. package/dist/agentLogin/agentLogin.js.map +1 -1
  32. package/dist/bot.d.ts +12 -3
  33. package/dist/bot.d.ts.map +1 -1
  34. package/dist/bot.js +504 -144
  35. package/dist/bot.js.map +1 -1
  36. package/dist/cli/claudeProfiles.js +2 -2
  37. package/dist/cli/claudeProfiles.js.map +1 -1
  38. package/dist/connectors/jira/client.js +1 -1
  39. package/dist/connectors/jira/client.js.map +1 -1
  40. package/dist/connectors/jira/config.d.ts +7 -0
  41. package/dist/connectors/jira/config.d.ts.map +1 -1
  42. package/dist/connectors/jira/config.js +12 -1
  43. package/dist/connectors/jira/config.js.map +1 -1
  44. package/dist/connectors/jira/connector.d.ts +7 -0
  45. package/dist/connectors/jira/connector.d.ts.map +1 -1
  46. package/dist/connectors/jira/connector.js +20 -3
  47. package/dist/connectors/jira/connector.js.map +1 -1
  48. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  49. package/dist/connectors/jira/inbound.js +4 -3
  50. package/dist/connectors/jira/inbound.js.map +1 -1
  51. package/dist/connectors/jira/issueBlocks.d.ts +1 -1
  52. package/dist/connectors/jira/trustedGroup.d.ts +21 -6
  53. package/dist/connectors/jira/trustedGroup.d.ts.map +1 -1
  54. package/dist/connectors/jira/trustedGroup.js +46 -6
  55. package/dist/connectors/jira/trustedGroup.js.map +1 -1
  56. package/dist/connectors/telegram/commands/botCore.d.ts +19 -2
  57. package/dist/connectors/telegram/commands/botCore.d.ts.map +1 -1
  58. package/dist/connectors/telegram/commands/compaction.d.ts +5 -3
  59. package/dist/connectors/telegram/commands/compaction.d.ts.map +1 -1
  60. package/dist/connectors/telegram/commands/compaction.js +21 -6
  61. package/dist/connectors/telegram/commands/compaction.js.map +1 -1
  62. package/dist/connectors/telegram/commands/todo.d.ts.map +1 -1
  63. package/dist/connectors/telegram/commands/todo.js +2 -2
  64. package/dist/connectors/telegram/commands/todo.js.map +1 -1
  65. package/dist/connectors/telegram/commands/topicAccess.d.ts +30 -0
  66. package/dist/connectors/telegram/commands/topicAccess.d.ts.map +1 -0
  67. package/dist/connectors/telegram/commands/topicAccess.js +399 -0
  68. package/dist/connectors/telegram/commands/topicAccess.js.map +1 -0
  69. package/dist/connectors/telegram/inbound.d.ts +44 -7
  70. package/dist/connectors/telegram/inbound.d.ts.map +1 -1
  71. package/dist/connectors/telegram/inbound.js +142 -24
  72. package/dist/connectors/telegram/inbound.js.map +1 -1
  73. package/dist/i18n/de.d.ts.map +1 -1
  74. package/dist/i18n/de.js +68 -0
  75. package/dist/i18n/de.js.map +1 -1
  76. package/dist/i18n/en.d.ts.map +1 -1
  77. package/dist/i18n/en.js +68 -0
  78. package/dist/i18n/en.js.map +1 -1
  79. package/dist/i18n/es.d.ts.map +1 -1
  80. package/dist/i18n/es.js +68 -0
  81. package/dist/i18n/es.js.map +1 -1
  82. package/dist/i18n/fr.d.ts.map +1 -1
  83. package/dist/i18n/fr.js +68 -0
  84. package/dist/i18n/fr.js.map +1 -1
  85. package/dist/i18n/hi.d.ts.map +1 -1
  86. package/dist/i18n/hi.js +68 -0
  87. package/dist/i18n/hi.js.map +1 -1
  88. package/dist/i18n/ja.d.ts.map +1 -1
  89. package/dist/i18n/ja.js +68 -0
  90. package/dist/i18n/ja.js.map +1 -1
  91. package/dist/i18n/ka.d.ts.map +1 -1
  92. package/dist/i18n/ka.js +68 -0
  93. package/dist/i18n/ka.js.map +1 -1
  94. package/dist/i18n/pt.d.ts.map +1 -1
  95. package/dist/i18n/pt.js +68 -0
  96. package/dist/i18n/pt.js.map +1 -1
  97. package/dist/i18n/ru.d.ts.map +1 -1
  98. package/dist/i18n/ru.js +68 -0
  99. package/dist/i18n/ru.js.map +1 -1
  100. package/dist/i18n/uk.d.ts.map +1 -1
  101. package/dist/i18n/uk.js +68 -0
  102. package/dist/i18n/uk.js.map +1 -1
  103. package/dist/i18n/uz.d.ts.map +1 -1
  104. package/dist/i18n/uz.js +68 -0
  105. package/dist/i18n/uz.js.map +1 -1
  106. package/dist/i18n/zh.d.ts.map +1 -1
  107. package/dist/i18n/zh.js +68 -0
  108. package/dist/i18n/zh.js.map +1 -1
  109. package/dist/installManager.d.ts +37 -1
  110. package/dist/installManager.d.ts.map +1 -1
  111. package/dist/installManager.js +205 -14
  112. package/dist/installManager.js.map +1 -1
  113. package/dist/legacyNames.d.ts +8 -0
  114. package/dist/legacyNames.d.ts.map +1 -1
  115. package/dist/legacyNames.js +9 -1
  116. package/dist/legacyNames.js.map +1 -1
  117. package/dist/mcpConfig.d.ts +4 -1
  118. package/dist/mcpConfig.d.ts.map +1 -1
  119. package/dist/mcpConfig.js +27 -2
  120. package/dist/mcpConfig.js.map +1 -1
  121. package/dist/platform/commandRouter.d.ts +13 -1
  122. package/dist/platform/commandRouter.d.ts.map +1 -1
  123. package/dist/platform/commandRouter.js +14 -2
  124. package/dist/platform/commandRouter.js.map +1 -1
  125. package/dist/platform/inbound.d.ts +2 -0
  126. package/dist/platform/inbound.d.ts.map +1 -1
  127. package/dist/runnerUtility/launcher.d.ts.map +1 -1
  128. package/dist/runnerUtility/launcher.js +11 -3
  129. package/dist/runnerUtility/launcher.js.map +1 -1
  130. package/dist/runners/runnerLock.d.ts +36 -1
  131. package/dist/runners/runnerLock.d.ts.map +1 -1
  132. package/dist/runners/runnerLock.js +94 -30
  133. package/dist/runners/runnerLock.js.map +1 -1
  134. package/dist/scheduler/checkRun.d.ts +0 -2
  135. package/dist/scheduler/checkRun.d.ts.map +1 -1
  136. package/dist/scheduler/checkRun.js +0 -10
  137. package/dist/scheduler/checkRun.js.map +1 -1
  138. package/dist/scheduler/injection.d.ts +7 -3
  139. package/dist/scheduler/injection.d.ts.map +1 -1
  140. package/dist/scheduler/injection.js +7 -3
  141. package/dist/scheduler/injection.js.map +1 -1
  142. package/dist/scheduler/mcpBoot.d.ts +10 -1
  143. package/dist/scheduler/mcpBoot.d.ts.map +1 -1
  144. package/dist/scheduler/mcpBoot.js +6 -1
  145. package/dist/scheduler/mcpBoot.js.map +1 -1
  146. package/dist/scheduler/mcpSurface.js +1 -1
  147. package/dist/scheduler/mcpSurface.js.map +1 -1
  148. package/dist/scheduler/workerActivity.d.ts.map +1 -1
  149. package/dist/scheduler/workerActivity.js +2 -1
  150. package/dist/scheduler/workerActivity.js.map +1 -1
  151. package/dist/selfUpdate/bootRollback.d.ts.map +1 -1
  152. package/dist/selfUpdate/bootRollback.js +3 -2
  153. package/dist/selfUpdate/bootRollback.js.map +1 -1
  154. package/dist/selfUpdate/updateRuntime.d.ts.map +1 -1
  155. package/dist/selfUpdate/updateRuntime.js +6 -3
  156. package/dist/selfUpdate/updateRuntime.js.map +1 -1
  157. package/dist/state.d.ts +50 -1
  158. package/dist/state.d.ts.map +1 -1
  159. package/dist/state.js +112 -0
  160. package/dist/state.js.map +1 -1
  161. package/dist/stateFile.d.ts.map +1 -1
  162. package/dist/stateFile.js +2 -1
  163. package/dist/stateFile.js.map +1 -1
  164. package/dist/testTimings.d.ts +3 -2
  165. package/dist/testTimings.d.ts.map +1 -1
  166. package/dist/testTimings.js +8 -1
  167. package/dist/testTimings.js.map +1 -1
  168. package/dist/threadContextPreamble.d.ts +15 -1
  169. package/dist/threadContextPreamble.d.ts.map +1 -1
  170. package/dist/threadContextPreamble.js +15 -3
  171. package/dist/threadContextPreamble.js.map +1 -1
  172. package/dist/threadRouting.d.ts +47 -4
  173. package/dist/threadRouting.d.ts.map +1 -1
  174. package/dist/threadRouting.js +31 -4
  175. package/dist/threadRouting.js.map +1 -1
  176. package/dist/todos/projects.d.ts +1 -1
  177. package/dist/todos/projects.d.ts.map +1 -1
  178. package/dist/todos/projects.js +3 -14
  179. package/dist/todos/projects.js.map +1 -1
  180. package/dist/topicTalkerMemory.d.ts +37 -0
  181. package/dist/topicTalkerMemory.d.ts.map +1 -0
  182. package/dist/topicTalkerMemory.js +61 -0
  183. package/dist/topicTalkerMemory.js.map +1 -0
  184. package/dist/topicTalkers.d.ts +123 -0
  185. package/dist/topicTalkers.d.ts.map +1 -0
  186. package/dist/topicTalkers.js +276 -0
  187. package/dist/topicTalkers.js.map +1 -0
  188. package/dist/types.d.ts +16 -12
  189. package/dist/types.d.ts.map +1 -1
  190. package/dist/utils/adoptReplayGate.d.ts +7 -5
  191. package/dist/utils/adoptReplayGate.d.ts.map +1 -1
  192. package/dist/utils/adoptReplayGate.js +7 -5
  193. package/dist/utils/adoptReplayGate.js.map +1 -1
  194. package/dist/utils/agentEnvironment.d.ts +23 -0
  195. package/dist/utils/agentEnvironment.d.ts.map +1 -1
  196. package/dist/utils/agentEnvironment.js +33 -1
  197. package/dist/utils/agentEnvironment.js.map +1 -1
  198. package/dist/utils/agentPlugin.d.ts +7 -2
  199. package/dist/utils/agentPlugin.d.ts.map +1 -1
  200. package/dist/utils/agentPlugin.js +11 -5
  201. package/dist/utils/agentPlugin.js.map +1 -1
  202. package/dist/utils/authorMark.d.ts +59 -0
  203. package/dist/utils/authorMark.d.ts.map +1 -0
  204. package/dist/utils/authorMark.js +86 -0
  205. package/dist/utils/authorMark.js.map +1 -0
  206. package/dist/utils/checkIsRecord.d.ts +6 -0
  207. package/dist/utils/checkIsRecord.d.ts.map +1 -0
  208. package/dist/utils/checkIsRecord.js +11 -0
  209. package/dist/utils/checkIsRecord.js.map +1 -0
  210. package/dist/utils/claudeCompactSummary.js +4 -4
  211. package/dist/utils/claudeCompactSummary.js.map +1 -1
  212. package/dist/utils/claudeLimitSwitch.d.ts +5 -1
  213. package/dist/utils/claudeLimitSwitch.d.ts.map +1 -1
  214. package/dist/utils/claudeLimitSwitch.js +6 -2
  215. package/dist/utils/claudeLimitSwitch.js.map +1 -1
  216. package/dist/utils/claudeMcpHeal.d.ts +18 -3
  217. package/dist/utils/claudeMcpHeal.d.ts.map +1 -1
  218. package/dist/utils/claudeMcpHeal.js +19 -4
  219. package/dist/utils/claudeMcpHeal.js.map +1 -1
  220. package/dist/utils/claudeProfileUsageLines.d.ts +1 -1
  221. package/dist/utils/claudeProfileUsageLines.js +3 -3
  222. package/dist/utils/claudeProfileUsageLines.js.map +1 -1
  223. package/dist/utils/claudeProfiles.d.ts +7 -0
  224. package/dist/utils/claudeProfiles.d.ts.map +1 -1
  225. package/dist/utils/claudeProfiles.js +15 -0
  226. package/dist/utils/claudeProfiles.js.map +1 -1
  227. package/dist/utils/claudeRuntimeInfo.d.ts.map +1 -1
  228. package/dist/utils/claudeRuntimeInfo.js +4 -6
  229. package/dist/utils/claudeRuntimeInfo.js.map +1 -1
  230. package/dist/utils/claudeStreamJson.d.ts +0 -3
  231. package/dist/utils/claudeStreamJson.d.ts.map +1 -1
  232. package/dist/utils/claudeStreamJson.js +21 -26
  233. package/dist/utils/claudeStreamJson.js.map +1 -1
  234. package/dist/utils/claudeSubagentTail.d.ts.map +1 -1
  235. package/dist/utils/claudeSubagentTail.js +4 -11
  236. package/dist/utils/claudeSubagentTail.js.map +1 -1
  237. package/dist/utils/claudeUsage.d.ts +56 -20
  238. package/dist/utils/claudeUsage.d.ts.map +1 -1
  239. package/dist/utils/claudeUsage.js +89 -48
  240. package/dist/utils/claudeUsage.js.map +1 -1
  241. package/dist/utils/fallbackChain.d.ts.map +1 -1
  242. package/dist/utils/fallbackChain.js +8 -4
  243. package/dist/utils/fallbackChain.js.map +1 -1
  244. package/dist/utils/folderGit.d.ts +9 -0
  245. package/dist/utils/folderGit.d.ts.map +1 -0
  246. package/dist/utils/folderGit.js +33 -0
  247. package/dist/utils/folderGit.js.map +1 -0
  248. package/dist/utils/forwardedMark.d.ts +8 -0
  249. package/dist/utils/forwardedMark.d.ts.map +1 -1
  250. package/dist/utils/forwardedMark.js +2 -0
  251. package/dist/utils/forwardedMark.js.map +1 -1
  252. package/dist/utils/jsonStreamHost.d.ts +2 -1
  253. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  254. package/dist/utils/jsonStreamHost.js +4 -2
  255. package/dist/utils/jsonStreamHost.js.map +1 -1
  256. package/dist/utils/messageContext.d.ts +22 -7
  257. package/dist/utils/messageContext.d.ts.map +1 -1
  258. package/dist/utils/messageContext.js +19 -5
  259. package/dist/utils/messageContext.js.map +1 -1
  260. package/dist/utils/openCodeUsage.d.ts.map +1 -1
  261. package/dist/utils/openCodeUsage.js +8 -10
  262. package/dist/utils/openCodeUsage.js.map +1 -1
  263. package/dist/utils/personLabel.d.ts +13 -0
  264. package/dist/utils/personLabel.d.ts.map +1 -0
  265. package/dist/utils/personLabel.js +15 -0
  266. package/dist/utils/personLabel.js.map +1 -0
  267. package/dist/utils/replyQuote.d.ts +17 -3
  268. package/dist/utils/replyQuote.d.ts.map +1 -1
  269. package/dist/utils/replyQuote.js +25 -2
  270. package/dist/utils/replyQuote.js.map +1 -1
  271. package/dist/utils/talkerAccess.d.ts +9 -0
  272. package/dist/utils/talkerAccess.d.ts.map +1 -0
  273. package/dist/utils/talkerAccess.js +20 -0
  274. package/dist/utils/talkerAccess.js.map +1 -0
  275. package/dist/utils/telegramError.d.ts.map +1 -1
  276. package/dist/utils/telegramError.js +5 -7
  277. package/dist/utils/telegramError.js.map +1 -1
  278. package/dist/utils/tmuxExec.d.ts +20 -8
  279. package/dist/utils/tmuxExec.d.ts.map +1 -1
  280. package/dist/utils/tmuxExec.js +27 -7
  281. package/dist/utils/tmuxExec.js.map +1 -1
  282. package/dist/utils/topicAccessScreenPlan.d.ts +253 -0
  283. package/dist/utils/topicAccessScreenPlan.d.ts.map +1 -0
  284. package/dist/utils/topicAccessScreenPlan.js +287 -0
  285. package/dist/utils/topicAccessScreenPlan.js.map +1 -0
  286. package/dist/utils/topicLabel.d.ts +12 -0
  287. package/dist/utils/topicLabel.d.ts.map +1 -0
  288. package/dist/utils/topicLabel.js +12 -0
  289. package/dist/utils/topicLabel.js.map +1 -0
  290. package/dist/utils/topicRequest.d.ts +8 -5
  291. package/dist/utils/topicRequest.d.ts.map +1 -1
  292. package/dist/utils/topicRequest.js +9 -7
  293. package/dist/utils/topicRequest.js.map +1 -1
  294. package/npm-shrinkwrap.json +1003 -0
  295. package/package.json +4 -2
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.OpenCodeAdapter = exports.openCodeServerRestartRetryBudgetMs = exports.openCodeServerRestartRetryDelaysMs = exports.schedulerMcpRetryDelaysMs = exports.openCodeErrorMessageMaxLength = exports.providerRetryReplacementStartTimeoutMs = exports.criticalSseEventTypes = exports.openCodeRuntimeContextHydrationConcurrency = void 0;
36
+ exports.OpenCodeAdapter = exports.mislaunchedServerRecheckDelayMs = exports.openCodeServerRestartRetryBudgetMs = exports.openCodeServerRestartRetryDelaysMs = exports.schedulerMcpRetryDelaysMs = exports.openCodeErrorMessageMaxLength = exports.providerRetryReplacementStartTimeoutMs = exports.criticalSseEventTypes = exports.openCodeRuntimeContextHydrationConcurrency = void 0;
37
37
  exports.listSavedOpenCodeModelLabels = listSavedOpenCodeModelLabels;
38
38
  exports.normaliseOpenCodeSseEvent = normaliseOpenCodeSseEvent;
39
39
  exports.buildDirectoryScopedPath = buildDirectoryScopedPath;
@@ -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
@@ -1010,6 +1053,12 @@ exports.openCodeServerRestartRetryDelaysMs = [2_000, 5_000, 10_000, 15_000, 20_0
1010
1053
  * a hopeless start from holding the topics for minutes.
1011
1054
  */
1012
1055
  exports.openCodeServerRestartRetryBudgetMs = 60_000;
1056
+ /**
1057
+ * How long {@link OpenCodeAdapter.replaceMislaunchedServer} waits before it looks again at a server it must replace while a
1058
+ * session works in it: a plain instance boots rarely, so "the next boot" alone could leave a server without a password open
1059
+ * for days.
1060
+ */
1061
+ exports.mislaunchedServerRecheckDelayMs = 10 * 60_000;
1013
1062
  /**
1014
1063
  * @description The pause before retry number `retryIndex` (0-based), or
1015
1064
  * `null` once the pauses are used up or the retry would start past `budgetMs`
@@ -1028,6 +1077,7 @@ const defaultOpenCodeServerRestartOps = {
1028
1077
  ensureServer: installManager_1.ensureOpenCodeServer,
1029
1078
  restartServer: installManager_1.restartOpenCodeServer,
1030
1079
  readServerLaunch: installManager_1.readOpenCodeServerLaunch,
1080
+ readServerExposure: installManager_1.readOpenCodeServerExposure,
1031
1081
  };
1032
1082
  function buildProviderApiAuthPayload(apiKey) {
1033
1083
  return { type: 'api', key: apiKey };
@@ -1062,18 +1112,18 @@ function getFreshProvidersConfig(now = Date.now()) {
1062
1112
  }
1063
1113
  function parseProvidersResponse(raw) {
1064
1114
  const out = { providers: new Map() };
1065
- if (!checkIsOpenCodeRecord(raw))
1115
+ if (!(0, checkIsRecord_1.checkIsRecord)(raw))
1066
1116
  return out;
1067
1117
  // Two shapes seen in the wild: `{ providers: [...] }` (array, opencode
1068
1118
  // 1.15.x) and `{ providers: { <id>: {...} } }` (older bundles). Parse
1069
1119
  // both into the same flat (providerId → modelId → model config) map so
1070
1120
  // the rest of the code doesn't care which shape the server sent.
1071
1121
  const collect = (providerId, providerObj) => {
1072
- if (!checkIsOpenCodeRecord(providerObj) || !checkIsOpenCodeRecord(providerObj.models))
1122
+ if (!(0, checkIsRecord_1.checkIsRecord)(providerObj) || !(0, checkIsRecord_1.checkIsRecord)(providerObj.models))
1073
1123
  return;
1074
1124
  const modelMap = new Map();
1075
1125
  for (const [modelId, modelObj] of Object.entries(providerObj.models)) {
1076
- if (!checkIsOpenCodeRecord(modelObj)) {
1126
+ if (!(0, checkIsRecord_1.checkIsRecord)(modelObj)) {
1077
1127
  modelMap.set(modelId, { variants: [], contextWindowTokens: null });
1078
1128
  continue;
1079
1129
  }
@@ -1087,11 +1137,11 @@ function parseProvidersResponse(raw) {
1087
1137
  const providersField = raw.providers;
1088
1138
  if (Array.isArray(providersField)) {
1089
1139
  for (const item of providersField) {
1090
- if (checkIsOpenCodeRecord(item) && typeof item.id === 'string')
1140
+ if ((0, checkIsRecord_1.checkIsRecord)(item) && typeof item.id === 'string')
1091
1141
  collect(item.id, item);
1092
1142
  }
1093
1143
  }
1094
- else if (checkIsOpenCodeRecord(providersField)) {
1144
+ else if ((0, checkIsRecord_1.checkIsRecord)(providersField)) {
1095
1145
  for (const [id, value] of Object.entries(providersField)) {
1096
1146
  collect(id, value);
1097
1147
  }
@@ -1216,11 +1266,18 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1216
1266
  */
1217
1267
  registeredSchedulerMcpDirs = new Set();
1218
1268
  /**
1219
- * Directories whose scheduler-MCP registration failed and is waiting for a
1220
- * retry: the number of retries already scheduled, and the pending timer (null
1221
- * 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.
1222
1274
  */
1223
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();
1224
1281
  /**
1225
1282
  * child sessionID → parent sessionID, learned from `session.updated` events.
1226
1283
  * OpenCode runs subagents (e.g. `@explore`) in child sessions whose SSE
@@ -1235,7 +1292,6 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1235
1292
  */
1236
1293
  sseDropLogThrottle = new Map();
1237
1294
  baseUrl;
1238
- authHeader;
1239
1295
  /**
1240
1296
  * Grace period (ms) the fallback rename waits for opencode's native
1241
1297
  * auto-title before stepping in. Instance field (initialised from
@@ -1268,8 +1324,12 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1268
1324
  * tests can fail attempts and shrink the pauses — production never changes them.
1269
1325
  */
1270
1326
  serverRestartOps = defaultOpenCodeServerRestartOps;
1271
- /** The skills boot step said once why it leaves the running server alone (`activateAgentSkillsForServer`). */
1272
- isAgentSkillsSkipAnnounced = false;
1327
+ /** The boot step said once why it leaves the running server alone (`replaceMislaunchedServer`). */
1328
+ isMislaunchedServerSkipAnnounced = false;
1329
+ /** The pending look again of {@link replaceMislaunchedServer} at a server a working session kept it from replacing. */
1330
+ mislaunchedServerRecheckTimer = null;
1331
+ /** Instance field only so a test can shorten it; production keeps {@link mislaunchedServerRecheckDelayMs}. */
1332
+ mislaunchedServerRecheckDelayMs = exports.mislaunchedServerRecheckDelayMs;
1273
1333
  serverRestartRetryDelaysMs = exports.openCodeServerRestartRetryDelaysMs;
1274
1334
  serverRestartRetryBudgetMs = exports.openCodeServerRestartRetryBudgetMs;
1275
1335
  /**
@@ -1335,14 +1395,6 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1335
1395
  super();
1336
1396
  // Audit S7 / #34: SSRF guard on OPENCODE_URL before any fetch runs.
1337
1397
  this.baseUrl = validateOpenCodeUrl(process.env.OPENCODE_URL || installManager_1.defaultOpenCodeUrl);
1338
- const password = process.env.OPENCODE_PASSWORD;
1339
- if (password) {
1340
- const username = process.env.OPENCODE_USERNAME || 'opencode';
1341
- this.authHeader = 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');
1342
- }
1343
- else {
1344
- this.authHeader = null;
1345
- }
1346
1398
  // Listen for unexpected server crashes (OOM kill, segfault, etc.)
1347
1399
  (0, installManager_1.onOpenCodeServerExit)((code, signal) => {
1348
1400
  console.error(`[OpenCode] Server crashed unexpectedly: code=${code}, signal=${signal}`);
@@ -1407,10 +1459,9 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1407
1459
  // stale reader would only self-heal later via the stall watchdog —
1408
1460
  // closing here makes recovery deterministic and tied to the restart.
1409
1461
  this.closeGlobalStream();
1410
- // The restarted server has a fresh, empty MCP table, so every directory's
1411
- // scheduler-MCP registration died with the old generation. Clear the gate
1412
- // so connectSse re-registers each still-active directory on resume.
1413
- 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.
1414
1465
  // OpenCode persists sessions to disk, so the restarted server still
1415
1466
  // knows the previous session ids — that's the basis of this recovery.
1416
1467
  // For each in-memory session that was active, re-resume the SAME id
@@ -1502,6 +1553,7 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1502
1553
  else
1503
1554
  await this.serverRestartOps.ensureServer();
1504
1555
  console.log(`[OpenCode] Server is up`);
1556
+ this.dropServerGenerationState();
1505
1557
  return;
1506
1558
  }
1507
1559
  catch (e) {
@@ -1515,6 +1567,17 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1515
1567
  }
1516
1568
  }
1517
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
+ }
1518
1581
  /**
1519
1582
  * @description {@link ensureServerWithRetries} for a session start or resume of
1520
1583
  * `key`: the server is brought up only when it is down, and the topic is told
@@ -1535,15 +1598,13 @@ class OpenCodeAdapter extends events_1.EventEmitter {
1535
1598
  async reloadProviderAuth() {
1536
1599
  return this.restartServer(true);
1537
1600
  }
1601
+ /** @description Read per request: every server generation the bot starts has a password of its own. */
1538
1602
  getHeaders() {
1539
- const headers = {
1603
+ return {
1540
1604
  'Content-Type': 'application/json',
1541
1605
  'Accept': 'application/json',
1606
+ ...(0, installManager_1.getOpenCodeServerAuthHeaders)(),
1542
1607
  };
1543
- if (this.authHeader) {
1544
- headers['Authorization'] = this.authHeader;
1545
- }
1546
- return headers;
1547
1608
  }
1548
1609
  async apiRequest(method, urlPath, body, options) {
1549
1610
  const url = `${this.baseUrl}${urlPath}`;
@@ -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).
@@ -3081,41 +3146,75 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3081
3146
  await Promise.allSettled(Array.from(directories, (directory) => this.reconcileSchedulerMcpForDirectory(directory)));
3082
3147
  }
3083
3148
  /**
3084
- * @description Boot step for the skills the bot gives its agents (`utils/agentPlugin.ts`). OpenCode reads its
3085
- * `OPENCODE_CONFIG_DIR` once, at start, so a server started the other way than the instance's «Bot skills» switch says —
3086
- * without the bot's folder while the switch is ON (an older bot, adopted ever since; the switch turned on since), with it
3087
- * while the switch is OFF — keeps offering the wrong thing. Such a server is replaced through the controlled restart that
3088
- * restores the sessions, but only when the bot owns it (its process record) AND `/proc` shows it is an `opencode … serve`
3089
- * (a server the bot does not own, or a listener it cannot identify, is left as is — one log line per process), the folder
3090
- * it would get is ready, and no session is working: a busy directory, or a status it cannot read, leaves it for the next
3091
- * boot. Only the INSTANCE value counts: one server serves every topic. Best-effort, never rejects.
3149
+ * @description Boot step that replaces a server started the wrong way, which a running server never corrects by itself:
3150
+ * - the skills the bot gives its agents (`utils/agentPlugin.ts`): OpenCode reads its `OPENCODE_CONFIG_DIR` once, at start,
3151
+ * so a server started the other way than the instance's «Bot skills» switch says — without the bot's folder while the
3152
+ * switch is ON (an older bot, adopted ever since; the switch turned on since), with it while the switch is OFF — keeps
3153
+ * offering the wrong thing; only the INSTANCE value counts: one server serves every topic. Replaced only when the bot
3154
+ * owns it (its process record) AND `/proc` shows it is an `opencode … serve`, and the folder it would get is ready;
3155
+ * - its password: a server that answers a request without one lets every local account drive its agents. Read the way such
3156
+ * an account would, on every platform ({@link OpenCodeServerExposure}), and replaced whether the bot owns it or not — like a
3157
+ * stale version — as long as it is an `opencode … serve` the bot may stop: one a bot from before passwords left running,
3158
+ * and also one the operator runs on the bot's port (the idle check sees only the bot's sessions, so a turn of the
3159
+ * operator's own in it ends; the docs tell them to start such a server with `OPENCODE_SERVER_PASSWORD`). A test's
3160
+ * stand-in or another account's process never is.
3161
+ * The replacement is the controlled restart that restores the sessions, and only when no session is working: a busy
3162
+ * directory, or a status it cannot read, makes it look again after {@link mislaunchedServerRecheckDelayMs} (and at the
3163
+ * next boot). A server it leaves for another reason gets one log line per process. Best-effort, never rejects.
3092
3164
  */
3093
- async activateAgentSkillsForServer() {
3165
+ async replaceMislaunchedServer() {
3094
3166
  try {
3095
3167
  const expectation = (0, agentPlugin_1.getOpenCodeAgentSkillsExpectation)(process.env, (0, state_1.resolveDataDir)(), (0, botSkills_1.checkIsBotSkillsEnabled)(null));
3096
- const action = (0, agentPlugin_1.getOpenCodeAgentSkillsServerAction)(await this.serverRestartOps.readServerLaunch(), expectation);
3097
- if (action === 'skipNotOwned' || action === 'skipUnidentified') {
3098
- if (!this.isAgentSkillsSkipAnnounced) {
3099
- this.isAgentSkillsSkipAnnounced = true;
3100
- const reason = action === 'skipNotOwned' ? 'is not owned by the bot' : 'cannot be identified as `opencode serve`';
3101
- console.log(`[OpenCode] the server ${reason}; it is left as is, and offers the bot's skills only if it was started with them`);
3102
- }
3103
- return;
3168
+ const skillsAction = (0, agentPlugin_1.getOpenCodeAgentSkillsServerAction)(await this.serverRestartOps.readServerLaunch(), expectation);
3169
+ const exposure = await this.serverRestartOps.readServerExposure();
3170
+ const faults = [];
3171
+ if (skillsAction === 'replace') {
3172
+ faults.push(expectation.kind === 'offered' ? `without the bot's skills` : `with the bot's skills, which the instance switched off`);
3104
3173
  }
3105
- if (action === 'none')
3174
+ if (exposure === 'openStoppable')
3175
+ faults.push('without a password (every local account can drive its agents)');
3176
+ if (faults.length === 0) {
3177
+ const reasonsLeft = [];
3178
+ if (skillsAction === 'skipNotOwned')
3179
+ reasonsLeft.push(`is not owned by the bot, and offers the bot's skills only if it was started with them`);
3180
+ if (skillsAction === 'skipUnidentified')
3181
+ reasonsLeft.push(`cannot be identified as \`opencode serve\`, and offers the bot's skills only if it was started with them`);
3182
+ if (exposure === 'openUnstoppable')
3183
+ reasonsLeft.push('answers without a password, and is not an `opencode serve` of the bot\'s user it may stop');
3184
+ if (reasonsLeft.length > 0)
3185
+ this.announceMislaunchedServerSkipOnce(`the server ${reasonsLeft.join('; it ')}; it is left as is`);
3106
3186
  return;
3107
- const startedWith = expectation.kind === 'offered' ? `without the bot's skills` : `with the bot's skills, which the instance switched off`;
3187
+ }
3188
+ const startedWith = faults.join(' and ');
3108
3189
  if (!(await this.checkIsEveryActiveSessionIdle())) {
3109
- console.log(`[OpenCode] the server was started ${startedWith}; a session is working, the next boot retries`);
3190
+ console.log(`[OpenCode] the server was started ${startedWith}; a session is working, looking again in ${Math.round(this.mislaunchedServerRecheckDelayMs / 60_000)} min`);
3191
+ this.scheduleMislaunchedServerRecheck();
3110
3192
  return;
3111
3193
  }
3112
3194
  console.log(`[OpenCode] the server was started ${startedWith}; replacing it`);
3113
3195
  await this.restartServer(true);
3114
3196
  }
3115
3197
  catch (e) {
3116
- console.warn(`[OpenCode] could not check the server for the bot's skills:`, e instanceof Error ? e.message : e);
3198
+ console.warn(`[OpenCode] could not check how the server was started:`, e instanceof Error ? e.message : e);
3117
3199
  }
3118
3200
  }
3201
+ /** @description Look again at the server once the delay is over; one pending look at a time, never holding the process open. */
3202
+ scheduleMislaunchedServerRecheck() {
3203
+ if (this.mislaunchedServerRecheckTimer)
3204
+ return;
3205
+ this.mislaunchedServerRecheckTimer = setTimeout(() => {
3206
+ this.mislaunchedServerRecheckTimer = null;
3207
+ void this.replaceMislaunchedServer();
3208
+ }, this.mislaunchedServerRecheckDelayMs);
3209
+ this.mislaunchedServerRecheckTimer.unref();
3210
+ }
3211
+ /** @description Say once per process why {@link replaceMislaunchedServer} leaves the running server alone. */
3212
+ announceMislaunchedServerSkipOnce(line) {
3213
+ if (this.isMislaunchedServerSkipAnnounced)
3214
+ return;
3215
+ this.isMislaunchedServerSkipAnnounced = true;
3216
+ console.log(`[OpenCode] ${line}`);
3217
+ }
3119
3218
  /**
3120
3219
  * @description Whether no active session is working — by the adapter's own view and by each directory's status.
3121
3220
  *
@@ -3145,7 +3244,7 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3145
3244
  * older version keeps the older text. Installs the file, then per directory
3146
3245
  * (de-duped, concurrently) recreates the instance when it lacks the current
3147
3246
  * plugin and nothing in it is running. A recreated directory loses
3148
- * 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
3149
3248
  * the boot caller reconciles the MCP right after.
3150
3249
  */
3151
3250
  async activateCompactionPluginForActiveSessions() {
@@ -3179,6 +3278,7 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3179
3278
  }
3180
3279
  await this.apiRequest('POST', buildDirectoryScopedPath('/instance/dispose', directory));
3181
3280
  this.registeredSchedulerMcpDirs.delete(directory);
3281
+ this.configDefinedMcpNames.delete(directory);
3182
3282
  console.log(`[OpenCode] recreated the ${directory} instance so it loads the compaction plugin`);
3183
3283
  }
3184
3284
  catch (e) {
@@ -3187,8 +3287,12 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3187
3287
  }
3188
3288
  /**
3189
3289
  * @description Reconcile ONE directory: read the live `GET /mcp` status and,
3190
- * when `telegramBot` is missing or not `connected`, drop the Set gate and
3191
- * 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,
3192
3296
  * scheduled for a retry, and swallowed so it never rejects out of
3193
3297
  * {@link reconcileSchedulerMcpForActiveSessions}.
3194
3298
  */
@@ -3196,8 +3300,27 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3196
3300
  try {
3197
3301
  const mcpStatus = await this.apiRequest('GET', buildDirectoryScopedPath('/mcp', directory));
3198
3302
  if (!checkNeedsSchedulerMcpReregister(mcpStatus)) {
3199
- // A registration that timed out can still have landed on the server.
3200
- 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);
3201
3324
  return;
3202
3325
  }
3203
3326
  // The live server contradicts the Set gate (stale entry from a prior
@@ -3218,14 +3341,18 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3218
3341
  * covers a second failure, and one that fires after the folder's last session
3219
3342
  * ended does nothing.
3220
3343
  */
3221
- scheduleSchedulerMcpRetry(directory) {
3222
- 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;
3223
3350
  if (retry.timer)
3224
3351
  return;
3225
3352
  const delayMs = getSchedulerMcpRetryDelayMs(retry.attempt);
3226
3353
  if (delayMs === null) {
3227
3354
  this.schedulerMcpRetries.delete(directory);
3228
- 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);
3229
3356
  return;
3230
3357
  }
3231
3358
  retry.attempt += 1;
@@ -3240,10 +3367,13 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3240
3367
  }, delayMs);
3241
3368
  retry.timer.unref?.();
3242
3369
  this.schedulerMcpRetries.set(directory, retry);
3243
- console.log(`[OpenCode] retrying the scheduler MCP registration for ${directory} in ${Math.round(delayMs / 1000)}s ` +
3244
- `(${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})`);
3245
3372
  }
3246
- /** @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
+ */
3247
3377
  clearSchedulerMcpRetry(directory) {
3248
3378
  const retry = this.schedulerMcpRetries.get(directory);
3249
3379
  if (!retry)
@@ -3342,15 +3472,92 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3342
3472
  return;
3343
3473
  if (this.registeredSchedulerMcpDirs.has(directory))
3344
3474
  return;
3475
+ let mcpStatus;
3345
3476
  try {
3346
- 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);
3347
3479
  this.registeredSchedulerMcpDirs.add(directory);
3348
- this.clearSchedulerMcpRetry(directory);
3349
3480
  (0, diagLog_1.appendDiagLog)(`scheduler mcp registered dir=${directory}`);
3350
3481
  }
3351
3482
  catch (e) {
3352
3483
  console.warn(`[OpenCode] scheduler MCP registration failed for ${directory}:`, e instanceof Error ? e.message : e);
3353
- 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;
3354
3561
  }
3355
3562
  }
3356
3563
  /**
@@ -3469,10 +3676,8 @@ class OpenCodeAdapter extends events_1.EventEmitter {
3469
3676
  const streamLabel = stream.directory;
3470
3677
  const headers = {
3471
3678
  'Accept': 'text/event-stream',
3679
+ ...(0, installManager_1.getOpenCodeServerAuthHeaders)(),
3472
3680
  };
3473
- if (this.authHeader) {
3474
- headers['Authorization'] = this.authHeader;
3475
- }
3476
3681
  // Audit S7 / #12: SSE was previously read with no abort path —
3477
3682
  // `await reader.read()` blocks until bytes arrive, so a teardown during a
3478
3683
  // silent server couldn't actually free the connection. The stream-scoped