@bitkyc08/opencodex 2.95.0 → 2.97.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ocx.mjs +214 -19
- package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
- package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
- package/gui/dist/assets/index-CynE_Rue.js +94 -0
- package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/kiro/stream.ts +63 -4
- package/src/adapters/kiro-constants.ts +15 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/ollama-native.ts +21 -7
- package/src/adapters/openai-responses/canonical-forward.ts +50 -13
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/passthrough.ts +8 -8
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/openai-responses/transport.ts +17 -26
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/qoder/adapter.ts +1 -1
- package/src/adapters/qoder/image-input.ts +5 -2
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/outbound.ts +49 -2
- package/src/cli/agent.ts +44 -15
- package/src/cli/capabilities-agents-routing.ts +9 -0
- package/src/cli/capabilities-base.ts +25 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +5 -4
- package/src/cli/dispatch.ts +11 -176
- package/src/cli/ensure-desired-integrations.ts +4 -3
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +9 -2
- package/src/cli/link.ts +1 -1
- package/src/cli/message-command.ts +2 -1
- package/src/cli/message-mcp-command.ts +29 -0
- package/src/cli/registry.ts +12 -4
- package/src/cli/root.ts +8 -0
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +150 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/client/connect.ts +31 -14
- package/src/client/link-home.ts +3 -2
- package/src/client/machine-listener.ts +3 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/account-store.ts +1 -0
- package/src/codex/auth-context-provider.ts +15 -0
- package/src/codex/auth-context.ts +59 -122
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +6 -8
- package/src/codex/forward-transport-headers.ts +65 -36
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/installation-id.ts +72 -0
- package/src/codex/lineage.ts +13 -7
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/process-state.ts +5 -0
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/generated/compatibility-version.json +496 -192
- package/src/grok/sync.ts +10 -1
- package/src/images/loop.ts +2 -1
- package/src/lib/client-error-body.ts +184 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership.ts +4 -0
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/desktop-cli-handoff.d.mts +1 -1
- package/src/lib/desktop-cli-handoff.mjs +11 -1
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +14 -11
- package/src/lib/windows-owner-acl.ts +13 -6
- package/src/lib/windows-secret-acl.ts +2 -2
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/messaging/mcp-queue-rpc.ts +102 -0
- package/src/messaging/mcp-queue-server.ts +42 -0
- package/src/messaging/mcp-queue-tools.ts +39 -0
- package/src/oauth/anthropic-identity.ts +2 -6
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +41 -74
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +1 -1
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +4 -0
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/trace.ts +18 -0
- package/src/providers/anthropic-subscription.ts +25 -0
- package/src/providers/claude-cli-usage.ts +15 -67
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/quota/anthropic-decision-windows.ts +5 -19
- package/src/providers/quota/anthropic-usage-windows.ts +65 -0
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/request-pacing.ts +3 -2
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/parser-tools.ts +1 -0
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/responses/schema.ts +5 -2
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +56 -0
- package/src/server/audio-dictation.ts +3 -0
- package/src/server/audio-live.ts +8 -2
- package/src/server/audio-upstream.ts +2 -0
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +57 -27
- package/src/server/context-history.ts +14 -7
- package/src/server/images.ts +14 -5
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/live-sideband.ts +16 -2
- package/src/server/index/ollama-routes.ts +89 -0
- package/src/server/index/serve-options.ts +22 -4
- package/src/server/index/websocket-handler.ts +5 -3
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +4 -2
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/live.ts +30 -5
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/route-registry.ts +1 -1
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +1 -1
- package/src/server/messages-native.ts +12 -7
- package/src/server/messages-shared.ts +6 -2
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +79 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +9 -4
- package/src/server/responses/adapter-delivery.ts +5 -4
- package/src/server/responses/adapter-dispatch.ts +36 -30
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +22 -17
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/combo-required-tool-contract.ts +24 -12
- package/src/server/responses/compact.ts +89 -41
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +34 -12
- package/src/server/responses/core-combo-failure.ts +5 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +51 -33
- package/src/server/responses/core-errors.ts +22 -20
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +8 -1
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-build-error.ts +36 -0
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +26 -39
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +67 -48
- package/src/server/responses/request-sidecar-auth.ts +3 -1
- package/src/server/responses/request-transport.ts +35 -31
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/search.ts +13 -4
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/server/ws-bridge.ts +5 -2
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/types/config.ts +2 -0
- package/src/update/index.ts +133 -25
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +60 -27
- package/src/vision/describe.ts +4 -7
- package/src/web-search/executor.ts +4 -7
- package/src/web-search/loop.ts +31 -5
- package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import type { ChildProcess } from "node:child_process";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { packageVersion } from "../lib/package-version";
|
|
7
|
+
import { getConfigDir } from "../config/paths";
|
|
8
|
+
import { readConfigDiagnostics } from "../config";
|
|
9
|
+
import { resolveServiceOwnership } from "../service/state";
|
|
10
|
+
import type { ServiceOwnershipResolution } from "../service/state";
|
|
11
|
+
import { inspectDesktopSupervision, type SupervisionEvidence } from "../service/desktop-supervision.mjs";
|
|
12
|
+
import { diagnoseService } from "../service/diagnostics";
|
|
13
|
+
import { detectInstallOwnership, defaultUpdateTag, latestVersion } from "./index";
|
|
14
|
+
import { parseOrchestratedUpdateArgs, type OrchestratedUpdateArgs } from "./orchestrated-arguments.mjs";
|
|
15
|
+
import { buildOrchestratedPlan, type PlanInputs } from "./orchestrated-plan";
|
|
16
|
+
import { inspectLiveOrchestratedIdentity } from "./orchestrated-live-identity";
|
|
17
|
+
import type { ServingIdentity } from "./orchestrated-identity";
|
|
18
|
+
import { planUpdateRuntimeHandling } from "./runtime-ownership.mjs";
|
|
19
|
+
import { isUpdateInFlight } from "./sync-update-mutex";
|
|
20
|
+
import { createOrchestratedResultChannel, encodeOrchestratedExpect, type OrchestratedExpect } from "./orchestrated-session.mjs";
|
|
21
|
+
import { waitForOrchestratedChild } from "./orchestrated-child.mjs";
|
|
22
|
+
import { classifyOrchestratedOutcome, type Outcome } from "./orchestrated-outcome.mjs";
|
|
23
|
+
import { verifyOrchestratedInstall } from "./orchestrated-tree.mjs";
|
|
24
|
+
import { decideOrchestratedApply } from "./orchestrated-admission.mjs";
|
|
25
|
+
import { createUpdatePlanToken } from "./orchestrated-token.mjs";
|
|
26
|
+
import { selfLaunchArgv } from "../lib/self-launch-argv";
|
|
27
|
+
import { proxyIdentityAt } from "../server/proxy-liveness";
|
|
28
|
+
import { probeSpawn, probeSpawnSync } from "./mutation-guard.mjs";
|
|
29
|
+
|
|
30
|
+
type Request = Extract<OrchestratedUpdateArgs, { ok: true }>;
|
|
31
|
+
type DetectedInstaller = PlanInputs["installer"] | "standalone";
|
|
32
|
+
export interface OrchestratedPlanDeps {
|
|
33
|
+
install(): { installer: DetectedInstaller; cliRoot: string; desktopPath: boolean };
|
|
34
|
+
currentVersion(): string;
|
|
35
|
+
identity(): Promise<ServingIdentity>;
|
|
36
|
+
ownership(identity: ServingIdentity): { runtimeOwner: PlanInputs["runtimeOwner"]; permits: boolean };
|
|
37
|
+
target(selector: string, installer: PlanInputs["installer"]): string | null;
|
|
38
|
+
inFlight(): boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function classifyPlanRuntimeOwner(identity: ServingIdentity, owner: ServiceOwnershipResolution,
|
|
42
|
+
supervision: SupervisionEvidence, serviceInstalled: boolean | null): { runtimeOwner: PlanInputs["runtimeOwner"]; permits: boolean } {
|
|
43
|
+
const policy = planUpdateRuntimeHandling({ ownership: owner.kind === "owned" ? owner.ownership : null,
|
|
44
|
+
ownershipUnknown: owner.kind === "unknown", serviceInstalled: serviceInstalled === true, supervision });
|
|
45
|
+
const desktop = supervision.kind === "desktop" || (owner.kind === "owned" && owner.ownership.owner !== "cli");
|
|
46
|
+
const uncertain = owner.kind === "unknown" || supervision.kind === "unknown" || supervision.kind === "unsupported" || serviceInstalled === null;
|
|
47
|
+
const identityUnknown = identity.kind !== "live" && identity.kind !== "absent";
|
|
48
|
+
const runtimeOwner = uncertain ? "unknown" : desktop ? "desktop-app" : identityUnknown ? "unknown" : identity.kind === "absent" ? "none"
|
|
49
|
+
: serviceInstalled && owner.kind === "owned" && owner.ownership.owner === "cli" ? "service" : "unmanaged";
|
|
50
|
+
return { runtimeOwner, permits: !uncertain && !identityUnknown && policy.mayReplacePackage };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const defaultDeps: OrchestratedPlanDeps = {
|
|
54
|
+
install() {
|
|
55
|
+
const installer = detectInstallOwnership().installer;
|
|
56
|
+
const path = installer === "standalone" ? process.execPath : resolve(dirname(fileURLToPath(import.meta.url)), "../..");
|
|
57
|
+
return { installer, cliRoot: realpathSync.native(path), desktopPath: /(?:[\\/]\.opencodex-desktop[\\/]|\.app[\\/]Contents[\\/])/i.test(path) };
|
|
58
|
+
},
|
|
59
|
+
currentVersion: packageVersion,
|
|
60
|
+
async identity() {
|
|
61
|
+
const config = readConfigDiagnostics({ passive: true });
|
|
62
|
+
if (config.source === "fallback") return { kind: "unknown" };
|
|
63
|
+
return inspectLiveOrchestratedIdentity(getConfigDir(), { port: config.config.port ?? 10100, hostname: config.config.hostname });
|
|
64
|
+
},
|
|
65
|
+
ownership(identity) {
|
|
66
|
+
const owner = resolveServiceOwnership();
|
|
67
|
+
const supervision = identity.kind === "live" ? inspectDesktopSupervision({ targetPid: identity.runtime.pid }) : { kind: "none" as const };
|
|
68
|
+
let serviceInstalled: boolean | null = false;
|
|
69
|
+
if (identity.kind === "live" && owner.kind === "owned" && owner.ownership.owner === "cli") {
|
|
70
|
+
const service = diagnoseService();
|
|
71
|
+
serviceInstalled = service.supported && !service.conflict ? service.installed : null;
|
|
72
|
+
}
|
|
73
|
+
return classifyPlanRuntimeOwner(identity, owner, supervision, serviceInstalled);
|
|
74
|
+
},
|
|
75
|
+
target: (selector, installer) => {
|
|
76
|
+
if (!["npm", "pnpm", "bun"].includes(installer)) return null;
|
|
77
|
+
const cache = mkdtempSync(join(tmpdir(), "ocx-registry-probe-"));
|
|
78
|
+
const overrides = { npm_config_cache: cache, npm_config_logs_dir: join(cache, "logs"), npm_config_logs_max: "0",
|
|
79
|
+
npm_config_update_notifier: "false", pnpm_config_cache_dir: join(cache, "pnpm-cache"),
|
|
80
|
+
npm_config_cache_dir: join(cache, "pnpm-cache"), npm_config_store_dir: join(cache, "pnpm-store"),
|
|
81
|
+
pnpm_config_store_dir: join(cache, "pnpm-store"), pnpm_config_state_dir: join(cache, "pnpm-state"),
|
|
82
|
+
BUN_INSTALL_CACHE_DIR: join(cache, "bun-cache"), XDG_CACHE_HOME: join(cache, "xdg-cache"), XDG_STATE_HOME: join(cache, "xdg-state") };
|
|
83
|
+
const keys = new Set(Object.keys(overrides).map(key => key.toLowerCase()));
|
|
84
|
+
const env = { ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !keys.has(key.toLowerCase()))), ...overrides };
|
|
85
|
+
try { return latestVersion(selector, installer as "npm" | "pnpm" | "bun", undefined, probeSpawnSync, env); }
|
|
86
|
+
finally { rmSync(cache, { recursive: true, force: true }); }
|
|
87
|
+
},
|
|
88
|
+
inFlight: () => isUpdateInFlight(getConfigDir()),
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
/** Passive identity and plan-bound fields for a Node update child. */
|
|
92
|
+
export async function inspectNodeOrchestratedIdentity(cliRoot: string, targetVersion?: string, installer?: "npm" | "pnpm") {
|
|
93
|
+
const root = realpathSync.native(cliRoot);
|
|
94
|
+
const identity = await defaultDeps.identity();
|
|
95
|
+
if (!targetVersion || !installer) return { ...identity, cliRoot: root };
|
|
96
|
+
const ownership = defaultDeps.ownership(identity);
|
|
97
|
+
const live = identity.kind === "live" ? identity : null;
|
|
98
|
+
const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as { version?: unknown };
|
|
99
|
+
if (typeof manifest.version !== "string") throw new Error("invalid package version");
|
|
100
|
+
return { ...identity, cliRoot: root, permits: ownership.permits, planToken: createUpdatePlanToken({
|
|
101
|
+
currentVersion: manifest.version, targetVersion, installer, cliRoot: root,
|
|
102
|
+
servingRoot: live?.servingRoot ?? null, runtimeOwner: ownership.runtimeOwner, runtime: live?.runtime ?? null,
|
|
103
|
+
}) };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function verifyOrchestratedChildIdentity(expected: OrchestratedExpect, targetVersion: string): Promise<boolean> {
|
|
107
|
+
if (getConfigDir() !== expected.home) return false;
|
|
108
|
+
const install = defaultDeps.install();
|
|
109
|
+
const identity = await defaultDeps.identity();
|
|
110
|
+
if (install.installer !== "bun" || install.cliRoot !== expected.cliRoot || (identity.kind !== "live" && identity.kind !== "absent")) return false;
|
|
111
|
+
const live = identity.kind === "live" ? identity : null;
|
|
112
|
+
if ((live?.servingRoot ?? null) !== expected.servingRoot || (live?.runtime.pid ?? null) !== expected.runtimePid) return false;
|
|
113
|
+
const ownership = defaultDeps.ownership(identity);
|
|
114
|
+
return ownership.permits && createUpdatePlanToken({ currentVersion: defaultDeps.currentVersion(), targetVersion,
|
|
115
|
+
installer: install.installer, cliRoot: install.cliRoot, servingRoot: live?.servingRoot ?? null,
|
|
116
|
+
runtimeOwner: ownership.runtimeOwner, runtime: live?.runtime ?? null }) === expected.planToken;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Observe first, then classify; failures never become permission to update. */
|
|
120
|
+
export async function observeOrchestratedPlan(request: Request, deps: OrchestratedPlanDeps = defaultDeps) {
|
|
121
|
+
let install: ReturnType<OrchestratedPlanDeps["install"]> = { installer: "unknown", cliRoot: process.execPath, desktopPath: false };
|
|
122
|
+
let currentVersion = "unknown", targetVersion: string | null = null, identity: ServingIdentity = { kind: "unknown" };
|
|
123
|
+
let runtimeOwner: PlanInputs["runtimeOwner"] = "unknown", permits = false, unavailable = false, updateInFlight = true;
|
|
124
|
+
try { install = deps.install(); currentVersion = deps.currentVersion(); } catch { unavailable = true; }
|
|
125
|
+
try { updateInFlight = deps.inFlight(); } catch { /* indeterminate means in flight */ }
|
|
126
|
+
try { identity = await deps.identity(); } catch { unavailable = true; }
|
|
127
|
+
try { const owner = deps.ownership(identity); runtimeOwner = owner.runtimeOwner; permits = owner.permits; } catch { runtimeOwner = "unknown"; }
|
|
128
|
+
const installer = install.installer === "standalone" ? (install.desktopPath || runtimeOwner === "desktop-app" ? "desktop-app" : "unknown") : install.installer;
|
|
129
|
+
try {
|
|
130
|
+
const selector = request.version ?? request.tag ?? defaultUpdateTag(currentVersion);
|
|
131
|
+
const resolved = deps.target(selector, installer);
|
|
132
|
+
targetVersion = request.version && resolved !== request.version ? null : resolved;
|
|
133
|
+
} catch { targetVersion = null; }
|
|
134
|
+
const plan = buildOrchestratedPlan({ currentVersion, targetVersion, installer, runtimeOwner, cliRoot: install.cliRoot,
|
|
135
|
+
identity, ownershipPermits: permits, updateInFlight });
|
|
136
|
+
return unavailable ? { ...plan, canApply: false, reason: "plan-unavailable" as const } : plan;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export { decideOrchestratedApply } from "./orchestrated-admission.mjs";
|
|
140
|
+
|
|
141
|
+
type Plan = Awaited<ReturnType<typeof observeOrchestratedPlan>>;
|
|
142
|
+
type BunDriverDeps = {
|
|
143
|
+
home: string;
|
|
144
|
+
identity: () => Promise<ServingIdentity>;
|
|
145
|
+
now: () => number;
|
|
146
|
+
spawn: (exe: string, args: string[], options: { env: Record<string, string | undefined>; stdio: ["ignore", number, number] }) => ChildProcess;
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
/** The parent owns stdout and verifies the child-reported outcome independently. */
|
|
150
|
+
export async function applyOrchestratedBun(plan: Plan, request: Request, deps: BunDriverDeps) {
|
|
151
|
+
const base = { fromVersion: plan.currentVersion, toVersion: plan.targetVersion, installer: plan.installer,
|
|
152
|
+
childExited: false, childExitCode: null, outcome: null, previousVerified: false, targetVerified: false, runtimeHealthy: false, restarted: false } as const;
|
|
153
|
+
const uncertain = () => classifyOrchestratedOutcome(base);
|
|
154
|
+
let channel: ReturnType<typeof createOrchestratedResultChannel> | undefined;
|
|
155
|
+
let childStarted = false, childEverStarted = false;
|
|
156
|
+
try {
|
|
157
|
+
const before = await deps.identity();
|
|
158
|
+
const live = before.kind === "live" ? before : null;
|
|
159
|
+
const token = createUpdatePlanToken({ currentVersion: plan.currentVersion, targetVersion: plan.targetVersion,
|
|
160
|
+
installer: plan.installer, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null,
|
|
161
|
+
runtimeOwner: plan.runtimeOwner, runtime: live?.runtime ?? null });
|
|
162
|
+
if ((before.kind !== "live" && before.kind !== "absent") || token !== plan.planToken || !plan.targetVersion) {
|
|
163
|
+
return { exitCode: 10 as const, result: { ...uncertain().result, error: "plan-changed" } };
|
|
164
|
+
}
|
|
165
|
+
const started = deps.now();
|
|
166
|
+
channel = createOrchestratedResultChannel();
|
|
167
|
+
const expect = encodeOrchestratedExpect({ home: deps.home, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null,
|
|
168
|
+
runtimePid: live?.runtime.pid ?? null, planToken: plan.planToken });
|
|
169
|
+
const args = ["update", "--version", plan.targetVersion, "--orchestrated-expect", expect, "--orchestrated-result", channel.resultPath,
|
|
170
|
+
...(request.notAfter === undefined ? [] : ["--not-after", String(request.notAfter)])];
|
|
171
|
+
const child = deps.spawn(process.execPath, selfLaunchArgv(args), { env: { ...process.env, OCX_UPDATE_ORCHESTRATED_CHILD: "1", OCX_UPDATE_RESULT_CAPABILITY: channel.capability }, stdio: ["ignore", 2, 2] });
|
|
172
|
+
childStarted = true; childEverStarted = true;
|
|
173
|
+
const waited = await waitForOrchestratedChild(child, { overrunMs: (request.notAfter ?? started) + plan.mutationBoundMs - deps.now() });
|
|
174
|
+
if (!waited.confirmed) {
|
|
175
|
+
child.unref();
|
|
176
|
+
if (waited.reason === "overrun") return { exitCode: 12 as const, result: { ...uncertain().result, error: "overrun" } };
|
|
177
|
+
return uncertain();
|
|
178
|
+
}
|
|
179
|
+
childStarted = false;
|
|
180
|
+
const outcome = channel.read() as Outcome | null;
|
|
181
|
+
const activeRoot = outcome?.phase === "installed" ? outcome.activeRoot : plan.cliPath;
|
|
182
|
+
const targetVerified = outcome?.phase === "installed" && activeRoot === plan.cliPath
|
|
183
|
+
&& verifyOrchestratedInstall(activeRoot, plan.targetVersion, "bun");
|
|
184
|
+
const previousVerified = verifyOrchestratedInstall(plan.cliPath, plan.currentVersion, "bun");
|
|
185
|
+
let runtimeHealthy = !plan.restartRequired, restarted = false;
|
|
186
|
+
if (plan.restartRequired) {
|
|
187
|
+
try {
|
|
188
|
+
const after = await deps.identity();
|
|
189
|
+
if (after.kind === "live" && after.servingRoot === activeRoot) {
|
|
190
|
+
const health = await proxyIdentityAt(after.runtime.port, { hostname: after.runtime.hostname, expectedPid: after.runtime.pid });
|
|
191
|
+
runtimeHealthy = health?.version === (outcome?.phase === "installed" ? plan.targetVersion : plan.currentVersion);
|
|
192
|
+
restarted = after.runtime.pid !== live?.runtime.pid;
|
|
193
|
+
}
|
|
194
|
+
} catch {
|
|
195
|
+
return { exitCode: 12 as const, result: { ...uncertain().result, applied: targetVerified, error: "runtime-unverified" } };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return classifyOrchestratedOutcome({ ...base, childExited: true, childExitCode: waited.code, outcome,
|
|
199
|
+
previousVerified, targetVerified, runtimeHealthy, restarted });
|
|
200
|
+
} catch {
|
|
201
|
+
if (childEverStarted) return uncertain();
|
|
202
|
+
return { exitCode: 10 as const, result: { ...uncertain().result, error: "plan-unavailable" } };
|
|
203
|
+
} finally {
|
|
204
|
+
if (channel && !childStarted) channel.dispose();
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export async function runOrchestratedUpdate(argv: string[]): Promise<number> {
|
|
209
|
+
const parsed = parseOrchestratedUpdateArgs(argv);
|
|
210
|
+
if (!parsed.ok) {
|
|
211
|
+
console.log(JSON.stringify({ error: "usage" }));
|
|
212
|
+
console.error("Usage: ocx update (--plan | --yes) --json [--tag latest|preview | --version <version>]");
|
|
213
|
+
return 64;
|
|
214
|
+
}
|
|
215
|
+
const plan = await observeOrchestratedPlan(parsed);
|
|
216
|
+
if (parsed.mode === "plan") {
|
|
217
|
+
console.log(JSON.stringify(plan));
|
|
218
|
+
return 0;
|
|
219
|
+
}
|
|
220
|
+
const admission = decideOrchestratedApply(plan, parsed, Date.now());
|
|
221
|
+
if (admission.kind === "done") {
|
|
222
|
+
console.log(JSON.stringify(admission.result));
|
|
223
|
+
return admission.exitCode;
|
|
224
|
+
}
|
|
225
|
+
if (plan.installer === "bun") {
|
|
226
|
+
const result = await applyOrchestratedBun(plan, parsed, { home: getConfigDir(), identity: defaultDeps.identity,
|
|
227
|
+
now: Date.now, spawn: (exe, args, options) => probeSpawn(exe, args, options) });
|
|
228
|
+
console.log(JSON.stringify(result.result));
|
|
229
|
+
return result.exitCode;
|
|
230
|
+
}
|
|
231
|
+
console.log(JSON.stringify({ schema: "ocx.update.result/1", applied: false, fromVersion: plan.currentVersion,
|
|
232
|
+
toVersion: null, installer: plan.installer, restarted: false, healthy: false, rolledBack: false, error: plan.reason ?? "plan-unavailable" }));
|
|
233
|
+
return 10;
|
|
234
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { dirname, resolve } from "node:path";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { inspectNodeOrchestratedIdentity } from "./orchestrated-entry";
|
|
4
|
+
import { proxyIdentityAt } from "../server/proxy-liveness";
|
|
5
|
+
|
|
6
|
+
// A direct Bun entry keeps the probe outside ordinary CLI startup and repair paths.
|
|
7
|
+
export async function runIdentityProbe(args: string[], cliRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../..")) {
|
|
8
|
+
if (args.length !== 1 || args[0] !== "__update-orchestrated-identity") return 1;
|
|
9
|
+
try {
|
|
10
|
+
const installer = process.env.OCX_IDENTITY_INSTALLER;
|
|
11
|
+
const target = process.env.OCX_IDENTITY_TARGET;
|
|
12
|
+
if ((installer || target) && (!(installer === "npm" || installer === "pnpm") || !target)) return 1;
|
|
13
|
+
const identity = await inspectNodeOrchestratedIdentity(cliRoot, target, installer as "npm" | "pnpm" | undefined);
|
|
14
|
+
const health = identity.kind === "live" ? await proxyIdentityAt(identity.runtime.port,
|
|
15
|
+
{ hostname: identity.runtime.hostname, expectedPid: identity.runtime.pid }) : null;
|
|
16
|
+
console.log(JSON.stringify({ ...identity, healthVersion: health?.version ?? null }));
|
|
17
|
+
return 0;
|
|
18
|
+
} catch { return 1; }
|
|
19
|
+
}
|
|
20
|
+
if (import.meta.main) process.exitCode = await runIdentityProbe(process.argv.slice(2), process.env.OCX_IDENTITY_CLI_ROOT);
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { dirname, isAbsolute, join } from "node:path";
|
|
2
|
+
import { isValidRuntimePortState, type RuntimePortState } from "../config/process-state";
|
|
3
|
+
import { isLocalAttestationSecret } from "../lib/local-management-attestation";
|
|
4
|
+
import type { HomeOwnershipProof } from "../server/proxy-liveness";
|
|
5
|
+
|
|
6
|
+
type RecordRead = { kind: "record"; raw: string } | { kind: "missing" } | { kind: "unreadable" };
|
|
7
|
+
type RuntimeIdentity = { pid: number; port: number; hostname: string; command: readonly string[] };
|
|
8
|
+
export type ServingIdentity =
|
|
9
|
+
| { kind: "unknown" | "absent" | "mismatch" }
|
|
10
|
+
| { kind: "live"; servingRoot: string; runtime: RuntimeIdentity };
|
|
11
|
+
|
|
12
|
+
export interface ServingIdentityDeps {
|
|
13
|
+
readRecord(): RecordRead;
|
|
14
|
+
prove(record: RuntimePortState): Promise<HomeOwnershipProof>;
|
|
15
|
+
probeConfigured(): Promise<"live" | "dead" | "unknown">;
|
|
16
|
+
legacyExecutableDiffers?(pid: number): Promise<boolean>;
|
|
17
|
+
realpath(path: string): string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A live listener is usable only when it attests the same record observed before and after. */
|
|
21
|
+
export async function inspectOrchestratedServingIdentity(deps: ServingIdentityDeps): Promise<ServingIdentity> {
|
|
22
|
+
try {
|
|
23
|
+
const first = deps.readRecord();
|
|
24
|
+
if (first.kind === "unreadable") return { kind: "unknown" };
|
|
25
|
+
if (first.kind === "missing") {
|
|
26
|
+
const endpoint = await deps.probeConfigured();
|
|
27
|
+
return endpoint === "dead" && deps.readRecord().kind === "missing" ? { kind: "absent" } : { kind: "unknown" };
|
|
28
|
+
}
|
|
29
|
+
const parsed: unknown = JSON.parse(first.raw);
|
|
30
|
+
if (!isValidRuntimePortState(parsed) || !isLocalAttestationSecret(parsed.attestationSecret)) return { kind: "unknown" };
|
|
31
|
+
if (await deps.prove(parsed) !== "proven") return { kind: "unknown" };
|
|
32
|
+
const after = deps.readRecord();
|
|
33
|
+
if (after.kind !== "record" || after.raw !== first.raw) return { kind: "unknown" };
|
|
34
|
+
const command: unknown = parsed.command;
|
|
35
|
+
if (command === undefined) {
|
|
36
|
+
return await deps.legacyExecutableDiffers?.(parsed.pid) ? { kind: "mismatch" } : { kind: "unknown" };
|
|
37
|
+
}
|
|
38
|
+
if (!Array.isArray(command) || command.length < 1 || command.length > 2 || !command.every(part => typeof part === "string" && isAbsolute(part))) return { kind: "unknown" };
|
|
39
|
+
let servingRoot: string;
|
|
40
|
+
if (command.length === 1) servingRoot = deps.realpath(command[0]);
|
|
41
|
+
else {
|
|
42
|
+
const source = command[1] as string;
|
|
43
|
+
const root = dirname(dirname(dirname(source)));
|
|
44
|
+
// Windows accepts both separators; only separators are equated, so dotted or doubled forms still fail.
|
|
45
|
+
const native = process.platform === "win32" ? source.replace(/\//g, "\\") : source;
|
|
46
|
+
if (join(root, "src", "cli", "index.ts") !== native) return { kind: "unknown" };
|
|
47
|
+
servingRoot = deps.realpath(root);
|
|
48
|
+
}
|
|
49
|
+
return { kind: "live", servingRoot, runtime: { pid: parsed.pid, port: parsed.port, hostname: parsed.hostname ?? "127.0.0.1", command } };
|
|
50
|
+
} catch {
|
|
51
|
+
return { kind: "unknown" };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
|
|
4
|
+
import { probeEndpointLiveness, proveLiveProxyOwnedByHome } from "../server/proxy-liveness";
|
|
5
|
+
import { processIdentity, procfs, windowsProcessPair } from "../service/desktop-supervision.mjs";
|
|
6
|
+
import { inspectOrchestratedServingIdentity } from "./orchestrated-identity";
|
|
7
|
+
|
|
8
|
+
function readRuntimeRecord(home: string): { kind: "record"; raw: string } | { kind: "missing" } | { kind: "unreadable" } {
|
|
9
|
+
const path = join(home, "runtime-port.json");
|
|
10
|
+
let observed = false, fd: number | undefined;
|
|
11
|
+
try {
|
|
12
|
+
const before = lstatSync(path);
|
|
13
|
+
observed = true;
|
|
14
|
+
if (!before.isFile() || before.size > 32_768) return { kind: "unreadable" };
|
|
15
|
+
fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
16
|
+
const opened = fstatSync(fd);
|
|
17
|
+
if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size) return { kind: "unreadable" };
|
|
18
|
+
const bytes = Buffer.alloc(32_769);
|
|
19
|
+
const count = readSync(fd, bytes, 0, bytes.length, 0);
|
|
20
|
+
if (count !== opened.size || count > 32_768) return { kind: "unreadable" };
|
|
21
|
+
const after = lstatSync(path);
|
|
22
|
+
if (before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs) return { kind: "unreadable" };
|
|
23
|
+
return { kind: "record", raw: new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, count)) };
|
|
24
|
+
} catch (error) {
|
|
25
|
+
return !observed && (error as NodeJS.ErrnoException).code === "ENOENT" ? { kind: "missing" } : { kind: "unreadable" };
|
|
26
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Read the specified home only; listener possession of its record key proves a live identity. */
|
|
30
|
+
export async function inspectLiveOrchestratedIdentity(home: string, configured: { port: number; hostname?: string }) {
|
|
31
|
+
assertNotRealHomeUnderTest(home);
|
|
32
|
+
return inspectOrchestratedServingIdentity({
|
|
33
|
+
readRecord: () => readRuntimeRecord(home),
|
|
34
|
+
realpath: path => realpathSync.native(path),
|
|
35
|
+
probeConfigured: () => probeEndpointLiveness(configured),
|
|
36
|
+
prove: record => proveLiveProxyOwnedByHome({ pid: record.pid, port: record.port, hostname: record.hostname, source: "runtime" }, { readRuntimeFn: () => record }),
|
|
37
|
+
legacyExecutableDiffers: async pid => {
|
|
38
|
+
try {
|
|
39
|
+
const executable = process.platform === "linux" ? procfs.exe(pid)
|
|
40
|
+
: process.platform === "darwin" ? processIdentity(pid)?.executable
|
|
41
|
+
: process.platform === "win32" ? windowsProcessPair(pid).child?.exe : undefined;
|
|
42
|
+
if (!executable) return false;
|
|
43
|
+
const key = (path: string) => process.platform === "win32" ? path.toLowerCase() : path;
|
|
44
|
+
return key(realpathSync.native(executable)) !== key(realpathSync.native(process.execPath));
|
|
45
|
+
} catch { return false; }
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import { decideOrchestratedApply } from "./orchestrated-admission.mjs";
|
|
3
|
+
import { createOrchestratedResultChannel, encodeOrchestratedExpect } from "./orchestrated-session.mjs";
|
|
4
|
+
import { createUpdatePlanToken } from "./orchestrated-token.mjs";
|
|
5
|
+
import { waitForOrchestratedChild } from "./orchestrated-child.mjs";
|
|
6
|
+
import { classifyOrchestratedOutcome } from "./orchestrated-outcome.mjs";
|
|
7
|
+
import { verifyOrchestratedInstall } from "./orchestrated-tree.mjs";
|
|
8
|
+
import { verifyOrchestratedPnpmInstall } from "./orchestrated-pnpm.mjs";
|
|
9
|
+
import { resolvePnpmGlobalOwner } from "./pnpm-global-install.mjs";
|
|
10
|
+
import { parseOrchestratedUpdateArgs } from "./orchestrated-arguments.mjs";
|
|
11
|
+
|
|
12
|
+
const BOUND = 900_000;
|
|
13
|
+
|
|
14
|
+
/** Parent retains stdout and independently verifies all child-reported effects. */
|
|
15
|
+
export async function applyNodeOrchestratedUpdate(request, deps) {
|
|
16
|
+
let started = false, exited = false, channel;
|
|
17
|
+
let plan;
|
|
18
|
+
const base = () => ({ fromVersion: plan?.currentVersion ?? deps.currentVersion, toVersion: plan?.targetVersion ?? null,
|
|
19
|
+
installer: deps.installer, childExited: false, childExitCode: null, outcome: null, previousVerified: false,
|
|
20
|
+
targetVerified: false, runtimeHealthy: false, restarted: false });
|
|
21
|
+
const uncertain = () => classifyOrchestratedOutcome(base());
|
|
22
|
+
const fail = error => ({ exitCode: 10, result: { ...uncertain().result, error } });
|
|
23
|
+
try {
|
|
24
|
+
const bun = deps.resolveBun();
|
|
25
|
+
if (!bun) return fail("plan-unavailable");
|
|
26
|
+
const p = deps.plan(bun, request.version, request.tag);
|
|
27
|
+
if (p.status !== 0 || p.error || p.signal || typeof p.stdout !== "string" || Buffer.byteLength(p.stdout) > 65536) return fail("plan-unavailable");
|
|
28
|
+
plan = JSON.parse(p.stdout);
|
|
29
|
+
const validVersion = version => typeof version === "string"
|
|
30
|
+
&& parseOrchestratedUpdateArgs(["--plan", "--json", "--version", version]).ok;
|
|
31
|
+
if (!plan || plan.schema !== "ocx.update.plan/1" || !validVersion(plan.currentVersion)
|
|
32
|
+
|| !(typeof plan.targetVersion === "string" || plan.targetVersion === null) || plan.installer !== deps.installer
|
|
33
|
+
|| typeof plan.cliPath !== "string" || realpathSync.native(plan.cliPath) !== realpathSync.native(deps.cliRoot)
|
|
34
|
+
|| typeof plan.canApply !== "boolean" || typeof plan.restartRequired !== "boolean"
|
|
35
|
+
|| (plan.targetVersion !== null && !validVersion(plan.targetVersion))
|
|
36
|
+
|| (plan.canApply && (!plan.targetVersion || plan.reason !== undefined))
|
|
37
|
+
|| (!plan.canApply && (typeof plan.reason !== "string" || !plan.reason))
|
|
38
|
+
|| !["service", "desktop-app", "unmanaged", "none", "unknown"].includes(plan.runtimeOwner)
|
|
39
|
+
|| !(plan.servingPath === null || typeof plan.servingPath === "string") || typeof plan.updateInFlight !== "boolean"
|
|
40
|
+
|| typeof plan.planToken !== "string" || !/^[A-Za-z0-9_-]{16,128}$/.test(plan.planToken)
|
|
41
|
+
|| plan.mutationBoundMs !== BOUND) throw Error("invalid plan");
|
|
42
|
+
const admission = decideOrchestratedApply(plan, request, Date.now());
|
|
43
|
+
if (admission.kind === "done") return admission;
|
|
44
|
+
const before = deps.identity(bun);
|
|
45
|
+
const live = before.kind === "live" ? before : null;
|
|
46
|
+
if ((before.kind !== "live" && before.kind !== "absent") || !plan.targetVersion
|
|
47
|
+
|| Boolean(live) !== plan.restartRequired || (live?.servingRoot ?? null) !== plan.servingPath
|
|
48
|
+
|| createUpdatePlanToken({ currentVersion: plan.currentVersion, targetVersion: plan.targetVersion,
|
|
49
|
+
installer: plan.installer, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null,
|
|
50
|
+
runtimeOwner: plan.runtimeOwner, runtime: live?.runtime ?? null }) !== plan.planToken) return fail("plan-changed");
|
|
51
|
+
let owner;
|
|
52
|
+
if (deps.installer === "pnpm") {
|
|
53
|
+
const resolved = resolvePnpmGlobalOwner({ packageName: "@bitkyc08/opencodex", packagePath: plan.cliPath,
|
|
54
|
+
commandPaths: deps.pnpmCommands, runningShimPath: deps.runningShimPath, runPnpm: deps.runPnpm });
|
|
55
|
+
if (!resolved.ok) return fail("plan-unavailable");
|
|
56
|
+
owner = resolved.owner;
|
|
57
|
+
}
|
|
58
|
+
const start = Date.now();
|
|
59
|
+
channel = createOrchestratedResultChannel();
|
|
60
|
+
const expect = encodeOrchestratedExpect({ home: deps.home, cliRoot: plan.cliPath, servingRoot: live?.servingRoot ?? null,
|
|
61
|
+
runtimePid: live?.runtime.pid ?? null, planToken: plan.planToken });
|
|
62
|
+
const args = [deps.launcher, "update", "--version", plan.targetVersion, "--orchestrated-expect", expect,
|
|
63
|
+
"--orchestrated-result", channel.resultPath, ...(request.notAfter === undefined ? [] : ["--not-after", String(request.notAfter)])];
|
|
64
|
+
const child = deps.spawn(process.execPath, args, { env: { ...process.env, OCX_UPDATE_ORCHESTRATED_CHILD: "1", OCX_UPDATE_RESULT_CAPABILITY: channel.capability }, stdio: ["ignore", 2, 2] });
|
|
65
|
+
started = true;
|
|
66
|
+
const waited = await waitForOrchestratedChild(child, { overrunMs: (request.notAfter ?? start) + BOUND - Date.now() });
|
|
67
|
+
if (!waited.confirmed) {
|
|
68
|
+
child.unref();
|
|
69
|
+
return waited.reason === "overrun" ? { exitCode: 12, result: { ...uncertain().result, error: "overrun" } } : uncertain();
|
|
70
|
+
}
|
|
71
|
+
exited = true;
|
|
72
|
+
const outcome = channel.read();
|
|
73
|
+
const activeRoot = outcome?.phase === "installed" ? outcome.activeRoot : plan.cliPath;
|
|
74
|
+
const verify = (root, version) => deps.installer === "npm"
|
|
75
|
+
? root === plan.cliPath && verifyOrchestratedInstall(root, version, "npm")
|
|
76
|
+
: verifyOrchestratedPnpmInstall({ owner, activeRoot: root, version, runPnpm: deps.runPnpm });
|
|
77
|
+
const targetVerified = outcome?.phase === "installed" && verify(activeRoot, plan.targetVersion);
|
|
78
|
+
const previousVerified = verify(plan.cliPath, plan.currentVersion);
|
|
79
|
+
let runtimeHealthy = !plan.restartRequired, restarted = false;
|
|
80
|
+
if (plan.restartRequired) {
|
|
81
|
+
try {
|
|
82
|
+
const afterBun = deps.resolveBun();
|
|
83
|
+
const after = afterBun ? deps.identity(afterBun) : null;
|
|
84
|
+
if (after?.kind === "live" && after.servingRoot === activeRoot) {
|
|
85
|
+
runtimeHealthy = after.healthVersion === (outcome?.phase === "installed" ? plan.targetVersion : plan.currentVersion);
|
|
86
|
+
restarted = after.runtime.pid !== live?.runtime.pid;
|
|
87
|
+
}
|
|
88
|
+
} catch {
|
|
89
|
+
return { exitCode: 12, result: { ...uncertain().result, applied: targetVerified, error: "runtime-unverified" } };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return classifyOrchestratedOutcome({ ...base(), childExited: true, childExitCode: waited.code, outcome,
|
|
93
|
+
previousVerified, targetVerified, runtimeHealthy, restarted });
|
|
94
|
+
} catch {
|
|
95
|
+
return started ? uncertain() : fail("plan-unavailable");
|
|
96
|
+
} finally {
|
|
97
|
+
if (channel && (!started || exited)) channel.dispose();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export type Outcome = ({ phase: "preflight" | "mutating" | "overrun" }
|
|
2
|
+
| { phase: "installed"; activeRoot: string; recoveryFailed?: boolean; error?: string }
|
|
3
|
+
| { phase: "refused"; error?: string }
|
|
4
|
+
| { phase: "failed"; error?: string; rollbackPerformed?: boolean }) & { terminationConfirmed?: boolean };
|
|
5
|
+
export interface OutcomeInput {
|
|
6
|
+
fromVersion: string;
|
|
7
|
+
toVersion: string | null;
|
|
8
|
+
installer: "npm" | "pnpm" | "bun" | "mise" | "desktop-app" | "source" | "unknown";
|
|
9
|
+
childExited: boolean;
|
|
10
|
+
childExitCode: number | null;
|
|
11
|
+
outcome: Outcome | null;
|
|
12
|
+
previousVerified: boolean;
|
|
13
|
+
targetVerified: boolean;
|
|
14
|
+
runtimeHealthy: boolean;
|
|
15
|
+
restarted: boolean;
|
|
16
|
+
}
|
|
17
|
+
export declare function classifyOrchestratedOutcome(input: OutcomeInput): {
|
|
18
|
+
exitCode: 0 | 10 | 11 | 12;
|
|
19
|
+
result: { schema: "ocx.update.result/1"; applied: boolean; fromVersion: string; toVersion: string | null;
|
|
20
|
+
installer: OutcomeInput["installer"]; restarted: boolean; healthy: boolean; rolledBack: boolean; error?: string };
|
|
21
|
+
};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
|
|
3
|
+
function validOutcome(outcome) {
|
|
4
|
+
if (!outcome || typeof outcome !== "object" || Array.isArray(outcome)) return false;
|
|
5
|
+
if (!["preflight", "mutating", "installed", "failed", "refused", "overrun"].includes(outcome.phase)) return false;
|
|
6
|
+
if (outcome.error !== undefined && typeof outcome.error !== "string") return false;
|
|
7
|
+
if (outcome.rollbackPerformed !== undefined && typeof outcome.rollbackPerformed !== "boolean") return false;
|
|
8
|
+
if (outcome.terminationConfirmed !== undefined && typeof outcome.terminationConfirmed !== "boolean") return false;
|
|
9
|
+
return outcome.phase !== "installed" || (typeof outcome.activeRoot === "string" && isAbsolute(outcome.activeRoot));
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Classify only independently observed state after confirmed child termination. */
|
|
13
|
+
export function classifyOrchestratedOutcome(input) {
|
|
14
|
+
const result = {
|
|
15
|
+
schema: "ocx.update.result/1", applied: false, fromVersion: input.fromVersion,
|
|
16
|
+
toVersion: input.toVersion, installer: input.installer, restarted: false,
|
|
17
|
+
healthy: false, rolledBack: false,
|
|
18
|
+
};
|
|
19
|
+
const done = (exitCode, error) => ({ exitCode, result: error ? { ...result, error } : result });
|
|
20
|
+
if (!input.childExited || input.childExitCode === null || !validOutcome(input.outcome) || input.outcome.phase === "overrun") return done(12, "outcome-unverified");
|
|
21
|
+
if (input.outcome.terminationConfirmed === false) return done(12, input.outcome.error || "installer-termination-unconfirmed");
|
|
22
|
+
if (input.outcome.phase === "refused" && input.childExitCode !== 0) return done(10, input.outcome.error || "runtime-ownership-refused");
|
|
23
|
+
if (input.outcome.phase === "failed" && input.outcome.error === "installer-termination-unconfirmed") return done(12, input.outcome.error);
|
|
24
|
+
if (input.outcome.phase === "installed") {
|
|
25
|
+
result.applied = input.targetVerified;
|
|
26
|
+
result.restarted = input.restarted;
|
|
27
|
+
result.healthy = input.targetVerified && input.runtimeHealthy && input.childExitCode === 0;
|
|
28
|
+
if (!input.targetVerified) return done(12, "install-unverified");
|
|
29
|
+
if (!result.healthy) return done(12, "runtime-unhealthy");
|
|
30
|
+
return done(0);
|
|
31
|
+
}
|
|
32
|
+
if (["preflight", "mutating", "failed"].includes(input.outcome.phase) && input.childExitCode !== 0
|
|
33
|
+
&& input.previousVerified && input.runtimeHealthy) {
|
|
34
|
+
result.healthy = true;
|
|
35
|
+
result.restarted = input.restarted;
|
|
36
|
+
result.rolledBack = input.outcome.phase === "failed" && input.outcome.rollbackPerformed === true;
|
|
37
|
+
return done(11, input.outcome.error || "update-failed");
|
|
38
|
+
}
|
|
39
|
+
return done(12, "outcome-unverified");
|
|
40
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { compareStrictSemver, parseStrictSemver } from "../lib/strict-semver";
|
|
2
|
+
import { createUpdatePlanToken } from "./orchestrated-token.mjs";
|
|
3
|
+
import type { ServingIdentity } from "./orchestrated-identity";
|
|
4
|
+
|
|
5
|
+
export const ORCHESTRATED_MUTATION_BOUND_MS = 900_000;
|
|
6
|
+
type Installer = "npm" | "pnpm" | "bun" | "mise" | "desktop-app" | "source" | "unknown";
|
|
7
|
+
type RuntimeOwner = "service" | "desktop-app" | "unmanaged" | "none" | "unknown";
|
|
8
|
+
type Reason = "desktop-app-owned" | "source-checkout" | "mise-managed" | "installer-unknown" | "plan-unavailable" | "serving-install-unknown" | "cli-not-serving-install" | "runtime-ownership-refused" | "target-unresolved" | "downgrade-refused" | "up-to-date";
|
|
9
|
+
|
|
10
|
+
export interface PlanInputs {
|
|
11
|
+
currentVersion: string;
|
|
12
|
+
targetVersion: string | null;
|
|
13
|
+
installer: Installer;
|
|
14
|
+
runtimeOwner: RuntimeOwner;
|
|
15
|
+
cliRoot: string;
|
|
16
|
+
identity: ServingIdentity;
|
|
17
|
+
ownershipPermits: boolean;
|
|
18
|
+
updateInFlight: boolean;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Construct the public plan from already-observed facts, refusing every uncertain boundary. */
|
|
22
|
+
export function buildOrchestratedPlan(input: PlanInputs) {
|
|
23
|
+
const live = input.identity.kind === "live" ? input.identity : null;
|
|
24
|
+
const servingRoot = live?.servingRoot ?? null;
|
|
25
|
+
const current = parseStrictSemver(input.currentVersion);
|
|
26
|
+
const target = parseStrictSemver(input.targetVersion);
|
|
27
|
+
let reason: Reason | undefined;
|
|
28
|
+
if (input.installer === "desktop-app") reason = "desktop-app-owned";
|
|
29
|
+
else if (input.installer === "source") reason = "source-checkout";
|
|
30
|
+
else if (input.installer === "mise") reason = "mise-managed";
|
|
31
|
+
else if (input.installer === "unknown") reason = "installer-unknown";
|
|
32
|
+
else if (input.identity.kind === "unknown") reason = "serving-install-unknown";
|
|
33
|
+
else if (input.identity.kind === "mismatch") reason = "cli-not-serving-install";
|
|
34
|
+
else if (live && servingRoot !== input.cliRoot) reason = "cli-not-serving-install";
|
|
35
|
+
else if (!input.ownershipPermits || input.runtimeOwner === "unknown") reason = "runtime-ownership-refused";
|
|
36
|
+
else if (!current || !target) reason = "target-unresolved";
|
|
37
|
+
else if (compareStrictSemver(target, current) < 0) reason = "downgrade-refused";
|
|
38
|
+
else if (compareStrictSemver(target, current) === 0) reason = "up-to-date";
|
|
39
|
+
const planToken = createUpdatePlanToken({
|
|
40
|
+
currentVersion: input.currentVersion, targetVersion: input.targetVersion, installer: input.installer,
|
|
41
|
+
cliRoot: input.cliRoot, servingRoot, runtimeOwner: input.runtimeOwner, runtime: live?.runtime ?? null,
|
|
42
|
+
});
|
|
43
|
+
return {
|
|
44
|
+
schema: "ocx.update.plan/1" as const, currentVersion: input.currentVersion, targetVersion: input.targetVersion,
|
|
45
|
+
installer: input.installer, runtimeOwner: input.runtimeOwner, servingPath: servingRoot, cliPath: input.cliRoot,
|
|
46
|
+
canApply: reason === undefined, ...(reason ? { reason } : {}), restartRequired: live !== null,
|
|
47
|
+
planToken, updateInFlight: input.updateInFlight, mutationBoundMs: ORCHESTRATED_MUTATION_BOUND_MS,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { readPnpmGlobalPackage, resolvePnpmGlobalOwner } from "./pnpm-global-install.mjs";
|
|
4
|
+
import { verifyPnpmInstallTree } from "./transactional-install.mjs";
|
|
5
|
+
|
|
6
|
+
const PACKAGE_NAME = "@bitkyc08/opencodex";
|
|
7
|
+
|
|
8
|
+
/** Re-resolve the selected pnpm group and verify its active tree and generated shims. */
|
|
9
|
+
export function verifyOrchestratedPnpmInstall({ owner, activeRoot, version, runPnpm }) {
|
|
10
|
+
try {
|
|
11
|
+
const key = path => {
|
|
12
|
+
const result = realpathSync.native(path);
|
|
13
|
+
return process.platform === "win32" ? result.toLowerCase() : result;
|
|
14
|
+
};
|
|
15
|
+
const verify = (path, expected) => {
|
|
16
|
+
try {
|
|
17
|
+
const manifest = JSON.parse(readFileSync(join(path, "package.json"), "utf8"));
|
|
18
|
+
const source = statSync(join(path, "src", "cli", "index.ts"));
|
|
19
|
+
return { ok: manifest.version === expected && Boolean(manifest.dependencies?.bun && manifest.dependencies?.zod)
|
|
20
|
+
&& source.isFile() && source.size > 0 && verifyPnpmInstallTree(path, expected).ok };
|
|
21
|
+
} catch { return { ok: false }; }
|
|
22
|
+
};
|
|
23
|
+
const resolved = resolvePnpmGlobalOwner({ packageName: PACKAGE_NAME, packagePath: activeRoot,
|
|
24
|
+
commandPaths: [owner.commandPath], runPnpm, verify });
|
|
25
|
+
if (!resolved.ok || key(resolved.owner.globalDir) !== key(owner.globalDir)
|
|
26
|
+
|| key(resolved.owner.globalRoot) !== key(owner.globalRoot)
|
|
27
|
+
|| key(resolved.owner.globalBinDir) !== key(owner.globalBinDir)) return false;
|
|
28
|
+
const active = readPnpmGlobalPackage(PACKAGE_NAME,
|
|
29
|
+
(args, capture) => runPnpm(owner.commandPath, args, capture), verify,
|
|
30
|
+
{ owner, expectedPackagePath: activeRoot, expectedGlobalRoot: owner.globalRoot, globalBinDir: owner.globalBinDir });
|
|
31
|
+
return active.ok && active.version === version && key(active.path) === key(activeRoot);
|
|
32
|
+
} catch { return false; }
|
|
33
|
+
}
|