@bitkyc08/opencodex 2.88.0 → 2.89.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 (205) hide show
  1. package/README.md +11 -1
  2. package/bin/ocx.mjs +15 -4
  3. package/gui/dist/assets/App-BnRSujOq.js +58 -0
  4. package/gui/dist/assets/App-dnkJ85te.css +1 -0
  5. package/gui/dist/assets/{Tray-B5bC7AWL.js → Tray-7z1COnmz.js} +1 -1
  6. package/gui/dist/assets/{index-B5bsvxor.js → index-uchD-ngf.js} +13 -13
  7. package/gui/dist/assets/{quota-summary-D8y2wTsB.js → quota-summary-BY_10IEz.js} +1 -1
  8. package/gui/dist/index.html +1 -1
  9. package/package.json +1 -1
  10. package/src/adapters/anthropic/cache-retention.ts +117 -0
  11. package/src/adapters/anthropic/passthrough.ts +7 -4
  12. package/src/adapters/anthropic.ts +10 -3
  13. package/src/adapters/coding-agent/protocol.ts +6 -0
  14. package/src/adapters/google-http.ts +3 -2
  15. package/src/adapters/google-vertex-endpoint.ts +67 -0
  16. package/src/adapters/google.ts +35 -29
  17. package/src/adapters/openai-responses/compaction-search-history.ts +27 -0
  18. package/src/adapters/openai-responses/passthrough.ts +17 -12
  19. package/src/adapters/openai-responses/reasoning.ts +68 -1
  20. package/src/adapters/registry.ts +1 -1
  21. package/src/adapters/upstream-http-error.ts +3 -2
  22. package/src/adapters/zed.ts +7 -4
  23. package/src/bridge/internal.ts +11 -1
  24. package/src/bridge/response-json.ts +2 -2
  25. package/src/bridge/sse.ts +10 -4
  26. package/src/claude/inbound.ts +12 -26
  27. package/src/claude/outbound.ts +5 -0
  28. package/src/cli/account-api.ts +13 -1
  29. package/src/cli/account-extended.ts +17 -5
  30. package/src/cli/account-key-quota.ts +4 -1
  31. package/src/cli/account.ts +1 -1
  32. package/src/cli/capabilities-agents-routing.ts +45 -8
  33. package/src/cli/capabilities-base.ts +5 -5
  34. package/src/cli/capabilities-provider-models.ts +5 -4
  35. package/src/cli/combo-result.ts +8 -2
  36. package/src/cli/combo.ts +17 -0
  37. package/src/cli/help.ts +1 -1
  38. package/src/cli/message-command.ts +4 -1
  39. package/src/cli/message-remote-args.ts +69 -0
  40. package/src/cli/message-remote-command.ts +77 -0
  41. package/src/cli/provider-runtime.ts +69 -1
  42. package/src/cli/registry.ts +3 -3
  43. package/src/codex/account-pause.ts +6 -1
  44. package/src/codex/account-runtime-state.ts +5 -0
  45. package/src/codex/account-store.ts +30 -3
  46. package/src/codex/auth-api/account-list.ts +3 -0
  47. package/src/codex/auth-api/main-account-probe.ts +3 -2
  48. package/src/codex/auth-context.ts +9 -4
  49. package/src/codex/catalog/aggregation.ts +15 -0
  50. package/src/codex/catalog/auto-review.ts +2 -1
  51. package/src/codex/catalog/build-entries.ts +17 -7
  52. package/src/codex/catalog/derive-entry.ts +3 -1
  53. package/src/codex/catalog/metadata.ts +2 -0
  54. package/src/codex/catalog/model-visibility.ts +0 -2
  55. package/src/codex/catalog/ownership.ts +71 -0
  56. package/src/codex/catalog/parsing.ts +12 -3
  57. package/src/codex/catalog/retained-sync.ts +2 -1
  58. package/src/codex/catalog/routed-removal.ts +4 -4
  59. package/src/codex/convergence.ts +2 -1
  60. package/src/codex/low-quota-desktop-notifier.ts +125 -0
  61. package/src/codex/low-quota-protection.ts +57 -31
  62. package/src/codex/main-account-cache.ts +77 -3
  63. package/src/codex/main-account.ts +6 -2
  64. package/src/codex/native-residue.ts +2 -3
  65. package/src/codex/quota.ts +26 -2
  66. package/src/combos/failover.ts +2 -1
  67. package/src/combos/jev-model-backend.ts +30 -7
  68. package/src/combos/jev-model-request.ts +20 -0
  69. package/src/combos/jev-quota-activation.ts +153 -0
  70. package/src/combos/jev-quota-config.ts +62 -0
  71. package/src/combos/jev-quota-route.ts +26 -0
  72. package/src/combos/jev-quota.ts +88 -0
  73. package/src/combos/jev.ts +25 -12
  74. package/src/combos/types.ts +27 -0
  75. package/src/compatibility/index.ts +3 -0
  76. package/src/compatibility/openai-responses.ts +8 -1
  77. package/src/compatibility/opengateway-responses.ts +61 -0
  78. package/src/config/account-auto-pause-revisions.ts +136 -0
  79. package/src/config/diagnostics.ts +13 -0
  80. package/src/config/live-reconcile.ts +9 -0
  81. package/src/config/persist-unlocked.ts +10 -1
  82. package/src/config/removed-opencode-free.ts +135 -0
  83. package/src/config/schema/account-auto-pause.ts +14 -0
  84. package/src/config/schema/config-schema.ts +15 -0
  85. package/src/config/schema/leaf-validators.ts +7 -0
  86. package/src/config.ts +10 -3
  87. package/src/generated/compatibility-version.json +344 -144
  88. package/src/images/loop.ts +32 -9
  89. package/src/lib/account-auto-pause-response.ts +16 -0
  90. package/src/lib/bun-runtime.ts +18 -1
  91. package/src/lib/bun-transpiler-cache-scope.d.mts +8 -0
  92. package/src/lib/bun-transpiler-cache-scope.mjs +68 -0
  93. package/src/lib/decision-quota-sink.ts +76 -0
  94. package/src/lib/state-store-registrations.ts +25 -0
  95. package/src/link/ssh-argv.ts +3 -0
  96. package/src/messaging/envelope.ts +6 -3
  97. package/src/messaging/remote-auth.ts +83 -0
  98. package/src/messaging/remote-bridge.ts +270 -0
  99. package/src/messaging/remote-contract.ts +108 -0
  100. package/src/messaging/remote-enrollment-recovery.ts +59 -0
  101. package/src/messaging/remote-enrollment.ts +244 -0
  102. package/src/messaging/remote-envelope.ts +40 -0
  103. package/src/messaging/remote-files.ts +117 -0
  104. package/src/messaging/remote-owner.ts +169 -0
  105. package/src/messaging/remote-ports.ts +56 -0
  106. package/src/messaging/remote-process.ts +131 -0
  107. package/src/messaging/remote-replies.ts +98 -0
  108. package/src/messaging/remote-rpc-admission.ts +32 -0
  109. package/src/messaging/remote-send.ts +72 -0
  110. package/src/messaging/remote-store.ts +111 -0
  111. package/src/messaging/remote-tunnels.ts +65 -0
  112. package/src/messaging/rpc.ts +13 -1
  113. package/src/oauth/account-auto-pause-policy.ts +66 -0
  114. package/src/oauth/account-auto-pause.ts +171 -0
  115. package/src/oauth/account-quota-rank.ts +2 -1
  116. package/src/oauth/anthropic-account-refusal.ts +6 -0
  117. package/src/oauth/anthropic-model-family.ts +8 -0
  118. package/src/oauth/anthropic-model-quota.ts +2 -6
  119. package/src/oauth/api-key-pool-preserve.ts +37 -0
  120. package/src/oauth/index.ts +5 -35
  121. package/src/oauth/store.ts +35 -8
  122. package/src/oauth/types.ts +2 -0
  123. package/src/plugins/upstream-hooks.ts +14 -1
  124. package/src/providers/api-key-pause.ts +32 -0
  125. package/src/providers/api-key-resolve.ts +10 -4
  126. package/src/providers/api-key-selection.ts +6 -1
  127. package/src/providers/api-keys.ts +8 -4
  128. package/src/providers/claude-cli-usage.ts +5 -0
  129. package/src/providers/key-failover.ts +11 -11
  130. package/src/providers/model-rename-fields.ts +1 -0
  131. package/src/providers/opencode-zen-rate-limit.ts +6 -72
  132. package/src/providers/quota/account-cache.ts +15 -1
  133. package/src/providers/quota/anthropic-account-quota.ts +2 -1
  134. package/src/providers/quota/anthropic-cooldown-recovery.ts +22 -4
  135. package/src/providers/quota/anthropic-decision-windows.ts +47 -0
  136. package/src/providers/quota/antigravity.ts +39 -6
  137. package/src/providers/quota/report-cache.ts +14 -0
  138. package/src/providers/quota/vendor-probes-oauth.ts +3 -3
  139. package/src/providers/quota-decision-publication.ts +77 -0
  140. package/src/providers/quota-decision-snapshot.ts +145 -0
  141. package/src/providers/quota-routing-cache.ts +3 -0
  142. package/src/providers/quota-types.ts +6 -1
  143. package/src/providers/quota.ts +3 -2
  144. package/src/providers/registry/entries-extended.ts +8 -52
  145. package/src/providers/registry/model-seeds.ts +1 -1
  146. package/src/providers/registry.ts +1 -2
  147. package/src/providers/stale-vision-classification-migration.ts +1 -1
  148. package/src/responses/parser.ts +18 -10
  149. package/src/responses/web-search-replay.ts +138 -0
  150. package/src/routing/compatibility/behavior.ts +4 -1
  151. package/src/server/auth-cors.ts +7 -0
  152. package/src/server/background-lifecycle.ts +2 -1
  153. package/src/server/chat-native.ts +28 -13
  154. package/src/server/claude-messages.ts +2 -1
  155. package/src/server/index/optional-listeners.ts +6 -0
  156. package/src/server/management/combo-routes.ts +17 -2
  157. package/src/server/management/oauth-account-routes.ts +10 -1
  158. package/src/server/management/provider-completion-test.ts +289 -0
  159. package/src/server/management/provider-routes.ts +9 -1
  160. package/src/server/management/route-registry.ts +2 -0
  161. package/src/server/messages-native.ts +18 -4
  162. package/src/server/messages-shared.ts +4 -1
  163. package/src/server/request-log.ts +7 -2
  164. package/src/server/responses/account-auto-pause-recovery.ts +26 -0
  165. package/src/server/responses/adapter-dispatch.ts +77 -28
  166. package/src/server/responses/combo-session-recall.ts +25 -0
  167. package/src/server/responses/combo-stream-preflight.ts +3 -1
  168. package/src/server/responses/combo-tool-loop-pin.ts +70 -0
  169. package/src/server/responses/compact.ts +8 -5
  170. package/src/server/responses/context-overflow.ts +141 -2
  171. package/src/server/responses/core-codex-account.ts +7 -1
  172. package/src/server/responses/core-combo.ts +31 -5
  173. package/src/server/responses/core.ts +12 -9
  174. package/src/server/responses/empty-completion-guard.ts +2 -0
  175. package/src/server/responses/fetch-helpers.ts +35 -4
  176. package/src/server/responses/jev-model-invoke.ts +13 -14
  177. package/src/server/responses/native-steering-log.ts +2 -2
  178. package/src/server/responses/passthrough-delivery.ts +3 -2
  179. package/src/server/responses/passthrough-dispatch.ts +30 -33
  180. package/src/server/responses/passthrough-observations.ts +38 -0
  181. package/src/server/responses/request-compression.ts +98 -0
  182. package/src/server/responses/request-transport.ts +32 -3
  183. package/src/server/responses/run-turn-execution.ts +2 -0
  184. package/src/server/responses/sidecar-execution.ts +16 -3
  185. package/src/server/responses/terminal-guard.ts +2 -0
  186. package/src/server/startup-action-control.ts +2 -2
  187. package/src/server/startup-health-cache.ts +2 -2
  188. package/src/server/windows-tray-control.ts +2 -2
  189. package/src/service/definition.ts +9 -1
  190. package/src/types/account-auto-pause.ts +15 -0
  191. package/src/types/config.ts +23 -1
  192. package/src/types/provider.ts +9 -5
  193. package/src/types/request.ts +20 -2
  194. package/src/types.ts +1 -0
  195. package/src/usage/cost.ts +17 -1
  196. package/src/usage/expected-prices.ts +3 -1
  197. package/src/usage/jev-stats.ts +4 -0
  198. package/src/usage/log.ts +2 -0
  199. package/src/usage/summary.ts +7 -0
  200. package/src/web-search/loop.ts +37 -11
  201. package/src/web-search/progress-stream.ts +4 -1
  202. package/src/web-search/run-turn-loop.ts +9 -3
  203. package/src/web-search/sidecar-search-replay.ts +96 -0
  204. package/gui/dist/assets/App-CHC89EXQ.js +0 -58
  205. package/gui/dist/assets/App-wT3mXqFz.css +0 -1
