@bitkyc08/opencodex 2.90.0 → 2.91.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/gui/dist/assets/App-DMps4OLk.css +1 -0
  2. package/gui/dist/assets/{App-DgxkE6Md.js → App-nZ34cR5G.js} +18 -18
  3. package/gui/dist/assets/{Tray-DbTNc_88.js → Tray-BuLy7hL1.js} +1 -1
  4. package/gui/dist/assets/{index-TmaHa54u.js → index-DGXS51sp.js} +12 -12
  5. package/gui/dist/assets/{quota-summary-B16x5DZZ.js → quota-summary-DO1Sx5TM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/anthropic.ts +2 -5
  9. package/src/adapters/claude-cli/usage-admission.ts +14 -0
  10. package/src/adapters/openai-responses/passthrough.ts +2 -1
  11. package/src/adapters/openai-responses/request-strips.ts +32 -0
  12. package/src/adapters/openai-responses/transport.ts +6 -0
  13. package/src/chat/inbound.ts +20 -2
  14. package/src/chat/outbound.ts +36 -4
  15. package/src/chat/reasoning-details.ts +137 -0
  16. package/src/cli/capabilities-agents-routing.ts +50 -0
  17. package/src/cli/capabilities-base.ts +15 -2
  18. package/src/cli/capabilities-observe-system.ts +4 -4
  19. package/src/cli/codex-shim-autorestore.ts +5 -0
  20. package/src/cli/dispatch.ts +30 -0
  21. package/src/cli/fallback.ts +127 -0
  22. package/src/cli/help.ts +1 -0
  23. package/src/cli/index.ts +1 -2
  24. package/src/cli/link-apply-restart.ts +72 -0
  25. package/src/cli/link-child.ts +6 -2
  26. package/src/cli/link-cleanup.ts +95 -0
  27. package/src/cli/link-enrollment.ts +4 -0
  28. package/src/cli/link.ts +84 -9
  29. package/src/cli/provider.ts +44 -2
  30. package/src/cli/registry.ts +13 -1
  31. package/src/cli/restart-failure.ts +4 -0
  32. package/src/cli/runtime-api.ts +1 -1
  33. package/src/cli/status-codex-settings.ts +56 -0
  34. package/src/cli/status-fallback.ts +29 -0
  35. package/src/cli/status-install.ts +52 -0
  36. package/src/cli/status.ts +20 -1
  37. package/src/cli/system-restart-client.ts +32 -1
  38. package/src/cli/update-restart-child.ts +4 -3
  39. package/src/cli/update-restart-home.ts +20 -8
  40. package/src/client/connect.ts +82 -6
  41. package/src/client/home-unreachable.ts +16 -0
  42. package/src/client/hub-relay.ts +8 -2
  43. package/src/client/link-home.ts +119 -6
  44. package/src/client/link-parity-reporter.ts +107 -0
  45. package/src/client/link-relay-transport.ts +8 -1
  46. package/src/client/link-relay.ts +27 -3
  47. package/src/client/machine-listener.ts +83 -1
  48. package/src/client/runtime-restart.ts +127 -0
  49. package/src/client/runtime.ts +137 -25
  50. package/src/codex/auth-context.ts +10 -6
  51. package/src/codex/catalog/parsing.ts +4 -0
  52. package/src/codex/desktop-compatibility/windows-key-protection.ts +18 -6
  53. package/src/codex/quota-history.ts +7 -0
  54. package/src/codex/quota.ts +10 -0
  55. package/src/codex/subagent-model-fallback.ts +24 -1
  56. package/src/combos/index.ts +1 -0
  57. package/src/combos/resolve.ts +12 -0
  58. package/src/config/diagnostics.ts +5 -0
  59. package/src/config/load-degrade.ts +2 -0
  60. package/src/config/schema/config-schema.ts +3 -0
  61. package/src/config/schema/fallback-policy.ts +40 -0
  62. package/src/generated/compatibility-version.json +205 -97
  63. package/src/lib/authorization-scheme.ts +95 -0
  64. package/src/lib/provider-client-headers.ts +1 -0
  65. package/src/lib/redact.ts +2 -2
  66. package/src/lib/system-restart-contract.ts +24 -0
  67. package/src/lib/test-home-guard.ts +78 -11
  68. package/src/link/child-parity.ts +124 -0
  69. package/src/link/codex-settings.ts +37 -0
  70. package/src/link/compatibility.ts +119 -0
  71. package/src/link/management-routes.ts +2 -0
  72. package/src/link/peer-report.ts +100 -0
  73. package/src/link/remote-platform.ts +78 -0
  74. package/src/link/ssh-argv.ts +19 -0
  75. package/src/link/status-projection.ts +24 -2
  76. package/src/oauth/index.ts +1 -1
  77. package/src/oauth/kimi.ts +2 -0
  78. package/src/oauth/nous.ts +4 -1
  79. package/src/oauth/store.ts +2 -1
  80. package/src/protocols/codecs/chat.ts +3 -3
  81. package/src/protocols/encoders/adapter-events.ts +26 -2
  82. package/src/protocols/encoders/chat.ts +55 -3
  83. package/src/providers/mistral-transport.ts +37 -4
  84. package/src/providers/quota/antigravity.ts +2 -8
  85. package/src/quota-pool/assemble.ts +326 -0
  86. package/src/quota-pool/contract.ts +58 -0
  87. package/src/quota-pool/identity.ts +203 -0
  88. package/src/remote/features.ts +74 -0
  89. package/src/remote/protocol.ts +2 -0
  90. package/src/remote/served-by.ts +57 -0
  91. package/src/responses/parser.ts +7 -0
  92. package/src/responses/reasoning-envelope.ts +12 -0
  93. package/src/routing/fallback-policy.ts +290 -0
  94. package/src/routing/fallback-state.ts +179 -0
  95. package/src/server/audio-client.ts +2 -1
  96. package/src/server/audio-dictation.ts +2 -1
  97. package/src/server/audio-upstream.ts +2 -1
  98. package/src/server/auth-cors.ts +6 -5
  99. package/src/server/background-lifecycle.ts +4 -0
  100. package/src/server/chat-completions.ts +8 -1
  101. package/src/server/gui-session.ts +2 -1
  102. package/src/server/index/link-listener.ts +11 -1
  103. package/src/server/index/link-management.ts +47 -0
  104. package/src/server/index/link-relay-sessions.ts +11 -2
  105. package/src/server/index/optional-listeners.ts +7 -2
  106. package/src/server/index/serve-options.ts +19 -2
  107. package/src/server/live.ts +5 -0
  108. package/src/server/management/context.ts +1 -1
  109. package/src/server/management/fallback-routes.ts +75 -0
  110. package/src/server/management/link-enrollment.ts +21 -3
  111. package/src/server/management/link-route-state.ts +2 -0
  112. package/src/server/management/link-routes.ts +12 -1
  113. package/src/server/management/quota-pool-routes.ts +24 -0
  114. package/src/server/management/route-registry.ts +3 -0
  115. package/src/server/management-api.ts +16 -0
  116. package/src/server/management-auth.ts +2 -1
  117. package/src/server/responses/agent-task-recovery.ts +1 -1
  118. package/src/server/responses/compact.ts +2 -2
  119. package/src/server/responses/core-auth.ts +11 -1
  120. package/src/server/responses/core-combo.ts +72 -1
  121. package/src/server/responses/encrypted-payload.ts +3 -3
  122. package/src/server/responses/main-hard-lock-routing.ts +54 -2
  123. package/src/server/responses/policy-fallback.ts +44 -1
  124. package/src/server/responses/request-prepare.ts +9 -1
  125. package/src/server/restart-replacement.ts +50 -2
  126. package/src/server/ws-bridge.ts +5 -0
  127. package/src/service/cli.ts +25 -2
  128. package/src/service/diagnostics.ts +20 -6
  129. package/src/service/status-json.ts +116 -0
  130. package/src/types/config.ts +7 -0
  131. package/src/types/fallback.ts +38 -0
  132. package/gui/dist/assets/App-dnkJ85te.css +0 -1
@@ -203,6 +203,56 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
203
203
  json: "payload",
204
204
  details: ["Without --list at least one setting is required. Stored settings and Codex application outcomes remain distinct.","Stream-routed-output belongs only to web. Timeout changes preserve siblings; native apply and saved state are distinct."],
205
205
  },
