@bitkyc08/opencodex 2.100.3 → 2.100.4
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/AGENTS_INSTALL.md +23 -1
- package/bin/ocx.mjs +8 -1
- package/gui/dist/assets/{App-Dnb6VMsP.js → App-DcpyI78f.js} +20 -19
- package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-CzjPJprT.js} +1 -1
- package/gui/dist/assets/brand-mark-BTIi7e69.js +1 -0
- package/gui/dist/assets/index-DJxM-imn.css +2 -0
- package/gui/dist/assets/index-DVgU6S3y.js +138 -0
- package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bn6Y-g3R.js} +1 -1
- package/gui/dist/classic/assets/{App-DA-scMPq.js → App-eYJAyNHM.js} +19 -18
- package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-xHMYxLkV.js} +1 -1
- package/gui/dist/classic/assets/index-DSaVRW4F.js +138 -0
- package/gui/dist/classic/assets/quota-summary-DyzHlkFl.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/src/cli.rs +5 -3
- package/native/ocx-child/src/codex_home.rs +1 -0
- package/package.json +2 -2
- package/src/adapters/anthropic/per-message-effort.ts +296 -0
- package/src/adapters/anthropic.ts +3 -0
- package/src/adapters/claude-cli/adapter.ts +1 -0
- package/src/adapters/devin/cloud-direct/chat.ts +71 -14
- package/src/adapters/google-errors.ts +14 -2
- package/src/adapters/qoder/adapter.ts +9 -1
- package/src/adapters/zed.ts +4 -2
- package/src/claude/desktop-remote-store.ts +60 -10
- package/src/cli/account-api.ts +4 -0
- package/src/cli/account-auth.ts +30 -2
- package/src/cli/account-extended.ts +33 -2
- package/src/cli/capabilities-access-remote.ts +3 -3
- package/src/cli/capabilities-accounts.ts +3 -3
- package/src/cli/capabilities-base.ts +11 -6
- package/src/cli/capabilities-observe-system.ts +2 -2
- package/src/cli/claude.ts +3 -3
- package/src/cli/disconnect-runtime.ts +16 -6
- package/src/cli/dispatch.ts +7 -1
- package/src/cli/index.ts +2 -2
- package/src/cli/link-apply-restart.ts +4 -2
- package/src/cli/link-routes.ts +4 -1
- package/src/cli/link.ts +5 -4
- package/src/cli/preflight-exemptions.ts +3 -0
- package/src/cli/registry.ts +5 -2
- package/src/cli/resolve.ts +23 -8
- package/src/cli/restart-failure.ts +11 -1
- package/src/cli/runtime-api.ts +4 -0
- package/src/cli/status.ts +4 -1
- package/src/cli/system-command.ts +1 -1
- package/src/cli/system-restart-client.ts +9 -3
- package/src/cli/system-settings-parity.ts +2 -1
- package/src/client/connect.ts +63 -9
- package/src/client/desktop-refusal.ts +38 -0
- package/src/client/lifecycle-lock.ts +29 -4
- package/src/client/runtime-restart.ts +27 -15
- package/src/client/runtime.ts +4 -2
- package/src/client/state.ts +14 -0
- package/src/codex/account-pause.ts +4 -0
- package/src/codex/account-runtime-state.ts +4 -0
- package/src/codex/auth-api/main-account-probe.ts +3 -1
- package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
- package/src/codex/auth-context.ts +40 -2
- package/src/codex/catalog/build-entries.ts +10 -0
- package/src/codex/catalog/derive-entry.ts +7 -0
- package/src/codex/catalog/reserve-warn.ts +7 -5
- package/src/codex/catalog/reserve.ts +4 -3
- package/src/codex/catalog/retained-sync.ts +2 -0
- package/src/codex/catalog/routed-defaults.ts +35 -0
- package/src/codex/convergence.ts +2 -0
- package/src/codex/loopback-target.ts +22 -8
- package/src/codex/main-account.ts +88 -29
- package/src/codex/native-main-auth-file.ts +14 -0
- package/src/codex/native-main-credentials.ts +270 -0
- package/src/codex/native-main-owner.ts +3 -0
- package/src/codex/native-main-refresh-mode.ts +14 -1
- package/src/codex/quota.ts +63 -14
- package/src/combos/failover.ts +12 -1
- package/src/combos/index.ts +5 -0
- package/src/combos/resolve.ts +115 -19
- package/src/config/diagnostics.ts +3 -0
- package/src/config/live-reconcile.ts +6 -3
- package/src/config/load-degrade.ts +2 -0
- package/src/config/persisted-mutation.ts +2 -2
- package/src/config/persisted-projections.ts +18 -0
- package/src/config/process-state.ts +4 -3
- package/src/config/reserve-capability.ts +96 -0
- package/src/config/schema/config-schema.ts +6 -0
- package/src/config/schema/leaf-validators.ts +2 -0
- package/src/config/schema/routed-catalog-defaults.ts +49 -0
- package/src/config.ts +7 -7
- package/src/desktop-update/acquire.ts +202 -0
- package/src/desktop-update/cli.ts +168 -0
- package/src/desktop-update/drain.ts +40 -0
- package/src/desktop-update/headless.ts +285 -0
- package/src/desktop-update/image.ts +85 -0
- package/src/desktop-update/install.ts +53 -0
- package/src/desktop-update/msi.ts +72 -0
- package/src/desktop-update/release.ts +128 -0
- package/src/desktop-update/runtime.ts +155 -0
- package/src/desktop-update/staging.ts +118 -0
- package/src/desktop-update/trust.ts +45 -0
- package/src/generated/compatibility-version.json +246 -130
- package/src/images/fulfill-video.ts +3 -3
- package/src/images/loop.ts +6 -2
- package/src/images/plan.ts +147 -11
- package/src/images/types.ts +13 -4
- package/src/images/xai-video-client.ts +72 -10
- package/src/lib/gcp-adc.ts +48 -4
- package/src/lib/offline-resend.ts +150 -0
- package/src/lib/paced-stream.ts +3 -3
- package/src/lib/provider-outbound.ts +17 -6
- package/src/lib/request-failure-model.ts +2 -0
- package/src/lib/response-body-inactivity.ts +23 -1
- package/src/lib/upstream-retry.ts +38 -5
- package/src/link/explicit-route.ts +4 -4
- package/src/link/remote-windows.ts +79 -31
- package/src/link/residual-recovery.ts +20 -8
- package/src/messaging/budget.ts +23 -5
- package/src/messaging/rpc.ts +4 -4
- package/src/oauth/antigravity-risk.ts +126 -0
- package/src/oauth/generic-account-failover.ts +89 -18
- package/src/oauth/generic-session-affinity.ts +10 -3
- package/src/oauth/login-cli.ts +35 -1
- package/src/oauth/pool-kernel.ts +3 -3
- package/src/providers/anthropic-billing-refusal.ts +27 -3
- package/src/providers/google-vertex-model-discovery.ts +6 -1
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/quota/workbuddy.ts +6 -2
- package/src/providers/workbuddy-credit-balance.ts +125 -16
- package/src/responses/effort-history.ts +732 -0
- package/src/routing/history/integrity.ts +41 -4
- package/src/server/auth-cors.ts +13 -3
- package/src/server/codex-model-list.ts +2 -1
- package/src/server/direct-local-http.ts +26 -3
- package/src/server/index/link-listener.ts +20 -14
- package/src/server/index/serve-options.ts +1 -0
- package/src/server/index.ts +3 -2
- package/src/server/link-turn.ts +17 -5
- package/src/server/management/config-routes.ts +39 -3
- package/src/server/management/link-child-preflight.ts +1 -1
- package/src/server/management/link-route-edit.ts +20 -1
- package/src/server/management/oauth-account-routes.ts +22 -5
- package/src/server/management/provider-overwrite-carry.ts +3 -0
- package/src/server/management/provider-routes.ts +4 -4
- package/src/server/management/static-catalog-probe.ts +33 -0
- package/src/server/proxy-liveness.ts +54 -9
- package/src/server/relay.ts +6 -1
- package/src/server/request-log-conversation.ts +2 -2
- package/src/server/request-log.ts +5 -1
- package/src/server/reserve-capability-startup.ts +32 -0
- package/src/server/responses/adapter-delivery.ts +2 -0
- package/src/server/responses/adapter-dispatch.ts +31 -10
- package/src/server/responses/antigravity-fault-rotation.ts +24 -0
- package/src/server/responses/antigravity-validation-refusal.ts +43 -6
- package/src/server/responses/combo-selection-keepalive.ts +254 -0
- package/src/server/responses/core-combo.ts +24 -9
- package/src/server/responses/core-errors.ts +9 -6
- package/src/server/responses/core-options.ts +8 -0
- package/src/server/responses/core.ts +21 -0
- package/src/server/responses/estimated-usage.ts +115 -0
- package/src/server/responses/jev-model-invoke.ts +7 -2
- package/src/server/responses/passthrough-completion.ts +6 -3
- package/src/server/responses/passthrough-delivery.ts +47 -8
- package/src/server/responses/passthrough-dispatch.ts +3 -0
- package/src/server/responses/request-prepare.ts +9 -5
- package/src/server/responses/sidecar-execution.ts +5 -0
- package/src/service/desktop-supervision.d.mts +2 -0
- package/src/service/desktop-supervision.mjs +5 -0
- package/src/stall-timeout.ts +11 -0
- package/src/types/config.ts +15 -92
- package/src/types/provider.ts +13 -0
- package/src/types/request.ts +19 -0
- package/src/types/routed-catalog-defaults.ts +17 -0
- package/src/types/routing-profile.ts +90 -0
- package/src/types.ts +1 -0
- package/src/update/index.ts +1 -1
- package/src/usage/log.ts +14 -4
- package/src/usage/telemetry-contract.ts +1 -0
- package/src/web-search/passthrough-bridge.ts +7 -0
- package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
- package/gui/dist/assets/index-DCdXsMyZ.js +0 -105
- package/gui/dist/assets/index-DQtCRNAw.css +0 -2
- package/gui/dist/classic/assets/index-BqOaGLf5.js +0 -105
- package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded HTTPS acquisition for the headless Desktop updater (#8246).
|
|
3
|
+
*
|
|
4
|
+
* The contract is the acquisition rule in devlog/_plan/261107_auto_update_parity/030_desktop_engine.md:
|
|
5
|
+
* HTTPS only, the exact lidge-jun/opencodex release source, at most three redirects to the
|
|
6
|
+
* listed GitHub asset hosts, no userinfo or non-default port, no credentials, a size cap counted
|
|
7
|
+
* before each chunk is kept, and connect, idle-read and total deadlines. A Content-Length header
|
|
8
|
+
* is advisory: it can refuse early but never raises the bound. The transport and the timers are
|
|
9
|
+
* injected so tests drive every hop and deadline without a network or a sleep; a loopback mock is
|
|
10
|
+
* reachable only through that injected transport, never through a production setting.
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
DESKTOP_ACQUIRE_LIMITS,
|
|
14
|
+
DESKTOP_REDIRECT_HOSTS,
|
|
15
|
+
DESKTOP_RELEASE_PATH_PREFIX,
|
|
16
|
+
} from "./trust";
|
|
17
|
+
|
|
18
|
+
export type DesktopAcquireErrorCode =
|
|
19
|
+
| "url_refused"
|
|
20
|
+
| "redirect_refused"
|
|
21
|
+
| "too_many_redirects"
|
|
22
|
+
| "http_status"
|
|
23
|
+
| "connect_timeout"
|
|
24
|
+
| "idle_timeout"
|
|
25
|
+
| "total_timeout"
|
|
26
|
+
| "oversize"
|
|
27
|
+
| "truncated"
|
|
28
|
+
| "transport";
|
|
29
|
+
|
|
30
|
+
export class DesktopAcquireError extends Error {
|
|
31
|
+
constructor(readonly code: DesktopAcquireErrorCode, readonly retryable: boolean, message: string) {
|
|
32
|
+
super(message);
|
|
33
|
+
this.name = "DesktopAcquireError";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface AcquireResponse {
|
|
38
|
+
status: number;
|
|
39
|
+
headers: { get(name: string): string | null };
|
|
40
|
+
body: AsyncIterable<Uint8Array> | null;
|
|
41
|
+
/** Release the connection of a response that is not read to the end. */
|
|
42
|
+
cancel?: () => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface AcquireTransport {
|
|
46
|
+
request(url: string, signal: AbortSignal): Promise<AcquireResponse>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface AcquireTimers {
|
|
50
|
+
/** Run `fire` once after `ms`; the returned function cancels it. */
|
|
51
|
+
schedule(ms: number, fire: () => void): () => void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface AcquireLimits {
|
|
55
|
+
maxBytes: number;
|
|
56
|
+
maxRedirects?: number;
|
|
57
|
+
connectMs?: number;
|
|
58
|
+
idleReadMs?: number;
|
|
59
|
+
totalMs?: number;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Admit one hop. The first request must name the exact release source on github.com; a redirect
|
|
66
|
+
* may move to a listed asset host, and a redirect back to github.com stays inside the same
|
|
67
|
+
* repository's releases.
|
|
68
|
+
*/
|
|
69
|
+
export function admitAcquireUrl(raw: string, initial: boolean): URL {
|
|
70
|
+
let url: URL;
|
|
71
|
+
try { url = new URL(raw); } catch { throw new DesktopAcquireError(initial ? "url_refused" : "redirect_refused", false, "not an absolute URL"); }
|
|
72
|
+
const code = initial ? "url_refused" : "redirect_refused";
|
|
73
|
+
if (url.protocol !== "https:") throw new DesktopAcquireError(code, false, `${url.protocol} is not https`);
|
|
74
|
+
if (url.username || url.password) throw new DesktopAcquireError(code, false, "a URL with credentials is refused");
|
|
75
|
+
if (url.port !== "") throw new DesktopAcquireError(code, false, "a non-default port is refused");
|
|
76
|
+
const host = url.hostname.toLowerCase();
|
|
77
|
+
if (initial || host === "github.com") {
|
|
78
|
+
if (host !== "github.com" || !url.pathname.startsWith(DESKTOP_RELEASE_PATH_PREFIX)) {
|
|
79
|
+
throw new DesktopAcquireError(code, false, `${host}${url.pathname} is not the OpenCodex release source`);
|
|
80
|
+
}
|
|
81
|
+
} else if (!DESKTOP_REDIRECT_HOSTS.includes(host)) {
|
|
82
|
+
throw new DesktopAcquireError(code, false, `${host} is not a listed GitHub release-asset host`);
|
|
83
|
+
}
|
|
84
|
+
return url;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Fetch one resource under the acquisition contract and return its exact bytes. */
|
|
88
|
+
export async function acquireBounded(
|
|
89
|
+
url: string,
|
|
90
|
+
limits: AcquireLimits,
|
|
91
|
+
deps: { transport: AcquireTransport; timers: AcquireTimers },
|
|
92
|
+
): Promise<Uint8Array> {
|
|
93
|
+
const maxRedirects = limits.maxRedirects ?? DESKTOP_ACQUIRE_LIMITS.maxRedirects;
|
|
94
|
+
const connectMs = limits.connectMs ?? DESKTOP_ACQUIRE_LIMITS.connectMs;
|
|
95
|
+
const idleReadMs = limits.idleReadMs ?? DESKTOP_ACQUIRE_LIMITS.idleReadMs;
|
|
96
|
+
const totalMs = limits.totalMs ?? DESKTOP_ACQUIRE_LIMITS.totalMs;
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
let failure: DesktopAcquireError | null = null;
|
|
99
|
+
let rejectFailure: (error: DesktopAcquireError) => void = () => {};
|
|
100
|
+
const failed = new Promise<never>((_, reject) => { rejectFailure = reject; });
|
|
101
|
+
failed.catch(() => {});
|
|
102
|
+
const fail = (code: DesktopAcquireErrorCode, message: string) => {
|
|
103
|
+
if (failure) return;
|
|
104
|
+
failure = new DesktopAcquireError(code, true, message);
|
|
105
|
+
controller.abort(failure);
|
|
106
|
+
rejectFailure(failure);
|
|
107
|
+
};
|
|
108
|
+
const raced = async <T>(work: Promise<T>): Promise<T> => {
|
|
109
|
+
try { return await Promise.race([work, failed]); }
|
|
110
|
+
catch (error) {
|
|
111
|
+
if (failure) throw failure;
|
|
112
|
+
if (error instanceof DesktopAcquireError) throw error;
|
|
113
|
+
throw new DesktopAcquireError("transport", true, "the download connection failed");
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const cancelTotal = deps.timers.schedule(totalMs, () => fail("total_timeout", `no complete response within ${totalMs} ms`));
|
|
117
|
+
try {
|
|
118
|
+
let current = url;
|
|
119
|
+
let redirects = 0;
|
|
120
|
+
for (;;) {
|
|
121
|
+
const target = admitAcquireUrl(current, redirects === 0);
|
|
122
|
+
const cancelConnect = deps.timers.schedule(connectMs, () => fail("connect_timeout", `no response within ${connectMs} ms`));
|
|
123
|
+
let response: AcquireResponse;
|
|
124
|
+
try { response = await raced(deps.transport.request(target.href, controller.signal)); }
|
|
125
|
+
finally { cancelConnect(); }
|
|
126
|
+
if (REDIRECT_STATUSES.has(response.status)) {
|
|
127
|
+
response.cancel?.();
|
|
128
|
+
const location = response.headers.get("location");
|
|
129
|
+
if (!location) throw new DesktopAcquireError("redirect_refused", false, "a redirect named no location");
|
|
130
|
+
if (++redirects > maxRedirects) throw new DesktopAcquireError("too_many_redirects", false, `more than ${maxRedirects} redirects`);
|
|
131
|
+
current = new URL(location, target).href;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (response.status !== 200) {
|
|
135
|
+
response.cancel?.();
|
|
136
|
+
const retryable = response.status === 429 || response.status >= 500;
|
|
137
|
+
throw new DesktopAcquireError("http_status", retryable, `the release source answered HTTP ${response.status}`);
|
|
138
|
+
}
|
|
139
|
+
// A transfer encoding changes what Content-Length counts, so only an identity body binds it.
|
|
140
|
+
const declaredRaw = response.headers.get("content-encoding") ? null : response.headers.get("content-length");
|
|
141
|
+
const declared = declaredRaw !== null && /^\d{1,15}$/.test(declaredRaw) ? Number(declaredRaw) : null;
|
|
142
|
+
if (declared !== null && declared > limits.maxBytes) {
|
|
143
|
+
response.cancel?.();
|
|
144
|
+
throw new DesktopAcquireError("oversize", false, `the response declares ${declared} bytes, over the ${limits.maxBytes}-byte cap`);
|
|
145
|
+
}
|
|
146
|
+
if (!response.body) throw new DesktopAcquireError("truncated", true, "the response had no body");
|
|
147
|
+
const iterator = response.body[Symbol.asyncIterator]();
|
|
148
|
+
const chunks: Uint8Array[] = [];
|
|
149
|
+
let total = 0;
|
|
150
|
+
for (;;) {
|
|
151
|
+
const cancelIdle = deps.timers.schedule(idleReadMs, () => fail("idle_timeout", `no data for ${idleReadMs} ms`));
|
|
152
|
+
let step: IteratorResult<Uint8Array>;
|
|
153
|
+
try { step = await raced(iterator.next()); }
|
|
154
|
+
finally { cancelIdle(); }
|
|
155
|
+
if (step.done) break;
|
|
156
|
+
const chunk = step.value;
|
|
157
|
+
// Count before keeping: an oversized chunk is never retained.
|
|
158
|
+
if (total + chunk.byteLength > limits.maxBytes) {
|
|
159
|
+
try { await iterator.return?.(); } catch { /* the cap already decided */ }
|
|
160
|
+
throw new DesktopAcquireError("oversize", false, `the response exceeded the ${limits.maxBytes}-byte cap`);
|
|
161
|
+
}
|
|
162
|
+
chunks.push(chunk);
|
|
163
|
+
total += chunk.byteLength;
|
|
164
|
+
}
|
|
165
|
+
if (declared !== null && declared !== total) {
|
|
166
|
+
throw new DesktopAcquireError("truncated", true, `received ${total} of ${declared} declared bytes`);
|
|
167
|
+
}
|
|
168
|
+
const bytes = new Uint8Array(total);
|
|
169
|
+
let offset = 0;
|
|
170
|
+
for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
|
|
171
|
+
return bytes;
|
|
172
|
+
}
|
|
173
|
+
} finally {
|
|
174
|
+
cancelTotal();
|
|
175
|
+
if (!controller.signal.aborted) controller.abort();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Production transport: manual redirects so every hop is admitted here, and no credentials. */
|
|
180
|
+
export const fetchAcquireTransport: AcquireTransport = {
|
|
181
|
+
async request(url, signal) {
|
|
182
|
+
const response = await fetch(url, {
|
|
183
|
+
redirect: "manual",
|
|
184
|
+
signal,
|
|
185
|
+
credentials: "omit",
|
|
186
|
+
headers: { "user-agent": "opencodex-desktop-updater", accept: "application/octet-stream, application/json" },
|
|
187
|
+
});
|
|
188
|
+
return {
|
|
189
|
+
status: response.status,
|
|
190
|
+
headers: response.headers,
|
|
191
|
+
body: response.body as unknown as AsyncIterable<Uint8Array> | null,
|
|
192
|
+
cancel: () => { response.body?.cancel().catch(() => {}); },
|
|
193
|
+
};
|
|
194
|
+
},
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
export const realAcquireTimers: AcquireTimers = {
|
|
198
|
+
schedule(ms, fire) {
|
|
199
|
+
const timer = setTimeout(fire, ms);
|
|
200
|
+
return () => clearTimeout(timer);
|
|
201
|
+
},
|
|
202
|
+
};
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Production composition of `ocx update --desktop` (#8246). The decisions live in
|
|
3
|
+
* `./headless.ts`; this file only binds them to the network, the filesystem, Windows Installer,
|
|
4
|
+
* the runtime record and the terminal.
|
|
5
|
+
*/
|
|
6
|
+
import { readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join, win32 } from "node:path";
|
|
8
|
+
import { getConfigDir } from "../config";
|
|
9
|
+
import { packageVersion } from "../lib/package-version";
|
|
10
|
+
import { findLiveProxy } from "../server/proxy-liveness";
|
|
11
|
+
import { requestBoundSystemRestart } from "../cli/system-restart-client";
|
|
12
|
+
import { CLIENT_RESTART_REQUEST_MIN_REMAINING_MS } from "../lib/system-restart-contract";
|
|
13
|
+
import { inspectDesktopSupervision, trustedWindowsSystemDirectory, windowsProcessPair } from "../service/desktop-supervision.mjs";
|
|
14
|
+
import { tryAcquireUpdateSyncMutex } from "../update/sync-update-mutex.mjs";
|
|
15
|
+
import { acquireBounded, fetchAcquireTransport, realAcquireTimers } from "./acquire";
|
|
16
|
+
import { DRAIN_DEADLINE_MS, DRAIN_STOP_DEADLINE_ENV, parseDrainResult, serviceRestartFailureDetail } from "./drain";
|
|
17
|
+
import { HEADLESS_EXIT, runHeadlessDesktopUpdate, type HeadlessResult } from "./headless";
|
|
18
|
+
import { windowsDesktopInstall, type WindowsDesktopInstall } from "./install";
|
|
19
|
+
import { ownImageMover } from "./image";
|
|
20
|
+
import { createStagingDirectory, windowsStagingDeps } from "./staging";
|
|
21
|
+
|
|
22
|
+
export const HEADLESS_USAGE = "Usage: ocx update --desktop [--check] [--json]";
|
|
23
|
+
/**
|
|
24
|
+
* The deadline handed to the bound restart request. A connected client refuses to ask for a
|
|
25
|
+
* restart it could not finish (and roll back) inside this window, so it must cover that budget.
|
|
26
|
+
*/
|
|
27
|
+
export const RESTART_REQUEST_WINDOW_MS = CLIENT_RESTART_REQUEST_MIN_REMAINING_MS + 5_000;
|
|
28
|
+
const SERVICE_RESTART_TIMEOUT_MS = 150_000;
|
|
29
|
+
const VERSION_PROBE_TIMEOUT_MS = 20_000;
|
|
30
|
+
|
|
31
|
+
export function parseHeadlessArgs(args: readonly string[]): { ok: true; check: boolean; json: boolean } | { ok: false } {
|
|
32
|
+
let desktop = false, check = false, json = false;
|
|
33
|
+
for (const arg of args) {
|
|
34
|
+
if (arg === "--desktop" && !desktop) desktop = true;
|
|
35
|
+
else if (arg === "--check" && !check) check = true;
|
|
36
|
+
else if (arg === "--json" && !json) json = true;
|
|
37
|
+
else return { ok: false };
|
|
38
|
+
}
|
|
39
|
+
return desktop ? { ok: true, check, json } : { ok: false };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `opencodex <version>` from a bounded `--version` run of the installed executable. */
|
|
43
|
+
export function parseVersionOutput(output: string): string | null {
|
|
44
|
+
const match = /^opencodex (\S+)\s*$/m.exec(output);
|
|
45
|
+
return match ? match[1]! : null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function readInstalledVersion(ocxExe: string): Promise<string | null> {
|
|
49
|
+
try {
|
|
50
|
+
const child = Bun.spawn([ocxExe, "--version"], {
|
|
51
|
+
stdin: "ignore", stdout: "pipe", stderr: "ignore", windowsHide: true, timeout: VERSION_PROBE_TIMEOUT_MS,
|
|
52
|
+
});
|
|
53
|
+
const [output, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
|
|
54
|
+
return code === 0 ? parseVersionOutput(output.slice(0, 4096)) : null;
|
|
55
|
+
} catch {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The installed CLI's own `ocx stop --json`, as the app's update drain runs it. */
|
|
61
|
+
async function drainRuntime(install: WindowsDesktopInstall): Promise<{ ok: boolean; detail?: string }> {
|
|
62
|
+
try {
|
|
63
|
+
const child = Bun.spawn([install.ocxExe, "stop", "--json"], {
|
|
64
|
+
stdin: "ignore", stdout: "pipe", stderr: "ignore", windowsHide: true, timeout: DRAIN_DEADLINE_MS + 10_000,
|
|
65
|
+
env: { ...process.env, [DRAIN_STOP_DEADLINE_ENV]: String(DRAIN_DEADLINE_MS - 3_000) },
|
|
66
|
+
});
|
|
67
|
+
const [output, code] = await Promise.all([new Response(child.stdout).text(), child.exited]);
|
|
68
|
+
return parseDrainResult(output.slice(-65_536), code);
|
|
69
|
+
} catch {
|
|
70
|
+
return { ok: false, detail: "the installed ocx stop could not run" };
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function desktopSupervisor(pid: number): string | null {
|
|
75
|
+
const evidence = inspectDesktopSupervision({ targetPid: pid });
|
|
76
|
+
return evidence.kind === "desktop" && evidence.runtimePid === pid ? evidence.app : null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The installed CLI's `ocx service restart`, which confirms a different serving pid or exits 1. */
|
|
80
|
+
async function restartService(install: WindowsDesktopInstall): Promise<{ ok: boolean; detail?: string }> {
|
|
81
|
+
try {
|
|
82
|
+
const child = Bun.spawn([install.ocxExe, "service", "restart"], {
|
|
83
|
+
stdin: "ignore", stdout: "ignore", stderr: "pipe", windowsHide: true, timeout: SERVICE_RESTART_TIMEOUT_MS,
|
|
84
|
+
});
|
|
85
|
+
const [errors, code] = await Promise.all([new Response(child.stderr).text(), child.exited]);
|
|
86
|
+
if (code === 0) return { ok: true };
|
|
87
|
+
return { ok: false, detail: serviceRestartFailureDetail(errors.slice(-65_536), code) };
|
|
88
|
+
} catch {
|
|
89
|
+
return { ok: false, detail: "the installed ocx service restart could not run" };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function print(result: HeadlessResult, json: boolean): void {
|
|
94
|
+
if (json) {
|
|
95
|
+
console.log(JSON.stringify(result));
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const line = result.message;
|
|
99
|
+
if (result.exitCode === HEADLESS_EXIT.ok) console.log(`✅ ${line}`);
|
|
100
|
+
else console.error(`❌ ${line}`);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export async function runHeadlessDesktopUpdateCommand(args: readonly string[]): Promise<number> {
|
|
104
|
+
const parsed = parseHeadlessArgs(args);
|
|
105
|
+
if (!parsed.ok) {
|
|
106
|
+
console.error(HEADLESS_USAGE);
|
|
107
|
+
return HEADLESS_EXIT.usage;
|
|
108
|
+
}
|
|
109
|
+
const install = windowsDesktopInstall();
|
|
110
|
+
if (!install) {
|
|
111
|
+
console.error("ocx update --desktop updates a Windows OpenCodex Desktop installation and must be run with that installation's ocx.exe "
|
|
112
|
+
+ "(next to opencodex-desktop.exe). On other installations use 'ocx update', or the app's own updater (tray → Check for Updates).");
|
|
113
|
+
return HEADLESS_EXIT.usage;
|
|
114
|
+
}
|
|
115
|
+
const log = (line: string) => (parsed.json ? console.error : console.log)(line);
|
|
116
|
+
let mutex: ReturnType<typeof tryAcquireUpdateSyncMutex> | null = null;
|
|
117
|
+
if (!parsed.check) {
|
|
118
|
+
mutex = tryAcquireUpdateSyncMutex(getConfigDir(), "update");
|
|
119
|
+
if (mutex.kind === "busy") {
|
|
120
|
+
console.error(`opencodex: another ${mutex.holder === "sync" ? "sync" : "update"} is in progress for this home; retry when it finishes.`);
|
|
121
|
+
return HEADLESS_EXIT.unchanged;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
const result = await runHeadlessDesktopUpdate({ check: parsed.check }, {
|
|
126
|
+
install,
|
|
127
|
+
currentVersion: packageVersion(),
|
|
128
|
+
fetch: (url, maxBytes) => acquireBounded(url, { maxBytes }, { transport: fetchAcquireTransport, timers: realAcquireTimers }),
|
|
129
|
+
staging: {
|
|
130
|
+
create: () => createStagingDirectory(windowsStagingDeps),
|
|
131
|
+
write: (path, bytes) => writeFileSync(path, bytes, { flag: "wx", mode: 0o600 }),
|
|
132
|
+
read: path => new Uint8Array(readFileSync(path)),
|
|
133
|
+
join: (dir, name) => join(dir, name),
|
|
134
|
+
discard: (dir, keep) => {
|
|
135
|
+
if (!keep.length) { rmSync(dir, { recursive: true, force: true }); return; }
|
|
136
|
+
for (const name of readdirSync(dir)) {
|
|
137
|
+
const path = join(dir, name);
|
|
138
|
+
if (!keep.includes(path)) rmSync(path, { force: true });
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
},
|
|
142
|
+
...ownImageMover(install),
|
|
143
|
+
msiexecPath: () => win32.join(trustedWindowsSystemDirectory(), "msiexec.exe"),
|
|
144
|
+
spawnInstaller: (file, installerArgs) => {
|
|
145
|
+
const child = Bun.spawn([file, ...installerArgs], { stdin: "ignore", stdout: "ignore", stderr: "ignore", windowsHide: true });
|
|
146
|
+
return { exited: child.exited };
|
|
147
|
+
},
|
|
148
|
+
timers: realAcquireTimers,
|
|
149
|
+
readInstalledVersion,
|
|
150
|
+
runtime: {
|
|
151
|
+
findLive: () => findLiveProxy(),
|
|
152
|
+
runtimeImage: pid => windowsProcessPair(pid).child?.exe ?? null,
|
|
153
|
+
requestRestart: (live, targetVersion) => requestBoundSystemRestart(live, Date.now() + RESTART_REQUEST_WINDOW_MS,
|
|
154
|
+
{ cliVersion: targetVersion, respawnRunsInstalledImage: true }),
|
|
155
|
+
desktopSupervisor,
|
|
156
|
+
drainRuntime: () => drainRuntime(install),
|
|
157
|
+
restartService: () => restartService(install),
|
|
158
|
+
now: Date.now,
|
|
159
|
+
wait: ms => Bun.sleep(ms),
|
|
160
|
+
},
|
|
161
|
+
log,
|
|
162
|
+
});
|
|
163
|
+
print(result, parsed.json);
|
|
164
|
+
return result.exitCode;
|
|
165
|
+
} finally {
|
|
166
|
+
if (mutex?.kind === "acquired") mutex.release();
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading the installed CLI's `ocx stop --json` result for the headless Desktop updater (#8246).
|
|
3
|
+
*
|
|
4
|
+
* The same acceptance the Desktop app applies to its own drain (`desktop/src-tauri/src/runtime_stop.rs`):
|
|
5
|
+
* the `ocx-stop/1` document and the process exit code must agree that this home's runtime is down.
|
|
6
|
+
* Exit 79 (history cleanup incomplete) still stopped the runtime; everything else is a failure.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** The app's Windows drain budget; the CLI receives it as OCX_STOP_DEADLINE_MS. */
|
|
10
|
+
export const DRAIN_DEADLINE_MS = 75_000;
|
|
11
|
+
export const DRAIN_STOP_DEADLINE_ENV = "OCX_STOP_DEADLINE_MS";
|
|
12
|
+
|
|
13
|
+
export function parseDrainResult(stdout: string, exitCode: number | null): { ok: boolean; detail?: string } {
|
|
14
|
+
const line = stdout.split(/\r?\n/).map(text => text.trim()).filter(text => text.startsWith("{")).at(-1);
|
|
15
|
+
let summary: Record<string, unknown> | null = null;
|
|
16
|
+
try { summary = line ? JSON.parse(line) as Record<string, unknown> : null; } catch { summary = null; }
|
|
17
|
+
if (!summary || summary.schema !== "ocx-stop/1") {
|
|
18
|
+
return { ok: false, detail: `unreadable stop result (exit ${exitCode ?? "none"})` };
|
|
19
|
+
}
|
|
20
|
+
const proxyDown = summary.proxy === "stopped" || summary.proxy === "stopped-orphan";
|
|
21
|
+
const stopped = exitCode === 0 && summary.ok === true && summary.exitCode === 0 && summary.runtimeDown === true
|
|
22
|
+
&& ((summary.outcome === "stopped" && proxyDown) || (summary.outcome === "not-running" && summary.proxy === "not-running"));
|
|
23
|
+
const historyOnly = exitCode === 79 && summary.exitCode === 79 && summary.outcome === "history-incomplete"
|
|
24
|
+
&& summary.runtimeDown === true && proxyDown;
|
|
25
|
+
if (stopped || historyOnly) return { ok: true };
|
|
26
|
+
const message = typeof summary.message === "string" ? `: ${summary.message.slice(0, 200)}` : "";
|
|
27
|
+
return { ok: false, detail: `${String(summary.outcome)}/${String(summary.proxy)} exit ${exitCode ?? "none"}${message}` };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The reason `ocx service restart` gives for not restarting: its first warning or error line,
|
|
32
|
+
* which names the cause, rather than the trailing log path. Bounded; emoji markers dropped.
|
|
33
|
+
*/
|
|
34
|
+
export function serviceRestartFailureDetail(stderr: string, exitCode: number | null): string {
|
|
35
|
+
const lines = stderr.split(/\r?\n/).map(line => line.trim()).filter(Boolean);
|
|
36
|
+
const marker = /^(?:\u26a0\ufe0f|\u26a0|\u274c)\s*/u;
|
|
37
|
+
const reason = lines.find(line => marker.test(line)) ?? lines.find(line => !/^(?:Log|Diagnostics):/i.test(line));
|
|
38
|
+
const text = reason?.replace(marker, "").slice(0, 400);
|
|
39
|
+
return `exit ${exitCode ?? "none"}${text ? `: ${text}` : ""}`;
|
|
40
|
+
}
|