@@ -260,7 +260,7 @@ function resetIso(value: number | undefined): string | null {
260
260
 
261
261
  function refreshLine(row: FamilyRows["rows"][number]): string {
262
262
  const parts = [row.id === MAIN_ID ? "main" : row.id, row.email, row.plan];
263
- if (row.paused) parts.push("paused");
263
+ if (row.paused) parts.push(row.pauseDetails ? `paused(${row.pauseDetails.reason})` : "paused");
264
264
  // Was a second quota dialect: it gated the whole block on weekly/monthly, so an account
265
265
  // reporting only a 5h window printed `quota: unknown` while `quotaParts` five lines below
266
266
  // rendered the same data correctly for the provider path (#2703). Two halves of one file
@@ -786,7 +786,7 @@ export async function cmdPriority(args: string[], deps: AccountDeps): Promise<nu
786
786
  return 0;
787
787
  }
788
788
 
789
- function resolveGenericOAuthAccountTarget(accounts: unknown[], requested: string): { id: string } | { error: string } {
789
+ function resolveGenericOAuthAccountTarget(accounts: unknown[], requested: string, kind: "OAuth" | "API key" = "OAuth"): { id: string } | { error: string } {
790
790
  const rows = accounts.filter((value): value is { id: string; alias?: unknown } =>
791
791
  typeof value === "object" && value !== null && typeof (value as { id?: unknown }).id === "string",
792
792
  );
@@ -797,10 +797,10 @@ function resolveGenericOAuthAccountTarget(accounts: unknown[], requested: string
797
797
  : rows.filter(account => typeof account.alias === "string" && account.alias.toLowerCase() === requested.toLowerCase());
798
798
  if (matches.length === 1) return { id: matches[0]!.id };
799
799
  if (matches.length > 1) return { error: `alias "${requested}" names ${matches.length} accounts; use the account id` };
800
- return { error: `Account not found: no OAuth account has the id or alias "${requested}"` };
800
+ return { error: `Account not found: no ${kind} account has the id or alias "${requested}"` };
801
801
  }
802
802
 
803
- /** Pause or resume a Codex or OAuth provider account, including Anthropic. */
803
+ /** Pause or resume a Codex, OAuth, or API-key pool account. */
804
804
  export async function cmdPause(args: string[], deps: AccountDeps, paused: boolean): Promise<number> {
805
805
  const wantsJson = flag(args, "--json");
806
806
  const name = args.shift();
@@ -839,8 +839,20 @@ export async function cmdPause(args: string[], deps: AccountDeps, paused: boolea
839
839
  return 0;
840
840
  }
841
841
 
842
+ if (classified.type === "api-key") {
843
+ const rows = await fetchRows(deps, baseUrl, name, "api-key");
844
+ if (rows.status === 0) return proxyUnreachable(rows.transportError);
845
+ if (rows.status !== 200) return apiError(rows.errorJson ?? {}, "failed to list API key accounts", rows.status);
846
+ const target = resolveGenericOAuthAccountTarget(rows.rows.map(row => ({ id: row.id, alias: row.label })), requestedId, "API key");
847
+ if ("error" in target) return usage(`Error: ${target.error}`);
848
+ const result = await apiJson(deps, baseUrl, "PUT", "/api/providers/keys/pause", { name, id: target.id, paused });
849
+ if (result.status === 0) return proxyUnreachable(result.transportError);
850
+ if (result.status !== 200) return apiError(result.json, `failed to ${verb} account`, result.status);
851
+ console.log(wantsJson ? JSON.stringify({ ok: true, provider: name, id: target.id, paused }, null, 2) : `${name}: account ${paused ? "paused" : "resumed"}`);
852
+ return 0;
853
+ }
842
854
  if (classified.type !== "codex") {
843
- return usage(`Error: ${verb} applies to the openai Codex account pool or a generic OAuth provider`);
855
+ return usage(`Error: ${verb} applies to the openai Codex account pool, a generic OAuth provider, or an API-key pool`);
844
856
  }
845
857
  const target = await resolveCodexAccountTarget(deps, baseUrl, requestedId);
846
858
  if ("networkDown" in target) return proxyUnreachable(target.transportError);
@@ -2,6 +2,7 @@
2
2
  import { parseQuotaFailureCode, type AccountQuotaFields, type ProviderQuota, type ProviderQuotaWindow, type ProviderQuotaCreditsUsd } from "../providers/quota-types";
3
3
  import { terminalSafeText } from "./runtime-api";
4
4
  import type { AccountRow, FamilyRows } from "./account-api";
5
+ import { accountPauseDetailsSchema } from "../config/schema/account-auto-pause";
5
6
 
6
7
  function record(value: unknown): Record<string, unknown> {
7
8
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed API-key quota response.");
@@ -88,7 +89,9 @@ export function projectApiKeyQuotaRows(value: unknown, provider: string): Family
88
89
  }
89
90
  const masked = optionalString(row, "masked");
90
91
  return { provider, type: "api-key", id, label: optionalString(row, "label") ?? masked,
91
- masked, active: optionalBoolean(row, "active") ?? id === activeId, ...fields };
92
+ masked, active: optionalBoolean(row, "active") ?? id === activeId,
93
+ // Same projection as the plain key listing: disabled keeps the key paused, unknown details drop.
94
+ paused: row.disabled === true, pauseDetails: accountPauseDetailsSchema.safeParse(row.pauseDetails).data, ...fields };
92
95
  });
93
96
  return { rows, activeId, status: 200 };
94
97
  }
