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
@@ -3,13 +3,6 @@ function isListed(model) {
3
3
  const visibility = String(model.visibility || 'list').toLowerCase();
4
4
  return visibility !== 'hide' && visibility !== 'hidden';
5
5
  }
6
- function escapeRegExp(text) {
7
- return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
8
- }
9
- function displayNamePattern(displayName) {
10
- const body = escapeRegExp(displayName.trim()).replace(/\\?-|\s+/g, '[-\\s]');
11
- return new RegExp(`(?<![\\w-])${body}(?![\\w-])`, 'gi');
12
- }
13
6
  export function pinCatalogToLatestGenerations(models) {
14
7
  const newest = new Map();
15
8
  for (const model of models) {
@@ -20,34 +13,14 @@ export function pinCatalogToLatestGenerations(models) {
20
13
  if (!best || compareModelVersions(id.version, parseGptModelId(best.public_id).version) > 0)
21
14
  newest.set(id.family, model);
22
15
  }
23
- const byId = new Map(models.map((model) => [model.public_id, model]));
24
16
  return models.map((model) => {
25
17
  const id = parseGptModelId(model.public_id);
26
- let next = model;
27
- if (id && isListed(model)) {
28
- const best = newest.get(id.family);
29
- if (best && compareModelVersions(parseGptModelId(best.public_id).version, id.version) > 0)
30
- next = { ...next, visibility: 'hide' };
31
- }
32
- const upgrade = model.upgrade;
33
- const target = upgrade && typeof upgrade === 'object' ? String(upgrade.model || '') : '';
34
- const targetId = parseGptModelId(target);
35
- const replacement = targetId ? newest.get(targetId.family) : undefined;
36
- if (targetId && replacement && replacement.public_id !== target
37
- && compareModelVersions(parseGptModelId(replacement.public_id).version, targetId.version) > 0) {
38
- const old = byId.get(target);
39
- const markdown = upgrade.migration_markdown;
40
- next = {
41
- ...next,
42
- upgrade: {
43
- ...upgrade,
44
- model: replacement.public_id,
45
- ...(typeof markdown === 'string' && old?.display_name
46
- ? { migration_markdown: markdown.replace(displayNamePattern(old.display_name), () => replacement.display_name) }
47
- : {})
48
- }
49
- };
50
- }
51
- return next;
18
+ if (!id || !isListed(model))
19
+ return model;
20
+ const best = newest.get(id.family);
21
+ if (!best || compareModelVersions(parseGptModelId(best.public_id).version, id.version) <= 0)
22
+ return model;
23
+ const { upgrade: _retired, ...rest } = model;
24
+ return { ...rest, visibility: 'hide' };
52
25
  });
53
26
  }
@@ -130,7 +130,7 @@ function normalizeCodexLbBridgeCatalogModels(payload, sourceCatalogGeneration) {
130
130
  ...codexModelInfoFields(publicId, row, {
131
131
  tools: row.supports_tools === true || row.supports_tool_choice === true
132
132
  }),
133
- ...(typeof row.priority === 'number' ? {} : { priority: 100 })
133
+ ...(typeof row.priority === 'number' ? {} : { priority: CODEX_LB_DEFAULT_PRIORITY })
134
134
  });
135
135
  }
