sneakoscope 10.6.2 → 10.7.1

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 (135) hide show
  1. package/README.md +28 -6
  2. package/config/perf-budgets.v1.json +1 -2
  3. package/config/skills-hash-ledger.v1.json +7 -2
  4. package/crates/sks-core/Cargo.lock +1 -1
  5. package/crates/sks-core/Cargo.toml +1 -1
  6. package/dist/bin/sks-dispatch.js +6 -3
  7. package/dist/cli/args.js +3 -1
  8. package/dist/cli/command-manifest-lite.js +48 -114
  9. package/dist/cli/command-registry.js +1 -18
  10. package/dist/cli/commands-fast.js +11 -4
  11. package/dist/cli/help-fast.js +11 -22
  12. package/dist/cli/help.js +3 -3
  13. package/dist/cli/install-helpers-codex-lb-config.js +11 -8
  14. package/dist/cli/install-helpers.js +1 -1
  15. package/dist/cli/router.js +12 -26
  16. package/dist/commands/codex-app.js +2 -2
  17. package/dist/commands/doctor-helpers.js +1 -1
  18. package/dist/commands/mad-sks.js +2 -2
  19. package/dist/config/skills-manifest.json +13 -8
  20. package/dist/core/agent-bridge/async-command.js +2 -2
  21. package/dist/core/agents/agent-recursion-guard.js +0 -2
  22. package/dist/core/agents/agent-role-config.js +6 -2
  23. package/dist/core/agents/sks-model-pin-hygiene.js +150 -0
  24. package/dist/core/auto-review.js +15 -172
  25. package/dist/core/code-structure.js +0 -1
  26. package/dist/core/codex/codex-config-guard.js +18 -13
  27. package/dist/core/codex-app/codex-app-ui-state-snapshot.js +7 -1
  28. package/dist/core/codex-control/codex-reliability-shield.js +64 -15
  29. package/dist/core/codex-control/codex-sdk-adapter.js +38 -5
  30. package/dist/core/codex-lb/bridge-contracts.js +5 -0
  31. package/dist/core/codex-lb/combined-catalog/builder.js +4 -2
  32. package/dist/core/codex-lb/combined-catalog/latest-generation.js +7 -34
  33. package/dist/core/codex-lb/combined-catalog/normalize.js +3 -1
  34. package/dist/core/codex-lb/desktop-bridge/codex-lb-turn-state.js +35 -0
  35. package/dist/core/codex-lb/desktop-bridge/compaction-adapter.js +3 -0
  36. package/dist/core/codex-lb/desktop-bridge/header-policy.js +10 -4
  37. package/dist/core/codex-lb/desktop-bridge/http-forward.js +92 -30
  38. package/dist/core/codex-lb/desktop-bridge/provider-handoff.js +79 -0
  39. package/dist/core/codex-lb/desktop-bridge/responses-websocket.js +57 -13
  40. package/dist/core/codex-lb/desktop-bridge/security.js +101 -55
  41. package/dist/core/codex-lb/desktop-bridge/server.js +10 -2
  42. package/dist/core/codex-lb/desktop-bridge/types.js +3 -0
  43. package/dist/core/codex-lb/desktop-bridge/websocket-forward.js +3 -0
  44. package/dist/core/codex-lb/desktop-controller-v3/catalog.js +13 -0
  45. package/dist/core/codex-lb/desktop-controller-v3/provider-commands.js +0 -9
  46. package/dist/core/codex-lb/desktop-service.js +10 -13
  47. package/dist/core/codex-lb/request-route-resolver.js +1 -1
  48. package/dist/core/codex-runtime/codex-desktop-config-policy.js +0 -1
  49. package/dist/core/commands/agent-bridge-command.js +1 -1
  50. package/dist/core/commands/basic-cli.js +60 -233
  51. package/dist/core/commands/command-utils.js +1 -1
  52. package/dist/core/commands/gc-command.js +30 -29
  53. package/dist/core/commands/image-ux-review-command.js +1 -1
  54. package/dist/core/commands/install-package-command.js +1 -1
  55. package/dist/core/commands/intent-normalization/normalizer.js +2 -2
  56. package/dist/core/commands/pipeline-command.js +13 -5
  57. package/dist/core/commands/plan-command.js +2 -3
  58. package/dist/core/commands/research-command.js +0 -3
  59. package/dist/core/commands/review-command.js +1 -1
  60. package/dist/core/commands/seo-command.js +27 -20
  61. package/dist/core/commands/status-command.js +8 -2
  62. package/dist/core/doctor/command-alias-cleanup.js +6 -6
  63. package/dist/core/evaluation.js +1 -1
  64. package/dist/core/feature-fixtures.js +9 -43
  65. package/dist/core/feature-registry.js +9 -27
  66. package/dist/core/git-hygiene/shared-memory-publish.js +1 -1
  67. package/dist/core/hooks-runtime/jev-spawn-routing.js +1 -5
  68. package/dist/core/hooks-runtime/parent-orchestration-gate.js +6 -8
  69. package/dist/core/hooks-runtime/stop-repeat-guard.js +0 -13
  70. package/dist/core/hooks-runtime.js +13 -9
  71. package/dist/core/init/skills.js +27 -16
  72. package/dist/core/init.js +0 -9
  73. package/dist/core/install/installed-package-smoke.js +3 -1
  74. package/dist/core/perf/import-graph-budget.js +0 -1
  75. package/dist/core/perf/release-latency-slo.js +2 -30
  76. package/dist/core/pipeline-internals/pipeline-stage-builder.js +2 -4
  77. package/dist/core/pipeline-internals/runtime-core.js +2 -38
  78. package/dist/core/proof/route-proof-policy.js +2 -4
  79. package/dist/core/proof/runtime-truth-matrix.js +2 -2
  80. package/dist/core/proof-field.js +104 -39
  81. package/dist/core/provider/provider-context.js +4 -1
  82. package/dist/core/questions.js +11 -7
  83. package/dist/core/release/gate-affected-globs.js +0 -2
  84. package/dist/core/research/research-reviewer-contract.js +34 -0
  85. package/dist/core/research/research-work-graph.js +1 -1
  86. package/dist/core/research.js +1 -1
  87. package/dist/core/routes/constants.js +0 -1
  88. package/dist/core/routes/diagnostic-allowlist.js +1 -3
  89. package/dist/core/routes/light-routes.js +1 -2
  90. package/dist/core/routes.js +1 -1
  91. package/dist/core/safety/command-contract/contracts.js +5 -1
  92. package/dist/core/search/context.js +2 -2
  93. package/dist/core/search-visibility/marketing-truthfulness.js +10 -7
  94. package/dist/core/search-visibility/marketing.js +194 -149
  95. package/dist/core/skill-forge.js +1 -361
  96. package/dist/core/strategy/adhd-orchestrating-gate.js +3 -3
  97. package/dist/core/triwiki/context-graph/extractors/topology/commands.js +2 -6
  98. package/dist/core/triwiki-wrongness/wrongness-cli.js +9 -27
  99. package/dist/core/update/update-migration-state.js +10 -40
  100. package/dist/core/version.js +1 -1
  101. package/package.json +2 -3
  102. package/release-gates.v2.json +1 -32
  103. package/dist/cli/recallpulse-command.js +0 -144
  104. package/dist/commands/auto-review.js +0 -5
  105. package/dist/commands/codex-native.js +0 -77
  106. package/dist/commands/recallpulse.js +0 -5
  107. package/dist/core/codex-native/codex-native-interop-policy.js +0 -127
  108. package/dist/core/commands/autoresearch-command.js +0 -4
  109. package/dist/core/commands/code-structure-command.js +0 -52
  110. package/dist/core/commands/goal-command.js +0 -43
  111. package/dist/core/commands/recallpulse-command.js +0 -4
  112. package/dist/core/commands/remote-command.js +0 -119
  113. package/dist/core/commands/skill-dream-command.js +0 -43
  114. package/dist/core/commands/wrongness-command.js +0 -2
  115. package/dist/core/goal-workflow.js +0 -80
  116. package/dist/core/mcp/mcp-tool-name-normalizer.js +0 -28
  117. package/dist/core/recallpulse/policy.js +0 -207
  118. package/dist/core/recallpulse.js +0 -947
  119. package/dist/core/remote/audit-idempotency.js +0 -241
  120. package/dist/core/remote/index.js +0 -10
  121. package/dist/core/remote/machine-registry.js +0 -167
  122. package/dist/core/remote/owner-proof.js +0 -216
  123. package/dist/core/remote/protocol.js +0 -249
  124. package/dist/core/remote/readiness.js +0 -156
  125. package/dist/core/remote/session-index.js +0 -61
  126. package/dist/core/remote/session-snapshot.js +0 -197
  127. package/dist/core/remote/ssh-worker-client.js +0 -377
  128. package/dist/core/remote/types.js +0 -10
  129. package/dist/core/remote/worker.js +0 -360
  130. package/dist/core/search/context-graph-seeds.js +0 -15
  131. package/dist/core/verification/context-graph-affected.js +0 -312
  132. package/dist/core/verification/verification-artifact-lock.js +0 -21
  133. package/dist/core/verification/verification-dag.js +0 -89
  134. package/dist/core/verification/verification-result.js +0 -19
  135. package/dist/core/verification/verification-worker-pool.js +0 -204
