@bitkyc08/opencodex 2.99.0 → 2.100.1
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 +19 -1
- package/README.md +37 -33
- package/SPONSORS.md +5 -1
- package/bin/ocx.mjs +1 -1
- package/gui/dist/assets/{App-C1hGwaN1.css → App-COo8Yopd.css} +1 -1
- package/gui/dist/assets/App-g3Cm2xhZ.js +59 -0
- package/gui/dist/assets/Tray-BMDkAiXy.js +1 -0
- package/gui/dist/assets/brand-mark-nr3ziR-T.js +1 -0
- package/gui/dist/assets/index-Bziu8gTy.css +2 -0
- package/gui/dist/assets/index-OYzhQUNP.js +94 -0
- package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-DKCVUUTi.js} +1 -1
- package/gui/dist/classic/assets/App-CgPBKUP-.js +58 -0
- package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-BedmOsE7.js} +1 -1
- package/gui/dist/classic/assets/index-BR-HhNrp.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/Cargo.lock +215 -0
- package/native/ocx-child/Cargo.toml +31 -0
- package/native/ocx-child/src/cli.rs +1901 -0
- package/native/ocx-child/src/codex_home.rs +429 -0
- package/native/ocx-child/src/codex_settings.rs +231 -0
- package/native/ocx-child/src/daemon.rs +363 -0
- package/native/ocx-child/src/http_wire.rs +619 -0
- package/native/ocx-child/src/journal.rs +977 -0
- package/native/ocx-child/src/lib.rs +22 -0
- package/native/ocx-child/src/main.rs +9 -0
- package/native/ocx-child/src/parity.rs +102 -0
- package/native/ocx-child/src/platform.rs +1487 -0
- package/native/ocx-child/src/relay.rs +1288 -0
- package/native/ocx-child/src/relay_auth.rs +166 -0
- package/native/ocx-child/src/routes.rs +236 -0
- package/native/ocx-child/src/state.rs +190 -0
- package/native/ocx-child/src/test_hooks.rs +58 -0
- package/native/ocx-child/src/toml_surgeon.rs +1156 -0
- package/package.json +8 -2
- package/src/adapters/anthropic-image-normalize.ts +1 -1
- package/src/adapters/anthropic.ts +28 -2
- package/src/adapters/claude-cli/adapter.ts +5 -25
- package/src/adapters/claude-cli/instruction-images.ts +31 -0
- package/src/adapters/claude-cli/stable-replay.ts +42 -14
- package/src/adapters/claude-cli/usage-admission.ts +53 -64
- package/src/adapters/client-fingerprint.ts +1 -1
- package/src/adapters/coding-agent/protocol.ts +1 -1
- package/src/adapters/devin/live-models.ts +3 -0
- package/src/adapters/google-http.ts +3 -0
- package/src/adapters/google-vertex-key-project.ts +10 -2
- package/src/adapters/google.ts +40 -8
- package/src/adapters/kiro/usage.ts +3 -13
- package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
- package/src/adapters/openai-chat-images.ts +100 -0
- package/src/adapters/openai-chat.ts +6 -9
- package/src/adapters/openai-responses/passthrough.ts +5 -2
- package/src/adapters/openai-responses/request-strips.ts +32 -0
- package/src/adapters/openai-responses/tool-schema.ts +9 -4
- package/src/chat/inbound.ts +1 -1
- package/src/claude/auth-detect.ts +26 -8
- package/src/claude/inbound-content-options.ts +18 -3
- package/src/claude/inbound.ts +5 -2
- package/src/cli/bundled-bun-diagnostic.ts +91 -0
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-observe-system.ts +60 -0
- package/src/cli/combo-input.ts +6 -0
- package/src/cli/combo-result.ts +1 -1
- package/src/cli/combo.ts +4 -0
- package/src/cli/config-command.ts +16 -2
- package/src/cli/connect.ts +12 -10
- package/src/cli/dispatch.ts +4 -0
- package/src/cli/doctor.ts +11 -0
- package/src/cli/help.ts +1 -0
- package/src/cli/init.ts +4 -0
- package/src/cli/link-enrollment.ts +152 -25
- package/src/cli/link-local-control.ts +49 -0
- package/src/cli/link.ts +37 -10
- package/src/cli/provider-lifecycle-runtime.ts +4 -2
- package/src/cli/registry.ts +13 -0
- package/src/cli/star-prompt.ts +2 -0
- package/src/cli/status.ts +1 -1
- package/src/cli/telemetry-profile.ts +206 -0
- package/src/cli/telemetry.ts +260 -0
- package/src/client/hub-relay.ts +26 -0
- package/src/client/machine-api.ts +3 -0
- package/src/clients/config-export/t3code.ts +44 -5
- package/src/clients/omo-role-models.ts +1 -1
- package/src/codex/catalog/bundled.ts +44 -2
- package/src/codex/runtime.ts +12 -0
- package/src/codex/shim-restore-lock.ts +67 -30
- package/src/combos/types.ts +21 -1
- package/src/config/atomic-write.ts +24 -1
- package/src/config/diagnostics.ts +15 -0
- package/src/config/live-reconcile.ts +17 -0
- package/src/config/load-degrade.ts +16 -0
- package/src/config/provider-validation.ts +29 -0
- package/src/config/schema/config-schema.ts +24 -0
- package/src/config/schema/leaf-validators.ts +17 -0
- package/src/config/telemetry-carry.ts +30 -0
- package/src/config.ts +13 -1
- package/src/generated/compatibility-version.json +422 -170
- package/src/generated/model-metadata.ts +3 -3
- package/src/integrations/aside-profiles.ts +7 -1
- package/src/integrations/owned-refresh.ts +9 -2
- package/src/lab/artifacts/secure-fs.ts +12 -11
- package/src/lab/fabric/scratch.ts +11 -9
- package/src/lab/public/community.ts +2 -3
- package/src/lab/public/file-safety.ts +18 -20
- package/src/lab/public/mutation-lock.ts +109 -337
- package/src/lab/public/private-file.ts +4 -3
- package/src/lib/bun-runtime-preflight.ts +1 -1
- package/src/lib/codex-catalog-read-only.ts +122 -0
- package/src/lib/config-ownership.ts +56 -18
- package/src/lib/errors.ts +11 -0
- package/src/lib/gcp-adc.ts +167 -48
- package/src/lib/jsonc.ts +4 -2
- package/src/lib/local-control-socket.ts +88 -0
- package/src/lib/privacy.ts +15 -0
- package/src/lib/provider-client-headers.ts +3 -0
- package/src/lib/token-estimate.ts +13 -2
- package/src/link/child-binary-source.ts +228 -0
- package/src/link/ephemeral-child.ts +45 -0
- package/src/link/remote-plant.ts +306 -0
- package/src/link/remote-windows.ts +59 -5
- package/src/link/ssh-argv.ts +71 -8
- package/src/link/status-projection.ts +2 -0
- package/src/link/store.ts +5 -1
- package/src/oauth/anthropic-model-quota.ts +12 -0
- package/src/oauth/anthropic-routing.ts +11 -4
- package/src/oauth/claude-keychain-read.ts +165 -0
- package/src/oauth/kiro-iam-identity-center.ts +4 -1
- package/src/oauth/local-token-detect.ts +14 -17
- package/src/protocols/envelope.ts +20 -2
- package/src/providers/api-key-selection.ts +8 -2
- package/src/providers/claude-cli-identity.ts +9 -3
- package/src/providers/claude-cli-usage-state.ts +93 -0
- package/src/providers/claude-cli-usage.ts +3 -2
- package/src/providers/github-copilot-auto.ts +25 -5
- package/src/providers/meta-muse-plan-refusal.ts +94 -0
- package/src/providers/model-rename-fields.ts +3 -0
- package/src/providers/quota/anthropic-family-headers.ts +8 -1
- package/src/providers/quota/anthropic-usage-windows.ts +49 -2
- package/src/providers/quota/vendor-probes-key.ts +23 -4
- package/src/providers/quota/vendor-probes-oauth.ts +59 -0
- package/src/providers/quota/workbuddy.ts +2 -2
- package/src/providers/quota-types.ts +7 -0
- package/src/providers/quota.ts +25 -18
- package/src/providers/registry/entries-core.ts +7 -4
- package/src/providers/registry/entries-extended.ts +42 -8
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/model-seeds.ts +10 -2
- package/src/providers/registry/types.ts +6 -0
- package/src/providers/resolved-model-policy.ts +4 -0
- package/src/providers/routed-config.ts +30 -3
- package/src/providers/stale-no-vision-seed-migration.ts +7 -0
- package/src/providers/vertex-environment-authority.ts +50 -0
- package/src/providers/workbuddy-credit-balance.ts +38 -6
- package/src/quota-pool/assemble.ts +14 -6
- package/src/responses/retained-compaction.ts +31 -5
- package/src/router.ts +1 -0
- package/src/server/adapter-resolve.ts +11 -6
- package/src/server/audio-dictation.ts +21 -7
- package/src/server/auth-cors.ts +19 -0
- package/src/server/background-lifecycle.ts +71 -0
- package/src/server/chat-completions.ts +2 -0
- package/src/server/claude-messages.ts +30 -3
- package/src/server/index/live-sideband.ts +15 -1
- package/src/server/index/local-control-listener.ts +515 -0
- package/src/server/index/optional-listeners.ts +21 -1
- package/src/server/index/serve-options.ts +4 -3
- package/src/server/index/websocket-handler.ts +2 -0
- package/src/server/index.ts +3 -0
- package/src/server/management/combo-routes.ts +6 -1
- package/src/server/management/context.ts +1 -0
- package/src/server/management/link-child-preflight.ts +74 -0
- package/src/server/management/link-enrollment.ts +190 -25
- package/src/server/management/link-route-state.ts +6 -1
- package/src/server/management/link-routes.ts +27 -9
- package/src/server/management/model-rows.ts +4 -0
- package/src/server/management/oauth-account-routes.ts +9 -4
- package/src/server/management/provider-overwrite-carry.ts +9 -2
- package/src/server/management/provider-routes.ts +14 -0
- package/src/server/management/provider-thinking-display-patch.ts +54 -0
- package/src/server/management/route-registry.ts +7 -0
- package/src/server/management/session-routes.ts +4 -1
- package/src/server/management/telemetry-routes.ts +37 -0
- package/src/server/management/usage-aggregate-cache.ts +290 -67
- package/src/server/management-api.ts +11 -2
- package/src/server/messages-native-preflight.ts +166 -0
- package/src/server/messages-native.ts +143 -43
- package/src/server/messages-shared.ts +14 -0
- package/src/server/proxy-liveness.ts +99 -6
- package/src/server/request-log-conversation.ts +18 -2
- package/src/server/request-log.ts +7 -2
- package/src/server/responses/adapter-continuation.ts +1 -0
- package/src/server/responses/adapter-dispatch.ts +11 -28
- package/src/server/responses/adapter-failure-message.ts +68 -0
- package/src/server/responses/combo-stream-preflight.ts +14 -2
- package/src/server/responses/compact.ts +13 -1
- package/src/server/responses/core-auth.ts +26 -5
- package/src/server/responses/core-codex-account.ts +8 -1
- package/src/server/responses/core-combo-failure.ts +6 -1
- package/src/server/responses/core-combo-native.ts +150 -37
- package/src/server/responses/core-combo.ts +15 -9
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +7 -1
- package/src/server/responses/core-pipeline.ts +21 -1
- package/src/server/responses/fetch-helpers.ts +5 -0
- package/src/server/responses/opengateway-completion-guard.ts +7 -3
- package/src/server/responses/passthrough-delivery.ts +8 -1
- package/src/server/responses/passthrough-error.ts +22 -0
- package/src/server/responses/request-prepare.ts +7 -1
- package/src/server/responses/request-transport.ts +28 -5
- package/src/server/responses/run-turn-execution.ts +13 -0
- package/src/server/sse-frame-buffer.ts +5 -0
- package/src/server/ws-bridge.ts +10 -0
- package/src/service/launchd.ts +78 -4
- package/src/telemetry/aggregate.ts +348 -0
- package/src/telemetry/consent.ts +128 -0
- package/src/telemetry/contract.ts +403 -0
- package/src/telemetry/disclosure.ts +19 -0
- package/src/telemetry/install-id.ts +226 -0
- package/src/telemetry/payload.ts +129 -0
- package/src/telemetry/profile/client.ts +150 -0
- package/src/telemetry/profile/contract.ts +288 -0
- package/src/telemetry/profile/disclosure.ts +14 -0
- package/src/telemetry/profile/paths.ts +13 -0
- package/src/telemetry/profile/routes.ts +99 -0
- package/src/telemetry/profile/service.ts +234 -0
- package/src/telemetry/profile/state.ts +189 -0
- package/src/telemetry/profile/sync.ts +276 -0
- package/src/telemetry/routes.ts +183 -0
- package/src/telemetry/scheduler.ts +386 -0
- package/src/telemetry/sender.ts +97 -0
- package/src/telemetry/state.ts +334 -0
- package/src/types/combo-jev-effort-mode.ts +11 -0
- package/src/types/config.ts +3 -0
- package/src/types/provider.ts +11 -1
- package/src/types/request.ts +2 -0
- package/src/types/telemetry.ts +15 -0
- package/src/types/wire.ts +10 -0
- package/src/types.ts +5 -0
- package/src/update/index.ts +7 -1
- package/src/update/minisign.d.mts +17 -0
- package/src/update/minisign.mjs +88 -0
- package/src/update/signed-supply.d.mts +59 -0
- package/src/update/signed-supply.mjs +289 -0
- package/src/update/trust-root.json +38 -0
- package/src/update/update-bounded-json.d.mts +4 -0
- package/src/update/update-bounded-json.mjs +113 -0
- package/src/update/update-bytes.d.mts +2 -0
- package/src/update/update-bytes.mjs +23 -0
- package/src/update/update-candidate-id.d.mts +2 -0
- package/src/update/update-candidate-id.mjs +23 -0
- package/src/update/update-checkpoint-codec.d.mts +33 -0
- package/src/update/update-checkpoint-codec.mjs +217 -0
- package/src/update/update-contracts.d.mts +24 -0
- package/src/update/update-contracts.mjs +207 -0
- package/src/update/update-signature-threshold.d.mts +12 -0
- package/src/update/update-signature-threshold.mjs +47 -0
- package/src/update/update-signed-version.d.mts +5 -0
- package/src/update/update-signed-version.mjs +25 -0
- package/src/update/update-trust-anchor.d.mts +2 -0
- package/src/update/update-trust-anchor.mjs +2 -0
- package/src/usage/cache-diagnostic.ts +195 -50
- package/src/usage/expected-prices.ts +20 -2
- package/src/usage/filter-index.ts +1469 -0
- package/src/usage/ledger-scanner.ts +245 -4
- package/src/usage/source-filter.ts +10 -2
- package/src/usage/summary.ts +16 -0
- package/src/web-search/parse.ts +265 -38
- package/gui/dist/assets/App-BepstgEN.js +0 -59
- package/gui/dist/assets/Tray-BinxbEZo.js +0 -1
- package/gui/dist/assets/brand-mark-wzPe3R-J.js +0 -1
- package/gui/dist/assets/index-C-9X2yaI.js +0 -94
- package/gui/dist/assets/index-bnUWypyz.css +0 -2
- package/gui/dist/classic/assets/App-DX88_GCW.js +0 -58
- package/gui/dist/classic/assets/index-fSP71pLB.js +0 -94
- package/gui/dist/classic/assets/quota-summary-y2fl0WBv.js +0 -1
|
@@ -0,0 +1,1901 @@
|
|
|
1
|
+
use std::fs;
|
|
2
|
+
use std::io::{self, BufRead, Read};
|
|
3
|
+
use std::path::{Path, PathBuf};
|
|
4
|
+
use std::time::Duration;
|
|
5
|
+
|
|
6
|
+
use serde::{Deserialize, Serialize};
|
|
7
|
+
|
|
8
|
+
use crate::codex_home::{
|
|
9
|
+
ClaimPolicy, CodexHomeError, CodexHomeGuard, OwnershipPhase, RestoreStepError,
|
|
10
|
+
};
|
|
11
|
+
use crate::codex_settings::{
|
|
12
|
+
HomeCodexSettings, HomeCodexSettingsDocument, HomeIdentity, codex_settings_digest,
|
|
13
|
+
parse_home_codex_settings_document,
|
|
14
|
+
};
|
|
15
|
+
use crate::daemon::{
|
|
16
|
+
ensure_port_available_for_attach, pick_ephemeral_link_port, probe_local_healthz,
|
|
17
|
+
start_or_rollover_daemon, stop_owned_daemon,
|
|
18
|
+
};
|
|
19
|
+
use crate::journal::{
|
|
20
|
+
DetachError, apply_attach_or_sync, offline_detach_deferred, remove_optional_file,
|
|
21
|
+
validate_existing_journal_paths,
|
|
22
|
+
};
|
|
23
|
+
use crate::parity::LinkChildParityReport;
|
|
24
|
+
use crate::platform::{
|
|
25
|
+
DirectoryIdentity, FileLock, LockAcquireError, PurgeExecutableOutcome, SecretBytes,
|
|
26
|
+
constant_time_eq, directory_identity, ensure_private_dir, format_iso8601_utc, now_epoch_ms,
|
|
27
|
+
purge_managed_executable, random_hex, reject_symlink, resolve_codex_home,
|
|
28
|
+
resolve_opencodex_home, resolve_user_home, volatile_zero_bytes, write_private_atomic,
|
|
29
|
+
write_regular_atomic,
|
|
30
|
+
};
|
|
31
|
+
use crate::relay::{
|
|
32
|
+
RelayCredentials, UpstreamError, fetch_home_authenticated, post_child_parity_report,
|
|
33
|
+
serve_foreground,
|
|
34
|
+
};
|
|
35
|
+
use crate::relay_auth::{is_valid_key_id, is_valid_link_id};
|
|
36
|
+
use crate::routes::RelayAuthKind;
|
|
37
|
+
use crate::state::{
|
|
38
|
+
AppliedSettingsRecord, CHILD_STATE_SCHEMA, ChildPaths, ChildStateV1, StateReadOutcome,
|
|
39
|
+
is_valid_daemon_generation, is_valid_link_token_format, read_child_state,
|
|
40
|
+
read_verified_link_key, write_child_state, write_link_key,
|
|
41
|
+
};
|
|
42
|
+
use crate::{DEFAULT_LISTEN_PORT, OCX_PROTOCOL_COMPAT_VERSION};
|
|
43
|
+
|
|
44
|
+
const REMOTE_LINK_SYNC_MESSAGE: &str = "Remote Link Home catalog synchronized.";
|
|
45
|
+
const STALE_REMOTE_CATALOG_MESSAGE: &str =
|
|
46
|
+
"Home unavailable; retained and applied the last-known-good remote catalog (stale).";
|
|
47
|
+
const MAX_STDIN_CREDENTIAL_BYTES: usize = 4096;
|
|
48
|
+
|
|
49
|
+
#[derive(Deserialize)]
|
|
50
|
+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
51
|
+
struct StdinLinkCredential {
|
|
52
|
+
api_key_id: String,
|
|
53
|
+
key: String,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
fn default_listen_port() -> u16 {
|
|
57
|
+
std::env::var("OCX_CHILD_LISTEN_PORT")
|
|
58
|
+
.ok()
|
|
59
|
+
.and_then(|v| v.parse::<u16>().ok())
|
|
60
|
+
.filter(|&p| p >= 1024)
|
|
61
|
+
.unwrap_or(DEFAULT_LISTEN_PORT)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
fn current_paths() -> ChildPaths {
|
|
65
|
+
ChildPaths::new(resolve_opencodex_home(), resolve_codex_home())
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
pub fn run_cli(args: &[String]) -> u8 {
|
|
69
|
+
let Some(first) = args.first().map(String::as_str) else {
|
|
70
|
+
eprintln!(
|
|
71
|
+
"Usage: ocx-child <attach|sync|detach|serve|restart|disconnect|status|port|--version>"
|
|
72
|
+
);
|
|
73
|
+
return 2;
|
|
74
|
+
};
|
|
75
|
+
match first {
|
|
76
|
+
"--version" | "-V" | "version" => {
|
|
77
|
+
println!("opencodex {OCX_PROTOCOL_COMPAT_VERSION}");
|
|
78
|
+
0
|
|
79
|
+
}
|
|
80
|
+
"--help" | "-h" | "help" => {
|
|
81
|
+
println!("opencodex {OCX_PROTOCOL_COMPAT_VERSION} (ocx-child ephemeral link client)");
|
|
82
|
+
0
|
|
83
|
+
}
|
|
84
|
+
"port" => cmd_port(),
|
|
85
|
+
"link" => match args.get(1).map(String::as_str) {
|
|
86
|
+
Some("port") => cmd_port(),
|
|
87
|
+
Some("status") => cmd_link_status(&args[2..]),
|
|
88
|
+
_ => {
|
|
89
|
+
eprintln!("Usage: ocx-child link <port|status>");
|
|
90
|
+
2
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
"config" => match (
|
|
94
|
+
args.get(1).map(String::as_str),
|
|
95
|
+
args.get(2).map(String::as_str),
|
|
96
|
+
) {
|
|
97
|
+
(Some("show"), Some("--json")) | (Some("show"), None) => cmd_config_show(),
|
|
98
|
+
_ => {
|
|
99
|
+
eprintln!("Usage: ocx-child config show --json");
|
|
100
|
+
2
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
"attach" => cmd_attach_or_connect(&args[1..], true),
|
|
104
|
+
"connect" => {
|
|
105
|
+
if args.get(1).map(String::as_str) == Some("status") {
|
|
106
|
+
cmd_connect_status(&args[2..])
|
|
107
|
+
} else {
|
|
108
|
+
cmd_attach_or_connect(&args[1..], false)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
"serve" => cmd_serve(&args[1..]),
|
|
112
|
+
"restart" => cmd_restart(),
|
|
113
|
+
"sync" => cmd_sync(&args[1..]),
|
|
114
|
+
"detach" | "disconnect" => cmd_detach(&args[1..]),
|
|
115
|
+
"status" => cmd_status(&args[1..]),
|
|
116
|
+
other => {
|
|
117
|
+
eprintln!("Unknown ocx-child subcommand: {other}");
|
|
118
|
+
2
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
fn cmd_port() -> u8 {
|
|
124
|
+
match pick_ephemeral_link_port() {
|
|
125
|
+
Ok(port) => {
|
|
126
|
+
println!("{{\"port\":{port}}}");
|
|
127
|
+
0
|
|
128
|
+
}
|
|
129
|
+
Err(e) => {
|
|
130
|
+
eprintln!("{e}");
|
|
131
|
+
1
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
fn cmd_config_show() -> u8 {
|
|
137
|
+
let paths = current_paths();
|
|
138
|
+
let (port, role) = match read_child_state(&paths.state_file) {
|
|
139
|
+
StateReadOutcome::Valid(st) if st.pending_operation.is_none() => (st.listen_port, "client"),
|
|
140
|
+
_ => (default_listen_port(), "standalone"),
|
|
141
|
+
};
|
|
142
|
+
println!("{{\"port\":{port},\"runtimeRole\":\"{role}\",\"ephemeralChild\":true}}");
|
|
143
|
+
0
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
fn read_stdin_credential() -> Result<(String, SecretBytes), String> {
|
|
147
|
+
let mut raw = Vec::with_capacity(256);
|
|
148
|
+
io::stdin()
|
|
149
|
+
.take((MAX_STDIN_CREDENTIAL_BYTES + 1) as u64)
|
|
150
|
+
.read_to_end(&mut raw)
|
|
151
|
+
.map_err(|e| format!("failed reading credential from stdin: {e}"))?;
|
|
152
|
+
let secret_buf = SecretBytes::new(raw);
|
|
153
|
+
if secret_buf.as_slice().len() > MAX_STDIN_CREDENTIAL_BYTES {
|
|
154
|
+
return Err("link credential exceeds 4 KiB stdin limit".to_owned());
|
|
155
|
+
}
|
|
156
|
+
let text = std::str::from_utf8(secret_buf.as_slice())
|
|
157
|
+
.map_err(|_| "invalid link credential UTF-8".to_owned())?
|
|
158
|
+
.trim();
|
|
159
|
+
let parsed: StdinLinkCredential =
|
|
160
|
+
serde_json::from_str(text).map_err(|_| "invalid link credential JSON".to_owned())?;
|
|
161
|
+
if !is_valid_key_id(&parsed.api_key_id) || !is_valid_link_token_format(&parsed.key) {
|
|
162
|
+
return Err("invalid link credential shape".to_owned());
|
|
163
|
+
}
|
|
164
|
+
let key_bytes = SecretBytes::new(parsed.key.into_bytes());
|
|
165
|
+
Ok((parsed.api_key_id, key_bytes))
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
struct SettingsFetchError {
|
|
169
|
+
retryable: bool,
|
|
170
|
+
message: String,
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
impl std::fmt::Display for SettingsFetchError {
|
|
174
|
+
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
175
|
+
f.write_str(&self.message)
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
fn fetch_home_settings_doc(
|
|
180
|
+
tunnel_port: u16,
|
|
181
|
+
creds: &RelayCredentials,
|
|
182
|
+
) -> Result<HomeCodexSettingsDocument, SettingsFetchError> {
|
|
183
|
+
let (head, body, _) = fetch_home_authenticated(
|
|
184
|
+
tunnel_port,
|
|
185
|
+
creds,
|
|
186
|
+
"GET",
|
|
187
|
+
"/v1/link-management/codex-settings",
|
|
188
|
+
RelayAuthKind::Bearer,
|
|
189
|
+
None,
|
|
190
|
+
64 * 1024,
|
|
191
|
+
)
|
|
192
|
+
.map_err(|e| SettingsFetchError {
|
|
193
|
+
retryable: matches!(e, UpstreamError::HomeUnreachable(_)),
|
|
194
|
+
message: format!("codex-settings fetch failed: {e:?}"),
|
|
195
|
+
})?;
|
|
196
|
+
if head.status == 404 {
|
|
197
|
+
return Ok(HomeCodexSettingsDocument {
|
|
198
|
+
version: 1,
|
|
199
|
+
home: HomeIdentity {
|
|
200
|
+
name: "home".to_owned(),
|
|
201
|
+
version: OCX_PROTOCOL_COMPAT_VERSION.to_owned(),
|
|
202
|
+
},
|
|
203
|
+
settings: HomeCodexSettings {
|
|
204
|
+
fast_mode: None,
|
|
205
|
+
multi_agent_mode: None,
|
|
206
|
+
web_search_sidecar_enabled: true,
|
|
207
|
+
subagent_defaults: None,
|
|
208
|
+
},
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
if head.status != 200 {
|
|
212
|
+
return Err(SettingsFetchError {
|
|
213
|
+
retryable: head.status >= 500,
|
|
214
|
+
message: format!("Home codex-settings returned HTTP {}", head.status),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
parse_home_codex_settings_document(&body).ok_or_else(|| SettingsFetchError {
|
|
218
|
+
retryable: false,
|
|
219
|
+
message: "Home codex-settings failed strict schema validation".to_owned(),
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
pub struct AttachRollbackSnapshot {
|
|
224
|
+
opencodex_home: String,
|
|
225
|
+
codex_home: String,
|
|
226
|
+
opencodex_home_identity: DirectoryIdentity,
|
|
227
|
+
codex_home_identity: DirectoryIdentity,
|
|
228
|
+
prior_state: Option<ChildStateV1>,
|
|
229
|
+
prior_was_serving: bool,
|
|
230
|
+
journal: Option<Vec<u8>>,
|
|
231
|
+
config: Option<Vec<u8>>,
|
|
232
|
+
catalog: Option<Vec<u8>>,
|
|
233
|
+
catalog_backup: Option<Vec<u8>>,
|
|
234
|
+
models_cache: Option<Vec<u8>>,
|
|
235
|
+
key: Option<SecretBytes>,
|
|
236
|
+
state_bytes: Option<Vec<u8>>,
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const MAX_ROLLBACK_BYTES: u64 = 256 * 1024 * 1024;
|
|
240
|
+
|
|
241
|
+
#[derive(Serialize)]
|
|
242
|
+
#[serde(rename_all = "camelCase")]
|
|
243
|
+
struct AttachRollbackRecordRef<'a> {
|
|
244
|
+
schema: &'static str,
|
|
245
|
+
opencodex_home: String,
|
|
246
|
+
codex_home: String,
|
|
247
|
+
opencodex_home_identity: DirectoryIdentity,
|
|
248
|
+
codex_home_identity: DirectoryIdentity,
|
|
249
|
+
prior_state: &'a Option<ChildStateV1>,
|
|
250
|
+
prior_was_serving: bool,
|
|
251
|
+
journal: Option<&'a [u8]>,
|
|
252
|
+
config: Option<&'a [u8]>,
|
|
253
|
+
catalog: Option<&'a [u8]>,
|
|
254
|
+
catalog_backup: Option<&'a [u8]>,
|
|
255
|
+
models_cache: Option<&'a [u8]>,
|
|
256
|
+
key: Option<&'a [u8]>,
|
|
257
|
+
state_bytes: Option<&'a [u8]>,
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
#[derive(Deserialize)]
|
|
261
|
+
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
|
262
|
+
struct AttachRollbackRecord {
|
|
263
|
+
schema: String,
|
|
264
|
+
opencodex_home: String,
|
|
265
|
+
codex_home: String,
|
|
266
|
+
opencodex_home_identity: DirectoryIdentity,
|
|
267
|
+
codex_home_identity: DirectoryIdentity,
|
|
268
|
+
prior_state: Option<ChildStateV1>,
|
|
269
|
+
prior_was_serving: bool,
|
|
270
|
+
journal: Option<Vec<u8>>,
|
|
271
|
+
config: Option<Vec<u8>>,
|
|
272
|
+
catalog: Option<Vec<u8>>,
|
|
273
|
+
catalog_backup: Option<Vec<u8>>,
|
|
274
|
+
models_cache: Option<Vec<u8>>,
|
|
275
|
+
key: Option<Vec<u8>>,
|
|
276
|
+
state_bytes: Option<Vec<u8>>,
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
impl Drop for AttachRollbackRecord {
|
|
280
|
+
fn drop(&mut self) {
|
|
281
|
+
for bytes in [
|
|
282
|
+
&mut self.journal,
|
|
283
|
+
&mut self.config,
|
|
284
|
+
&mut self.catalog,
|
|
285
|
+
&mut self.catalog_backup,
|
|
286
|
+
&mut self.models_cache,
|
|
287
|
+
&mut self.key,
|
|
288
|
+
&mut self.state_bytes,
|
|
289
|
+
]
|
|
290
|
+
.into_iter()
|
|
291
|
+
.flatten()
|
|
292
|
+
{
|
|
293
|
+
volatile_zero_bytes(bytes);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
fn rollback_pending(paths: &ChildPaths) -> Result<bool, String> {
|
|
299
|
+
match fs::symlink_metadata(&paths.rollback_file) {
|
|
300
|
+
Ok(_) => Ok(true),
|
|
301
|
+
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
|
|
302
|
+
Err(e) => Err(format!("cannot inspect rollback snapshot: {e}")),
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
impl Drop for AttachRollbackSnapshot {
|
|
307
|
+
fn drop(&mut self) {
|
|
308
|
+
for bytes in [
|
|
309
|
+
&mut self.journal,
|
|
310
|
+
&mut self.config,
|
|
311
|
+
&mut self.catalog,
|
|
312
|
+
&mut self.catalog_backup,
|
|
313
|
+
&mut self.models_cache,
|
|
314
|
+
&mut self.state_bytes,
|
|
315
|
+
]
|
|
316
|
+
.into_iter()
|
|
317
|
+
.flatten()
|
|
318
|
+
{
|
|
319
|
+
volatile_zero_bytes(bytes);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
impl AttachRollbackSnapshot {
|
|
325
|
+
fn read_optional(path: &std::path::Path) -> Result<Option<Vec<u8>>, String> {
|
|
326
|
+
match fs::read(path) {
|
|
327
|
+
Ok(b) => Ok(Some(b)),
|
|
328
|
+
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
|
|
329
|
+
Err(e) => Err(format!("attach failed reading {}: {e}", path.display())),
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
pub fn capture(
|
|
334
|
+
guard: &CodexHomeGuard,
|
|
335
|
+
prior_state: Option<ChildStateV1>,
|
|
336
|
+
) -> Result<Self, String> {
|
|
337
|
+
let paths = guard.paths();
|
|
338
|
+
ensure_private_dir(&paths.child_dir)?;
|
|
339
|
+
let mut builder = fs::DirBuilder::new();
|
|
340
|
+
builder.recursive(true);
|
|
341
|
+
#[cfg(unix)]
|
|
342
|
+
{
|
|
343
|
+
use std::os::unix::fs::DirBuilderExt;
|
|
344
|
+
builder.mode(0o700);
|
|
345
|
+
}
|
|
346
|
+
builder
|
|
347
|
+
.create(&paths.codex_home)
|
|
348
|
+
.map_err(|e| format!("cannot create Codex home for rollback: {e}"))?;
|
|
349
|
+
let (opencodex_home, codex_home) = Self::canonical_homes(paths)?;
|
|
350
|
+
let opencodex_home_identity = directory_identity(std::path::Path::new(&opencodex_home))?;
|
|
351
|
+
let codex_home_identity = directory_identity(std::path::Path::new(&codex_home))?;
|
|
352
|
+
let prior_was_serving = prior_state.as_ref().is_some_and(|st| {
|
|
353
|
+
probe_local_healthz(st.listen_port, Duration::from_millis(300)).is_some()
|
|
354
|
+
});
|
|
355
|
+
let snapshot = Self {
|
|
356
|
+
opencodex_home,
|
|
357
|
+
codex_home,
|
|
358
|
+
opencodex_home_identity,
|
|
359
|
+
codex_home_identity,
|
|
360
|
+
prior_state,
|
|
361
|
+
prior_was_serving,
|
|
362
|
+
journal: Self::read_optional(&paths.journal_file)?,
|
|
363
|
+
config: Self::read_optional(&paths.codex_config_path())?,
|
|
364
|
+
catalog: Self::read_optional(&paths.codex_catalog_path())?,
|
|
365
|
+
catalog_backup: Self::read_optional(&paths.catalog_backup_file)?,
|
|
366
|
+
models_cache: Self::read_optional(&paths.codex_models_cache_path())?,
|
|
367
|
+
key: Self::read_optional(&paths.key_file)?.map(SecretBytes::new),
|
|
368
|
+
state_bytes: Self::read_optional(&paths.state_file)?,
|
|
369
|
+
};
|
|
370
|
+
snapshot.validate_homes(paths)?;
|
|
371
|
+
snapshot.persist(paths)?;
|
|
372
|
+
Ok(snapshot)
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
fn canonical_homes(paths: &ChildPaths) -> Result<(String, String), String> {
|
|
376
|
+
let ocx = fs::canonicalize(&paths.opencodex_home)
|
|
377
|
+
.map_err(|e| format!("cannot resolve OpenCodex home for rollback: {e}"))?;
|
|
378
|
+
let codex = fs::canonicalize(&paths.codex_home)
|
|
379
|
+
.map_err(|e| format!("cannot resolve Codex home for rollback: {e}"))?;
|
|
380
|
+
let ocx = ocx.to_str().ok_or("OpenCodex home is not UTF-8")?;
|
|
381
|
+
let codex = codex.to_str().ok_or("Codex home is not UTF-8")?;
|
|
382
|
+
Ok((ocx.to_owned(), codex.to_owned()))
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
fn validate_homes(&self, paths: &ChildPaths) -> Result<(), String> {
|
|
386
|
+
let (ocx, codex) = Self::canonical_homes(paths)?;
|
|
387
|
+
if ocx != self.opencodex_home
|
|
388
|
+
|| codex != self.codex_home
|
|
389
|
+
|| directory_identity(std::path::Path::new(&ocx))? != self.opencodex_home_identity
|
|
390
|
+
|| directory_identity(std::path::Path::new(&codex))? != self.codex_home_identity
|
|
391
|
+
{
|
|
392
|
+
return Err("rollback snapshot belongs to a different home".to_owned());
|
|
393
|
+
}
|
|
394
|
+
Ok(())
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
fn persist(&self, paths: &ChildPaths) -> Result<(), String> {
|
|
398
|
+
ensure_private_dir(&paths.child_dir)?;
|
|
399
|
+
let mut builder = fs::DirBuilder::new();
|
|
400
|
+
builder.recursive(true);
|
|
401
|
+
#[cfg(unix)]
|
|
402
|
+
{
|
|
403
|
+
use std::os::unix::fs::DirBuilderExt;
|
|
404
|
+
builder.mode(0o700);
|
|
405
|
+
}
|
|
406
|
+
builder
|
|
407
|
+
.create(&paths.codex_home)
|
|
408
|
+
.map_err(|e| format!("cannot create Codex home for rollback: {e}"))?;
|
|
409
|
+
reject_symlink(&paths.rollback_file)?;
|
|
410
|
+
match fs::symlink_metadata(&paths.rollback_file) {
|
|
411
|
+
Ok(_) => return Err("attach refused: unresolved rollback snapshot exists".to_owned()),
|
|
412
|
+
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
|
413
|
+
Err(e) => return Err(format!("cannot inspect rollback snapshot: {e}")),
|
|
414
|
+
}
|
|
415
|
+
self.validate_homes(paths)?;
|
|
416
|
+
let record = AttachRollbackRecordRef {
|
|
417
|
+
schema: "ocx.child.attach-rollback/1",
|
|
418
|
+
opencodex_home_identity: self.opencodex_home_identity.clone(),
|
|
419
|
+
codex_home_identity: self.codex_home_identity.clone(),
|
|
420
|
+
opencodex_home: self.opencodex_home.clone(),
|
|
421
|
+
codex_home: self.codex_home.clone(),
|
|
422
|
+
prior_state: &self.prior_state,
|
|
423
|
+
prior_was_serving: self.prior_was_serving,
|
|
424
|
+
journal: self.journal.as_deref(),
|
|
425
|
+
config: self.config.as_deref(),
|
|
426
|
+
catalog: self.catalog.as_deref(),
|
|
427
|
+
catalog_backup: self.catalog_backup.as_deref(),
|
|
428
|
+
models_cache: self.models_cache.as_deref(),
|
|
429
|
+
key: self.key.as_ref().map(SecretBytes::as_slice),
|
|
430
|
+
state_bytes: self.state_bytes.as_deref(),
|
|
431
|
+
};
|
|
432
|
+
let mut bytes = serde_json::to_vec(&record)
|
|
433
|
+
.map_err(|e| format!("cannot serialize rollback snapshot: {e}"))?;
|
|
434
|
+
if bytes.len() as u64 > MAX_ROLLBACK_BYTES {
|
|
435
|
+
volatile_zero_bytes(&mut bytes);
|
|
436
|
+
return Err("rollback snapshot exceeds size limit".to_owned());
|
|
437
|
+
}
|
|
438
|
+
let result = write_private_atomic(&paths.rollback_file, &bytes);
|
|
439
|
+
volatile_zero_bytes(&mut bytes);
|
|
440
|
+
result
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
fn recover(guard: &CodexHomeGuard) -> Result<bool, String> {
|
|
444
|
+
let paths = guard.paths();
|
|
445
|
+
reject_symlink(&paths.rollback_file)?;
|
|
446
|
+
let file = match fs::File::open(&paths.rollback_file) {
|
|
447
|
+
Ok(file) => file,
|
|
448
|
+
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
|
|
449
|
+
Err(e) => return Err(format!("cannot open rollback snapshot: {e}")),
|
|
450
|
+
};
|
|
451
|
+
let mut bytes = Vec::new();
|
|
452
|
+
file.take(MAX_ROLLBACK_BYTES + 1)
|
|
453
|
+
.read_to_end(&mut bytes)
|
|
454
|
+
.map_err(|e| format!("cannot read rollback snapshot: {e}"))?;
|
|
455
|
+
if bytes.len() as u64 > MAX_ROLLBACK_BYTES {
|
|
456
|
+
volatile_zero_bytes(&mut bytes);
|
|
457
|
+
return Err("rollback snapshot exceeds size limit".to_owned());
|
|
458
|
+
}
|
|
459
|
+
let parsed = serde_json::from_slice::<AttachRollbackRecord>(&bytes);
|
|
460
|
+
volatile_zero_bytes(&mut bytes);
|
|
461
|
+
let mut record = parsed.map_err(|e| format!("invalid rollback snapshot: {e}"))?;
|
|
462
|
+
let (ocx, codex) = Self::canonical_homes(paths)?;
|
|
463
|
+
if record.schema != "ocx.child.attach-rollback/1"
|
|
464
|
+
|| record.opencodex_home != ocx
|
|
465
|
+
|| record.codex_home != codex
|
|
466
|
+
|| record.opencodex_home_identity != directory_identity(std::path::Path::new(&ocx))?
|
|
467
|
+
|| record.codex_home_identity != directory_identity(std::path::Path::new(&codex))?
|
|
468
|
+
{
|
|
469
|
+
return Err("rollback snapshot belongs to a different home".to_owned());
|
|
470
|
+
}
|
|
471
|
+
match read_child_state(&paths.state_file) {
|
|
472
|
+
StateReadOutcome::Valid(state) => stop_owned_daemon(&state)?,
|
|
473
|
+
StateReadOutcome::Absent => {}
|
|
474
|
+
StateReadOutcome::Invalid(_) => {
|
|
475
|
+
return Err("cannot recover rollback with invalid child state".to_owned());
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
let snapshot = Self {
|
|
479
|
+
opencodex_home: record.opencodex_home.clone(),
|
|
480
|
+
codex_home: record.codex_home.clone(),
|
|
481
|
+
opencodex_home_identity: record.opencodex_home_identity.clone(),
|
|
482
|
+
codex_home_identity: record.codex_home_identity.clone(),
|
|
483
|
+
prior_state: record.prior_state.take(),
|
|
484
|
+
// A recovery requested by detach restores files without starting a daemon.
|
|
485
|
+
prior_was_serving: false,
|
|
486
|
+
journal: record.journal.take(),
|
|
487
|
+
config: record.config.take(),
|
|
488
|
+
catalog: record.catalog.take(),
|
|
489
|
+
catalog_backup: record.catalog_backup.take(),
|
|
490
|
+
models_cache: record.models_cache.take(),
|
|
491
|
+
key: record.key.take().map(SecretBytes::new),
|
|
492
|
+
state_bytes: record.state_bytes.take(),
|
|
493
|
+
};
|
|
494
|
+
let _ = record.prior_was_serving;
|
|
495
|
+
snapshot.restore(guard)?;
|
|
496
|
+
Ok(true)
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/// Restore one file. An ordinary failure is collected in `errors` so the remaining files
|
|
500
|
+
/// are still attempted; a changed home stops restoration at once (`Err`).
|
|
501
|
+
fn restore_path(
|
|
502
|
+
guard: &CodexHomeGuard,
|
|
503
|
+
path: &std::path::Path,
|
|
504
|
+
bytes: Option<&[u8]>,
|
|
505
|
+
private: bool,
|
|
506
|
+
errors: &mut Vec<String>,
|
|
507
|
+
) -> Result<(), String> {
|
|
508
|
+
let result = guard.restore_step(|| match bytes {
|
|
509
|
+
Some(b) if private => write_private_atomic(path, b),
|
|
510
|
+
Some(b) => write_regular_atomic(path, b),
|
|
511
|
+
None => remove_optional_file(path),
|
|
512
|
+
});
|
|
513
|
+
match result {
|
|
514
|
+
Ok(()) => Ok(()),
|
|
515
|
+
Err(RestoreStepError::Failed(e)) => {
|
|
516
|
+
errors.push(format!("restore {}: {e}", path.display()));
|
|
517
|
+
Ok(())
|
|
518
|
+
}
|
|
519
|
+
Err(RestoreStepError::HomeChanged(e)) => Err(format!("attach rollback stopped: {e}")),
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
pub fn restore(&self, guard: &CodexHomeGuard) -> Result<(), String> {
|
|
524
|
+
let paths = guard.paths();
|
|
525
|
+
self.validate_homes(paths)?;
|
|
526
|
+
let mut errors = Vec::new();
|
|
527
|
+
for (path, bytes) in [
|
|
528
|
+
(paths.codex_config_path(), self.config.as_deref()),
|
|
529
|
+
(paths.codex_catalog_path(), self.catalog.as_deref()),
|
|
530
|
+
(
|
|
531
|
+
paths.codex_models_cache_path(),
|
|
532
|
+
self.models_cache.as_deref(),
|
|
533
|
+
),
|
|
534
|
+
] {
|
|
535
|
+
Self::restore_path(guard, &path, bytes, false, &mut errors)?;
|
|
536
|
+
}
|
|
537
|
+
if errors.is_empty() {
|
|
538
|
+
for (path, bytes) in [
|
|
539
|
+
(&paths.catalog_backup_file, self.catalog_backup.as_deref()),
|
|
540
|
+
(
|
|
541
|
+
&paths.key_file,
|
|
542
|
+
self.key.as_ref().map(SecretBytes::as_slice),
|
|
543
|
+
),
|
|
544
|
+
(&paths.state_file, self.state_bytes.as_deref()),
|
|
545
|
+
] {
|
|
546
|
+
Self::restore_path(guard, path, bytes, true, &mut errors)?;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if errors.is_empty() {
|
|
550
|
+
Self::restore_path(
|
|
551
|
+
guard,
|
|
552
|
+
&paths.journal_file,
|
|
553
|
+
self.journal.as_deref(),
|
|
554
|
+
true,
|
|
555
|
+
&mut errors,
|
|
556
|
+
)?;
|
|
557
|
+
}
|
|
558
|
+
let mut restarted = None;
|
|
559
|
+
if let Some(mut prev) = self.prior_state.clone()
|
|
560
|
+
&& self.prior_was_serving
|
|
561
|
+
&& errors.is_empty()
|
|
562
|
+
&& probe_local_healthz(prev.listen_port, Duration::from_millis(250)).is_none()
|
|
563
|
+
{
|
|
564
|
+
let state_key_consistent = match read_child_state(&paths.state_file) {
|
|
565
|
+
StateReadOutcome::Valid(st)
|
|
566
|
+
if st.link_id == prev.link_id
|
|
567
|
+
&& st.token_fingerprint == prev.token_fingerprint =>
|
|
568
|
+
{
|
|
569
|
+
read_verified_link_key(&paths.key_file, &st.token_fingerprint).is_ok()
|
|
570
|
+
}
|
|
571
|
+
_ => false,
|
|
572
|
+
};
|
|
573
|
+
if !state_key_consistent {
|
|
574
|
+
errors.push("prior relay restart skipped: restored state.json and link-key are inconsistent".to_owned());
|
|
575
|
+
} else {
|
|
576
|
+
// The state naming the new generation and PID is durable once this returns.
|
|
577
|
+
match start_or_rollover_daemon(paths, &mut prev, None) {
|
|
578
|
+
Ok(pending) => restarted = Some(pending),
|
|
579
|
+
Err(e) => errors.push(format!("restart prior daemon: {e}")),
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
if errors.is_empty() {
|
|
584
|
+
// The rollback record goes only after restoration verified both homes, and before a
|
|
585
|
+
// restarted prior relay is committed, so that relay never serves while recovery
|
|
586
|
+
// could still restore files underneath it. Dropping an uncommitted relay stops it.
|
|
587
|
+
guard
|
|
588
|
+
.restore_step(|| remove_optional_file(&paths.rollback_file))
|
|
589
|
+
.map_err(RestoreStepError::into_message)?;
|
|
590
|
+
if let Some(pending) = restarted {
|
|
591
|
+
pending.commit().map_err(|e| {
|
|
592
|
+
format!("attach rolled back, but the prior relay did not restart: {e}")
|
|
593
|
+
})?;
|
|
594
|
+
}
|
|
595
|
+
Ok(())
|
|
596
|
+
} else {
|
|
597
|
+
Err(format!("attach rollback incomplete: {}", errors.join("; ")))
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/// Restore after a failed attach; true when every file and record was restored.
|
|
602
|
+
fn restore_and_report(&self, guard: &CodexHomeGuard) -> bool {
|
|
603
|
+
match self.restore(guard) {
|
|
604
|
+
Ok(()) => true,
|
|
605
|
+
Err(rb_err) => {
|
|
606
|
+
eprintln!("{rb_err}");
|
|
607
|
+
false
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
fn cmd_attach_or_connect(args: &[String], native_attach_default_start: bool) -> u8 {
|
|
614
|
+
let mut link_id: Option<String> = None;
|
|
615
|
+
let mut tunnel_port: Option<u16> = None;
|
|
616
|
+
let mut listen_port: u16 = default_listen_port();
|
|
617
|
+
let mut start_daemon = native_attach_default_start;
|
|
618
|
+
let mut i = 0;
|
|
619
|
+
while i < args.len() {
|
|
620
|
+
match args[i].as_str() {
|
|
621
|
+
"--link" | "--key-stdin" => i += 1,
|
|
622
|
+
"--start-daemon" => {
|
|
623
|
+
start_daemon = true;
|
|
624
|
+
i += 1;
|
|
625
|
+
}
|
|
626
|
+
"--no-daemon" => {
|
|
627
|
+
start_daemon = false;
|
|
628
|
+
i += 1;
|
|
629
|
+
}
|
|
630
|
+
"--link-id" => {
|
|
631
|
+
link_id = args.get(i + 1).cloned();
|
|
632
|
+
i += 2;
|
|
633
|
+
}
|
|
634
|
+
"--tunnel-port" => {
|
|
635
|
+
tunnel_port = args.get(i + 1).and_then(|s| s.parse::<u16>().ok());
|
|
636
|
+
i += 2;
|
|
637
|
+
}
|
|
638
|
+
"--listen-port" | "--port" => {
|
|
639
|
+
if let Some(p) = args.get(i + 1).and_then(|s| s.parse::<u16>().ok()) {
|
|
640
|
+
listen_port = p;
|
|
641
|
+
} else {
|
|
642
|
+
eprintln!("invalid --listen-port");
|
|
643
|
+
return 2;
|
|
644
|
+
}
|
|
645
|
+
i += 2;
|
|
646
|
+
}
|
|
647
|
+
"--clients" => i += 2,
|
|
648
|
+
other => {
|
|
649
|
+
eprintln!("unrecognized attach/connect argument: {other}");
|
|
650
|
+
return 2;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
let Some(link_id) = link_id.filter(|id| is_valid_link_id(id)) else {
|
|
655
|
+
eprintln!("--link-id lnk_<16hex> is required");
|
|
656
|
+
return 2;
|
|
657
|
+
};
|
|
658
|
+
let Some(tunnel_port) = tunnel_port.filter(|&p| p >= 1024) else {
|
|
659
|
+
eprintln!("--tunnel-port <1024..65535> is required");
|
|
660
|
+
return 2;
|
|
661
|
+
};
|
|
662
|
+
let (api_key_id, raw_key) = match read_stdin_credential() {
|
|
663
|
+
Ok(v) => v,
|
|
664
|
+
Err(e) => {
|
|
665
|
+
eprintln!("{e}");
|
|
666
|
+
return 2;
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
|
|
670
|
+
let local_paths = current_paths();
|
|
671
|
+
let _lock = match FileLock::acquire_blocking(&local_paths.lock_file) {
|
|
672
|
+
Ok(l) => l,
|
|
673
|
+
Err(_) => {
|
|
674
|
+
eprintln!("attach failed: could not acquire child lifecycle lock");
|
|
675
|
+
return 1;
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
|
|
679
|
+
if !matches!(rollback_pending(&local_paths), Ok(false)) {
|
|
680
|
+
eprintln!("attach refused: incomplete attach requires detach recovery");
|
|
681
|
+
return 1;
|
|
682
|
+
}
|
|
683
|
+
let mut guard = match CodexHomeGuard::acquire(&local_paths, true, true, ClaimPolicy::Attach) {
|
|
684
|
+
Ok(guard) => guard,
|
|
685
|
+
Err(e) => {
|
|
686
|
+
eprintln!("attach refused: {}", e.message());
|
|
687
|
+
return 1;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
crate::test_hooks::barrier("attach-protected");
|
|
691
|
+
let request = AttachRequest {
|
|
692
|
+
link_id,
|
|
693
|
+
tunnel_port,
|
|
694
|
+
listen_port,
|
|
695
|
+
start_daemon,
|
|
696
|
+
api_key_id,
|
|
697
|
+
raw_key,
|
|
698
|
+
};
|
|
699
|
+
match attach_locked(&mut guard, request) {
|
|
700
|
+
Ok(()) => 0,
|
|
701
|
+
Err(failure) => {
|
|
702
|
+
if failure.left_no_changes
|
|
703
|
+
&& let Err(e) = guard.revert_claim()
|
|
704
|
+
{
|
|
705
|
+
eprintln!("attach could not release Codex home ownership: {e}");
|
|
706
|
+
}
|
|
707
|
+
failure.code
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
struct AttachRequest {
|
|
713
|
+
link_id: String,
|
|
714
|
+
tunnel_port: u16,
|
|
715
|
+
listen_port: u16,
|
|
716
|
+
start_daemon: bool,
|
|
717
|
+
api_key_id: String,
|
|
718
|
+
raw_key: SecretBytes,
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
struct AttachFailure {
|
|
722
|
+
code: u8,
|
|
723
|
+
/// True when nothing was changed, or every change was rolled back and recorded as such.
|
|
724
|
+
left_no_changes: bool,
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
fn attach_locked(guard: &mut CodexHomeGuard, request: AttachRequest) -> Result<(), AttachFailure> {
|
|
728
|
+
let AttachRequest {
|
|
729
|
+
link_id,
|
|
730
|
+
tunnel_port,
|
|
731
|
+
listen_port,
|
|
732
|
+
start_daemon,
|
|
733
|
+
api_key_id,
|
|
734
|
+
raw_key,
|
|
735
|
+
} = request;
|
|
736
|
+
let paths = guard.paths().clone();
|
|
737
|
+
let refuse = |code: u8| AttachFailure {
|
|
738
|
+
code,
|
|
739
|
+
left_no_changes: true,
|
|
740
|
+
};
|
|
741
|
+
let prior_state = match read_child_state(&paths.state_file) {
|
|
742
|
+
StateReadOutcome::Valid(st) => Some(*st),
|
|
743
|
+
_ => None,
|
|
744
|
+
};
|
|
745
|
+
let existing_pid = prior_state
|
|
746
|
+
.as_ref()
|
|
747
|
+
.filter(|prev| prev.listen_port == listen_port)
|
|
748
|
+
.and_then(|prev| prev.daemon_pid);
|
|
749
|
+
if let Err(e) = ensure_port_available_for_attach(listen_port, existing_pid) {
|
|
750
|
+
eprintln!("{e}");
|
|
751
|
+
return Err(refuse(1));
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
let raw_key_str = match std::str::from_utf8(raw_key.as_slice()) {
|
|
755
|
+
Ok(s) => s,
|
|
756
|
+
Err(_) => {
|
|
757
|
+
eprintln!("invalid credential encoding");
|
|
758
|
+
return Err(refuse(2));
|
|
759
|
+
}
|
|
760
|
+
};
|
|
761
|
+
let fp = crate::relay_auth::token_fingerprint_hex(raw_key_str);
|
|
762
|
+
let creds = RelayCredentials {
|
|
763
|
+
api_key_id: api_key_id.clone(),
|
|
764
|
+
link_id: link_id.clone(),
|
|
765
|
+
token_fingerprint: fp.clone(),
|
|
766
|
+
raw_token: SecretBytes::new(raw_key.as_slice().to_vec()),
|
|
767
|
+
};
|
|
768
|
+
|
|
769
|
+
// Probe Home /readyz and pull /v1/catalog + /v1/link-management/codex-settings
|
|
770
|
+
match fetch_home_authenticated(
|
|
771
|
+
tunnel_port,
|
|
772
|
+
&creds,
|
|
773
|
+
"GET",
|
|
774
|
+
"/readyz",
|
|
775
|
+
RelayAuthKind::ApiKeyHeader,
|
|
776
|
+
None,
|
|
777
|
+
64 * 1024,
|
|
778
|
+
) {
|
|
779
|
+
Ok((h, _, _)) if h.status == 200 => {}
|
|
780
|
+
Ok((h, _, _)) => {
|
|
781
|
+
eprintln!("Home /readyz returned HTTP {}", h.status);
|
|
782
|
+
return Err(refuse(1));
|
|
783
|
+
}
|
|
784
|
+
Err(e) => {
|
|
785
|
+
eprintln!("Home /readyz unreachable over tunnel: {e:?}");
|
|
786
|
+
return Err(refuse(1));
|
|
787
|
+
}
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
let catalog_bytes = match fetch_home_authenticated(
|
|
791
|
+
tunnel_port,
|
|
792
|
+
&creds,
|
|
793
|
+
"GET",
|
|
794
|
+
"/v1/catalog",
|
|
795
|
+
RelayAuthKind::Bearer,
|
|
796
|
+
None,
|
|
797
|
+
4 * 1024 * 1024,
|
|
798
|
+
) {
|
|
799
|
+
Ok((h, b, _)) if h.status == 200 => b,
|
|
800
|
+
Ok((h, _, _)) => {
|
|
801
|
+
eprintln!("Home /v1/catalog returned HTTP {}", h.status);
|
|
802
|
+
return Err(refuse(1));
|
|
803
|
+
}
|
|
804
|
+
Err(e) => {
|
|
805
|
+
eprintln!("Home /v1/catalog failed: {e:?}");
|
|
806
|
+
return Err(refuse(1));
|
|
807
|
+
}
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
let settings_doc = match fetch_home_settings_doc(tunnel_port, &creds) {
|
|
811
|
+
Ok(d) => d,
|
|
812
|
+
Err(e) => {
|
|
813
|
+
eprintln!("{e}");
|
|
814
|
+
return Err(refuse(1));
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
let rollback = match AttachRollbackSnapshot::capture(guard, prior_state.clone()) {
|
|
819
|
+
Ok(r) => r,
|
|
820
|
+
Err(e) => {
|
|
821
|
+
eprintln!("{e}");
|
|
822
|
+
// A persisted snapshot means changes may need recovery; keep ownership for detach.
|
|
823
|
+
let left_no_changes = matches!(rollback_pending(&paths), Ok(false));
|
|
824
|
+
return Err(AttachFailure {
|
|
825
|
+
code: 1,
|
|
826
|
+
left_no_changes,
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
};
|
|
830
|
+
|
|
831
|
+
let journal = match apply_attach_or_sync(
|
|
832
|
+
guard,
|
|
833
|
+
&link_id,
|
|
834
|
+
&api_key_id,
|
|
835
|
+
listen_port,
|
|
836
|
+
&catalog_bytes,
|
|
837
|
+
&settings_doc.settings,
|
|
838
|
+
) {
|
|
839
|
+
Ok(j) => j,
|
|
840
|
+
Err(e) => {
|
|
841
|
+
let restored = rollback.restore_and_report(guard);
|
|
842
|
+
eprintln!("{e}");
|
|
843
|
+
return Err(AttachFailure {
|
|
844
|
+
code: 1,
|
|
845
|
+
left_no_changes: restored,
|
|
846
|
+
});
|
|
847
|
+
}
|
|
848
|
+
};
|
|
849
|
+
|
|
850
|
+
if let Err(e) = write_link_key(&paths.key_file, raw_key_str) {
|
|
851
|
+
let restored = rollback.restore_and_report(guard);
|
|
852
|
+
eprintln!("{e}");
|
|
853
|
+
return Err(AttachFailure {
|
|
854
|
+
code: 1,
|
|
855
|
+
left_no_changes: restored,
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
let now_ms = now_epoch_ms();
|
|
860
|
+
let now_iso = format_iso8601_utc(now_ms);
|
|
861
|
+
let digest = codex_settings_digest(&settings_doc.settings);
|
|
862
|
+
let shutdown_secret = match random_hex(24) {
|
|
863
|
+
Ok(s) => s,
|
|
864
|
+
Err(e) => {
|
|
865
|
+
let restored = rollback.restore_and_report(guard);
|
|
866
|
+
eprintln!("{e}");
|
|
867
|
+
return Err(AttachFailure {
|
|
868
|
+
code: 1,
|
|
869
|
+
left_no_changes: restored,
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
if let Some(prev) = &prior_state
|
|
874
|
+
&& prev.listen_port != listen_port
|
|
875
|
+
&& let Err(e) = stop_owned_daemon(prev)
|
|
876
|
+
{
|
|
877
|
+
let restored = rollback.restore_and_report(guard);
|
|
878
|
+
eprintln!(
|
|
879
|
+
"attach failed stopping previous relay on port {}: {e}",
|
|
880
|
+
prev.listen_port
|
|
881
|
+
);
|
|
882
|
+
return Err(AttachFailure {
|
|
883
|
+
code: 1,
|
|
884
|
+
left_no_changes: restored,
|
|
885
|
+
});
|
|
886
|
+
}
|
|
887
|
+
let mut state = ChildStateV1 {
|
|
888
|
+
schema: CHILD_STATE_SCHEMA.to_owned(),
|
|
889
|
+
link_id: link_id.clone(),
|
|
890
|
+
api_key_id: api_key_id.clone(),
|
|
891
|
+
token_fingerprint: fp,
|
|
892
|
+
tunnel_port,
|
|
893
|
+
listen_port,
|
|
894
|
+
connected_at: now_iso.clone(),
|
|
895
|
+
catalog_fingerprint: journal.latest_catalog_sha256,
|
|
896
|
+
catalog_synced_at: now_iso.clone(),
|
|
897
|
+
daemon_pid: existing_pid,
|
|
898
|
+
daemon_started_at_ms: None,
|
|
899
|
+
shutdown_secret: shutdown_secret.into(),
|
|
900
|
+
parity_sequence: 0,
|
|
901
|
+
pending_operation: None,
|
|
902
|
+
daemon_generation: None,
|
|
903
|
+
applied_settings: Some(AppliedSettingsRecord {
|
|
904
|
+
link_id: link_id.clone(),
|
|
905
|
+
fetched_at: now_iso.clone(),
|
|
906
|
+
applied_at: now_iso,
|
|
907
|
+
applied_at_ms: now_ms,
|
|
908
|
+
digest: digest.clone(),
|
|
909
|
+
document: settings_doc,
|
|
910
|
+
}),
|
|
911
|
+
};
|
|
912
|
+
if let Err(e) = write_child_state(&paths.state_file, &state) {
|
|
913
|
+
let restored = rollback.restore_and_report(guard);
|
|
914
|
+
eprintln!("{e}");
|
|
915
|
+
return Err(AttachFailure {
|
|
916
|
+
code: 1,
|
|
917
|
+
left_no_changes: restored,
|
|
918
|
+
});
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
let pending = if start_daemon {
|
|
922
|
+
crate::test_hooks::barrier("attach-before-daemon-start");
|
|
923
|
+
match start_or_rollover_daemon(&paths, &mut state, Some(now_ms)) {
|
|
924
|
+
Ok(pending) => Some(pending),
|
|
925
|
+
Err(e) => {
|
|
926
|
+
let restored = rollback.restore_and_report(guard);
|
|
927
|
+
eprintln!("{e}");
|
|
928
|
+
return Err(AttachFailure {
|
|
929
|
+
code: 1,
|
|
930
|
+
left_no_changes: restored,
|
|
931
|
+
});
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
} else {
|
|
935
|
+
None
|
|
936
|
+
};
|
|
937
|
+
|
|
938
|
+
if let Err(e) = guard.set_phase(OwnershipPhase::Attached) {
|
|
939
|
+
// Stop the uncommitted daemon before restoring files it could otherwise serve.
|
|
940
|
+
drop(pending);
|
|
941
|
+
let restored = rollback.restore_and_report(guard);
|
|
942
|
+
eprintln!("attach failed recording Codex home ownership: {e}");
|
|
943
|
+
return Err(AttachFailure {
|
|
944
|
+
code: 1,
|
|
945
|
+
left_no_changes: restored,
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
if let Err(e) = remove_optional_file(&paths.rollback_file) {
|
|
949
|
+
drop(pending);
|
|
950
|
+
eprintln!("attach failed to clear rollback snapshot: {e}");
|
|
951
|
+
return Err(AttachFailure {
|
|
952
|
+
code: 1,
|
|
953
|
+
left_no_changes: false,
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
// The daemon may serve only now: state and ownership are durable and the rollback record
|
|
957
|
+
// is gone, so recovery can no longer restore files underneath it.
|
|
958
|
+
if let Some(pending) = pending {
|
|
959
|
+
match pending.commit() {
|
|
960
|
+
Ok((_, started_ms)) => {
|
|
961
|
+
state.parity_sequence += 1;
|
|
962
|
+
let _ = write_child_state(&paths.state_file, &state);
|
|
963
|
+
let report = LinkChildParityReport {
|
|
964
|
+
link_id,
|
|
965
|
+
last_apply_at: Some(now_ms),
|
|
966
|
+
runtime_started_at: started_ms,
|
|
967
|
+
applied_codex_settings_digest: Some(digest),
|
|
968
|
+
sequence: state.parity_sequence,
|
|
969
|
+
};
|
|
970
|
+
let _ = post_child_parity_report(tunnel_port, &creds, &report);
|
|
971
|
+
}
|
|
972
|
+
Err(e) => {
|
|
973
|
+
eprintln!(
|
|
974
|
+
"attach completed but the client relay did not start: {e}; run `ocx-child restart`"
|
|
975
|
+
);
|
|
976
|
+
return Err(AttachFailure {
|
|
977
|
+
code: 1,
|
|
978
|
+
left_no_changes: false,
|
|
979
|
+
});
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
println!("Connected to http://127.0.0.1:{tunnel_port}.");
|
|
984
|
+
println!("Local Codex CLI: ready (ephemeral ocx-child Design B attached).");
|
|
985
|
+
Ok(())
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
struct LifecycleStart {
|
|
989
|
+
generation: String,
|
|
990
|
+
secret: SecretBytes,
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/// Read the parent's start line: `ocx-child-start/1 <generation> <shutdown secret>\n`.
|
|
994
|
+
fn read_lifecycle_start() -> Result<LifecycleStart, String> {
|
|
995
|
+
let mut line = Vec::with_capacity(128);
|
|
996
|
+
let read = io::stdin().lock().take(161).read_until(b'\n', &mut line);
|
|
997
|
+
let buffer = SecretBytes::new(line);
|
|
998
|
+
read.map_err(|e| format!("cannot read lifecycle start line: {e}"))?;
|
|
999
|
+
let text = std::str::from_utf8(buffer.as_slice())
|
|
1000
|
+
.ok()
|
|
1001
|
+
.and_then(|t| t.strip_suffix('\n'))
|
|
1002
|
+
.ok_or("invalid lifecycle start line")?;
|
|
1003
|
+
let mut parts = text.split(' ');
|
|
1004
|
+
match (parts.next(), parts.next(), parts.next(), parts.next()) {
|
|
1005
|
+
(Some("ocx-child-start/1"), Some(generation), Some(secret), None)
|
|
1006
|
+
if is_valid_daemon_generation(generation) && secret.len() == 48 =>
|
|
1007
|
+
{
|
|
1008
|
+
Ok(LifecycleStart {
|
|
1009
|
+
generation: generation.to_owned(),
|
|
1010
|
+
secret: SecretBytes::new(secret.as_bytes().to_vec()),
|
|
1011
|
+
})
|
|
1012
|
+
}
|
|
1013
|
+
_ => Err("invalid lifecycle start line".to_owned()),
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
fn cmd_serve(args: &[String]) -> u8 {
|
|
1018
|
+
let mut foreground = false;
|
|
1019
|
+
let mut lifecycle_start = false;
|
|
1020
|
+
let mut listen_port: Option<u16> = None;
|
|
1021
|
+
let mut i = 0;
|
|
1022
|
+
while i < args.len() {
|
|
1023
|
+
match args[i].as_str() {
|
|
1024
|
+
"--foreground" => {
|
|
1025
|
+
foreground = true;
|
|
1026
|
+
i += 1;
|
|
1027
|
+
}
|
|
1028
|
+
"--lifecycle-start" => {
|
|
1029
|
+
lifecycle_start = true;
|
|
1030
|
+
i += 1;
|
|
1031
|
+
}
|
|
1032
|
+
"--listen-port" | "--port" => {
|
|
1033
|
+
listen_port = args.get(i + 1).and_then(|s| s.parse::<u16>().ok());
|
|
1034
|
+
i += 2;
|
|
1035
|
+
}
|
|
1036
|
+
_ => i += 1,
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
let paths = current_paths();
|
|
1040
|
+
if foreground {
|
|
1041
|
+
let start = if lifecycle_start {
|
|
1042
|
+
match read_lifecycle_start() {
|
|
1043
|
+
Ok(start) => Some(start),
|
|
1044
|
+
Err(e) => {
|
|
1045
|
+
eprintln!("serve refused: {e}");
|
|
1046
|
+
return 1;
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
} else {
|
|
1050
|
+
None
|
|
1051
|
+
};
|
|
1052
|
+
// Watch for the commit from now on, so a parent that dies while this process waits
|
|
1053
|
+
// on the start gate still ends it.
|
|
1054
|
+
let committed = start
|
|
1055
|
+
.as_ref()
|
|
1056
|
+
.map(|s| crate::relay::spawn_commit_watcher(s.generation.clone()));
|
|
1057
|
+
let state = match read_child_state(&paths.state_file) {
|
|
1058
|
+
StateReadOutcome::Valid(st) if st.pending_operation.is_none() => st,
|
|
1059
|
+
StateReadOutcome::Absent => {
|
|
1060
|
+
eprintln!("serve refused: ocx-child is detached (no active link)");
|
|
1061
|
+
return 1;
|
|
1062
|
+
}
|
|
1063
|
+
_ => {
|
|
1064
|
+
eprintln!("serve refused: child state is invalid or pending teardown");
|
|
1065
|
+
return 1;
|
|
1066
|
+
}
|
|
1067
|
+
};
|
|
1068
|
+
if !matches!(validate_existing_journal_paths(&paths), Ok(true)) {
|
|
1069
|
+
eprintln!(
|
|
1070
|
+
"serve refused: child recovery journal is missing or belongs to another home"
|
|
1071
|
+
);
|
|
1072
|
+
return 1;
|
|
1073
|
+
}
|
|
1074
|
+
match rollback_pending(&paths) {
|
|
1075
|
+
Ok(true) if start.is_none() => {
|
|
1076
|
+
eprintln!("serve refused: incomplete attach requires lifecycle authorization");
|
|
1077
|
+
return 1;
|
|
1078
|
+
}
|
|
1079
|
+
Ok(_) => {}
|
|
1080
|
+
Err(e) => {
|
|
1081
|
+
eprintln!("serve refused: {e}");
|
|
1082
|
+
return 1;
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
if let Some(start) = &start
|
|
1086
|
+
&& !constant_time_eq(start.secret.as_slice(), state.shutdown_secret.as_bytes())
|
|
1087
|
+
{
|
|
1088
|
+
eprintln!("serve refused: lifecycle authorization does not match child state");
|
|
1089
|
+
return 1;
|
|
1090
|
+
}
|
|
1091
|
+
if let Err(e) = read_verified_link_key(&paths.key_file, &state.token_fingerprint) {
|
|
1092
|
+
eprintln!("serve refused: {e}");
|
|
1093
|
+
return 1;
|
|
1094
|
+
}
|
|
1095
|
+
let port = listen_port.unwrap_or(state.listen_port);
|
|
1096
|
+
if port != state.listen_port {
|
|
1097
|
+
eprintln!("serve refused: listen port does not match child state");
|
|
1098
|
+
return 1;
|
|
1099
|
+
}
|
|
1100
|
+
let served = match (&start, committed) {
|
|
1101
|
+
(Some(start), Some(committed)) => {
|
|
1102
|
+
crate::relay::serve_foreground_lifecycle(paths, port, &start.generation, committed)
|
|
1103
|
+
}
|
|
1104
|
+
_ => serve_foreground(paths, port),
|
|
1105
|
+
};
|
|
1106
|
+
return match served {
|
|
1107
|
+
Ok(()) => 0,
|
|
1108
|
+
Err(e) => {
|
|
1109
|
+
eprintln!("{e}");
|
|
1110
|
+
1
|
|
1111
|
+
}
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
cmd_restart()
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
fn cmd_restart() -> u8 {
|
|
1118
|
+
let paths = current_paths();
|
|
1119
|
+
let _lock = match FileLock::acquire_blocking(&paths.lock_file) {
|
|
1120
|
+
Ok(l) => l,
|
|
1121
|
+
Err(_) => {
|
|
1122
|
+
eprintln!("restart failed: child lifecycle lock busy");
|
|
1123
|
+
return 1;
|
|
1124
|
+
}
|
|
1125
|
+
};
|
|
1126
|
+
if !matches!(rollback_pending(&paths), Ok(false)) {
|
|
1127
|
+
eprintln!("restart refused: incomplete attach requires detach recovery");
|
|
1128
|
+
return 1;
|
|
1129
|
+
}
|
|
1130
|
+
let codex_guard = match CodexHomeGuard::acquire(&paths, true, false, ClaimPolicy::Continue) {
|
|
1131
|
+
Ok(guard) => guard,
|
|
1132
|
+
Err(e) => {
|
|
1133
|
+
eprintln!("restart refused: {}", e.message());
|
|
1134
|
+
return 1;
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
let paths = codex_guard.paths().clone();
|
|
1138
|
+
let mut state = match read_child_state(&paths.state_file) {
|
|
1139
|
+
StateReadOutcome::Valid(st) if st.pending_operation.is_none() => *st,
|
|
1140
|
+
StateReadOutcome::Absent => {
|
|
1141
|
+
eprintln!("restart refused: ocx-child is detached (no active link)");
|
|
1142
|
+
return 1;
|
|
1143
|
+
}
|
|
1144
|
+
_ => {
|
|
1145
|
+
eprintln!("restart refused: child state is invalid or pending teardown");
|
|
1146
|
+
return 1;
|
|
1147
|
+
}
|
|
1148
|
+
};
|
|
1149
|
+
if !matches!(validate_existing_journal_paths(&paths), Ok(true)) {
|
|
1150
|
+
eprintln!("restart refused: child recovery journal is missing or belongs to another home");
|
|
1151
|
+
return 1;
|
|
1152
|
+
}
|
|
1153
|
+
let floor_ms = state.applied_settings.as_ref().map(|a| a.applied_at_ms);
|
|
1154
|
+
let (pid, started_ms) = match start_or_rollover_daemon(&paths, &mut state, floor_ms)
|
|
1155
|
+
.and_then(|pending| pending.commit())
|
|
1156
|
+
{
|
|
1157
|
+
Ok(v) => v,
|
|
1158
|
+
Err(e) => {
|
|
1159
|
+
eprintln!("{e}");
|
|
1160
|
+
return 1;
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
if let Ok(raw_token) = read_verified_link_key(&paths.key_file, &state.token_fingerprint) {
|
|
1164
|
+
let creds = RelayCredentials {
|
|
1165
|
+
api_key_id: state.api_key_id.clone(),
|
|
1166
|
+
link_id: state.link_id.clone(),
|
|
1167
|
+
token_fingerprint: state.token_fingerprint.clone(),
|
|
1168
|
+
raw_token,
|
|
1169
|
+
};
|
|
1170
|
+
state.parity_sequence += 1;
|
|
1171
|
+
let _ = write_child_state(&paths.state_file, &state);
|
|
1172
|
+
let (last_apply_at, digest) = match &state.applied_settings {
|
|
1173
|
+
Some(rec) => (Some(rec.applied_at_ms), Some(rec.digest.clone())),
|
|
1174
|
+
None => (None, None),
|
|
1175
|
+
};
|
|
1176
|
+
let report = LinkChildParityReport {
|
|
1177
|
+
link_id: state.link_id.clone(),
|
|
1178
|
+
last_apply_at,
|
|
1179
|
+
runtime_started_at: started_ms,
|
|
1180
|
+
applied_codex_settings_digest: digest,
|
|
1181
|
+
sequence: state.parity_sequence,
|
|
1182
|
+
};
|
|
1183
|
+
let _ = post_child_parity_report(state.tunnel_port, &creds, &report);
|
|
1184
|
+
}
|
|
1185
|
+
println!(
|
|
1186
|
+
"ocx-child client relay active (PID {pid}, port {}).",
|
|
1187
|
+
state.listen_port
|
|
1188
|
+
);
|
|
1189
|
+
0
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
fn emit_expectation_mismatch(phase: &str, reason: &str) -> u8 {
|
|
1193
|
+
eprintln!(
|
|
1194
|
+
"Sync refused ({phase}: {reason}); nothing was changed and local providers were not synced."
|
|
1195
|
+
);
|
|
1196
|
+
eprintln!("{{\"phase\":\"{phase}\",\"reason\":\"{reason}\"}}");
|
|
1197
|
+
5
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
fn cmd_sync(args: &[String]) -> u8 {
|
|
1201
|
+
let mut json_mode = false;
|
|
1202
|
+
let mut expect_link: Option<String> = None;
|
|
1203
|
+
let mut expect_hub_key: Option<String> = None;
|
|
1204
|
+
let mut expect_count = 0usize;
|
|
1205
|
+
let mut i = 0;
|
|
1206
|
+
while i < args.len() {
|
|
1207
|
+
let arg = &args[i];
|
|
1208
|
+
if arg == "--json" {
|
|
1209
|
+
json_mode = true;
|
|
1210
|
+
i += 1;
|
|
1211
|
+
} else if arg == "--local-only"
|
|
1212
|
+
|| arg == "--restart-codex"
|
|
1213
|
+
|| arg == "--restart-app-server-only"
|
|
1214
|
+
{
|
|
1215
|
+
i += 1;
|
|
1216
|
+
} else if arg == "--expect-link" {
|
|
1217
|
+
expect_count += 1;
|
|
1218
|
+
expect_link = args.get(i + 1).cloned();
|
|
1219
|
+
i += 2;
|
|
1220
|
+
} else if let Some(val) = arg.strip_prefix("--expect-link=") {
|
|
1221
|
+
expect_count += 1;
|
|
1222
|
+
expect_link = Some(val.to_owned());
|
|
1223
|
+
i += 1;
|
|
1224
|
+
} else if arg == "--expect-hub-key" {
|
|
1225
|
+
expect_count += 1;
|
|
1226
|
+
expect_hub_key = args.get(i + 1).cloned();
|
|
1227
|
+
i += 2;
|
|
1228
|
+
} else if let Some(val) = arg.strip_prefix("--expect-hub-key=") {
|
|
1229
|
+
expect_count += 1;
|
|
1230
|
+
expect_hub_key = Some(val.to_owned());
|
|
1231
|
+
i += 1;
|
|
1232
|
+
} else {
|
|
1233
|
+
eprintln!("unrecognized sync flag: {arg}");
|
|
1234
|
+
return 2;
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
if expect_count > 1 {
|
|
1238
|
+
eprintln!("ocx sync accepts one --expect-link or --expect-hub-key, given once.");
|
|
1239
|
+
return 2;
|
|
1240
|
+
}
|
|
1241
|
+
if let Some(id) = &expect_link
|
|
1242
|
+
&& !is_valid_link_id(id)
|
|
1243
|
+
{
|
|
1244
|
+
eprintln!(
|
|
1245
|
+
"--expect-link needs a link id of the form lnk_ followed by 16 hex digits (see ocx connect status --json)."
|
|
1246
|
+
);
|
|
1247
|
+
return 2;
|
|
1248
|
+
}
|
|
1249
|
+
if let Some(k) = &expect_hub_key
|
|
1250
|
+
&& (k.trim().is_empty() || k.trim() != k || k.len() > 256)
|
|
1251
|
+
{
|
|
1252
|
+
eprintln!(
|
|
1253
|
+
"--expect-hub-key needs the connected API key id (see ocx connect status --json)."
|
|
1254
|
+
);
|
|
1255
|
+
return 2;
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
let paths = current_paths();
|
|
1259
|
+
let has_expectation = expect_link.is_some() || expect_hub_key.is_some();
|
|
1260
|
+
let _lock = if has_expectation {
|
|
1261
|
+
match FileLock::try_acquire_nonblocking(&paths.lock_file) {
|
|
1262
|
+
Ok(l) => l,
|
|
1263
|
+
Err(LockAcquireError::Busy) => {
|
|
1264
|
+
let phase = if expect_link.is_some() {
|
|
1265
|
+
"child_link_mismatch"
|
|
1266
|
+
} else {
|
|
1267
|
+
"hub_client_mismatch"
|
|
1268
|
+
};
|
|
1269
|
+
return emit_expectation_mismatch(phase, "pending_operation");
|
|
1270
|
+
}
|
|
1271
|
+
Err(LockAcquireError::Io) => {
|
|
1272
|
+
let phase = if expect_link.is_some() {
|
|
1273
|
+
"child_link_mismatch"
|
|
1274
|
+
} else {
|
|
1275
|
+
"hub_client_mismatch"
|
|
1276
|
+
};
|
|
1277
|
+
return emit_expectation_mismatch(phase, "invalid_state");
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
} else {
|
|
1281
|
+
match FileLock::acquire_blocking(&paths.lock_file) {
|
|
1282
|
+
Ok(l) => l,
|
|
1283
|
+
Err(_) => {
|
|
1284
|
+
eprintln!("sync failed: child lifecycle lock unavailable");
|
|
1285
|
+
return 1;
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
|
|
1290
|
+
let mut state = match read_child_state(&paths.state_file) {
|
|
1291
|
+
StateReadOutcome::Absent => {
|
|
1292
|
+
if expect_link.is_some() {
|
|
1293
|
+
return emit_expectation_mismatch("child_link_mismatch", "disconnected");
|
|
1294
|
+
}
|
|
1295
|
+
if expect_hub_key.is_some() {
|
|
1296
|
+
return emit_expectation_mismatch("hub_client_mismatch", "disconnected");
|
|
1297
|
+
}
|
|
1298
|
+
eprintln!("ocx-child is not attached to a Remote Link Home.");
|
|
1299
|
+
return 1;
|
|
1300
|
+
}
|
|
1301
|
+
StateReadOutcome::Invalid(_) => {
|
|
1302
|
+
if expect_link.is_some() {
|
|
1303
|
+
return emit_expectation_mismatch("child_link_mismatch", "invalid_state");
|
|
1304
|
+
}
|
|
1305
|
+
if expect_hub_key.is_some() {
|
|
1306
|
+
return emit_expectation_mismatch("hub_client_mismatch", "invalid_state");
|
|
1307
|
+
}
|
|
1308
|
+
eprintln!("ocx-child state is invalid.");
|
|
1309
|
+
return 1;
|
|
1310
|
+
}
|
|
1311
|
+
StateReadOutcome::Valid(st) => *st,
|
|
1312
|
+
};
|
|
1313
|
+
if !matches!(rollback_pending(&paths), Ok(false)) {
|
|
1314
|
+
if expect_link.is_some() {
|
|
1315
|
+
return emit_expectation_mismatch("child_link_mismatch", "invalid_state");
|
|
1316
|
+
}
|
|
1317
|
+
if expect_hub_key.is_some() {
|
|
1318
|
+
return emit_expectation_mismatch("hub_client_mismatch", "invalid_state");
|
|
1319
|
+
}
|
|
1320
|
+
eprintln!("sync refused: incomplete attach requires detach recovery");
|
|
1321
|
+
return 1;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
if let Some(op) = &state.pending_operation {
|
|
1325
|
+
let reason = if op == "disconnect" {
|
|
1326
|
+
"disconnect_pending"
|
|
1327
|
+
} else {
|
|
1328
|
+
"pending_operation"
|
|
1329
|
+
};
|
|
1330
|
+
if expect_link.is_some() {
|
|
1331
|
+
return emit_expectation_mismatch("child_link_mismatch", reason);
|
|
1332
|
+
}
|
|
1333
|
+
if expect_hub_key.is_some() {
|
|
1334
|
+
return emit_expectation_mismatch("hub_client_mismatch", reason);
|
|
1335
|
+
}
|
|
1336
|
+
eprintln!("sync refused: {reason}");
|
|
1337
|
+
return 1;
|
|
1338
|
+
}
|
|
1339
|
+
if expect_hub_key.is_some() {
|
|
1340
|
+
return emit_expectation_mismatch("hub_client_mismatch", "link_client");
|
|
1341
|
+
}
|
|
1342
|
+
if let Some(expected_id) = &expect_link
|
|
1343
|
+
&& state.link_id != *expected_id
|
|
1344
|
+
{
|
|
1345
|
+
return emit_expectation_mismatch("child_link_mismatch", "other_link");
|
|
1346
|
+
}
|
|
1347
|
+
let codex_guard =
|
|
1348
|
+
match CodexHomeGuard::acquire(&paths, !has_expectation, false, ClaimPolicy::Continue) {
|
|
1349
|
+
Ok(guard) => guard,
|
|
1350
|
+
Err(e) => {
|
|
1351
|
+
if expect_link.is_some() {
|
|
1352
|
+
let reason = if e == CodexHomeError::Busy {
|
|
1353
|
+
"pending_operation"
|
|
1354
|
+
} else {
|
|
1355
|
+
"invalid_state"
|
|
1356
|
+
};
|
|
1357
|
+
return emit_expectation_mismatch("child_link_mismatch", reason);
|
|
1358
|
+
}
|
|
1359
|
+
eprintln!("sync refused: {}", e.message());
|
|
1360
|
+
return 1;
|
|
1361
|
+
}
|
|
1362
|
+
};
|
|
1363
|
+
let paths = codex_guard.paths().clone();
|
|
1364
|
+
if !matches!(validate_existing_journal_paths(&paths), Ok(true)) {
|
|
1365
|
+
if expect_link.is_some() {
|
|
1366
|
+
return emit_expectation_mismatch("child_link_mismatch", "invalid_state");
|
|
1367
|
+
}
|
|
1368
|
+
eprintln!("sync refused: child recovery journal is missing or belongs to another home");
|
|
1369
|
+
return 1;
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
let raw_token = match read_verified_link_key(&paths.key_file, &state.token_fingerprint) {
|
|
1373
|
+
Ok(t) => t,
|
|
1374
|
+
Err(e) => {
|
|
1375
|
+
if expect_link.is_some() {
|
|
1376
|
+
return emit_expectation_mismatch("child_link_mismatch", "invalid_state");
|
|
1377
|
+
}
|
|
1378
|
+
eprintln!("Connected sync failed without local fallback: {e}");
|
|
1379
|
+
return 1;
|
|
1380
|
+
}
|
|
1381
|
+
};
|
|
1382
|
+
let creds = RelayCredentials {
|
|
1383
|
+
api_key_id: state.api_key_id.clone(),
|
|
1384
|
+
link_id: state.link_id.clone(),
|
|
1385
|
+
token_fingerprint: state.token_fingerprint.clone(),
|
|
1386
|
+
raw_token,
|
|
1387
|
+
};
|
|
1388
|
+
|
|
1389
|
+
let mut stale = false;
|
|
1390
|
+
let catalog_bytes = match fetch_home_authenticated(
|
|
1391
|
+
state.tunnel_port,
|
|
1392
|
+
&creds,
|
|
1393
|
+
"GET",
|
|
1394
|
+
"/v1/catalog",
|
|
1395
|
+
RelayAuthKind::Bearer,
|
|
1396
|
+
None,
|
|
1397
|
+
4 * 1024 * 1024,
|
|
1398
|
+
) {
|
|
1399
|
+
Ok((h, b, _)) if h.status == 200 => b,
|
|
1400
|
+
result @ (Err(UpstreamError::HomeUnreachable(_)) | Ok((_, _, _)))
|
|
1401
|
+
if matches!(&result, Err(UpstreamError::HomeUnreachable(_)))
|
|
1402
|
+
|| matches!(&result, Ok((h, _, _)) if h.status >= 500) =>
|
|
1403
|
+
{
|
|
1404
|
+
match fs::read(&paths.catalog_backup_file) {
|
|
1405
|
+
Ok(cached) => {
|
|
1406
|
+
stale = true;
|
|
1407
|
+
cached
|
|
1408
|
+
}
|
|
1409
|
+
Err(_) => {
|
|
1410
|
+
eprintln!(
|
|
1411
|
+
"Connected sync failed without local fallback: Home /v1/catalog unreachable"
|
|
1412
|
+
);
|
|
1413
|
+
return 1;
|
|
1414
|
+
}
|
|
1415
|
+
}
|
|
1416
|
+
}
|
|
1417
|
+
Ok((head, _, _)) => {
|
|
1418
|
+
eprintln!(
|
|
1419
|
+
"Connected sync failed: Home /v1/catalog returned HTTP {}",
|
|
1420
|
+
head.status
|
|
1421
|
+
);
|
|
1422
|
+
return 1;
|
|
1423
|
+
}
|
|
1424
|
+
Err(e) => {
|
|
1425
|
+
eprintln!("Connected sync failed: Home /v1/catalog: {e:?}");
|
|
1426
|
+
return 1;
|
|
1427
|
+
}
|
|
1428
|
+
};
|
|
1429
|
+
|
|
1430
|
+
let now_ms = now_epoch_ms();
|
|
1431
|
+
let now_iso = format_iso8601_utc(now_ms);
|
|
1432
|
+
let settings_doc = match fetch_home_settings_doc(state.tunnel_port, &creds) {
|
|
1433
|
+
Ok(doc) => doc,
|
|
1434
|
+
Err(e) if stale && e.retryable && state.applied_settings.is_some() => {
|
|
1435
|
+
state.applied_settings.as_ref().unwrap().document.clone()
|
|
1436
|
+
}
|
|
1437
|
+
Err(e) => {
|
|
1438
|
+
eprintln!("Connected sync failed without local fallback: {e}");
|
|
1439
|
+
return 1;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
|
|
1443
|
+
let journal = match apply_attach_or_sync(
|
|
1444
|
+
&codex_guard,
|
|
1445
|
+
&state.link_id,
|
|
1446
|
+
&state.api_key_id,
|
|
1447
|
+
state.listen_port,
|
|
1448
|
+
&catalog_bytes,
|
|
1449
|
+
&settings_doc.settings,
|
|
1450
|
+
) {
|
|
1451
|
+
Ok(j) => j,
|
|
1452
|
+
Err(e) => {
|
|
1453
|
+
eprintln!("Connected sync failed without local fallback: {e}");
|
|
1454
|
+
return 1;
|
|
1455
|
+
}
|
|
1456
|
+
};
|
|
1457
|
+
|
|
1458
|
+
let new_digest = codex_settings_digest(&settings_doc.settings);
|
|
1459
|
+
let (applied_at_iso, applied_at_ms) = match &state.applied_settings {
|
|
1460
|
+
Some(prev) if prev.link_id == state.link_id && prev.digest == new_digest => {
|
|
1461
|
+
(prev.applied_at.clone(), prev.applied_at_ms)
|
|
1462
|
+
}
|
|
1463
|
+
_ => (now_iso.clone(), now_ms),
|
|
1464
|
+
};
|
|
1465
|
+
state.catalog_fingerprint = journal.latest_catalog_sha256;
|
|
1466
|
+
state.catalog_synced_at = now_iso.clone();
|
|
1467
|
+
state.applied_settings = Some(AppliedSettingsRecord {
|
|
1468
|
+
link_id: state.link_id.clone(),
|
|
1469
|
+
fetched_at: now_iso,
|
|
1470
|
+
applied_at: applied_at_iso,
|
|
1471
|
+
applied_at_ms,
|
|
1472
|
+
digest: new_digest.clone(),
|
|
1473
|
+
document: settings_doc,
|
|
1474
|
+
});
|
|
1475
|
+
if let Err(e) = write_child_state(&paths.state_file, &state) {
|
|
1476
|
+
eprintln!("Failed writing child state: {e}");
|
|
1477
|
+
return 1;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// OCX-6 freshness: ensure live ocx-child serve started >= applied_at_ms and POST child-parity
|
|
1481
|
+
let live = probe_local_healthz(state.listen_port, Duration::from_millis(500));
|
|
1482
|
+
let needs_rollover = match (&live, state.daemon_pid, state.daemon_started_at_ms) {
|
|
1483
|
+
(Some(h), Some(pid), Some(started_ms))
|
|
1484
|
+
if h.service == "opencodex" && h.ephemeral_child == Some(true) && h.pid == pid =>
|
|
1485
|
+
{
|
|
1486
|
+
started_ms < applied_at_ms
|
|
1487
|
+
}
|
|
1488
|
+
_ => true,
|
|
1489
|
+
};
|
|
1490
|
+
let runtime_started_ms = if needs_rollover {
|
|
1491
|
+
match start_or_rollover_daemon(&paths, &mut state, Some(applied_at_ms))
|
|
1492
|
+
.and_then(|pending| pending.commit())
|
|
1493
|
+
{
|
|
1494
|
+
Ok((_, s_ms)) => s_ms,
|
|
1495
|
+
Err(e) => {
|
|
1496
|
+
eprintln!("The client runtime restart did not complete: {e}");
|
|
1497
|
+
return 1;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
} else {
|
|
1501
|
+
state.daemon_started_at_ms.unwrap_or(now_ms)
|
|
1502
|
+
};
|
|
1503
|
+
|
|
1504
|
+
if !stale {
|
|
1505
|
+
state.parity_sequence += 1;
|
|
1506
|
+
let _ = write_child_state(&paths.state_file, &state);
|
|
1507
|
+
let report = LinkChildParityReport {
|
|
1508
|
+
link_id: state.link_id.clone(),
|
|
1509
|
+
last_apply_at: Some(applied_at_ms),
|
|
1510
|
+
runtime_started_at: runtime_started_ms,
|
|
1511
|
+
applied_codex_settings_digest: Some(new_digest),
|
|
1512
|
+
sequence: state.parity_sequence,
|
|
1513
|
+
};
|
|
1514
|
+
let _ = post_child_parity_report(state.tunnel_port, &creds, &report);
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
let home_state = if stale { "stale" } else { "synced" };
|
|
1518
|
+
let human_msg = if stale {
|
|
1519
|
+
STALE_REMOTE_CATALOG_MESSAGE
|
|
1520
|
+
} else {
|
|
1521
|
+
REMOTE_LINK_SYNC_MESSAGE
|
|
1522
|
+
};
|
|
1523
|
+
if json_mode {
|
|
1524
|
+
eprintln!("{human_msg}");
|
|
1525
|
+
println!(
|
|
1526
|
+
"{{\"schema\":\"ocx.sync.fanout/1\",\"home\":{{\"state\":\"{home_state}\",\"exit\":0}},\"fanout\":{{\"state\":\"not-applicable\",\"reason\":null}},\"children\":[]}}"
|
|
1527
|
+
);
|
|
1528
|
+
} else {
|
|
1529
|
+
println!("{human_msg}");
|
|
1530
|
+
}
|
|
1531
|
+
0
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
fn cmd_detach(args: &[String]) -> u8 {
|
|
1535
|
+
detach_with_exe(args, None)
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
pub fn detach_with_exe(args: &[String], current_exe_override: Option<&Path>) -> u8 {
|
|
1539
|
+
let mut keep_catalog = false;
|
|
1540
|
+
let mut json_mode = false;
|
|
1541
|
+
let mut purge = false;
|
|
1542
|
+
for arg in args {
|
|
1543
|
+
match arg.as_str() {
|
|
1544
|
+
"--keep-catalog" => keep_catalog = true,
|
|
1545
|
+
"--json" => json_mode = true,
|
|
1546
|
+
"--purge" => purge = true,
|
|
1547
|
+
_ => {
|
|
1548
|
+
eprintln!("Usage: ocx-child detach [--keep-catalog] [--purge] [--json]");
|
|
1549
|
+
return 2;
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
let local_paths = current_paths();
|
|
1554
|
+
let lock = match FileLock::acquire_blocking(&local_paths.lock_file) {
|
|
1555
|
+
Ok(l) => l,
|
|
1556
|
+
Err(_) => {
|
|
1557
|
+
eprintln!("detach failed: child lifecycle lock busy");
|
|
1558
|
+
return 1;
|
|
1559
|
+
}
|
|
1560
|
+
};
|
|
1561
|
+
let mut codex_guard =
|
|
1562
|
+
match CodexHomeGuard::acquire(&local_paths, true, false, ClaimPolicy::Detach) {
|
|
1563
|
+
Ok(guard) => guard,
|
|
1564
|
+
Err(CodexHomeError::Missing) => {
|
|
1565
|
+
if let Err(code) = detach_without_codex_home(&local_paths) {
|
|
1566
|
+
return code;
|
|
1567
|
+
}
|
|
1568
|
+
drop(lock);
|
|
1569
|
+
let purged = match purge_after_detach(purge, current_exe_override) {
|
|
1570
|
+
Ok(purged) => purged,
|
|
1571
|
+
Err(code) => return code,
|
|
1572
|
+
};
|
|
1573
|
+
print_detached(
|
|
1574
|
+
json_mode,
|
|
1575
|
+
crate::journal::DetachOutcome::NotAttached,
|
|
1576
|
+
purged,
|
|
1577
|
+
);
|
|
1578
|
+
return 0;
|
|
1579
|
+
}
|
|
1580
|
+
Err(e) => {
|
|
1581
|
+
eprintln!("detach refused: {}", e.message());
|
|
1582
|
+
return 1;
|
|
1583
|
+
}
|
|
1584
|
+
};
|
|
1585
|
+
let paths = codex_guard.paths().clone();
|
|
1586
|
+
if let Err(e) = codex_guard.set_phase(OwnershipPhase::Detaching) {
|
|
1587
|
+
eprintln!("detach failed recording Codex home ownership phase: {e}");
|
|
1588
|
+
return 1;
|
|
1589
|
+
}
|
|
1590
|
+
let _startup_gate = match FileLock::acquire_blocking(&paths.child_dir.join("daemon-start.lock"))
|
|
1591
|
+
{
|
|
1592
|
+
Ok(lock) => lock,
|
|
1593
|
+
Err(_) => {
|
|
1594
|
+
eprintln!("detach failed: daemon startup gate unavailable");
|
|
1595
|
+
return 1;
|
|
1596
|
+
}
|
|
1597
|
+
};
|
|
1598
|
+
if let Err(e) = AttachRollbackSnapshot::recover(&codex_guard) {
|
|
1599
|
+
eprintln!("detach recovery failed: {e}");
|
|
1600
|
+
return 1;
|
|
1601
|
+
}
|
|
1602
|
+
let journal_exists = match validate_existing_journal_paths(&paths) {
|
|
1603
|
+
Ok(exists) => exists,
|
|
1604
|
+
Err(e) => {
|
|
1605
|
+
eprintln!("detach refused: {e}");
|
|
1606
|
+
return 1;
|
|
1607
|
+
}
|
|
1608
|
+
};
|
|
1609
|
+
let state = match read_child_state(&paths.state_file) {
|
|
1610
|
+
StateReadOutcome::Valid(st) if journal_exists => Some(st),
|
|
1611
|
+
StateReadOutcome::Absent => None,
|
|
1612
|
+
_ => {
|
|
1613
|
+
eprintln!("detach refused: child state or recovery journal is invalid");
|
|
1614
|
+
return 1;
|
|
1615
|
+
}
|
|
1616
|
+
};
|
|
1617
|
+
if !journal_exists {
|
|
1618
|
+
for path in [&paths.key_file, &paths.catalog_backup_file] {
|
|
1619
|
+
match fs::symlink_metadata(path) {
|
|
1620
|
+
Ok(_) => {
|
|
1621
|
+
eprintln!("detach refused: orphaned child recovery material exists");
|
|
1622
|
+
return 1;
|
|
1623
|
+
}
|
|
1624
|
+
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
|
1625
|
+
Err(e) => {
|
|
1626
|
+
eprintln!("detach refused: cannot inspect child recovery material: {e}");
|
|
1627
|
+
return 1;
|
|
1628
|
+
}
|
|
1629
|
+
}
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
if let Some(mut st) = state {
|
|
1633
|
+
st.pending_operation = Some("disconnect".to_owned());
|
|
1634
|
+
if let Err(e) = write_child_state(&paths.state_file, &st) {
|
|
1635
|
+
eprintln!("detach refused: failed to record pending operation: {e}");
|
|
1636
|
+
return 1;
|
|
1637
|
+
}
|
|
1638
|
+
if let Err(e) = stop_owned_daemon(&st) {
|
|
1639
|
+
eprintln!("{e}");
|
|
1640
|
+
return 1;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
let outcome = match offline_detach_deferred(&codex_guard, keep_catalog) {
|
|
1644
|
+
Ok(o) => o,
|
|
1645
|
+
Err(DetachError::Conflict(msg)) => {
|
|
1646
|
+
eprintln!("detach conflict: {msg}");
|
|
1647
|
+
return 4;
|
|
1648
|
+
}
|
|
1649
|
+
Err(DetachError::Io(msg)) => {
|
|
1650
|
+
eprintln!("detach failed: {msg}");
|
|
1651
|
+
return 1;
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
for path in [
|
|
1655
|
+
&paths.key_file,
|
|
1656
|
+
&paths.state_file,
|
|
1657
|
+
&paths.catalog_backup_file,
|
|
1658
|
+
&paths.journal_file,
|
|
1659
|
+
] {
|
|
1660
|
+
if let Err(e) = codex_guard.restore_step(|| remove_optional_file(path)) {
|
|
1661
|
+
eprintln!("detach cleanup failed: {}", e.into_message());
|
|
1662
|
+
return 1;
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
// Ownership is released last, after cleanup is durable, so a crash before this point
|
|
1666
|
+
// leaves a record that only this OpenCodex home's detach can resume.
|
|
1667
|
+
if let Err(e) = codex_guard.release() {
|
|
1668
|
+
eprintln!("detach cleanup failed releasing Codex home ownership: {e}");
|
|
1669
|
+
return 1;
|
|
1670
|
+
}
|
|
1671
|
+
drop(codex_guard);
|
|
1672
|
+
// The lifecycle lock lives outside the child directory, so the emptied directory can go.
|
|
1673
|
+
// The start gate is removed only after it is released; a relay still waiting on it finds
|
|
1674
|
+
// no state and exits without serving.
|
|
1675
|
+
drop(_startup_gate);
|
|
1676
|
+
let _ = remove_optional_file(&paths.child_dir.join("daemon-start.lock"));
|
|
1677
|
+
let _ = fs::remove_dir(&paths.child_dir);
|
|
1678
|
+
drop(lock);
|
|
1679
|
+
let purged = match purge_after_detach(purge, current_exe_override) {
|
|
1680
|
+
Ok(purged) => purged,
|
|
1681
|
+
Err(code) => return code,
|
|
1682
|
+
};
|
|
1683
|
+
print_detached(json_mode, outcome, purged);
|
|
1684
|
+
0
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1687
|
+
/// Removes the running binary when `--purge` was requested and it sits in the managed plant
|
|
1688
|
+
/// directory. Runs only after every recovery record is gone and the lifecycle lock is released.
|
|
1689
|
+
fn purge_after_detach(purge: bool, current_exe_override: Option<&Path>) -> Result<bool, u8> {
|
|
1690
|
+
if !purge {
|
|
1691
|
+
return Ok(false);
|
|
1692
|
+
}
|
|
1693
|
+
let exe = match current_exe_override {
|
|
1694
|
+
Some(p) => p.to_path_buf(),
|
|
1695
|
+
None => match std::env::current_exe() {
|
|
1696
|
+
Ok(p) => p,
|
|
1697
|
+
Err(e) => {
|
|
1698
|
+
eprintln!("detach --purge failed resolving current executable: {e}");
|
|
1699
|
+
return Err(1);
|
|
1700
|
+
}
|
|
1701
|
+
},
|
|
1702
|
+
};
|
|
1703
|
+
let user_home = resolve_user_home();
|
|
1704
|
+
let local_appdata = std::env::var_os("LOCALAPPDATA")
|
|
1705
|
+
.filter(|v| !v.is_empty())
|
|
1706
|
+
.map(PathBuf::from);
|
|
1707
|
+
match purge_managed_executable(&exe, &user_home, local_appdata.as_deref()) {
|
|
1708
|
+
Ok(PurgeExecutableOutcome::Removed) => Ok(true),
|
|
1709
|
+
Ok(PurgeExecutableOutcome::SkippedUnmanagedPath) => Ok(false),
|
|
1710
|
+
Err(e) => {
|
|
1711
|
+
eprintln!("detach --purge failed: {e}");
|
|
1712
|
+
Err(1)
|
|
1713
|
+
}
|
|
1714
|
+
}
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
fn print_detached(json_mode: bool, outcome: crate::journal::DetachOutcome, purged: bool) {
|
|
1718
|
+
if json_mode {
|
|
1719
|
+
println!(
|
|
1720
|
+
"{{\"restored\":true,\"outcome\":\"{outcome:?}\",\"daemonRunning\":false,\"purged\":{purged}}}"
|
|
1721
|
+
);
|
|
1722
|
+
} else {
|
|
1723
|
+
println!(
|
|
1724
|
+
"Disconnected ephemeral Remote Link Child ({outcome:?}, purged={purged}); zero background daemon running."
|
|
1725
|
+
);
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
/// Detach when `CODEX_HOME` does not exist: succeed only if nothing needs restoring.
|
|
1730
|
+
fn detach_without_codex_home(paths: &ChildPaths) -> Result<(), u8> {
|
|
1731
|
+
for path in [
|
|
1732
|
+
&paths.rollback_file,
|
|
1733
|
+
&paths.journal_file,
|
|
1734
|
+
&paths.state_file,
|
|
1735
|
+
&paths.key_file,
|
|
1736
|
+
&paths.catalog_backup_file,
|
|
1737
|
+
] {
|
|
1738
|
+
match fs::symlink_metadata(path) {
|
|
1739
|
+
Ok(_) => {
|
|
1740
|
+
eprintln!(
|
|
1741
|
+
"detach refused: Codex home does not exist; child recovery records were kept"
|
|
1742
|
+
);
|
|
1743
|
+
return Err(1);
|
|
1744
|
+
}
|
|
1745
|
+
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
|
1746
|
+
Err(e) => {
|
|
1747
|
+
eprintln!("detach refused: cannot inspect child recovery material: {e}");
|
|
1748
|
+
return Err(1);
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
Ok(())
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
fn cmd_status(args: &[String]) -> u8 {
|
|
1756
|
+
let wants_json = args.iter().any(|a| a == "--json");
|
|
1757
|
+
if args.iter().any(|a| a != "--json") {
|
|
1758
|
+
eprintln!("Usage: ocx status [--json]");
|
|
1759
|
+
return 1;
|
|
1760
|
+
}
|
|
1761
|
+
let paths = current_paths();
|
|
1762
|
+
let state_opt = match read_child_state(&paths.state_file) {
|
|
1763
|
+
StateReadOutcome::Valid(st) => Some(*st),
|
|
1764
|
+
_ => None,
|
|
1765
|
+
};
|
|
1766
|
+
let port = state_opt
|
|
1767
|
+
.as_ref()
|
|
1768
|
+
.map(|s| s.listen_port)
|
|
1769
|
+
.unwrap_or_else(default_listen_port);
|
|
1770
|
+
let live = probe_local_healthz(port, Duration::from_millis(500));
|
|
1771
|
+
let verified_live = live.filter(|h| {
|
|
1772
|
+
h.service == "opencodex"
|
|
1773
|
+
&& h.role.as_deref() == Some("client")
|
|
1774
|
+
&& h.ephemeral_child == Some(true)
|
|
1775
|
+
&& h.port == port
|
|
1776
|
+
&& state_opt
|
|
1777
|
+
.as_ref()
|
|
1778
|
+
.and_then(|s| s.daemon_pid)
|
|
1779
|
+
.is_none_or(|expected| expected == h.pid)
|
|
1780
|
+
});
|
|
1781
|
+
let running = verified_live.is_some();
|
|
1782
|
+
let (digest, last_apply_at) = match state_opt.as_ref().and_then(|s| s.applied_settings.as_ref())
|
|
1783
|
+
{
|
|
1784
|
+
Some(rec) => (Some(rec.digest.clone()), Some(rec.applied_at_ms)),
|
|
1785
|
+
None => (None, None),
|
|
1786
|
+
};
|
|
1787
|
+
let runtime_started_at = if running {
|
|
1788
|
+
state_opt.as_ref().and_then(|s| s.daemon_started_at_ms)
|
|
1789
|
+
} else {
|
|
1790
|
+
None
|
|
1791
|
+
};
|
|
1792
|
+
let payload = serde_json::json!({
|
|
1793
|
+
"schemaVersion": 1,
|
|
1794
|
+
"ephemeralChild": true,
|
|
1795
|
+
"runtimeRole": if state_opt.is_some() { "client" } else { "standalone" },
|
|
1796
|
+
"proxy": {
|
|
1797
|
+
"running": running,
|
|
1798
|
+
"pid": verified_live.as_ref().map(|h| h.pid),
|
|
1799
|
+
"health": {
|
|
1800
|
+
"ok": running,
|
|
1801
|
+
"url": format!("http://127.0.0.1:{port}/healthz"),
|
|
1802
|
+
}
|
|
1803
|
+
},
|
|
1804
|
+
"listen": { "port": port, "hostname": "127.0.0.1" },
|
|
1805
|
+
"connection": match &state_opt {
|
|
1806
|
+
Some(st) => serde_json::json!({
|
|
1807
|
+
"state": "connected",
|
|
1808
|
+
"transport": "link",
|
|
1809
|
+
"serverUrl": format!("http://127.0.0.1:{}", st.tunnel_port),
|
|
1810
|
+
"apiKeyId": st.api_key_id,
|
|
1811
|
+
"link": { "linkId": st.link_id, "tunnelPort": st.tunnel_port },
|
|
1812
|
+
"readiness": "ready",
|
|
1813
|
+
}),
|
|
1814
|
+
None => serde_json::json!({ "state": "disconnected" }),
|
|
1815
|
+
},
|
|
1816
|
+
"appliedCodexSettingsDigest": digest,
|
|
1817
|
+
"lastApplyAt": last_apply_at,
|
|
1818
|
+
"runtimeStartedAt": runtime_started_at,
|
|
1819
|
+
});
|
|
1820
|
+
if wants_json {
|
|
1821
|
+
println!(
|
|
1822
|
+
"{}",
|
|
1823
|
+
serde_json::to_string_pretty(&payload).unwrap_or_default()
|
|
1824
|
+
);
|
|
1825
|
+
} else {
|
|
1826
|
+
println!(
|
|
1827
|
+
"ocx-child: {} (port {port}, proxy {})",
|
|
1828
|
+
if state_opt.is_some() {
|
|
1829
|
+
"attached"
|
|
1830
|
+
} else {
|
|
1831
|
+
"detached"
|
|
1832
|
+
},
|
|
1833
|
+
if running { "running" } else { "stopped" }
|
|
1834
|
+
);
|
|
1835
|
+
}
|
|
1836
|
+
0
|
|
1837
|
+
}
|
|
1838
|
+
|
|
1839
|
+
fn cmd_connect_status(args: &[String]) -> u8 {
|
|
1840
|
+
let wants_json = args.iter().any(|a| a == "--json");
|
|
1841
|
+
let paths = current_paths();
|
|
1842
|
+
let payload = match read_child_state(&paths.state_file) {
|
|
1843
|
+
StateReadOutcome::Valid(st) => serde_json::json!({
|
|
1844
|
+
"state": "connected",
|
|
1845
|
+
"transport": "link",
|
|
1846
|
+
"link": { "linkId": st.link_id, "tunnelPort": st.tunnel_port },
|
|
1847
|
+
"serverUrl": format!("http://127.0.0.1:{}", st.tunnel_port),
|
|
1848
|
+
"apiKeyId": st.api_key_id,
|
|
1849
|
+
"protocolVersion": 1,
|
|
1850
|
+
"catalog": if paths.codex_catalog_path().exists() { "present" } else { "missing" },
|
|
1851
|
+
"token": if paths.key_file.exists() { "owned" } else { "missing" },
|
|
1852
|
+
"readiness": "ready",
|
|
1853
|
+
}),
|
|
1854
|
+
StateReadOutcome::Absent => serde_json::json!({ "state": "disconnected" }),
|
|
1855
|
+
StateReadOutcome::Invalid(reason) => {
|
|
1856
|
+
serde_json::json!({ "state": "invalid", "reason": reason })
|
|
1857
|
+
}
|
|
1858
|
+
};
|
|
1859
|
+
if wants_json {
|
|
1860
|
+
println!(
|
|
1861
|
+
"{}",
|
|
1862
|
+
serde_json::to_string_pretty(&payload).unwrap_or_default()
|
|
1863
|
+
);
|
|
1864
|
+
} else {
|
|
1865
|
+
println!(
|
|
1866
|
+
"Connection: {}",
|
|
1867
|
+
payload["state"].as_str().unwrap_or("unknown")
|
|
1868
|
+
);
|
|
1869
|
+
}
|
|
1870
|
+
0
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
fn cmd_link_status(args: &[String]) -> u8 {
|
|
1874
|
+
let wants_json = args.iter().any(|a| a == "--json");
|
|
1875
|
+
let paths = current_paths();
|
|
1876
|
+
let payload = match read_child_state(&paths.state_file) {
|
|
1877
|
+
StateReadOutcome::Valid(st) => serde_json::json!({
|
|
1878
|
+
"role": "child",
|
|
1879
|
+
"listener": { "state": "off", "port": null },
|
|
1880
|
+
"links": [],
|
|
1881
|
+
"child": null,
|
|
1882
|
+
"linkId": st.link_id,
|
|
1883
|
+
"tunnelPort": st.tunnel_port,
|
|
1884
|
+
}),
|
|
1885
|
+
_ => serde_json::json!({
|
|
1886
|
+
"role": "standalone",
|
|
1887
|
+
"listener": { "state": "off", "port": null },
|
|
1888
|
+
"links": [],
|
|
1889
|
+
"child": null,
|
|
1890
|
+
}),
|
|
1891
|
+
};
|
|
1892
|
+
if wants_json {
|
|
1893
|
+
println!(
|
|
1894
|
+
"{}",
|
|
1895
|
+
serde_json::to_string_pretty(&payload).unwrap_or_default()
|
|
1896
|
+
);
|
|
1897
|
+
} else {
|
|
1898
|
+
println!("Role: {}", payload["role"].as_str().unwrap_or("standalone"));
|
|
1899
|
+
}
|
|
1900
|
+
0
|
|
1901
|
+
}
|