136
136
  catch (error) {
@@ -164,6 +164,8 @@ export const OPENROUTER_REASONING_LEVELS = [
164
164
  { effort: 'xhigh', description: 'Extra high reasoning depth for complex problems' }
165
165
  ];
166
166
  export const OPENROUTER_DEFAULT_REASONING_LEVEL = 'medium';
167
+ export const CODEX_LB_DEFAULT_PRIORITY = 500;
168
+ export const OPENROUTER_PRIORITY_BASE = 1000;
167
169
  function openRouterReasoningLevels() {
168
170
  return OPENROUTER_REASONING_LEVELS.map((level) => ({ ...level }));
169
171
  }
@@ -0,0 +1,35 @@
1
+ const MAX_THREADS = 4_096;
2
+ const MAX_VALUES_PER_THREAD = 8;
3
+ const issued = new Map();
4
+ function scope(threadId, keyFingerprint) {
5
+ return `${keyFingerprint}\u0000${threadId}`;
6
+ }
7
+ function headerValues(value) {
8
+ const values = Array.isArray(value) ? value : value === undefined ? [] : [String(value)];
9
+ return values.map((entry) => entry.trim()).filter(Boolean);
10
+ }
11
+ export function rememberCodexLbTurnState(threadId, keyFingerprint, headers) {
12
+ const values = headerValues(headers['x-codex-turn-state']);
13
+ if (!threadId || !values.length)
14
+ return;
15
+ const key = scope(threadId, keyFingerprint);
16
+ const kept = (issued.get(key) ?? []).filter((value) => !values.includes(value));
17
+ issued.delete(key);
18
+ issued.set(key, [...kept, ...values].slice(-MAX_VALUES_PER_THREAD));
19
+ while (issued.size > MAX_THREADS)
20
+ issued.delete(issued.keys().next().value);
21
+ }
22
+ export function admitCodexLbTurnState(headers, threadId, keyFingerprint) {
23
+ const values = headerValues(headers['x-codex-turn-state']);
24
+ if (!values.length) {
25
+ delete headers['x-codex-turn-state'];
26
+ return;
27
+ }
28
+ const known = threadId ? issued.get(scope(threadId, keyFingerprint)) : undefined;
29
+ if (values.length === 1 && known?.includes(values[0]))
30
+ return;
31
+ delete headers['x-codex-turn-state'];
32
+ }
33
+ export function forgetCodexLbTurnStates() {
34
+ issued.clear();
35
+ }
@@ -43,6 +43,9 @@ export function decodeBridgeCompaction(encrypted) {
43
43
  return null;
44
44
  }
45
45
  }
46
+ export function isNativeCompactionItem(item) {
47
+ return isObject(item) && COMPACTION_ITEM_TYPES.has(String(item.type)) && decodeBridgeCompaction(item.encrypted_content) === null;
48
+ }
46
49
  function summaryMessage(summary) {
47
50
  return { type: 'message', role: 'user', content: [{ type: 'input_text', text: `${CODEX_SUMMARY_PREFIX}\n${summary}` }] };
48
51
  }
@@ -7,9 +7,10 @@ const REQUEST_HEADER_ALLOWLIST = new Set([
7
7
  ]);
8
8
  const CODEX_LOCAL_HEADERS = new Set([
9
9
  'thread-id', 'thread_id', 'session-id', 'session_id', 'x-client-request-id',
10
- 'x-codex-installation-id', 'x-codex-turn-metadata', 'x-codex-window-id',
10
+ 'x-codex-installation-id', 'x-codex-turn-metadata', 'x-codex-window-id', 'x-codex-turn-state',
11
11
  'originator', 'openai-beta',
12
12
  ]);
