polygram 0.30.0 → 0.31.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://anthropic.com/claude-code/plugin.schema.json",
3
3
  "name": "polygram",
4
- "version": "0.30.0",
4
+ "version": "0.31.0",
5
5
  "description": "Telegram integration for Claude Code that preserves the OpenClaw per-chat session model. Migration target for OpenClaw users. Multi-bot, multi-chat, per-topic isolation; SQLite transcripts; inline-keyboard approvals. Bundles /polygram:status|logs|pair-code|approvals admin commands plus history (transcript queries) and polygram-send (out-of-turn IPC sends with file-upload validation) skills.",
6
6
  "keywords": [
7
7
  "telegram",
@@ -133,6 +133,7 @@ function inspectCodexProfile(raw, profileId) {
133
133
  new RegExp(`^default_permissions\\s*=\\s*"${escapedProfile}"\\s*$`, 'm'),
134
134
  /^approval_policy\s*=\s*"never"\s*$/m,
135
135
  /^web_search\s*=\s*"disabled"\s*$/m,
136
+ /^\[features\]\s*\ngoals\s*=\s*false\s*$/m,
136
137
  new RegExp(
137
138
  `^\\[permissions\\."${escapedProfile}"\\.network\\]\\s*\\n`
138
139
  + 'enabled\\s*=\\s*false\\s*$',
@@ -11,6 +11,7 @@ const {
11
11
  } = require('./runtime-profile');
12
12
  const {
13
13
  createCodexRuntimeAvailability,
14
+ resolveCodexRuntimeCandidate,
14
15
  resolveCodexRuntimeRequest,
15
16
  resolveRuntimeConfig,
16
17
  } = require('../runtime-config');
@@ -140,6 +141,7 @@ function createCodexRuntimeController({
140
141
  attestCodexHome = orchestraDefault.attestPinnedCodexHome,
141
142
  createAvailability = createCodexRuntimeAvailability,
142
143
  resolveRuntime = resolveRuntimeConfig,
144
+ resolveCandidate = resolveCodexRuntimeCandidate,
143
145
  resolveRequest = resolveCodexRuntimeRequest,
144
146
  orchestra = orchestraDefault,
145
147
  logger = console,
@@ -166,6 +168,7 @@ function createCodexRuntimeController({
166
168
  || typeof attestCodexHome !== 'function'
167
169
  || typeof createAvailability !== 'function'
168
170
  || typeof resolveRuntime !== 'function'
171
+ || typeof resolveCandidate !== 'function'
169
172
  || typeof resolveRequest !== 'function'
170
173
  || typeof orchestra?.CodexAppServerClient !== 'function'
171
174
  || !Array.isArray(defaultDaemonSecretRoots)
@@ -370,17 +373,7 @@ function createCodexRuntimeController({
370
373
  return state;
371
374
  }
372
375
 
373
- async function prepareSession({ sessionKey, chatId, threadId = null } = {}) {
374
- boundedString(sessionKey, 'session key');
375
- const state = requireAvailableInitialization();
376
- const request = resolveRequest({
377
- config,
378
- chatId,
379
- threadId,
380
- defaultPm: 'sdk',
381
- });
382
- if (!request) return null;
383
-
376
+ async function prepareCodexRequest({ sessionKey, request, state }) {
384
377
  const existing = receiptsBySession.get(sessionKey);
385
378
  if (existing && sameProfileRequest(
386
379
  existing.receipt.expectedStaticProfile,
@@ -403,7 +396,7 @@ function createCodexRuntimeController({
403
396
  && catalogAgeMs < catalogMaxAgeMs
404
397
  && catalogSupports(existing.catalog, request)
405
398
  ) {
406
- return prepareRuntimeView(existing, request, chatId, threadId);
399
+ return existing;
407
400
  }
408
401
  invalidatePreparedSession(sessionKey, existing);
409
402
  }
@@ -472,7 +465,7 @@ function createCodexRuntimeController({
472
465
  deploymentIdentity,
473
466
  };
474
467
  receiptsBySession.set(sessionKey, entry);
475
- return prepareRuntimeView(entry, request, chatId, threadId);
468
+ return entry;
476
469
  })();
477
470
  preparingByKey.set(key, promise);
478
471
  try {
@@ -482,14 +475,42 @@ function createCodexRuntimeController({
482
475
  }
483
476
  }
484
477
 
485
- async function resolveRuntimeView({
478
+ async function prepareCandidate({
486
479
  sessionKey,
487
480
  chatId,
488
481
  threadId = null,
489
482
  } = {}) {
490
- const prepared = await prepareSession({ sessionKey, chatId, threadId });
491
- if (!prepared) return Object.freeze({ runtime: 'claude' });
492
- const { runtimeConfig, catalog } = prepared;
483
+ boundedString(sessionKey, 'session key');
484
+ const state = requireAvailableInitialization();
485
+ const request = resolveCandidate({
486
+ config,
487
+ chatId,
488
+ threadId,
489
+ });
490
+ if (!request) return null;
491
+ const entry = await prepareCodexRequest({ sessionKey, request, state });
492
+ return Object.freeze({
493
+ request,
494
+ availability: entry.availability,
495
+ catalog: entry.catalog,
496
+ });
497
+ }
498
+
499
+ async function prepareSession({ sessionKey, chatId, threadId = null } = {}) {
500
+ boundedString(sessionKey, 'session key');
501
+ const state = requireAvailableInitialization();
502
+ const request = resolveRequest({
503
+ config,
504
+ chatId,
505
+ threadId,
506
+ defaultPm: 'sdk',
507
+ });
508
+ if (!request) return null;
509
+ const entry = await prepareCodexRequest({ sessionKey, request, state });
510
+ return prepareRuntimeView(entry, request, chatId, threadId);
511
+ }
512
+
513
+ function runtimeCatalogView({ model, effort, catalog }) {
493
514
  const models = Array.isArray(catalog.models)
494
515
  ? catalog.models.map((entry) => Object.freeze({
495
516
  model: entry.model,
@@ -502,16 +523,54 @@ function createCodexRuntimeController({
502
523
  : [];
503
524
  return Object.freeze({
504
525
  runtime: 'codex',
505
- model: runtimeConfig.model,
506
- effort: runtimeConfig.effort,
526
+ model,
527
+ effort,
507
528
  models: Object.freeze(models),
508
529
  efforts: Object.freeze(
509
- models.find(({ model }) => model === runtimeConfig.model)
530
+ models.find((entry) => entry.model === model)
510
531
  ?.supportedReasoningEfforts ?? [],
511
532
  ),
512
533
  });
513
534
  }
514
535
 
536
+ async function resolveCandidateRuntimeView({
537
+ sessionKey,
538
+ chatId,
539
+ threadId = null,
540
+ } = {}) {
541
+ const prepared = await prepareCandidate({ sessionKey, chatId, threadId });
542
+ if (!prepared) return Object.freeze({ runtime: 'claude' });
543
+ return runtimeCatalogView({
544
+ model: prepared.request.model,
545
+ effort: prepared.request.effort,
546
+ catalog: prepared.catalog,
547
+ });
548
+ }
549
+
550
+ function discardCandidateRuntime(sessionKey) {
551
+ boundedString(sessionKey, 'session key');
552
+ if (currentProcessBySession.has(sessionKey)) return false;
553
+ const entry = receiptsBySession.get(sessionKey);
554
+ if (!entry) return false;
555
+ receiptsBySession.delete(sessionKey);
556
+ return true;
557
+ }
558
+
559
+ async function resolveRuntimeView({
560
+ sessionKey,
561
+ chatId,
562
+ threadId = null,
563
+ } = {}) {
564
+ const prepared = await prepareSession({ sessionKey, chatId, threadId });
565
+ if (!prepared) return Object.freeze({ runtime: 'claude' });
566
+ const { runtimeConfig, catalog } = prepared;
567
+ return runtimeCatalogView({
568
+ model: runtimeConfig.model,
569
+ effort: runtimeConfig.effort,
570
+ catalog,
571
+ });
572
+ }
573
+
515
574
  function resolveReceipt(sessionKey, identity) {
516
575
  const entry = receiptsBySession.get(sessionKey);
517
576
  if (
@@ -1270,6 +1329,8 @@ function createCodexRuntimeController({
1270
1329
  return Object.freeze({
1271
1330
  initialize,
1272
1331
  prepareSession,
1332
+ discardCandidateRuntime,
1333
+ resolveCandidateRuntimeView,
1273
1334
  resolveRuntimeView,
1274
1335
  resolveReceipt,
1275
1336
  clientFactory,
@@ -303,6 +303,9 @@ function buildOwnedConfig({
303
303
  approvals_reviewer: 'user',
304
304
  web_search: 'disabled',
305
305
  allow_login_shell: false,
306
+ features: {
307
+ goals: false,
308
+ },
306
309
  shell_environment_policy: {
307
310
  inherit: 'none',
308
311
  ignore_default_excludes: false,
@@ -342,6 +345,9 @@ function renderOwnedConfig(config, {
342
345
  'web_search = "disabled"',
343
346
  'allow_login_shell = false',
344
347
  '',
348
+ '[features]',
349
+ 'goals = false',
350
+ '',
345
351
  '[shell_environment_policy]',
346
352
  'inherit = "none"',
347
353
  'ignore_default_excludes = false',
@@ -3,6 +3,9 @@
3
3
  const {
4
4
  resolveProviderSessionForSpawn,
5
5
  } = require('../db/sessions');
6
+ const {
7
+ processMatchesRuntime,
8
+ } = require('../runtime-config');
6
9
 
7
10
  async function buildCodexSpawnContext({
8
11
  sessionKey,
@@ -14,6 +17,7 @@ async function buildCodexSpawnContext({
14
17
  runtimeController,
15
18
  getSessionLabel,
16
19
  logEvent,
20
+ mutateSessionOnDrift = true,
17
21
  }) {
18
22
  const prepared = await runtimeController.prepareSession({
19
23
  sessionKey,
@@ -22,9 +26,13 @@ async function buildCodexSpawnContext({
22
26
  });
23
27
  const runtime = prepared.runtimeConfig;
24
28
  let liveProcess = pm?.get(sessionKey) ?? null;
29
+ let liveCodexProcess = processMatchesRuntime(
30
+ liveProcess,
31
+ 'codex',
32
+ 'codex',
33
+ );
25
34
  const replacementReason = (
26
- liveProcess
27
- && !liveProcess.closed
35
+ liveCodexProcess
28
36
  ) ? runtimeController.processReplacementReason(
29
37
  sessionKey,
30
38
  liveProcess,
@@ -39,9 +47,10 @@ async function buildCodexSpawnContext({
39
47
  });
40
48
  await pm.kill(sessionKey, replacementReason);
41
49
  liveProcess = null;
50
+ liveCodexProcess = false;
42
51
  }
43
52
 
44
- const isColdSpawn = !liveProcess || liveProcess.closed;
53
+ const isColdSpawn = !liveCodexProcess;
45
54
  let existingSessionId = null;
46
55
  if (isColdSpawn) {
47
56
  const resolved = resolveProviderSessionForSpawn(db, sessionKey, {
@@ -51,7 +60,7 @@ async function buildCodexSpawnContext({
51
60
  cwd: runtime.cwd,
52
61
  model: runtime.model,
53
62
  effort: runtime.effort,
54
- });
63
+ }, { mutateOnDrift: mutateSessionOnDrift });
55
64
  existingSessionId = resolved.existingSessionId;
56
65
  if (resolved.drift) {
57
66
  logEvent('session-config-drift', {
@@ -115,7 +115,12 @@ function getClaudeSessionId(db, sessionKey) {
115
115
  return row?.claude_session_id || null;
116
116
  }
117
117
 
118
- function resolveProviderSessionForSpawn(db, sessionKey, resolved = {}) {
118
+ function resolveProviderSessionForSpawn(
119
+ db,
120
+ sessionKey,
121
+ resolved = {},
122
+ { mutateOnDrift = true } = {},
123
+ ) {
119
124
  const namespace = sessionNamespaceFor(resolved);
120
125
  if (!db) {
121
126
  return {
@@ -126,7 +131,12 @@ function resolveProviderSessionForSpawn(db, sessionKey, resolved = {}) {
126
131
  };
127
132
  }
128
133
  if (resolved.runtime !== 'codex') {
129
- const legacy = resolveSessionForSpawn(db, sessionKey, resolved);
134
+ const legacy = resolveSessionForSpawn(
135
+ db,
136
+ sessionKey,
137
+ resolved,
138
+ { mutateOnDrift },
139
+ );
130
140
  const row = legacy.existingSessionId
131
141
  ? db.getProviderSession(sessionKey, namespace)
132
142
  : null;
@@ -163,7 +173,9 @@ function resolveProviderSessionForSpawn(db, sessionKey, resolved = {}) {
163
173
  after[field] != null && after[field] !== before[field]
164
174
  ));
165
175
  if (fields.length > 0) {
166
- db.clearProviderSession(sessionKey, namespace);
176
+ if (mutateOnDrift) {
177
+ db.clearProviderSession(sessionKey, namespace);
178
+ }
167
179
  return {
168
180
  existingSessionId: null,
169
181
  appServerSessionId: null,
@@ -238,25 +250,35 @@ const CODEX_SPAWN_IDENTITY_FIELDS = ['cwd'];
238
250
  * or whether config drift means it must be dropped and re-spawned
239
251
  * fresh.
240
252
  *
241
- * On drift the stale row is DELETED here — so the very next spawn
242
- * mints a fresh claude_session_id under the correct config and the
243
- * `onInit` callback re-upserts the row. This self-heals every
244
- * pre-migration stale row across all chats with no manual SQL.
253
+ * By default, drift deletes the stale row so the next spawn mints a fresh
254
+ * claude_session_id and `onInit` re-upserts it. Runtime-switch preparation
255
+ * can report the same drift without mutation so a failed replacement leaves
256
+ * the dormant session recoverable.
245
257
  *
246
258
  * @param {object|null} db — DB handle (null → fresh spawn)
247
259
  * @param {string} sessionKey
248
260
  * @param {object} resolved — freshly-resolved spawn config
261
+ * @param {object} [options]
262
+ * @param {boolean} [options.mutateOnDrift=true]
263
+ * Delete an incompatible stored row immediately. Runtime-switch
264
+ * preparation sets this false so a later replacement failure cannot erase
265
+ * the dormant session.
249
266
  * @param {string} [resolved.agent]
250
267
  * @param {string} [resolved.cwd]
251
268
  * @param {string} [resolved.backend] — 'sdk' | 'tmux' (resolved by
252
269
  * process/factory.js pickBackend); compared to the row's pm_backend
253
270
  * @returns {{ existingSessionId: string|null, drift: object|null }}
254
271
  * existingSessionId — pass to start() for --resume, or null for a
255
- * fresh spawn (no stored row, or drift dropped it)
272
+ * fresh spawn (no stored row, or incompatible stored row)
256
273
  * drift — null when no drift; otherwise { fields, before, after }
257
274
  * for the `session-config-drift` telemetry event
258
275
  */
259
- function resolveSessionForSpawn(db, sessionKey, resolved = {}) {
276
+ function resolveSessionForSpawn(
277
+ db,
278
+ sessionKey,
279
+ resolved = {},
280
+ { mutateOnDrift = true } = {},
281
+ ) {
260
282
  if (!db) return { existingSessionId: null, drift: null };
261
283
  const row = db.getSession(sessionKey);
262
284
  if (!row || !row.claude_session_id) {
@@ -321,8 +343,10 @@ function resolveSessionForSpawn(db, sessionKey, resolved = {}) {
321
343
  return { existingSessionId: row.claude_session_id, drift: null };
322
344
  }
323
345
 
324
- // Drift: drop the stale row so the next spawn is fresh + correct.
325
- db.clearSessionId(sessionKey);
346
+ // Normal cold spawns delete stale rows. Runtime-switch preparation leaves
347
+ // them intact so only a successful target initialization can supersede the
348
+ // active provider-session record.
349
+ if (mutateOnDrift) db.clearSessionId(sessionKey);
326
350
  return {
327
351
  existingSessionId: null,
328
352
  drift: {
@@ -1,11 +1,10 @@
1
1
  /**
2
- * Inline-keyboard callback handler for the /model and /effort cards.
2
+ * Inline-keyboard callback handler for the /config, /model, and /effort cards.
3
3
  *
4
4
  * When a user taps a button on the config card, this routes:
5
5
  * 1. validate the new value;
6
- * 2. mutate chatConfig in-place + persist via db.logConfigChange;
7
- * 3. apply the change live to Claude via its legacy methods, or select one
8
- * complete Codex pair for the next turn via pm.selectModelSettings;
6
+ * 2. mutate and persist the scoped chat configuration;
7
+ * 3. apply a setting live or strictly replace an idle selected runtime;
9
8
  * 4. re-render the card with the new ✓ marker;
10
9
  * 5. acknowledge the button press with a context-aware toast.
11
10
  *
@@ -19,18 +18,54 @@
19
18
  const { toTelegramHtml } = require('../telegram/format');
20
19
  const { resolveRichTextEnabled } = require('../telegram/rich');
21
20
  const { getTopicConfig, getConfigWriteScope } = require('../session-key');
21
+ const { resolveRuntimeDescriptor } = require('../runtime-config');
22
22
  const {
23
23
  configuredRuntimeValue,
24
24
  formatCodexSettingsOutcome,
25
25
  getCodexCatalogEfforts,
26
26
  getCodexCatalogModels,
27
27
  isCodexRuntimeView,
28
+ RUNTIME_OPTIONS,
28
29
  resolveCodexEffortForModel,
29
30
  withCodexSettingsOutcome,
30
31
  } = require('./config-ui');
31
32
 
32
33
  const MODEL_OPTIONS = ['opus', 'sonnet', 'haiku'];
33
34
  const EFFORT_OPTIONS = ['low', 'medium', 'high', 'xhigh', 'max'];
35
+ const RUNTIME_OPTION_BY_BACKEND = new Map(
36
+ RUNTIME_OPTIONS.map((option) => [option.backend, option]),
37
+ );
38
+ const BLOCKED_RUNTIME_STATES = new Set([
39
+ 'RecoveryConflict',
40
+ 'ContainmentFailed',
41
+ 'FailedAmbiguous',
42
+ 'DurabilityBlocked',
43
+ 'StartingTurn',
44
+ 'Active',
45
+ 'Settling',
46
+ 'BackgroundWorking',
47
+ 'BackgroundSettling',
48
+ 'Quiescing',
49
+ ]);
50
+
51
+ function runtimeLabel(runtime) {
52
+ return RUNTIME_OPTION_BY_BACKEND.get(runtime)?.label ?? 'Claude SDK';
53
+ }
54
+
55
+ function runtimeSwitchBlocked(proc) {
56
+ if (!proc || proc.closed) return false;
57
+ try {
58
+ return Boolean(
59
+ proc.inFlight
60
+ || proc.hasActiveBackgroundWork?.()
61
+ || proc.hasOpenQuestions?.()
62
+ || proc.hasPendingDeliveryWork?.()
63
+ || BLOCKED_RUNTIME_STATES.has(proc.state),
64
+ );
65
+ } catch {
66
+ return true;
67
+ }
68
+ }
34
69
 
35
70
  function createHandleConfigCallback({
36
71
  config,
@@ -41,6 +76,9 @@ function createHandleConfigCallback({
41
76
  formatConfigInfoText,
42
77
  buildConfigKeyboard,
43
78
  resolveRuntimeView = null,
79
+ prepareRuntimeSelection = null,
80
+ discardRuntimeSelection = null,
81
+ buildSpawnContext = null,
44
82
  intentLock,
45
83
  saveConfig = () => {},
46
84
  botName,
@@ -49,7 +87,9 @@ function createHandleConfigCallback({
49
87
 
50
88
  return async function handleConfigCallback(ctx) {
51
89
  const data = ctx.callbackQuery?.data || '';
52
- const m = String(data).match(/^cfg:(model|effort|richtext):(\S+)$/);
90
+ const m = String(data).match(
91
+ /^cfg:(model|effort|richtext|runtime):(\S+)$/,
92
+ );
53
93
  if (!m) return;
54
94
  const setting = m[1];
55
95
  const value = m[2];
@@ -83,7 +123,313 @@ function createHandleConfigCallback({
83
123
  releaseIntent();
84
124
  };
85
125
  let runtimeView = null;
126
+ let candidatePrepared = false;
127
+ let runtimeSwitchCompleted = false;
86
128
  try {
129
+ if (setting === 'runtime') {
130
+ if (!RUNTIME_OPTION_BY_BACKEND.has(value)) {
131
+ releaseConfigIntent();
132
+ await ctx.answerCallbackQuery({ text: 'Invalid runtime' })
133
+ .catch(() => {});
134
+ return;
135
+ }
136
+ const currentSelection = resolveRuntimeDescriptor({
137
+ config,
138
+ chatId,
139
+ threadId: callbackThreadIdEarly,
140
+ defaultPm: 'sdk',
141
+ logger,
142
+ });
143
+ if (currentSelection.backend === value) {
144
+ releaseConfigIntent();
145
+ await ctx.answerCallbackQuery({
146
+ text: `Already ${runtimeLabel(value)}`,
147
+ }).catch(() => {});
148
+ return;
149
+ }
150
+
151
+ const currentProcess = typeof pm.get === 'function'
152
+ ? pm.get(callbackSessionKey)
153
+ : null;
154
+ if (runtimeSwitchBlocked(currentProcess)) {
155
+ releaseConfigIntent();
156
+ await ctx.answerCallbackQuery({
157
+ text: 'Wait for the current turn to finish before switching runtime',
158
+ show_alert: true,
159
+ }).catch(() => {});
160
+ return;
161
+ }
162
+
163
+ let candidateView = null;
164
+ if (value === 'codex') {
165
+ if (
166
+ typeof prepareRuntimeSelection !== 'function'
167
+ || typeof discardRuntimeSelection !== 'function'
168
+ ) {
169
+ releaseConfigIntent();
170
+ await ctx.answerCallbackQuery({
171
+ text: 'Codex is unavailable: runtime preflight is not configured',
172
+ show_alert: true,
173
+ }).catch(() => {});
174
+ return;
175
+ }
176
+ try {
177
+ candidateView = await prepareRuntimeSelection({
178
+ sessionKey: callbackSessionKey,
179
+ chatId,
180
+ threadId: callbackThreadIdEarly,
181
+ runtime: 'codex',
182
+ });
183
+ candidatePrepared = true;
184
+ } catch (error) {
185
+ logger.error?.(
186
+ `[${botName}] Codex runtime selection preflight failed: `
187
+ + `${error?.code || error?.name || 'unknown'}`,
188
+ );
189
+ releaseConfigIntent();
190
+ await ctx.answerCallbackQuery({
191
+ text: 'Codex is unavailable; check login and runtime diagnostics',
192
+ show_alert: true,
193
+ }).catch(() => {});
194
+ return;
195
+ }
196
+ }
197
+
198
+ const topicId = callbackThreadIdEarly == null
199
+ ? null
200
+ : String(callbackThreadIdEarly);
201
+ const originalTopicsPresent = Object.hasOwn(
202
+ chatConfig,
203
+ 'topics',
204
+ );
205
+ const originalTopics = chatConfig.topics;
206
+ const originalTopicPresent = Boolean(
207
+ topicId
208
+ && chatConfig.topics
209
+ && Object.hasOwn(chatConfig.topics, topicId)
210
+ );
211
+ const originalTopic = originalTopicPresent
212
+ ? chatConfig.topics[topicId]
213
+ : undefined;
214
+ const { scope: writeScope, threadId: writeThreadId } =
215
+ getConfigWriteScope(chatConfig, callbackThreadIdEarly);
216
+ const pmSnapshot = {
217
+ present: Object.hasOwn(writeScope, 'pm'),
218
+ value: writeScope.pm,
219
+ };
220
+ const restoreSelection = () => {
221
+ if (
222
+ writeThreadId
223
+ && originalTopicsPresent
224
+ && chatConfig.topics !== originalTopics
225
+ ) {
226
+ chatConfig.topics = originalTopics;
227
+ return;
228
+ }
229
+ if (
230
+ writeThreadId
231
+ && (
232
+ typeof originalTopic === 'string'
233
+ || !originalTopicPresent
234
+ )
235
+ ) {
236
+ if (originalTopicPresent) {
237
+ chatConfig.topics[writeThreadId] = originalTopic;
238
+ } else {
239
+ delete chatConfig.topics[writeThreadId];
240
+ }
241
+ if (!originalTopicsPresent) delete chatConfig.topics;
242
+ return;
243
+ }
244
+ if (pmSnapshot.present) writeScope.pm = pmSnapshot.value;
245
+ else delete writeScope.pm;
246
+ };
247
+
248
+ writeScope.pm = value;
249
+ try {
250
+ await saveConfig();
251
+ } catch (error) {
252
+ restoreSelection();
253
+ logger.error?.(
254
+ `[${botName}] runtime selection save failed: ${error.message}`,
255
+ );
256
+ releaseConfigIntent();
257
+ await ctx.answerCallbackQuery({
258
+ text: 'Could not save runtime; nothing changed',
259
+ show_alert: true,
260
+ }).catch(() => {});
261
+ return;
262
+ }
263
+
264
+ const cmdUserId = ctx.callbackQuery.from?.id || null;
265
+ const cmdUser = ctx.callbackQuery.from?.first_name
266
+ || ctx.callbackQuery.from?.username
267
+ || null;
268
+ const auditRow = {
269
+ chat_id: chatId,
270
+ thread_id: writeThreadId,
271
+ field: 'pm',
272
+ old_value: currentSelection.configuredPm,
273
+ new_value: value,
274
+ user: cmdUser,
275
+ user_id: cmdUserId,
276
+ source: 'inline-button',
277
+ };
278
+ try {
279
+ db.logConfigChange(auditRow);
280
+ } catch (error) {
281
+ restoreSelection();
282
+ let rollbackFailed = false;
283
+ try {
284
+ await saveConfig();
285
+ } catch (rollbackError) {
286
+ rollbackFailed = true;
287
+ logger.error?.(
288
+ `[${botName}] runtime audit rollback failed: `
289
+ + rollbackError.message,
290
+ );
291
+ }
292
+ logger.error?.(
293
+ `[${botName}] runtime selection audit failed: ${error.message}`,
294
+ );
295
+ releaseConfigIntent();
296
+ await ctx.answerCallbackQuery({
297
+ text: rollbackFailed
298
+ ? 'Could not audit runtime; persisted config needs attention'
299
+ : 'Could not audit runtime; nothing changed',
300
+ show_alert: true,
301
+ }).catch(() => {});
302
+ return;
303
+ }
304
+
305
+ let replacementError = null;
306
+ try {
307
+ if (typeof buildSpawnContext !== 'function') {
308
+ const error = new Error('runtime spawn-context builder unavailable');
309
+ error.code = 'RUNTIME_SWITCH_UNAVAILABLE';
310
+ throw error;
311
+ }
312
+ const spawnContext = await buildSpawnContext(
313
+ callbackSessionKey,
314
+ { mutateSessionOnDrift: false },
315
+ );
316
+ await pm.replaceRuntime(callbackSessionKey, spawnContext);
317
+ } catch (error) {
318
+ replacementError = error;
319
+ }
320
+ if (replacementError) {
321
+ restoreSelection();
322
+ let rollbackFailed = false;
323
+ let rollbackAuditFailed = false;
324
+ try {
325
+ await saveConfig();
326
+ } catch (rollbackError) {
327
+ rollbackFailed = true;
328
+ logger.error?.(
329
+ `[${botName}] runtime replacement rollback failed: `
330
+ + rollbackError.message,
331
+ );
332
+ }
333
+ if (!rollbackFailed) {
334
+ try {
335
+ db.logConfigChange({
336
+ ...auditRow,
337
+ old_value: value,
338
+ new_value: currentSelection.configuredPm,
339
+ source: 'runtime-switch-rollback',
340
+ });
341
+ } catch (auditError) {
342
+ rollbackAuditFailed = true;
343
+ logger.error?.(
344
+ `[${botName}] runtime rollback audit failed: `
345
+ + auditError.message,
346
+ );
347
+ }
348
+ }
349
+ logger.error?.(
350
+ `[${botName}] runtime replacement failed: `
351
+ + `${replacementError.code || replacementError.name || 'unknown'}`,
352
+ );
353
+ releaseConfigIntent();
354
+ await ctx.answerCallbackQuery({
355
+ text: rollbackFailed
356
+ ? 'Runtime switch failed; persisted config needs attention'
357
+ : rollbackAuditFailed
358
+ ? 'Previous runtime restored; audit history needs attention'
359
+ : 'Previous runtime selection restored; session may reconnect '
360
+ + 'on the next message',
361
+ show_alert: true,
362
+ }).catch(() => {});
363
+ return;
364
+ }
365
+
366
+ if (
367
+ value !== 'codex'
368
+ && typeof discardRuntimeSelection === 'function'
369
+ ) {
370
+ try {
371
+ discardRuntimeSelection(callbackSessionKey);
372
+ } catch (error) {
373
+ logger.error?.(
374
+ `[${botName}] retired Codex runtime receipt cleanup failed: `
375
+ + `${error?.code || error?.name || 'unknown'}`,
376
+ );
377
+ }
378
+ }
379
+ runtimeSwitchCompleted = true;
380
+ releaseConfigIntent();
381
+ runtimeView = value === 'codex'
382
+ ? candidateView
383
+ : { runtime: 'claude', backend: value };
384
+ if (runtimeView) {
385
+ runtimeView = {
386
+ ...runtimeView,
387
+ backend: value,
388
+ configuredPm: value,
389
+ selectionSource: writeThreadId ? 'topic' : 'chat',
390
+ };
391
+ }
392
+ const topicConfig = getTopicConfig(
393
+ chatConfig,
394
+ callbackThreadIdEarly,
395
+ );
396
+ const effectiveRichText = resolveRichTextEnabled(
397
+ config,
398
+ chatId,
399
+ callbackThreadIdEarly,
400
+ );
401
+ try {
402
+ const newInfo = await formatConfigInfoText(
403
+ chatConfig,
404
+ 'all',
405
+ callbackSessionKey,
406
+ topicConfig,
407
+ effectiveRichText,
408
+ runtimeView,
409
+ );
410
+ const newKeyboard = buildConfigKeyboard(
411
+ chatConfig,
412
+ 'all',
413
+ topicConfig,
414
+ effectiveRichText,
415
+ runtimeView,
416
+ );
417
+ const { text: html, parseMode } = toTelegramHtml(newInfo);
418
+ await ctx.editMessageText(html, {
419
+ reply_markup: newKeyboard,
420
+ ...(parseMode && { parse_mode: parseMode }),
421
+ });
422
+ } catch (error) {
423
+ logger.error?.(
424
+ `[${botName}] runtime config-card edit failed: ${error.message}`,
425
+ );
426
+ }
427
+ await ctx.answerCallbackQuery({
428
+ text: `Runtime → ${runtimeLabel(value)}`,
429
+ }).catch(() => {});
430
+ return;
431
+ }
432
+
87
433
  if (typeof resolveRuntimeView === 'function') {
88
434
  try {
89
435
  runtimeView = await resolveRuntimeView({
@@ -386,6 +732,16 @@ function createHandleConfigCallback({
386
732
  );
387
733
  await ctx.answerCallbackQuery({ text: ackText }).catch(() => {});
388
734
  } finally {
735
+ if (candidatePrepared && !runtimeSwitchCompleted) {
736
+ try {
737
+ discardRuntimeSelection(callbackSessionKey);
738
+ } catch (error) {
739
+ logger.error?.(
740
+ `[${botName}] Codex candidate discard failed: `
741
+ + `${error?.code || error?.name || 'unknown'}`,
742
+ );
743
+ }
744
+ }
389
745
  releaseConfigIntent();
390
746
  }
391
747
  };
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Config card UI builders — inline keyboard + descriptive body
3
3
  * shown above it. Used by polygram's /config slash command and
4
- * the /model + /effort callback re-render path
4
+ * the runtime/model/effort callback re-render paths
5
5
  * (lib/handlers/config-callback.js).
6
6
  *
7
7
  * Pure functions (no DB / fs) but `formatConfigInfoText` needs
@@ -18,11 +18,48 @@
18
18
 
19
19
  const MODEL_OPTIONS = ['opus', 'sonnet', 'haiku'];
20
20
  const EFFORT_OPTIONS = ['low', 'medium', 'high', 'xhigh', 'max'];
21
+ const RUNTIME_OPTIONS = Object.freeze([
22
+ Object.freeze({ backend: 'sdk', label: 'Claude SDK' }),
23
+ Object.freeze({ backend: 'cli', label: 'Claude CLI' }),
24
+ Object.freeze({ backend: 'codex', label: 'Codex' }),
25
+ ]);
21
26
 
22
27
  function isCodexRuntimeView(runtimeView) {
23
28
  return runtimeView?.runtime === 'codex';
24
29
  }
25
30
 
31
+ function canonicalRuntimeBackend(runtimeView) {
32
+ const backend = runtimeView?.backend;
33
+ if (backend === 'sdk' || backend === 'cli' || backend === 'codex') {
34
+ return backend;
35
+ }
36
+ if (backend === 'tmux' || backend === 'channels') return 'cli';
37
+ if (
38
+ runtimeView?.runtime === 'codex'
39
+ || runtimeView?.runtime === 'cli'
40
+ || runtimeView?.runtime === 'sdk'
41
+ ) {
42
+ return runtimeView.runtime;
43
+ }
44
+ return 'sdk';
45
+ }
46
+
47
+ function runtimeSelectionSource(runtimeView) {
48
+ const source = runtimeView?.selectionSource
49
+ ?? runtimeView?.source
50
+ ?? runtimeView?.sources?.pm;
51
+ return typeof source === 'string' && source.length > 0 ? source : null;
52
+ }
53
+
54
+ function formatRuntimeLine(runtimeView) {
55
+ const backend = canonicalRuntimeBackend(runtimeView);
56
+ const label = backend === 'codex'
57
+ ? 'Codex app-server'
58
+ : backend === 'cli' ? 'Claude CLI' : 'Claude SDK';
59
+ const source = runtimeSelectionSource(runtimeView);
60
+ return `Runtime: ${label}${source ? ` (source: ${source})` : ''}`;
61
+ }
62
+
26
63
  function uniqueStrings(values) {
27
64
  if (!Array.isArray(values)) return [];
28
65
  return [...new Set(values.filter(
@@ -226,7 +263,14 @@ function buildConfigKeyboard(
226
263
  ? getCodexCatalogEfforts(runtimeView, model)
227
264
  : EFFORT_OPTIONS;
228
265
  const rows = [];
229
- if (show === 'model' || show === 'all') {
266
+ if (show === 'all') {
267
+ const currentBackend = canonicalRuntimeBackend(runtimeView);
268
+ rows.push(RUNTIME_OPTIONS.map(({ backend, label }) => ({
269
+ text: backend === currentBackend ? `✓ ${label}` : label,
270
+ callback_data: `cfg:runtime:${backend}`,
271
+ })));
272
+ }
273
+ if ((show === 'model' || show === 'all') && modelOptions.length > 0) {
230
274
  rows.push(modelOptions.map((entry) => {
231
275
  const label = (
232
276
  typeof entry.displayName === 'string'
@@ -238,7 +282,7 @@ function buildConfigKeyboard(
238
282
  };
239
283
  }));
240
284
  }
241
- if (show === 'effort' || show === 'all') {
285
+ if ((show === 'effort' || show === 'all') && effortOptions.length > 0) {
242
286
  rows.push(effortOptions.map((e) => ({
243
287
  text: e === effort ? `✓ ${e}` : e,
244
288
  callback_data: `cfg:effort:${e}`,
@@ -300,9 +344,13 @@ function createFormatConfigInfoText({
300
344
  runtimeView,
301
345
  'effort',
302
346
  );
347
+ const codexModels = codex ? getCodexCatalogModels(runtimeView) : [];
348
+ const codexEfforts = codex
349
+ ? getCodexCatalogEfforts(runtimeView, model)
350
+ : [];
303
351
  const agent = (topicConfig && topicConfig.agent) || chatConfig.agent;
304
352
  const codexModelEntry = codex
305
- ? getCodexCatalogModels(runtimeView)
353
+ ? codexModels
306
354
  .find((entry) => entry.model === model)
307
355
  : null;
308
356
  const codexDisplayName = codexModelEntry?.displayName;
@@ -340,13 +388,12 @@ function createFormatConfigInfoText({
340
388
  const richTextLine = richText
341
389
  ? 'Rich text: on (headings/tables/checklists on qualifying replies; agent authors for it once this session next (re)spawns)'
342
390
  : 'Rich text: off';
343
- const identityLine = codex
344
- ? 'Runtime: Codex app-server'
345
- : `Agent: ${agent}`;
391
+ const runtimeLine = formatRuntimeLine(runtimeView);
346
392
  let head;
347
393
  if (codex) {
348
394
  const desired = runtimeView.desiredSettings ?? { model, effort };
349
- const desiredPair = formatSettingsPair(desired) ?? `${model}/${effort}`;
395
+ const desiredPair = formatSettingsPair(desired)
396
+ ?? 'incomplete Codex selection';
350
397
  const activePair = formatSettingsPair(runtimeView.activeTurnSettings);
351
398
  const nextTurn = runtimeView.nextTurnSettings;
352
399
  const nextTurnPair = formatSettingsPair(nextTurn);
@@ -403,7 +450,7 @@ function createFormatConfigInfoText({
403
450
  head = [
404
451
  ...settingsLines,
405
452
  richTextLine,
406
- identityLine,
453
+ runtimeLine,
407
454
  processLine,
408
455
  `Session: ${sess}`,
409
456
  ].join('\n');
@@ -412,16 +459,17 @@ function createFormatConfigInfoText({
412
459
  `${modelLine}\n` +
413
460
  `${effortLine}\n` +
414
461
  `${richTextLine}\n` +
415
- `${identityLine}\n` +
462
+ `${runtimeLine}\n` +
463
+ `Agent: ${agent}\n` +
416
464
  `Process: ${alive ? 'warm' : 'cold'}\n` +
417
465
  `Session: ${sess}`;
418
466
  }
419
467
 
420
468
  const modelHelp = codex
421
- ? [
469
+ ? codexModels.length > 0 ? [
422
470
  '',
423
471
  '**Models**',
424
- ...getCodexCatalogModels(runtimeView).map((entry) => {
472
+ ...codexModels.map((entry) => {
425
473
  const displayName = (
426
474
  typeof entry.displayName === 'string'
427
475
  && entry.displayName.length > 0
@@ -429,6 +477,10 @@ function createFormatConfigInfoText({
429
477
  ) ? ` — ${entry.displayName}` : '';
430
478
  return `• **${entry.model}**${displayName}`;
431
479
  }),
480
+ ].join('\n') : [
481
+ '',
482
+ '**Models**',
483
+ 'Models are unavailable until Codex preflight succeeds.',
432
484
  ].join('\n')
433
485
  : [
434
486
  '',
@@ -439,12 +491,15 @@ function createFormatConfigInfoText({
439
491
  ].join('\n');
440
492
 
441
493
  const effortHelp = codex
442
- ? [
494
+ ? codexEfforts.length > 0 ? [
443
495
  '',
444
496
  `**Effort** — authenticated options for ${model}:`,
445
- ...getCodexCatalogEfforts(runtimeView, model)
446
- .map((value) => `• **${value}**`),
497
+ ...codexEfforts.map((value) => `• **${value}**`),
447
498
  'Model and effort changes apply to the next turn; an active turn is unchanged.',
499
+ ].join('\n') : [
500
+ '',
501
+ '**Effort**',
502
+ 'Effort options are unavailable until Codex preflight succeeds.',
448
503
  ].join('\n')
449
504
  : [
450
505
  '',
@@ -459,7 +514,9 @@ function createFormatConfigInfoText({
459
514
  if (codex) {
460
515
  body += '\n\nNative Codex beta: command network and web search are disabled. '
461
516
  + 'Product MCP tools and interactive approvals are unavailable. '
462
- + 'Detached/background servers are unsupported and may survive hard runtime loss.';
517
+ + 'Detached/background servers are unsupported and may survive hard runtime loss. '
518
+ + 'Native goals are disabled for Polygram-managed Codex sessions until '
519
+ + 'native goal support is implemented.';
463
520
  }
464
521
  if (show === 'model' || show === 'all') body += '\n' + modelHelp;
465
522
  if (show === 'effort' || show === 'all') body += '\n' + effortHelp;
@@ -509,6 +566,7 @@ function createFormatConfigInfoText({
509
566
  module.exports = {
510
567
  buildConfigKeyboard,
511
568
  createFormatConfigInfoText,
569
+ RUNTIME_OPTIONS,
512
570
  MODEL_OPTIONS,
513
571
  EFFORT_OPTIONS,
514
572
  MODEL_VERSIONS_DESC,
@@ -59,6 +59,18 @@ const DEFAULT_CODEX_AVAILABILITY = Object.freeze({
59
59
  const MAX_CONFIG_VALUE_LENGTH = 4096;
60
60
  const assertedReceiptByAvailability = new WeakMap();
61
61
 
62
+ function processMatchesRuntime(proc, runtime, backend) {
63
+ if (!proc || proc.closed) return false;
64
+ const processRuntime = (
65
+ proc.runtime === 'codex'
66
+ || proc.backend === 'codex'
67
+ ) ? 'codex' : 'claude';
68
+ if (processRuntime !== runtime) return false;
69
+ return runtime === 'codex'
70
+ ? backend === 'codex'
71
+ : proc.backend === backend;
72
+ }
73
+
62
74
  class RuntimeConfigError extends Error {
63
75
  constructor(message, {
64
76
  code,
@@ -343,17 +355,16 @@ function resolveRuntimeConfig({
343
355
  }
344
356
 
345
357
  /**
346
- * Resolve only the operator-selected Codex inputs needed to run the matching
347
- * preflight. This does not make Codex available and carries no receipt.
358
+ * Resolve the prospective Codex inputs for one chat/topic without consulting
359
+ * its currently selected runtime. This supports preflight before an atomic
360
+ * runtime switch; it does not make Codex available and carries no receipt.
348
361
  */
349
- function resolveCodexRuntimeRequest({
362
+ function resolveCodexRuntimeCandidate({
350
363
  config = {},
351
364
  chatId = null,
352
365
  threadId = null,
353
- defaultPm = 'sdk',
354
366
  } = {}) {
355
- const pmChoice = resolvePmChoice(config, chatId, threadId, defaultPm);
356
- if (!chatId || pmChoice.value !== 'codex') return null;
367
+ if (!chatId) return null;
357
368
 
358
369
  const scopes = configScopes(config, chatId, threadId);
359
370
  const modelChoice = resolveScopedValue(
@@ -368,7 +379,6 @@ function resolveCodexRuntimeRequest({
368
379
  );
369
380
  const cwdChoice = resolveScopedValue(scopes.codexSpawn, 'cwd', null);
370
381
  const sources = Object.freeze({
371
- pm: pmChoice.source,
372
382
  model: modelChoice.source,
373
383
  effort: effortChoice.source,
374
384
  cwd: cwdChoice.source,
@@ -398,6 +408,33 @@ function resolveCodexRuntimeRequest({
398
408
  });
399
409
  }
400
410
 
411
+ /**
412
+ * Resolve only the operator-selected Codex inputs needed to run the matching
413
+ * preflight. This does not make Codex available and carries no receipt.
414
+ */
415
+ function resolveCodexRuntimeRequest({
416
+ config = {},
417
+ chatId = null,
418
+ threadId = null,
419
+ defaultPm = 'sdk',
420
+ } = {}) {
421
+ const pmChoice = resolvePmChoice(config, chatId, threadId, defaultPm);
422
+ if (!chatId || pmChoice.value !== 'codex') return null;
423
+
424
+ const candidate = resolveCodexRuntimeCandidate({
425
+ config,
426
+ chatId,
427
+ threadId,
428
+ });
429
+ return Object.freeze({
430
+ ...candidate,
431
+ sources: Object.freeze({
432
+ pm: pmChoice.source,
433
+ ...candidate.sources,
434
+ }),
435
+ });
436
+ }
437
+
401
438
  function configScopes(config, chatId, threadId) {
402
439
  const hasChat = Boolean(chatId);
403
440
  const chat = hasChat ? config?.chats?.[chatId] : null;
@@ -598,7 +635,9 @@ function stableRuntimeConfigIdentity(fields) {
598
635
 
599
636
  module.exports = {
600
637
  createCodexRuntimeAvailability,
638
+ processMatchesRuntime,
601
639
  RuntimeConfigError,
640
+ resolveCodexRuntimeCandidate,
602
641
  resolveCodexRuntimeRequest,
603
642
  resolveRuntimeConfig,
604
643
  resolveRuntimeDescriptor,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "polygram",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
4
4
  "description": "Telegram daemon for Claude Code that preserves the OpenClaw per-chat session model. Migration path for OpenClaw users moving to Claude Code.",
5
5
  "main": "lib/ipc/client.js",
6
6
  "bin": {
package/polygram.js CHANGED
@@ -72,6 +72,11 @@ const {
72
72
  const {
73
73
  buildCodexSpawnContext,
74
74
  } = require('./lib/codex/spawn-context');
75
+ const {
76
+ processMatchesRuntime,
77
+ resolveCodexRuntimeCandidate,
78
+ resolveRuntimeDescriptor,
79
+ } = require('./lib/runtime-config');
75
80
  const {
76
81
  scheduleCodexRetention,
77
82
  } = require('./lib/codex/retention-scheduler');
@@ -599,58 +604,157 @@ async function clearAutosteeredReactions(sessionKey) {
599
604
  let buildSdkOptions = null;
600
605
  let codexRuntimeController = null;
601
606
 
607
+ function buildUnavailableCodexRuntimeView({
608
+ runtimeSelection,
609
+ chatId,
610
+ threadId,
611
+ error,
612
+ runtimeView = null,
613
+ }) {
614
+ let candidate = null;
615
+ try {
616
+ candidate = resolveCodexRuntimeCandidate({
617
+ config,
618
+ chatId,
619
+ threadId,
620
+ });
621
+ } catch {
622
+ // The runtime button must remain available even when the saved Codex
623
+ // model, effort, or cwd is incomplete.
624
+ }
625
+ const model = runtimeView?.model ?? candidate?.model ?? null;
626
+ const effort = runtimeView?.effort ?? candidate?.effort ?? null;
627
+ const desiredSettings = (
628
+ typeof model === 'string'
629
+ && typeof effort === 'string'
630
+ ) ? Object.freeze({ model, effort }) : null;
631
+ return Object.freeze({
632
+ ...runtimeView,
633
+ runtime: 'codex',
634
+ backend: runtimeSelection.backend,
635
+ configuredPm: runtimeSelection.configuredPm,
636
+ selectionSource: runtimeSelection.source,
637
+ model,
638
+ effort,
639
+ models: runtimeView?.models ?? Object.freeze([]),
640
+ efforts: runtimeView?.efforts ?? Object.freeze([]),
641
+ desiredSettings: runtimeView?.desiredSettings ?? desiredSettings,
642
+ nextTurnSettings: runtimeView?.nextTurnSettings ?? null,
643
+ observedThreadSettings: runtimeView?.observedThreadSettings ?? null,
644
+ activeTurnSettings: runtimeView?.activeTurnSettings ?? null,
645
+ processStatus: 'unavailable',
646
+ unavailableReason:
647
+ error?.code || error?.name || 'CODEX_RUNTIME_UNAVAILABLE',
648
+ });
649
+ }
650
+
602
651
  async function resolveSessionRuntimeView({
603
652
  sessionKey,
604
653
  chatId,
605
654
  threadId = null,
606
655
  } = {}) {
607
- if (codexRuntimeController) {
608
- const runtimeView = await codexRuntimeController.resolveRuntimeView({
656
+ const runtimeSelection = resolveRuntimeDescriptor({
657
+ config,
658
+ chatId,
659
+ threadId,
660
+ defaultPm: 'sdk',
661
+ logger: console,
662
+ });
663
+ const runtimeMetadata = {
664
+ runtime: runtimeSelection.runtime,
665
+ backend: runtimeSelection.backend,
666
+ configuredPm: runtimeSelection.configuredPm,
667
+ selectionSource: runtimeSelection.source,
668
+ };
669
+ if (runtimeSelection.runtime !== 'codex') {
670
+ return Object.freeze(runtimeMetadata);
671
+ }
672
+ if (!codexRuntimeController) {
673
+ return buildUnavailableCodexRuntimeView({
674
+ runtimeSelection,
675
+ chatId,
676
+ threadId,
677
+ error: { code: 'CODEX_RUNTIME_UNAVAILABLE' },
678
+ });
679
+ }
680
+
681
+ let runtimeView;
682
+ try {
683
+ runtimeView = await codexRuntimeController.resolveRuntimeView({
609
684
  sessionKey,
610
685
  chatId,
611
686
  threadId,
612
687
  });
613
- if (!isCodexRuntimeView(runtimeView)) return runtimeView;
614
- if (typeof pm?.getModelSettingsStatus !== 'function') {
615
- const error = new Error('Codex model-settings status is unavailable');
616
- error.code = 'CODEX_RUNTIME_UNAVAILABLE';
617
- throw error;
618
- }
619
- const settingsStatus = await pm.getModelSettingsStatus(sessionKey);
620
- const processStatus = settingsStatus.outcome;
621
- const unavailableReason = settingsStatus.reason ?? null;
622
- const copySettings = (settings) => (
623
- settings
624
- && typeof settings.model === 'string'
625
- && typeof settings.effort === 'string'
626
- ? Object.freeze({
627
- model: settings.model,
628
- effort: settings.effort,
629
- })
630
- : null
631
- );
632
- return Object.freeze({
633
- ...runtimeView,
634
- desiredSettings: Object.freeze({
635
- model: runtimeView.model,
636
- effort: runtimeView.effort,
637
- }),
638
- nextTurnSettings: copySettings(settingsStatus.nextTurn),
639
- observedThreadSettings: copySettings(settingsStatus.observedThread),
640
- activeTurnSettings: copySettings(settingsStatus.currentTurn),
641
- processStatus,
642
- unavailableReason,
688
+ } catch (error) {
689
+ return buildUnavailableCodexRuntimeView({
690
+ runtimeSelection,
691
+ chatId,
692
+ threadId,
693
+ error,
643
694
  });
644
695
  }
645
- if (resolvePromptBackend({ config, chatId, threadId }) === 'codex') {
646
- const error = new Error('Codex runtime controller is not initialized');
647
- error.code = 'CODEX_RUNTIME_UNAVAILABLE';
648
- throw error;
696
+ if (!isCodexRuntimeView(runtimeView)) {
697
+ return buildUnavailableCodexRuntimeView({
698
+ runtimeSelection,
699
+ chatId,
700
+ threadId,
701
+ error: { code: 'CODEX_RUNTIME_VIEW_MISMATCH' },
702
+ runtimeView,
703
+ });
649
704
  }
650
- return Object.freeze({ runtime: 'claude' });
705
+ runtimeView = Object.freeze({
706
+ ...runtimeView,
707
+ ...runtimeMetadata,
708
+ });
709
+ if (typeof pm?.getModelSettingsStatus !== 'function') {
710
+ return buildUnavailableCodexRuntimeView({
711
+ runtimeSelection,
712
+ chatId,
713
+ threadId,
714
+ error: { code: 'CODEX_RUNTIME_UNAVAILABLE' },
715
+ runtimeView,
716
+ });
717
+ }
718
+ let settingsStatus;
719
+ try {
720
+ settingsStatus = await pm.getModelSettingsStatus(sessionKey);
721
+ } catch (error) {
722
+ return buildUnavailableCodexRuntimeView({
723
+ runtimeSelection,
724
+ chatId,
725
+ threadId,
726
+ error,
727
+ runtimeView,
728
+ });
729
+ }
730
+ const copySettings = (settings) => (
731
+ settings
732
+ && typeof settings.model === 'string'
733
+ && typeof settings.effort === 'string'
734
+ ? Object.freeze({
735
+ model: settings.model,
736
+ effort: settings.effort,
737
+ })
738
+ : null
739
+ );
740
+ return Object.freeze({
741
+ ...runtimeView,
742
+ desiredSettings: Object.freeze({
743
+ model: runtimeView.model,
744
+ effort: runtimeView.effort,
745
+ }),
746
+ nextTurnSettings: copySettings(settingsStatus.nextTurn),
747
+ observedThreadSettings: copySettings(settingsStatus.observedThread),
748
+ activeTurnSettings: copySettings(settingsStatus.currentTurn),
749
+ processStatus: settingsStatus.outcome,
750
+ unavailableReason: settingsStatus.reason ?? null,
751
+ });
651
752
  }
652
753
 
653
- async function buildSpawnContext(sessionKey) {
754
+ async function buildSpawnContext(
755
+ sessionKey,
756
+ { mutateSessionOnDrift = true } = {},
757
+ ) {
654
758
  const chatId = getChatIdFromKey(sessionKey);
655
759
  const chatConfig = config.chats[chatId];
656
760
  if (!chatConfig) return null;
@@ -677,6 +781,7 @@ async function buildSpawnContext(sessionKey) {
677
781
  runtimeController: codexRuntimeController,
678
782
  getSessionLabel,
679
783
  logEvent,
784
+ mutateSessionOnDrift,
680
785
  });
681
786
  }
682
787
 
@@ -684,24 +789,25 @@ async function buildSpawnContext(sessionKey) {
684
789
  // under. agent / cwd are spawn-identity — baked into the process at
685
790
  // spawn time, never mutable on a live session. Resolve them the
686
791
  // same way the backends do (topic override merged over chat-level)
687
- // and compare to the stored `sessions` row. On drift,
688
- // resolveSessionForSpawn drops the stale row and returns
689
- // existingSessionId:null → the spawn starts fresh under the correct
690
- // config instead of `--resume`-ing a stale one. This self-heals the
691
- // pre-per-topic-config rows (e.g. shumorobot's Music topic :3,
692
- // stored agent=shumabit / cwd=$HOME vs the current
693
- // music-curation:music-curator / .../Music/rekordbox).
792
+ // and compare to the stored `sessions` row. On a normal cold spawn,
793
+ // resolveSessionForSpawn drops a stale row and returns
794
+ // existingSessionId:null. Runtime-switch preparation can defer that
795
+ // deletion so a rejected replacement cannot erase the dormant session.
694
796
  // model/effort are NOT compared — they apply live via setModel /
695
- // applyFlagSettings with no respawn. pm_backend is also NOT
696
- // compared (rc.32): both backends spawn the same pinned claude
697
- // binary against the same on-disk JSONL, so a backend flip
698
- // preserves context. See lib/db/sessions.js for full reasoning.
797
+ // applyFlagSettings with no respawn. Compatible inline-wrapper backend
798
+ // changes preserve context; the CLI Channels boundary remains
799
+ // invalidating. See lib/db/sessions.js for the compatibility rules.
699
800
  //
700
801
  // The drift check runs only at COLD spawn (no warm process). A warm
701
802
  // process already runs under its spawn-time config; getOrSpawn
702
803
  // returns it without using this context, so dropping its row here
703
804
  // would be premature — defer to the next cold spawn.
704
- const isColdSpawn = !pm || !pm.has(sessionKey) || pm.get(sessionKey)?.closed;
805
+ const liveProcess = pm?.get(sessionKey) ?? null;
806
+ const isColdSpawn = !processMatchesRuntime(
807
+ liveProcess,
808
+ 'claude',
809
+ promptBackend,
810
+ );
705
811
  let existingSessionId;
706
812
  if (isColdSpawn) {
707
813
  const topicConfig = getTopicConfig(chatConfig, threadId || null);
@@ -710,7 +816,12 @@ async function buildSpawnContext(sessionKey) {
710
816
  cwd: topicConfig.cwd || chatConfig.cwd || null,
711
817
  backend: pickBackend({ config, chatId, threadId: threadId || null, pmDefault: 'sdk' }),
712
818
  };
713
- const r = resolveSessionForSpawn(db, sessionKey, resolved);
819
+ const r = resolveSessionForSpawn(
820
+ db,
821
+ sessionKey,
822
+ resolved,
823
+ { mutateOnDrift: mutateSessionOnDrift },
824
+ );
714
825
  existingSessionId = r.existingSessionId;
715
826
  if (r.drift) {
716
827
  logEvent('session-config-drift', {
@@ -3971,6 +4082,27 @@ async function main() {
3971
4082
  config, db, dbWrite, pm, intentLock, getSessionKey,
3972
4083
  formatConfigInfoText, buildConfigKeyboard, saveConfig,
3973
4084
  resolveRuntimeView: resolveSessionRuntimeView,
4085
+ prepareRuntimeSelection: ({
4086
+ sessionKey,
4087
+ chatId,
4088
+ threadId,
4089
+ runtime,
4090
+ }) => {
4091
+ if (runtime !== 'codex' || !codexRuntimeController) {
4092
+ const error = new Error('Codex runtime preflight is unavailable');
4093
+ error.code = 'CODEX_RUNTIME_UNAVAILABLE';
4094
+ throw error;
4095
+ }
4096
+ return codexRuntimeController.resolveCandidateRuntimeView({
4097
+ sessionKey,
4098
+ chatId,
4099
+ threadId,
4100
+ });
4101
+ },
4102
+ discardRuntimeSelection: (sessionKey) => (
4103
+ codexRuntimeController?.discardCandidateRuntime(sessionKey) ?? false
4104
+ ),
4105
+ buildSpawnContext,
3974
4106
  botName: BOT_NAME, logger: console,
3975
4107
  });
3976
4108
  handleCodexReconciliationCallback = createHandleCodexReconciliationCallback({