@@ -1,10 +1,12 @@
1
1
  import net from 'node:net';
2
2
  import tls from 'node:tls';
3
3
  import WebSocket, { WebSocketServer } from 'ws';
4
- import { BRIDGE_OFFICIAL_ROUTE_ID } from '../bridge-contracts.js';
4
+ import { BRIDGE_OFFICIAL_ROUTE_ID, BRIDGE_REMOTE_COMPACTION } from '../bridge-contracts.js';
5
5
  import { buildOfficialPassthroughWebSocketHeaders, buildProviderWebSocketHeaders } from './header-policy.js';
6
6
  import { createDesktopBridgeRejectionLogger } from './rejection-log.js';
7
- import { assertDesktopBridgeRouteContext, ensureDesktopBridgeRemoteTarget, isUnreachableUpstreamError, refreshDesktopBridgeRemoteTarget, resolveAndBindDesktopBridgeRouteContext, resolveCodexSessionIdentity, resolveDesktopBridgeTarget, safeBridgeErrorCode } from './security.js';
7
+ import { assertDesktopBridgeRouteContext, ensureDesktopBridgeRemoteTarget, isUnreachableUpstreamError, refreshDesktopBridgeRemoteTarget, resolveAndBindDesktopBridgeRouteContext, resolveCodexSessionIdentity, resolveDesktopBridgeTarget, safeBridgeErrorCode, threadRouteMove } from './security.js';
8
+ import { admitCodexLbTurnState } from './codex-lb-turn-state.js';
9
+ import { ProviderHandoffRefusedError, assertProviderHandoffAllowed, providerHandoffRefusedEvent, stripProviderBoundItems, } from './provider-handoff.js';
8
10
  import { DEFAULT_DESKTOP_BRIDGE_MAX_REQUEST_BODY_BYTES, DesktopBridgeError } from './types.js';
9
11
  import { buildCompactionSummaryRequest, compactionCreatedEvent, compactionFailedEvent, compactionResponseEvents, expandBridgeCompactionItems, newCompactionResponseId, parseProviderSummary, requestsRemoteCompaction, ResponsesContinuationChain, summaryFailure, summaryWithinBounds, } from './compaction-adapter.js';
10
12
  import { requestProviderCompactionSummary } from './http-forward.js';
