@bitkyc08/opencodex 2.100.1 → 2.100.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/gui/dist/assets/App-BpJOzw4F.js +59 -0
- package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
- package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-DU-0Vdkr.js} +1 -1
- package/gui/dist/assets/index-Bbor_y80.js +94 -0
- package/gui/dist/assets/index-DJEkIDAi.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-e9A_FogJ.js} +1 -1
- package/gui/dist/classic/assets/{App-CgPBKUP-.js → App-BrIlUiLc.js} +18 -18
- package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-DT146AhS.js} +1 -1
- package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/package.json +2 -2
- package/src/adapters/client-fingerprint.ts +5 -3
- package/src/adapters/cursor/native-exec.ts +3 -2
- package/src/adapters/cursor/tool-guidance.ts +3 -3
- package/src/adapters/cursor/tool-wording.ts +10 -1
- package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
- package/src/adapters/google-antigravity-wire.ts +13 -6
- package/src/adapters/google-truncation.ts +4 -2
- package/src/adapters/google.ts +8 -2
- package/src/adapters/openai-chat/tool-schema.ts +9 -0
- package/src/adapters/openai-responses/tool-schema.ts +18 -4
- package/src/adapters/run-turn-queue.ts +139 -5
- package/src/adapters/upstream-http-error.ts +4 -2
- package/src/bridge/sse.ts +8 -1
- package/src/claude/chat-tool-dispatch.ts +233 -0
- package/src/claude/inbound-tool-loading.ts +42 -17
- package/src/cli/account-api.ts +6 -0
- package/src/cli/account-extended.ts +60 -6
- package/src/cli/account-key-quota.ts +22 -2
- package/src/cli/account.ts +1 -1
- package/src/cli/capabilities-access-remote.ts +10 -0
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-base.ts +2 -2
- package/src/cli/claude.ts +19 -14
- package/src/cli/config-command.ts +24 -1
- package/src/cli/connect.ts +36 -3
- package/src/cli/gui-pair-client.ts +23 -2
- package/src/cli/help.ts +1 -1
- package/src/cli/hub.ts +18 -1
- package/src/cli/link-child-ops.ts +136 -0
- package/src/cli/link-status-child.ts +94 -0
- package/src/cli/link.ts +22 -9
- package/src/cli/registry.ts +3 -2
- package/src/cli/sync-command.ts +3 -1
- package/src/cli/sync-fanout.ts +8 -81
- package/src/client/link-readiness.ts +16 -6
- package/src/client/link-tunnel-status.ts +76 -0
- package/src/clients/config-export.ts +14 -1
- package/src/codex/account-resume-health.ts +41 -0
- package/src/codex/auth-api/login-flow.ts +6 -0
- package/src/codex/auth-api/routes.ts +35 -2
- package/src/codex/catalog/gather-capture.ts +2 -0
- package/src/codex/catalog/provider-models.ts +13 -8
- package/src/codex/convergence-types.ts +2 -0
- package/src/codex/quota.ts +111 -6
- package/src/combos/cooldown-store.ts +208 -0
- package/src/combos/failover.ts +432 -35
- package/src/config/salvage.ts +1 -0
- package/src/config/schema/config-schema.ts +6 -3
- package/src/config/schema/leaf-validators.ts +34 -12
- package/src/generated/compatibility-version.json +213 -121
- package/src/lib/catalog-etag.ts +10 -0
- package/src/lib/client-error-body.ts +15 -0
- package/src/lib/context-overflow-verdict.ts +266 -9
- package/src/lib/failure-detail.ts +72 -3
- package/src/lib/hard-refusal.ts +259 -0
- package/src/link/child-activity.ts +57 -0
- package/src/link/child-catalog-freshness.ts +149 -0
- package/src/link/child-gated-ocx.ts +117 -0
- package/src/link/child-observations.ts +205 -0
- package/src/link/child-observe.ts +121 -0
- package/src/link/child-ops-engine.ts +162 -0
- package/src/link/child-update-contract.ts +165 -0
- package/src/link/paths.ts +5 -0
- package/src/link/remote-windows.ts +42 -6
- package/src/link/ssh-argv.ts +126 -32
- package/src/link/status-projection.ts +73 -0
- package/src/link/sync-fanout-classify.ts +98 -0
- package/src/link/tunnel-state.ts +10 -4
- package/src/messaging/mcp-queue-rpc.ts +2 -1
- package/src/messaging/mcp-queue-server.ts +5 -0
- package/src/messaging/mcp-reply-tools.ts +24 -9
- package/src/messaging/mcp-reply-wait.ts +70 -0
- package/src/oauth/account-resume-health.ts +60 -0
- package/src/oauth/index.ts +1 -0
- package/src/oauth/store.ts +44 -1
- package/src/providers/api-key-pause-state.ts +23 -0
- package/src/providers/api-key-pause.ts +68 -10
- package/src/providers/api-key-selection-capture.ts +3 -1
- package/src/providers/api-key-selection.ts +3 -2
- package/src/providers/api-keys.ts +18 -5
- package/src/providers/claude-cli-usage-state.ts +11 -6
- package/src/providers/claude-cli-usage.ts +27 -9
- package/src/providers/codex-capacity.ts +11 -2
- package/src/providers/key-failover.ts +13 -6
- package/src/providers/model-discovery-config.ts +31 -0
- package/src/providers/model-discovery-diagnostic.ts +34 -3
- package/src/providers/model-discovery.ts +43 -7
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/openai-sidecar.ts +15 -2
- package/src/providers/provider-id-rewrite.ts +3 -0
- package/src/providers/quota/account-cache.ts +52 -34
- package/src/providers/quota/anthropic-usage-windows.ts +19 -9
- package/src/providers/quota/report-cache.ts +53 -5
- package/src/providers/quota/vendor-probes-key.ts +73 -0
- package/src/providers/quota/vendor-probes-oauth.ts +57 -3
- package/src/providers/quota-key-accounts.ts +12 -5
- package/src/providers/quota-mistral-budget.ts +18 -0
- package/src/providers/quota-types.ts +25 -0
- package/src/providers/quota.ts +22 -22
- package/src/providers/reasoning-metadata.ts +1051 -12
- package/src/quota/reset-observer.ts +4 -2
- package/src/quota/reset-seen-store.ts +9 -0
- package/src/quota/window-mapping.ts +1 -0
- package/src/quota-pool/assemble.ts +4 -1
- package/src/responses/hosted-tool-policy.ts +56 -12
- package/src/router.ts +2 -0
- package/src/server/auth-cors.ts +11 -8
- package/src/server/catalog-download.ts +3 -5
- package/src/server/chat-native.ts +11 -2
- package/src/server/claude-messages.ts +2 -1
- package/src/server/images.ts +41 -13
- package/src/server/index/link-listener.ts +16 -2
- package/src/server/index/link-relay-sessions.ts +43 -2
- package/src/server/index/optional-listeners.ts +18 -0
- package/src/server/management/config-routes.ts +7 -1
- package/src/server/management/context.ts +1 -1
- package/src/server/management/link-child-ops-routes.ts +116 -0
- package/src/server/management/link-route-state.ts +10 -0
- package/src/server/management/link-routes.ts +10 -0
- package/src/server/management/oauth-account-routes.ts +33 -4
- package/src/server/management/provider-overwrite-carry.ts +28 -3
- package/src/server/management/provider-routes.ts +16 -11
- package/src/server/management/route-registry.ts +3 -0
- package/src/server/messages-native.ts +5 -0
- package/src/server/request-log-failure-detail.ts +59 -1
- package/src/server/responses/adapter-dispatch.ts +35 -44
- package/src/server/responses/combo-stream-preflight.ts +146 -29
- package/src/server/responses/compact.ts +16 -5
- package/src/server/responses/context-overflow.ts +58 -2
- package/src/server/responses/core-combo-failure.ts +29 -4
- package/src/server/responses/core-combo-native.ts +3 -1
- package/src/server/responses/core-combo.ts +30 -3
- package/src/server/responses/core-errors.ts +3 -1
- package/src/server/responses/core-opaque-recovery.ts +45 -2
- package/src/server/responses/core-options.ts +12 -0
- package/src/server/responses/passthrough-dispatch.ts +30 -38
- package/src/server/responses/request-transport.ts +43 -14
- package/src/server/responses/reset-replay.ts +58 -2
- package/src/server/responses/run-turn-execution.ts +56 -30
- package/src/types/claude-tool-loading.ts +48 -0
- package/src/types/config.ts +5 -35
- package/src/types/provider.ts +21 -0
- package/src/types.ts +1 -0
- package/src/web-search/parse.ts +21 -2
- package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
- package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
- package/gui/dist/assets/index-Bziu8gTy.css +0 -2
- package/gui/dist/assets/index-OYzhQUNP.js +0 -94
- package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
- package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
|
@@ -3,6 +3,8 @@ import { loadConfig } from "../config";
|
|
|
3
3
|
import { anthropicProviderIdentityError, cmdAnthropicAccountThreshold } from "./account-anthropic-threshold";
|
|
4
4
|
import { isReservedCodexAccountWord, reportCodexAccountTargetError, resolveCodexAccountTarget } from "./account-target";
|
|
5
5
|
import { hasPassiveAccountQuota } from "../providers/quota";
|
|
6
|
+
import { isWeeklyAllowancePercent } from "../providers/quota-types";
|
|
7
|
+
import { terminalSafeText } from "./runtime-api";
|
|
6
8
|
import { closeSync, openSync, readSync, readFileSync, statSync } from "node:fs";
|
|
7
9
|
import {
|
|
8
10
|
MAX_ACCOUNT_PRIORITY,
|
|
@@ -46,7 +48,7 @@ const EXTENDED_USAGE = `Usage:
|
|
|
46
48
|
ocx account alias <provider> <id|alias|main> <display-name|-> [--json]
|
|
47
49
|
ocx account priority <provider> <id|alias|main> [<-100..100|first|earlier|normal|later|last|reset>] [--json]
|
|
48
50
|
ocx account pause <provider> <id|alias|main> [--json]
|
|
49
|
-
ocx account resume <provider> <id|alias|main> [--json]
|
|
51
|
+
ocx account resume <provider> <id|alias|main> [--if-healthy] [--json]
|
|
50
52
|
ocx account pause-exhausted <provider> [--json]
|
|
51
53
|
ocx account strategy <provider> [<quota|round-robin|fill-first|least-loaded|reset-first>] [--json]
|
|
52
54
|
ocx account sticky <provider> [<1-100>] [--json]
|
|
@@ -275,16 +277,28 @@ function refreshLine(row: FamilyRows["rows"][number]): string {
|
|
|
275
277
|
|
|
276
278
|
function quotaParts(quota: ProviderQuotaDto): string[] {
|
|
277
279
|
const parts: string[] = [];
|
|
278
|
-
const add = (label: string, percent: number | undefined, resetAt?: number) => {
|
|
280
|
+
const add = (label: string, percent: number | undefined, resetAt?: number, note?: string) => {
|
|
279
281
|
if (percent === undefined) return;
|
|
280
|
-
parts.push(`${label} ${percent}
|
|
282
|
+
parts.push(`${label} ${percent}%${note ? ` (${note})` : ""}`);
|
|
281
283
|
const reset = resetIso(resetAt);
|
|
282
284
|
if (reset) parts.push(`resets ${reset}`);
|
|
283
285
|
};
|
|
284
286
|
add("5h", quota.fiveHourPercent, quota.fiveHourResetAt);
|
|
285
287
|
add("weekly", quota.weeklyPercent, quota.weeklyResetAt);
|
|
286
288
|
add("monthly", quota.monthlyPercent, quota.monthlyResetAt);
|
|
287
|
-
for (const window of quota.customWindows ?? []) add(window.label, window.percent, window.resetAt);
|
|
289
|
+
for (const window of quota.customWindows ?? []) add(terminalSafeText(window.displayLabel ?? window.label), window.percent, window.resetAt);
|
|
290
|
+
// Same rule as the dashboard: a routed row with the same label wins over a display-only one.
|
|
291
|
+
const routed = new Set((quota.customWindows ?? []).map(window => window.label));
|
|
292
|
+
for (const window of quota.displayWindows ?? []) {
|
|
293
|
+
if (routed.has(window.label)) continue;
|
|
294
|
+
const share = isWeeklyAllowancePercent(window.weeklyAllowancePercent) ? `up to ${window.weeklyAllowancePercent}% of weekly; ` : "";
|
|
295
|
+
add(terminalSafeText(window.label), window.percent, window.resetAt, `${share}not in effect`);
|
|
296
|
+
}
|
|
297
|
+
for (const window of quota.unknownBudgetWindows ?? []) {
|
|
298
|
+
parts.push(`${terminalSafeText(window.label)} unknown`);
|
|
299
|
+
const reset = resetIso(window.resetAt);
|
|
300
|
+
if (reset) parts.push(`resets ${reset}`);
|
|
301
|
+
}
|
|
288
302
|
return parts;
|
|
289
303
|
}
|
|
290
304
|
|
|
@@ -803,14 +817,26 @@ function resolveGenericOAuthAccountTarget(accounts: unknown[], requested: string
|
|
|
803
817
|
/** Pause or resume a Codex, OAuth, or API-key pool account. */
|
|
804
818
|
export async function cmdPause(args: string[], deps: AccountDeps, paused: boolean): Promise<number> {
|
|
805
819
|
const wantsJson = flag(args, "--json");
|
|
820
|
+
// #8398: an explicit resume the server performs only after an account-bound health read.
|
|
821
|
+
const ifHealthy = flag(args, "--if-healthy");
|
|
806
822
|
const name = args.shift();
|
|
807
823
|
const requestedId = args.shift();
|
|
808
824
|
const verb = paused ? "pause" : "resume";
|
|
809
825
|
if (!name || !requestedId || args.length) return usage();
|
|
826
|
+
if (ifHealthy && paused) return usage("Error: --if-healthy applies only to resume");
|
|
810
827
|
const classified = configAndType(deps, name);
|
|
811
828
|
if ("error" in classified) return usage(`Error: ${classified.error}`);
|
|
829
|
+
if (ifHealthy && classified.type === "api-key") return usage("Error: --if-healthy applies to the openai Codex account pool or an OAuth provider pool");
|
|
812
830
|
const baseUrl = await resolveBaseUrl(deps);
|
|
813
831
|
if (!baseUrl) return proxyUnreachable();
|
|
832
|
+
const healthGate = ifHealthy ? { ifHealthy: true } : {};
|
|
833
|
+
// A refused health-gated resume is an answer, not a failure: exit 3 lets a supervisor tell it apart.
|
|
834
|
+
const refusedResume = (json: Record<string, unknown>, id: string): number | undefined => {
|
|
835
|
+
if (!ifHealthy || json.code !== "resume_refused" || typeof json.reason !== "string") return undefined;
|
|
836
|
+
if (wantsJson) console.log(JSON.stringify({ ok: false, provider: name, id, resumed: false, reason: json.reason }, null, 2));
|
|
837
|
+
else console.log(`${name}: ${requestedId} not resumed: ${json.reason}`);
|
|
838
|
+
return 3;
|
|
839
|
+
};
|
|
814
840
|
|
|
815
841
|
if (classified.type === "oauth") {
|
|
816
842
|
const list = await apiJson(deps, baseUrl, "GET", `/api/oauth/accounts?provider=${encodeURIComponent(name)}`);
|
|
@@ -823,8 +849,10 @@ export async function cmdPause(args: string[], deps: AccountDeps, paused: boolea
|
|
|
823
849
|
provider: name,
|
|
824
850
|
accountId: target.id,
|
|
825
851
|
paused,
|
|
852
|
+
...healthGate,
|
|
826
853
|
});
|
|
827
854
|
if (response.status === 0) return proxyUnreachable(response.transportError);
|
|
855
|
+
if (response.status === 409) { const refused = refusedResume(response.json, target.id); if (refused !== undefined) return refused; }
|
|
828
856
|
if (response.status !== 200) return apiError(response.json, `failed to ${verb} ${requestedId}`, response.status);
|
|
829
857
|
|
|
830
858
|
if (wantsJson) {
|
|
@@ -848,7 +876,32 @@ export async function cmdPause(args: string[], deps: AccountDeps, paused: boolea
|
|
|
848
876
|
const result = await apiJson(deps, baseUrl, "PUT", "/api/providers/keys/pause", { name, id: target.id, paused });
|
|
849
877
|
if (result.status === 0) return proxyUnreachable(result.transportError);
|
|
850
878
|
if (result.status !== 200) return apiError(result.json, `failed to ${verb} account`, result.status);
|
|
851
|
-
|
|
879
|
+
const idx = rows.rows.findIndex(row => row.id === target.id);
|
|
880
|
+
const ordered = idx >= 0 ? [...rows.rows.slice(idx + 1), ...rows.rows.slice(0, idx)] : rows.rows;
|
|
881
|
+
const beforeActiveId = rows.rows.find(row => row.active && !row.paused)?.id ?? null;
|
|
882
|
+
const inferredActiveId = paused
|
|
883
|
+
? (beforeActiveId === target.id
|
|
884
|
+
? (ordered.find(row => row.id !== target.id && !row.paused)?.id ?? null)
|
|
885
|
+
: beforeActiveId)
|
|
886
|
+
: (beforeActiveId ?? (rows.rows.some(row => row.paused) ? target.id : null));
|
|
887
|
+
const activeAccountId = result.json.activeAccountId !== undefined
|
|
888
|
+
? result.json.activeAccountId
|
|
889
|
+
: result.json.activeId !== undefined
|
|
890
|
+
? result.json.activeId
|
|
891
|
+
: inferredActiveId;
|
|
892
|
+
const activeAccountChanged = typeof result.json.activeAccountChanged === "boolean"
|
|
893
|
+
? result.json.activeAccountChanged
|
|
894
|
+
: beforeActiveId !== activeAccountId;
|
|
895
|
+
if (wantsJson) {
|
|
896
|
+
console.log(JSON.stringify({ ok: true, provider: name, id: target.id, paused,
|
|
897
|
+
activeAccountId: activeAccountId ?? null,
|
|
898
|
+
activeAccountChanged }, null, 2));
|
|
899
|
+
} else {
|
|
900
|
+
console.log(`${name}: account ${paused ? "paused" : "resumed"}`);
|
|
901
|
+
if (activeAccountChanged) {
|
|
902
|
+
console.error(`Active account changed to ${String(activeAccountId ?? "none")}.`);
|
|
903
|
+
}
|
|
904
|
+
}
|
|
852
905
|
return 0;
|
|
853
906
|
}
|
|
854
907
|
if (classified.type !== "codex") {
|
|
@@ -859,10 +912,11 @@ export async function cmdPause(args: string[], deps: AccountDeps, paused: boolea
|
|
|
859
912
|
if ("error" in target) return reportCodexAccountTargetError(target);
|
|
860
913
|
const id = target.id;
|
|
861
914
|
|
|
862
|
-
const response = await apiJson(deps, baseUrl, "PUT", "/api/codex-auth/accounts/pause", { id, paused });
|
|
915
|
+
const response = await apiJson(deps, baseUrl, "PUT", "/api/codex-auth/accounts/pause", { id, paused, ...healthGate });
|
|
863
916
|
// Transport sentinel first: status 0 means the proxy never answered, and comparing it to
|
|
864
917
|
// 200 would report an unreachable proxy as a management error.
|
|
865
918
|
if (response.status === 0) return proxyUnreachable(response.transportError);
|
|
919
|
+
if (response.status === 409) { const refused = refusedResume(response.json, id); if (refused !== undefined) return refused; }
|
|
866
920
|
if (response.status !== 200) return apiError(response.json, `failed to ${verb} ${requestedId}`, response.status);
|
|
867
921
|
|
|
868
922
|
if (wantsJson) {
|
|
@@ -27,6 +27,8 @@ function windowProjection(value: unknown): ProviderQuotaWindow {
|
|
|
27
27
|
const label = optionalString(row, "label");
|
|
28
28
|
if (label === undefined) throw new Error("Malformed API-key quota response.");
|
|
29
29
|
const result: ProviderQuotaWindow = { label, percent: finite(row.percent) };
|
|
30
|
+
const displayLabel = optionalString(row, "displayLabel");
|
|
31
|
+
if (displayLabel !== undefined) result.displayLabel = displayLabel;
|
|
30
32
|
if (row.resetAt !== undefined) result.resetAt = finite(row.resetAt);
|
|
31
33
|
if (row.passiveObservedAt !== undefined) result.passiveObservedAt = finite(row.passiveObservedAt);
|
|
32
34
|
if (row.scope !== undefined) {
|
|
@@ -60,6 +62,15 @@ function quotaProjection(value: unknown): ProviderQuota | null {
|
|
|
60
62
|
if (!Array.isArray(row.customWindows)) throw new Error("Malformed API-key quota response.");
|
|
61
63
|
result.customWindows = row.customWindows.map(windowProjection);
|
|
62
64
|
}
|
|
65
|
+
if (row.unknownBudgetWindows !== undefined) {
|
|
66
|
+
if (!Array.isArray(row.unknownBudgetWindows)) throw new Error("Malformed API-key quota response.");
|
|
67
|
+
result.unknownBudgetWindows = row.unknownBudgetWindows.map(value => {
|
|
68
|
+
const item = record(value);
|
|
69
|
+
const label = optionalString(item, "label");
|
|
70
|
+
if (label === undefined) throw new Error("Malformed API-key quota response.");
|
|
71
|
+
return { label, ...(item.resetAt === undefined ? {} : { resetAt: finite(item.resetAt) }) };
|
|
72
|
+
});
|
|
73
|
+
}
|
|
63
74
|
if (row.creditsUsd !== undefined) result.creditsUsd = creditsProjection(row.creditsUsd);
|
|
64
75
|
return result;
|
|
65
76
|
}
|
|
@@ -109,8 +120,17 @@ export function apiKeyQuotaText(row: AccountRow): string {
|
|
|
109
120
|
}
|
|
110
121
|
for (const window of quota.customWindows ?? []) {
|
|
111
122
|
// Labels are upstream text: keep terminal controls out of the human table.
|
|
112
|
-
const label = terminalSafeText(window.label);
|
|
113
|
-
|
|
123
|
+
const label = terminalSafeText(window.displayLabel ?? window.label);
|
|
124
|
+
// Only a probe that supplied its own display text adds the reset clock; every other
|
|
125
|
+
// provider keeps the dev-era text byte for byte.
|
|
126
|
+
const resetAt = window.displayLabel === undefined || window.resetAt === undefined ? undefined : new Date(window.resetAt);
|
|
127
|
+
const reset = resetAt && Number.isFinite(resetAt.getTime()) ? `; resets ${resetAt.toISOString()}` : "";
|
|
128
|
+
parts.push(`${label} ${window.percent}%${window.rejected ? " (rejected)" : ""}${reset}`);
|
|
129
|
+
}
|
|
130
|
+
for (const window of quota.unknownBudgetWindows ?? []) {
|
|
131
|
+
const resetAt = window.resetAt === undefined ? undefined : new Date(window.resetAt);
|
|
132
|
+
const reset = resetAt && Number.isFinite(resetAt.getTime()) ? `; resets ${resetAt.toISOString()}` : "";
|
|
133
|
+
parts.push(`${terminalSafeText(window.label)} unknown${reset}`);
|
|
114
134
|
}
|
|
115
135
|
if (quota.creditsUsd) {
|
|
116
136
|
const c = quota.creditsUsd;
|
package/src/cli/account.ts
CHANGED
|
@@ -57,7 +57,7 @@ const ACCOUNT_USAGE = `Usage:
|
|
|
57
57
|
ocx account preserve-signed-in openai [on|off|status] [--apply-to-bound] [--json]
|
|
58
58
|
ocx account priority <provider> <account-id|alias|main> [<-100..100|first|earlier|normal|later|last|reset>] [--json]
|
|
59
59
|
ocx account pause <provider> <account-id|alias|main> [--json]
|
|
60
|
-
ocx account resume <provider> <account-id|alias|main> [--json]
|
|
60
|
+
ocx account resume <provider> <account-id|alias|main> [--if-healthy] [--json]
|
|
61
61
|
ocx account reset-affinity <anthropic|anthropic2> [--json]
|
|
62
62
|
ocx account pause-exhausted <provider> [--json]
|
|
63
63
|
ocx account strategy <provider> [<quota|round-robin|fill-first|least-loaded|reset-first>] [--json]
|
|
@@ -165,4 +165,14 @@ export const ACCESS_REMOTE_CAPABILITIES: readonly Capability[] = [
|
|
|
165
165
|
json: "envelope",
|
|
166
166
|
details: ["Fixed data-plane WebSocket /v1/live with the existing audio key carrier and session.update, then session.close. It contacts upstream and may incur provider usage; no microphone, audio upload, tool execution or voice-roundtrip claim.","Version1 report distinguishes readiness from confirmed normal close. Socket-open alone is not ready.15s readiness,2s close deadline; stuck/abnormal closure remains unverified/nonzero, with local socket termination.","No raw frames/session IDs/encoded credentials are printed. NativeWebSocket redirect refusal is verified separately from HTTP upload behavior."],
|
|
167
167
|
},
|
|
168
|
+
{
|
|
169
|
+
command: ["link","check"],
|
|
170
|
+
usage: "ocx link check (--link-id <id> | --all) [--no-wait] [--json]",
|
|
171
|
+
summary: "Read each Home-initiated Child's installed version, install kind and update route.",
|
|
172
|
+
routes: [{"method":"POST","path":"/api/link/children/operations"},{"method":"GET","path":"/api/link/children/jobs/{jobId}"}],
|
|
173
|
+
flags: [{"name":"--link-id","value":"string","summary":"Link id to check; repeatable, up to 64."},{"name":"--all","value":"boolean","summary":"Check every link in the Home's store."},{"name":"--no-wait","value":"boolean","summary":"Print the queued job and return without polling it."},{"name":"--json","value":"boolean","summary":"Emit the ocx.link.child-job/1 document as JSON (always JSON)."}],
|
|
174
|
+
mutates: true,
|
|
175
|
+
json: "payload",
|
|
176
|
+
details: ["Requires loopback admin authority on the Home. Starts one observe job; the CLI polls it every 2 s and prints the final ocx.link.child-job/1 document. Exit 0 when every item succeeded, 6 when an item is busy, offline, refused, owner-action or unsupported, 1 on a failure, 4 when the link is unknown or the Home predates Child operations, 5 on a conflict: the link already has an operation running, --all found no Home-initiated link, or the command ran on a Child.","Changes no install on the Child: it runs the gated update --plan, which only computes. An npm Child without a census pair runs it through its ocx shim, so the launcher's ordinary bootstrap (sync-guard bookkeeping, Bun resolution) runs first, as for any pinned sync; the gated script disables the Desktop handoff. Writes the Home's Child observation cache.","One SSH call per Child, up to 60 s, three at a time; a POSIX Child older than 2.97.0 costs one more read-only call for its version. Home-initiated links only: client-initiated and ocx-child links are reported without SSH. One operation per link per running Home."],
|
|
177
|
+
},
|
|
168
178
|
];
|
|
@@ -28,11 +28,11 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [
|
|
|
28
28
|
},
|
|
29
29
|
{
|
|
30
30
|
command: ["message", "mcp"], usage: "ocx message mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home> [--allow-reply-read]",
|
|
31
|
-
summary: "Serve MCP tools for stored Codex metadata, queued text and explicitly enabled stored-turn reply reads.",
|
|
31
|
+
summary: "Serve MCP tools for stored Codex metadata, queued text and explicitly enabled stored-turn reply reads and bounded waits.",
|
|
32
32
|
routes: [], mutates: true, json: "none",
|
|
33
33
|
flags: [{ name: "--codex", value: "string", required: true, summary: "Explicit local Codex CLI executable." },
|
|
34
34
|
{ name: "--codex-home", value: "string", required: true, summary: "Explicit existing Codex home; no creation or login." },
|
|
35
|
-
{ name: "--allow-reply-read", value: "boolean", summary: "Explicitly expose stored final-turn text through codex_read_reply; disabled by default." }],
|
|
35
|
+
{ name: "--allow-reply-read", value: "boolean", summary: "Explicitly expose stored final-turn text through codex_read_reply and codex_wait_reply; disabled by default." }],
|
|
36
36
|
details: ["macOS/Linux only. No proxy/control socket required. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged.",
|
|
37
37
|
"Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. --allow-reply-read exposes bounded same-turn final text, not exclusive reply ownership or goal completion. No daemon start, thread resume, steer, automatic replies or registration."],
|
|
38
38
|
},
|
|
@@ -383,10 +383,10 @@ export const CAPABILITIES: readonly Capability[] = [
|
|
|
383
383
|
command: ["account","resume"],
|
|
384
384
|
summary: "Return a paused account to a Codex, Anthropic, generic OAuth or API-key pool.",
|
|
385
385
|
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"}],
|
|
386
|
-
flags: [{"name":"--json","value":"boolean","summary":"Emit the resume result as JSON."}],
|
|
386
|
+
flags: [{"name":"--if-healthy","value":"boolean","summary":"Resume only after a fresh account-bound health read succeeds; Codex and Anthropic pools."},{"name":"--json","value":"boolean","summary":"Emit the resume result as JSON."}],
|
|
387
387
|
mutates: true,
|
|
388
388
|
json: "envelope",
|
|
389
|
-
usage: "ocx account resume <provider> <account-id|alias|main> [--json]",
|
|
389
|
+
usage: "ocx account resume <provider> <account-id|alias|main> [--if-healthy] [--json]",
|
|
390
390
|
details: [],
|
|
391
391
|
},
|
|
392
392
|
{
|
package/src/cli/claude.ts
CHANGED
|
@@ -377,21 +377,26 @@ export function buildClaudeEnv(
|
|
|
377
377
|
if (config.claudeCode?.alwaysEnableEffort === true) {
|
|
378
378
|
setDefault("CLAUDE_CODE_ALWAYS_ENABLE_EFFORT", "1");
|
|
379
379
|
}
|
|
380
|
-
// Tool-search deferral (#4838). Claude Code
|
|
381
|
-
//
|
|
382
|
-
//
|
|
383
|
-
//
|
|
384
|
-
//
|
|
380
|
+
// Tool-search deferral (#4838, #7963). Claude Code v2.1.304 and later turn tool
|
|
381
|
+
// search ON by default behind an ANTHROPIC_BASE_URL gateway, so MCP tools are
|
|
382
|
+
// deferred and requests carry defer_loading fields and tool_reference blocks.
|
|
383
|
+
// Earlier versions kept it off behind a gateway unless ENABLE_TOOL_SEARCH was
|
|
384
|
+
// true / auto / auto:N (code.claude.com/docs/en/mcp#tool-search-through-a-gateway).
|
|
385
385
|
//
|
|
386
|
-
//
|
|
387
|
-
// route cannot honour
|
|
388
|
-
// wire (deferral is a server-side context optimisation, not a smaller
|
|
389
|
-
// toolsToResponses drops the tool_search server tool and ignores
|
|
390
|
-
// and compatibility.ts lists tool_search/tool_reference/
|
|
391
|
-
// unsupported.
|
|
392
|
-
//
|
|
393
|
-
//
|
|
394
|
-
//
|
|
386
|
+
// The native Anthropic passthrough route forwards those fields. A translated
|
|
387
|
+
// route cannot honour them server-side: deferred tools still carry input_schema
|
|
388
|
+
// on the wire (deferral is a server-side context optimisation, not a smaller
|
|
389
|
+
// request), toolsToResponses drops the tool_search server tool and ignores
|
|
390
|
+
// defer_loading, and compatibility.ts lists tool_search/tool_reference/
|
|
391
|
+
// deferred_tools as unsupported. On a translated Chat route each client
|
|
392
|
+
// ToolSearch load also changes the tool list and the catalog nudge, so the next
|
|
393
|
+
// request re-misses the provider's prompt cache (#7963);
|
|
394
|
+
// claudeCode.appendOnlyToolLoadingModels covers verified Responses destinations
|
|
395
|
+
// and claudeCode.chatToolDispatchModels verified direct Chat routes.
|
|
396
|
+
//
|
|
397
|
+
// We inject only when claudeCode.toolSearch is set, so an unset value leaves the
|
|
398
|
+
// client's own version default in place, and setDefault keeps an operator's own
|
|
399
|
+
// export (ENABLE_TOOL_SEARCH=false restores upfront loading).
|
|
395
400
|
setDefault("ENABLE_TOOL_SEARCH", claudeToolSearchEnv(config.claudeCode?.toolSearch));
|
|
396
401
|
const maxCtx = config.claudeCode?.maxContextTokens;
|
|
397
402
|
if (typeof maxCtx === "number" && Number.isFinite(maxCtx) && maxCtx > 0) {
|
|
@@ -142,6 +142,26 @@ function pathSegments(path: string): string[] {
|
|
|
142
142
|
return segments;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
/**
|
|
146
|
+
* #8319: `config set` writes the file, but a running proxy keeps checking pairing and CORS origins
|
|
147
|
+
* against the config it is running with. `hub` is live topology and is applied only at start, including the
|
|
148
|
+
* management listener (`hub.managementIngress`)
|
|
149
|
+
* (`LIVE_TOPOLOGY_KEYS`); `corsAllowOrigins` reaches the running config only when some later live
|
|
150
|
+
* save adopts the file. Saying only "Set <path>." left an operator retrying a refused
|
|
151
|
+
* `ocx hub invite` against the old list. Limited to these keys, so the note never claims a restart
|
|
152
|
+
* that is not needed.
|
|
153
|
+
*/
|
|
154
|
+
export function startupOnlyConfigNotes(path: string): string[] {
|
|
155
|
+
const segments = pathSegments(path);
|
|
156
|
+
if (segments[0] === "corsAllowOrigins") {
|
|
157
|
+
return ["A running OpenCodex may keep using its previous corsAllowOrigins until it restarts; restart it to apply the new value now."];
|
|
158
|
+
}
|
|
159
|
+
if (segments[0] === "hub" && (segments.length === 1 || segments[1] === "managementPublicOrigin" || segments[1] === "managementIngress")) {
|
|
160
|
+
return [`A running OpenCodex applies ${segments.join(".")} only when it starts; restart it to use the new value.`];
|
|
161
|
+
}
|
|
162
|
+
return [];
|
|
163
|
+
}
|
|
164
|
+
|
|
145
165
|
function getPath(root: unknown, path: string): unknown {
|
|
146
166
|
let current = root;
|
|
147
167
|
for (const segment of pathSegments(path)) {
|
|
@@ -298,7 +318,10 @@ export async function handleConfigCommand(argv: string[]): Promise<number> {
|
|
|
298
318
|
: `config is ${outcome.reason}`);
|
|
299
319
|
}
|
|
300
320
|
printData({ ok: true, path, value: redact(savedValue, pathSegments(path).at(-1)) }, wantsJson,
|
|
301
|
-
[
|
|
321
|
+
[
|
|
322
|
+
`${action === "unset" ? "Unset" : "Set"} ${path}.`,
|
|
323
|
+
...(outcome.status === "committed" ? startupOnlyConfigNotes(path) : []),
|
|
324
|
+
]);
|
|
302
325
|
return;
|
|
303
326
|
}
|
|
304
327
|
if (action === "validate") {
|
package/src/cli/connect.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
} from "../client/connect";
|
|
17
17
|
import { inspectClientRotationRecoveryGate, readClientConnectionState } from "../client/state";
|
|
18
18
|
import { readClientLinkState } from "../client/link-state";
|
|
19
|
+
import { probeLinkTunnelStatus, type LinkTunnelStatus } from "../client/link-tunnel-status";
|
|
19
20
|
import { teardownClientLink } from "../client/link-teardown";
|
|
20
21
|
import { reapOrphanTunnel } from "../client/link-tunnel";
|
|
21
22
|
import { readServiceApiTokenState } from "../lib/service-secrets";
|
|
@@ -55,6 +56,8 @@ export interface ClientCommandDeps extends RuntimeApiDeps {
|
|
|
55
56
|
knownHostsFile?: string;
|
|
56
57
|
timeoutMs?: number;
|
|
57
58
|
};
|
|
59
|
+
/** Injected in tests; defaults to asking the running Child's /readyz. */
|
|
60
|
+
probeLinkTunnel?: () => Promise<LinkTunnelStatus>;
|
|
58
61
|
}
|
|
59
62
|
|
|
60
63
|
export interface ClientCatalogProbeDeps extends CatalogCompatibilityDeps {
|
|
@@ -119,6 +122,12 @@ export type ClientConnectionStatus = {
|
|
|
119
122
|
readiness?: ClientCatalogReadiness["kind"];
|
|
120
123
|
/** Present whenever readiness is not `ready`; names the fault and the way out. */
|
|
121
124
|
readinessReason?: string;
|
|
125
|
+
/**
|
|
126
|
+
* A Remote Link Child's tunnel as its running runtime sees it (#8470). `state: "connected"` is
|
|
127
|
+
* the durable link record; this says whether a request can cross it now. Additive, and only on
|
|
128
|
+
* `ocx connect status` for `transport: "link"`.
|
|
129
|
+
*/
|
|
130
|
+
linkTunnel?: LinkTunnelStatus;
|
|
122
131
|
};
|
|
123
132
|
|
|
124
133
|
function readInstalledCatalogBody(): string | null {
|
|
@@ -342,7 +351,26 @@ export function connectCompletionReport(
|
|
|
342
351
|
};
|
|
343
352
|
}
|
|
344
353
|
|
|
345
|
-
|
|
354
|
+
/**
|
|
355
|
+
* Adds the tunnel verdict (#8470) only for a connected Remote Link Child, the one case with a
|
|
356
|
+
* runtime verdict to read; a hub client or a disconnected machine is returned untouched, unprobed.
|
|
357
|
+
*/
|
|
358
|
+
export async function withLinkTunnelStatus(
|
|
359
|
+
status: ClientConnectionStatus,
|
|
360
|
+
probe: () => Promise<LinkTunnelStatus>,
|
|
361
|
+
): Promise<ClientConnectionStatus> {
|
|
362
|
+
if (status.state !== "connected" || status.transport !== "link") return status;
|
|
363
|
+
// An optional diagnostic: a probe that fails must not take the durable status down with it.
|
|
364
|
+
let linkTunnel: LinkTunnelStatus;
|
|
365
|
+
try { linkTunnel = await probe(); } catch { linkTunnel = { state: "unknown", reason: "runtime_unreadable" }; }
|
|
366
|
+
return { ...status, linkTunnel };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function linkTunnelLine(tunnel: LinkTunnelStatus): string {
|
|
370
|
+
return tunnel.state === "up" ? "Link tunnel: up" : `Link tunnel: ${tunnel.state} (${terminalSafeText(tunnel.reason)})`;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
export function clientConnectionStatusLines(status: ClientConnectionStatus): string[] {
|
|
346
374
|
if (status.state !== "connected") {
|
|
347
375
|
return [`Connection: ${status.state}${status.reason ? ` (${status.reason})` : ""}`];
|
|
348
376
|
}
|
|
@@ -351,6 +379,8 @@ function statusLines(status: ClientConnectionStatus): string[] {
|
|
|
351
379
|
// Second line on purpose. The whole of #4207 is that a reader stopped at "connected" and
|
|
352
380
|
// believed the client was usable, so the local verdict has to arrive before the hub detail.
|
|
353
381
|
readinessLine(status),
|
|
382
|
+
// #8470: the same holds for a link Child whose tunnel is down; say so before the detail.
|
|
383
|
+
...(status.linkTunnel ? [linkTunnelLine(status.linkTunnel)] : []),
|
|
354
384
|
`Transport: ${status.transport ?? "hub"}`,
|
|
355
385
|
...(status.link ? [`Link: ${status.link.linkId} via tunnel port ${status.link.tunnelPort}`] : []),
|
|
356
386
|
`Hub: ${status.serverUrl}`,
|
|
@@ -515,8 +545,11 @@ export async function handleConnectCommand(argv: string[], deps: ClientCommandDe
|
|
|
515
545
|
const args = argv.slice(1);
|
|
516
546
|
const wantsJson = takeFlag(args, "--json");
|
|
517
547
|
rejectArgs(args, CONNECT_USAGE, { redactValues: true });
|
|
518
|
-
const status =
|
|
519
|
-
|
|
548
|
+
const status = await withLinkTunnelStatus(
|
|
549
|
+
collectClientConnectionStatus(Date.now(), deps.lifecycleLockDeps, deps.catalogProbeDeps ?? {}),
|
|
550
|
+
deps.probeLinkTunnel ?? probeLinkTunnelStatus,
|
|
551
|
+
);
|
|
552
|
+
printData(status, wantsJson, clientConnectionStatusLines(status));
|
|
520
553
|
return;
|
|
521
554
|
}
|
|
522
555
|
if (argv[0] === "revoke") {
|
|
@@ -31,7 +31,7 @@ import {
|
|
|
31
31
|
|
|
32
32
|
export type GuiPairRequestResult =
|
|
33
33
|
| { kind: "created"; grant: string; browserOrigin: string; serverOrigin: string; expiresAt: number }
|
|
34
|
-
| { kind: "unavailable"; reason: "unattested-target" | "runtime-mismatch" | "attestation" | "capability" | "transport" | "rejected" | "local-intent" };
|
|
34
|
+
| { kind: "unavailable"; reason: "unattested-target" | "runtime-mismatch" | "attestation" | "capability" | "transport" | "rejected" | "local-intent" | "origin-refused" | "rate-limited" };
|
|
35
35
|
|
|
36
36
|
export interface GuiPairClientDeps {
|
|
37
37
|
fetchImpl?: typeof fetch;
|
|
@@ -57,6 +57,27 @@ function sameRuntime(left: RuntimePortState, right: RuntimePortState | null): bo
|
|
|
57
57
|
&& timingSafeEqual(leftSecret, rightSecret);
|
|
58
58
|
}
|
|
59
59
|
|
|
60
|
+
/**
|
|
61
|
+
* Which refusal the grant route sent, as one fixed word; the body itself never surfaces.
|
|
62
|
+
*
|
|
63
|
+
* Only the route's plain 403 "GUI pairing grant refused" (no `code`) means its loaded config did not
|
|
64
|
+
* admit this origin, the one case an allow-list edit or a restart can cure (#8319). Its 429 is the
|
|
65
|
+
* per-minute grant limit. A coded refusal, a capability refusal and anything else stay `rejected`,
|
|
66
|
+
* so the caller does not send an operator to edit a correct allow-list (#8495 review).
|
|
67
|
+
*
|
|
68
|
+
* This is a heuristic: the route answers the same uncoded 403 for any unexpected failure inside
|
|
69
|
+
* grant creation, not only for a refused origin. Those are rare and the advice (check the two origin
|
|
70
|
+
* settings, restart) is harmless there; an explicit server code would make it exact.
|
|
71
|
+
*/
|
|
72
|
+
async function refusalReason(response: Response): Promise<"origin-refused" | "rate-limited" | "rejected"> {
|
|
73
|
+
if (response.status === 429) return "rate-limited";
|
|
74
|
+
if (response.status !== 403) return "rejected";
|
|
75
|
+
const body: unknown = await response.json().catch(() => null);
|
|
76
|
+
if (!body || typeof body !== "object" || Array.isArray(body)) return "rejected";
|
|
77
|
+
const record = body as Record<string, unknown>;
|
|
78
|
+
return record.error === "GUI pairing grant refused" && record.code === undefined ? "origin-refused" : "rejected";
|
|
79
|
+
}
|
|
80
|
+
|
|
60
81
|
function parseCreatedResult(value: unknown, browserOrigin: string): GuiPairRequestResult | null {
|
|
61
82
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
62
83
|
const record = value as Record<string, unknown>;
|
|
@@ -158,7 +179,7 @@ export async function requestBoundGuiPairingGrant(
|
|
|
158
179
|
},
|
|
159
180
|
signal: AbortSignal.timeout(timeoutMs),
|
|
160
181
|
});
|
|
161
|
-
if (!response.ok) return { kind: "unavailable", reason:
|
|
182
|
+
if (!response.ok) return { kind: "unavailable", reason: await refusalReason(response) };
|
|
162
183
|
const result = parseCreatedResult(await response.json().catch(() => null), browserOrigin);
|
|
163
184
|
return result ?? { kind: "unavailable", reason: "rejected" };
|
|
164
185
|
} catch {
|
package/src/cli/help.ts
CHANGED
|
@@ -67,7 +67,7 @@ Usage:
|
|
|
67
67
|
Open the dashboard or create a single-use remote pairing grant
|
|
68
68
|
ocx hub invite [--json] Print a ready-to-run \`ocx connect\` line for one more machine
|
|
69
69
|
(hub only; see \`ocx help hub\` for the one-port topology)
|
|
70
|
-
ocx link <sub> Machine links over SSH (port|issue|revoke|status)
|
|
70
|
+
ocx link <sub> Machine links over SSH (port|issue|revoke|status|check)
|
|
71
71
|
ocx update [--tag <tag>] Update opencodex (keeps preview installs on @preview)
|
|
72
72
|
ocx restart Stop and restart the proxy
|
|
73
73
|
ocx v2 <sub> multi_agent_v2 surface (status|on|off|mode|keep-native-v1|threads|mode-hint)
|
package/src/cli/hub.ts
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
type GuiPairRequestResult,
|
|
8
8
|
} from "./gui-pair-client";
|
|
9
9
|
import type { RuntimeApiDeps } from "./runtime-api";
|
|
10
|
-
import { HUB_DISABLE_USAGE, runHubDisable, type HubDisableDeps } from "./hub-disable";
|
|
10
|
+
import { HUB_DISABLE_USAGE, hubDisableRestartHint, runHubDisable, type HubDisableDeps } from "./hub-disable";
|
|
11
11
|
|
|
12
12
|
export const HUB_USAGE =
|
|
13
13
|
"ocx hub invite [--json] [--data-url <origin>] [--management-url <origin>] [--clients codex,claude]\n " + HUB_DISABLE_USAGE;
|
|
@@ -32,6 +32,8 @@ export interface HubCommandDeps extends RuntimeApiDeps, HubDisableDeps {
|
|
|
32
32
|
browserOrigin: string,
|
|
33
33
|
deps?: GuiPairClientDeps,
|
|
34
34
|
) => Promise<GuiPairRequestResult>;
|
|
35
|
+
/** Supervisor-aware "Restart to apply: …" line; injected so tests do not probe the machine. */
|
|
36
|
+
restartHint?: () => string;
|
|
35
37
|
}
|
|
36
38
|
|
|
37
39
|
export interface HubInviteOptions {
|
|
@@ -333,6 +335,21 @@ async function runInvite(args: string[], deps: HubCommandDeps): Promise<number>
|
|
|
333
335
|
});
|
|
334
336
|
if (result.kind !== "created") {
|
|
335
337
|
console.error(`Minting a pairing code failed (${result.reason}).`);
|
|
338
|
+
if (result.reason === "origin-refused") {
|
|
339
|
+
// #8319: the CLI picks the origin from the config on disk, but the running hub checks it
|
|
340
|
+
// against the config it is running with, so an allow-list edited since then can be refused
|
|
341
|
+
// until a restart. The reason code alone did not say which origin, setting, or step.
|
|
342
|
+
console.error(
|
|
343
|
+
`The running hub refused to mint a code bound to browser origin ${browserOrigin}. It admits only `
|
|
344
|
+
+ "hub.managementPublicOrigin and the corsAllowOrigins entries it is running with, which can predate "
|
|
345
|
+
+ "a recent 'ocx config set'. If you changed either, restart the hub and invite again.",
|
|
346
|
+
);
|
|
347
|
+
console.error((deps.restartHint ?? hubDisableRestartHint)());
|
|
348
|
+
} else if (result.reason === "rate-limited") {
|
|
349
|
+
// The 429 covers both the per-minute grant limit and the cap on unused codes, which only
|
|
350
|
+
// clears as earlier codes are used or expire (five minutes), so the advice fits both.
|
|
351
|
+
console.error("The hub is limiting new pairing codes (a per-minute limit and a cap on unused codes). Wait for earlier codes to be used or expire, then invite again.");
|
|
352
|
+
}
|
|
336
353
|
return 1;
|
|
337
354
|
}
|
|
338
355
|
const payload: HubInvitePayload = {
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import type { ChildItemState, ChildJob, ChildJobItem } from "../link/child-ops-engine";
|
|
2
|
+
import { CliUsageError, RuntimeApiError, rejectArgs, takeFlag, takeJsonFlag, takeOption } from "./runtime-api";
|
|
3
|
+
import type { LinkCliDeps } from "./link";
|
|
4
|
+
|
|
5
|
+
type LinkRequest = <T>(path: string, init: RequestInit, deps: LinkCliDeps) => Promise<T>;
|
|
6
|
+
|
|
7
|
+
export interface LinkCheckDeps extends LinkCliDeps {
|
|
8
|
+
/** Test seams for the job poll. */
|
|
9
|
+
sleep?: (ms: number) => Promise<void>;
|
|
10
|
+
now?: () => number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export const LINK_CHECK_POLL_MS = 2_000;
|
|
14
|
+
export const OLD_HOME_MESSAGE = "This Home does not support Child operations; update the Home.";
|
|
15
|
+
export const NO_ELIGIBLE_LINKS_MESSAGE = "This Home has no Home-initiated links to operate on.";
|
|
16
|
+
export const RUNTIME_ROLE_CLIENT_MESSAGE = "This machine is a Child; run Child operations on its Home.";
|
|
17
|
+
const CONFLICT_MESSAGES: Readonly<Record<string, string>> = {
|
|
18
|
+
no_eligible_links: NO_ELIGIBLE_LINKS_MESSAGE,
|
|
19
|
+
runtime_role_client: RUNTIME_ROLE_CLIENT_MESSAGE,
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const LINK_ID = /^lnk_[0-9a-f]{16}$/;
|
|
23
|
+
const JOB_ID = /^ljob_[0-9a-f]{16}$/;
|
|
24
|
+
const SUCCESS: ReadonlySet<string> = new Set<ChildItemState>(["succeeded", "up-to-date"]);
|
|
25
|
+
const PARTIAL: ReadonlySet<string> = new Set<ChildItemState>(["busy", "offline", "refused", "owner-action", "unsupported"]);
|
|
26
|
+
|
|
27
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Read an `ocx.link.child-job/1` document. Tolerant from its first release (G1, audit H5): known keys are type-checked,
|
|
31
|
+
* unknown keys at job, item, `sync` and `restart` level are dropped, and an unknown string in an enum field is kept
|
|
32
|
+
* for display, so this CLI keeps polling a later Home whose items carry more. A known key of the wrong type throws.
|
|
33
|
+
*/
|
|
34
|
+
export function validateChildJob(value: unknown): ChildJob {
|
|
35
|
+
const fail = (field: string): never => { throw new Error(`invalid link API response: job ${field}`); };
|
|
36
|
+
const text = (target: unknown, field: string): string => typeof target === "string" && target.length <= 256 ? target : fail(field);
|
|
37
|
+
const nullableText = (target: unknown, field: string): string | null => target === null ? null : text(target, field);
|
|
38
|
+
if (!isRecord(value)) return fail("object");
|
|
39
|
+
if (value.schema !== "ocx.link.child-job/1") fail("schema");
|
|
40
|
+
if (!Array.isArray(value.items)) fail("items");
|
|
41
|
+
const jobId = text(value.jobId, "jobId");
|
|
42
|
+
if (!JOB_ID.test(jobId)) fail("jobId");
|
|
43
|
+
const items = (value.items as unknown[]).map((raw, index): ChildJobItem => {
|
|
44
|
+
if (!isRecord(raw)) return fail(`item ${index}`);
|
|
45
|
+
const item: ChildJobItem & Record<string, unknown> = {
|
|
46
|
+
linkId: text(raw.linkId, `item ${index} linkId`), alias: text(raw.alias, `item ${index} alias`),
|
|
47
|
+
state: text(raw.state, `item ${index} state`) as ChildItemState, reason: nullableText(raw.reason, `item ${index} reason`),
|
|
48
|
+
startedAt: nullableText(raw.startedAt, `item ${index} startedAt`), finishedAt: nullableText(raw.finishedAt, `item ${index} finishedAt`),
|
|
49
|
+
};
|
|
50
|
+
if (raw.hint !== undefined) item.hint = text(raw.hint, `item ${index} hint`);
|
|
51
|
+
if (raw.fromVersion !== undefined) item.fromVersion = text(raw.fromVersion, `item ${index} fromVersion`);
|
|
52
|
+
if (raw.toVersion !== undefined) item.toVersion = text(raw.toVersion, `item ${index} toVersion`);
|
|
53
|
+
for (const key of ["sync", "restart"] as const) {
|
|
54
|
+
if (raw[key] === undefined || raw[key] === null) continue;
|
|
55
|
+
const nested = raw[key];
|
|
56
|
+
if (!isRecord(nested)) return fail(`item ${index} ${key}`);
|
|
57
|
+
const field = key === "sync" ? "state" : "outcome";
|
|
58
|
+
item[key] = { [field]: text(nested[field], `item ${index} ${key}.${field}`),
|
|
59
|
+
...(nested.reason === undefined ? {} : { reason: nullableText(nested.reason, `item ${index} ${key}.reason`) }) };
|
|
60
|
+
}
|
|
61
|
+
return item;
|
|
62
|
+
});
|
|
63
|
+
return {
|
|
64
|
+
schema: "ocx.link.child-job/1", jobId, op: text(value.op, "op") as ChildJob["op"], trigger: text(value.trigger, "trigger") as ChildJob["trigger"],
|
|
65
|
+
restart: text(value.restart, "restart") as ChildJob["restart"], state: text(value.state, "state") as ChildJob["state"],
|
|
66
|
+
createdAt: text(value.createdAt, "createdAt"), finishedAt: nullableText(value.finishedAt, "finishedAt"), items,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** D15: 0 every item succeeded or up-to-date; 6 any item needs the operator; 1 any failure or an unknown state. */
|
|
71
|
+
export function linkCheckExitCode(job: ChildJob): number {
|
|
72
|
+
let code = 0;
|
|
73
|
+
for (const item of job.items) {
|
|
74
|
+
if (SUCCESS.has(item.state)) continue;
|
|
75
|
+
if (PARTIAL.has(item.state)) code = Math.max(code, 6);
|
|
76
|
+
else return 1;
|
|
77
|
+
}
|
|
78
|
+
return code;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function readJob(response: unknown): ChildJob {
|
|
82
|
+
if (!isRecord(response) || Object.keys(response).length !== 1 || !("job" in response)) throw new Error("invalid link API response: job envelope");
|
|
83
|
+
return validateChildJob(response.job);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** `ocx link check (--link-id <id> | --all) [--no-wait] [--json]`: run the observe operation and return the exit code. */
|
|
87
|
+
export async function runLinkCheck(args: string[], deps: LinkCheckDeps, request: LinkRequest, usage: string): Promise<number> {
|
|
88
|
+
takeJsonFlag(args);
|
|
89
|
+
const all = takeFlag(args, "--all");
|
|
90
|
+
const noWait = takeFlag(args, "--no-wait");
|
|
91
|
+
const linkIds: string[] = [];
|
|
92
|
+
for (let id = takeOption(args, "--link-id"); id !== undefined; id = takeOption(args, "--link-id")) {
|
|
93
|
+
if (!LINK_ID.test(id)) throw new CliUsageError("check requires valid --link-id values", usage);
|
|
94
|
+
if (!linkIds.includes(id)) linkIds.push(id);
|
|
95
|
+
}
|
|
96
|
+
rejectArgs(args, usage);
|
|
97
|
+
if (all === (linkIds.length > 0)) throw new CliUsageError("check requires --link-id <id> or --all, not both", usage);
|
|
98
|
+
if (linkIds.length > 64) throw new CliUsageError("check accepts at most 64 --link-id values", usage);
|
|
99
|
+
let job: ChildJob;
|
|
100
|
+
try {
|
|
101
|
+
job = readJob(await request<unknown>("/api/link/children/operations", {
|
|
102
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ op: "observe", linkIds: all ? "all" : linkIds }),
|
|
103
|
+
}, deps));
|
|
104
|
+
} catch (error) {
|
|
105
|
+
// A new Home answers link_not_found for a mistyped id; an older Home has no such route at all.
|
|
106
|
+
if (error instanceof RuntimeApiError && error.status === 404) {
|
|
107
|
+
const body = error.body as { error?: { code?: unknown } } | null;
|
|
108
|
+
if (body?.error?.code !== "link_not_found") throw new RuntimeApiError(OLD_HOME_MESSAGE, 404, error.body);
|
|
109
|
+
}
|
|
110
|
+
// Every 409 still exits 5; the conflicts that are not "another operation holds the link" say what happened.
|
|
111
|
+
if (error instanceof RuntimeApiError && error.status === 409) {
|
|
112
|
+
const code = (error.body as { error?: { code?: unknown } } | null)?.error?.code;
|
|
113
|
+
const message = typeof code === "string" && Object.hasOwn(CONFLICT_MESSAGES, code) ? CONFLICT_MESSAGES[code] : undefined;
|
|
114
|
+
if (message) throw new RuntimeApiError(message, 409, error.body);
|
|
115
|
+
}
|
|
116
|
+
throw error;
|
|
117
|
+
}
|
|
118
|
+
if (noWait) {
|
|
119
|
+
console.log(JSON.stringify(job));
|
|
120
|
+
return job.state === "done" ? linkCheckExitCode(job) : 0;
|
|
121
|
+
}
|
|
122
|
+
const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));
|
|
123
|
+
const now = deps.now ?? Date.now;
|
|
124
|
+
const deadline = now() + Math.ceil(job.items.length / 3) * 120_000 + 30_000;
|
|
125
|
+
while (job.state !== "done") {
|
|
126
|
+
if (now() >= deadline) {
|
|
127
|
+
console.log(JSON.stringify(job));
|
|
128
|
+
console.error(`Error: job_still_running: ${job.jobId} has not finished; read it again with GET /api/link/children/jobs/${job.jobId}.`);
|
|
129
|
+
return 1;
|
|
130
|
+
}
|
|
131
|
+
await sleep(LINK_CHECK_POLL_MS);
|
|
132
|
+
job = readJob(await request<unknown>(`/api/link/children/jobs/${encodeURIComponent(job.jobId)}`, {}, deps));
|
|
133
|
+
}
|
|
134
|
+
console.log(JSON.stringify(job));
|
|
135
|
+
return linkCheckExitCode(job);
|
|
136
|
+
}
|