cordisx 0.1.0-beta.44 → 0.1.0-beta.46

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 (72) hide show
  1. package/dist/assets/launcher/native-app-server-protocol.mjs +175 -41
  2. package/dist/assets/launcher/native-managed-resume.mjs +3 -2
  3. package/dist/assets/launcher/native-provider-errors.mjs +12 -0
  4. package/dist/assets/launcher/native-provider-transport.mjs +309 -0
  5. package/dist/assets/launcher/native-thread-switch.mjs +112 -0
  6. package/dist/codex-adapter/adapter.d.mts +1 -0
  7. package/dist/codex-adapter/adapter.mjs +86 -3
  8. package/dist/codex-adapter/index.d.ts +1 -0
  9. package/dist/codex-adapter/index.js +1 -0
  10. package/dist/codex-adapter/native-chunk-structure.d.ts +5 -0
  11. package/dist/codex-adapter/native-chunk-structure.js +72 -0
  12. package/dist/codex-adapter/native-submission-structure.js +25 -3
  13. package/dist/native/native-helper-artifact.json +1 -1
  14. package/dist/src/cli/production-host-bootstrap.d.ts.map +1 -1
  15. package/dist/src/cli/production-host-bootstrap.js +13 -6
  16. package/dist/src/cli/production-host-bootstrap.js.map +1 -1
  17. package/dist/src/launcher/builtin-skill.d.ts.map +1 -1
  18. package/dist/src/launcher/builtin-skill.js +6 -3
  19. package/dist/src/launcher/builtin-skill.js.map +1 -1
  20. package/dist/src/launcher/cdp.d.ts +1 -1
  21. package/dist/src/launcher/cdp.d.ts.map +1 -1
  22. package/dist/src/launcher/cdp.js +18 -2
  23. package/dist/src/launcher/cdp.js.map +1 -1
  24. package/dist/src/launcher/configured-encrypted-replay.d.ts.map +1 -1
  25. package/dist/src/launcher/configured-encrypted-replay.js +7 -1
  26. package/dist/src/launcher/configured-encrypted-replay.js.map +1 -1
  27. package/dist/src/launcher/native-agent-models.d.ts +1 -1
  28. package/dist/src/launcher/native-agent-models.d.ts.map +1 -1
  29. package/dist/src/launcher/native-agent-models.js +1 -1
  30. package/dist/src/launcher/native-agent-models.js.map +1 -1
  31. package/dist/src/launcher/native-app-resources.d.ts.map +1 -1
  32. package/dist/src/launcher/native-app-resources.js +8 -2
  33. package/dist/src/launcher/native-app-resources.js.map +1 -1
  34. package/dist/src/launcher/native-submission-cdp-channel.d.ts +1 -1
  35. package/dist/src/launcher/native-submission-cdp-channel.d.ts.map +1 -1
  36. package/dist/src/launcher/native-submission-cdp-channel.js +99 -6
  37. package/dist/src/launcher/native-submission-cdp-channel.js.map +1 -1
  38. package/dist/src/launcher/native-submission-control-server.d.ts.map +1 -1
  39. package/dist/src/launcher/native-submission-control-server.js +102 -6
  40. package/dist/src/launcher/native-submission-control-server.js.map +1 -1
  41. package/dist/src/launcher/native-submission-controller-contracts.d.ts +6 -3
  42. package/dist/src/launcher/native-submission-controller-contracts.d.ts.map +1 -1
  43. package/dist/src/launcher/native-submission-controller.d.ts.map +1 -1
  44. package/dist/src/launcher/native-submission-controller.js +23 -5
  45. package/dist/src/launcher/native-submission-controller.js.map +1 -1
  46. package/dist/src/launcher/native-thread-switch-error.d.ts +8 -0
  47. package/dist/src/launcher/native-thread-switch-error.d.ts.map +1 -0
  48. package/dist/src/launcher/native-thread-switch-error.js +12 -0
  49. package/dist/src/launcher/native-thread-switch-error.js.map +1 -0
  50. package/dist/src/renderer/adapter/native-model-provider-interaction.d.ts.map +1 -1
  51. package/dist/src/renderer/adapter/native-model-provider-interaction.js +3 -0
  52. package/dist/src/renderer/adapter/native-model-provider-interaction.js.map +1 -1
  53. package/dist/src/renderer/adapter/native-model-provider-seat.d.ts.map +1 -1
  54. package/dist/src/renderer/adapter/native-model-provider-seat.js +7 -2
  55. package/dist/src/renderer/adapter/native-model-provider-seat.js.map +1 -1
  56. package/dist/src/renderer/model-provider-copy.d.ts +4 -0
  57. package/dist/src/renderer/model-provider-copy.d.ts.map +1 -1
  58. package/dist/src/renderer/model-provider-copy.js +18 -0
  59. package/dist/src/renderer/model-provider-copy.js.map +1 -1
  60. package/dist/src/renderer/model-provider-selector.d.ts.map +1 -1
  61. package/dist/src/renderer/model-provider-selector.js +6 -5
  62. package/dist/src/renderer/model-provider-selector.js.map +1 -1
  63. package/dist/src/renderer/native-model-provider-transport.js +1 -1
  64. package/dist/src/renderer/native-model-provider-transport.js.map +1 -1
  65. package/dist/src/renderer/native-provider-selection-client.d.ts +7 -1
  66. package/dist/src/renderer/native-provider-selection-client.d.ts.map +1 -1
  67. package/dist/src/renderer/native-provider-selection-client.js +61 -6
  68. package/dist/src/renderer/native-provider-selection-client.js.map +1 -1
  69. package/dist/src/renderer/native-provider-submission-policy.d.ts +1 -0
  70. package/dist/src/renderer/native-provider-submission-policy.d.ts.map +1 -1
  71. package/dist/src/renderer/native-provider-submission-policy.js.map +1 -1
  72. package/package.json +1 -1
