@bitkyc08/opencodex 2.100.0 → 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-DU-0Vdkr.js +1 -0
- 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-CcxZBnxv.js → segment-thumb-features-e9A_FogJ.js} +1 -1
- package/gui/dist/classic/assets/{App-aYgIQMxI.js → App-BrIlUiLc.js} +18 -18
- package/gui/dist/classic/assets/{Tray-D8jfUXpQ.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/anthropic-image-normalize.ts +1 -1
- package/src/adapters/client-fingerprint.ts +6 -4
- 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/mistral-image-limit.ts +28 -15
- package/src/adapters/openai-chat/tool-schema.ts +9 -0
- package/src/adapters/openai-chat-images.ts +100 -0
- package/src/adapters/openai-chat.ts +6 -9
- 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 +227 -135
- package/src/lib/catalog-etag.ts +10 -0
- package/src/lib/client-error-body.ts +15 -0
- package/src/lib/config-ownership.ts +9 -2
- 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/anthropic-model-quota.ts +12 -0
- package/src/oauth/anthropic-routing.ts +11 -4
- package/src/oauth/index.ts +1 -0
- package/src/oauth/kiro-iam-identity-center.ts +4 -1
- 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-identity.ts +9 -3
- package/src/providers/claude-cli-usage-state.ts +11 -6
- package/src/providers/claude-cli-usage.ts +27 -8
- 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-family-headers.ts +8 -1
- package/src/providers/quota/anthropic-usage-windows.ts +66 -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 +32 -0
- package/src/providers/quota.ts +22 -22
- package/src/providers/reasoning-metadata.ts +1051 -12
- package/src/providers/registry/entries-extended.ts +3 -1
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/types.ts +6 -0
- 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/responses/retained-compaction.ts +31 -5
- 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 +27 -4
- 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 +44 -4
- package/gui/dist/assets/App-CitvEefy.js +0 -59
- package/gui/dist/assets/Tray-CeKVWQyB.js +0 -1
- package/gui/dist/assets/brand-mark-M92UnxX2.js +0 -1
- package/gui/dist/assets/index-BP47do6-.js +0 -94
- package/gui/dist/assets/index-DmDooSAG.css +0 -2
- package/gui/dist/classic/assets/index-CfGqHooN.js +0 -94
- package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +0 -1
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { ChildOp, ChildOperationSummary } from "../link/child-observations";
|
|
2
|
+
import type { InstallKind, UpdateRoute } from "../link/child-update-contract";
|
|
3
|
+
import type { LinkChildOpsStatus } from "../link/status-projection";
|
|
4
|
+
|
|
5
|
+
/** What the Child reports about its Codex app-servers (wp8); known fields only, each optional. */
|
|
6
|
+
export interface LinkChildCodexView {
|
|
7
|
+
appServers?: "fresh" | "stale" | "not_running" | "unknown"; staleCount?: number; catalogMatchesHome?: boolean | null;
|
|
8
|
+
catalogSyncedAt?: number | null; reportedAt?: number | null;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A row's `child` block as this CLI reads it. Tolerant (G1): a later Home may add keys or enum values, so unknown keys
|
|
13
|
+
* are dropped and an unknown enum value reads "unknown"; a known key with the wrong type is still rejected.
|
|
14
|
+
*/
|
|
15
|
+
export type LinkChildOpsView = Omit<LinkChildOpsStatus, "update" | "codex" | "activeJob" | "lastOperation"> & {
|
|
16
|
+
update: { route: UpdateRoute | "unknown" | null; reason: string | null; observedAt: string | null };
|
|
17
|
+
codex: LinkChildCodexView | null;
|
|
18
|
+
activeJob: { jobId: string; op: ChildOp | string; state: "queued" | "running" | "unknown" } | null;
|
|
19
|
+
lastOperation: (Omit<ChildOperationSummary, "op"> & { op: ChildOp | string }) | null;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const INSTALL_KINDS: ReadonlySet<string> = new Set<InstallKind>(["npm", "pnpm", "bun", "source", "mise", "desktop-app", "goat", "standalone", "ocx-child", "unknown"]);
|
|
23
|
+
const ROUTES: ReadonlySet<string> = new Set<UpdateRoute>(["orchestrated", "desktop-request", "owner-action", "replant", "none"]);
|
|
24
|
+
const SKEWS: ReadonlySet<string> = new Set(["same", "behind", "ahead", "unknown"]);
|
|
25
|
+
const CATALOG_STATES: ReadonlySet<string> = new Set(["current", "behind", "unknown"]);
|
|
26
|
+
const APP_SERVER_STATES: ReadonlySet<string> = new Set(["fresh", "stale", "not_running", "unknown"]);
|
|
27
|
+
|
|
28
|
+
const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
29
|
+
|
|
30
|
+
export function validateChildOps(value: unknown, index: number): LinkChildOpsView {
|
|
31
|
+
const fail = (field: string): never => { throw new Error(`invalid link API response: link ${index} child ${field}`); };
|
|
32
|
+
const record = (target: unknown, field: string): Record<string, unknown> => isRecord(target) ? target : fail(field);
|
|
33
|
+
const text = (target: unknown, field: string): string => typeof target === "string" && target.length <= 256 ? target : fail(field);
|
|
34
|
+
const nullableText = (target: unknown, field: string): string | null => target === null ? null : text(target, field);
|
|
35
|
+
const count = (target: unknown, field: string): number => typeof target === "number" && Number.isFinite(target) && target >= 0 ? target : fail(field);
|
|
36
|
+
const nullableCount = (target: unknown, field: string): number | null => target === null ? null : count(target, field);
|
|
37
|
+
const member = <T extends string>(set: ReadonlySet<string>, target: unknown, field: string): T | "unknown" =>
|
|
38
|
+
set.has(text(target, field)) ? target as T : "unknown";
|
|
39
|
+
const child = record(value, "");
|
|
40
|
+
const update = record(child.update, "update");
|
|
41
|
+
const catalog = record(child.catalog, "catalog");
|
|
42
|
+
const activity = record(child.activity, "activity");
|
|
43
|
+
if (typeof activity.idle !== "boolean") fail("activity.idle");
|
|
44
|
+
const installKind = child.installKind === null ? null : member<InstallKind>(INSTALL_KINDS, child.installKind, "installKind");
|
|
45
|
+
return {
|
|
46
|
+
homeVersion: text(child.homeVersion, "homeVersion"),
|
|
47
|
+
runningVersion: nullableText(child.runningVersion, "runningVersion"),
|
|
48
|
+
installedVersion: nullableText(child.installedVersion, "installedVersion"),
|
|
49
|
+
installKind: installKind as InstallKind | null,
|
|
50
|
+
versionSkew: member<LinkChildOpsStatus["versionSkew"]>(SKEWS, child.versionSkew, "versionSkew"),
|
|
51
|
+
update: {
|
|
52
|
+
route: update.route === null ? null : member<UpdateRoute>(ROUTES, update.route, "update.route"),
|
|
53
|
+
reason: nullableText(update.reason, "update.reason"),
|
|
54
|
+
observedAt: nullableText(update.observedAt, "update.observedAt"),
|
|
55
|
+
},
|
|
56
|
+
catalog: {
|
|
57
|
+
state: member<LinkChildOpsStatus["catalog"]["state"]>(CATALOG_STATES, catalog.state, "catalog.state"),
|
|
58
|
+
pulledAt: nullableCount(catalog.pulledAt, "catalog.pulledAt"),
|
|
59
|
+
homeChangedAt: nullableCount(catalog.homeChangedAt, "catalog.homeChangedAt"),
|
|
60
|
+
},
|
|
61
|
+
codex: child.codex === null ? null : validateCodex(record(child.codex, "codex"), fail, member, nullableCount, count),
|
|
62
|
+
activity: { idle: activity.idle as boolean, inFlight: count(activity.inFlight, "activity.inFlight"), lastDataEndAt: nullableCount(activity.lastDataEndAt, "activity.lastDataEndAt") },
|
|
63
|
+
activeJob: child.activeJob === null ? null : (() => {
|
|
64
|
+
const job = record(child.activeJob, "activeJob");
|
|
65
|
+
const state = text(job.state, "activeJob.state");
|
|
66
|
+
return { jobId: text(job.jobId, "activeJob.jobId"), op: text(job.op, "activeJob.op"), state: state === "queued" || state === "running" ? state : "unknown" as const };
|
|
67
|
+
})(),
|
|
68
|
+
lastOperation: child.lastOperation === null ? null : (() => {
|
|
69
|
+
const last = record(child.lastOperation, "lastOperation");
|
|
70
|
+
return {
|
|
71
|
+
op: text(last.op, "lastOperation.op"), jobId: text(last.jobId, "lastOperation.jobId"), state: text(last.state, "lastOperation.state"),
|
|
72
|
+
reason: nullableText(last.reason, "lastOperation.reason"),
|
|
73
|
+
...(last.fromVersion === undefined ? {} : { fromVersion: text(last.fromVersion, "lastOperation.fromVersion") }),
|
|
74
|
+
...(last.toVersion === undefined ? {} : { toVersion: text(last.toVersion, "lastOperation.toVersion") }),
|
|
75
|
+
finishedAt: text(last.finishedAt, "lastOperation.finishedAt"),
|
|
76
|
+
};
|
|
77
|
+
})(),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function validateCodex(codex: Record<string, unknown>, fail: (field: string) => never,
|
|
82
|
+
member: <T extends string>(set: ReadonlySet<string>, target: unknown, field: string) => T | "unknown",
|
|
83
|
+
nullableCount: (target: unknown, field: string) => number | null, count: (target: unknown, field: string) => number): LinkChildCodexView {
|
|
84
|
+
const view: LinkChildCodexView = {};
|
|
85
|
+
if (codex.appServers !== undefined) view.appServers = member<NonNullable<LinkChildCodexView["appServers"]>>(APP_SERVER_STATES, codex.appServers, "codex.appServers");
|
|
86
|
+
if (codex.staleCount !== undefined) view.staleCount = count(codex.staleCount, "codex.staleCount");
|
|
87
|
+
if (codex.catalogMatchesHome !== undefined) {
|
|
88
|
+
if (codex.catalogMatchesHome !== null && typeof codex.catalogMatchesHome !== "boolean") fail("codex.catalogMatchesHome");
|
|
89
|
+
view.catalogMatchesHome = codex.catalogMatchesHome as boolean | null;
|
|
90
|
+
}
|
|
91
|
+
if (codex.catalogSyncedAt !== undefined) view.catalogSyncedAt = nullableCount(codex.catalogSyncedAt, "codex.catalogSyncedAt");
|
|
92
|
+
if (codex.reportedAt !== undefined) view.reportedAt = nullableCount(codex.reportedAt, "codex.reportedAt");
|
|
93
|
+
return view;
|
|
94
|
+
}
|
package/src/cli/link.ts
CHANGED
|
@@ -10,6 +10,8 @@ import { CODEX_SETTINGS_DIGEST_PATTERN } from "../link/codex-settings";
|
|
|
10
10
|
import type { LinkLocalPeer, LinkPeerStatus } from "../link/compatibility";
|
|
11
11
|
import { runLinkEnrollment } from "./link-enrollment";
|
|
12
12
|
import { runLinkCleanup, type LinkCleanupDeps } from "./link-cleanup";
|
|
13
|
+
import { runLinkCheck } from "./link-child-ops";
|
|
14
|
+
import { validateChildOps, type LinkChildOpsView } from "./link-status-child";
|
|
13
15
|
import { assertSshAlias } from "../link/ssh-argv";
|
|
14
16
|
import { boundHint } from "../link/ssh-runner";
|
|
15
17
|
import { linkStorePath } from "../link/paths";
|
|
@@ -42,15 +44,20 @@ export const LINK_USAGE = `Usage:
|
|
|
42
44
|
ocx link revoke --link-id <id> [--purge] [--force --yes] [--json]
|
|
43
45
|
ocx link reconnect --link-id <id> [--json]
|
|
44
46
|
ocx link cleanup [--link-id <id>] [--json]
|
|
47
|
+
ocx link check (--link-id <id> | --all) [--no-wait] [--json]
|
|
45
48
|
|
|
46
49
|
Forced revoke skips remote cleanup. Run ocx disconnect on the remote client.
|
|
47
|
-
Cleanup reports each Child's platform with disconnect guidance; it changes nothing
|
|
50
|
+
Cleanup reports each Child's platform with disconnect guidance; it changes nothing.
|
|
51
|
+
Check reads each Home-initiated Child's installed version and update route; it changes no install.`;
|
|
48
52
|
|
|
49
53
|
/**
|
|
50
54
|
* What `ocx link status` prints: the runtime's status DTO itself, so a field the server adds (like
|
|
51
|
-
* `peer` or the diagnostics `tunnel`) is part of this type the moment it is part of the wire.
|
|
55
|
+
* `peer` or the diagnostics `tunnel`) is part of this type the moment it is part of the wire. The `child` block is
|
|
56
|
+
* read tolerantly, so its type is this CLI's view of it.
|
|
52
57
|
*/
|
|
53
|
-
export type LinkStatusPayload = LinkStatusDto
|
|
58
|
+
export type LinkStatusPayload = Omit<LinkStatusDto, "links"> & {
|
|
59
|
+
links: Array<Omit<LinkStatusDto["links"][number], "child"> & { child?: LinkChildOpsView }>;
|
|
60
|
+
};
|
|
54
61
|
|
|
55
62
|
export interface LinkIssuePayload {
|
|
56
63
|
linkId: string;
|
|
@@ -156,7 +163,7 @@ export function validateStatus(value: unknown): LinkStatusPayload {
|
|
|
156
163
|
if (!isRecord(candidate)) throw new Error(`invalid link API response: link ${index}`);
|
|
157
164
|
// The OCX-6 parity fields are optional on the wire (an older runtime omits them) and always
|
|
158
165
|
// present in this output, null when absent.
|
|
159
|
-
assertKeys(candidate, ["id", "alias", "direction", "state", "since", "reason", "tunnelPort"], [...PARITY_KEYS, "peer", "tunnel", "childKind"], `link ${index}`);
|
|
166
|
+
assertKeys(candidate, ["id", "alias", "direction", "state", "since", "reason", "tunnelPort"], [...PARITY_KEYS, "peer", "tunnel", "childKind", "child"], `link ${index}`);
|
|
160
167
|
const parity = validateParity(candidate, index);
|
|
161
168
|
if (typeof candidate.id !== "string" || !LINK_ID.test(candidate.id)
|
|
162
169
|
|| !validString(candidate.alias) || (candidate.direction !== "hub-initiated" && candidate.direction !== "client-initiated")
|
|
@@ -177,6 +184,7 @@ export function validateStatus(value: unknown): LinkStatusPayload {
|
|
|
177
184
|
...parity,
|
|
178
185
|
...(candidate.peer !== undefined ? { peer: validatePeer(candidate.peer, index) } : {}),
|
|
179
186
|
...(candidate.tunnel !== undefined ? { tunnel: validateTunnel(candidate.tunnel, index) } : {}),
|
|
187
|
+
...(candidate.child !== undefined ? { child: validateChildOps(candidate.child, index) } : {}),
|
|
180
188
|
};
|
|
181
189
|
});
|
|
182
190
|
let child: LinkStatusPayload["child"] = null;
|
|
@@ -305,10 +313,10 @@ async function runStatus(args: string[], deps: LinkCliDeps): Promise<void> {
|
|
|
305
313
|
}
|
|
306
314
|
throw error;
|
|
307
315
|
}
|
|
308
|
-
// A proxy older than the compatibility report
|
|
309
|
-
// answers without those fields.
|
|
316
|
+
// A proxy older than the compatibility report, the tunnel diagnostics or the Child block ignores
|
|
317
|
+
// the query and answers without those fields.
|
|
310
318
|
const result = validateStatus(await viaLocalControlSocket(baseUrl, deps,
|
|
311
|
-
statusDeps => linkRequest<unknown>("/api/link/status?compatibility=1&diagnostics=1", {}, statusDeps)));
|
|
319
|
+
statusDeps => linkRequest<unknown>("/api/link/status?compatibility=1&diagnostics=1&children=1", {}, statusDeps)));
|
|
312
320
|
console.log(JSON.stringify(result));
|
|
313
321
|
}
|
|
314
322
|
|
|
@@ -383,7 +391,10 @@ async function runReconnect(args: string[], deps: LinkCliDeps): Promise<void> {
|
|
|
383
391
|
}
|
|
384
392
|
|
|
385
393
|
export async function runLinkCommand(rawArgs: string[], deps: LinkCliDeps = {}): Promise<number> {
|
|
386
|
-
|
|
394
|
+
// runCliAction maps thrown errors (2 usage, 4 on 404, 5 on 409, else 1) and returns 0 on success, so a
|
|
395
|
+
// verb's own verdict exit (check: 6 for a partial result) travels beside it.
|
|
396
|
+
let verdictExit = 0;
|
|
397
|
+
const code = await runCliAction(async () => {
|
|
387
398
|
const args = [...rawArgs];
|
|
388
399
|
const command = args.shift();
|
|
389
400
|
if (command === "probe" || command === "add") await runLinkEnrollment(command, args, deps, linkRequest, LINK_USAGE);
|
|
@@ -393,8 +404,10 @@ export async function runLinkCommand(rawArgs: string[], deps: LinkCliDeps = {}):
|
|
|
393
404
|
else if (command === "revoke") await runRevoke(args, deps);
|
|
394
405
|
else if (command === "reconnect") await runReconnect(args, deps);
|
|
395
406
|
else if (command === "cleanup") await runLinkCleanup(args, deps, LINK_USAGE);
|
|
396
|
-
else
|
|
407
|
+
else if (command === "check") verdictExit = await runLinkCheck(args, deps, linkRequest, LINK_USAGE);
|
|
408
|
+
else throw new CliUsageError("link requires one of: probe, add, port, issue, status, revoke, reconnect, cleanup, check", LINK_USAGE);
|
|
397
409
|
});
|
|
410
|
+
return code === 0 ? verdictExit : code;
|
|
398
411
|
}
|
|
399
412
|
|
|
400
413
|
const PARITY_KEYS = ["lastApplyAt", "runtimeStartedAt", "appliedCodexSettingsDigest", "reportedAt"] as const;
|
package/src/cli/registry.ts
CHANGED
|
@@ -152,7 +152,7 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
|
|
|
152
152
|
},
|
|
153
153
|
{
|
|
154
154
|
name: "link",
|
|
155
|
-
usage: "ocx link <port|issue|status|revoke|reconnect|cleanup>",
|
|
155
|
+
usage: "ocx link <port|issue|status|revoke|reconnect|cleanup|check>",
|
|
156
156
|
summary: "Allocate and manage a loopback remote home link.",
|
|
157
157
|
details: [
|
|
158
158
|
"Port: ocx link port [--json]",
|
|
@@ -161,7 +161,8 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
|
|
|
161
161
|
"Revoke: ocx link revoke --link-id <id> [--force --yes] [--json]",
|
|
162
162
|
"Reconnect: ocx link reconnect --link-id <id> [--json]",
|
|
163
163
|
"Cleanup: ocx link cleanup [--link-id <id>] [--json]",
|
|
164
|
-
"
|
|
164
|
+
"Check: ocx link check (--link-id <id> | --all) [--no-wait] [--json]",
|
|
165
|
+
"Issue, status, revoke, reconnect, and check use the running proxy's loopback management API and admin token.",
|
|
165
166
|
],
|
|
166
167
|
},
|
|
167
168
|
{
|
package/src/cli/sync-command.ts
CHANGED
|
@@ -217,7 +217,9 @@ export async function runSyncCommand(deps: CliDispatchDeps): Promise<number> {
|
|
|
217
217
|
}
|
|
218
218
|
try {
|
|
219
219
|
const result = await runFanoutProcess(buildExecArgv({ alias: link.alias, knownHostsFile: linkKnownHostsPath(), argv: remotePinnedSyncArgv(link.id, platform) }), { timeoutMs: Math.max(0, deadline - Date.now()) });
|
|
220
|
-
|
|
220
|
+
// Pick the public fields: a verdict key that ocx.sync.fanout/1 does not define never reaches the document.
|
|
221
|
+
const { state, reason } = classifySyncResult(result);
|
|
222
|
+
return { state, reason, exit: result.code };
|
|
221
223
|
} catch (error) {
|
|
222
224
|
if (error instanceof FanoutProcessError) return { state: error.reason === "deadline-exceeded" || error.reason === "termination-unconfirmed" ? "timed-out" : "failed", reason: error.reason, exit: null };
|
|
223
225
|
throw error;
|
package/src/cli/sync-fanout.ts
CHANGED
|
@@ -1,86 +1,11 @@
|
|
|
1
|
-
import { compareStrictSemver, parseStrictSemver } from "../lib/strict-semver";
|
|
2
1
|
import type { LinkRecord, LinkStore } from "../link/store";
|
|
3
|
-
import type {
|
|
2
|
+
import type { LinkStatusPayload } from "./link";
|
|
4
3
|
import { LinkStatusError } from "./sync-link-status";
|
|
5
4
|
|
|
6
|
-
export
|
|
7
|
-
|
|
5
|
+
export { classifySyncResult, classifyVersionProbe, parseOcxVersion, REMOTE_LINK_SYNC_MESSAGE,
|
|
6
|
+
STALE_REMOTE_CATALOG_MESSAGE, type ChildVerdict } from "../link/sync-fanout-classify";
|
|
8
7
|
export const SYNC_FANOUT_PARTIAL_EXIT = 6;
|
|
9
8
|
|
|
10
|
-
export type ChildVerdict = { state: "synced" | "skipped" | "failed"; reason: string | null };
|
|
11
|
-
const failure = (reason: string): ChildVerdict => ({ state: "failed", reason });
|
|
12
|
-
const skipped = (reason: string): ChildVerdict => ({ state: "skipped", reason });
|
|
13
|
-
const minimum = parseStrictSemver("2.93.0")!;
|
|
14
|
-
|
|
15
|
-
export function parseOcxVersion(output: string): string | null {
|
|
16
|
-
const version = output.trim().replace(/^opencodex /, "");
|
|
17
|
-
return parseStrictSemver(version) ? version : null;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
export function classifyVersionProbe(output: string): "child-ocx-version-unknown" | "child-ocx-lacks-expect-link" | null {
|
|
21
|
-
const version = parseOcxVersion(output);
|
|
22
|
-
if (!version) return "child-ocx-version-unknown";
|
|
23
|
-
return compareStrictSemver(parseStrictSemver(version)!, minimum) < 0 ? "child-ocx-lacks-expect-link" : null;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
const mismatchReasons = new Set(["disconnected", "invalid_state", "disconnect_pending", "pending_operation", "hub_client", "link_client", "other_link", "other_key"]);
|
|
27
|
-
|
|
28
|
-
function validDocument(value: unknown): "synced" | "stale" | null {
|
|
29
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
30
|
-
const v = value as Record<string, unknown>;
|
|
31
|
-
const keysAre = (object: Record<string, unknown>, keys: readonly string[]): boolean => Object.keys(object).length === keys.length && keys.every(key => Object.hasOwn(object, key));
|
|
32
|
-
if (!keysAre(v, ["schema", "home", "fanout", "children"])) return null;
|
|
33
|
-
if (v.schema !== "ocx.sync.fanout/1" || !v.home || typeof v.home !== "object" || Array.isArray(v.home)
|
|
34
|
-
|| !v.fanout || typeof v.fanout !== "object" || Array.isArray(v.fanout) || !Array.isArray(v.children)) return null;
|
|
35
|
-
const home = v.home as Record<string, unknown>, fanout = v.fanout as Record<string, unknown>;
|
|
36
|
-
if (!keysAre(home, ["state", "exit"]) || !keysAre(fanout, ["state", "reason"])) return null;
|
|
37
|
-
if (home.exit !== 0 || (home.state !== "synced" && home.state !== "stale")) return null;
|
|
38
|
-
if (fanout.state !== "not-applicable" || fanout.reason !== null || v.children.length !== 0) return null;
|
|
39
|
-
return home.state;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
export function classifySyncResult(result: { code: number; stdout: string; stderr: string }): ChildVerdict {
|
|
43
|
-
const { code, stdout, stderr } = result;
|
|
44
|
-
if (code === 255) return failure("ssh-failed");
|
|
45
|
-
if (code === 127) return failure("child-ocx-not-found");
|
|
46
|
-
if (code === 126) return failure("child-ocx-not-contained");
|
|
47
|
-
if (code === 125) return skipped("child-platform-unsupported");
|
|
48
|
-
const lines = stderr.split(/\r?\n/);
|
|
49
|
-
const last = stderr.trimEnd().split(/\r?\n/).at(-1);
|
|
50
|
-
if (code === 121) {
|
|
51
|
-
if (last === "ocx-fanout:child-ocx-lacks-expect-link") return skipped("child-ocx-lacks-expect-link");
|
|
52
|
-
if (last === "ocx-fanout:child-ocx-version-unknown") return skipped("child-ocx-version-unknown");
|
|
53
|
-
return failure("child-sync-failed");
|
|
54
|
-
}
|
|
55
|
-
const markers = lines.map(line => /^ocx-fanout:selected:(.+)$/.exec(line)).filter(match => match !== null);
|
|
56
|
-
if (markers.length !== 1 || !parseStrictSemver(markers[0]![1]!)) return failure("child-output-invalid");
|
|
57
|
-
const outputLines = stdout.split(/\r?\n/);
|
|
58
|
-
const delimiters = outputLines.flatMap((line, index) => line === "ocx-fanout:stdout-begin" ? [index] : []);
|
|
59
|
-
if (delimiters.length !== 1) return failure("child-output-invalid");
|
|
60
|
-
if (code === 5) {
|
|
61
|
-
try {
|
|
62
|
-
const detail: unknown = JSON.parse(last ?? "");
|
|
63
|
-
if (detail && typeof detail === "object" && "phase" in detail && detail.phase === "child_link_mismatch"
|
|
64
|
-
&& "reason" in detail && typeof detail.reason === "string" && mismatchReasons.has(detail.reason)) return skipped(`child-link-mismatch:${detail.reason}`);
|
|
65
|
-
} catch { /* The generic mismatch is the only safe fallback. */ }
|
|
66
|
-
return skipped("child-link-mismatch");
|
|
67
|
-
}
|
|
68
|
-
if (code === 7) return skipped("child-updating");
|
|
69
|
-
if (code !== 0) return failure("child-sync-failed");
|
|
70
|
-
const text = outputLines.slice(delimiters[0]! + 1).join("\n").trim();
|
|
71
|
-
if (text.startsWith("{")) {
|
|
72
|
-
try {
|
|
73
|
-
const state = validDocument(JSON.parse(text));
|
|
74
|
-
if (state === "synced") return { state: "synced", reason: null };
|
|
75
|
-
if (state === "stale") return failure("child-catalog-stale");
|
|
76
|
-
} catch { /* Reject invalid or multiple JSON documents. */ }
|
|
77
|
-
return failure("child-output-invalid");
|
|
78
|
-
}
|
|
79
|
-
if (text.includes(STALE_REMOTE_CATALOG_MESSAGE)) return failure("child-catalog-stale");
|
|
80
|
-
if (text.includes(REMOTE_LINK_SYNC_MESSAGE)) return { state: "synced", reason: null };
|
|
81
|
-
return failure("child-output-invalid");
|
|
82
|
-
}
|
|
83
|
-
|
|
84
9
|
export type HomeResult = { state: "synced" | "stale" | "skipped" | "failed"; exit: number };
|
|
85
10
|
export type ChildResult = { linkId: string; alias: string; state: "synced" | "skipped" | "failed" | "timed-out"; reason: string | null; exit: number | null; hint?: string };
|
|
86
11
|
export type FanoutDocument = { schema: "ocx.sync.fanout/1"; home: HomeResult; fanout: { state: "ran" | "disabled" | "not-applicable" | "failed"; reason: string | null }; children: ChildResult[] };
|
|
@@ -98,7 +23,7 @@ function childSkipHint(reason: string | null, alias: string): string {
|
|
|
98
23
|
|
|
99
24
|
export async function runHomeFanout(deps: {
|
|
100
25
|
home: HomeResult; catalogCurrent: boolean; localOnly?: boolean; applicable?: boolean;
|
|
101
|
-
readStore: () => LinkStore; readLinkStatus: () => Promise<
|
|
26
|
+
readStore: () => LinkStore; readLinkStatus: () => Promise<LinkStatusPayload>;
|
|
102
27
|
runChild: (link: LinkRecord, deadline: number) => Promise<Omit<ChildResult, "linkId" | "alias">>;
|
|
103
28
|
now?: () => number; deadlineMs?: number; concurrency?: number; terminationGraceMs?: number;
|
|
104
29
|
}): Promise<FanoutDocument> {
|
|
@@ -115,7 +40,7 @@ export async function runHomeFanout(deps: {
|
|
|
115
40
|
result.children = store.links.map(link => classify(link, "skipped", link.direction === "client-initiated" ? "client-initiated-link" : skipReason));
|
|
116
41
|
return result;
|
|
117
42
|
}
|
|
118
|
-
let status:
|
|
43
|
+
let status: LinkStatusPayload;
|
|
119
44
|
try { status = await deps.readLinkStatus(); }
|
|
120
45
|
catch (error) {
|
|
121
46
|
const reason = error instanceof LinkStatusError ? error.reason : "home-link-status-unavailable";
|
|
@@ -141,7 +66,9 @@ export async function runHomeFanout(deps: {
|
|
|
141
66
|
timer = setTimeout(() => resolve({ state: "timed-out", reason: "termination-unconfirmed", exit: null }), budget + (deps.terminationGraceMs ?? 3000));
|
|
142
67
|
}),
|
|
143
68
|
]);
|
|
144
|
-
|
|
69
|
+
// Build the row from the schema's own fields, so an extra key on a runner's result never reaches ocx.sync.fanout/1.
|
|
70
|
+
const hint = child.state === "skipped" ? childSkipHint(child.reason, link.alias) : child.hint;
|
|
71
|
+
result.children[index] = { linkId: link.id, alias: link.alias, state: child.state, reason: child.reason, exit: child.exit, ...(hint === undefined ? {} : { hint }) };
|
|
145
72
|
} catch { result.children[index] = classify(link, "failed", "internal-error"); }
|
|
146
73
|
finally { if (timer !== undefined) clearTimeout(timer); }
|
|
147
74
|
}
|
|
@@ -17,12 +17,22 @@ import { isLinkPort } from "../link/ports";
|
|
|
17
17
|
import { probeLinkRelayPreflight, type BoundLinkRelayTarget, type LinkRelayPreflightResult } from "./link-relay-transport";
|
|
18
18
|
import type { ClientLinkSupervisorStatus } from "./link-tunnel";
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Every reason word /readyz may report. `client_state_changed`: the Child's durable connection no
|
|
22
|
+
* longer matches the one this runtime started with. A reader of /readyz (`ocx connect status`)
|
|
23
|
+
* accepts only these words, so nothing else a listener sends is echoed to a terminal.
|
|
24
|
+
*/
|
|
25
|
+
export const LINK_READINESS_REASONS = [
|
|
26
|
+
"tunnel_idle", "tunnel_connecting", "tunnel_failed", "tunnel_unavailable", "sidecar_invalid",
|
|
27
|
+
"home_unreachable", "home_unauthorized", "link_auth_failed", "link_credential_unavailable",
|
|
28
|
+
"link_unverified", "client_state_changed",
|
|
29
|
+
] as const;
|
|
30
|
+
|
|
31
|
+
export type LinkReadinessReason = typeof LINK_READINESS_REASONS[number];
|
|
32
|
+
|
|
33
|
+
export function isLinkReadinessReason(value: unknown): value is LinkReadinessReason {
|
|
34
|
+
return typeof value === "string" && (LINK_READINESS_REASONS as readonly string[]).includes(value);
|
|
35
|
+
}
|
|
26
36
|
|
|
27
37
|
export type LinkReadiness = { ready: true } | { ready: false; reason: LinkReadinessReason };
|
|
28
38
|
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether this Remote Link Child's tunnel can carry a request right now, for `ocx connect status`.
|
|
3
|
+
*
|
|
4
|
+
* The durable connection record says only that this machine was linked. A Home-initiated tunnel
|
|
5
|
+
* drops whenever the Child sleeps, and `Connection: connected` kept reading healthy while every
|
|
6
|
+
* relayed request failed with 503 home_unreachable (#8470). The running Child already computes the
|
|
7
|
+
* verdict for its own /readyz (`src/client/link-readiness.ts`, served by the machine listener), so
|
|
8
|
+
* this asks it instead of probing the tunnel a second time. The answer is a fixed word: nothing a
|
|
9
|
+
* listener sends beyond LINK_READINESS_REASONS reaches the terminal.
|
|
10
|
+
*/
|
|
11
|
+
import { LINK_RELAY_AUTH_TIMEOUT_MS } from "../link/relay-auth";
|
|
12
|
+
import { directLocalHttpFetch } from "../server/direct-local-http";
|
|
13
|
+
import { findLiveProxy, probeHostname, validateReadyzBody, type LiveProxy } from "../server/proxy-liveness";
|
|
14
|
+
import { isLinkReadinessReason, type LinkReadinessReason } from "./link-readiness";
|
|
15
|
+
|
|
16
|
+
export type LinkTunnelStatus =
|
|
17
|
+
| { state: "up" }
|
|
18
|
+
| { state: "down"; reason: LinkReadinessReason }
|
|
19
|
+
| { state: "unknown"; reason: "runtime_not_running" | "runtime_unreadable" | "link_unverified" };
|
|
20
|
+
|
|
21
|
+
export interface LinkTunnelStatusDeps {
|
|
22
|
+
findLive?: () => Promise<LiveProxy | null>;
|
|
23
|
+
fetchImpl?: typeof fetch;
|
|
24
|
+
/** Resolves after `ms`; the wait for a relay preflight the runtime has not finished yet. */
|
|
25
|
+
delay?: (ms: number) => Promise<void>;
|
|
26
|
+
now?: () => number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* /readyz answers `link_unverified` when its preflight is still running after its 500 ms wait. That
|
|
31
|
+
* preflight ends within LINK_RELAY_AUTH_TIMEOUT_MS of this read's start, no earlier than 500 ms in,
|
|
32
|
+
* and its verdict is reused for LINK_READINESS_TTL_MS (5 s). One more read timed from the FIRST
|
|
33
|
+
* read's start lands after the preflight can finish and inside the cached verdict: anywhere in
|
|
34
|
+
* [start + 5000, start + 5500] works, so this aims at the middle. Timing it from the first read's
|
|
35
|
+
* return instead could miss the cache and start a second Home probe (#8496 review).
|
|
36
|
+
*/
|
|
37
|
+
const SECOND_READ_AFTER_START_MS = LINK_RELAY_AUTH_TIMEOUT_MS + 250;
|
|
38
|
+
const READ_TIMEOUT_MS = 2_000;
|
|
39
|
+
|
|
40
|
+
export async function probeLinkTunnelStatus(deps: LinkTunnelStatusDeps = {}): Promise<LinkTunnelStatus> {
|
|
41
|
+
let live: LiveProxy | null;
|
|
42
|
+
try { live = await (deps.findLive ?? findLiveProxy)(); } catch { live = null; }
|
|
43
|
+
// Only the Child's machine listener reports a link verdict; anything else on the port cannot.
|
|
44
|
+
if (!live || live.role !== "client") return { state: "unknown", reason: "runtime_not_running" };
|
|
45
|
+
const target = live;
|
|
46
|
+
const fetchImpl = deps.fetchImpl ?? directLocalHttpFetch;
|
|
47
|
+
const read = async (): Promise<LinkTunnelStatus> => {
|
|
48
|
+
try {
|
|
49
|
+
const host = target.probeHostname ? probeHostname(target.probeHostname) : probeHostname(target.hostname);
|
|
50
|
+
const response = await fetchImpl(`http://${host}:${target.port}/readyz`, {
|
|
51
|
+
headers: { Accept: "application/json" },
|
|
52
|
+
signal: AbortSignal.timeout(READ_TIMEOUT_MS),
|
|
53
|
+
});
|
|
54
|
+
const body: unknown = await response.json().catch(() => null);
|
|
55
|
+
const parsed = validateReadyzBody(body, target.port, target.pid ? { expectedPid: target.pid } : {});
|
|
56
|
+
const link = parsed ? (body as { link?: unknown }).link : undefined;
|
|
57
|
+
if (!parsed || !link || typeof link !== "object") return { state: "unknown", reason: "runtime_unreadable" };
|
|
58
|
+
const { state, reason } = link as { state?: unknown; reason?: unknown };
|
|
59
|
+
if (state === "available" && parsed.status === "ready" && response.status === 200) return { state: "up" };
|
|
60
|
+
if (state === "unavailable" && response.status === 503 && isLinkReadinessReason(reason)) return { state: "down", reason };
|
|
61
|
+
return { state: "unknown", reason: "runtime_unreadable" };
|
|
62
|
+
} catch {
|
|
63
|
+
return { state: "unknown", reason: "runtime_unreadable" };
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
const now = deps.now ?? Date.now;
|
|
67
|
+
const startedAt = now();
|
|
68
|
+
const first = await read();
|
|
69
|
+
if (first.state !== "down" || first.reason !== "link_unverified") return first;
|
|
70
|
+
const wait = Math.max(0, startedAt + SECOND_READ_AFTER_START_MS - now());
|
|
71
|
+
await (deps.delay ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms))))(wait);
|
|
72
|
+
const second = await read();
|
|
73
|
+
return second.state === "down" && second.reason === "link_unverified"
|
|
74
|
+
? { state: "unknown", reason: "link_unverified" }
|
|
75
|
+
: second;
|
|
76
|
+
}
|
|
@@ -530,6 +530,19 @@ export function commandCodeConfigPath(env: OpencodeLaunchEnv = process.env, home
|
|
|
530
530
|
return join(commandCodeHomeDir(env, home, platform), "providers.json");
|
|
531
531
|
}
|
|
532
532
|
|
|
533
|
+
/**
|
|
534
|
+
* Command Code's credential store, next to the provider file.
|
|
535
|
+
*
|
|
536
|
+
* Only the DESKTOP app reads this before it will show a workspace; the published
|
|
537
|
+
* CLI is content with `apiKey: false` in `providers.json`. It is the vendor's file,
|
|
538
|
+
* shared with real logins and other providers' tokens, so this integration NEVER
|
|
539
|
+
* writes it: the desktop user signs in themselves. Exported so callers and tests
|
|
540
|
+
* can name the path they must leave alone.
|
|
541
|
+
*/
|
|
542
|
+
export function commandCodeAuthPath(env: OpencodeLaunchEnv = process.env, home: string = homedir(), platform: NodeJS.Platform = process.platform): string {
|
|
543
|
+
return join(commandCodeHomeDir(env, home, platform), "auth.json");
|
|
544
|
+
}
|
|
545
|
+
|
|
533
546
|
/**
|
|
534
547
|
* The provider store a current ZCode reads, which is NOT the file above.
|
|
535
548
|
*
|
|
@@ -1623,7 +1636,7 @@ export const EXPORT_CLIENTS: Record<ExportClientId, ExportClientSpec> = {
|
|
|
1623
1636
|
// No env var exists behind this integration: buildCommandCodeClientConfig
|
|
1624
1637
|
// writes `apiKey: false`, the documented keyless form for a loopback endpoint.
|
|
1625
1638
|
apiKeyEnv: "",
|
|
1626
|
-
exportHint: "The provider is written with `apiKey: false
|
|
1639
|
+
exportHint: "The provider is written with `apiKey: false`, the keyless form the CLI accepts. The desktop app needs its own Command Code sign-in; opencodex never writes `~/.commandcode/auth.json`.",
|
|
1627
1640
|
build: buildCommandCodeClientConfig,
|
|
1628
1641
|
format: "json",
|
|
1629
1642
|
summarize: summarizeCommandCode,
|