@@ -119,7 +119,7 @@ function statusText(row: AccountRow): string {
119
119
  // `paused` leads, and does NOT replace `selected`. A paused-but-selected account is the
120
120
  // state an operator most needs named -- requests route to it while the pool believes it is
121
121
  // held out -- so printing only one of the two would hide exactly the confusing case (#2703).
122
- if (row.paused) parts.push("paused");
122
+ if (row.paused) parts.push(row.pauseDetails ? `paused(${row.pauseDetails.reason})` : "paused");
123
123
  if (row.active) parts.push(row.type === "codex" ? "selected" : "active");
124
124
  if (row.needsReauth && !(row.provider === "kiro" && row.skipReason === "needs_reauth")) {
125
125
  parts.push(row.needsReauthReason === "verify_account" ? "needs-reauth(verify)" : "needs-reauth");
@@ -3,15 +3,15 @@ import type { Capability } from "./capability-types";
3
3
  export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
4
4
  {
5
5
  command: ["message", "sessions"],
6
- summary: "Discover already-loaded local Codex sessions without reading conversation history.",
7
- routes: [], flags: [{ name: "--json", value: "boolean", summary: "Emit a versioned local session directory." }],
6
+ summary: "Discover already-loaded Codex sessions locally or on an explicitly enrolled peer.",
7
+ routes: [], flags: [{ name: "--json", value: "boolean", summary: "Emit a versioned session directory." }, { name: "--host", value: "string", summary: "Exact enrolled peer alias or machine UUID; requires a live foreground owner." }],
8
8
  mutates: false, json: "envelope",
9
- bannerLines: ["ocx message <sub> Loaded local Codex sessions and queued peer messages (sessions|send)"],
10
- details: ["Linux/macOS Unix socket only. Uses effective CODEX_HOME; starts no daemon and returns no partial directory."],
9
+ bannerLines: ["ocx message <sub> Codex queued messages, explicit SSH peers and foreground ownership"],
10
+ details: ["Linux/macOS only. Local discovery uses the effective CODEX_HOME Unix socket; --host uses the live foreground owner's authenticated loopback route. Starts no daemon and returns no partial directory."],
11
11
  },
12
12
  {
13
13
  command: ["message", "send"],
14
- summary: "Submit one correlated peer message to an exact loaded local Codex destination.",
14
+ summary: "Submit one correlated peer message to an exact loaded Codex destination.",
15
15
  routes: [], mutates: true, json: "envelope",
16
16
  flags: [
17
17
  { name: "--thread", value: "string", summary: "Exact loaded UUID; choose this or --name." },
@@ -20,10 +20,11 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
20
20
  { name: "--kind", value: "string", summary: "request (default), response or notification." },
21
21
  { name: "--in-reply-to", value: "string", summary: "Request message UUID; required only for a response." },
22
22
  { name: "--json", value: "boolean", summary: "Emit a receipt with not_sent, queued or unknown status." },
23
+ { name: "--host", value: "string", summary: "Exact enrolled peer alias or machine UUID; omit for the unchanged local path." },
23
24
  ],
24
25
  details: ["Requires daemon support for experimental thread/queue/add. Sender context comes from CODEX_THREAD_ID, not an authentication claim.",
25
26
  "queued means submitted, not processed. unknown must not be replayed; no automatic retry, daemon start or thread resume.",
26
- "Exit 0: queued; 1: not sent; 3: unknown; 64: invalid usage. No remote/Claude transport or skill installation."],
27
+ "Exit 0: queued; 1: not sent; 3: unknown; 64: invalid usage. No Claude transport, native lifecycle mutation or skill installation."],
27
28
  },
28
29
  {
29
30
  command: ["advisor"],
@@ -46,6 +47,42 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
46
47
  ],
47
48
  },
48
49
 