13
+ const CLIENT_IDENTITY_HEADERS = new Set(['authorization', 'cookie', 'chatgpt-account-id']);
13
14
  const NEVER_FORWARD_FROM_CLIENT = new Set([
14
15
  'authorization', 'cookie', 'forwarded', 'proxy-authorization', 'x-api-key', 'x-codex-lb-api-key',
15
16
  'x-forwarded-for', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-proto', 'x-real-ip',
@@ -39,14 +40,19 @@ function injectCredential(result, providerId, transport, credential) {
39
40
  result.authorization = `Bearer ${credential.value}`;
40
41
  }
41
42
  export function buildProviderUpstreamHeaders(inbound, context, upstreamHost) {
43
+ if (context.providerId === 'codex-lb') {
44
+ const result = buildOfficialPassthroughHeaders(inbound, upstreamHost);
45
+ for (const name of CLIENT_IDENTITY_HEADERS)
46
+ delete result[name];
47
+ injectCredential(result, context.providerId, context.authTransport, context.credential);
48
+ return result;
49
+ }
42
50
  const result = {};
43
51
  for (const [rawName, rawValue] of Object.entries(inbound)) {
44
52
  if (rawValue === undefined)
45
53
  continue;
46
54
  const name = rawName.toLowerCase();
47
- const providerAllowed = (context.providerId === 'openrouter' && OPENROUTER_CLIENT_HEADERS.has(name))
48
- || (context.providerId === 'codex-lb' && CODEX_LOCAL_HEADERS.has(name));
49
- if (!REQUEST_HEADER_ALLOWLIST.has(name) && !providerAllowed)
55
+ if (!REQUEST_HEADER_ALLOWLIST.has(name) && !(context.providerId === 'openrouter' && OPENROUTER_CLIENT_HEADERS.has(name)))
50
56
  continue;
51
57
  result[name] = rawValue;
52
58
  }
@@ -2,16 +2,19 @@ import http, {} from 'node:http';
2
2
  import https from 'node:https';
3
3
  import zlib from 'node:zlib';
4
4
  import { pipeline } from 'node:stream/promises';
5
- import { BRIDGE_OFFICIAL_ROUTE_ID } from '../bridge-contracts.js';
5
+ import { BRIDGE_OFFICIAL_ROUTE_ID, BRIDGE_REMOTE_COMPACTION } from '../bridge-contracts.js';
6
6
  import { buildOfficialPassthroughHeaders, buildProviderUpstreamHeaders, rewriteResponseHeaders } from './header-policy.js';
7
7
  import { createDesktopBridgeRejectionLogger } from './rejection-log.js';
8
- import { OPENROUTER_ONLY_REFUSAL_CODES, openRouterOnlyEnabled } from './exclusive-provider-guard.js';
9
- import { ensureDesktopBridgeRemoteTarget, isNoRouteUpstreamError, isUnreachableUpstreamError, refreshDesktopBridgeRemoteTarget, resolveAndBindDesktopBridgeRouteContext, resolveCodexSessionIdentity, resolveDesktopBridgeTarget, safeBridgeErrorCode, singleBridgeHeader } from './security.js';
8
+ import { OPENROUTER_ONLY_REFUSAL_CODES } from './exclusive-provider-guard.js';
9
+ import { ensureDesktopBridgeRemoteTarget, isNoRouteUpstreamError, isResponsesFamilyPath, isUnreachableUpstreamError, pinnedPublicModel, refreshDesktopBridgeRemoteTarget, resolveAndBindDesktopBridgeRouteContext, resolveCodexSessionIdentity, resolveDesktopBridgeTarget, safeBridgeErrorCode, singleBridgeHeader, threadRouteMove } from './security.js';
10
+ import { admitCodexLbTurnState, forgetCodexLbTurnStates, rememberCodexLbTurnState } from './codex-lb-turn-state.js';
11
+ import { ProviderHandoffRefusedError, assertProviderHandoffAllowed, providerHandoffRefusalBody, stripProviderBoundItems, } from './provider-handoff.js';
10
12
  import { desktopBridgeListenOrigin } from './state.js';
11
13
  import { buildCompactionSummaryRequest, compactEndpointResult, compactionCreatedEvent, compactionFailedEvent, compactionResponseEvents, expandBridgeCompactionItems, newCompactionResponseId, parseProviderSummary, requestsRemoteCompaction, safeUpstreamErrorId, sseEvent, summaryFailure, summaryWithinBounds, } from './compaction-adapter.js';
12
- import { isAdvisableEventStream, modelCapacityAdvisingSse } from './capacity-retry-advice.js';
13
- import { DEFAULT_DESKTOP_BRIDGE_MAX_REQUEST_BODY_BYTES, DesktopBridgeError, DesktopBridgeRequestBodyTooLargeError } from './types.js';
14
+ import { MODEL_CAPACITY_ERROR_CODE, MODEL_CAPACITY_RETRY_AFTER_SECONDS, isAdvisableEventStream, modelCapacityAdvisingSse } from './capacity-retry-advice.js';
15
+ import { DEFAULT_DESKTOP_BRIDGE_MAX_REQUEST_BODY_BYTES, DesktopBridgeError, DesktopBridgeRequestBodyTooLargeError, isDesktopBridgeRoutingConflict } from './types.js';
14
16
  const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
17
+ const NATIVE_COMPACTION_IDLE_FLOOR_MS = 300_000;
15
18
  function decodeBridgeRequestBody(body, encoding, maximum) {
16
19
  const options = { maxOutputLength: maximum };
17
20
  try {
@@ -61,11 +64,10 @@ async function reencodeLikeClient(plain, encoding) {
61
64
  return new Promise((resolve) => compress(plain, (error, result) => resolve(error ? null : result)));
62
65
  }
63
66
  const RESPONSES_PATHS = ['/backend-api/codex/responses', '/api/v1/responses', '/v1/responses'];
64
- function modelBodyKind(req, pathname, config) {
67
+ function modelBodyKind(req, pathname) {
65
68
  if (RESPONSES_PATHS.includes(pathname))
66
69
  return req.method === 'POST' ? 'responses' : null;
67
- return openRouterOnlyEnabled(config) && req.method === 'POST'
68
- && RESPONSES_PATHS.some((prefix) => pathname.startsWith(`${prefix}/`)) ? 'sub-endpoint' : null;
70
+ return req.method === 'POST' && RESPONSES_PATHS.some((prefix) => pathname.startsWith(`${prefix}/`)) ? 'sub-endpoint' : null;
69
71
  }
70
72
  function isCompactEndpoint(req, pathname) {
71
73
  return req.method === 'POST' && RESPONSES_PATHS.some((prefix) => pathname === `${prefix}/compact`);
@@ -105,7 +107,7 @@ export async function prepareDesktopBridgeRequest(req, config) {
105
107
  let contentEncodingStripped = false;
106
108
  let encoding = '';
107
109
  let encodedBody = null;
108
- const bodyKind = modelBodyKind(req, pathname, config);
110
+ const bodyKind = modelBodyKind(req, pathname);
109
111
  if (bodyKind) {
110
112
  const maximum = config.maxRequestBodyBytes ?? DEFAULT_DESKTOP_BRIDGE_MAX_REQUEST_BODY_BYTES;
111
113
  body = await readBoundedBody(req, maximum);
@@ -131,12 +133,19 @@ export async function prepareDesktopBridgeRequest(req, config) {
131
133
  body = decoded;
132
134
  }
133
135
  const headerModel = singleBridgeHeader(req.headers, 'x-sks-model');
134
- const model = typeof payload?.model === 'string' ? payload.model : headerModel;
135
136
  const sessionIdentity = resolveCodexSessionIdentity(req.headers, payload);
136
- const route = await resolveAndBindDesktopBridgeRouteContext({
137
+ const model = typeof payload?.model === 'string'
138
+ ? payload.model
139
+ : headerModel || (isResponsesFamilyPath(pathname) ? pinnedPublicModel(sessionIdentity.thread_id, config) : null);
140
+ const routeRequest = {
137
141
  public_model: String(model || ''), session_id: sessionIdentity.thread_id,
138
142
  pathname, transport: 'http', headers: req.headers, identity: sessionIdentity,
139
- }, config);
143
+ };
144
+ let move = null;
145
+ const route = await resolveAndBindDesktopBridgeRouteContext(routeRequest, config, (resolved) => {
146
+ move = threadRouteMove(routeRequest, resolved, config);
147
+ assertProviderHandoffAllowed(payload, move);
148
+ });
140
149
  let rewrite = false;
141
150
  if (payload && (bodyKind === 'responses' || typeof payload.model === 'string') && payload.model !== route.upstream_model) {
142
151
  payload.model = route.upstream_model;
@@ -144,14 +153,15 @@ export async function prepareDesktopBridgeRequest(req, config) {
144
153
  }
145
154
  if (expandBridgeCompactionItems(payload))
146
155
  rewrite = true;
156
+ if (route.session_pin?.handoff_from && stripProviderBoundItems(payload, Boolean(move)))
157
+ rewrite = true;
147
158
  if (payload && rewrite)
148
159
  body = Buffer.from(JSON.stringify(payload));
149
160
  const compaction = bodyKind === 'responses' && requestsRemoteCompaction(payload)
150
161
  ? 'trigger'
151
162
  : bodyKind === 'sub-endpoint' && isCompactEndpoint(req, pathname) ? 'endpoint' : null;
152
163
  let plainBody = null;
153
- const answeredByBridge = Boolean(compaction) && route.provider_id !== BRIDGE_OFFICIAL_ROUTE_ID;
154
- if (encodedBody && body && !answeredByBridge && keepsClientEncoding(route)) {
164
+ if (encodedBody && body && !answeredByBridge(compaction, route) && keepsClientEncoding(route)) {
155
165
  const upstreamBody = rewrite ? await reencodeLikeClient(body, encoding) : encodedBody;
156
166
  if (upstreamBody) {
157
167
  plainBody = body;
@@ -160,7 +170,10 @@ export async function prepareDesktopBridgeRequest(req, config) {
160
170
  }
161
171
  }
162
172
  const credential = route.provider_id === BRIDGE_OFFICIAL_ROUTE_ID ? null : await resolveCredential(config, route);
163
- return { body, route, credential, contentEncodingStripped, plainBody, compaction, payload };
173
+ return { body, route, credential, contentEncodingStripped, plainBody, compaction, payload, threadId: sessionIdentity.thread_id, move };
174
+ }
175
+ function answeredByBridge(compaction, route) {
176
+ return Boolean(compaction) && BRIDGE_REMOTE_COMPACTION[route.provider_id] === 'bridge_summary';
164
177
  }
165
178
  function connectTimeout(request, config) {
166
179
  request.once('socket', (socket) => {
@@ -191,8 +204,12 @@ function writeHttpBridgeError(res, error, req) {
191
204
  res.destroy(error instanceof Error ? error : undefined);
192
205
  return;
193
206
  }
194
- res.writeHead(code.startsWith('catalog_') || code.startsWith('session_') || code.includes('route_')
195
- || OPENROUTER_ONLY_REFUSAL_CODES.has(code) ? 409 : 502, {
207
+ if (error instanceof ProviderHandoffRefusedError) {
208
+ res.writeHead(400, { 'content-type': 'application/json', 'cache-control': 'no-store', connection: 'close' });
209
+ res.end(providerHandoffRefusalBody(error));
210
+ return;
211
+ }
212
+ res.writeHead(isDesktopBridgeRoutingConflict(code) || OPENROUTER_ONLY_REFUSAL_CODES.has(code) ? 409 : 502, {
196
213
  'content-type': 'application/json', 'cache-control': 'no-store', connection: 'close',
197
214
  });
198
215
  res.end(JSON.stringify({ error: { type: 'sks_bridge_error', code, message: code } }));
@@ -229,19 +246,32 @@ function redactedUpstreamClientMessage(statusCode, transient) {
229
246
  const UNREADABLE_BODY_HINT = /json|pars(?:e|ing)|decod|encod|compress|utf-?8/i;
230
247
  async function readRedactedUpstreamError(response) {
231
248
  let total = 0;
249
+ let complete = true;
232
250
  const chunks = [];
233
251
  for await (const raw of response) {
234
252
  const chunk = Buffer.isBuffer(raw) ? raw : Buffer.from(raw);
235
253
  total += chunk.length;
236
254
  if (total > MAX_UPSTREAM_ERROR_BODY_BYTES) {
237
255
  response.destroy();
256
+ complete = false;
238
257
  break;
239
258
  }
240
259
  chunks.push(chunk);
241
260
  }
242
261
  let upstreamCode = null;
243
262
  let upstreamType = null;
244
- const text = Buffer.concat(chunks).toString('utf8');
263
+ const raw = Buffer.concat(chunks);
264
+ const encoding = String(response.headers['content-encoding'] || '').trim().toLowerCase();
265
+ let decoded = complete ? raw : null;
266
+ if (decoded && encoding && encoding !== 'identity') {
267
+ try {
268
+ decoded = decodeBridgeRequestBody(decoded, encoding, 4 * MAX_UPSTREAM_ERROR_BODY_BYTES);
269
+ }
270
+ catch {
271
+ decoded = null;
272
+ }
273
+ }
274
+ const text = (decoded ?? raw).toString('utf8');
245
275
  try {
246
276
  const parsed = JSON.parse(text);
247
277
  upstreamCode = safeUpstreamErrorId(parsed?.error?.code) ?? safeUpstreamErrorId(parsed?.detail);
@@ -249,7 +279,21 @@ async function readRedactedUpstreamError(response) {
249
279
  }
250
280
  catch {
251
281
  }
252
- return { upstreamCode, upstreamType, unreadableBody: UNREADABLE_BODY_HINT.test(text.slice(0, 4096)) };
282
+ return {
283
+ upstreamCode,
284
+ upstreamType,
285
+ unreadableBody: UNREADABLE_BODY_HINT.test(text.slice(0, 4096)),
286
+ body: decoded,
287
+ };
288
+ }
289
+ function scrubUpstreamErrorBody(body, credential) {
290
+ let text = body.toString('utf8');
291
+ if (credential)
292
+ text = text.split(credential).join('[REDACTED]');
293
+ text = text
294
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/-]{8,}=*/gi, 'Bearer [REDACTED]')
295
+ .replace(/\bsk-[A-Za-z0-9_-]{16,}/g, '[REDACTED]');
296
+ return Buffer.from(text, 'utf8');
253
297
  }
254
298
  function buildRedactedUpstreamErrorBody(statusCode, upstreamCode, upstreamType, transient) {
255
299
  return Buffer.from(JSON.stringify({
@@ -284,6 +328,7 @@ export function destroyDesktopBridgeUpstreamAgents() {
284
328
  agent.destroy();
285
329
  upstreamAgents.clear();
286
330
  encodedBodyRefusals.clear();
331
+ forgetCodexLbTurnStates();
287
332
  }
288
333
  const STALE_CONNECTION_ERROR_CODES = new Set(['ECONNRESET', 'EPIPE', 'ECONNABORTED']);
289
334
  function isStalePooledSocketFailure(request, error) {
@@ -319,7 +364,7 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
319
364
  if (!official && !request.credential)
320
365
  throw new DesktopBridgeError('bridge_provider_credential_invalid');
321
366
  await ensureDesktopBridgeRemoteTarget(remote, config.remoteLookup);
322
- if (!official && request.compaction && request.payload) {
367
+ if (!official && request.compaction && answeredByBridge(request.compaction, request.route) && request.payload) {
323
368
  await answerCompactionWithProviderSummary(req, res, config, {
324
369
  kind: request.compaction,
325
370
  payload: request.payload,
@@ -341,6 +386,12 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
341
386
  : buildProviderUpstreamHeaders(req.headers, {
342
387
  providerId: provider.provider_id, authTransport: provider.auth_transport, credential: request.credential,
343
388
  }, target.host);
389
+ const codexLb = provider?.provider_id === 'codex-lb';
390
+ const threadId = request.threadId ?? null;
391
+ if (request.move)
392
+ delete headers['x-codex-turn-state'];
393
+ else if (codexLb)
394
+ admitCodexLbTurnState(headers, threadId, request.credential.fingerprint);
344
395
  if (request.body)
345
396
  headers['content-length'] = String(request.body.length);
346
397
  else
@@ -348,6 +399,7 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
348
399
  if (request.contentEncodingStripped)
349
400
  delete headers['content-encoding'];
350
401
  const agent = upstreamAgent(remote.secure, `${remote.address}:${remote.port}`, config.idleTimeoutMs);
402
+ const idleTimeoutMs = request.compaction ? Math.max(config.idleTimeoutMs, NATIVE_COMPACTION_IDLE_FLOOR_MS) : config.idleTimeoutMs;
351
403
  const replayable = Buffer.isBuffer(request.body);
352
404
  let body = request.body;
353
405
  let plainFallbackActive = false;
@@ -371,7 +423,7 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
371
423
  ...(remote.tlsServername ? { servername: remote.tlsServername } : {}),
372
424
  });
373
425
  connectTimeout(upstream, config);
374
- upstream.setTimeout(config.idleTimeoutMs, () => upstream.destroy(new DesktopBridgeError('bridge_upstream_idle_timeout')));
426
+ upstream.setTimeout(idleTimeoutMs, () => upstream.destroy(new DesktopBridgeError('bridge_upstream_idle_timeout')));
375
427
  req.once('aborted', abort);
376
428
  res.once('close', abort);
377
429
  upstream.once('error', (error) => {
@@ -390,6 +442,8 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
390
442
  });
391
443
  upstream.once('response', (response) => {
392
444
  const statusCode = response.statusCode || 502;
445
+ if (codexLb)
446
+ rememberCodexLbTurnState(threadId, request.credential.fingerprint, response.headers);
393
447
  if (plainFallbackActive && statusCode < 400 && !official && !encodedBodyRefusals.has(provider.provider_id)) {
394
448
  encodedBodyRefusals.add(provider.provider_id);
395
449
  logHttpRejection({ code: 'bridge_upstream_encoded_body_refused', transport: 'http', ...(req.method === undefined ? {} : { method: req.method }), ...(req.url === undefined ? {} : { url: req.url }), provider_id: provider.provider_id });
@@ -425,7 +479,7 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
425
479
  return;
426
480
  }
427
481
  if (statusCode >= 400) {
428
- void readRedactedUpstreamError(response).then(({ upstreamCode, upstreamType, unreadableBody }) => {
482
+ void readRedactedUpstreamError(response).then(({ upstreamCode, upstreamType, unreadableBody, body: upstreamBody }) => {
429
483
  if (budget.plainFallback && (statusCode === 415
430
484
  || (unreadableBody && !upstreamType && !upstreamCode && (statusCode === 400 || statusCode === 422)))) {
431
485
  responseStarted = true;
@@ -440,10 +494,13 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
440
494
  : 'bridge_upstream_transient_mislabel')));
441
495
  return;
442
496
  }
443
- const clientStatus = transientMislabel ? 503 : statusCode;
444
- const body = buildRedactedUpstreamErrorBody(statusCode, upstreamCode, upstreamType, transientMislabel);
497
+ const verbatim = codexLb && upstreamBody !== null;
498
+ const clientStatus = verbatim ? statusCode : transientMislabel ? 503 : statusCode;
499
+ const body = verbatim
500
+ ? scrubUpstreamErrorBody(upstreamBody, request.credential.value)
501
+ : buildRedactedUpstreamErrorBody(statusCode, upstreamCode, upstreamType, transientMislabel);
445
502
  logHttpRejection({
446
- code: transientMislabel
503
+ code: transientMislabel && !verbatim
447
504
  ? `bridge_upstream_status_${statusCode}_translated_503`
448
505
  : upstreamCode ? `bridge_upstream_status_${statusCode}:${upstreamCode}` : `bridge_upstream_status_${statusCode}`,
449
506
  transport: 'http',
@@ -457,10 +514,10 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
457
514
  const responseHeaders = rewriteResponseHeaders(response.headers, upstreamBaseUrl, authenticatedLocalBaseUrl);
458
515
  responseHeaders['content-length'] = String(body.length);
459
516
  delete responseHeaders['transfer-encoding'];
460
- if (transientMislabel)
461
- responseHeaders['retry-after'] = String(responseHeaders['retry-after'] || '10');
462
- if (statusCode === 429 && !responseHeaders['retry-after'])
463
- responseHeaders['retry-after'] = '10';
517
+ delete responseHeaders['content-encoding'];
518
+ if (verbatim && upstreamCode === MODEL_CAPACITY_ERROR_CODE && responseHeaders['retry-after'] === undefined) {
519
+ responseHeaders['retry-after'] = String(MODEL_CAPACITY_RETRY_AFTER_SECONDS);
520
+ }
464
521
  res.writeHead(clientStatus, responseHeaders);
465
522
  res.end(body, () => finish());
466
523
  }).catch(finish);
@@ -638,6 +695,10 @@ export async function requestProviderCompactionSummary(config, input, body, onAc
638
695
  }
639
696
  }
640
697
  }
698
+ function singleRetryAfter(value) {
699
+ const text = String(Array.isArray(value) ? value[0] ?? '' : value ?? '').trim();
700
+ return /^[A-Za-z0-9 ,:.-]{1,64}$/.test(text) ? text : null;
701
+ }
641
702
  function upstreamErrorIds(body) {
642
703
  try {
643
704
  const parsed = JSON.parse(body.toString('utf8'));
@@ -683,9 +744,10 @@ async function answerCompactionWithProviderSummary(req, res, config, input) {
683
744
  const transient = isTransientUpstreamFailure(call.status, upstreamType, upstreamCode);
684
745
  const clientStatus = transient ? 503 : call.status;
685
746
  const errorBody = buildRedactedUpstreamErrorBody(call.status, upstreamCode, upstreamType, transient);
747
+ const retryAfter = singleRetryAfter(call.headers['retry-after']);
686
748
  res.writeHead(clientStatus, {
687
749
  'content-type': 'application/json', 'cache-control': 'no-store', 'content-length': String(errorBody.length),
688
- ...(transient || call.status === 429 ? { 'retry-after': String(call.headers['retry-after'] || '10') } : {}),
750
+ ...(retryAfter ? { 'retry-after': retryAfter } : {}),
689
751
  });
690
752
  res.end(errorBody);
691
753
  return;
@@ -0,0 +1,79 @@
1
+ import { DesktopBridgeError } from './types.js';
2
+ import { isNativeCompactionItem } from './compaction-adapter.js';
3
+ export const PROVIDER_HANDOFF_NATIVE_COMPACTION_REFUSED = 'bridge_thread_handoff_after_native_compaction';
4
+ const ROUTE_TARGET_NAMES = {
5
+ openai: 'your ChatGPT account',
6
+ 'codex-lb': 'Codex-LB',
7
+ openrouter: 'OpenRouter',
8
+ };
9
+ function isObject(value) {
10
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
11
+ }
12
+ function targetName(id) {
13
+ return ROUTE_TARGET_NAMES[id] ?? id;
14
+ }
15
+ export class ProviderHandoffRefusedError extends DesktopBridgeError {
16
+ move;
17
+ constructor(move) {
18
+ super(PROVIDER_HANDOFF_NATIVE_COMPACTION_REFUSED);
19
+ this.move = move;
20
+ }
21
+ userMessage() {
22
+ return `This thread was compacted on ${targetName(this.move.from)}, and that compaction can only be read there. `
23
+ + `Switch back to the model you were using, or start a new thread to continue on ${targetName(this.move.to)}.`;
24
+ }
25
+ }
26
+ export function carriesNativeCompaction(payload) {
27
+ return Boolean(payload && Array.isArray(payload.input) && payload.input.some(isNativeCompactionItem));
28
+ }
29
+ export function assertProviderHandoffAllowed(payload, move) {
30
+ if (!move || move.from === move.to || !carriesNativeCompaction(payload))
31
+ return;
32
+ throw new ProviderHandoffRefusedError(move);
33
+ }
34
+ export function providerHandoffRefusalBody(error) {
35
+ return JSON.stringify({
36
+ error: { type: 'invalid_request_error', code: 'invalid_prompt', message: error.userMessage(), param: error.code },
37
+ });
38
+ }
39
+ export function providerHandoffRefusedEvent(error, responseId, publicModel) {
40
+ return {
41
+ type: 'response.failed',
42
+ response: {
43
+ id: responseId,
44
+ object: 'response',
45
+ created_at: Math.floor(Date.now() / 1000),
46
+ model: publicModel,
47
+ status: 'failed',
48
+ error: { code: 'invalid_prompt', message: error.userMessage() },
49
+ },
50
+ };
51
+ }
52
+ export function stripProviderBoundItems(payload, moving) {
53
+ if (!payload)
54
+ return false;
55
+ let changed = false;
56
+ if (Array.isArray(payload.input)) {
57
+ const input = [];
58
+ for (const item of payload.input) {
59
+ if (isObject(item) && item.type === 'reasoning') {
60
+ changed = true;
61
+ continue;
62
+ }
63
+ if (isObject(item) && 'encrypted_content' in item && !isNativeCompactionItem(item)) {
64
+ const { encrypted_content: _foreign, ...rest } = item;
65
+ input.push(rest);
66
+ changed = true;
67
+ continue;
68
+ }
69
+ input.push(item);
70
+ }
71
+ if (changed)
72
+ payload.input = input;
73
+ }
74
+ if (moving && payload.previous_response_id !== undefined) {
75
+ delete payload.previous_response_id;
76
+ changed = true;
77
+ }
78
+ return changed;
79
+ }