polygram 0.29.2 → 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,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,