50
+ {
51
+ command: ["message", "enable"], summary: "Explicitly enable private remote messaging state, without starting a listener.", routes: [],
52
+ flags: [{ name: "--port", value: "number", summary: "Unprivileged IPv4-loopback port; defaults to 39176 on first enable." },
53
+ { name: "--json", value: "boolean", summary: "Emit configuration without credentials." }], mutates: true, json: "envelope",
54
+ },
55
+ { command: ["message", "disable"], summary: "Disable remote admission and retire the foreground owner generation.", routes: [],
56
+ flags: [{ name: "--json", value: "boolean", summary: "Emit safe configuration." }], mutates: true, json: "envelope" },
57
+ { command: ["message", "status"], summary: "Read enabled, running and leased/initiated route states without activation.", routes: [],
58
+ flags: [{ name: "--json", value: "boolean", summary: "Emit safe configuration and owner observations." }], mutates: false, json: "envelope" },
59
+ { command: ["message", "serve"], summary: "Own a foreground listener and optional duplex SSH peer routes; no automatic reconnect.", routes: [],
60
+ flags: [{ name: "--host", value: "string", summary: "Exact initiating peer; repeat for at most four distinct peers." },
61
+ { name: "--json", value: "boolean", summary: "Emit the startup observation without credentials." }], mutates: true, json: "envelope" },
62
+ { command: ["message", "hosts", "probe"], summary: "Offer an SSH host fingerprint without enrollment or persistent changes.", routes: [],
63
+ flags: [{ name: "--ssh", value: "string", required: true, summary: "OpenSSH destination/alias." },
64
+ { name: "--json", value: "boolean", summary: "Emit the offered fingerprint." }], mutates: false, json: "envelope" },
65
+ { command: ["message", "hosts", "add"], usage: "ocx message hosts add <alias> --ssh <destination> --fingerprint <SHA256> [--json]",
66
+ summary: "Enroll outbound delivery and correlated return replies after SSH fingerprint confirmation.", routes: [],
67
+ flags: [{ name: "--ssh", value: "string", required: true, summary: "OpenSSH destination/alias." },
68
+ { name: "--fingerprint", value: "string", required: true, summary: "Explicitly confirmed offered SSH host-key fingerprint." },
69
+ { name: "--json", value: "boolean", summary: "Emit enrollment metadata, never credentials." }], mutates: true, json: "envelope" },
70
+ { command: ["message", "hosts", "allow-inbound"], usage: "ocx message hosts allow-inbound <alias-or-machine-uuid> [--json]",
71
+ summary: "Explicitly allow this enrolled peer to send any message kind to local loaded sessions.", routes: [],
72
+ flags: [{ name: "--json", value: "boolean", summary: "Emit the local inbound grant, without credentials." }], mutates: true, json: "envelope" },
73
+ { command: ["message", "hosts", "deny-inbound"], usage: "ocx message hosts deny-inbound <alias-or-machine-uuid> [--json]",
74
+ summary: "Restrict this peer to correlated replies on locally opened reply routes.", routes: [],
75
+ flags: [{ name: "--json", value: "boolean", summary: "Emit the narrowed local inbound grant." }], mutates: true, json: "envelope" },
76
+ { command: ["message", "hosts", "list"], summary: "List exact peer identities without credentials or listener activation.", routes: [],
77
+ flags: [{ name: "--json", value: "boolean", summary: "Emit safe peer metadata." }], mutates: false, json: "envelope" },
78
+ { command: ["message", "hosts", "remove"], usage: "ocx message hosts remove <alias-or-machine-uuid> [--transaction <uuid>] [--json]",
79
+ summary: "Revoke local admission first and report any unconfirmed remote cleanup explicitly.", routes: [],
80
+ flags: [{ name: "--transaction", value: "string", summary: "Remove only this exact enrollment; refuse a replacement transaction." },
81
+ { name: "--json", value: "boolean", summary: "Emit local and remote revocation outcomes." }], mutates: true, json: "envelope" },
82
+ { command: ["message", "hosts", "abandon"], usage: "ocx message hosts abandon --transaction <uuid> [--json]",
83
+ summary: "Abandon an exact pending local enrollment; remote cleanup remains unconfirmed (exit 3).", routes: [],
84
+ flags: [{ name: "--transaction", value: "string", required: true, summary: "Exact pending UUID from hosts list or status; never an alias." },
85
+ { name: "--json", value: "boolean", summary: "Emit local abandonment and explicit remote-cleanup guidance." }], mutates: true, json: "envelope" },
49
86
  {
50
87
  command: ["agent", "status"],
51
88
  usage: "ocx agent status [--json]",
@@ -298,10 +335,10 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
298
335
  },