@@ -45,6 +47,7 @@ export function forwardResponsesWebSocket(req, socket, head, config) {
45
47
  let upstream = null;
46
48
  let upstreamSocket = null;
47
49
  let bound = null;
50
+ let boundByMove = false;
48
51
  let boundBaseUrl = null;
49
52
  let boundCredentialGeneration = null;
50
53
  let boundCredentialFingerprint = null;
@@ -126,26 +129,44 @@ export function forwardResponsesWebSocket(req, socket, head, config) {
126
129
  }
127
130
  identity = bound ? withLineage(identity, nextIdentity) : nextIdentity;
128
131
  const request = routeRequest(model);
129
- assertBinding(assertDesktopBridgeRouteContext(request, config));
130
- const route = await resolveAndBindDesktopBridgeRouteContext(request, config);
132
+ const planned = assertDesktopBridgeRouteContext(request, config);
133
+ assertProviderHandoffAllowed(message.create, threadRouteMove(request, planned, config));
134
+ assertBinding(planned);
135
+ let move = null;
136
+ const route = await resolveAndBindDesktopBridgeRouteContext(request, config, (resolved) => {
137
+ move = threadRouteMove(request, resolved, config);
138
+ assertProviderHandoffAllowed(message.create, move);
139
+ });
131
140
  if (stopped || client.readyState !== WebSocket.OPEN)
132
141
  return;
133
142
  assertBinding(route);
134
143
  routedModel = route.public_model;
135
144
  if (!bound) {
136
145
  bound = route;
146
+ boundByMove = Boolean(move);
137
147
  await connect(route);
138
148
  }
139
149
  const create = { ...message.create, model: route.upstream_model };
140
- const expanded = expandBridgeCompactionItems(create);
141
- if (route.provider_id !== BRIDGE_OFFICIAL_ROUTE_ID && requestsRemoteCompaction(create)) {
150
+ let rewritten = expandBridgeCompactionItems(create);
151
+ if (route.session_pin?.handoff_from && stripProviderBoundItems(create, Boolean(move)))
152
+ rewritten = true;
153
+ if (BRIDGE_REMOTE_COMPACTION[route.provider_id] === 'bridge_summary' && requestsRemoteCompaction(create)) {
142
154
  message.compaction = create;
143
155
  return;
144
156
  }
145
- if (route.upstream_model !== model || expanded)
157
+ if (route.upstream_model !== model || rewritten)
146
158
  message.data = Buffer.from(JSON.stringify(create));
147
159
  message.routed = create;
148
160
  }
161
+ function refuseMove(message, error) {
162
+ const model = typeof message.create?.model === 'string' ? message.create.model : '';
163
+ logRejection({ code: error.code, transport: 'websocket', ...(req.url ? { url: req.url } : {}) });
164
+ relay(client, Buffer.from(JSON.stringify(providerHandoffRefusedEvent(error, newCompactionResponseId(), model))), false);
165
+ const index = pending.indexOf(message);
166
+ if (index >= 0)
167
+ pending.splice(index, 1);
168
+ pendingBytes -= message.originalBytes;
169
+ }
149
170
  async function answerCompaction(create) {
150
171
  const route = bound;
151
172
  const provider = config.providers[route.provider_id];
@@ -192,6 +213,7 @@ export function forwardResponsesWebSocket(req, socket, head, config) {
192
213
  }
193
214
  async function connect(route) {
194
215
  const official = route.provider_id === BRIDGE_OFFICIAL_ROUTE_ID;
216
+ const summarizes = BRIDGE_REMOTE_COMPACTION[route.provider_id] === 'bridge_summary';
195
217
  const provider = route.provider_id === BRIDGE_OFFICIAL_ROUTE_ID ? null : config.providers[route.provider_id];
196
218
  const remote = official ? config.officialRemote : provider?.remote;
197
219
  if (!remote)
@@ -209,6 +231,10 @@ export function forwardResponsesWebSocket(req, socket, head, config) {
209
231
  const target = resolveDesktopBridgeTarget(req.url, remote);
210
232
  const outgoing = official ? buildOfficialPassthroughWebSocketHeaders(req.headers, target.host)
211
233
  : buildProviderWebSocketHeaders(req.headers, { providerId: provider.provider_id, authTransport: provider.auth_transport, credential: credential }, target.host);
234
+ if (boundByMove)
235
+ delete outgoing['x-codex-turn-state'];
236
+ else if (provider?.provider_id === 'codex-lb')
237
+ admitCodexLbTurnState(outgoing, identity.thread_id, credential.fingerprint);
212
238
  const headers = {};
213
239
  for (const [name, value] of Object.entries(outgoing)) {
214
240
  if (name.startsWith('sec-websocket-') || name === 'connection' || name === 'upgrade' || name === 'content-length')
@@ -256,7 +282,8 @@ export function forwardResponsesWebSocket(req, socket, head, config) {
256
282
  frame = advised;
257
283
  logRejection({ code: 'bridge_upstream_model_capacity_retry_advised', transport: 'websocket', provider_id: route.provider_id, public_model: routedModel ?? route.public_model, ...(req.url ? { url: req.url } : {}) });
258
284
  }
259
- chain.received(frame);
285
+ if (summarizes)
286
+ chain.received(frame);
260
287
  try {
261
288
  relay(client, frame, binary);
262
289
  }
@@ -289,24 +316,41 @@ export function forwardResponsesWebSocket(req, socket, head, config) {
289
316
  return;
290
317
  processing = true;
291
318
  try {
292
- if (!bound) {
319
+ while (!bound) {
293
320
  const firstCreate = pending.find((message) => message.create);
294
321
  if (!firstCreate)
295
322
  return;
296
- await resolveCreate(firstCreate);
323
+ try {
324
+ await resolveCreate(firstCreate);
325
+ }
326
+ catch (error) {
327
+ if (!(error instanceof ProviderHandoffRefusedError))
328
+ throw error;
329
+ refuseMove(firstCreate, error);
330
+ continue;
331
+ }
297
332
  firstCreate.create = null;
298
333
  }
299
334
  while (!stopped && client.readyState === WebSocket.OPEN && pending.length) {
300
335
  const message = pending[0];
301
- if (message.create)
302
- await resolveCreate(message);
336
+ if (message.create) {
337
+ try {
338
+ await resolveCreate(message);
339
+ }
340
+ catch (error) {
341
+ if (!(error instanceof ProviderHandoffRefusedError))
342
+ throw error;
343
+ refuseMove(message, error);
344
+ continue;
345
+ }
346
+ }
303
347
  if (stopped || client.readyState !== WebSocket.OPEN)
304
348
  return;
305
349
  if (message.compaction)
306
350
  await answerCompaction(message.compaction);
307
351
  else {
308
352
  relay(upstream, message.data, message.binary);
309
- if (message.routed && bound?.provider_id !== BRIDGE_OFFICIAL_ROUTE_ID)
353
+ if (message.routed && bound && BRIDGE_REMOTE_COMPACTION[bound.provider_id] === 'bridge_summary')
310
354
  chain.sent(message.routed, message.data);
311
355
  }
312
356
  pending.shift();
@@ -209,14 +209,45 @@ function canonicalPublicModel(value) {
209
209
  export function desktopBridgeOfficialPassthroughEnabled(config) {
210
210
  return Boolean(config.officialPassthrough?.baseUrl);
211
211
  }
212
- function officialRouteContext(publicModel, policy, upstreamModel) {
212
+ function mintSessionPin(sessionId, target, publicModel, policy, previous) {
213
+ const handoffFrom = previous && previous.provider_id !== target.provider_id ? previous.provider_id : previous?.handoff_from;
214
+ return {
215
+ thread_id: sessionId,
216
+ provider_id: target.provider_id,
217
+ public_model: publicModel,
218
+ upstream_model: target.upstream_model,
219
+ catalog_generation: policy.catalog_generation,
220
+ route_policy_generation: policy.policy_generation,
221
+ created_at: new Date().toISOString(),
222
+ ...(handoffFrom ? { handoff_from: handoffFrom } : {}),
223
+ };
224
+ }
225
+ function officialRouteContext(publicModel, policy, upstreamModel, pin = null) {
213
226
  return {
214
227
  provider_id: BRIDGE_OFFICIAL_ROUTE_ID,
215
228
  public_model: publicModel,
216
229
  upstream_model: upstreamModel || publicModel,
217
230
  catalog_generation: policy.catalog_generation,
218
231
  route_policy_generation: policy.policy_generation,
219
- session_pin: null,
232
+ session_pin: pin,
233
+ };
234
+ }
235
+ function pinnedRouteContext(pin, publicModel, policy) {
236
+ const aged = pin.catalog_generation !== policy.catalog_generation
237
+ || pin.route_policy_generation !== policy.policy_generation;
238
+ return {
239
+ provider_id: pin.provider_id,
240
+ public_model: publicModel,
241
+ upstream_model: pin.upstream_model,
242
+ catalog_generation: policy.catalog_generation,
243
+ route_policy_generation: policy.policy_generation,
244
+ session_pin: aged
245
+ ? {
246
+ ...pin,
247
+ catalog_generation: policy.catalog_generation,
248
+ route_policy_generation: policy.policy_generation,
249
+ }
250
+ : pin,
220
251
  };
221
252
  }
222
253
  export function resolveBridgeRequestRoute(request, policy, pins) {
@@ -224,43 +255,22 @@ export function resolveBridgeRequestRoute(request, policy, pins) {
224
255
  const sessionId = request.session_id ? canonicalSessionId(request.session_id) : null;
225
256
  const pin = sessionId ? pins.find((entry) => entry.thread_id === sessionId) || null : null;
226
257
  if (pin && pin.public_model === publicModel) {
258
+ if (pin.provider_id === BRIDGE_OFFICIAL_ROUTE_ID)
259
+ return pinnedRouteContext(pin, publicModel, policy);
227
260
  const bare = policy.model_routes[publicModel];
228
261
  const qualified = policy.model_routes[`${pin.provider_id}:${publicModel}`];
229
262
  const current = bare?.provider_id === pin.provider_id && bare.upstream_model === pin.upstream_model ? bare : qualified;
230
263
  if (!current || current.provider_id !== pin.provider_id || current.upstream_model !== pin.upstream_model) {
231
264
  throw new DesktopBridgeError('session_pin_route_unavailable');
232
265
  }
233
- const aged = pin.catalog_generation !== policy.catalog_generation
234
- || pin.route_policy_generation !== policy.policy_generation;
235
- return {
236
- provider_id: pin.provider_id,
237
- public_model: publicModel,
238
- upstream_model: pin.upstream_model,
239
- catalog_generation: policy.catalog_generation,
240
- route_policy_generation: policy.policy_generation,
241
- session_pin: aged
242
- ? {
243
- ...pin,
244
- catalog_generation: policy.catalog_generation,
245
- route_policy_generation: policy.policy_generation,
246
- }
247
- : pin,
248
- };
266
+ return pinnedRouteContext(pin, publicModel, policy);
249
267
  }
250
268
  const route = policy.model_routes[publicModel];
251
269
  if (!route)
252
270
  throw new DesktopBridgeError('catalog_model_route_missing');
271
+ const nextPin = sessionId ? mintSessionPin(sessionId, route, publicModel, policy, pin) : null;
253
272
  if (route.provider_id === BRIDGE_OFFICIAL_ROUTE_ID)
254
- return officialRouteContext(publicModel, policy, route.upstream_model);
255
- const nextPin = sessionId ? {
256
- thread_id: sessionId,
257
- provider_id: route.provider_id,
258
- public_model: publicModel,
259
- upstream_model: route.upstream_model,
260
- catalog_generation: policy.catalog_generation,
261
- route_policy_generation: policy.policy_generation,
262
- created_at: new Date().toISOString(),
263
- } : null;
273
+ return officialRouteContext(publicModel, policy, route.upstream_model, nextPin);
264
274
  return {
265
275
  provider_id: route.provider_id,
266
276
  public_model: publicModel,
@@ -270,7 +280,7 @@ export function resolveBridgeRequestRoute(request, policy, pins) {
270
280
  session_pin: nextPin,
271
281
  };
272
282
  }
273
- function threadPinProvider(request, config) {
283
+ function threadPin(request, pins) {
274
284
  if (!request.session_id)
275
285
  return null;
276
286
  let threadId;
@@ -280,7 +290,25 @@ function threadPinProvider(request, config) {
280
290
  catch {
281
291
  return null;
282
292
  }
283
- return config.providerSessionPins.find((pin) => pin.thread_id === threadId)?.provider_id ?? null;
293
+ return pins.find((pin) => pin.thread_id === threadId) ?? null;
294
+ }
295
+ function threadPinProvider(request, config) {
296
+ return threadPin(request, config.providerSessionPins)?.provider_id ?? null;
297
+ }
298
+ export function pinnedPublicModel(threadId, config) {
299
+ if (!threadId)
300
+ return null;
301
+ return threadPin({ session_id: threadId }, config.providerSessionPins)?.public_model ?? null;
302
+ }
303
+ const RESPONSES_PATH_PREFIXES = ['/backend-api/codex/responses', '/api/v1/responses', '/v1/responses'];
304
+ export function isResponsesFamilyPath(pathname) {
305
+ return RESPONSES_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
306
+ }
307
+ export function threadRouteMove(request, route, config) {
308
+ if (!route.session_pin)
309
+ return null;
310
+ const previous = threadPin(request, config.providerSessionPins);
311
+ return previous && previous.provider_id !== route.provider_id ? { from: previous.provider_id, to: route.provider_id } : null;
284
312
  }
285
313
  export function assertDesktopBridgeRouteContext(request, config) {
286
314
  const resolver = config.resolveRequestRoute || resolveBridgeRequestRoute;
@@ -295,8 +323,16 @@ export function assertDesktopBridgeRouteContext(request, config) {
295
323
  && error.code === 'catalog_model_route_missing') {
296
324
  const model = canonicalizeBridgeModelId(request.public_model) || '';
297
325
  const live = model ? policy.model_routes[model] : undefined;
326
+ const pin = threadPin(request, config.providerSessionPins);
327
+ const responses = isResponsesFamilyPath(request.pathname);
328
+ if (pin && pin.provider_id !== BRIDGE_OFFICIAL_ROUTE_ID && responses) {
329
+ assertOpenRouterOnlyRoute(request, officialRouteContext(model, policy), config);
330
+ throw error;
331
+ }
298
332
  if (!live || live.provider_id === BRIDGE_OFFICIAL_ROUTE_ID) {
299
- route = officialRouteContext(model, policy, live?.upstream_model);
333
+ const sessionId = model && responses && request.session_id ? canonicalSessionId(request.session_id) : null;
334
+ const target = { provider_id: BRIDGE_OFFICIAL_ROUTE_ID, upstream_model: live?.upstream_model || model };
335
+ route = officialRouteContext(model, policy, live?.upstream_model, sessionId ? mintSessionPin(sessionId, target, model, policy, pin) : null);
300
336
  }
301
337
  else
302
338
  throw error;
@@ -315,8 +351,7 @@ export function assertDesktopBridgeRouteContext(request, config) {
315
351
  if (route.catalog_generation !== policy.catalog_generation || route.route_policy_generation !== policy.policy_generation) {
316
352
  throw new DesktopBridgeError('session_pin_route_unavailable');
317
353
  }
318
- if (route.session_pin)
319
- throw new DesktopBridgeError('bridge_session_pin_invalid');
354
+ assertRouteSessionPin(request, route, false);
320
355
  return route;
321
356
  }
322
357
  const existingPin = request.session_id ? config.providerSessionPins.find((pin) => pin.thread_id === request.session_id && pin.public_model === route.public_model
@@ -330,21 +365,7 @@ export function assertDesktopBridgeRouteContext(request, config) {
330
365
  if (route.catalog_generation !== policy.catalog_generation || route.route_policy_generation !== policy.policy_generation) {
331
366
  throw new DesktopBridgeError('session_pin_route_unavailable');
332
367
  }
333
- if (request.session_id) {
334
- const sessionId = canonicalSessionId(request.session_id);
335
- if (!route.session_pin
336
- || route.session_pin.thread_id !== sessionId
337
- || route.session_pin.provider_id !== route.provider_id
338
- || route.session_pin.public_model !== route.public_model
339
- || route.session_pin.upstream_model !== route.upstream_model
340
- || route.session_pin.catalog_generation !== route.catalog_generation
341
- || route.session_pin.route_policy_generation !== route.route_policy_generation) {
342
- throw new DesktopBridgeError('bridge_session_pin_invalid');
343
- }
344
- }
345
- else if (route.session_pin) {
346
- throw new DesktopBridgeError('bridge_session_pin_invalid');
347
- }
368
+ assertRouteSessionPin(request, route, true);
348
369
  const provider = config.providers[route.provider_id];
349
370
  if (!provider || !provider.enabled)
350
371
  throw new DesktopBridgeError('bridge_provider_route_unavailable');
@@ -358,7 +379,28 @@ export function assertDesktopBridgeRouteContext(request, config) {
358
379
  }
359
380
  return route;
360
381
  }
361
- export async function resolveAndBindDesktopBridgeRouteContext(request, config) {
382
+ function assertRouteSessionPin(request, route, required) {
383
+ if (!request.session_id) {
384
+ if (route.session_pin)
385
+ throw new DesktopBridgeError('bridge_session_pin_invalid');
386
+ return;
387
+ }
388
+ if (!route.session_pin) {
389
+ if (required)
390
+ throw new DesktopBridgeError('bridge_session_pin_invalid');
391
+ return;
392
+ }
393
+ const sessionId = canonicalSessionId(request.session_id);
394
+ if (route.session_pin.thread_id !== sessionId
395
+ || route.session_pin.provider_id !== route.provider_id
396
+ || route.session_pin.public_model !== route.public_model
397
+ || route.session_pin.upstream_model !== route.upstream_model
398
+ || route.session_pin.catalog_generation !== route.catalog_generation
399
+ || route.session_pin.route_policy_generation !== route.route_policy_generation) {
400
+ throw new DesktopBridgeError('bridge_session_pin_invalid');
401
+ }
402
+ }
403
+ export async function resolveAndBindDesktopBridgeRouteContext(request, config, beforeBind) {
362
404
  const pinsRead = config.providerSessionPins;
363
405
  let steady = null;
364
406
  try {
@@ -368,13 +410,14 @@ export async function resolveAndBindDesktopBridgeRouteContext(request, config) {
368
410
  steady = null;
369
411
  }
370
412
  const steadyPin = steady?.session_pin;
371
- if (steady && !steadyPin)
372
- return steady;
373
413
  const persisted = steadyPin ? pinsRead.find((entry) => entry.thread_id === steadyPin.thread_id) : undefined;
374
- if (steady && steadyPin && persisted && sameSessionPin(persisted, steadyPin))
414
+ if (steady && (!steadyPin || (persisted && sameSessionPin(persisted, steadyPin)))) {
415
+ beforeBind?.(steady);
375
416
  return steady;
417
+ }
376
418
  return withSessionPinMutation(config, async () => {
377
419
  const route = steady && config.providerSessionPins === pinsRead ? steady : assertDesktopBridgeRouteContext(request, config);
420
+ beforeBind?.(route);
378
421
  const pin = route.session_pin;
379
422
  if (!pin)
380
423
  return route;
@@ -418,7 +461,8 @@ function sameSessionPin(left, right) {
418
461
  && left.public_model === right.public_model
419
462
  && left.upstream_model === right.upstream_model
420
463
  && left.catalog_generation === right.catalog_generation
421
- && left.route_policy_generation === right.route_policy_generation;
464
+ && left.route_policy_generation === right.route_policy_generation
465
+ && left.handoff_from === right.handoff_from;
422
466
  }
423
467
  export function canonicalSessionId(value) {
424
468
  const sessionId = typeof value === 'string' ? value.trim() : '';
@@ -634,15 +678,17 @@ function assertRegistryAndPolicy(config, registry) {
634
678
  }
635
679
  }
636
680
  const pinIds = new Set();
681
+ const pinTargets = [...ids, BRIDGE_OFFICIAL_ROUTE_ID];
637
682
  for (const pin of config.providerSessionPins) {
638
683
  const keys = Object.keys(pin);
639
684
  if (keys.some((key) => ![
640
685
  'thread_id', 'provider_id', 'public_model', 'upstream_model',
641
- 'catalog_generation', 'route_policy_generation', 'created_at',
686
+ 'catalog_generation', 'route_policy_generation', 'created_at', 'handoff_from',
642
687
  ].includes(key))
643
688
  || canonicalSessionId(pin.thread_id) !== pin.thread_id
644
689
  || pinIds.has(pin.thread_id)
645
- || !ids.includes(pin.provider_id)
690
+ || !pinTargets.includes(pin.provider_id)
691
+ || (pin.handoff_from !== undefined && (!pinTargets.includes(pin.handoff_from) || pin.handoff_from === pin.provider_id))
646
692
  || canonicalizeBridgeModelId(pin.public_model) !== pin.public_model
647
693
  || normalizeBridgeUpstreamModelId(pin.upstream_model) !== pin.upstream_model
648
694
  || !pin.catalog_generation
@@ -6,7 +6,8 @@ import { createDesktopBridgeRejectionLogger } from './rejection-log.js';
6
6
  import { OPENROUTER_ONLY_REFUSAL_CODES } from './exclusive-provider-guard.js';
7
7
  import { assertAllowedOrigin, assertAllowedPath, assertLoopbackPeer, assertLoopbackListenHost, assertWebSocketUpgrade, prepareDesktopBridgeConfig, safeBridgeErrorCode, validatePreparedDesktopBridgeConfig, } from './security.js';
8
8
  import { createDesktopBridgePublicState, desktopBridgeListenOrigin, desktopBridgeStatePath, refreshDesktopBridgeState, removeDesktopBridgeStateIfOwned, writeDesktopBridgeState, } from './state.js';
9
- import { DesktopBridgeError, DesktopBridgeRequestBodyTooLargeError } from './types.js';
9
+ import { DesktopBridgeError, DesktopBridgeRequestBodyTooLargeError, isDesktopBridgeRoutingConflict } from './types.js';
10
+ import { ProviderHandoffRefusedError, providerHandoffRefusalBody } from './provider-handoff.js';
10
11
  import { PACKAGE_VERSION } from '../../version.js';
11
12
  import { DESKTOP_BRIDGE_CLIENT_PATH_PREFIX, DESKTOP_BRIDGE_DIAGNOSTIC_HEALTH_PATH, DESKTOP_BRIDGE_DIAGNOSTIC_PATH, DESKTOP_BRIDGE_DIAGNOSTIC_PROTOCOL, DESKTOP_BRIDGE_IMAGEGEN_PATH } from './types.js';
12
13
  import { handleDesktopBridgeImagegen } from './imagegen-endpoint.js';
@@ -94,7 +95,9 @@ function rejectionStatus(code) {
94
95
  return 404;
95
96
  if (code === 'bridge_request_capacity_exhausted')
96
97
  return 503;
97
- if (code === 'bridge_session_pin_persist_failed' || code.startsWith('bridge_upstream_'))
98
+ if (isDesktopBridgeRoutingConflict(code))
99
+ return 409;
100
+ if (code.startsWith('bridge_upstream_'))
98
101
  return 502;
99
102
  if (code.includes('origin') || code.includes('peer') || code.includes('loopback') || code.includes('capability'))
100
103
  return 403;
@@ -134,6 +137,11 @@ function writeBridgeRejection(res, error, req) {
134
137
  res.destroy(error instanceof Error ? error : undefined);
135
138
  return;
136
139
  }
140
+ if (error instanceof ProviderHandoffRefusedError) {
141
+ res.writeHead(400, { 'content-type': 'application/json', 'cache-control': 'no-store', connection: 'close' });
142
+ res.end(providerHandoffRefusalBody(error));
143
+ return;
144
+ }
137
145
  const code = rejectedCode;
138
146
  res.writeHead(rejectionStatus(code), {
139
147
  'content-type': 'application/json',
@@ -22,6 +22,9 @@ export class DesktopBridgeError extends Error {
22
22
  this.code = code;
23
23
  }
24
24
  }
25
+ export function isDesktopBridgeRoutingConflict(code) {
26
+ return code.startsWith('catalog_') || code.startsWith('session_') || code.includes('route_');
27
+ }
25
28
  export const DEFAULT_DESKTOP_BRIDGE_MAX_REQUEST_BODY_BYTES = 128 * 1024 * 1024;
26
29
  export class DesktopBridgeRequestBodyTooLargeError extends DesktopBridgeError {
27
30
  maximumBytes;
@@ -9,6 +9,7 @@ import { OPENROUTER_ONLY_REFUSAL_CODES, openRouterOnlyEnabled } from './exclusiv
9
9
  import { desktopBridgeOfficialPassthroughEnabled, ensureDesktopBridgeRemoteTarget, isUnreachableUpstreamError, refreshDesktopBridgeRemoteTarget, resolveAndBindDesktopBridgeRouteContext, resolveCodexSessionIdentity, resolveDesktopBridgeTarget, safeBridgeErrorCode, singleBridgeHeader, canonicalSessionId } from './security.js';
10
10
  import { desktopBridgeListenOrigin } from './state.js';
11
11
  import { forwardResponsesWebSocket, isResponsesWebSocketRequest } from './responses-websocket.js';
12
+ import { admitCodexLbTurnState } from './codex-lb-turn-state.js';
12
13
  import { DESKTOP_BRIDGE_DIAGNOSTIC_PROTOCOL, DesktopBridgeError, } from './types.js';
13
14
  const MAX_HEAD = 64 * 1024;
14
15
  const REDACTED_RESPONSE_HEADERS = new Set(['authorization', 'cookie', 'proxy-authenticate', 'proxy-authorization', 'set-cookie', 'x-api-key', 'x-codex-lb-api-key']);
@@ -203,6 +204,8 @@ export async function forwardWebSocket(req, client, head, config, authenticatedL
203
204
  const headers = official
204
205
  ? buildOfficialPassthroughWebSocketHeaders(req.headers, target.host)
205
206
  : buildProviderWebSocketHeaders(req.headers, { providerId: provider.provider_id, authTransport: provider.auth_transport, credential: credential }, target.host);
207
+ if (provider?.provider_id === 'codex-lb')
208
+ admitCodexLbTurnState(headers, route.session_pin?.thread_id ?? null, credential.fingerprint);
206
209
  upstream.write([`${req.method || 'GET'} ${target.pathname}${target.search} HTTP/1.1`, ...serializeHeaders(headers), '', ''].join('\r\n'));
207
210
  if (head.length)
208
211
  upstream.write(head);
@@ -1,4 +1,6 @@
1
1
  import { readText, writeJsonAtomic } from '../../fsx.js';
2
+ import { repairManagedCodexLbClientSelection } from '../../../cli/install-helpers-codex-lb-config.js';
3
+ import { safeWriteCodexConfigToml } from '../../codex-runtime/codex-desktop-config-policy.js';
2
4
  import { readTopLevelTomlString } from '../../codex-app/codex-model-catalog.js';
3
5
  import { codexRestartBlockers, maybeRestartRunningCodexApp } from '../../codex-app/codex-app-restart-policy.js';
4
6
  import { BRIDGE_MODEL_SELECTION_SCHEMA, MAX_SELECTED_OPENROUTER_MODELS, bridgeAvailableModelsPath, pruneSelection, readBridgeModelSelectionState, writeBridgeModelSelection } from '../combined-catalog/model-selection.js';
@@ -24,8 +26,19 @@ export async function syncCatalog(options) {
24
26
  : {};
25
27
  return commandResult('catalog.sync', result.ok === true, status, { catalog_sync: result }, result.ok === true ? [] : stringArray(activation.blockers), options);
26
28
  }
29
+ async function repairCodexLbClientSelection(configPath) {
30
+ const current = await readText(configPath, '');
31
+ const next = repairManagedCodexLbClientSelection(current);
32
+ if (next === current)
33
+ return null;
34
+ const write = await safeWriteCodexConfigToml(configPath, current, next, 'codex-lb-client-provider-repair', { verifyUnchangedBeforeWrite: true });
35
+ return write.ok ? null : `codex_lb_client_provider_repair_refused:${write.status}`;
36
+ }
27
37
  export async function syncCatalogInternal(options, behavior = {}) {
28
38
  const paths = controllerPaths(options);
39
+ const repair = await repairCodexLbClientSelection(paths.configPath);
40
+ if (repair)
41
+ return blockedSync(inspectHistoricalDesktopBridgeIntent(''), [repair]);
29
42
  const historicalIntent = inspectHistoricalDesktopBridgeIntent(await readText(paths.configPath, ''));
30
43
  if (historicalIntent.blockers.length > 0)
31
44
  return blockedSync(historicalIntent, historicalIntent.blockers);
@@ -1,6 +1,3 @@
1
- import { bindCodexClientProvider } from '../../../cli/install-helpers-codex-lb-config.js';
2
- import { safeWriteCodexConfigToml } from '../../codex-runtime/codex-desktop-config-policy.js';
3
- import { readText } from '../../fsx.js';
4
1
  import { testOpenRouterConnection } from '../../providers/openrouter/openrouter-account.js';
5
2
  import { openRouterSecretPaths } from '../../providers/openrouter/openrouter-secret-store.js';
6
3
  import { codexLbEnvPath, codexLbMetadataPath, readCodexLbModelCatalog } from '../codex-lb-env.js';
@@ -111,12 +108,6 @@ export async function setProviderState(providerId, enabled, operation, options)
111
108
  });
112
109
  }
113
110
  }
114
- if (providerId === 'codex-lb') {
115
- const current = await readText(paths.configPath, '');
116
- const next = bindCodexClientProvider(current, enabled ? 'codex-lb' : 'openai');
117
- if (next !== current)
118
- await safeWriteCodexConfigToml(paths.configPath, current, next, 'codex-lb-client-provider');
119
- }
120
111
  const status = await desktopBridgeStatusV3(options);
121
112
  return commandResult(operation, true, status, { provider_id: providerId, enabled }, [], options);
122
113
  }
@@ -313,23 +313,17 @@ export async function resolveDesktopBridgeRuntimeConfig(options = {}) {
313
313
  if (!officialOnly && !providerRouteIds.some((id) => credentials.registry.providers[id].credential_state === 'ready'))
314
314
  throw new Error('desktop_bridge_provider_credentials_unavailable');
315
315
  const persistProviderSessionPins = options.persistProviderSessionPins
316
- || ((pins) => persistDesktopBridgeSessionPins(paths.settings_path, settings, pins));
316
+ || ((pins) => persistDesktopBridgeSessionPins(paths.settings_path, pins));
317
317
  const openRouterOnly = resolveDesktopBridgeOpenRouterOnly({ home, ...(options.env ? { env: options.env } : {}) });
318
318
  const config = { providerRegistry: settings.provider_registry, routePolicy: settings.route_policy, providerSessionPins: settings.provider_session_pins, ...(options.resolveRequestRoute ? { resolveRequestRoute: options.resolveRequestRoute } : {}), persistProviderSessionPins, resolveProviderCredential: credentials.resolver, clientCapabilitySha256: settings.client_capability_sha256, listenHost: settings.listen_host, listenPort: settings.listen_port, allowedPathPrefixes: DESKTOP_BRIDGE_ALLOWED_PATH_PREFIXES, allowedOrigins: settings.allowed_origins, connectTimeoutMs: settings.connect_timeout_ms, idleTimeoutMs: settings.idle_timeout_ms, officialPassthrough: settings.official_passthrough.enabled ? { baseUrl: settings.official_passthrough.base_url } : null, ...(openRouterOnly ? { openRouterOnly } : {}) };
319
319
  const primary = credentials.sources['codex-lb'] || credentials.sources.openrouter;
320
320
  return { config, settings, loaded_env: credentials.loaded, credential_source: primary || null, credential_sources: credentials.sources, paths };
321
321
  }
322
- async function persistDesktopBridgeSessionPins(file, expected, pins) {
322
+ async function persistDesktopBridgeSessionPins(file, pins) {
323
323
  await withFileLock(settingsLockOptions(file), async () => {
324
324
  const current = await readDesktopBridgeServiceSettings(file);
325
- if (!current
326
- || current.listen_host !== expected.listen_host
327
- || current.listen_port !== expected.listen_port
328
- || current.provider_registry.generation !== expected.provider_registry.generation
329
- || current.route_policy.policy_generation !== expected.route_policy.policy_generation
330
- || current.route_policy.catalog_generation !== expected.route_policy.catalog_generation) {
331
- throw new DesktopBridgeError('session_pin_route_unavailable');
332
- }
325
+ if (!current)
326
+ return;
333
327
  await writeDesktopBridgeServiceSettingsUnlocked(file, {
334
328
  ...current,
335
329
  provider_session_pins: [...pins],
@@ -701,8 +695,9 @@ function validateProviderSessionPins(value) {
701
695
  const pin = value;
702
696
  const allowed = new Set([
703
697
  'thread_id', 'provider_id', 'public_model', 'upstream_model',
704
- 'catalog_generation', 'route_policy_generation', 'created_at'
698
+ 'catalog_generation', 'route_policy_generation', 'created_at', 'handoff_from'
705
699
  ]);
700
+ const target = (value) => value === 'codex-lb' || value === 'openrouter' || value === BRIDGE_OFFICIAL_ROUTE_ID;
706
701
  const threadId = typeof pin.thread_id === 'string' ? pin.thread_id.trim() : '';
707
702
  if (Object.keys(pin).some((key) => !allowed.has(key))
708
703
  || !threadId
@@ -710,7 +705,8 @@ function validateProviderSessionPins(value) {
710
705
  || threadId.length > 256
711
706
  || !/^[A-Za-z0-9._:/-]+$/.test(threadId)
712
707
  || seen.has(threadId)
713
- || (pin.provider_id !== 'codex-lb' && pin.provider_id !== 'openrouter')
708
+ || !target(pin.provider_id)
709
+ || (pin.handoff_from !== undefined && (!target(pin.handoff_from) || pin.handoff_from === pin.provider_id))
714
710
  || canonicalizeBridgeModelId(pin.public_model) !== pin.public_model
715
711
  || normalizeBridgeUpstreamModelId(pin.upstream_model) !== pin.upstream_model
716
712
  || typeof pin.catalog_generation !== 'string'
@@ -729,7 +725,8 @@ function validateProviderSessionPins(value) {
729
725
  upstream_model: pin.upstream_model,
730
726
  catalog_generation: pin.catalog_generation,
731
727
  route_policy_generation: pin.route_policy_generation,
732
- created_at: pin.created_at
728
+ created_at: pin.created_at,
729
+ ...(pin.handoff_from === undefined ? {} : { handoff_from: pin.handoff_from })
733
730
  };
734
731
  });
735
732
  }
@@ -23,7 +23,7 @@ export function resolveBridgeRequestRoute(request, policy, options) {
23
23
  return blocked(base, 'catalog_route_index_stale');
24
24
  }
25
25
  const threadPin = request.thread_id ? findSessionPin(options.session_pins, request.thread_id) : null;
26
- const pin = threadPin && canonicalizeBridgeModelId(threadPin.public_model) === model ? threadPin : null;
26
+ const pin = threadPin && threadPin.provider_id !== 'openai' && canonicalizeBridgeModelId(threadPin.public_model) === model ? threadPin : null;
27
27
  const pinAffinity = pin ? sessionPinAffinity(pin, policy, options.route_index, options.registry) : null;
28
28
  if (pinAffinity === 'unprovable')
29
29
  return blocked(base, 'session_pin_route_unavailable');
@@ -197,7 +197,6 @@ export async function safeWriteCodexConfigToml(configPath, current, next, tag =
197
197
  configPath,
198
198
  before: String(current || ''),
199
199
  cause: tag,
200
- removeTopLevelModeLocks: true,
201
200
  ...(opts.preserveFastUiKeys === undefined ? {} : { preserveFastUiKeys: opts.preserveFastUiKeys }),
202
201
  ...(opts.verifyUnchangedBeforeWrite === undefined ? {} : { verifyUnchangedBeforeWrite: opts.verifyUnchangedBeforeWrite }),
203
202
  ...(opts.expectedBeforeExists === undefined ? {} : { expectedBeforeExists: opts.expectedBeforeExists }),
@@ -90,7 +90,7 @@ export async function inspectAgentBridgeHostCapabilities(root, dependencies, pro
90
90
  export function usage() {
91
91
  return [
92
92
  'Usage: sks agent-bridge setup [--trusted-project] [--json]',
93
- ' sks agent-bridge async --prompt "task" [--tools status,stats] [--json]',
93
+ ' sks agent-bridge async --prompt "task" [--tools status,search] [--json]',
94
94
  '',
95
95
  'setup: register read-only SKS tools with an external agent host.',
96
96
  'async: run native Astra Async tool calling through the registered Codex-LB bridge.',