@bitkyc08/opencodex 2.99.0 → 2.100.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/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-CitvEefy.js +59 -0
- package/gui/dist/assets/Tray-CeKVWQyB.js +1 -0
- package/gui/dist/assets/{brand-mark-wzPe3R-J.js → brand-mark-M92UnxX2.js} +1 -1
- package/gui/dist/assets/index-BP47do6-.js +94 -0
- package/gui/dist/assets/index-DmDooSAG.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-fYEMxBaW.js → segment-thumb-features-CcxZBnxv.js} +1 -1
- package/gui/dist/classic/assets/App-aYgIQMxI.js +58 -0
- package/gui/dist/classic/assets/{Tray-BqZueZOx.js → Tray-D8jfUXpQ.js} +1 -1
- package/gui/dist/classic/assets/index-CfGqHooN.js +94 -0
- package/gui/dist/classic/assets/quota-summary-R-ih7OlS.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.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/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-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 +405 -153
- 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 +49 -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/claude-keychain-read.ts +165 -0
- 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-usage-state.ts +93 -0
- 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/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.ts +25 -18
- package/src/providers/registry/entries-core.ts +7 -4
- package/src/providers/registry/entries-extended.ts +39 -7
- package/src/providers/registry/model-seeds.ts +10 -2
- 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/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/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 +244 -38
- package/gui/dist/assets/App-BepstgEN.js +0 -59
- package/gui/dist/assets/Tray-BinxbEZo.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,276 @@
|
|
|
1
|
+
import { readConfigDiagnostics } from "../../config/diagnostics";
|
|
2
|
+
import { getConfigDir } from "../../config/paths";
|
|
3
|
+
import { registerOptionalShutdownHook } from "../../lib/optional-shutdown-hooks";
|
|
4
|
+
import type { OcxConfig } from "../../types";
|
|
5
|
+
import { aggregateTelemetryForDay, type DailyTelemetryAggregate } from "../aggregate";
|
|
6
|
+
import { isTelemetryEnvOptOut, resolveTelemetryStatus, type TelemetryConsentStatus } from "../consent";
|
|
7
|
+
import type { TelemetryModelFamily } from "../contract";
|
|
8
|
+
import { resolveNextEligibleTelemetryDay } from "../scheduler";
|
|
9
|
+
import { readTelemetryStateFile, withPendingTelemetryDecision, type TelemetryState } from "../state";
|
|
10
|
+
import { deleteProfile, submitProfileDay, type ProfileClientOptions } from "./client";
|
|
11
|
+
import { PROFILE_SCHEMA_VERSION, type ProfileDayV1, type ProfileFamilyRowV1 } from "./contract";
|
|
12
|
+
import {
|
|
13
|
+
deleteTelemetryProfileFile,
|
|
14
|
+
readTelemetryProfileFile,
|
|
15
|
+
updateTelemetryProfileState,
|
|
16
|
+
type TelemetryProfileState,
|
|
17
|
+
} from "./state";
|
|
18
|
+
|
|
19
|
+
export const PROFILE_TICK_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
20
|
+
export const PROFILE_INTERVAL_JITTER_MS = 30 * 60 * 1000;
|
|
21
|
+
export const PROFILE_STARTUP_BASE_DELAY_MS = 2 * 60 * 1000;
|
|
22
|
+
export const PROFILE_STARTUP_JITTER_MS = 8 * 60 * 1000;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The day totals a profile submits, built from the same local daily aggregate as anonymous
|
|
26
|
+
* telemetry: only the request count, the five token buckets and per-family totals. Provider
|
|
27
|
+
* kinds, outcomes, errors and active minutes are dropped. Null when the day had no requests.
|
|
28
|
+
*/
|
|
29
|
+
export function buildProfileDay(aggregate: DailyTelemetryAggregate): ProfileDayV1 | null {
|
|
30
|
+
const byFamily = new Map<TelemetryModelFamily, ProfileFamilyRowV1>();
|
|
31
|
+
const tokens = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, reasoning: 0 };
|
|
32
|
+
let requests = 0;
|
|
33
|
+
for (const row of aggregate.models) {
|
|
34
|
+
if (row.requests <= 0) continue;
|
|
35
|
+
const rowTokens = row.inputTokens + row.cacheReadTokens + row.cacheWriteTokens + row.outputTokens + row.reasoningTokens;
|
|
36
|
+
requests += row.requests;
|
|
37
|
+
tokens.input += row.inputTokens;
|
|
38
|
+
tokens.cacheRead += row.cacheReadTokens;
|
|
39
|
+
tokens.cacheWrite += row.cacheWriteTokens;
|
|
40
|
+
tokens.output += row.outputTokens;
|
|
41
|
+
tokens.reasoning += row.reasoningTokens;
|
|
42
|
+
const existing = byFamily.get(row.modelFamily);
|
|
43
|
+
if (existing) {
|
|
44
|
+
existing.requests += row.requests;
|
|
45
|
+
existing.tokens += rowTokens;
|
|
46
|
+
} else {
|
|
47
|
+
byFamily.set(row.modelFamily, { family: row.modelFamily, requests: row.requests, tokens: rowTokens });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (requests === 0) return null;
|
|
51
|
+
const families = [...byFamily.values()].sort((a, b) => b.tokens - a.tokens || a.family.localeCompare(b.family));
|
|
52
|
+
return { schemaVersion: PROFILE_SCHEMA_VERSION, day: aggregate.day, requests, tokens, families };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export interface ProfileGate {
|
|
56
|
+
status: TelemetryConsentStatus;
|
|
57
|
+
telemetryState: TelemetryState | null;
|
|
58
|
+
telemetryStateUnreadable: boolean;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Anonymous telemetry's effective state, read from disk like the anonymous scheduler does. */
|
|
62
|
+
export function readProfileTelemetryGate(options: {
|
|
63
|
+
configDir?: string;
|
|
64
|
+
env?: Record<string, string | undefined>;
|
|
65
|
+
readConfig?: () => Pick<OcxConfig, "telemetry"> | undefined;
|
|
66
|
+
} = {}): ProfileGate {
|
|
67
|
+
const configDir = options.configDir ?? getConfigDir();
|
|
68
|
+
const env = options.env ?? process.env;
|
|
69
|
+
const config = options.readConfig ? options.readConfig() : readConfigDiagnostics({ passive: true }).config;
|
|
70
|
+
const status = resolveTelemetryStatus(withPendingTelemetryDecision(config, configDir), env);
|
|
71
|
+
const file = readTelemetryStateFile(configDir);
|
|
72
|
+
return { status, telemetryState: file.unreadable ? null : file.state, telemetryStateUnreadable: file.unreadable };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* The next day a connected profile would send: every anonymous eligibility rule (consent day,
|
|
77
|
+
* env opt-out periods, the 7-day window) plus strictly after the connect day and not yet sent
|
|
78
|
+
* for this profile.
|
|
79
|
+
*/
|
|
80
|
+
export function resolveNextProfileDay(
|
|
81
|
+
profile: TelemetryProfileState,
|
|
82
|
+
gate: ProfileGate,
|
|
83
|
+
now = Date.now(),
|
|
84
|
+
): { day: string | null; reason: string } {
|
|
85
|
+
if (!gate.status.effective) return { day: null, reason: "telemetry-off" };
|
|
86
|
+
if (gate.telemetryStateUnreadable || !gate.telemetryState) return { day: null, reason: "state-unreadable" };
|
|
87
|
+
const anonymousFloor = gate.telemetryState.ineligibleThroughDay;
|
|
88
|
+
const ineligibleThroughDay = anonymousFloor && anonymousFloor > profile.connectedDay ? anonymousFloor : profile.connectedDay;
|
|
89
|
+
return resolveNextEligibleTelemetryDay(
|
|
90
|
+
gate.status,
|
|
91
|
+
{ ...gate.telemetryState, sentDays: profile.sentDays, ineligibleThroughDay },
|
|
92
|
+
now,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface ProfileTickOptions extends ProfileClientOptions {
|
|
97
|
+
now?: number;
|
|
98
|
+
configDir?: string;
|
|
99
|
+
env?: Record<string, string | undefined>;
|
|
100
|
+
readConfig?: () => Pick<OcxConfig, "telemetry"> | undefined;
|
|
101
|
+
aggregateDay?: (day: string, options: { signal?: AbortSignal }) => Promise<DailyTelemetryAggregate>;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export interface ProfileTickResult {
|
|
105
|
+
sent: boolean;
|
|
106
|
+
deleted?: boolean;
|
|
107
|
+
day?: string;
|
|
108
|
+
reason: string;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Retry a pending deletion. Not gated on anonymous telemetry: deleting is the person's own request. */
|
|
112
|
+
async function retryPendingDelete(
|
|
113
|
+
state: TelemetryProfileState,
|
|
114
|
+
configDir: string,
|
|
115
|
+
now: number,
|
|
116
|
+
options: ProfileClientOptions,
|
|
117
|
+
): Promise<ProfileTickResult> {
|
|
118
|
+
const result = await deleteProfile(state.secret, options);
|
|
119
|
+
if (result.deleted) {
|
|
120
|
+
// Only the file of the profile just deleted: a reconnect in the meantime has its own secret.
|
|
121
|
+
const current = readTelemetryProfileFile(configDir).state;
|
|
122
|
+
if (current && current.secret !== state.secret) return { sent: false, deleted: true, reason: "deleted" };
|
|
123
|
+
if (!deleteTelemetryProfileFile(configDir)) return { sent: false, deleted: false, reason: "local-file-remains" };
|
|
124
|
+
return { sent: false, deleted: true, reason: "deleted" };
|
|
125
|
+
}
|
|
126
|
+
if (result.retryAfterMs) {
|
|
127
|
+
const retryAfterUntil = new Date(now + result.retryAfterMs).toISOString();
|
|
128
|
+
updateTelemetryProfileState(state.secret, current => ({ ...current, retryAfterUntil }), { configDir, now, whilePendingDelete: true });
|
|
129
|
+
}
|
|
130
|
+
return { sent: false, deleted: false, reason: "deletion-pending" };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function runProfileTick(options: ProfileTickOptions = {}): Promise<ProfileTickResult> {
|
|
134
|
+
const now = options.now ?? Date.now();
|
|
135
|
+
const configDir = options.configDir ?? getConfigDir();
|
|
136
|
+
const env = options.env ?? process.env;
|
|
137
|
+
const file = readTelemetryProfileFile(configDir);
|
|
138
|
+
if (file.unreadable) return { sent: false, reason: "state-unreadable" };
|
|
139
|
+
const profile = file.state;
|
|
140
|
+
if (!profile) return { sent: false, reason: "not-connected" };
|
|
141
|
+
const retryUntil = profile.retryAfterUntil ? Date.parse(profile.retryAfterUntil) : Number.NaN;
|
|
142
|
+
const backingOff = !Number.isNaN(retryUntil) && now < retryUntil;
|
|
143
|
+
if (profile.pendingDelete) {
|
|
144
|
+
if (backingOff) return { sent: false, reason: "retry-after-backoff" };
|
|
145
|
+
return retryPendingDelete(profile, configDir, now, options);
|
|
146
|
+
}
|
|
147
|
+
if (profile.revoked) return { sent: false, reason: "revoked" };
|
|
148
|
+
if (isTelemetryEnvOptOut(env) !== null) return { sent: false, reason: "telemetry-off" };
|
|
149
|
+
const gate = readProfileTelemetryGate({ configDir, env, readConfig: options.readConfig });
|
|
150
|
+
if (backingOff) return { sent: false, reason: "retry-after-backoff" };
|
|
151
|
+
const { day, reason } = resolveNextProfileDay(profile, gate, now);
|
|
152
|
+
if (!day) return { sent: false, reason };
|
|
153
|
+
|
|
154
|
+
const aggregate = await (options.aggregateDay
|
|
155
|
+
? options.aggregateDay(day, { signal: options.signal })
|
|
156
|
+
: aggregateTelemetryForDay(day, { signal: options.signal }));
|
|
157
|
+
if (options.signal?.aborted) return { sent: false, day, reason: "aborted" };
|
|
158
|
+
|
|
159
|
+
// Consent and the profile may have changed while the day was aggregated.
|
|
160
|
+
const latestFile = readTelemetryProfileFile(configDir);
|
|
161
|
+
const latest = latestFile.state;
|
|
162
|
+
if (latestFile.unreadable || !latest || latest.pendingDelete || latest.revoked || latest.secret !== profile.secret) {
|
|
163
|
+
return { sent: false, day, reason: "profile-changed" };
|
|
164
|
+
}
|
|
165
|
+
if (isTelemetryEnvOptOut(env) !== null) return { sent: false, day, reason: "telemetry-off" };
|
|
166
|
+
const latestGate = readProfileTelemetryGate({ configDir, env, readConfig: options.readConfig });
|
|
167
|
+
if (resolveNextProfileDay(latest, latestGate, now).day !== day) return { sent: false, day, reason: "eligibility-changed" };
|
|
168
|
+
|
|
169
|
+
const nowIso = new Date(now).toISOString();
|
|
170
|
+
const body = buildProfileDay(aggregate);
|
|
171
|
+
if (!body) {
|
|
172
|
+
updateTelemetryProfileState(latest.secret, current => ({ ...current, sentDays: { ...current.sentDays, [day]: nowIso } }), { configDir, now });
|
|
173
|
+
return { sent: false, day, reason: "no-usage" };
|
|
174
|
+
}
|
|
175
|
+
const result = await submitProfileDay(latest.secret, body, options);
|
|
176
|
+
if (!result.ok) {
|
|
177
|
+
if (result.status === 401) {
|
|
178
|
+
updateTelemetryProfileState(latest.secret, current => ({ ...current, revoked: true }), { configDir, now });
|
|
179
|
+
return { sent: false, day, reason: "revoked" };
|
|
180
|
+
}
|
|
181
|
+
if (result.retryAfterMs) {
|
|
182
|
+
const retryAfterUntil = new Date(now + result.retryAfterMs).toISOString();
|
|
183
|
+
updateTelemetryProfileState(latest.secret, current => ({ ...current, retryAfterUntil }), { configDir, now });
|
|
184
|
+
return { sent: false, day, reason: "retry-after-backoff" };
|
|
185
|
+
}
|
|
186
|
+
if (typeof result.status === "number" && result.status >= 400 && result.status < 500) {
|
|
187
|
+
// A permanent refusal for this day (validation, too old, before the creation day): set the
|
|
188
|
+
// day aside so the oldest-first order never stalls on it.
|
|
189
|
+
updateTelemetryProfileState(latest.secret, current => ({ ...current, sentDays: { ...current.sentDays, [day]: `refused ${nowIso}` } }), { configDir, now });
|
|
190
|
+
return { sent: false, day, reason: "refused" };
|
|
191
|
+
}
|
|
192
|
+
return { sent: false, day, reason: "send-failed" };
|
|
193
|
+
}
|
|
194
|
+
updateTelemetryProfileState(latest.secret, current => ({
|
|
195
|
+
...current,
|
|
196
|
+
sentDays: { ...current.sentDays, [day]: nowIso },
|
|
197
|
+
lastSentDay: day,
|
|
198
|
+
lastSentAt: nowIso,
|
|
199
|
+
retryAfterUntil: null,
|
|
200
|
+
}), { configDir, now });
|
|
201
|
+
return { sent: true, day, reason: "sent" };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
let running = false;
|
|
205
|
+
let startupTimer: ReturnType<typeof setTimeout> | null = null;
|
|
206
|
+
let intervalTimer: ReturnType<typeof setInterval> | null = null;
|
|
207
|
+
let nudgeTimer: ReturnType<typeof setTimeout> | null = null;
|
|
208
|
+
let activeTick: Promise<ProfileTickResult> | null = null;
|
|
209
|
+
let activeController: AbortController | null = null;
|
|
210
|
+
let detachShutdownHook: (() => void) | null = null;
|
|
211
|
+
|
|
212
|
+
function triggerTick(): void {
|
|
213
|
+
if (!running || activeTick) return;
|
|
214
|
+
const controller = new AbortController();
|
|
215
|
+
activeController = controller;
|
|
216
|
+
activeTick = runProfileTick({ signal: controller.signal })
|
|
217
|
+
.catch((): ProfileTickResult => ({ sent: false, reason: "tick-error" }))
|
|
218
|
+
.finally(() => {
|
|
219
|
+
activeTick = null;
|
|
220
|
+
if (activeController === controller) activeController = null;
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Start the profile loop. Started by the server only when a profile file exists, and by a connect;
|
|
226
|
+
* independent of the anonymous scheduler so a pending deletion is retried even while anonymous
|
|
227
|
+
* telemetry is off.
|
|
228
|
+
*/
|
|
229
|
+
export function startProfileScheduler(options: { startupDelayMs?: number; intervalMs?: number; random?: () => number } = {}): () => void {
|
|
230
|
+
if (running) return stopProfileScheduler;
|
|
231
|
+
running = true;
|
|
232
|
+
const random = options.random ?? Math.random;
|
|
233
|
+
detachShutdownHook = registerOptionalShutdownHook("telemetry-profile", stopProfileScheduler);
|
|
234
|
+
startupTimer = setTimeout(() => {
|
|
235
|
+
startupTimer = null;
|
|
236
|
+
triggerTick();
|
|
237
|
+
}, options.startupDelayMs ?? PROFILE_STARTUP_BASE_DELAY_MS + Math.floor(random() * PROFILE_STARTUP_JITTER_MS));
|
|
238
|
+
startupTimer.unref?.();
|
|
239
|
+
intervalTimer = setInterval(triggerTick, options.intervalMs ?? PROFILE_TICK_INTERVAL_MS + Math.floor(random() * PROFILE_INTERVAL_JITTER_MS));
|
|
240
|
+
intervalTimer.unref?.();
|
|
241
|
+
return stopProfileScheduler;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function stopProfileScheduler(): void {
|
|
245
|
+
running = false;
|
|
246
|
+
activeController?.abort(new Error("Profile scheduler stopped"));
|
|
247
|
+
for (const timer of [startupTimer, nudgeTimer]) if (timer) clearTimeout(timer);
|
|
248
|
+
if (intervalTimer) clearInterval(intervalTimer);
|
|
249
|
+
startupTimer = null;
|
|
250
|
+
nudgeTimer = null;
|
|
251
|
+
intervalTimer = null;
|
|
252
|
+
const detach = detachShutdownHook;
|
|
253
|
+
detachShutdownHook = null;
|
|
254
|
+
detach?.();
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export function isProfileSchedulerRunning(): boolean {
|
|
258
|
+
return running;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Run a tick soon (after a connect or a pending disconnect), starting the loop only for a profile file that exists. */
|
|
262
|
+
export function nudgeProfileScheduler(): void {
|
|
263
|
+
if (!running) {
|
|
264
|
+
const file = readTelemetryProfileFile();
|
|
265
|
+
if (!file.state && !file.unreadable) return;
|
|
266
|
+
startProfileScheduler();
|
|
267
|
+
}
|
|
268
|
+
if (nudgeTimer) clearTimeout(nudgeTimer);
|
|
269
|
+
nudgeTimer = setTimeout(() => {
|
|
270
|
+
nudgeTimer = null;
|
|
271
|
+
triggerTick();
|
|
272
|
+
}, 10);
|
|
273
|
+
nudgeTimer.unref?.();
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { mutatePersistedConfig } from "../config";
|
|
2
|
+
import { readConfigDiagnostics } from "../config/diagnostics";
|
|
3
|
+
import { adoptPersistedTelemetry } from "../config/live-reconcile";
|
|
4
|
+
import { getConfigDir, withConfigDirHardeningSettled } from "../config/paths";
|
|
5
|
+
import { jsonResponse } from "../server/auth-cors";
|
|
6
|
+
import { hasHumanDashboardSession } from "../server/management/consent-session";
|
|
7
|
+
import type { ManagementContext } from "../server/management/context";
|
|
8
|
+
import type { OcxConfig, OcxTelemetryConfig, OcxTelemetryDecision } from "../types";
|
|
9
|
+
import { aggregateTelemetryForDay, type DailyTelemetryAggregate } from "./aggregate";
|
|
10
|
+
import { resolveTelemetryStatus, type TelemetryConsentStatus } from "./consent";
|
|
11
|
+
import type { TelemetryInstallChannel, TelemetryPayloadV1 } from "./contract";
|
|
12
|
+
import {
|
|
13
|
+
TELEMETRY_PREVIEW_HASH_PLACEHOLDER,
|
|
14
|
+
computeInstallDayHash,
|
|
15
|
+
deleteTelemetryInstallId,
|
|
16
|
+
readTelemetryInstallId,
|
|
17
|
+
} from "./install-id";
|
|
18
|
+
import { buildTelemetryPayloadV1, resolveInstallChannel } from "./payload";
|
|
19
|
+
import {
|
|
20
|
+
clearPendingTelemetryDecision,
|
|
21
|
+
latestCompletedUtcDay,
|
|
22
|
+
nudgeTelemetryScheduler,
|
|
23
|
+
readTelemetryState,
|
|
24
|
+
readTelemetryStateFile,
|
|
25
|
+
recordPendingTelemetryDecision,
|
|
26
|
+
resolveNextEligibleTelemetryDay,
|
|
27
|
+
withPendingTelemetryDecision,
|
|
28
|
+
} from "./scheduler";
|
|
29
|
+
|
|
30
|
+
export interface TelemetryStatusSnapshot extends TelemetryConsentStatus {
|
|
31
|
+
installChannel: TelemetryInstallChannel;
|
|
32
|
+
lastSentDay: string | null;
|
|
33
|
+
lastSentAt: string | null;
|
|
34
|
+
previewEligible: boolean;
|
|
35
|
+
preview: TelemetryPayloadV1;
|
|
36
|
+
/** Present when telemetry-state.json exists but cannot be read: every send is refused until it can. */
|
|
37
|
+
stateUnreadable?: true;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** How long the dashboard's preview may reuse a completed day's aggregate (the panel polls). */
|
|
41
|
+
export const TELEMETRY_PREVIEW_CACHE_MS = 10 * 60 * 1000;
|
|
42
|
+
let previewAggregateCache: { configDir: string; day: string; at: number; aggregate: DailyTelemetryAggregate } | null = null;
|
|
43
|
+
|
|
44
|
+
export function resetTelemetryPreviewCacheForTests(): void {
|
|
45
|
+
previewAggregateCache = null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function previewAggregate(day: string, configDir: string, now: number, cache: boolean): Promise<DailyTelemetryAggregate> {
|
|
49
|
+
const hit = previewAggregateCache;
|
|
50
|
+
if (cache && hit && hit.configDir === configDir && hit.day === day && now - hit.at >= 0 && now - hit.at < TELEMETRY_PREVIEW_CACHE_MS) {
|
|
51
|
+
return hit.aggregate;
|
|
52
|
+
}
|
|
53
|
+
// A completed day's aggregate scans usage.jsonl from the start; the dashboard polls this route.
|
|
54
|
+
const aggregate = await aggregateTelemetryForDay(day);
|
|
55
|
+
if (cache) previewAggregateCache = { configDir, day, at: now, aggregate };
|
|
56
|
+
return aggregate;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function buildTelemetryStatusSnapshot(
|
|
60
|
+
config: Pick<OcxConfig, "telemetry"> | null | undefined,
|
|
61
|
+
options: { now?: number; env?: Record<string, string | undefined>; configDir?: string; cachePreview?: boolean } = {},
|
|
62
|
+
): Promise<TelemetryStatusSnapshot> {
|
|
63
|
+
const now = options.now ?? Date.now();
|
|
64
|
+
const env = options.env ?? process.env;
|
|
65
|
+
const configDir = options.configDir ?? getConfigDir();
|
|
66
|
+
const status = resolveTelemetryStatus(withPendingTelemetryDecision(config, configDir), env);
|
|
67
|
+
const installChannel = resolveInstallChannel({ env });
|
|
68
|
+
const stateFile = readTelemetryStateFile(configDir);
|
|
69
|
+
const state = stateFile.state;
|
|
70
|
+
// An unreadable state file blocks every send (state-unreadable), so nothing is eligible to preview.
|
|
71
|
+
const { day: nextEligibleDay } = stateFile.unreadable
|
|
72
|
+
? { day: null }
|
|
73
|
+
: resolveNextEligibleTelemetryDay(status, state, now);
|
|
74
|
+
const previewEligible = nextEligibleDay !== null;
|
|
75
|
+
const day = nextEligibleDay ?? latestCompletedUtcDay(now);
|
|
76
|
+
const aggregate = await previewAggregate(day, configDir, now, options.cachePreview === true);
|
|
77
|
+
const identity = readTelemetryInstallId(configDir);
|
|
78
|
+
const installDayHash = identity
|
|
79
|
+
? computeInstallDayHash(identity.installId, day)
|
|
80
|
+
: TELEMETRY_PREVIEW_HASH_PLACEHOLDER;
|
|
81
|
+
const newInstall = state.everReported !== true && identity?.firstReportSent !== true;
|
|
82
|
+
const preview = buildTelemetryPayloadV1({
|
|
83
|
+
aggregate,
|
|
84
|
+
installDayHash,
|
|
85
|
+
newInstall,
|
|
86
|
+
installChannel,
|
|
87
|
+
now,
|
|
88
|
+
});
|
|
89
|
+
return {
|
|
90
|
+
...status,
|
|
91
|
+
installChannel,
|
|
92
|
+
lastSentDay: state.lastSentDay,
|
|
93
|
+
lastSentAt: state.lastSentAt,
|
|
94
|
+
previewEligible,
|
|
95
|
+
preview,
|
|
96
|
+
...(stateFile.unreadable ? { stateUnreadable: true as const } : {}),
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function consentRefusedResponse(ctx: ManagementContext): Response {
|
|
101
|
+
return jsonResponse(
|
|
102
|
+
{
|
|
103
|
+
ok: false,
|
|
104
|
+
code: "agent_consent_required",
|
|
105
|
+
error: "Telemetry consent requires a human dashboard session.",
|
|
106
|
+
message:
|
|
107
|
+
"Refused: this request carries no human dashboard session. Telemetry consent must be chosen by the user in the dashboard or an interactive terminal.",
|
|
108
|
+
},
|
|
109
|
+
403,
|
|
110
|
+
ctx.req,
|
|
111
|
+
ctx.config,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export async function handleGetTelemetryRoute(ctx: ManagementContext): Promise<Response> {
|
|
116
|
+
// Consent is read from disk, like the scheduler: a CLI decision while the proxy runs must show here.
|
|
117
|
+
const snapshot = await buildTelemetryStatusSnapshot(readConfigDiagnostics({ passive: true }).config, { cachePreview: true });
|
|
118
|
+
return jsonResponse(snapshot, 200, ctx.req, ctx.config);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function handlePutTelemetryRoute(ctx: ManagementContext): Promise<Response> {
|
|
122
|
+
if (!hasHumanDashboardSession(ctx)) {
|
|
123
|
+
return consentRefusedResponse(ctx);
|
|
124
|
+
}
|
|
125
|
+
let body: unknown;
|
|
126
|
+
try {
|
|
127
|
+
body = await ctx.req.json();
|
|
128
|
+
} catch {
|
|
129
|
+
return jsonResponse({ error: "invalid JSON body", code: "invalid_json" }, 400, ctx.req, ctx.config);
|
|
130
|
+
}
|
|
131
|
+
const rawDecision = body && typeof body === "object" && !Array.isArray(body)
|
|
132
|
+
? (body as { decision?: unknown }).decision
|
|
133
|
+
: undefined;
|
|
134
|
+
if (rawDecision !== "accepted" && rawDecision !== "declined") {
|
|
135
|
+
return jsonResponse(
|
|
136
|
+
{ error: "decision must be \"accepted\" or \"declined\"", code: "invalid_decision" },
|
|
137
|
+
400,
|
|
138
|
+
ctx.req,
|
|
139
|
+
ctx.config,
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
const decision: OcxTelemetryDecision = rawDecision;
|
|
143
|
+
const nowIso = new Date().toISOString();
|
|
144
|
+
let committed: OcxTelemetryConfig | undefined;
|
|
145
|
+
const outcome = await withConfigDirHardeningSettled(getConfigDir(), () =>
|
|
146
|
+
mutatePersistedConfig(fresh => {
|
|
147
|
+
const prev = fresh.telemetry;
|
|
148
|
+
const next: OcxTelemetryConfig = {
|
|
149
|
+
decision,
|
|
150
|
+
decidedAt: nowIso,
|
|
151
|
+
noticeShownAt: prev?.noticeShownAt ?? nowIso,
|
|
152
|
+
};
|
|
153
|
+
const changed = JSON.stringify(prev) !== JSON.stringify(next);
|
|
154
|
+
fresh.telemetry = next;
|
|
155
|
+
committed = structuredClone(next);
|
|
156
|
+
return { changed, value: next };
|
|
157
|
+
}),
|
|
158
|
+
);
|
|
159
|
+
if (outcome.status === "unavailable" && outcome.reason === "missing") {
|
|
160
|
+
// A fresh install's first-run popup can answer before any config.json exists; hold the
|
|
161
|
+
// decision so creating a config here does not make `ocx init` skip setup.
|
|
162
|
+
committed = { decision, decidedAt: nowIso, noticeShownAt: nowIso };
|
|
163
|
+
recordPendingTelemetryDecision(committed);
|
|
164
|
+
} else if (outcome.status === "unavailable") {
|
|
165
|
+
return jsonResponse(
|
|
166
|
+
{ error: `Configuration is ${outcome.reason}`, code: "config_unavailable" },
|
|
167
|
+
503,
|
|
168
|
+
ctx.req,
|
|
169
|
+
ctx.config,
|
|
170
|
+
);
|
|
171
|
+
} else {
|
|
172
|
+
clearPendingTelemetryDecision();
|
|
173
|
+
}
|
|
174
|
+
// A decision held before config.json exists stays out of the running config: a later write that
|
|
175
|
+
// creates config.json from it must not carry a decision another process may since have replaced.
|
|
176
|
+
adoptPersistedTelemetry(ctx.config, outcome.status === "unavailable" ? undefined : committed);
|
|
177
|
+
if (decision === "declined") {
|
|
178
|
+
deleteTelemetryInstallId();
|
|
179
|
+
}
|
|
180
|
+
nudgeTelemetryScheduler();
|
|
181
|
+
const snapshot = await buildTelemetryStatusSnapshot(ctx.config);
|
|
182
|
+
return jsonResponse({ ok: true, ...snapshot }, 200, ctx.req, ctx.config);
|
|
183
|
+
}
|