299
336
  {
300
337
  command: ["combo","set"],
301
- usage: "ocx combo set <id> [--targets <provider/model[:weight],...> | --targets-file <FILE|->] [--strategy <failover|round-robin|random|least-used|reset-window|jev>] [--sticky <1-100|->] [--effort <low|medium|high|xhigh|max|ultra|->] [--effort-mode <fallback|force|->] [--alias <name|->] [--native-alias [on|off]] [--allow-metered-targets <on|off>] [--display-name <label|->] [--decision-provider <provider|-> | --decision-model <route|->] [--decision-timeout <ms|->] [--rename-from <id>] [--image-input <auto|disabled>] [--reasoning-effort-mode <strict|adaptive>] [--json]",
338
+ usage: "ocx combo set <id> [--targets <provider/model[:weight],...> | --targets-file <FILE|->] [--strategy <failover|round-robin|random|least-used|reset-window|jev>] [--sticky <1-100|->] [--effort <low|medium|high|xhigh|max|ultra|->] [--effort-mode <fallback|force|->] [--alias <name|->] [--native-alias [on|off]] [--allow-metered-targets <on|off>] [--display-name <label|->] [--description <text|->] [--decision-provider <provider|-> | --decision-model <route|->] [--decision-timeout <ms|->] [--decision-quota-signals <on|off|->] [--decision-quota-tiers <JSON|->] [--rename-from <id>] [--image-input <auto|disabled>] [--reasoning-effort-mode <strict|adaptive>] [--json]",
302
339
  summary: "Create, update or rename a combo.",
303
340
  routes: [{"method":"GET","path":"/api/combos"},{"method":"PUT","path":"/api/combos"}],
304
- flags: [{"name":"--allow-metered-targets","value":"string","summary":"on grants operator consent to metered targets only on a loopback-only proxy; off clears it."},{"name":"--targets","value":"string","summary":"Ordered provider/model[:weight] list; required for creation."},{"name":"--strategy","value":"string","summary":"Routing strategy."},{"name":"--sticky","value":"string","summary":"Round-robin limit 1-100; - resets."},{"name":"--effort","value":"string","summary":"Default effort; - clears."},{"name":"--effort-mode","value":"string","summary":"fallback or force; - resets to fallback."},{"name":"--alias","value":"string","summary":"Alias; - clears."},{"name":"--display-name","value":"string","summary":"Label; - clears."},{"name":"--decision-provider","value":"string","summary":"JEV provider; - clears."},{"name":"--decision-model","value":"string","summary":"JEV route; - clears; exclusive with provider."},{"name":"--decision-timeout","value":"string","summary":"JEV deadline 1000-120000 ms; - clears."},{"name":"--rename-from","value":"string","summary":"Existing combo ID to rename."},{"name":"--json","value":"boolean","summary":"Emit structured JSON."},{"name":"--native-alias","value":"string","summary":"Bare legacy flag means on; explicit on/off preserves presence, including false."},{"name":"--targets-file","value":"string","summary":"Bounded ordered target JSON array, exclusive with --targets; preserves effort/profile/last-resort metadata."},{"name":"--image-input","value":"string","summary":"auto or disabled; explicit auto clears the previous disabled choice."},{"name":"--reasoning-effort-mode","value":"string","summary":"strict or adaptive, distinct from --effort-mode fallback/force."}],
341
+ flags: [{"name":"--allow-metered-targets","value":"string","summary":"on grants operator consent to metered targets only on a loopback-only proxy; off clears it."},{"name":"--targets","value":"string","summary":"Ordered provider/model[:weight] list; required for creation."},{"name":"--strategy","value":"string","summary":"Routing strategy."},{"name":"--sticky","value":"string","summary":"Round-robin limit 1-100; - resets."},{"name":"--effort","value":"string","summary":"Default effort; - clears."},{"name":"--effort-mode","value":"string","summary":"fallback or force; - resets to fallback."},{"name":"--alias","value":"string","summary":"Alias; - clears."},{"name":"--display-name","value":"string","summary":"Label; - clears."},{"name":"--description","value":"string","summary":"Catalog row description; - clears."},{"name":"--decision-provider","value":"string","summary":"JEV provider; - clears."},{"name":"--decision-model","value":"string","summary":"JEV route; - clears; exclusive with provider."},{"name":"--decision-timeout","value":"string","summary":"JEV deadline 1000-120000 ms; - clears."},{"name":"--decision-quota-signals","value":"string","summary":"JEV advisory quota on/off; - clears."},{"name":"--decision-quota-tiers","value":"string","summary":"Partial JSON thresholds; - clears."},{"name":"--rename-from","value":"string","summary":"Existing combo ID to rename."},{"name":"--json","value":"boolean","summary":"Emit structured JSON."},{"name":"--native-alias","value":"string","summary":"Bare legacy flag means on; explicit on/off preserves presence, including false."},{"name":"--targets-file","value":"string","summary":"Bounded ordered target JSON array, exclusive with --targets; preserves effort/profile/last-resort metadata."},{"name":"--image-input","value":"string","summary":"auto or disabled; explicit auto clears the previous disabled choice."},{"name":"--reasoning-effort-mode","value":"string","summary":"strict or adaptive, distinct from --effort-mode fallback/force."}],
305
342
  mutates: true,
306
343
  json: "payload",
307
344
  details: ["create and update are aliases of set. Existing fields are read before writing; --targets replaces targets.","force overrides valid client effort and may increase cost and latency.","Only the implemented target grammar is supported; full GUI target metadata and routing-profile writes are separate tasks.","New file/flag conflicts refuse before transport. Partial edits preserve target metadata; explicit false/default values override server carry. Turning a native alias off may also require clearing its incompatible alias.","Read/merge/write uses one target and remains an upsert without revision CAS. Saved-but-incomplete catalog outcomes return nonzero with their receipt."],
@@ -340,18 +340,18 @@ export const CAPABILITIES: readonly Capability[] = [
340
340
  },
341
341
  {
342
342
  command: ["account","pause"],
343
- summary: "Exclude one account in a Codex, Anthropic or supported generic OAuth pool from automatic selection.",
344
- routes: [{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"PUT","path":"/api/codex-auth/accounts/pause"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/pause"}],
343
+ summary: "Exclude one account in a Codex, Anthropic, generic OAuth or API-key pool from automatic selection.",
344
+ routes: [{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"PUT","path":"/api/codex-auth/accounts/pause"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/pause"},{"method":"GET","path":"/api/providers/keys"},{"method":"PUT","path":"/api/providers/keys/pause"}],
345
345
  flags: [{"name":"--json","value":"boolean","summary":"Emit the pause result as JSON."}],
346
346
  mutates: true,
347
347
  json: "envelope",
348
- details: ["Codex pause unbinds pinned threads and selects a fallback when possible; with no fallback, a paused-but-selected Codex account still receives requests. Anthropic and generic OAuth pause exclude the account from new requests, failover and refresh, and an all-paused pool answers 403. Credentials and health are preserved; already-sent turns are not cancelled."],
348
+ details: ["Codex pause unbinds pinned threads and selects a fallback when possible; with no fallback, the paused account cannot dispatch until resumed. Anthropic and generic OAuth pause exclude the account from new requests, failover and refresh, and an all-paused pool answers 403. Credentials and health are preserved; already-sent turns are not cancelled."],
349
349
  usage: "ocx account pause <provider> <account-id|alias|main> [--json]",
350
350
  },
351
351
  {
352
352
  command: ["account","resume"],
353
- summary: "Return a paused account to a Codex, Anthropic or supported generic OAuth pool.",
354
- routes: [{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"PUT","path":"/api/codex-auth/accounts/pause"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/pause"}],
353
+ summary: "Return a paused account to a Codex, Anthropic, generic OAuth or API-key pool.",
354
+ routes: [{"method":"GET","path":"/api/codex-auth/accounts"},{"method":"PUT","path":"/api/codex-auth/accounts/pause"},{"method":"GET","path":"/api/oauth/accounts"},{"method":"PUT","path":"/api/oauth/accounts/pause"},{"method":"GET","path":"/api/providers/keys"},{"method":"PUT","path":"/api/providers/keys/pause"}],
355
355
  flags: [{"name":"--json","value":"boolean","summary":"Emit the resume result as JSON."}],
356
356
  mutates: true,
357
357
  json: "envelope",
@@ -49,10 +49,11 @@ export const PROVIDER_MODEL_CAPABILITIES: readonly Capability[] = [
49
49
  details: ["At least one edit is required; only supplied fields are patched. update is an existing alias. Use provider show only for local state, not as proof of the live write.","Management errors use safe fixed provider diagnostics; catalog failures retain the saved receipt and a nonzero exit."],
50
50
  },
51
51
  {
52
- command: ["provider", "test"], summary: "Probe a provider's live model discovery connectivity.",
53
- usage: "ocx provider test <name> [--json]", routes: [{ method: "POST", path: "/api/providers/test" }], mutates: true, json: "payload",
54
- flags: [{ name: "--json", value: "boolean", summary: "Emit the probe result." }],
55
- details: ["May contact the upstream provider; requires operator intent to probe. Static catalogs can return applicable:false; failed connectivity exits nonzero."],
52
+ command: ["provider", "test"], summary: "Probe discovery connectivity or explicitly test one model completion.",
53
+ usage: "ocx provider test <name> [--model <id> [--yes]] [--json]",
54
+ routes: [{ method: "POST", path: "/api/providers/test" }, { method: "POST", path: "/api/providers/test-completion" }], mutates: true, json: "payload",
55
+ flags: [{ name: "--model", value: "string", summary: "Run one bounded completion for this model instead of discovery." }, { name: "--yes", value: "boolean", summary: "Confirm completion quota/cost; requires --model. Mandatory with --json or non-interactive input." }, { name: "--json", value: "boolean", summary: "Emit the probe result; completion warnings go to stderr." }],
56
+ details: ["Without --model, discovery behavior is unchanged; static catalogs can return applicable:false. Completion tests print a quota/cost warning and require a default-No terminal confirmation or --yes; cancellation exits 1 without a request.", "Completion output includes TTFT, total latency, upstream/wire model metadata and comparison. Metadata is not proof of model identity; mismatch still exits 0. Failed tests exit 1; non-applicable results exit 0."],
56
57
  },
57
58
  {
58
59
  command: ["provider", "quota"], summary: "Read provider quota reports, optionally refreshing them.",
@@ -1,3 +1,4 @@
1
+ import { normalizeJevQuotaTiers } from "../combos/jev-quota-config";
1
2
  import { parseComboTargets } from "./combo-input";
2
3
  import { printCatalogResult } from "./catalog-command-result";
3
4
 
@@ -7,7 +8,7 @@ const ENUMS: Readonly<Record<string, readonly (string | null)[]>> = {
7
8
  defaultEffortMode: ["fallback", "force"], reasoningEffortMode: ["strict", "adaptive"],
8
9
  imageInput: ["auto", "disabled"], cooldownWaitPolicy: ["before-last-resort"],
9
10
  };
10
- const STRINGS = new Set(["alias", "displayName", "decisionProvider", "decisionModel"]);
11
+ const STRINGS = new Set(["alias", "displayName", "description", "decisionProvider", "decisionModel"]);
11
12
  const RANGES: Readonly<Record<string, readonly [number, number]>> = {
12
13
  stickyLimit: [1, 100], cooldownMs: [1, 600_000], waitForCooldownMs: [0, 600_000],
13
14
  decisionTimeoutMs: [1_000, 120_000],
@@ -33,7 +34,12 @@ function publicCombo(value: unknown): Record<string, unknown> {
33
34
  } else if (Object.hasOwn(RANGES, key)) {
34
35
  const [min, max] = RANGES[key]!;
35
36
  if (typeof child !== "number" || !Number.isSafeInteger(child) || child < min || child > max) invalid();
36
- } else if (key === "nativeAlias" || key === "allowMeteredTargets") {
37
+ } else if (key === "decisionQuotaTiers") {
38
+ const tiers = normalizeJevQuotaTiers(child);
39
+ if (!tiers) invalid();
40
+ result[key] = tiers;
41
+ continue;
42
+ } else if (key === "nativeAlias" || key === "allowMeteredTargets" || key === "decisionQuotaSignals") {
37
43
  if (typeof child !== "boolean") invalid();
38
44
  } else invalid();
39
45
  result[key] = child;
package/src/cli/combo.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { normalizeJevQuotaTiers } from "../combos/jev-quota-config";
1
2
  import { JEV_DECISION_TIMEOUT_MAX_MS, JEV_DECISION_TIMEOUT_MIN_MS } from "../combos/types";
2
3
  import {
3
4
  CliUsageError,
@@ -24,8 +25,10 @@ const USAGE = `Usage:
24
25
  [--effort <low|medium|high|xhigh|max|ultra|->] [--effort-mode <fallback|force|->]
25
26
  (force overrides valid client effort and can increase cost/latency) [--alias <name|->]
26
27
  [--native-alias [on|off]] [--allow-metered-targets <on|off>] [--display-name <label|->]
28
+ [--description <text|->]
27
29
  [--image-input <auto|disabled>] [--reasoning-effort-mode <strict|adaptive>]
28
30
  [--decision-provider <provider|-> | --decision-model <route|->] [--decision-timeout <ms|->]
31
+ [--decision-quota-signals <on|off|->] [--decision-quota-tiers <JSON|->]
29
32
  (jev only; the provider must be a configured jev-decision row)
30
33
  [--rename-from <id>] [--json]
31
34
  ocx combo stats <id> [--range <7d|30d|all>] [--json]
@@ -80,6 +83,7 @@ async function show(argv: string[], deps: RuntimeApiDeps): Promise<void> {
80
83
  printData(combo, wantsJson);
81
84
  }
82
85
 
86
+ /** Handle `ocx combo set`: parse the combo id and flags (including `--decision-quota-signals` and `--decision-quota-tiers`), then create or update the combo through the management API. */
83
87
  async function set(argv: string[], deps: RuntimeApiDeps): Promise<number> {
84
88
  const args = [...argv];
85
89
  const id = args.shift()?.trim();
@@ -118,6 +122,7 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise<number> {
118
122
  const alias = takeOption(args, "--alias");
119
123
 
120
124
  const displayName = takeOption(args, "--display-name");
125
+ const description = takeOption(args, "--description");
121
126
  const decisionProvider = takeOption(args, "--decision-provider");
122
127
  const decisionModel = takeOption(args, "--decision-model");
123
128
  if (decisionModel !== undefined && decisionModel !== "-" && decisionProvider !== undefined && decisionProvider !== "-") {
@@ -129,6 +134,13 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise<number> {
129
134
  if (decisionProvider !== undefined && decisionProvider !== "-" && strategy !== "jev") {
130
135
  throw new CliUsageError("--decision-provider applies only to the jev strategy", USAGE);
131
136
  }
137
+ const quotaSignals = takeOption(args, "--decision-quota-signals");
138
+ const quotaTiers = takeOption(args, "--decision-quota-tiers");
139
+ if (quotaSignals !== undefined && !["on", "off", "-"].includes(quotaSignals)) throw new CliUsageError("--decision-quota-signals must be on, off or -", USAGE);
140
+ let parsedQuotaTiers: ReturnType<typeof normalizeJevQuotaTiers> | null;
141
+ try { parsedQuotaTiers = quotaTiers === undefined || quotaTiers === "-" ? null : normalizeJevQuotaTiers(JSON.parse(quotaTiers)); } catch { throw new CliUsageError("invalid --decision-quota-tiers JSON", USAGE); }
142
+ if (quotaTiers !== undefined && quotaTiers !== "-" && !parsedQuotaTiers) throw new CliUsageError("quota tiers must be finite 0..100 and strictly ascending", USAGE);
143
+ if (strategy !== "jev" && (quotaSignals !== undefined && quotaSignals !== "-" || quotaTiers !== undefined && quotaTiers !== "-")) throw new CliUsageError("quota settings apply only to jev", USAGE);
132
144
  const decisionTimeout = takeOption(args, "--decision-timeout");
133
145
  let decisionTimeoutMs: number | null | undefined;
134
146
  if (decisionTimeout !== undefined) {
@@ -164,15 +176,20 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise<number> {
164
176
  if (additional.imageInput !== undefined) combo.imageInput = additional.imageInput;
165
177
  if (additional.reasoningEffortMode !== undefined) combo.reasoningEffortMode = additional.reasoningEffortMode;
166
178
  if (displayName !== undefined) combo.displayName = displayName === "-" ? "" : displayName;
179
+ if (description !== undefined) combo.description = description === "-" ? "" : description;
167
180
  if (decisionProvider !== undefined) combo.decisionProvider = decisionProvider === "-" ? null : decisionProvider;
168
181
  if (decisionModel !== undefined) combo.decisionModel = decisionModel === "-" ? null : decisionModel;
169
182
  if (decisionProvider !== undefined && decisionProvider !== "-") combo.decisionModel = null;
170
183
  if (decisionModel !== undefined && decisionModel !== "-") combo.decisionProvider = null;
171
184
  if (decisionTimeoutMs !== undefined) combo.decisionTimeoutMs = decisionTimeoutMs;
185
+ if (quotaSignals !== undefined) combo.decisionQuotaSignals = quotaSignals === "-" ? null : quotaSignals === "on";
186
+ if (quotaTiers !== undefined) combo.decisionQuotaTiers = parsedQuotaTiers;
172
187
  if (strategy !== "jev") {
173
188
  delete combo.decisionProvider;
174
189
  delete combo.decisionModel;
175
190
  delete combo.decisionTimeoutMs;
191
+ delete combo.decisionQuotaSignals;
192
+ delete combo.decisionQuotaTiers;
176
193
  }
177
194
  const current = partialCurrent ?? await runtimeRequest<{ combos?: ComboRow[] }>("/api/combos", { redirect: "error" }, deps);
178
195
  const existing = (current.combos ?? []).find(row => row.id === (renameFrom ?? id));
package/src/cli/help.ts CHANGED
@@ -79,7 +79,7 @@ Usage:
79
79
  ocx alias <sub> Short names for providers and models (list, set, rm, defaults)
80
80
  ocx combo <sub> Combo routing strategies and failover
81
81
  ocx agent <sub> Subagents, injection, effort caps, and sidecars
82
- ocx message <sub> Loaded local Codex sessions and queued peer messages (sessions|send)
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
84
  ocx observe <sub> Logs, usage, storage, memory, and debug data
85
85
  ocx inspect <sub> Effective config, catalog, analytics, pacing, client-config
@@ -2,13 +2,16 @@ import { MessageBudget } from "../messaging/budget";
2
2
  import { readMessageInput } from "../messaging/input";
3
3
  import { localSessions, messageFailure, sendLocalMessage } from "../messaging/send";
4
4
  import { parseMessageArgs } from "./message-args";
5
+ import { parseRemoteMessageArgs } from "./message-remote-args";
5
6
  import { terminalSafeText } from "./runtime-api";
6
7
 
7
8
  /** Run one local messaging operation after pure syntax validation, then release owned resources. */
8
9
  export async function runMessageCommand(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): Promise<number> {
10
+ const remote = parseRemoteMessageArgs(argv);
11
+ if (remote) return (await import("./message-remote-command")).runRemoteMessageCommand(remote, env);
9
12
  const args = parseMessageArgs(argv);
10
13
  if (!args) {
11
- console.error("Usage: ocx message sessions [--json] | send (--thread <uuid> | --name <exact-name>) --stdin [--kind request|response|notification] [--in-reply-to <uuid>] [--json]");
14
+ console.error("Usage: ocx message sessions [--host <peer>] [--json] | send (--thread <uuid> | --name <exact-name>) --stdin [--host <peer>] [--kind request|response|notification] [--in-reply-to <uuid>] [--json] | enable [--port <port>] | disable | status | hosts <probe|add|list|remove|abandon|allow-inbound|deny-inbound> | serve [--host <peer>]...");
12
15
  return 64;
13
16
  }
14
17
  const controller = new AbortController();
@@ -0,0 +1,69 @@
1
+ import { validAlias, validPort, REMOTE_LIMITS } from "../messaging/remote-contract";
2
+ import { isSshAlias } from "../link/ssh-argv";
3
+ import { parseMessageArgs, type MessageArgs } from "./message-args";
4
+ import { isThreadId } from "../messaging/types";
5
+
6
+ export type RemoteMessageArgs = { action: "enable"; port?: number; json: boolean }
7
+ | { action: "disable" | "status" | "hosts-list" | "_control" | "_port"; json: boolean }
8
+ | { action: "serve"; hosts: string[]; json: boolean }
9
+ | { action: "hosts-probe"; ssh: string; json: boolean }
10
+ | { action: "hosts-add"; alias: string; ssh: string; fingerprint: string; json: boolean }
11
+ | { action: "hosts-remove"; host: string; transaction?: string; json: boolean }
12
+ | { action: "hosts-allow-inbound" | "hosts-deny-inbound"; host: string; json: boolean }
13
+ | { action: "hosts-abandon"; transaction: string; json: boolean }
14
+ | { action: "remote-operation"; host: string; local: MessageArgs; json: boolean };
15
+
16
+ /** Pure remote syntax validation precedes state, home selection, listeners or SSH allocation. */
17
+ export function parseRemoteMessageArgs(argv: readonly string[]): RemoteMessageArgs | null {
18
+ let action = argv[0], start = 1, positional: string | undefined;
19
+ if (action === "sessions" || action === "send") {
20
+ const hostIndex = argv.indexOf("--host");
21
+ if (hostIndex < 0 || argv.lastIndexOf("--host") !== hostIndex || !validAlias(argv[hostIndex + 1])) return null;
22
+ const local = parseMessageArgs([...argv.slice(0, hostIndex), ...argv.slice(hostIndex + 2)]);
23
+ return local ? { action: "remote-operation", host: argv[hostIndex + 1]!, local, json: local.json } : null;
24
+ }
25
+ if (action === "hosts") {
26
+ if (!["list", "probe", "add", "remove", "abandon", "allow-inbound", "deny-inbound"].includes(argv[1] ?? "")) return null;
27
+ action = `hosts-${argv[1]}`; start = 2;
28
+ if (["hosts-add", "hosts-remove", "hosts-allow-inbound", "hosts-deny-inbound"].includes(action)) {
29
+ positional = argv[start++]; if (!validAlias(positional)) return null;
30
+ }
31
+ }
32
+ const seen = new Set<string>(), flags: Record<string, string> = {}, hosts: string[] = [];
33
+ for (let index = start; index < argv.length; index++) {
34
+ const flag = argv[index]!;
35
+ if (seen.has(flag) && !(action === "serve" && flag === "--host")) return null;
36
+ seen.add(flag);
37
+ if (flag === "--json") continue;
38
+ const allowed = action === "enable" ? ["--port"] : action === "serve" ? ["--host"]
39
+ : action === "hosts-probe" ? ["--ssh"] : action === "hosts-add" ? ["--ssh", "--fingerprint"]
40
+ : action === "hosts-abandon" || action === "hosts-remove" ? ["--transaction"] : [];
41
+ if (!allowed.includes(flag)) return null;
42
+ const value = argv[++index]; if (!value || value.startsWith("--")) return null;
43
+ flags[flag] = value; if (flag === "--host") hosts.push(value);
44
+ }
45
+ const json = seen.has("--json");
46
+ if (action === "enable") {
47
+ if (flags["--port"] !== undefined && (!/^\d{4,5}$/.test(flags["--port"]) || !validPort(Number(flags["--port"])))) return null;
48
+ return { action, json, ...(flags["--port"] ? { port: Number(flags["--port"]) } : {}) };
49
+ }
50
+ if (action === "serve") return hosts.length <= REMOTE_LIMITS.peers && hosts.every(validAlias)
51
+ && new Set(hosts).size === hosts.length ? { action, hosts, json } : null;
52
+ if (["disable", "status", "hosts-list", "_control", "_port"].includes(action ?? "")) {
53
+ return { action: action as "disable", json };
54
+ }
55
+ if (action === "hosts-remove") {
56
+ const transaction = flags["--transaction"];
57
+ if (transaction !== undefined && !isThreadId(transaction)) return null;
58
+ return { action, host: positional!, json, ...(transaction !== undefined ? { transaction } : {}) };
59
+ }
60
+ if (action === "hosts-allow-inbound" || action === "hosts-deny-inbound") return { action, host: positional!, json };
61
+ if (action === "hosts-abandon" && isThreadId(flags["--transaction"])) return { action, transaction: flags["--transaction"]!, json };
62
+ if ((action === "hosts-probe" || action === "hosts-add") && flags["--ssh"] && isSshAlias(flags["--ssh"])) {
63
+ if (action === "hosts-probe") return { action, ssh: flags["--ssh"], json };
64
+ if (/^SHA256:[A-Za-z0-9+/=]{1,64}$/.test(flags["--fingerprint"] ?? "")) return {
65
+ action, alias: positional!, ssh: flags["--ssh"], fingerprint: flags["--fingerprint"], json,
66
+ };
67
+ }
68
+ return null;
69
+ }
@@ -0,0 +1,77 @@
1
+ import { getConfigDir } from "../config/paths";
2
+ import { MessageBudget } from "../messaging/budget";
3
+ import { readMessageInput } from "../messaging/input";
4
+ import { RemoteCapacity } from "../messaging/remote-contract";
5
+ import { enrollRemoteHost, handleEnrollmentControl, probeRemoteHost, removeRemoteHost } from "../messaging/remote-enrollment";
6
+ import { abandonRemoteEnrollment, pendingRemoteEnrollment } from "../messaging/remote-enrollment-recovery";
7
+ import { remoteControl } from "../messaging/remote-auth";
8
+ import { ownerEndpoint, startRemoteOwner } from "../messaging/remote-owner";
9
+ import { remotePortCandidate } from "../messaging/remote-ports";
10
+ import { remoteSessions, sendRemoteMessage } from "../messaging/remote-send";
11
+ import { RemoteMessageStore } from "../messaging/remote-store";
12
+ import { messageFailure } from "../messaging/send";
13
+ import { messageCodexHome } from "./message-runtime";
14
+ import { terminalSafeText } from "./runtime-api";
15
+ import type { RemoteMessageArgs } from "./message-remote-args";
16
+
17
+ /** Activate remote resources only after an explicit remote command's pure parser succeeds. */
18
+ export async function runRemoteMessageCommand(args: RemoteMessageArgs, env: NodeJS.ProcessEnv): Promise<number> {
19
+ const store = new RemoteMessageStore(getConfigDir()), controller = new AbortController(), capacity = new RemoteCapacity();
20
+ const cancel = () => controller.abort();
21
+ process.once("SIGINT", cancel); process.once("SIGTERM", cancel);
22
+ const emit = (value: unknown) => console.log(args.json || args.action.startsWith("_")
23
+ ? JSON.stringify(value) : terminalSafeText(JSON.stringify(value)));
24
+ try {
25
+ if (args.action === "serve") {
26
+ const owner = await startRemoteOwner(store, messageCodexHome(env), args.hosts, controller.signal);
27
+ try {
28
+ emit({ protocol: "ocx-message-remote/1", running: true, port: owner.port });
29
+ await Promise.race([owner.finished, new Promise<void>(resolve => {
30
+ controller.signal.addEventListener("abort", () => resolve(), { once: true });
31
+ if (controller.signal.aborted) resolve();
32
+ })]);
33
+ if (!controller.signal.aborted) { emit({ running: false, error: { code: "owner_retired", message: "Foreground messaging owner retired; restart explicitly after resolving its route/configuration failure." } }); return 1; }
34
+ } finally { await owner.close(); }
35
+ return 0;
36
+ }
37
+ const budget = new MessageBudget(30000, controller.signal);
38
+ try {
39
+ if (args.action === "enable") { store.enable(args.port ?? store.read()?.port ?? 39176); emit(store.publicState()); }
40
+ else if (args.action === "disable") { store.disable(); emit(store.publicState()); }
41
+ else if (args.action === "hosts-list") emit({ ...store.publicState(), pendingEnrollment: pendingRemoteEnrollment(store) });
42
+ else if (args.action === "hosts-abandon") { emit(abandonRemoteEnrollment(store, args.transaction)); return 3; }
43
+ else if (args.action === "status") {
44
+ const state = store.read(); let running = false, routes: unknown = [];
45
+ if (state?.enabled) {
46
+ try { const result = await remoteControl(state, ownerEndpoint(state), "message/routes", {}, budget);
47
+ running = true; routes = result; } catch { /* Disabled/offline is not activation or repair. */ }
48
+ }
49
+ emit({ ...store.publicState(), running, routes, pendingEnrollment: pendingRemoteEnrollment(store) });
50
+ } else if (args.action === "hosts-probe") emit({ ssh: args.ssh, fingerprint: (await probeRemoteHost(args.ssh, budget, capacity)).fingerprint });
51
+ else if (args.action === "hosts-add") emit(await enrollRemoteHost(store, args.alias, args.ssh, args.fingerprint, budget, capacity));
52
+ else if (args.action === "hosts-allow-inbound" || args.action === "hosts-deny-inbound") {
53
+ emit(store.setInbound(args.host, args.action === "hosts-allow-inbound"));
54
+ }
55
+ else if (args.action === "hosts-remove") {
56
+ const receipt = await removeRemoteHost(store, args.host, budget, capacity, undefined, undefined, args.transaction); emit(receipt);
57
+ return receipt.remote === "removed" ? 0 : 3;
58
+ } else if (args.action === "_control") {
59
+ emit(handleEnrollmentControl(store, JSON.parse(await readMessageInput(Bun.stdin.stream(), budget))));
60
+ } else if (args.action === "_port") { store.requireEnabled(); emit({ port: remotePortCandidate() }); }
61
+ else if (args.action === "remote-operation") {
62
+ if (args.local.action === "sessions") emit(await remoteSessions(store, args.host, budget));
63
+ else {
64
+ const body = await readMessageInput(Bun.stdin.stream(), budget);
65
+ const receipt = await sendRemoteMessage(store, { ...args.local, host: args.host, body },
66
+ { home: messageCodexHome(env), senderId: env.CODEX_THREAD_ID }, budget);
67
+ emit(receipt); return receipt.status === "queued" ? 0 : receipt.status === "unknown" ? 3 : 1;
68
+ }
69
+ }
70
+ return 0;
71
+ } finally { budget.dispose(); }
72
+ } catch (error) {
73
+ // Control errors never echo stdin, SSH output, keys or paths; a failed enrollment keeps its transaction.
74
+ const failure = messageFailure(error), unknown = ["enrollment_unknown", "remote_control_unknown", "remote_storage_unknown", "cleanup_incomplete"].includes(failure.code);
75
+ emit({ schema: "ocx-message-error/1", ...(unknown ? { status: "unknown" } : args.action === "remote-operation" && args.local.action === "send" ? { status: "not_sent" } : {}), error: failure }); return unknown ? 3 : 1;
76
+ } finally { process.removeListener("SIGINT", cancel); process.removeListener("SIGTERM", cancel); }
77
+ }
@@ -10,8 +10,10 @@ import {
10
10
  takeBooleanOption,
11
11
  takeFlag,
12
12
  takeOption,
13
+ terminalSafeText,
13
14
  type RuntimeApiDeps,
14
15
  } from "./runtime-api";
16
+ import { interactiveConfirm } from "./interactive-confirm";
15
17
  import { takeProviderEditSettings } from "./provider-settings";
16
18
  import { printProviderReceipt, runProviderAction } from "./provider-result";
17
19
  import { providerQuotaLine } from "./account-extended";
@@ -46,7 +48,7 @@ const USAGE = `Usage:
46
48
  [--retain-models <id,id|->] [--model <id> --text-only]
47
49
  [--xai-chat <on|off>] [--upstream-http-version <http1.1|->] [--fast <on|off>] [--context-window <tokens|->]
48
50
  [--allow-private-network <on|off>] [--model-context-tier <model=default|long_context>] [--json]
49
- ocx provider test <name> [--json]
51
+ ocx provider test <name> [--model <id> [--yes]] [--json]
50
52
  ocx provider quota [--refresh] [--json]
51
53
  ocx provider resets [--limit <n>] [--json]
52
54
  ocx provider presets [--json]
@@ -147,12 +149,78 @@ async function edit(argv: string[], deps: RuntimeApiDeps): Promise<number> {
147
149
  return printProviderReceipt(result, wantsJson, "Provider edit");
148
150
  }
149
151
 
152
+ interface CompletionTestDto {
153
+ applicable: boolean;
154
+ reason?: string;
155
+ detail?: string;
156
+ adapter?: string;
157
+ ok?: boolean;
158
+ wireModel?: string;
159
+ upstreamModel?: string | null;
160
+ modelComparison?: "match" | "mismatch" | "unknown";
161
+ comparisonNote?: "missing_metadata" | "conflicting_metadata";
162
+ ttftMs?: number | null;
163
+ totalLatencyMs?: number;
164
+ error?: { code: string; message: string; status?: number } | null;
165
+ }
166
+
167
+ async function testCompletion(name: string, model: string, yes: boolean, wantsJson: boolean, deps: RuntimeApiDeps): Promise<number> {
168
+ const input = deps.stdinImpl ?? process.stdin;
169
+ if (!yes && (wantsJson || !input.isTTY)) {
170
+ throw new CliUsageError("completion tests consume quota and may incur cost; --yes is required with --json or non-interactive input", USAGE);
171
+ }
172
+ const warning = terminalSafeText(`${name}: completion test for model ${model}. Warning: this sends an upstream request, consumes quota and may incur cost.`);
173
+ if (wantsJson) console.error(warning);
174
+ else console.log(warning);
175
+ if (!yes && !await interactiveConfirm({
176
+ question: "Run this completion test?", defaultYes: false, input: input as NodeJS.ReadStream,
177
+ })) {
178
+ console.log("cancelled");
179
+ return 1;
180
+ }
181
+ const result = await runtimeRequest<CompletionTestDto>(`/api/providers/test-completion?name=${encodeURIComponent(name)}`, {
182
+ method: "POST", redirect: "error", body: JSON.stringify({ model, confirm: true }),
183
+ }, deps);
184
+ if (result.applicable === false) {
185
+ printData(result, wantsJson, [
186
+ `${name}: not applicable — ${result.reason}`,
187
+ ...(result.detail ? [`Detail: ${result.detail}`] : []),
188
+ ...(result.adapter ? [`Adapter: ${result.adapter}`] : []),
189
+ ]);
190
+ return 0;
191
+ }
192
+ if (result.ok === true) {
193
+ printData(result, wantsJson, [
194
+ `${name}: connected`,
195
+ `TTFT: ${result.ttftMs ?? "unknown"} ms`,
196
+ `Total latency: ${result.totalLatencyMs ?? "unknown"} ms`,
197
+ `Upstream reported ${result.upstreamModel ?? "unknown"} for ${result.wireModel} — ${result.modelComparison}${result.comparisonNote ? ` (${result.comparisonNote})` : ""}`,
198
+ "metadata only — not proof of model identity",
199
+ ]);
200
+ return 0;
201
+ }
202
+ printData(result, wantsJson, [
203
+ `${name}: failed`,
204
+ `${result.error?.code ?? "unknown"}: ${result.error?.message ?? "Completion test failed"}${result.error?.status === undefined ? "" : ` (HTTP ${result.error.status})`}`,
205
+ ]);
206
+ return 1;
207
+ }
208
+
150
209
  async function testProvider(argv: string[], deps: RuntimeApiDeps): Promise<number> {
151
210
  const args = [...argv];
152
211
  const name = args.shift()?.trim();
153
212
  const wantsJson = takeFlag(args, "--json");
154
213
  if (!name) throw new CliUsageError("provider name is required", USAGE);
214
+ const model = takeOption(args, "--model")?.trim();
215
+ const yes = takeFlag(args, "--yes");
155
216
  rejectArgs(args, USAGE);
217
+ if (yes && model === undefined) throw new CliUsageError("--yes requires --model", USAGE);
218
+ if (model !== undefined) {
219
+ if (!model || model.length > 256 || /[\x00-\x1f\x7f-\x9f]/.test(model)) {
220
+ throw new CliUsageError("--model must contain 1..256 characters without control characters", USAGE);
221
+ }
222
+ return testCompletion(name, model, yes, wantsJson, deps);
223
+ }
156
224
  const result = await runtimeRequest<Record<string, unknown>>(`/api/providers/test?name=${encodeURIComponent(name)}`, {
157
225
  method: "POST",
158
226
  }, deps);