@@ -6,12 +6,31 @@ import { NativeTurnDiagnostics } from './native-turn-diagnostics.mjs'
6
6
  import { NativeRequestTracker } from './native-request-tracker.mjs'
7
7
  import { prepareManagedResume } from './native-managed-resume.mjs'
8
8
  import { nativeInput } from './native-app-server-input.mjs'
9
+ import { createNativeProviderTransport } from './native-provider-transport.mjs'
10
+ import { nativeProviderFailure } from './native-provider-errors.mjs'
11
+ import { switchNativeThread } from './native-thread-switch.mjs'
9
12
 
10
13
  const socketPath = process.env.CORDISX_NATIVE_CONTROL_SOCKET
11
14
  const nonce = process.env.CORDISX_NATIVE_CONTROL_NONCE
12
15
  const executable = process.env.CORDISX_NATIVE_REAL_CODEX_PATH
13
16
  const agentModelsBinding = process.env.CORDISX_NATIVE_AGENT_MODELS_BINDING
14
17
  const marker = 'cordisx.operation_token'
18
+ function configuredOverrides(existing, overrides) {
19
+ const merged = { ...existing, ...overrides }
20
+ for (const [name, definition] of Object.entries(overrides)) {
21
+ if (!name.startsWith('model_providers.') || !object(definition)) continue
22
+ const id = name.slice('model_providers.'.length)
23
+ merged[name] = {
24
+ ...definition,
25
+ ...object(object(existing?.model_providers)?.[id]),
26
+ ...object(existing?.[name]),
27
+ base_url: definition.base_url,
28
+ wire_api: definition.wire_api,
29
+ }
30
+ if (Object.hasOwn(merged, `${name}.base_url`)) merged[`${name}.base_url`] = definition.base_url
31
+ }
32
+ return merged
33
+ }
15
34
  // Native history and plugin catalogs can exceed the small private control-message budget.
16
35
  const maxNativeLineBytes = 64 * 1024 * 1024
17
36
  const maxControlLineBytes = 8 * 1024 * 1024