206
+ {
207
+ command: ["fallback"],
208
+ usage: "ocx fallback [status] [--json]",
209
+ summary: "Show which model and provider fallbacks are allowed, per-device local fallback, and the last fallback taken or refused.",
210
+ routes: [{"method": "GET", "path": "/api/fallback"}],
211
+ flags: [{"name": "--json", "value": "boolean", "summary": "Emit the ocx.fallback/1 state."}],
212
+ mutates: false,
213
+ json: "payload",
214
+ details: ["Reads the live proxy. On a Remote Link Child it reads the Home's state over the link (aliases omitted). The last event is in memory and resets on restart."],
215
+ },
216
+ {
217
+ command: ["fallback", "off"],
218
+ usage: "ocx fallback off [--kind model|provider|all] [--provider <name> | --route <selector> | --device <id|alias>] [--json]",
219
+ summary: "Refuse model or provider fallback globally or for one provider, route or device.",
220
+ routes: [{"method": "PUT", "path": "/api/fallback"}],
221
+ flags: [{"name": "--kind", "value": "string", "summary": "model, provider or all (default)."}, {"name": "--provider", "value": "string", "summary": "Scope to the provider a request started on."}, {"name": "--route", "value": "string", "summary": "Scope to an exact selector such as combo/<id> or policy/<id>."}, {"name": "--device", "value": "string", "summary": "Scope to a Remote Link id or alias, or a Hub data key id; device off always refuses."}, {"name": "--json", "value": "boolean", "summary": "Emit the resulting state."}],
222
+ mutates: true,
223
+ json: "payload",
224
+ details: ["A refused hop answers fallback_refused with the triggering failure's status. Rotation among accounts or keys of one provider pool is not a fallback and stays on."],
225
+ },
226
+ {
227
+ command: ["fallback", "on"],
228
+ usage: "ocx fallback on [--kind model|provider|all] [--provider <name> | --route <selector> | --device <id|alias>] [--json]",
229
+ summary: "Allow model or provider fallback at one scope, overriding a broader off.",
230
+ routes: [{"method": "PUT", "path": "/api/fallback"}],
231
+ flags: [{"name": "--kind", "value": "string", "summary": "model, provider or all (default)."}, {"name": "--provider", "value": "string", "summary": "Scope to a provider."}, {"name": "--route", "value": "string", "summary": "Scope to an exact selector."}, {"name": "--device", "value": "string", "summary": "Scope to a device."}, {"name": "--json", "value": "boolean", "summary": "Emit the resulting state."}],
232
+ mutates: true,
233
+ json: "payload",
234
+ details: ["Route beats provider beats global. A device setting can only refuse: on for a device records the value but never reopens a hop another scope refuses."],
235
+ },
236
+ {
237
+ command: ["fallback", "clear"],
238
+ usage: "ocx fallback clear [--kind model|provider|all] [--provider <name> | --route <selector> | --device <id|alias>] [--json]",
239
+ summary: "Remove a fallback override so the scope inherits again.",
240
+ routes: [{"method": "PUT", "path": "/api/fallback"}],
241
+ flags: [{"name": "--kind", "value": "string", "summary": "model, provider or all (default)."}, {"name": "--provider", "value": "string", "summary": "Scope to a provider."}, {"name": "--route", "value": "string", "summary": "Scope to an exact selector."}, {"name": "--device", "value": "string", "summary": "Scope to a device."}, {"name": "--json", "value": "boolean", "summary": "Emit the resulting state."}],
242
+ mutates: true,
243
+ json: "payload",
244
+ details: ["Clearing every override restores today's behavior: every fallback allowed."],
245
+ },
246
+ {
247
+ command: ["fallback", "local"],
248
+ usage: "ocx fallback local <on|off> --device <id|alias> [--json]",
249
+ summary: "Record whether a device may use its own providers while the Home is unreachable.",
250
+ routes: [{"method": "PUT", "path": "/api/fallback"}],
251
+ flags: [{"name": "--device", "value": "string", "summary": "Remote Link id or alias, or Hub data key id."}, {"name": "--json", "value": "boolean", "summary": "Emit the resulting state."}],
252
+ mutates: true,
253
+ json: "payload",
254
+ details: ["Run on the Home. A permission GOAT reads; OpenCodex itself keeps answering home_unreachable on the device and never serves it from local providers."],
255
+ },
206
256
  {
207
257
  command: ["effort"],
208
258
  usage: "ocx effort [status|low|medium|high|xhigh|max|ultra|->] [--json]",
@@ -86,6 +86,16 @@ export const CAPABILITIES: readonly Capability[] = [
86
86
  usage: "ocx link reconnect --link-id <id> [--json]",
87
87
  details: ["Requires a valid link ID and loopback admin authority. Stops the current ssh child, clears any backoff or failed state and starts a fresh attempt; read ocx link status for the outcome.","A Child-initiated link is refused with link_not_home_initiated: its own computer owns and retries that tunnel.","Always emits {linkId} JSON."],
88
88
  },
89
+ {
90
+ command: ["link","cleanup"],
91
+ summary: "Find Windows Remote Link Children and explain how to move them to Hub mode.",
92
+ routes: [],
93
+ flags: [{"name":"--link-id","value":"string","summary":"Check only this link."},{"name":"--json","value":"boolean","summary":"Emit {links, changed:false} as JSON."}],
94
+ mutates: false,
95
+ json: "payload",
96
+ usage: "ocx link cleanup [--link-id <id>] [--json]",
97
+ details: ["Runs on the Home from its local link store. Asks each Home-initiated Child for uname -s over the link's pinned SSH trust; a Windows answer (Git Bash, MSYS, Cygwin, cmd or PowerShell) is reported with recovery steps.","Never revokes, disconnects or edits a link. A Windows Child needs ocx disconnect on itself, then ocx link revoke --force --yes on the Home, then ocx hub invite and ocx connect."],
98
+ },
89
99
  {
90
100
  command: ["remote-workspace","pair"],
91
101
  summary: "Enroll this executor with one Hub using a one-time code from stdin and locally approved roots.",
@@ -156,7 +166,7 @@ export const CAPABILITIES: readonly Capability[] = [
156
166
  flags: [{ name: "--json", value: "boolean", summary: "Emit the status envelope as JSON." }],
157
167
  mutates: false,
158
168
  json: "envelope",
159
- details: ["Reads /healthz plus local config; drives no management API route."],
169
+ details: ["Reads /healthz plus local config; drives no management API route.", "--json includes install: {method: bun|npm|pnpm|mise|source|standalone|unknown, evidence: {basis, mise?, error?}} from the updater's install detector."],
160
170
  },
161
171
  {
162
172
  command: ["resolve"],
@@ -225,7 +235,10 @@ export const CAPABILITIES: readonly Capability[] = [
225
235
  flags: [{"name":"--json","value":"boolean","summary":"Emit the provider list as JSON."},{"name":"--jsonl","value":"boolean","summary":"Emit one configured provider per JSON line."}],
226
236
  mutates: false,
227
237
  json: "envelope",
228
- details: ["Local config and registry read, not GET /api/providers. --json and --jsonl are mutually exclusive."],
238
+ details: [
239
+ "Local config and registry read, not GET /api/providers. --json and --jsonl are mutually exclusive.",
240
+ "Each configured row carries active: false while this device is linked to a Home (a Remote Link Child or a Hub-mode client), whose providers serve instead; true when the row serves. Credential values are never printed.",
241
+ ],
229
242
  usage: "ocx provider list [--json|--jsonl]",
230
243
  },
231
244
  {
@@ -621,11 +621,11 @@ export const OBSERVE_SYSTEM_CAPABILITIES: readonly Capability[] = [
621
621
  },
622
622
  {
623
623
  command: ["service", "status"], summary: "Inspect local service-manager status.",
624
- usage: "ocx service status",
624
+ usage: "ocx service status [--json]",
625
625
  routes: [],
626
- flags: [],
627
- mutates: false, json: "none",
628
- details: ["Local OS service manager: macOS launchd, Linux systemd, Windows Task Scheduler or WinSW. No management API or JSON mode.", "Backend options apply only to install; other verbs use the installed backend."],
626
+ flags: [{"name": "--json", "value": "boolean", "summary": "Emit the passive service status document as JSON."}],
627
+ mutates: false, json: "payload",
628
+ details: ["Local OS service manager: macOS launchd, Linux systemd, Windows Task Scheduler or WinSW. No management API.", "--json is passive: schemaVersion 1 with installed, running, enabled, viable, stale, conflict, backend (launchd|systemd|schtasks|winsw|none), label, serving {probed, ok, port}, summary, logPath, ownershipLease and desktopLogin. It starts, stops, installs and repairs nothing.", "Backend options apply only to install; other verbs use the installed backend."],
629
629
  },
630
630
  {
631
631
  command: ["service", "uninstall"], summary: "Uninstall the local service.",
@@ -26,6 +26,11 @@ export function skipsCodexShimAutoRestore(command: string | undefined, args: str
26
26
  // `resolve` is read-only inspection for embedding shells: a lookup made to populate
27
27
  // a consent surface must not trigger a shim repair side effect first.
28
28
  if (command === "resolve") return true;
29
+ // `service status --json` is a passive inventory read for peers such as GOAT: a shim repair
30
+ // before dispatch would change the installation it was asked only to describe.
31
+ // Flags may precede the verb (`ocx service --json status`), exactly as parseServiceArgs reads it.
32
+ if (command === "service" && args.includes("--json")
33
+ && args.slice(1).find(arg => !arg.startsWith("--")) === "status") return true;
29
34
  // The desktop's approval-bound stop must validate its snapshot before any unrelated
30
35
  // CLI repair changes the installation it was approved against.
31
36
  if (command === "stop" && args.some(arg => arg.startsWith("--expect-"))) return true;
@@ -437,6 +437,32 @@ const commandRunners: Record<string, CommandRunner> = {
437
437
  }
438
438
  }
439
439
  await handleConnectedSyncCatalogWrite(result, restartScope);
440
+ if (result.applyRecordFailed) {
441
+ console.error("The Home's Codex settings were applied, but the apply record could not be written; the client runtime was not restarted. Run 'ocx sync' again.");
442
+ process.exitCode = 1;
443
+ }
444
+ // OCX-6: a link Child's runtime must have started after the apply it serves under.
445
+ if (link && result.appliedRecord) {
446
+ const { applyRestartMessage, restartRuntimeAfterApply } = await import("./link-apply-restart");
447
+ const { sameClientConnectionOwner } = await import("../client/state");
448
+ const applied = clientState.value;
449
+ const outcome = await restartRuntimeAfterApply(result.appliedRecord, {
450
+ restart: startWhenStopped => deps.handleProxyRestart(startWhenStopped),
451
+ recoveryStart: recovering => deps.handleRestartStartWhenStopped(recovering),
452
+ connectionUnchanged: () => {
453
+ const current = readClientConnectionState();
454
+ return current.kind === "connected" && sameClientConnectionOwner(current.value, applied)
455
+ && current.value.link?.linkId === applied.link?.linkId;
456
+ },
457
+ });
458
+ const message = applyRestartMessage(outcome);
459
+ if (outcome.kind === "failed" || outcome.kind === "connection-changed") {
460
+ console.error(message);
461
+ process.exitCode = 1;
462
+ } else {
463
+ console.log(message);
464
+ }
465
+ }
440
466
  // `process.exitCode` rather than a literal 0, for the same reason every other
441
467
  // runner does it (tests/cli/cli-transport-honesty.test.ts): the catalog-write helper
442
468
  // drives app-server restarts, and one of those recording a failure must not be
@@ -876,6 +902,10 @@ const commandRunners: Record<string, CommandRunner> = {
876
902
  const { handleEffortCommand } = await import("./effort");
877
903
  return await handleEffortCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
878
904
  },
905
+ fallback: async deps => {
906
+ const { handleFallbackCommand } = await import("./fallback");
907
+ return await handleFallbackCommand(deps.args.slice(1), { findLiveProxy: deps.findLiveProxy });
908
+ },
879
909
  agent: async deps => {
880
910
  const { handleAgentCommand } = await import("./agent");
881
911
  return await handleAgentCommand(deps.args.slice(1));
@@ -0,0 +1,127 @@
1
+ import {
2
+ CliUsageError,
3
+ printData,
4
+ rejectArgs,
5
+ runCliAction,
6
+ runtimeRequest,
7
+ takeFlag,
8
+ takeOption,
9
+ terminalSafeText,
10
+ type RuntimeApiDeps,
11
+ } from "./runtime-api";
12
+
13
+ export const FALLBACK_USAGE = `Usage:
14
+ ocx fallback status [--json]
15
+ ocx fallback off [--kind model|provider|all] [--provider <name> | --route <selector> | --device <id|alias>] [--json]
16
+ ocx fallback on [--kind model|provider|all] [--provider <name> | --route <selector> | --device <id|alias>] [--json]
17
+ ocx fallback clear [--kind model|provider|all] [--provider <name> | --route <selector> | --device <id|alias>] [--json]
18
+ ocx fallback local <on|off> --device <id|alias> [--json]`;
19
+
20
+ type Switches = { model?: boolean; provider?: boolean };
21
+ interface DeviceRow { id?: string; alias?: string; localFallback?: boolean; model?: boolean | null; provider?: boolean | null }
22
+ interface EventRow { at?: string; site?: string; route?: string; kind?: string; from?: string; to?: string; trigger?: string; outcome?: string; scope?: string }
23
+ interface FallbackState {
24
+ global?: { model?: boolean; provider?: boolean };
25
+ providers?: Record<string, Switches>;
26
+ routes?: Record<string, Switches>;
27
+ devices?: DeviceRow[];
28
+ last?: EventRow | null;
29
+ }
30
+
31
+ const onOff = (value: boolean | null | undefined): string => value === false ? "off" : value === true ? "on" : "inherit";
32
+
33
+ function switchesLine(label: string, value: Switches): string {
34
+ const parts: string[] = [];
35
+ if (value.model !== undefined) parts.push("model " + onOff(value.model));
36
+ if (value.provider !== undefined) parts.push("provider " + onOff(value.provider));
37
+ return terminalSafeText(label) + ": " + parts.join(", ");
38
+ }
39
+
40
+ export function fallbackStatusLines(state: FallbackState): string[] {
41
+ const lines = [
42
+ "model fallback: " + (state.global?.model === false ? "off" : "on") + " (global)",
43
+ "provider fallback: " + (state.global?.provider === false ? "off" : "on") + " (global)",
44
+ ];
45
+ for (const [name, value] of Object.entries(state.providers ?? {})) lines.push(switchesLine("provider " + name, value));
46
+ for (const [name, value] of Object.entries(state.routes ?? {})) lines.push(switchesLine("route " + name, value));
47
+ for (const device of state.devices ?? []) {
48
+ const label = "device " + (device.id ?? "?") + (device.alias ? " (" + device.alias + ")" : "");
49
+ lines.push(terminalSafeText(label) + ": local fallback " + (device.localFallback ? "allowed" : "off")
50
+ + ", model " + onOff(device.model) + ", provider " + onOff(device.provider));
51
+ }
52
+ const last = state.last;
53
+ lines.push(last
54
+ ? terminalSafeText("last: " + last.at + " " + last.outcome + " " + last.kind + " fallback on " + last.route + ": "
55
+ + last.from + " -> " + last.to + " (" + last.trigger + ", " + last.scope + ")")
56
+ : "last: no fallback since this proxy started");
57
+ return lines;
58
+ }
59
+
60
+ function takeScope(args: string[]): { scope: "global" | "provider" | "route" | "device"; key?: string } {
61
+ const provider = takeOption(args, "--provider");
62
+ const route = takeOption(args, "--route");
63
+ const device = takeOption(args, "--device");
64
+ const given = [provider, route, device].filter(value => value !== undefined);
65
+ if (given.length > 1) throw new CliUsageError("use one of --provider, --route or --device", FALLBACK_USAGE);
66
+ if (provider !== undefined) return { scope: "provider", key: provider };
67
+ if (route !== undefined) return { scope: "route", key: route };
68
+ if (device !== undefined) return { scope: "device", key: device };
69
+ return { scope: "global" };
70
+ }
71
+
72
+ function takeKinds(args: string[]): Array<"model" | "provider"> {
73
+ const kind = takeOption(args, "--kind") ?? "all";
74
+ if (kind === "all") return ["model", "provider"];
75
+ if (kind === "model" || kind === "provider") return [kind];
76
+ throw new CliUsageError("--kind must be model, provider or all", FALLBACK_USAGE);
77
+ }
78
+
79
+ async function put(body: Record<string, unknown>, deps: RuntimeApiDeps): Promise<FallbackState> {
80
+ return await runtimeRequest<FallbackState>("/api/fallback", {
81
+ method: "PUT",
82
+ headers: { "content-type": "application/json" },
83
+ body: JSON.stringify(body),
84
+ }, deps);
85
+ }
86
+
87
+ async function status(argv: string[], deps: RuntimeApiDeps): Promise<void> {
88
+ const args = [...argv];
89
+ const wantsJson = takeFlag(args, "--json");
90
+ rejectArgs(args, FALLBACK_USAGE);
91
+ const state = await runtimeRequest<FallbackState>("/api/fallback", {}, deps);
92
+ printData(state, wantsJson, fallbackStatusLines(state));
93
+ }
94
+
95
+ async function setSwitch(argv: string[], value: boolean | null, deps: RuntimeApiDeps): Promise<void> {
96
+ const args = [...argv];
97
+ const wantsJson = takeFlag(args, "--json");
98
+ const kinds = takeKinds(args);
99
+ const scope = takeScope(args);
100
+ rejectArgs(args, FALLBACK_USAGE);
101
+ const state = await put({ writes: kinds.map(setting => ({ ...scope, setting, value })) }, deps);
102
+ printData(state, wantsJson, fallbackStatusLines(state));
103
+ }
104
+
105
+ async function local(argv: string[], deps: RuntimeApiDeps): Promise<void> {
106
+ const args = [...argv];
107
+ const wantsJson = takeFlag(args, "--json");
108
+ const mode = args.shift();
109
+ if (mode !== "on" && mode !== "off") throw new CliUsageError("fallback local needs on or off", FALLBACK_USAGE);
110
+ const device = takeOption(args, "--device");
111
+ if (!device) throw new CliUsageError("fallback local needs --device <id|alias>", FALLBACK_USAGE);
112
+ rejectArgs(args, FALLBACK_USAGE);
113
+ const state = await put({ scope: "device", key: device, setting: "localFallback", value: mode === "on" }, deps);
114
+ printData(state, wantsJson, fallbackStatusLines(state));
115
+ }
116
+
117
+ export async function handleFallbackCommand(argv: string[], deps: RuntimeApiDeps = {}): Promise<number> {
118
+ return runCliAction(async () => {
119
+ const [sub, ...rest] = argv;
120
+ if (sub === undefined || sub === "status") await status(rest, deps);
121
+ else if (sub === "off") await setSwitch(rest, false, deps);
122
+ else if (sub === "on") await setSwitch(rest, true, deps);
123
+ else if (sub === "clear") await setSwitch(rest, null, deps);
124
+ else if (sub === "local") await local(rest, deps);
125
+ else throw new CliUsageError("unknown fallback command: " + sub, FALLBACK_USAGE);
126
+ });
127
+ }
package/src/cli/help.ts CHANGED
@@ -81,6 +81,7 @@ Usage:
81
81
  ocx agent <sub> Subagents, injection, effort caps, and sidecars
82
82
  ocx message <sub> Codex queued messages, explicit SSH peers and foreground ownership
83
83
  ocx effort [sub] Inspect and configure reasoning effort caps and defaults
84
+ ocx fallback <sub> Turn model or provider fallback off per scope; per-device local fallback
84
85
  ocx observe <sub> Logs, usage, storage, memory, and debug data
85
86
  ocx inspect <sub> Effective config, catalog, analytics, pacing, client-config
86
87
  ocx route <sub> Routing features (combo, policy)
package/src/cli/index.ts CHANGED
@@ -167,7 +167,7 @@ import { startClientRuntimeUnderOwnershipLease } from "./client-start-fence";
167
167
  import { recoverStartStateUnderOwnershipLease } from "./start-owner-fence";
168
168
  import { handledSignalExitCode } from "../lib/handled-signal-exit";
169
169
  import { createLocalAttestationSecret } from "../lib/local-management-attestation";
170
- import { MEMORY_DRAIN_RESTART_MS, REPLACEMENT_READY_TIMEOUT_MS } from "../lib/system-restart-contract";
170
+ import { MEMORY_DRAIN_RESTART_MS, REPLACEMENT_READY_TIMEOUT_MS, RESTART_REOBSERVE_RESERVE_MS } from "../lib/system-restart-contract";
171
171
  import { startServiceLogging } from "../service/logging";
172
172
 
173
173
  /**
@@ -941,7 +941,6 @@ async function handleTrayProxyStart(existingIsSuccess = true): Promise<boolean>
941
941
  const PROXY_RESTART_OBSERVE_MS = MEMORY_DRAIN_RESTART_MS + REPLACEMENT_READY_TIMEOUT_MS + 15_000;
942
942
 
943
943
  /** Reserve confirmation time within the shared restart deadline. */
944
- const RESTART_REOBSERVE_RESERVE_MS = 10_000;
945
944
  async function handleProxyRestart(
946
945
  startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>,
947
946
  ): Promise<boolean> {
@@ -0,0 +1,72 @@
1
+ /**
2
+ * After `ocx sync` applies the Home's Codex settings on a Remote Link Child, restart the Child's
3
+ * runtime so it started after the apply (OCX-6, P5).
4
+ *
5
+ * Idempotent: the record keeps its apply time while the settings digest is unchanged, so a runtime
6
+ * that already started after it is left alone, and a sync after a failed restart retries it. The
7
+ * restart is `ocx restart`'s own (`handleProxyRestart`); this module only decides whether to call
8
+ * it and never starts a runtime that was not running, except to recover one an accepted restart
9
+ * left absent.
10
+ */
11
+ import type { HomeCodexSettingsRecord } from "../client/link-home";
12
+ import { findLiveProxy, probeHostname, type LiveProxy } from "../server/proxy-liveness";
13
+ import type { ProxyRestartStartOutcome } from "./tray-proxy";
14
+
15
+ export type ApplyRestartOutcome =
16
+ | { kind: "current" }
17
+ | { kind: "not-running" }
18
+ | { kind: "connection-changed" }
19
+ | { kind: "restarted" }
20
+ | { kind: "failed" };
21
+
22
+ export interface ApplyRestartDeps {
23
+ findLive?: () => Promise<LiveProxy | null>;
24
+ /** Epoch ms the live client runtime reports as its start, or null when it reports none. */
25
+ readStartedAt?: (live: LiveProxy) => Promise<number | null>;
26
+ restart: (startWhenStopped: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>) => Promise<boolean>;
27
+ recoveryStart: (recoveringLiveRestart: boolean) => Promise<ProxyRestartStartOutcome>;
28
+ /** Still the connection this sync applied for (rechecked right before the restart). */
29
+ connectionUnchanged: () => boolean;
30
+ }
31
+
32
+ export async function readClientRuntimeStartedAt(live: LiveProxy, fetchImpl: typeof fetch = fetch): Promise<number | null> {
33
+ try {
34
+ const response = await fetchImpl(`http://${probeHostname(live.hostname)}:${live.port}/healthz`, {
35
+ headers: { accept: "application/json" },
36
+ redirect: "manual",
37
+ signal: AbortSignal.timeout(2_000),
38
+ });
39
+ if (!response.ok) return null;
40
+ const body = await response.json() as { pid?: unknown; startedAt?: unknown } | null;
41
+ if (body?.pid !== live.pid || typeof body.startedAt !== "string") return null;
42
+ const startedAt = Date.parse(body.startedAt);
43
+ return Number.isFinite(startedAt) ? startedAt : null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export async function restartRuntimeAfterApply(record: HomeCodexSettingsRecord, deps: ApplyRestartDeps): Promise<ApplyRestartOutcome> {
50
+ const live = await (deps.findLive ?? (() => findLiveProxy()))();
51
+ if (!live || live.role !== "client") return { kind: "not-running" };
52
+ const appliedAt = Date.parse(record.appliedAt);
53
+ // A runtime that reports no start time predates OCX-6 and cannot prove it is current.
54
+ const startedAt = await (deps.readStartedAt ?? (target => readClientRuntimeStartedAt(target)))(live);
55
+ if (startedAt !== null && Number.isFinite(appliedAt) && startedAt >= appliedAt) return { kind: "current" };
56
+ if (!deps.connectionUnchanged()) return { kind: "connection-changed" };
57
+ const ok = await deps.restart(async recovering => recovering
58
+ ? deps.recoveryStart(true)
59
+ : { status: "skipped" });
60
+ return ok ? { kind: "restarted" } : { kind: "failed" };
61
+ }
62
+
63
+ /** One line for each outcome, printed by `ocx sync`. */
64
+ export function applyRestartMessage(outcome: ApplyRestartOutcome): string {
65
+ switch (outcome.kind) {
66
+ case "current": return "Client runtime already started after this apply; no restart needed.";
67
+ case "not-running": return "No client runtime is running; the applied settings take effect when it starts.";
68
+ case "connection-changed": return "The connection changed during sync; the client runtime was not restarted. Run 'ocx sync' again.";
69
+ case "restarted": return "Client runtime restarted after applying the Home's settings.";
70
+ case "failed": return "The client runtime restart did not complete; the previous runtime keeps serving. If a background service or the desktop app owns it, restart it there; otherwise retry with 'ocx restart' or 'ocx sync'.";
71
+ }
72
+ }
@@ -74,6 +74,7 @@ export async function readLinkHomeJson(
74
74
  context: LinkChildContext,
75
75
  path: string,
76
76
  deps: LinkHomeDeps = {},
77
+ init: { signal?: AbortSignal } = {},
77
78
  ): Promise<{ status: number; body: unknown }> {
78
79
  const token = readServiceApiTokenState();
79
80
  if (token.kind !== "present" || token.fingerprint !== context.connection.tokenFingerprint) {
@@ -81,12 +82,15 @@ export async function readLinkHomeJson(
81
82
  }
82
83
  let response: Response;
83
84
  try {
84
- response = await fetchLinkHomeManagement(context.connection, token.token, path.startsWith("/") ? path : `/${path}`, {}, deps);
85
+ response = await fetchLinkHomeManagement(context.connection, token.token, path.startsWith("/") ? path : `/${path}`,
86
+ init.signal ? { signal: init.signal } : {}, deps);
85
87
  } catch (error) {
86
88
  const detail = error instanceof Error && error.name === "LinkRelayAuthenticationError" ? error.message : "the link tunnel did not answer";
87
89
  throw new Error(`Could not read ${context.homePhrase} over Remote Link (${context.linkId}): ${detail}.`);
88
90
  }
89
- const result = await readBoundedResponseBytes(response, { maxBytes: RESPONSE_MAX_BYTES, signal: AbortSignal.timeout(30_000) });
91
+ // A caller's deadline (the status report's 2 s) bounds the body read as well as the request.
92
+ const readSignal = init.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(30_000)]) : AbortSignal.timeout(30_000);
93
+ const result = await readBoundedResponseBytes(response, { maxBytes: RESPONSE_MAX_BYTES, signal: readSignal });
90
94
  if (result.oversized) throw new Error(`${context.homePhrase} returned a response larger than the CLI accepts.`);
91
95
  const text = new TextDecoder().decode(result.bytes);
92
96
  let body: unknown = null;
@@ -0,0 +1,95 @@
1
+ /**
2
+ * `ocx link cleanup`: find Home-initiated Remote Link Children that run Windows and explain how to
3
+ * move each one to Hub mode. It never revokes or changes anything.
4
+ *
5
+ * Windows Children are refused at enrollment, but a link enrolled before that refusal existed keeps
6
+ * its record, key and reverse tunnel. Its record carries no platform, so this command asks the
7
+ * Child over the same pinned SSH trust the tunnel uses (`uname -s` through `sh`) and classifies the
8
+ * answer with `detectRemotePlatform` (a localized cmd or PowerShell refusal gets the fixed %OS% probe).
9
+ *
10
+ * The recovery order matters. An ordinary `ocx link revoke` runs `ocx disconnect` on the Child
11
+ * through the POSIX ocx prelude, which exits 125 on Windows, so for these Children the revoke must
12
+ * be forced after the Child disconnected itself.
13
+ */
14
+ import { linkKnownHostsPath, linkStorePath } from "../link/paths";
15
+ import { detectRemotePlatform, REMOTE_UNAME_ARGV, type RemotePlatform } from "../link/remote-platform";
16
+ import { buildExecArgv } from "../link/ssh-argv";
17
+ import { createSshRunner, sshFailureHint, sshRunnerErrorHint, type SshRunner } from "../link/ssh-runner";
18
+ import { readLinkStore, type LinkStore } from "../link/store";
19
+ import { CliUsageError, printData, rejectArgs, takeJsonFlag, takeOption } from "./runtime-api";
20
+
21
+ const LINK_ID = /^lnk_[0-9a-f]{16}$/;
22
+ const CHECK_TIMEOUT_MS = 30_000;
23
+
24
+ export interface LinkCleanupDeps {
25
+ readStore?: () => LinkStore;
26
+ sshRunner?: SshRunner;
27
+ knownHostsFile?: string;
28
+ }
29
+
30
+ export interface LinkCleanupEntry {
31
+ linkId: string;
32
+ alias: string;
33
+ direction: LinkStore["links"][number]["direction"];
34
+ platform: RemotePlatform | "not_checked";
35
+ reason: string | null;
36
+ recovery: string[];
37
+ }
38
+
39
+ export function windowsChildRecovery(linkId: string, alias: string): string[] {
40
+ return [
41
+ `On ${alias}, run 'ocx disconnect' and then 'ocx restart' so it stops using this link.`,
42
+ `On this Home, run 'ocx link revoke --link-id ${linkId} --force --yes'. A plain revoke cannot disconnect a Windows Child remotely.`,
43
+ `Then connect ${alias} in Hub mode: run 'ocx hub invite' on a Hub and the printed 'ocx connect' command on ${alias}.`,
44
+ ];
45
+ }
46
+
47
+ async function checkPlatform(runner: SshRunner, alias: string, knownHostsFile: string): Promise<{ platform: RemotePlatform; reason: string | null }> {
48
+ try {
49
+ const result = await runner.run(buildExecArgv({ alias, argv: REMOTE_UNAME_ARGV, knownHostsFile }), { timeoutMs: CHECK_TIMEOUT_MS });
50
+ const platform = await detectRemotePlatform(runner, alias, knownHostsFile, result);
51
+ return { platform, reason: platform === "unknown" ? (sshFailureHint(result.stderr) ?? `ssh exited ${result.code}`) : null };
52
+ } catch (error) {
53
+ return { platform: "unknown", reason: sshRunnerErrorHint(error) ?? "ssh could not run" };
54
+ }
55
+ }
56
+
57
+ function humanLines(entries: LinkCleanupEntry[]): string[] {
58
+ if (entries.length === 0) return ["No links are recorded on this Home.", "Nothing was revoked or changed."];
59
+ const lines: string[] = [];
60
+ for (const entry of entries) {
61
+ const label = `${entry.linkId} (${entry.alias})`;
62
+ if (entry.platform === "windows") {
63
+ lines.push(`${label}: Windows Child. Remote Link does not support Windows Children; this link predates that refusal.`);
64
+ for (const [index, step] of entry.recovery.entries()) lines.push(` ${index + 1}. ${step}`);
65
+ } else if (entry.platform === "posix") lines.push(`${label}: macOS or Linux Child; nothing to clean up.`);
66
+ else if (entry.platform === "not_checked") lines.push(`${label}: Child-initiated; this Home has no SSH route to check it.`);
67
+ else lines.push(`${label}: platform could not be checked (${entry.reason ?? "unknown"}); retry when it is reachable.`);
68
+ }
69
+ lines.push("Nothing was revoked or changed.");
70
+ return lines;
71
+ }
72
+
73
+ export async function runLinkCleanup(args: string[], deps: LinkCleanupDeps, usage: string): Promise<void> {
74
+ const wantsJson = takeJsonFlag(args);
75
+ const linkId = takeOption(args, "--link-id");
76
+ if (linkId !== undefined && !LINK_ID.test(linkId)) throw new CliUsageError("cleanup --link-id must be a valid link id", usage);
77
+ rejectArgs(args, usage);
78
+ const store = (deps.readStore ?? (() => readLinkStore(linkStorePath())))();
79
+ const records = linkId === undefined ? store.links : store.links.filter(link => link.id === linkId);
80
+ if (linkId !== undefined && records.length === 0) throw new CliUsageError(`No link ${linkId} is recorded on this Home.`, usage);
81
+ const runner = deps.sshRunner ?? createSshRunner();
82
+ const knownHostsFile = deps.knownHostsFile ?? linkKnownHostsPath();
83
+ const entries: LinkCleanupEntry[] = [];
84
+ // One at a time: each check is a bounded SSH command, and order keeps the report stable.
85
+ for (const record of records) {
86
+ const checked = record.direction === "hub-initiated"
87
+ ? await checkPlatform(runner, record.alias, knownHostsFile)
88
+ : { platform: "not_checked" as const, reason: null };
89
+ entries.push({
90
+ linkId: record.id, alias: record.alias, direction: record.direction, ...checked,
91
+ recovery: checked.platform === "windows" ? windowsChildRecovery(record.id, record.alias) : [],
92
+ });
93
+ }
94
+ printData({ links: entries, changed: false }, wantsJson, humanLines(entries));
95
+ }
@@ -1,5 +1,6 @@
1
1
  import { createInterface } from "node:readline/promises";
2
2
  import { assertSshAlias } from "../link/ssh-argv";
3
+ import { windowsChildRefusal } from "../link/remote-platform";
3
4
  import { CliUsageError, RuntimeApiError, runtimeBaseUrl, rejectArgs, takeJsonFlag, takeOption, printData } from "./runtime-api";
4
5
  import type { LinkCliDeps } from "./link";
5
6
 
@@ -83,6 +84,9 @@ export async function runLinkEnrollment(command: "probe" | "add", args: string[]
83
84
  catch (error) {
84
85
  if (error instanceof RuntimeApiError && record(error.body)) {
85
86
  const code = record(error.body.error) ? error.body.error.code : undefined;
87
+ // Refused at probe or confirm, before any key or tunnel: point at Hub mode, not at a phase.
88
+ // A residual response comes after key issuance; it keeps its Child recovery below.
89
+ if (code === "remote_platform_unsupported" && error.body.residual !== true) throw new Error(windowsChildRefusal(alias));
86
90
  const phase = typeof code === "string" && Object.hasOwn(PHASES, code) ? PHASES[code] : undefined;
87
91
  const message = phase ? "Remote Link failed during " + phase : error.message;
88
92
  if (phase || error.body.residual === true) throw new Error(message + (error.body.residual === true ? ". " + RECOVERY : ""));