sneakoscope 9.0.6 → 9.1.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.
package/README.md CHANGED
@@ -22,7 +22,7 @@ Proof-first orchestration for Codex CLI, ChatGPT Desktop, AI coding agents, mult
22
22
  Sneakoscope Codex (`sks`) is an open-source trust layer for Codex CLI and ChatGPT Desktop. It coordinates bounded AI coding agents, records machine-verifiable evidence, preserves project memory, and blocks release claims that are not supported by current tests or artifacts. Search visibility outcomes are measured separately; SKS does not promise rankings or traffic.
23
23
  <!-- END SKS SEARCH VISIBILITY MARKETING -->
24
24
 
25
- This README documents package **SKS 9.0.6** — its own identity, read from `package.json` and subject to release-gate verification, not advice about what to install.
25
+ This README documents package **SKS 9.1.1** — its own identity, read from `package.json` and subject to release-gate verification, not advice about what to install.
26
26
 
27
27
  Use the official latest stable SKS and Codex CLI releases. The Codex compatibility SSOT is always the **current latest stable** host; capability probes measure what that host can actually do. Product docs do not crown a fixed `0.x.y` string as SSOT (release pins and schema directories are measured artifacts for the current package, not a permanent product version claim). Menu Bar / Center induce updates to the latest stable build. Run `sks update-check` for what is installed and read the capability report for what is supported. Install SSOT is npm `sneakoscope@latest`; PATH `sks` and Menu Bar stamped generation must match that version or gates fail. It resolves managed SKS skills from the authoritative global install, preserves a runnable Naruto child slot when `max_threads=2`, and keeps Menu Bar repair transactional so stamped generations remain verifiable. Naruto uses stable opt-in multi-agent V2 when the host exposes it (Codex official multi-agent wrap-only; SKS does not reimplement a parallel runtime). Local code search is mode-separated (`sks search files|text|structure|symbol|context`); `context` is answered by the compiled TriWiki Context Graph (`context-graph.json` is exhaustive authority; `context-pack.json` and managed `AGENTS.md` are bounded projections) — see [docs/architecture/context-graph.md](https://github.com/mandarange/Sneakoscope-Codex/blob/main/docs/architecture/context-graph.md) and [docs/PRODUCT-CONTRACT.md](https://github.com/mandarange/Sneakoscope-Codex/blob/main/docs/PRODUCT-CONTRACT.md). See [CHANGELOG.md](https://github.com/mandarange/Sneakoscope-Codex/blob/main/CHANGELOG.md).
28
28
 
@@ -259,7 +259,7 @@ dependencies = [
259
259
 
260
260
  [[package]]
261
261
  name = "sks-core"
262
- version = "9.0.6"
262
+ version = "9.1.1"
263
263
  dependencies = [
264
264
  "globset",
265
265
  "grep-matcher",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "sks-core"
3
- version = "9.0.6"
3
+ version = "9.1.1"
4
4
  edition = "2021"
5
5
 
6
6
  [dependencies]
@@ -302,6 +302,9 @@ export function safeReadOnlySubcommand(command, args) {
302
302
  if (command === 'mcp' && sub === 'config' && ['list', 'test', 'backups', 'show'].includes(nested)) {
303
303
  return !args.some((arg) => ['--fix', '--yes', '-y', '--write', '--apply', '--execute', '--force', '--real'].includes(String(arg)));
304
304
  }
305
+ if (command === 'codex-app' && sub === 'context-1m' && (nested === 'status' || nested === '' || nested.startsWith('--'))) {
306
+ return !args.some((arg) => ['--fix', '--yes', '-y', '--write', '--apply', '--execute', '--force', '--real'].includes(String(arg)));
307
+ }
305
308
  if (command === 'remote' && ['readiness', 'status', 'show'].includes(sub)) {
306
309
  return !args.some((arg) => ['--fix', '--yes', '-y', '--write', '--apply', '--execute', '--force', '--real'].includes(String(arg)));
307
310
  }
@@ -16,6 +16,35 @@ export async function run(_command, args = []) {
16
16
  const action = args[0] || 'check';
17
17
  if (action === 'restart')
18
18
  return printCodexAppResult(args, await restartCodexApp());
19
+ if (action === 'context-1m') {
20
+ const { codexContext1mCommand } = await import('../core/codex-app/codex-context-window.js');
21
+ const result = await codexContext1mCommand(args.slice(1));
22
+ if (flag(args, '--json')) {
23
+ printJson(result);
24
+ if (!result.ok)
25
+ process.exitCode = 1;
26
+ return;
27
+ }
28
+ console.log(`Codex 1M Context: ${result.enabled ? 'enabled' : 'disabled'}`);
29
+ console.log(`Config: ${result.config_path}`);
30
+ console.log(`Model: ${result.model || 'not set'} (documented for ${result.expected_model})`);
31
+ for (const [key, target] of Object.entries(result.target)) {
32
+ const state = result.keys[key];
33
+ const detail = state?.present ? `${state.value ?? 'unparsed'}${state.managed ? ' (SKS-managed)' : ''}` : 'not set';
34
+ console.log(`${key}: ${detail} · target ${target}`);
35
+ }
36
+ if (result.restart)
37
+ console.log(`Restart: ${result.restart.status}${result.restart.reason ? ` (${result.restart.reason})` : ''}`);
38
+ for (const note of result.notes)
39
+ console.log(`Note: ${note}`);
40
+ for (const warning of result.warnings)
41
+ console.log(`- warning: ${warning}`);
42
+ for (const blocker of result.blockers)
43
+ console.log(`- blocker: ${blocker}`);
44
+ if (!result.ok)
45
+ process.exitCode = 1;
46
+ return;
47
+ }
19
48
  if (action === 'remote-control' || action === 'remote')
20
49
  return codexAppRemoteControlCommand(args.slice(1));
21
50
  if (action === 'harness-matrix') {
@@ -108,7 +137,7 @@ export async function run(_command, args = []) {
108
137
  process.exitCode = 1;
109
138
  return;
110
139
  }
111
- console.error('Usage: sks codex-app check|status|restart|harness-matrix|skill-sync|agent-role-sync|init-deep|hook-lifecycle|execution-profile|role-models|set-role-model --role <name> [--provider <id>] --model <catalog-slug> --reasoning <effort>|reset-role-model --role <name>|product-design [--check-only]|ensure-product-design|chrome-extension|pat status|remote-control [--json]');
140
+ console.error('Usage: sks codex-app check|status|restart|context-1m [status|on|off] [--no-restart]|harness-matrix|skill-sync|agent-role-sync|init-deep|hook-lifecycle|execution-profile|role-models|set-role-model --role <name> [--provider <id>] --model <catalog-slug> --reasoning <effort>|reset-role-model --role <name>|product-design [--check-only]|ensure-product-design|chrome-extension|pat status|remote-control [--json]');
112
141
  console.error('Provider routing moved to: sks bridge provider configure|validate|enable; sks bridge catalog sync; sks bridge route set-default.');
113
142
  process.exitCode = 1;
114
143
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schema": "sks.skills-manifest.v1",
3
- "package_version": "9.0.6",
3
+ "package_version": "9.1.1",
4
4
  "skills": [
5
5
  {
6
6
  "canonical_name": "sks",
@@ -0,0 +1,227 @@
1
+ import { exists, readText } from '../fsx.js';
2
+ import { escapeRegExp } from '../text/regex.js';
3
+ import { safeWriteCodexConfigToml } from '../codex-runtime/codex-desktop-config-policy.js';
4
+ import { codexUserConfigPath, readTopLevelTomlString } from './codex-model-catalog.js';
5
+ import { isCodexAppRunningByBundleId } from './menubar/config.js';
6
+ import { restartCodexApp } from './codex-app-restart.js';
7
+ export const CODEX_CONTEXT_1M_SCHEMA = 'sks.codex-context-1m.v1';
8
+ export const CODEX_CONTEXT_1M_MARKER = 'sks-codex-context-1m';
9
+ export const CODEX_CONTEXT_1M_TARGETS = {
10
+ model_context_window: 1_000_000,
11
+ model_auto_compact_token_limit: 900_000
12
+ };
13
+ export const CODEX_CONTEXT_1M_MODEL = 'gpt-5.6-sol';
14
+ const MANAGED_KEYS = Object.keys(CODEX_CONTEXT_1M_TARGETS);
15
+ function topLevelRegionEnd(lines) {
16
+ const first = lines.findIndex((line) => /^\s*\[.+\]\s*$/.test(line));
17
+ return first === -1 ? lines.length : first;
18
+ }
19
+ function managedLine(key, previous) {
20
+ return `${key} = ${CODEX_CONTEXT_1M_TARGETS[key]} # ${CODEX_CONTEXT_1M_MARKER} prev=${previous}`;
21
+ }
22
+ function inspectKeyLines(lines, key) {
23
+ const end = topLevelRegionEnd(lines);
24
+ const keyPattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*=`);
25
+ const managedPattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*(\\d+)\\s*#\\s*${escapeRegExp(CODEX_CONTEXT_1M_MARKER)}\\s+prev=(unset|\\d+)\\s*$`);
26
+ const valuePattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*=\\s*(\\d+)\\s*(?:#.*)?$`);
27
+ let state = null;
28
+ let duplicate = false;
29
+ for (let index = 0; index < end; index += 1) {
30
+ const line = lines[index] || '';
31
+ if (!keyPattern.test(line))
32
+ continue;
33
+ if (state) {
34
+ duplicate = true;
35
+ continue;
36
+ }
37
+ const managed = line.match(managedPattern);
38
+ const value = line.match(valuePattern);
39
+ state = {
40
+ present: true,
41
+ managed: Boolean(managed),
42
+ value: managed ? Number(managed[1]) : value ? Number(value[1]) : null,
43
+ previous: managed ? (managed[2] === 'unset' ? 'unset' : Number(managed[2])) : null,
44
+ duplicate: false,
45
+ lineIndex: index
46
+ };
47
+ }
48
+ if (!state)
49
+ return { present: false, managed: false, value: null, previous: null, duplicate: false, lineIndex: -1 };
50
+ return { ...state, duplicate };
51
+ }
52
+ export function inspectCodexContext1m(text) {
53
+ const lines = String(text || '').split('\n');
54
+ const warnings = [];
55
+ const keys = {};
56
+ for (const key of MANAGED_KEYS) {
57
+ const { lineIndex: _lineIndex, ...state } = inspectKeyLines(lines, key);
58
+ keys[key] = state;
59
+ if (state.duplicate)
60
+ warnings.push(`codex_context_duplicate_key:${key}`);
61
+ if (state.managed && state.value !== CODEX_CONTEXT_1M_TARGETS[key])
62
+ warnings.push(`codex_context_managed_value_drift:${key}`);
63
+ }
64
+ const enabled = MANAGED_KEYS.every((key) => keys[key].managed && keys[key].value === CODEX_CONTEXT_1M_TARGETS[key]);
65
+ return { enabled, model: readTopLevelTomlString(String(text || ''), 'model'), keys, warnings };
66
+ }
67
+ export function enableCodexContext1m(text) {
68
+ const source = String(text || '');
69
+ const lines = source.split('\n');
70
+ const blockers = [];
71
+ const previous = {};
72
+ for (const key of MANAGED_KEYS) {
73
+ const state = inspectKeyLines(lines, key);
74
+ if (state.duplicate)
75
+ blockers.push(`codex_context_duplicate_key:${key}`);
76
+ if (state.present && !state.managed && state.value === null)
77
+ blockers.push(`codex_context_unparseable_value:${key}`);
78
+ }
79
+ if (blockers.length)
80
+ return { next: source, changed: false, previous: {}, restored: {}, blockers, warnings: [] };
81
+ for (const key of MANAGED_KEYS) {
82
+ const state = inspectKeyLines(lines, key);
83
+ if (state.present) {
84
+ const prior = state.managed ? (state.previous ?? 'unset') : state.value;
85
+ previous[key] = prior;
86
+ lines[state.lineIndex] = managedLine(key, prior);
87
+ }
88
+ else {
89
+ previous[key] = 'unset';
90
+ lines.splice(topLevelRegionEnd(lines), 0, managedLine(key, 'unset'));
91
+ }
92
+ }
93
+ const next = lines.join('\n').replace(/^\n+/, '').replace(/\n{3,}/g, '\n\n');
94
+ return { next, changed: next !== source, previous, restored: {}, blockers: [], warnings: [] };
95
+ }
96
+ export function disableCodexContext1m(text) {
97
+ const source = String(text || '');
98
+ const lines = source.split('\n');
99
+ const warnings = [];
100
+ const restored = {};
101
+ for (const key of MANAGED_KEYS) {
102
+ const state = inspectKeyLines(lines, key);
103
+ if (state.duplicate) {
104
+ return { next: source, changed: false, previous: {}, restored: {}, blockers: [`codex_context_duplicate_key:${key}`], warnings: [] };
105
+ }
106
+ if (!state.present)
107
+ continue;
108
+ if (!state.managed) {
109
+ warnings.push(`codex_context_unmanaged_key_left:${key}`);
110
+ continue;
111
+ }
112
+ const prior = state.previous ?? 'unset';
113
+ restored[key] = prior;
114
+ if (prior === 'unset')
115
+ lines.splice(state.lineIndex, 1);
116
+ else
117
+ lines[state.lineIndex] = `${key} = ${prior}`;
118
+ }
119
+ const next = lines.join('\n').replace(/^\n+/, '').replace(/\n{3,}/g, '\n\n');
120
+ return { next, changed: next !== source, previous: {}, restored, blockers: [], warnings };
121
+ }
122
+ export function normalizeCodexContext1mAction(value) {
123
+ const text = String(value || 'status').toLowerCase();
124
+ if (['on', 'enable', 'enabled', '1m'].includes(text))
125
+ return 'on';
126
+ if (['off', 'disable', 'disabled', 'default'].includes(text))
127
+ return 'off';
128
+ return 'status';
129
+ }
130
+ export async function codexContext1mCommand(args = [], opts = {}) {
131
+ const env = opts.env || process.env;
132
+ const action = normalizeCodexContext1mAction(args[0]);
133
+ const noRestart = args.includes('--no-restart');
134
+ const configPath = codexUserConfigPath({ env, ...(opts.home ? { home: opts.home } : {}) });
135
+ const before = String(await readText(configPath, ''));
136
+ const fileExists = await exists(configPath);
137
+ const blockers = [];
138
+ const warnings = [];
139
+ let write = null;
140
+ let changed = false;
141
+ let afterText = before;
142
+ let mutation = null;
143
+ if (action === 'on' || action === 'off') {
144
+ mutation = action === 'on' ? enableCodexContext1m(before) : disableCodexContext1m(before);
145
+ blockers.push(...mutation.blockers);
146
+ warnings.push(...mutation.warnings);
147
+ if (!blockers.length && mutation.changed) {
148
+ write = await safeWriteCodexConfigToml(configPath, before, mutation.next, 'codex-context-1m', {
149
+ verifyUnchangedBeforeWrite: true,
150
+ expectedBeforeExists: fileExists
151
+ });
152
+ if (!write.ok) {
153
+ blockers.push(`codex_config_write_${write.status}`);
154
+ }
155
+ else {
156
+ changed = write.changed;
157
+ afterText = write.expected_after?.text ?? mutation.next;
158
+ }
159
+ }
160
+ }
161
+ const inspection = inspectCodexContext1m(afterText);
162
+ warnings.push(...inspection.warnings);
163
+ if (action === 'on' || inspection.enabled) {
164
+ if (!inspection.model)
165
+ warnings.push('codex_context_model_line_missing');
166
+ else if (inspection.model !== CODEX_CONTEXT_1M_MODEL)
167
+ warnings.push(`codex_context_active_model_not_${CODEX_CONTEXT_1M_MODEL}:${inspection.model}`);
168
+ }
169
+ let restart = null;
170
+ if ((action === 'on' || action === 'off') && !blockers.length) {
171
+ restart = await maybeRestartCodexApp({
172
+ env,
173
+ changed,
174
+ noRestart,
175
+ ...(opts.root === undefined ? {} : { root: opts.root }),
176
+ ...(opts.isRunningImpl === undefined ? {} : { isRunningImpl: opts.isRunningImpl }),
177
+ ...(opts.restartImpl === undefined ? {} : { restartImpl: opts.restartImpl })
178
+ });
179
+ if (restart.attempted && !restart.ok)
180
+ warnings.push('codex_restart_failed_manual_restart_required');
181
+ }
182
+ return {
183
+ schema: CODEX_CONTEXT_1M_SCHEMA,
184
+ ok: blockers.length === 0,
185
+ action,
186
+ enabled: inspection.enabled,
187
+ config_path: configPath,
188
+ model: inspection.model,
189
+ expected_model: CODEX_CONTEXT_1M_MODEL,
190
+ target: { ...CODEX_CONTEXT_1M_TARGETS },
191
+ keys: inspection.keys,
192
+ previous: mutation && action === 'on' ? mutation.previous : null,
193
+ restored: mutation && action === 'off' ? mutation.restored : null,
194
+ changed,
195
+ write: write ? { status: write.status, backup_path: write.backup_path } : null,
196
+ restart,
197
+ blockers,
198
+ warnings,
199
+ notes: [
200
+ 'Only new Codex sessions pick up context-window changes; existing conversations keep their previous limits.',
201
+ 'Requests with more than 272K input tokens are billed at the long-context rate (2x input / 1.5x output) for the entire request.'
202
+ ],
203
+ cli_commands: {
204
+ status: 'sks codex-app context-1m status',
205
+ on: 'sks codex-app context-1m on',
206
+ off: 'sks codex-app context-1m off'
207
+ }
208
+ };
209
+ }
210
+ async function maybeRestartCodexApp(input) {
211
+ const skippedOutcome = (reason) => ({ attempted: false, running: null, status: 'skipped', reason, ok: true, blockers: [] });
212
+ if (input.noRestart)
213
+ return skippedOutcome('no_restart_flag');
214
+ if (!input.changed)
215
+ return skippedOutcome('config_unchanged');
216
+ if (input.env.SKS_SKIP_CODEX_APP_RESTART === '1')
217
+ return skippedOutcome('SKS_SKIP_CODEX_APP_RESTART');
218
+ if (process.platform !== 'darwin')
219
+ return skippedOutcome('not_macos');
220
+ const bundleId = String(input.env.SKS_CODEX_APP_BUNDLE_ID || 'com.openai.codex');
221
+ const running = await (input.isRunningImpl || isCodexAppRunningByBundleId)(bundleId, input.env);
222
+ if (!running) {
223
+ return { attempted: false, running: false, status: 'skipped', reason: 'codex_not_running', ok: true, blockers: [] };
224
+ }
225
+ const result = await (input.restartImpl || restartCodexApp)({ env: input.env, ...(input.root ? { root: input.root } : {}) });
226
+ return { attempted: true, running: true, status: result.status, reason: null, ok: result.ok, blockers: result.blockers };
227
+ }
@@ -148,6 +148,34 @@ function safeUpstreamErrorId(value) {
148
148
  const text = String(value ?? '').trim();
149
149
  return /^[A-Za-z0-9_.:-]{1,64}$/.test(text) ? text : null;
150
150
  }
151
+ const TRANSIENT_UPSTREAM_STATUSES = new Set([500, 502, 503, 524]);
152
+ const TRANSIENT_UPSTREAM_IDENTIFIERS = new Set(['upstream_error', 'upstream_request_timeout']);
153
+ export const TRANSIENT_UPSTREAM_REPLAY_LIMIT = 3;
154
+ const TRANSIENT_UPSTREAM_REPLAY_BACKOFF_MS = [200, 400, 800];
155
+ function isTransientUpstreamIdentifier(value) {
156
+ return Boolean(value && TRANSIENT_UPSTREAM_IDENTIFIERS.has(value));
157
+ }
158
+ function delay(ms) {
159
+ return new Promise((resolve) => {
160
+ const timer = setTimeout(resolve, ms);
161
+ timer.unref();
162
+ });
163
+ }
164
+ function isTransientUpstreamFailure(statusCode, upstreamType, upstreamCode) {
165
+ if (statusCode === 429)
166
+ return false;
167
+ if (statusCode === 404) {
168
+ return isTransientUpstreamIdentifier(upstreamType) || isTransientUpstreamIdentifier(upstreamCode);
169
+ }
170
+ return TRANSIENT_UPSTREAM_STATUSES.has(statusCode);
171
+ }
172
+ function redactedUpstreamClientMessage(statusCode, transient) {
173
+ if (statusCode === 429)
174
+ return 'rate_limited';
175
+ if (transient)
176
+ return 'temporary_upstream_failure';
177
+ return 'bridge_upstream_request_failed';
178
+ }
151
179
  async function readRedactedUpstreamError(response) {
152
180
  let total = 0;
153
181
  const chunks = [];
@@ -169,19 +197,18 @@ async function readRedactedUpstreamError(response) {
169
197
  }
170
198
  catch {
171
199
  }
172
- return {
173
- upstreamCode,
174
- upstreamType,
175
- body: Buffer.from(JSON.stringify({
176
- error: {
177
- type: 'upstream_error',
178
- code: 'bridge_upstream_request_failed',
179
- message: 'Upstream request failed',
180
- ...(upstreamType ? { upstream_type: upstreamType } : {}),
181
- ...(upstreamCode ? { upstream_code: upstreamCode } : {})
182
- }
183
- }))
184
- };
200
+ return { upstreamCode, upstreamType };
201
+ }
202
+ function buildRedactedUpstreamErrorBody(statusCode, upstreamCode, upstreamType, transient) {
203
+ return Buffer.from(JSON.stringify({
204
+ error: {
205
+ type: 'upstream_error',
206
+ code: 'bridge_upstream_request_failed',
207
+ message: redactedUpstreamClientMessage(statusCode, transient),
208
+ ...(upstreamType ? { upstream_type: upstreamType } : {}),
209
+ ...(upstreamCode ? { upstream_code: upstreamCode } : {}),
210
+ },
211
+ }));
185
212
  }
186
213
  const upstreamAgents = new Map();
187
214
  function upstreamAgent(secure, key, idleTimeoutMs) {
@@ -240,7 +267,7 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
240
267
  delete headers['content-encoding'];
241
268
  const agent = upstreamAgent(provider.remote.secure, `${provider.remote.address}:${provider.remote.port}`, config.idleTimeoutMs);
242
269
  const replayable = Buffer.isBuffer(request.body);
243
- const attempt = (useFreshConnection) => new Promise((resolve, reject) => {
270
+ const attempt = (useFreshConnection, canReplay) => new Promise((resolve, reject) => {
244
271
  let responseStarted = false;
245
272
  let settled = false;
246
273
  const abort = () => { if (!res.writableEnded)
@@ -273,15 +300,17 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
273
300
  upstream.once('response', (response) => {
274
301
  const statusCode = response.statusCode || 502;
275
302
  if (statusCode >= 400) {
276
- void readRedactedUpstreamError(response).then(({ body, upstreamCode, upstreamType }) => {
277
- const transientMislabel = statusCode === 404
278
- && (upstreamType === 'upstream_error' || upstreamCode === 'upstream_error');
279
- if (transientMislabel && replayable && !useFreshConnection) {
303
+ void readRedactedUpstreamError(response).then(({ upstreamCode, upstreamType }) => {
304
+ const transientMislabel = isTransientUpstreamFailure(statusCode, upstreamType, upstreamCode);
305
+ if (transientMislabel && replayable && canReplay) {
280
306
  responseStarted = true;
281
- finish(new StalePooledSocketFailure(new DesktopBridgeError('bridge_upstream_transient_mislabel')));
307
+ finish(new StalePooledSocketFailure(new DesktopBridgeError(upstreamCode === 'upstream_request_timeout'
308
+ ? 'bridge_upstream_request_timeout'
309
+ : 'bridge_upstream_transient_mislabel')));
282
310
  return;
283
311
  }
284
312
  const clientStatus = transientMislabel ? 503 : statusCode;
313
+ const body = buildRedactedUpstreamErrorBody(statusCode, upstreamCode, upstreamType, transientMislabel);
285
314
  logHttpRejection({
286
315
  code: transientMislabel
287
316
  ? `bridge_upstream_status_${statusCode}_translated_503`
@@ -298,6 +327,8 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
298
327
  responseHeaders['content-length'] = String(body.length);
299
328
  delete responseHeaders['transfer-encoding'];
300
329
  if (transientMislabel)
330
+ responseHeaders['retry-after'] = String(responseHeaders['retry-after'] || '10');
331
+ if (statusCode === 429 && !responseHeaders['retry-after'])
301
332
  responseHeaders['retry-after'] = '10';
302
333
  res.writeHead(clientStatus, responseHeaders);
303
334
  res.end(body, () => finish());
@@ -321,21 +352,34 @@ export async function forwardHttp(req, res, config, prepared, authenticatedLocal
321
352
  void pipeline(req, upstream).catch((error) => { if (!responseStarted)
322
353
  finish(error); });
323
354
  });
324
- try {
325
- await attempt(false);
326
- }
327
- catch (error) {
328
- if (!(error instanceof StalePooledSocketFailure))
329
- throw error;
330
- agent.destroy();
331
- upstreamAgents.delete(`${provider.remote.secure ? 'https' : 'http'}:${provider.remote.address}:${provider.remote.port}`);
332
- logHttpRejection({
333
- code: `bridge_upstream_socket_stale_replayed:${underlyingErrorCode(error.reason) || 'unknown'}`,
334
- transport: 'http',
335
- ...(req.method === undefined ? {} : { method: req.method }),
336
- ...(req.url === undefined ? {} : { url: req.url }),
337
- });
338
- await attempt(true);
355
+ let remainingReplays = replayable ? TRANSIENT_UPSTREAM_REPLAY_LIMIT : 0;
356
+ let useFreshConnection = false;
357
+ for (;;) {
358
+ try {
359
+ await attempt(useFreshConnection, remainingReplays > 0);
360
+ return;
361
+ }
362
+ catch (error) {
363
+ if (!(error instanceof StalePooledSocketFailure) || remainingReplays <= 0)
364
+ throw error;
365
+ remainingReplays -= 1;
366
+ if (!useFreshConnection) {
367
+ agent.destroy();
368
+ upstreamAgents.delete(`${provider.remote.secure ? 'https' : 'http'}:${provider.remote.address}:${provider.remote.port}`);
369
+ }
370
+ logHttpRejection({
371
+ code: `bridge_upstream_socket_stale_replayed:${underlyingErrorCode(error.reason) || 'unknown'}`,
372
+ transport: 'http',
373
+ ...(req.method === undefined ? {} : { method: req.method }),
374
+ ...(req.url === undefined ? {} : { url: req.url }),
375
+ });
376
+ useFreshConnection = true;
377
+ const backoffIndex = TRANSIENT_UPSTREAM_REPLAY_LIMIT - remainingReplays - 1;
378
+ const backoffMs = TRANSIENT_UPSTREAM_REPLAY_BACKOFF_MS[Math.max(0, backoffIndex)]
379
+ ?? TRANSIENT_UPSTREAM_REPLAY_BACKOFF_MS[TRANSIENT_UPSTREAM_REPLAY_BACKOFF_MS.length - 1];
380
+ if (backoffMs)
381
+ await delay(backoffMs);
382
+ }
339
383
  }
340
384
  }
341
385
  catch (error) {
@@ -8,7 +8,7 @@ import { createDesktopBridgePublicState, desktopBridgeListenOrigin, desktopBridg
8
8
  import { DesktopBridgeError } from './types.js';
9
9
  import { PACKAGE_VERSION } from '../../version.js';
10
10
  import { DESKTOP_BRIDGE_CLIENT_PATH_PREFIX, DESKTOP_BRIDGE_DIAGNOSTIC_HEALTH_PATH, DESKTOP_BRIDGE_DIAGNOSTIC_PATH, DESKTOP_BRIDGE_DIAGNOSTIC_PROTOCOL } from './types.js';
11
- import { forwardWebSocket } from './websocket-forward.js';
11
+ import { forwardWebSocket, safeEndUpgradeSocket } from './websocket-forward.js';
12
12
  function authenticateDesktopBridgeClient(req, input) {
13
13
  const raw = String(req.url || '/');
14
14
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) || raw.startsWith('//') || /[\r\n\0]/.test(raw)) {
@@ -135,22 +135,14 @@ function writeUpgradeRejection(socket, error, req) {
135
135
  url: req?.url,
136
136
  status: rejectionStatus(safeBridgeErrorCode(error)),
137
137
  });
138
- socket.on('error', () => undefined);
139
- if (socket.destroyed || socket.writableEnded)
140
- return;
141
138
  const code = safeBridgeErrorCode(error);
142
139
  const status = rejectionStatus(code);
143
- try {
144
- socket.end(`HTTP/1.1 ${status} ${rejectionStatusText(status)}\r\n`
145
- + 'Content-Type: application/json\r\n'
146
- + 'Cache-Control: no-store\r\n'
147
- + 'Connection: close\r\n'
148
- + '\r\n'
149
- + JSON.stringify({ error: { type: 'sks_bridge_rejection', code, message: code } }));
150
- }
151
- catch {
152
- socket.destroy();
153
- }
140
+ safeEndUpgradeSocket(socket, `HTTP/1.1 ${status} ${rejectionStatusText(status)}\r\n`
141
+ + 'Content-Type: application/json\r\n'
142
+ + 'Cache-Control: no-store\r\n'
143
+ + 'Connection: close\r\n'
144
+ + '\r\n'
145
+ + JSON.stringify({ error: { type: 'sks_bridge_rejection', code, message: code } }));
154
146
  }
155
147
  function writeDiagnosticHealth(req, res, input) {
156
148
  if (req.method !== 'GET')
@@ -107,6 +107,17 @@ const PERMANENT_UPGRADE_REFUSALS = new Set([
107
107
  'catalog_model_route_missing',
108
108
  'bridge_provider_route_unavailable',
109
109
  ]);
110
+ export function safeEndUpgradeSocket(socket, payload) {
111
+ socket.on('error', () => undefined);
112
+ if (socket.destroyed || socket.writableEnded)
113
+ return;
114
+ try {
115
+ socket.end(payload);
116
+ }
117
+ catch {
118
+ socket.destroy();
119
+ }
120
+ }
110
121
  function writeUpgradeFailure(client, error, req) {
111
122
  const code = safeBridgeErrorCode(error) || 'bridge_websocket_upstream_unavailable';
112
123
  const permanent = PERMANENT_UPGRADE_REFUSALS.has(code);
@@ -119,9 +130,7 @@ function writeUpgradeFailure(client, error, req) {
119
130
  ...(req?.url === undefined ? {} : { url: req.url }),
120
131
  status,
121
132
  });
122
- if (client.destroyed)
123
- return;
124
- client.end(`HTTP/1.1 ${status} ${reason}\r\nContent-Type: application/json\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n`
133
+ safeEndUpgradeSocket(client, `HTTP/1.1 ${status} ${reason}\r\nContent-Type: application/json\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n`
125
134
  + JSON.stringify({ error: { type: 'sks_bridge_error', code, retryable: !permanent } }));
126
135
  }
127
136
  export async function forwardWebSocket(req, client, head, config, authenticatedLocalBaseUrl = desktopBridgeListenOrigin(config)) {
@@ -18,6 +18,28 @@ import { MAX_LIFECYCLE_THREADS } from './subagent-skill-availability-contract.js
18
18
  import { officialSubagentEvidenceReady, terminalBlockedNarutoGate } from '../subagents/terminal-subagent-state.js';
19
19
  const SUBAGENT_LIFECYCLE_CAPTURE_FAILURE_SCHEMA = 'sks.subagent-lifecycle-capture-failure.v1';
20
20
  const MAX_SUBAGENT_LIFECYCLE_CAPTURE_FAILURES = 528;
21
+ export const ACTIVE_OFFICIAL_WORKFLOW_IDLE_MS = 2 * 60 * 60 * 1000;
22
+ function parseIsoMs(value) {
23
+ const parsed = Date.parse(String(value || ''));
24
+ return Number.isFinite(parsed) ? parsed : 0;
25
+ }
26
+ export function officialWorkflowLastActivityMs(input) {
27
+ const times = [
28
+ parseIsoMs(input.plan?.created_at),
29
+ parseIsoMs(input.plan?.updated_at),
30
+ parseIsoMs(input.plan?.wave_lifecycle?.updated_at),
31
+ parseIsoMs(input.plan?.wave_lifecycle?.created_at),
32
+ parseIsoMs(input.gate?.updated_at),
33
+ parseIsoMs(input.gate?.created_at),
34
+ ...(input.events || []).map((event) => parseIsoMs(event.occurred_at ?? event.ts))
35
+ ];
36
+ return times.reduce((max, value) => (value > max ? value : max), 0);
37
+ }
38
+ export function officialWorkflowIsIdle(activityMs, nowMs = Date.now()) {
39
+ if (activityMs <= 0)
40
+ return true;
41
+ return nowMs - activityMs > ACTIVE_OFFICIAL_WORKFLOW_IDLE_MS;
42
+ }
21
43
  export async function inspectActiveOfficialSubagentWorkflow(root, state, sessionKey = null) {
22
44
  const missionId = String(state?.mission_id || '').trim();
23
45
  const workflowRunId = String(state?.official_subagent_run_id || '').trim();
@@ -71,8 +93,14 @@ export async function inspectActiveOfficialSubagentWorkflow(root, state, session
71
93
  if (events.length > 0 && openThreads !== liveThreads.size) {
72
94
  return { status: 'invalid', missionId, workflowRunId, reason: 'active_lifecycle_event_mismatch' };
73
95
  }
96
+ if (officialWorkflowIsIdle(officialWorkflowLastActivityMs({ plan, gate, events }))) {
97
+ return { status: 'inactive' };
98
+ }
74
99
  return { status: 'active', missionId, workflowRunId, openThreads };
75
100
  }
101
+ if (officialWorkflowIsIdle(officialWorkflowLastActivityMs({ plan, gate, events }))) {
102
+ return { status: 'inactive' };
103
+ }
76
104
  return { status: 'active', missionId, workflowRunId, openThreads: liveThreads.size };
77
105
  }
78
106
  catch {
@@ -2,7 +2,7 @@ import fsp from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { projectRoot, readJson, writeJsonAtomic, writeTextAtomic, appendJsonl, nowIso, sha256, packageRoot } from './fsx.js';
4
4
  import { looksInteractiveCommand, interactiveCommandReason } from './no-question-guard.js';
5
- import { loadStateForSession, missionDir, sessionStateKey, setCurrent, stateFileForSession } from './mission.js';
5
+ import { loadOwnedRouteState, missionDir, sessionStateKey, setCurrent, stateFileForSession } from './mission.js';
6
6
  import { checkDbOperation, dbBlockReason, handleMadSksUserConfirmation } from './db-safety.js';
7
7
  import { maybeRecordMadSksSqlPlaneToolResultFromToolUse } from './mad-sks/sql-plane/result-lifecycle.js';
8
8
  import { checkHarnessModification, harnessGuardBlockReason, isHarnessSourceProject } from './harness-guard.js';
@@ -53,7 +53,7 @@ export { selftestCodexCommitHooks } from './hooks-runtime/codex-commit-hooks-sel
53
53
  async function loadState(root, payload = {}) {
54
54
  const sessionKey = conversationId(payload);
55
55
  if (!explicitConversationId(payload))
56
- return loadStateForSession(root, sessionKey);
56
+ return loadOwnedRouteState(root);
57
57
  const hashed = sessionStateKey(sessionKey);
58
58
  const sessionState = await readJson(stateFileForSession(root, sessionKey), null).catch(() => null);
59
59
  return sessionState ? { ...sessionState, _session_key: sessionState._session_key || hashed } : {};
@@ -228,6 +228,12 @@ export async function installProjectSkills(root) {
228
228
  export async function installSkills(root) {
229
229
  return installGlobalSkills(root);
230
230
  }
231
+ function hostExtraRemovedSkillTargets(home) {
232
+ return [
233
+ { scope: 'global-host-extra', ownerRoot: home, targetDir: path.join(home, '.cursor', 'skills'), managedOnly: true },
234
+ { scope: 'global-host-extra', ownerRoot: home, targetDir: path.join(home, '.claude', 'skills'), managedOnly: true },
235
+ ];
236
+ }
231
237
  export async function cleanupRemovedSksSkillResidue(opts) {
232
238
  const projectRoot = path.resolve(opts.root);
233
239
  const home = path.resolve(opts.home || os.homedir());
@@ -238,7 +244,8 @@ export async function cleanupRemovedSksSkillResidue(opts) {
238
244
  { scope: 'project', ownerRoot: projectRoot, targetDir: path.join(projectRoot, '.agents', 'skills') },
239
245
  { scope: 'project-codex', ownerRoot: projectRoot, targetDir: path.join(projectRoot, '.codex', 'skills') },
240
246
  { scope: 'global-runtime', ownerRoot: globalRuntimeRoot, targetDir: path.join(globalRuntimeRoot, '.agents', 'skills') },
241
- { scope: 'global-runtime-codex', ownerRoot: globalRuntimeRoot, targetDir: path.join(globalRuntimeRoot, '.codex', 'skills') }
247
+ { scope: 'global-runtime-codex', ownerRoot: globalRuntimeRoot, targetDir: path.join(globalRuntimeRoot, '.codex', 'skills') },
248
+ ...hostExtraRemovedSkillTargets(home),
242
249
  ];
243
250
  if (projectRoot !== home && projectRoot !== globalRuntimeRoot) {
244
251
  const scan = await collectNestedProjectRoots(projectRoot, new Set([home, globalRuntimeRoot]));
@@ -365,6 +372,8 @@ async function reconcileRemovedSkillTargets(targets, fix) {
365
372
  remaining.push(displayPath);
366
373
  continue;
367
374
  }
375
+ if (!managed && target.managedOnly)
376
+ continue;
368
377
  detected.push({
369
378
  scope: target.scope,
370
379
  name,
@@ -394,7 +403,7 @@ async function reconcileRemovedSkillTargets(targets, fix) {
394
403
  quarantinedManifestCollisions,
395
404
  remaining,
396
405
  errors
397
- });
406
+ }, { managedOnly: target.managedOnly === true });
398
407
  if (fix)
399
408
  await removeEmptySkillParents(target, errors);
400
409
  }
@@ -448,7 +457,7 @@ async function removeEmptySkillParents(target, errors) {
448
457
  }
449
458
  }
450
459
  }
451
- async function reconcileRemovedSkillManifests(target, rowByName, fix, report) {
460
+ async function reconcileRemovedSkillManifests(target, rowByName, fix, report, opts = {}) {
452
461
  for (const fileName of [SKS_SKILL_MANIFEST_FILE, 'skills-manifest.json']) {
453
462
  if (!rowByName.has(fileName))
454
463
  continue;
@@ -466,6 +475,8 @@ async function reconcileRemovedSkillManifests(target, rowByName, fix, report) {
466
475
  if (!inspection.exists)
467
476
  continue;
468
477
  if (inspection.leafSymlink || !inspection.stat?.isFile()) {
478
+ if (opts.managedOnly)
479
+ continue;
469
480
  if (fix) {
470
481
  try {
471
482
  await quarantineSkillDir(target.ownerRoot, manifestPath, fileName, 'removed-skill-manifest-collision');
@@ -496,6 +507,8 @@ async function reconcileRemovedSkillManifests(target, rowByName, fix, report) {
496
507
  catch {
497
508
  if (!manifestTextContainsRetiredJsonValue(text))
498
509
  continue;
510
+ if (opts.managedOnly)
511
+ continue;
499
512
  if (fix) {
500
513
  try {
501
514
  await quarantineSkillDir(target.ownerRoot, manifestPath, fileName, 'unparseable-removed-skill-manifest-collision');
@@ -514,6 +527,8 @@ async function reconcileRemovedSkillManifests(target, rowByName, fix, report) {
514
527
  if (!scrubbed.valid) {
515
528
  if (!scrubbed.hasRetiredResidue)
516
529
  continue;
530
+ if (opts.managedOnly)
531
+ continue;
517
532
  if (fix) {
518
533
  try {
519
534
  await quarantineSkillDir(target.ownerRoot, manifestPath, fileName, 'unmanaged-removed-skill-manifest-collision');
@@ -726,7 +741,7 @@ async function reconcileSkillsUnlocked(opts) {
726
741
  scope: 'global-runtime-codex',
727
742
  ownerRoot: globalRuntimeRoot,
728
743
  targetDir: path.join(globalRuntimeRoot, '.codex', 'skills')
729
- });
744
+ }, ...hostExtraRemovedSkillTargets(root));
730
745
  }
731
746
  const removedResidue = await reconcileRemovedSkillTargets(removedResidueTargets, opts.fix);
732
747
  report.retired_residue = {
@@ -644,7 +644,7 @@ export const COMMAND_CATALOG = [
644
644
  { name: 'uninstall', usage: 'sks uninstall [--dry-run] [--yes] [--keep-config] [--keep-data] [--purge-projects] [--json]', description: 'Remove SKS global skills, hooks, menu bar, state, temp files, and optional project residue while preserving user-owned content by default.' },
645
645
  { name: 'deps', usage: 'sks deps check [--json] [--yes]', description: 'Check Node/npm and Codex CLI readiness; pass --yes to repair missing Codex CLI tooling when supported.' },
646
646
  { name: 'codex', usage: 'sks codex compatibility|version|update-status [--refresh]|update|doctor|schema|current [--json]', description: 'Check Codex CLI compatibility/version/update status, run the official `codex update`, and inspect current manifest, capability, and hook-schema evidence.' },
647
- { name: 'codex-app', usage: 'sks codex-app [check|status|restart|product-design|chrome-extension|pat status|remote-control]', description: 'Check Codex App integration, Desktop Bridge readiness, Product Design plugin readiness, Codex Chrome Extension web verification readiness, PAT-safe status, first-party MCP/plugin readiness, and Codex CLI remote-control availability. Provider routing is managed only by sks bridge.' },
647
+ { name: 'codex-app', usage: 'sks codex-app [check|status|restart|context-1m [status|on|off]|product-design|chrome-extension|pat status|remote-control]', description: 'Check Codex App integration, Desktop Bridge readiness, Product Design plugin readiness, Codex Chrome Extension web verification readiness, PAT-safe status, first-party MCP/plugin readiness, Codex CLI remote-control availability, and the opt-in GPT-5.6 Sol 1M context window toggle with automatic Codex restart. Provider routing is managed only by sks bridge.' },
648
648
  { name: 'codex-native', usage: 'sks codex-native status|feature-broker|invocation-plan|init-deep [--json]', description: 'Inspect Codex Native feature broker readiness, invocation routing, pattern evidence, and managed memory setup.' },
649
649
  { name: 'hooks', usage: 'sks hooks explain|status|trust-report|replay|codex-validate|warning-check ... [--json]', description: 'Explain Codex hook events, validate current vendored event output schemas, replay fixtures, and enforce warning-zero SKS hook policies.' },
650
650
  { name: 'remote', usage: 'sks remote readiness|machines|worker ... [--json]', description: 'Inspect official Codex Remote readiness and the allowlisted proof-aware SSH stdio worker surface.' },
@@ -1,32 +1,38 @@
1
1
  import { codexHookTrustDoctor } from '../../codex-hooks/codex-hook-trust-doctor.js';
2
2
  export async function runOtherHarnessCleanupStage(root) {
3
- const { scanHarnessConflicts } = await import('../../harness-conflicts.js');
3
+ const { cleanupOtherHarnessConflicts, scanHarnessConflicts } = await import('../../harness-conflicts.js');
4
4
  const scan = await scanHarnessConflicts(root);
5
- if (scan.hard_block) {
5
+ if (!scan.hard_block) {
6
6
  return {
7
- ok: false,
8
- status: 'failed',
9
- actions: ['other_harness_conflict_detected'],
10
- blockers: scan.hard.map((row) => `other_harness_conflict:${row.path}`),
7
+ ok: true,
8
+ status: 'ok',
9
+ actions: ['other_harness_conflict_check_clean'],
10
+ blockers: [],
11
11
  warnings: [],
12
12
  detail: {
13
13
  cleaned_count: 0,
14
- remaining_count: scan.hard.length,
15
- error_count: 0,
16
- cleanup_prompt_command: 'sks conflicts cleanup --yes'
14
+ remaining_count: 0,
15
+ error_count: 0
17
16
  }
18
17
  };
19
18
  }
19
+ const cleanup = await cleanupOtherHarnessConflicts(root);
20
+ const remaining = Array.isArray(cleanup.remaining) ? cleanup.remaining : [];
21
+ const errors = Array.isArray(cleanup.errors) ? cleanup.errors : [];
22
+ const blockers = [
23
+ ...remaining.map((row) => `other_harness_conflict:${row.path || 'unknown'}`),
24
+ ...errors.map((row) => `other_harness_cleanup_failed:${row.path || 'unknown'}:${row.error || 'error'}`),
25
+ ];
20
26
  return {
21
- ok: true,
22
- status: 'ok',
23
- actions: ['other_harness_conflict_check_clean'],
24
- blockers: [],
27
+ ok: blockers.length === 0,
28
+ status: blockers.length ? 'failed' : 'ok',
29
+ actions: ['other_harness_conflicts_quarantined'],
30
+ blockers,
25
31
  warnings: [],
26
32
  detail: {
27
- cleaned_count: 0,
28
- remaining_count: 0,
29
- error_count: 0
33
+ cleaned_count: Array.isArray(cleanup.cleaned) ? cleanup.cleaned.length : 0,
34
+ remaining_count: remaining.length,
35
+ error_count: errors.length
30
36
  }
31
37
  };
32
38
  }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = '9.0.6';
1
+ export const PACKAGE_VERSION = '9.1.1';
@@ -30,7 +30,7 @@ final class ControlCenterWindowController: NSWindowController, NSTableViewDataSo
30
30
  .providers: ProvidersViewController(processClient: processClient, operations: operations),
31
31
  .remoteCoding: RemoteCodingViewController(),
32
32
  .diagnostics: DiagnosticsViewController(processClient: processClient, operations: operations),
33
- .settings: SettingsViewController(notifications: notifications)
33
+ .settings: SettingsViewController(processClient: processClient, operations: operations, notifications: notifications)
34
34
  ]
35
35
  let window = NSWindow(
36
36
  contentRect: NSRect(x: 0, y: 0, width: 860, height: 560),
@@ -8,22 +8,41 @@ final class SettingsViewController: NSViewController, ControlCenterPage {
8
8
  case malformed
9
9
  }
10
10
 
11
+ private let processClient: ProcessClient
12
+ private let operations: OperationCoordinator
11
13
  private let notifications: NotificationCoordinator
12
14
  private let followCodexLifecycle = NSButton(checkboxWithTitle: "Show SKS Menu only while Codex is running", target: nil, action: nil)
13
15
  private let status = NativeView.detail("Settings use the native app configuration file.")
16
+ private let contextStatus = NativeView.detail("Codex 1M context: checking current state…")
14
17
  private var notificationButton: NSButton!
15
- init(notifications: NotificationCoordinator) { self.notifications = notifications; super.init(nibName: nil, bundle: nil) }
18
+ private var contextToggleButton: NSButton!
19
+ private var contextEnabled: Bool?
20
+ private var contextBusy = false
21
+ private var contextGeneration = 0
22
+ init(processClient: ProcessClient, operations: OperationCoordinator, notifications: NotificationCoordinator) {
23
+ self.processClient = processClient
24
+ self.operations = operations
25
+ self.notifications = notifications
26
+ super.init(nibName: nil, bundle: nil)
27
+ }
16
28
  required init?(coder: NSCoder) { nil }
17
29
 
18
30
  override func loadView() {
19
31
  followCodexLifecycle.target = self; followCodexLifecycle.action = #selector(save)
20
32
  followCodexLifecycle.setAccessibilityLabel("Show SKS Menu only while Codex is running")
21
33
  notificationButton = NativeView.button("Enable Notifications", target: self, action: #selector(enableNotifications))
34
+ contextToggleButton = NativeView.button("Enable 1M Context", target: self, action: #selector(toggleContext1m))
35
+ contextToggleButton.isEnabled = false
22
36
  let lifecycleCard = NativeView.card(
23
37
  title: "Codex lifecycle",
24
38
  subtitle: "On keeps a lightweight observer running, hides the icon when Codex is closed, and shows it automatically when Codex opens.",
25
39
  views: [followCodexLifecycle]
26
40
  )
41
+ let contextCard = NativeView.card(
42
+ title: "Codex 1M Context",
43
+ subtitle: "Opt Codex into the documented 1,000,000-token context window for GPT-5.6 Sol (model_context_window = 1000000, model_auto_compact_token_limit = 900000 in ~/.codex/config.toml). Requests beyond 272K input tokens bill the entire request at the long-context rate, only new sessions pick up the change, and Codex restarts automatically when it is running. Off restores the previous value.",
44
+ views: [NativeView.row([contextToggleButton]), contextStatus]
45
+ )
27
46
  let notificationsCard = NativeView.card(
28
47
  title: "Notifications",
29
48
  subtitle: "Operation results always stay available in Control Center, even when notifications are denied.",
@@ -31,11 +50,12 @@ final class SettingsViewController: NSViewController, ControlCenterPage {
31
50
  )
32
51
  view = NativeView.page([
33
52
  ControlKit.header("Settings", "These options stay on this Mac. Notification permission and Codex lifecycle behavior never leave the machine."),
34
- lifecycleCard, notificationsCard
53
+ lifecycleCard, contextCard, notificationsCard
35
54
  ])
36
55
  }
37
56
 
38
57
  func refreshOnAppear() {
58
+ refreshContext1m()
39
59
  let configResult = readConfig()
40
60
  switch configResult {
41
61
  case .loaded(let config):
@@ -67,6 +87,101 @@ final class SettingsViewController: NSViewController, ControlCenterPage {
67
87
  }
68
88
  }
69
89
 
90
+ private func refreshContext1m(preserveStatusText: Bool = false) {
91
+ contextGeneration += 1
92
+ let requestGeneration = contextGeneration
93
+ processClient.run(["codex-app", "context-1m", "status", "--json"], timeout: NativeView.statusTimeout) { [weak self] result in
94
+ guard let self = self, self.contextGeneration == requestGeneration, !self.contextBusy else { return }
95
+ guard let json = self.json(result.output),
96
+ json["schema"] as? String == "sks.codex-context-1m.v1",
97
+ json["ok"] as? Bool == true,
98
+ let enabled = json["enabled"] as? Bool else {
99
+ self.contextEnabled = nil
100
+ self.contextToggleButton.isEnabled = false
101
+ if !preserveStatusText {
102
+ self.contextStatus.stringValue = "Codex 1M context state unavailable · update SKS, then reopen Settings."
103
+ self.contextStatus.textColor = .systemOrange
104
+ }
105
+ return
106
+ }
107
+ self.contextEnabled = enabled
108
+ self.contextToggleButton.isEnabled = true
109
+ self.contextToggleButton.title = enabled ? "Disable 1M Context" : "Enable 1M Context"
110
+ guard !preserveStatusText else { return }
111
+ let model = json["model"] as? String
112
+ var text = enabled
113
+ ? "Enabled · window 1,000,000 · auto-compact 900,000 · applies to new sessions only."
114
+ : "Disabled · Codex uses its tuned default context window."
115
+ var tone: NSColor = enabled ? .systemGreen : .secondaryLabelColor
116
+ if enabled, let model = model, model != "gpt-5.6-sol" {
117
+ text += " Active model is \(model); the 1M window is documented for gpt-5.6-sol."
118
+ tone = .systemOrange
119
+ }
120
+ self.contextStatus.stringValue = text
121
+ self.contextStatus.textColor = tone
122
+ }
123
+ }
124
+
125
+ @objc private func toggleContext1m() {
126
+ guard !contextBusy, let enabled = contextEnabled else { return }
127
+ let verb = enabled ? "off" : "on"
128
+ guard let snapshot = operations.begin(
129
+ kind: "codex-context-1m",
130
+ mutationGroup: "codex-config",
131
+ summary: enabled ? "Disable Codex 1M context" : "Enable Codex 1M context"
132
+ ) else {
133
+ contextStatus.stringValue = "Another guarded mutation is running. Try again after it completes."
134
+ contextStatus.textColor = .systemOrange
135
+ return
136
+ }
137
+ contextBusy = true
138
+ contextToggleButton.isEnabled = false
139
+ contextStatus.stringValue = enabled ? "Disabling 1M context…" : "Enabling 1M context and restarting Codex if it is running…"
140
+ contextStatus.textColor = .secondaryLabelColor
141
+ _ = operations.update(snapshot, state: .running, stage: "applying", progress: nil, summary: contextStatus.stringValue)
142
+ processClient.run(["codex-app", "context-1m", verb, "--json"], timeout: NativeView.mutationTimeout) { [weak self] result in
143
+ guard let self = self else { return }
144
+ self.contextBusy = false
145
+ self.contextToggleButton.isEnabled = true
146
+ let json = self.json(result.output)
147
+ let ok = result.code == 0
148
+ && json?["schema"] as? String == "sks.codex-context-1m.v1"
149
+ && json?["ok"] as? Bool == true
150
+ let summary: String
151
+ if ok {
152
+ let restart = json?["restart"] as? [String: Any]
153
+ let applied = verb == "on" ? "1M context enabled" : "1M context disabled"
154
+ if restart?["status"] as? String == "restarted" {
155
+ summary = "\(applied) · Codex restarted — start a new session to apply it."
156
+ } else if restart?["reason"] as? String == "codex_not_running" {
157
+ summary = "\(applied) · Codex is not running — the change applies on its next launch."
158
+ } else if restart?["reason"] as? String == "config_unchanged" {
159
+ summary = "\(applied) · configuration already matched; nothing restarted."
160
+ } else {
161
+ summary = "\(applied) · restart Codex manually, then start a new session."
162
+ }
163
+ } else {
164
+ let blocker = (json?["blockers"] as? [String])?.first
165
+ summary = blocker.map { "1M context change failed · \($0)" } ?? "1M context change failed · unexpected CLI response."
166
+ }
167
+ _ = self.operations.update(snapshot, state: ok ? .succeeded : .failed, stage: "complete", progress: 1, summary: summary)
168
+ self.contextStatus.stringValue = summary
169
+ self.contextStatus.textColor = ok ? .systemGreen : .systemRed
170
+ self.refreshContext1m(preserveStatusText: true)
171
+ }
172
+ }
173
+
174
+ private func json(_ text: String) -> [String: Any]? {
175
+ guard let data = text.data(using: .utf8) else { return nil }
176
+ if let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { return object }
177
+ // Child processes may print banner lines before JSON; prefer the last
178
+ // top-level object payload, matching the Overview parser.
179
+ guard let start = text.range(of: "{", options: [.backwards])?.lowerBound else { return nil }
180
+ let slice = String(text[start...])
181
+ guard let sliced = slice.data(using: .utf8) else { return nil }
182
+ return try? JSONSerialization.jsonObject(with: sliced) as? [String: Any]
183
+ }
184
+
70
185
  @objc private func enableNotifications() {
71
186
  if notifications.authorizationDenied {
72
187
  guard openSystemSettings() else {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sneakoscope",
3
3
  "displayName": "ㅅㅋㅅ",
4
- "version": "9.0.6",
4
+ "version": "9.1.1",
5
5
  "description": "Sneakoscope Codex (`sks`) is an open-source trust layer for Codex CLI and ChatGPT Desktop. It coordinates bounded AI coding agents, records machine-verifiable evidence, preserves project memory, and blocks release claims that are not supported by current tests or artifacts. Search visibility outcomes are measured separately; SKS does not promise rankings or traffic.",
6
6
  "type": "module",
7
7
  "homepage": "https://github.com/mandarange/Sneakoscope-Codex#readme",