@@ -48,6 +67,7 @@ if (agentModelsBinding && nativeArgs.includes('app-server')) {
48
67
  )
49
68
  }
50
69
  const child = spawn(executable, nativeArgs, { stdio: ['pipe', 'pipe', 'inherit'], env: process.env })
70
+ const nativeTransport = createNativeProviderTransport(child, { executable, args: nativeArgs, env: process.env })
51
71
  const control = net.connect(socketPath)
52
72
  const controlCalls = new Map()
53
73
  const privateCalls = new Map()
@@ -57,6 +77,8 @@ const preparedResumes = new Map()
57
77
  const unmarkedTurns = new NativeRequestTracker()
58
78
  // An unacknowledged lifecycle mutation stays uncertain; retain its fence, not its payload.
59
79
  const lifecycleCalls = new Map()
80
+ const uncertainSwitches = new Map()
81
+ const switchReconciliations = new NativeRequestTracker()
60
82
  // If the bounded map loses a mutation, its safety fence lasts until this process restarts.
61
83
  // Ordinary native requests still pass through; only automatic recovery/Host switching stops.
62
84
  let lifecycleUncertain = false
@@ -147,14 +169,16 @@ const nativeErrorCode = error =>
147
169
  ['ENOENT', 'EACCES', 'EPERM', 'EPIPE', 'ECONNRESET', 'ECONNREFUSED'].includes(error?.code) ? error.code : 'unknown'
148
170
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined
149
171
  const validToken = value => typeof value === 'string' && /^[^\0\r\n]{16,256}$/u.test(value)
150
- const lifecyclePending = threadId => lifecycleUncertain || [...lifecycleCalls.values()].includes(threadId)
172
+ const lifecyclePending = threadId =>
173
+ lifecycleUncertain || uncertainSwitches.has(threadId)
174
+ || [...lifecycleCalls.values()].includes(threadId)
151
175
  const write = (stream, value) =>
152
176
  new Promise((resolve, reject) => {
153
177
  if (stream.destroyed) {
154
178
  reject(new Error('Native transport is closed'))
155
179
  return
156
180
  }
157
- if (stream === child.stdin) {
181
+ if (stream === nativeTransport.stdin) {
158
182
  try {
159
183
  const message = typeof value === 'string' ? JSON.parse(value) : value
160
184
  if (message?.method === 'initialize') {
@@ -191,11 +215,15 @@ function stop(reason = 'transport-closed') {
191
215
  recoveringTurns.clear()
192
216
  cancelledRecovery.clear()
193
217
  lifecycleCalls.clear()
218
+ uncertainSwitches.clear()
219
+ switchReconciliations.clear()
220
+ switchRequests.clear()
194
221
  firstTurns.clear()
195
222
  agentFirstTurns.clear()
196
223
  control.destroy()
197
224
  nativeInput.destroy()
198
- child.stdin.destroy()
225
+ nativeTransport.stdin.destroy()
226
+ nativeTransport.close()
199
227
  if (child.exitCode === null) child.kill('SIGTERM')
200
228
  }
201
229
  function call(stream, calls, request, timeout = 30_000) {
@@ -218,7 +246,19 @@ function controlCall(type, input = {}) {
218
246
  return call(control, controlCalls, { type, ...input })
219
247
  }
220
248
  function nativeCall(method, params) {
221
- return call(child.stdin, privateCalls, { method, params })
249
+ return call(nativeTransport.stdin, privateCalls, { method, params })
250
+ }
251
+ function acknowledgedSwitchResume(message, expected) {
252
+ return expected && message.error === undefined && message.result?.thread?.id === expected.threadId
253
+ && message.result.thread.status?.type === 'idle' && message.result.modelProvider === expected.providerId
254
+ && message.result.model === expected.model
255
+ }
256
+ function reconcileSwitch(message, expected, hostAdmitted = false) {
257
+ if (
258
+ acknowledgedSwitchResume(message, expected) && uncertainSwitches.get(expected.threadId) === expected
259
+ && (expected.providerId === 'openai' || hostAdmitted) && !lifecycleUncertain
260
+ && ![...lifecycleCalls.values()].includes(expected.threadId)
261
+ ) uncertainSwitches.delete(expected.threadId)
222
262
  }
223
263
  function settle(calls, message, isControl) {
224
264
  const pending = calls.get(message.id)
@@ -235,6 +275,8 @@ function settle(calls, message, isControl) {
235
275
  }
236
276
 
237
277
  function missingManagedProvider(message) {
278
+ const structured = nativeProviderFailure(message)
279
+ if (structured !== undefined) return structured
238
280
  if (message?.error?.code !== -32600 || typeof message.error.message !== 'string') return undefined
239
281
  const match = /^failed to load configuration: Model provider `([^`\0\r\n]{1,128})` not found$/u.exec(
240
282
  message.error.message,
@@ -298,7 +340,7 @@ child.on('error', error => {
298
340
  nativeLifecycle('child-spawn-failed', { errorCode: nativeErrorCode(error) })
299
341
  stop(error)
300
342
  })
301
- child.stdin.on('error', error => {
343
+ nativeTransport.stdin.on('error', error => {
302
344
  nativeLifecycle('child-input-error', { errorCode: nativeErrorCode(error) })
303
345
  stop(error)
304
346
  })
@@ -320,7 +362,7 @@ async function forward(line) {
320
362
  try {
321
363
  message = JSON.parse(line)
322
364
  } catch {
323
- await write(child.stdin, line)
365
+ await write(nativeTransport.stdin, line)
324
366
  return
325
367
  }
326
368
  const params = object(message?.params)
@@ -360,10 +402,24 @@ async function forward(line) {
360
402
  const managed = config !== undefined && Object.hasOwn(config, marker)
361
403
  if (message?.method === 'turn/interrupt' && typeof params?.threadId === 'string') {
362
404
  unmarkedTurns.retireThread(params.threadId)
363
- if (recoveringTurns.has(params.threadId)) cancelledRecovery.add(params.threadId)
405
+ if (recoveringTurns.has(params.threadId) || switching.has(params.threadId)) cancelledRecovery.add(params.threadId)
364
406
  }
365
407
  const mutatesThread = ['turn/start', 'turn/addUserMessage', 'turn/steer', 'thread/resume', 'thread/unsubscribe']
366
408
  .includes(message?.method)
409
+ if (
410
+ uncertainSwitches.has(params?.threadId)
411
+ && ['thread/resume', 'thread/unsubscribe', 'turn/interrupt'].includes(message?.method)
412
+ ) uncertainSwitches.set(params.threadId, undefined)
413
+ if (
414
+ uncertainSwitches.has(params?.threadId)
415
+ && ['turn/start', 'turn/addUserMessage', 'turn/steer'].includes(message?.method)
416
+ ) {
417
+ await write(process.stdout, {
418
+ id: message.id,
419
+ error: { code: -32000, message: 'Provider switch status is uncertain. Reopen this conversation before sending.' },
420
+ })
421
+ return
422
+ }
367
423
  if (
368
424
  mutatesThread && (recoveringTurns.has(params?.threadId) || switching.has(params?.threadId))
369
425
  ) {
@@ -406,7 +462,37 @@ async function forward(line) {
406
462
  if (
407
463
  message?.method === 'thread/resume' && typeof params?.threadId === 'string'
408
464
  && ['string', 'number'].includes(typeof message.id)
409
- ) trackedResume = resumeCalls.track(message.id, params)
465
+ ) {
466
+ trackedResume = resumeCalls.track(message.id, params)
467
+ if (uncertainSwitches.has(params.threadId)) {
468
+ let expected
469
+ try {
470
+ const before = await nativeCall('thread/read', { threadId: params.threadId, includeTurns: false })
471
+ const thread = before?.thread
472
+ if (
473
+ thread?.id === params.threadId && typeof thread.modelProvider === 'string'
474
+ && typeof thread.model === 'string'
475
+ && ['idle', 'notLoaded', 'systemError'].includes(thread.status?.type)
476
+ && params.path == null && params.history == null
477
+ && (params.modelProvider == null || params.modelProvider === thread.modelProvider)
478
+ && (params.config?.model_provider === undefined || params.config.model_provider === thread.modelProvider)
479
+ && (params.model == null || params.model === thread.model)
480
+ ) expected = { threadId: params.threadId, providerId: thread.modelProvider, model: thread.model }
481
+ } catch {}
482
+ if (!expected || !switchReconciliations.track(message.id, expected)) {
483
+ resumeCalls.take(message.id)
484
+ await write(process.stdout, {
485
+ id: message.id,
486
+ error: {
487
+ code: -32000,
488
+ message: 'Provider switch status is uncertain. Reopen the original conversation and service.',
489
+ },
490
+ })
491
+ return
492
+ }
493
+ uncertainSwitches.set(params.threadId, expected)
494
+ }
495
+ }
410
496
  if (
411
497
  message?.method === 'turn/start' && typeof params?.threadId === 'string'
412
498
  && ['string', 'number'].includes(typeof message.id)
@@ -428,15 +514,34 @@ async function forward(line) {
428
514
  ) {
429
515
  let prepared
430
516
  try {
431
- prepared = await prepareManagedResume(message, { nativeCall, controlCall })
517
+ prepared = await prepareManagedResume(message, {
518
+ nativeCall,
519
+ controlCall,
520
+ allowConfigured: uncertainSwitches.has(params.threadId),
521
+ })
432
522
  } catch {}
433
523
  if (prepared) {
434
524
  preparedResumes.set(message.id, { threadId: prepared.threadId, resumeToken: prepared.resumeToken })
435
525
  // A failed native write must not cause a second attempt with the original request.
436
- await write(child.stdin, prepared.message)
526
+ await write(nativeTransport.stdin, prepared.message)
437
527
  return
438
528
  }
439
529
  }
530
+ const reconciliation = uncertainSwitches.get(params?.threadId)
531
+ if (message?.method === 'thread/resume' && reconciliation && reconciliation.providerId !== 'openai') {
532
+ resumeCalls.take(message.id)
533
+ switchReconciliations.take(message.id)
534
+ lifecycleCalls.delete(message.id)
535
+ uncertainSwitches.set(params.threadId, undefined)
536
+ await write(process.stdout, {
537
+ id: message.id,
538
+ error: {
539
+ code: -32000,
540
+ message: 'Provider switch status is uncertain. Original service preparation was not admitted.',
541
+ },
542
+ })
543
+ return
544
+ }
440
545
  if (['thread/start', 'thread/resume'].includes(message?.method) && params) {
441
546
  try {
442
547
  let providerId = params.modelProvider
@@ -448,13 +553,13 @@ async function forward(line) {
448
553
  ...(typeof providerId === 'string' ? { providerId } : {}),
449
554
  })
450
555
  if (object(overrides) && Object.keys(overrides).length) {
451
- params.config = { ...object(params.config), ...overrides }
452
- await write(child.stdin, message)
556
+ params.config = configuredOverrides(object(params.config), overrides)
557
+ await write(nativeTransport.stdin, message)
453
558
  return
454
559
  }
455
560
  } catch {}
456
561
  }
457
- await write(child.stdin, line)
562
+ await write(nativeTransport.stdin, line)
458
563
  return
459
564
  }
460
565
  let admitted = false
@@ -480,7 +585,9 @@ async function forward(line) {
480
585
  if (message.method === 'thread/start') {
481
586
  params.modelProvider = dispatch.providerId
482
587
  params.model = dispatch.model
483
- params.config = { ...nextConfig, ...dispatch.configOverrides }
588
+ params.config = dispatch.providerSource === 'config'
589
+ ? configuredOverrides(nextConfig, dispatch.configOverrides)
590
+ : { ...nextConfig, ...dispatch.configOverrides }
484
591
  if (typeof dispatch.reasoningEffort === 'string') {
485
592
  params.config.model_reasoning_effort = dispatch.reasoningEffort
486
593
  }
@@ -511,7 +618,7 @@ async function forward(line) {
511
618
  firstTurns.delete(params.threadId)
512
619
  agentFirstTurns.delete(params.threadId)
513
620
  }
514
- await write(child.stdin, JSON.stringify(message))
621
+ await write(nativeTransport.stdin, JSON.stringify(message))
515
622
  } catch {
516
623
  desktopCalls.delete(message?.id)
517
624
  if (admitted) {
@@ -583,7 +690,7 @@ async function recoverResume(id, params, providerId, failureLine) {
583
690
 
584
691
  // A persisted history can exist after its executable session has been unloaded.
585
692
  // Replay only the exact missing-thread rejection, never a timeout or failed turn.
586
- async function recoverUnloadedTurn(id, params, failureLine) {
693
+ async function recoverUnloadedTurn(id, params, failureLine, expectedProvider) {
587
694
  const threadId = params.threadId
588
695
  if (recoveringTurns.has(threadId) || switching.has(threadId) || lifecyclePending(threadId)) {
589
696
  await write(process.stdout, failureLine)
@@ -597,9 +704,14 @@ async function recoverUnloadedTurn(id, params, failureLine) {
597
704
  const read = await nativeCall('thread/read', { threadId, includeTurns: false })
598
705
  const thread = object(read?.thread)
599
706
  if (
600
- thread?.id !== threadId || thread.status?.type !== 'notLoaded'
707
+ thread?.id !== threadId
708
+ || !(expectedProvider === undefined ? ['notLoaded'] : ['idle', 'notLoaded', 'systemError']).includes(
709
+ thread.status?.type,
710
+ )
601
711
  || typeof thread.modelProvider !== 'string' || thread.modelProvider === 'openai'
712
+ || (expectedProvider !== undefined && expectedProvider !== thread.modelProvider)
602
713
  || typeof thread.model !== 'string' || thread.model === ''
714
+ || thread.ephemeral === true
603
715
  ) throw new Error('Missing thread is not an unloaded managed session')
604
716
  const prepared = await controlCall('resume', {
605
717
  threadId,
@@ -610,6 +722,9 @@ async function recoverUnloadedTurn(id, params, failureLine) {
610
722
  throw new Error('Managed recovery rejected')
611
723
  }
612
724
  resumeToken = prepared.resumeToken
725
+ if (expectedProvider !== undefined && thread.status.type !== 'notLoaded') {
726
+ await nativeCall('thread/unsubscribe', { threadId })
727
+ }
613
728
  const resumed = await nativeCall('thread/resume', {
614
729
  threadId,
615
730
  modelProvider: thread.modelProvider,
@@ -672,10 +787,10 @@ readLines(nativeInput, line => {
672
787
  })
673
788
  nativeInput.once('end', () => {
674
789
  nativeLifecycle('desktop-input-ended')
675
- void inputQueue.finally(() => child.stdin.end())
790
+ void inputQueue.finally(() => nativeTransport.stdin.end())
676
791
  })
677
792
 
678
- readLines(child.stdout, line => {
793
+ readLines(nativeTransport.stdout, line => {
679
794
  let message
680
795
  try {
681
796
  message = JSON.parse(line)
@@ -692,8 +807,14 @@ readLines(child.stdout, line => {
692
807
  // Late private responses must never escape into the Desktop's request table.
693
808
  if (typeof message?.id === 'string' && message.id.startsWith(privatePrefix)) return
694
809
  if (message.method === undefined) lifecycleCalls.delete(message.id)
810
+ const reconciliation = message.method === undefined ? switchReconciliations.take(message.id) : undefined
695
811
  const turnParams = message.method === undefined ? unmarkedTurns.take(message.id) : undefined
696
812
  if (turnParams !== undefined) {
813
+ const providerId = nativeProviderFailure(message)
814
+ if (providerId !== undefined && providerId !== 'openai') {
815
+ void recoverUnloadedTurn(message.id, turnParams, line, providerId).catch(stop)
816
+ return
817
+ }
697
818
  if (message.error?.code === -32600 && message.error.message === `thread not found: ${turnParams.threadId}`) {
698
819
  void recoverUnloadedTurn(message.id, turnParams, line).catch(stop)
699
820
  return
@@ -704,8 +825,14 @@ readLines(child.stdout, line => {
704
825
  preparedResumes.delete(message.id)
705
826
  resumeCalls.take(message.id)
706
827
  const succeeded = message.error === undefined && message.result?.thread?.id === preparedResume.threadId
828
+ && (reconciliation === undefined
829
+ || (acknowledgedSwitchResume(message, reconciliation)
830
+ && uncertainSwitches.get(reconciliation.threadId) === reconciliation))
707
831
  void controlCall('resume-complete', { ...preparedResume, succeeded })
708
- .then(() => write(process.stdout, line)).catch(stop)
832
+ .then(completed => {
833
+ if (completed === true) reconcileSwitch(message, reconciliation, true)
834
+ return write(process.stdout, line)
835
+ }).catch(stop)
709
836
  return
710
837
  }
711
838
  const resumeParams = message.method === undefined ? resumeCalls.take(message?.id) : undefined
@@ -716,6 +843,7 @@ readLines(child.stdout, line => {
716
843
  return
717
844
  }
718
845
  }
846
+ reconcileSwitch(message, reconciliation)
719
847
  const operation = desktopCalls.get(message?.id)
720
848
  if (!operation || message.method !== undefined) {
721
849
  void write(process.stdout, line).catch(stop)
@@ -743,6 +871,7 @@ readLines(child.stdout, line => {
743
871
  })
744
872
 
745
873
  const switching = new Set()
874
+ const switchRequests = new Map()
746
875
  const BRIDGE_NATIVE_METHODS = new Set([
747
876
  'thread/list',
748
877
  'thread/read',
@@ -761,6 +890,14 @@ readLines(control, line => {
761
890
  return
762
891
  }
763
892
  if (settle(controlCalls, message, true)) return
893
+ if (
894
+ message.type === 'switch-cancel' && typeof message.switchId === 'string'
895
+ && switchRequests.get(message.switchId) === message.threadId
896
+ ) {
897
+ cancelledRecovery.add(message.threadId)
898
+ uncertainSwitches.set(message.threadId, undefined)
899
+ return
900
+ }
764
901
  if (message.type === 'task-create' && typeof message.id === 'string') {
765
902
  void nativeCall('mcpServer/tool/call', {
766
903
  server: 'codex_app',
@@ -784,6 +921,13 @@ readLines(control, line => {
784
921
  void write(control, { id: message.id, ok: false }).catch(stop)
785
922
  return
786
923
  }
924
+ if (uncertainSwitches.has(params.threadId) && message.method === 'turn/start') {
925
+ void write(control, { id: message.id, ok: false, reason: 'provider-switch-reconciliation-required' }).catch(stop)
926
+ return
927
+ }
928
+ if (
929
+ uncertainSwitches.has(params.threadId) && ['thread/resume', 'turn/interrupt'].includes(message.method)
930
+ ) uncertainSwitches.set(params.threadId, undefined)
787
931
  void nativeCall(message.method, params)
788
932
  .then(value => write(control, { id: message.id, ok: true, value }))
789
933
  .catch(() => write(control, { id: message.id, ok: false }).catch(stop))
@@ -809,34 +953,24 @@ readLines(control, line => {
809
953
  return
810
954
  }
811
955
  switching.add(message.threadId)
956
+ switchRequests.set(message.id, message.threadId)
812
957
  void (async () => {
813
958
  try {
814
- if (message.requireIdle === true) {
815
- const before = await nativeCall('thread/read', { threadId: message.threadId, includeTurns: false })
816
- if (before?.thread?.id !== message.threadId || before?.thread?.status?.type !== 'idle') {
817
- await write(control, { id: message.id, ok: true, value: { status: 'rejected', reason: 'thread-not-idle' } })
818
- return
819
- }
820
- }
821
- // Ephemeral side chats have no rollout to resume. Unsubscribe would destroy
822
- // the only live session even when the following resume fails.
823
- const current = await nativeCall('thread/read', { threadId: message.threadId, includeTurns: false })
824
- if (current?.thread?.ephemeral === true) throw new Error('Ephemeral provider switching requires a new side chat')
825
- await nativeCall('thread/unsubscribe', { threadId: message.threadId })
826
- const result = await nativeCall('thread/resume', {
827
- threadId: message.threadId,
828
- model: message.model,
829
- modelProvider: message.providerId,
830
- config: message.config,
831
- excludeTurns: true,
959
+ const result = await switchNativeThread(message, {
960
+ nativeCall,
961
+ controlCall,
962
+ current: () => !closed && !cancelledRecovery.has(message.threadId) && !lifecyclePending(message.threadId),
832
963
  })
833
- const ok = result?.thread?.id === message.threadId && result?.modelProvider === message.providerId
834
- && result?.model === message.model
835
- await write(control, { id: message.id, ok })
964
+ if (result.reason === 'provider-switch-reconciliation-required') {
965
+ uncertainSwitches.set(message.threadId, undefined)
966
+ }
967
+ await write(control, { id: message.id, ...result })
836
968
  } catch {
837
969
  await write(control, { id: message.id, ok: false })
838
970
  } finally {
839
971
  switching.delete(message.threadId)
972
+ switchRequests.delete(message.id)
973
+ cancelledRecovery.delete(message.threadId)
840
974
  }
841
975
  })().catch(stop)
842
976
  }, maxControlLineBytes)
@@ -2,7 +2,7 @@ const object = value => value !== null && typeof value === 'object' && !Array.is
2
2
  const validToken = value => typeof value === 'string' && /^[^\0\r\n]{16,256}$/u.test(value)
3
3
 
4
4
  /** Refresh recognized persisted managed routes without changing the selected provider or inventing a Send. */
5
- export async function prepareManagedResume(message, { nativeCall, controlCall }) {
5
+ export async function prepareManagedResume(message, { nativeCall, controlCall, allowConfigured = false }) {
6
6
  const params = message.params
7
7
  // Native path/history overrides can select history other than the named thread.
8
8
  if (params.path != null || params.history != null) return undefined
@@ -15,7 +15,8 @@ export async function prepareManagedResume(message, { nativeCall, controlCall })
15
15
  || (params.modelProvider != null && params.modelProvider !== thread.modelProvider)
16
16
  || (params.config?.model_provider !== undefined && params.config.model_provider !== thread.modelProvider)
17
17
  ) return undefined
18
- const prepared = await controlCall('managed-resume', {
18
+ // Only an exact persisted-pair reconciliation uses ordinary configured-provider admission.
19
+ const prepared = await controlCall(allowConfigured ? 'resume' : 'managed-resume', {
19
20
  threadId: params.threadId,
20
21
  providerId: thread.modelProvider,
21
22
  model: typeof params.model === 'string' ? params.model : thread.model,
@@ -0,0 +1,12 @@
1
+ /** Native structured provider failures occur before a model turn is accepted. */
2
+ export function nativeProviderFailure(message) {
3
+ if (message?.error?.code !== -32600) return undefined
4
+ const data = message.error.data
5
+ if (!['modelProviderNotConfigured', 'modelProviderMismatch'].includes(data?.type)) return undefined
6
+ if (typeof data.modelProvider !== 'string' || !/^[a-zA-Z0-9_.:-]{1,128}$/u.test(data.modelProvider)) return undefined
7
+ if (
8
+ data.type === 'modelProviderMismatch'
9
+ && (typeof data.currentModelProvider !== 'string' || data.currentModelProvider === data.modelProvider)
10
+ ) return undefined
11
+ return data.modelProvider
12
+ }