@bitkyc08/opencodex 2.100.1 → 2.100.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/gui/dist/assets/App-BpJOzw4F.js +59 -0
- package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
- package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-DU-0Vdkr.js} +1 -1
- package/gui/dist/assets/index-Bbor_y80.js +94 -0
- package/gui/dist/assets/index-DJEkIDAi.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-e9A_FogJ.js} +1 -1
- package/gui/dist/classic/assets/{App-CgPBKUP-.js → App-BrIlUiLc.js} +18 -18
- package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-DT146AhS.js} +1 -1
- package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/package.json +2 -2
- package/src/adapters/client-fingerprint.ts +5 -3
- package/src/adapters/cursor/native-exec.ts +3 -2
- package/src/adapters/cursor/tool-guidance.ts +3 -3
- package/src/adapters/cursor/tool-wording.ts +10 -1
- package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
- package/src/adapters/google-antigravity-wire.ts +13 -6
- package/src/adapters/google-truncation.ts +4 -2
- package/src/adapters/google.ts +8 -2
- package/src/adapters/openai-chat/tool-schema.ts +9 -0
- package/src/adapters/openai-responses/tool-schema.ts +18 -4
- package/src/adapters/run-turn-queue.ts +139 -5
- package/src/adapters/upstream-http-error.ts +4 -2
- package/src/bridge/sse.ts +8 -1
- package/src/claude/chat-tool-dispatch.ts +233 -0
- package/src/claude/inbound-tool-loading.ts +42 -17
- package/src/cli/account-api.ts +6 -0
- package/src/cli/account-extended.ts +60 -6
- package/src/cli/account-key-quota.ts +22 -2
- package/src/cli/account.ts +1 -1
- package/src/cli/capabilities-access-remote.ts +10 -0
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-base.ts +2 -2
- package/src/cli/claude.ts +19 -14
- package/src/cli/config-command.ts +24 -1
- package/src/cli/connect.ts +36 -3
- package/src/cli/gui-pair-client.ts +23 -2
- package/src/cli/help.ts +1 -1
- package/src/cli/hub.ts +18 -1
- package/src/cli/link-child-ops.ts +136 -0
- package/src/cli/link-status-child.ts +94 -0
- package/src/cli/link.ts +22 -9
- package/src/cli/registry.ts +3 -2
- package/src/cli/sync-command.ts +3 -1
- package/src/cli/sync-fanout.ts +8 -81
- package/src/client/link-readiness.ts +16 -6
- package/src/client/link-tunnel-status.ts +76 -0
- package/src/clients/config-export.ts +14 -1
- package/src/codex/account-resume-health.ts +41 -0
- package/src/codex/auth-api/login-flow.ts +6 -0
- package/src/codex/auth-api/routes.ts +35 -2
- package/src/codex/catalog/gather-capture.ts +2 -0
- package/src/codex/catalog/provider-models.ts +13 -8
- package/src/codex/convergence-types.ts +2 -0
- package/src/codex/quota.ts +111 -6
- package/src/combos/cooldown-store.ts +208 -0
- package/src/combos/failover.ts +432 -35
- package/src/config/salvage.ts +1 -0
- package/src/config/schema/config-schema.ts +6 -3
- package/src/config/schema/leaf-validators.ts +34 -12
- package/src/generated/compatibility-version.json +213 -121
- package/src/lib/catalog-etag.ts +10 -0
- package/src/lib/client-error-body.ts +15 -0
- package/src/lib/context-overflow-verdict.ts +266 -9
- package/src/lib/failure-detail.ts +72 -3
- package/src/lib/hard-refusal.ts +259 -0
- package/src/link/child-activity.ts +57 -0
- package/src/link/child-catalog-freshness.ts +149 -0
- package/src/link/child-gated-ocx.ts +117 -0
- package/src/link/child-observations.ts +205 -0
- package/src/link/child-observe.ts +121 -0
- package/src/link/child-ops-engine.ts +162 -0
- package/src/link/child-update-contract.ts +165 -0
- package/src/link/paths.ts +5 -0
- package/src/link/remote-windows.ts +42 -6
- package/src/link/ssh-argv.ts +126 -32
- package/src/link/status-projection.ts +73 -0
- package/src/link/sync-fanout-classify.ts +98 -0
- package/src/link/tunnel-state.ts +10 -4
- package/src/messaging/mcp-queue-rpc.ts +2 -1
- package/src/messaging/mcp-queue-server.ts +5 -0
- package/src/messaging/mcp-reply-tools.ts +24 -9
- package/src/messaging/mcp-reply-wait.ts +70 -0
- package/src/oauth/account-resume-health.ts +60 -0
- package/src/oauth/index.ts +1 -0
- package/src/oauth/store.ts +44 -1
- package/src/providers/api-key-pause-state.ts +23 -0
- package/src/providers/api-key-pause.ts +68 -10
- package/src/providers/api-key-selection-capture.ts +3 -1
- package/src/providers/api-key-selection.ts +3 -2
- package/src/providers/api-keys.ts +18 -5
- package/src/providers/claude-cli-usage-state.ts +11 -6
- package/src/providers/claude-cli-usage.ts +27 -9
- package/src/providers/codex-capacity.ts +11 -2
- package/src/providers/key-failover.ts +13 -6
- package/src/providers/model-discovery-config.ts +31 -0
- package/src/providers/model-discovery-diagnostic.ts +34 -3
- package/src/providers/model-discovery.ts +43 -7
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/openai-sidecar.ts +15 -2
- package/src/providers/provider-id-rewrite.ts +3 -0
- package/src/providers/quota/account-cache.ts +52 -34
- package/src/providers/quota/anthropic-usage-windows.ts +19 -9
- package/src/providers/quota/report-cache.ts +53 -5
- package/src/providers/quota/vendor-probes-key.ts +73 -0
- package/src/providers/quota/vendor-probes-oauth.ts +57 -3
- package/src/providers/quota-key-accounts.ts +12 -5
- package/src/providers/quota-mistral-budget.ts +18 -0
- package/src/providers/quota-types.ts +25 -0
- package/src/providers/quota.ts +22 -22
- package/src/providers/reasoning-metadata.ts +1051 -12
- package/src/quota/reset-observer.ts +4 -2
- package/src/quota/reset-seen-store.ts +9 -0
- package/src/quota/window-mapping.ts +1 -0
- package/src/quota-pool/assemble.ts +4 -1
- package/src/responses/hosted-tool-policy.ts +56 -12
- package/src/router.ts +2 -0
- package/src/server/auth-cors.ts +11 -8
- package/src/server/catalog-download.ts +3 -5
- package/src/server/chat-native.ts +11 -2
- package/src/server/claude-messages.ts +2 -1
- package/src/server/images.ts +41 -13
- package/src/server/index/link-listener.ts +16 -2
- package/src/server/index/link-relay-sessions.ts +43 -2
- package/src/server/index/optional-listeners.ts +18 -0
- package/src/server/management/config-routes.ts +7 -1
- package/src/server/management/context.ts +1 -1
- package/src/server/management/link-child-ops-routes.ts +116 -0
- package/src/server/management/link-route-state.ts +10 -0
- package/src/server/management/link-routes.ts +10 -0
- package/src/server/management/oauth-account-routes.ts +33 -4
- package/src/server/management/provider-overwrite-carry.ts +28 -3
- package/src/server/management/provider-routes.ts +16 -11
- package/src/server/management/route-registry.ts +3 -0
- package/src/server/messages-native.ts +5 -0
- package/src/server/request-log-failure-detail.ts +59 -1
- package/src/server/responses/adapter-dispatch.ts +35 -44
- package/src/server/responses/combo-stream-preflight.ts +146 -29
- package/src/server/responses/compact.ts +16 -5
- package/src/server/responses/context-overflow.ts +58 -2
- package/src/server/responses/core-combo-failure.ts +29 -4
- package/src/server/responses/core-combo-native.ts +3 -1
- package/src/server/responses/core-combo.ts +30 -3
- package/src/server/responses/core-errors.ts +3 -1
- package/src/server/responses/core-opaque-recovery.ts +45 -2
- package/src/server/responses/core-options.ts +12 -0
- package/src/server/responses/passthrough-dispatch.ts +30 -38
- package/src/server/responses/request-transport.ts +43 -14
- package/src/server/responses/reset-replay.ts +58 -2
- package/src/server/responses/run-turn-execution.ts +56 -30
- package/src/types/claude-tool-loading.ts +48 -0
- package/src/types/config.ts +5 -35
- package/src/types/provider.ts +21 -0
- package/src/types.ts +1 -0
- package/src/web-search/parse.ts +21 -2
- package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
- package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
- package/gui/dist/assets/index-Bziu8gTy.css +0 -2
- package/gui/dist/assets/index-OYzhQUNP.js +0 -94
- package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
- package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { atomicWriteFile } from "../config/atomic-write";
|
|
4
|
+
import { withConfigMutationLockSync } from "../config/mutation-lock";
|
|
5
|
+
import { assertNotRealHomeUnderTest } from "../lib/test-home-guard";
|
|
6
|
+
import { parseStrictSemver } from "../lib/strict-semver";
|
|
7
|
+
import { hardenSecretDir } from "../lib/windows-secret-acl";
|
|
8
|
+
import { PLAN_RUNTIME_OWNERS, type InstallKind, type PlanRuntimeOwner, type UpdateRoute } from "./child-update-contract";
|
|
9
|
+
import { childObservationsPath } from "./paths";
|
|
10
|
+
import { readLinkStore } from "./store";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* What the Home last learned about each Child, keyed by link id, in <configDir>/link/child-observations.json.
|
|
14
|
+
* A cache, not a trust boundary: unlike links.json's strict record keys, unknown keys are dropped, an invalid entry is
|
|
15
|
+
* dropped and a damaged or foreign file reads as empty, so a downgraded Home ignores it and links.json never changes.
|
|
16
|
+
*/
|
|
17
|
+
export const CHILD_OBSERVATIONS_SCHEMA = "ocx.link.child-observations/1";
|
|
18
|
+
export const CHILD_OBSERVATIONS_MAX_BYTES = 1024 * 1024;
|
|
19
|
+
export const DEFAULT_MAX_CHILD_OBSERVATIONS = 256;
|
|
20
|
+
export type ChildOp = "observe" | "sync" | "restart-codex" | "update";
|
|
21
|
+
/** The persisted slice of a wp3 job item. */
|
|
22
|
+
export interface ChildOperationSummary {
|
|
23
|
+
op: ChildOp; jobId: string; state: string; reason: string | null;
|
|
24
|
+
fromVersion?: string; toVersion?: string; finishedAt: string;
|
|
25
|
+
}
|
|
26
|
+
export interface ChildObservation {
|
|
27
|
+
observedAt: string; source: "plan" | "inspect" | "peer";
|
|
28
|
+
installedVersion: string | null; installKind: InstallKind; runtimeOwner: PlanRuntimeOwner | null;
|
|
29
|
+
updateRoute: UpdateRoute; updateReason: string | null; targetVersion: string | null;
|
|
30
|
+
catalogPulledAt: number | null; lastOperation: ChildOperationSummary | null; suppressedTarget: string | null;
|
|
31
|
+
/** Etag of the catalog bytes served with the pull at catalogPulledAt. Display verdict only. */
|
|
32
|
+
catalogPulledEtag: string | null;
|
|
33
|
+
/** Home catalog etag current when a Home-run pinned sync of this Child last reported synced. Fan-out eligibility
|
|
34
|
+
* uses this field, never catalogPulledAt: a GET of /v1/catalog only proves a fetch. */
|
|
35
|
+
catalogSyncedEtag: string | null;
|
|
36
|
+
/** Counted automatic update attempts for one target; survives a Home restart. */
|
|
37
|
+
autoUpdateAttempts: { target: string; count: number } | null;
|
|
38
|
+
/** plan.updateInFlight from the last ocx.update.plan/1 probe; null when the observation did not come from a plan.
|
|
39
|
+
* Not a carried field: every observe replaces it. */
|
|
40
|
+
updateInFlight: boolean | null;
|
|
41
|
+
/** An update whose result is unknown. A record carrying desktopRequestId is cleared only by the Desktop route's
|
|
42
|
+
* status reconciliation or by expiry, never by a sync. */
|
|
43
|
+
pendingUpdateRecovery: { target: string; since: string; until: string; desktopRequestId?: string } | null;
|
|
44
|
+
}
|
|
45
|
+
/** Fields an operation or the Home owns; a fresh observe never overwrites them. Missing in an older file ⇒ null. */
|
|
46
|
+
export const CARRIED_OBSERVATION_FIELDS = ["catalogPulledAt", "catalogPulledEtag", "catalogSyncedEtag", "lastOperation",
|
|
47
|
+
"suppressedTarget", "autoUpdateAttempts", "pendingUpdateRecovery"] as const;
|
|
48
|
+
export interface ChildObservationsFile {
|
|
49
|
+
schema: typeof CHILD_OBSERVATIONS_SCHEMA;
|
|
50
|
+
homeCatalog: { etag: string; changedAt: number } | null;
|
|
51
|
+
children: Record<string, ChildObservation>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const LINK_ID = /^lnk_[0-9a-f]{16}$/;
|
|
55
|
+
const REASON = /^[a-z][a-z0-9:-]{0,79}$/;
|
|
56
|
+
const STATE = /^[a-z][a-z0-9-]{0,63}$/;
|
|
57
|
+
const OPAQUE_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
58
|
+
const SOURCES: ReadonlySet<string> = new Set(["plan", "inspect", "peer"]);
|
|
59
|
+
const OPS: ReadonlySet<string> = new Set<ChildOp>(["observe", "sync", "restart-codex", "update"]);
|
|
60
|
+
const INSTALL_KINDS: ReadonlySet<string> = new Set<InstallKind>(["npm", "pnpm", "bun", "source", "mise", "desktop-app", "goat", "standalone", "ocx-child", "unknown"]);
|
|
61
|
+
const ROUTES: ReadonlySet<string> = new Set<UpdateRoute>(["orchestrated", "desktop-request", "owner-action", "replant", "none"]);
|
|
62
|
+
|
|
63
|
+
/** Thrown inside a field reader; the entry that holds the field is dropped. */
|
|
64
|
+
class Drop extends Error {}
|
|
65
|
+
const drop = (): never => { throw new Drop(); };
|
|
66
|
+
const isObject = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
|
|
67
|
+
const version = (value: unknown): string => typeof value === "string" && value.length <= 128 && parseStrictSemver(value) ? value : drop();
|
|
68
|
+
const nullable = <T>(value: unknown, read: (value: unknown) => T): T | null => value === null || value === undefined ? null : read(value);
|
|
69
|
+
const time = (value: unknown): string => typeof value === "string" && value.length <= 64 && !Number.isNaN(Date.parse(value)) ? value : drop();
|
|
70
|
+
const epoch = (value: unknown): number => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : drop();
|
|
71
|
+
const token = (pattern: RegExp) => (value: unknown): string => typeof value === "string" && pattern.test(value) ? value : drop();
|
|
72
|
+
const member = <T extends string>(set: ReadonlySet<string>) => (value: unknown): T => typeof value === "string" && set.has(value) ? value as T : drop();
|
|
73
|
+
// Etags are quoted opaque strings; anything printable and bounded is kept.
|
|
74
|
+
const etag = (value: unknown): string => typeof value === "string" && value.length >= 1 && value.length <= 256 && /^[\x20-\x7e]+$/.test(value) ? value : drop();
|
|
75
|
+
|
|
76
|
+
function summary(value: unknown): ChildOperationSummary {
|
|
77
|
+
if (!isObject(value)) return drop();
|
|
78
|
+
return {
|
|
79
|
+
op: member<ChildOp>(OPS)(value.op), jobId: token(OPAQUE_ID)(value.jobId), state: token(STATE)(value.state),
|
|
80
|
+
reason: nullable(value.reason, token(REASON)),
|
|
81
|
+
...(value.fromVersion === undefined ? {} : { fromVersion: version(value.fromVersion) }),
|
|
82
|
+
...(value.toVersion === undefined ? {} : { toVersion: version(value.toVersion) }),
|
|
83
|
+
finishedAt: time(value.finishedAt),
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
function attempts(value: unknown): { target: string; count: number } {
|
|
87
|
+
if (!isObject(value)) return drop();
|
|
88
|
+
const count = value.count;
|
|
89
|
+
return { target: version(value.target), count: typeof count === "number" && Number.isSafeInteger(count) && count >= 0 ? count : drop() };
|
|
90
|
+
}
|
|
91
|
+
function recovery(value: unknown): NonNullable<ChildObservation["pendingUpdateRecovery"]> {
|
|
92
|
+
if (!isObject(value)) return drop();
|
|
93
|
+
return { target: version(value.target), since: time(value.since), until: time(value.until),
|
|
94
|
+
...(value.desktopRequestId === undefined ? {} : { desktopRequestId: token(OPAQUE_ID)(value.desktopRequestId) }) };
|
|
95
|
+
}
|
|
96
|
+
function observation(value: unknown): ChildObservation {
|
|
97
|
+
if (!isObject(value)) return drop();
|
|
98
|
+
return {
|
|
99
|
+
observedAt: time(value.observedAt), source: member<ChildObservation["source"]>(SOURCES)(value.source),
|
|
100
|
+
installedVersion: nullable(value.installedVersion, version), installKind: member<InstallKind>(INSTALL_KINDS)(value.installKind),
|
|
101
|
+
runtimeOwner: nullable(value.runtimeOwner, member<PlanRuntimeOwner>(PLAN_RUNTIME_OWNERS)),
|
|
102
|
+
updateRoute: member<UpdateRoute>(ROUTES)(value.updateRoute), updateReason: nullable(value.updateReason, token(REASON)),
|
|
103
|
+
targetVersion: nullable(value.targetVersion, version), catalogPulledAt: nullable(value.catalogPulledAt, epoch),
|
|
104
|
+
lastOperation: nullable(value.lastOperation, summary), suppressedTarget: nullable(value.suppressedTarget, version),
|
|
105
|
+
catalogPulledEtag: nullable(value.catalogPulledEtag, etag), catalogSyncedEtag: nullable(value.catalogSyncedEtag, etag),
|
|
106
|
+
autoUpdateAttempts: nullable(value.autoUpdateAttempts, attempts),
|
|
107
|
+
updateInFlight: nullable(value.updateInFlight, item => typeof item === "boolean" ? item : drop()),
|
|
108
|
+
pendingUpdateRecovery: nullable(value.pendingUpdateRecovery, recovery),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function homeCatalog(value: unknown): ChildObservationsFile["homeCatalog"] {
|
|
112
|
+
if (!isObject(value)) return null;
|
|
113
|
+
try { return { etag: etag(value.etag), changedAt: epoch(value.changedAt) }; } catch (error) {
|
|
114
|
+
if (error instanceof Drop) return null;
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function emptyChildObservations(): ChildObservationsFile {
|
|
120
|
+
return { schema: CHILD_OBSERVATIONS_SCHEMA, homeCatalog: null, children: {} };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function withoutCarriedFields(value: ChildObservation): Partial<ChildObservation> {
|
|
124
|
+
const copy: Partial<ChildObservation> = { ...value };
|
|
125
|
+
for (const field of CARRIED_OBSERVATION_FIELDS) delete copy[field];
|
|
126
|
+
return copy;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Tolerant: unknown keys dropped, an invalid entry dropped, an invalid file or wrong schema reads as empty. */
|
|
130
|
+
export function parseChildObservations(text: string): ChildObservationsFile {
|
|
131
|
+
let raw: unknown;
|
|
132
|
+
try { raw = JSON.parse(text); } catch { return emptyChildObservations(); }
|
|
133
|
+
if (!isObject(raw) || raw.schema !== CHILD_OBSERVATIONS_SCHEMA) return emptyChildObservations();
|
|
134
|
+
const file: ChildObservationsFile = { schema: CHILD_OBSERVATIONS_SCHEMA, homeCatalog: homeCatalog(raw.homeCatalog), children: {} };
|
|
135
|
+
if (!isObject(raw.children)) return file;
|
|
136
|
+
for (const [linkId, entry] of Object.entries(raw.children)) {
|
|
137
|
+
if (!LINK_ID.test(linkId)) continue;
|
|
138
|
+
try { file.children[linkId] = observation(entry); } catch (error) {
|
|
139
|
+
if (!(error instanceof Drop)) throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return file;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Missing, unreadable, larger than 1 MiB or damaged → empty. Never throws for content. */
|
|
146
|
+
export function readChildObservations(path: string = childObservationsPath()): ChildObservationsFile {
|
|
147
|
+
let bytes: Buffer;
|
|
148
|
+
try { bytes = readFileSync(path); } catch { return emptyChildObservations(); }
|
|
149
|
+
if (bytes.length > CHILD_OBSERVATIONS_MAX_BYTES) return emptyChildObservations();
|
|
150
|
+
return parseChildObservations(bytes.toString("utf8"));
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Keep the most recently observed entries when the file holds more than maxEntries. */
|
|
154
|
+
function capEntries(file: ChildObservationsFile, maxEntries: number): void {
|
|
155
|
+
const entries = Object.entries(file.children);
|
|
156
|
+
if (entries.length <= maxEntries) return;
|
|
157
|
+
entries.sort(([, a], [, b]) => Date.parse(b.observedAt) - Date.parse(a.observedAt));
|
|
158
|
+
file.children = Object.fromEntries(entries.slice(0, Math.max(0, maxEntries)));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Read–mutate–write under withConfigMutationLockSync. Inside the lock it reads links.json and drops entries whose link
|
|
163
|
+
* id is absent; a damaged links.json disables pruning for that write only. Dir 0700 (hardenSecretDir on Windows), file
|
|
164
|
+
* written with atomicWriteFile then chmod 0600, as writeLinkStore. Throws ConfigMutationLockError on contention
|
|
165
|
+
* (busy_timeout=0); callers decide whether to retry.
|
|
166
|
+
*/
|
|
167
|
+
export function updateChildObservations(mutate: (file: ChildObservationsFile) => void,
|
|
168
|
+
deps: { path?: string; storePath?: string; maxEntries?: number } = {}): ChildObservationsFile {
|
|
169
|
+
const path = deps.path ?? childObservationsPath();
|
|
170
|
+
const dir = dirname(path), configDir = dirname(dir);
|
|
171
|
+
assertNotRealHomeUnderTest(configDir);
|
|
172
|
+
return withConfigMutationLockSync(() => {
|
|
173
|
+
const current = readChildObservations(path);
|
|
174
|
+
mutate(current);
|
|
175
|
+
const next = parseChildObservations(JSON.stringify(current));
|
|
176
|
+
let linkIds: Set<string> | null = null;
|
|
177
|
+
try { linkIds = new Set(readLinkStore(deps.storePath ?? join(dir, "links.json")).links.map(link => link.id)); } catch { linkIds = null; }
|
|
178
|
+
if (linkIds) for (const linkId of Object.keys(next.children)) if (!linkIds.has(linkId)) delete next.children[linkId];
|
|
179
|
+
capEntries(next, deps.maxEntries ?? DEFAULT_MAX_CHILD_OBSERVATIONS);
|
|
180
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
181
|
+
if (process.platform === "win32") hardenSecretDir(dir, { required: true });
|
|
182
|
+
else chmodSync(dir, 0o700);
|
|
183
|
+
atomicWriteFile(path, `${JSON.stringify(next, null, 2)}\n`);
|
|
184
|
+
if (process.platform !== "win32") chmodSync(path, 0o600);
|
|
185
|
+
return next;
|
|
186
|
+
}, configDir);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Merge a patch into one Child's entry and stamp observedAt with now. A patch of carried fields only (a catalog pull,
|
|
191
|
+
* an operation summary) keeps an existing entry's observedAt, so install facts never read fresher than they are.
|
|
192
|
+
* A Child never observed before starts as an unknown "inspect" record with every field null, so an operation summary
|
|
193
|
+
* can be stored before the first observe; that new entry is stamped.
|
|
194
|
+
*/
|
|
195
|
+
export function patchChildObservation(file: ChildObservationsFile, linkId: string, patch: Partial<ChildObservation>, now: Date): void {
|
|
196
|
+
const existing = file.children[linkId];
|
|
197
|
+
const base: ChildObservation = existing ?? {
|
|
198
|
+
observedAt: now.toISOString(), source: "inspect", installedVersion: null, installKind: "unknown", runtimeOwner: null,
|
|
199
|
+
updateRoute: "none", updateReason: null, targetVersion: null, catalogPulledAt: null, lastOperation: null, suppressedTarget: null,
|
|
200
|
+
catalogPulledEtag: null, catalogSyncedEtag: null, autoUpdateAttempts: null, updateInFlight: null, pendingUpdateRecovery: null,
|
|
201
|
+
};
|
|
202
|
+
const carriedOnly = Object.keys(patch).every(key => (CARRIED_OBSERVATION_FIELDS as readonly string[]).includes(key));
|
|
203
|
+
file.children[linkId] = { ...base, ...patch, observedAt: carriedOnly && existing ? base.observedAt : now.toISOString() };
|
|
204
|
+
}
|
|
205
|
+
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { classifyUpdatePlanProbe, remoteUpdatePlanArgv, type SshResult } from "./child-gated-ocx";
|
|
2
|
+
import type { PlanClassification } from "./child-update-contract";
|
|
3
|
+
import type { ChildObservation } from "./child-observations";
|
|
4
|
+
import type { LinkPeerEntry } from "./peer-report";
|
|
5
|
+
import type { inspectRemoteChildRuntime } from "./remote-plant";
|
|
6
|
+
import { buildExecArgv, LinkSshArgumentError } from "./ssh-argv";
|
|
7
|
+
import { SshRunnerError, type SshRunner } from "./ssh-runner";
|
|
8
|
+
import type { LinkRecord } from "./store";
|
|
9
|
+
import { parseOcxVersion } from "./sync-fanout-classify";
|
|
10
|
+
import { parseStrictSemver } from "../lib/strict-semver";
|
|
11
|
+
|
|
12
|
+
export const OBSERVE_TIMEOUT_MS = 60_000;
|
|
13
|
+
export const OBSERVE_MAX_OUTPUT_BYTES = 65_536;
|
|
14
|
+
|
|
15
|
+
export interface ObserveDeps {
|
|
16
|
+
runner: Pick<SshRunner, "run">; knownHostsFile: string; homeVersion: string;
|
|
17
|
+
peer: (linkId: string) => LinkPeerEntry; platformOf: (record: LinkRecord) => Promise<"posix" | "windows">;
|
|
18
|
+
inspect: typeof inspectRemoteChildRuntime; now: () => Date;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Set only for a parsed plan. childNowMs is the Child's clock from the gate; startedAt is the Home's clock when the probe
|
|
23
|
+
* was sent; platform is the one observe resolved, so the wp3 update runner never probes it again.
|
|
24
|
+
*/
|
|
25
|
+
export interface ObserveProbe { classification: PlanClassification; childNowMs: number | null; startedAt: number; platform: "posix" | "windows" }
|
|
26
|
+
|
|
27
|
+
/** observation is a whole ChildObservation with every carried field null; writers strip them with withoutCarriedFields. */
|
|
28
|
+
export interface ObserveOutcome {
|
|
29
|
+
state: "succeeded" | "owner-action" | "unsupported" | "offline" | "failed"; reason: string | null;
|
|
30
|
+
observation: ChildObservation | null; probe: ObserveProbe | null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
type ObservedFields = Pick<ChildObservation, "source" | "installedVersion" | "installKind" | "runtimeOwner" | "updateRoute" | "updateReason"
|
|
34
|
+
| "targetVersion" | "updateInFlight">;
|
|
35
|
+
|
|
36
|
+
function observation(fields: ObservedFields, now: Date): ChildObservation {
|
|
37
|
+
return {
|
|
38
|
+
observedAt: now.toISOString(), ...fields,
|
|
39
|
+
catalogPulledAt: null, catalogPulledEtag: null, catalogSyncedEtag: null, lastOperation: null, suppressedTarget: null,
|
|
40
|
+
autoUpdateAttempts: null, pendingUpdateRecovery: null,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const strictVersion = (value: string | null | undefined): string | null => typeof value === "string" && parseStrictSemver(value) ? value : null;
|
|
45
|
+
const peerVersion = (deps: ObserveDeps, record: LinkRecord): string | null => strictVersion(deps.peer(record.id).observed?.version);
|
|
46
|
+
const outcome = (state: ObserveOutcome["state"], reason: string | null, value: ChildObservation | null = null): ObserveOutcome =>
|
|
47
|
+
({ state, reason, observation: value, probe: null });
|
|
48
|
+
|
|
49
|
+
function ephemeral(now: Date): ObserveOutcome {
|
|
50
|
+
// An ocx-child's version is a protocol constant (D10), so no version is stored.
|
|
51
|
+
return outcome("succeeded", null, observation({ source: "peer", installedVersion: null, installKind: "ocx-child", runtimeOwner: null,
|
|
52
|
+
updateRoute: "replant", updateReason: "ocx-child", targetVersion: null, updateInFlight: null }, now));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function runnerFailure(error: unknown): ObserveOutcome {
|
|
56
|
+
if (error instanceof SshRunnerError && error.code === "output_limit") return outcome("failed", "ssh-output-limit");
|
|
57
|
+
if (error instanceof SshRunnerError && error.code === "decode") return outcome("failed", "ssh-output-decode");
|
|
58
|
+
return outcome("offline", "ssh-error");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The observe operation (D3): one gated `ocx update --plan` over the link's pinned SSH channel, reduced to closed
|
|
63
|
+
* tokens. It never changes an install. Client-initiated and ocx-child links never reach SSH; a pre-2.97 POSIX Child
|
|
64
|
+
* costs one more read-only SSH call to read its version. No remote text is returned.
|
|
65
|
+
*/
|
|
66
|
+
export async function observeChild(record: LinkRecord, deps: ObserveDeps): Promise<ObserveOutcome> {
|
|
67
|
+
if (record.direction === "client-initiated") {
|
|
68
|
+
return { state: "unsupported", reason: "child-initiated", probe: null, observation: observation({ source: "peer",
|
|
69
|
+
installedVersion: peerVersion(deps, record), installKind: "unknown", runtimeOwner: null, updateRoute: "none",
|
|
70
|
+
updateReason: "child-initiated", targetVersion: null, updateInFlight: null }, deps.now()) };
|
|
71
|
+
}
|
|
72
|
+
if (record.childKind === "ephemeral") return ephemeral(deps.now());
|
|
73
|
+
let platform: "posix" | "windows";
|
|
74
|
+
try { platform = record.remotePlatform ?? await deps.platformOf(record); } catch { return outcome("offline", "platform-unknown"); }
|
|
75
|
+
let argv: string[];
|
|
76
|
+
try {
|
|
77
|
+
argv = buildExecArgv({ alias: record.alias, knownHostsFile: deps.knownHostsFile, argv: remoteUpdatePlanArgv(deps.homeVersion, platform) });
|
|
78
|
+
} catch (error) {
|
|
79
|
+
if (error instanceof LinkSshArgumentError && error.message === "windows-command-too-long") return outcome("failed", "windows-command-too-long");
|
|
80
|
+
if (error instanceof LinkSshArgumentError && error.message === "invalid Home version") return outcome("failed", "home-version-invalid");
|
|
81
|
+
return outcome("failed", "ssh-argument-invalid");
|
|
82
|
+
}
|
|
83
|
+
const startedAt = deps.now().getTime();
|
|
84
|
+
let result: SshResult;
|
|
85
|
+
try {
|
|
86
|
+
result = await deps.runner.run(argv, { timeoutMs: OBSERVE_TIMEOUT_MS, maxOutputBytes: OBSERVE_MAX_OUTPUT_BYTES });
|
|
87
|
+
} catch (error) { return runnerFailure(error); }
|
|
88
|
+
const peerFeatures = deps.peer(record.id).observed?.features ?? [];
|
|
89
|
+
// Always pass the platform: the Windows script prints no entry marker and only this lets the classifier infer binary.
|
|
90
|
+
const verdict = classifyUpdatePlanProbe(result, { homeVersion: deps.homeVersion, desktopUpdateRequest: peerFeatures.includes("desktop-update-request/1"), platform });
|
|
91
|
+
switch (verdict.kind) {
|
|
92
|
+
case "plan": {
|
|
93
|
+
const { classification } = verdict;
|
|
94
|
+
return { state: "succeeded", reason: null, probe: { classification, childNowMs: verdict.childNowMs, startedAt, platform },
|
|
95
|
+
observation: observation({ source: "plan", installedVersion: strictVersion(classification.installedVersion),
|
|
96
|
+
installKind: classification.installKind, runtimeOwner: classification.runtimeOwner, updateRoute: classification.updateRoute,
|
|
97
|
+
updateReason: classification.updateReason, targetVersion: strictVersion(classification.targetVersion),
|
|
98
|
+
updateInFlight: classification.updateInFlight }, deps.now()) };
|
|
99
|
+
}
|
|
100
|
+
case "ephemeral": return ephemeral(deps.now());
|
|
101
|
+
case "legacy": {
|
|
102
|
+
let installedVersion: string | null;
|
|
103
|
+
let source: ChildObservation["source"];
|
|
104
|
+
if (platform === "posix") {
|
|
105
|
+
source = "inspect";
|
|
106
|
+
try {
|
|
107
|
+
const inspected = await deps.inspect(deps.runner, record.alias, deps.knownHostsFile, "posix");
|
|
108
|
+
installedVersion = parseOcxVersion(inspected?.ocxVersionLine ?? "");
|
|
109
|
+
} catch { installedVersion = null; }
|
|
110
|
+
} else {
|
|
111
|
+
// Windows inspection does not read the served census, so the peer report is the better source.
|
|
112
|
+
source = "peer";
|
|
113
|
+
installedVersion = peerVersion(deps, record);
|
|
114
|
+
}
|
|
115
|
+
return outcome("owner-action", "legacy-ocx", observation({ source, installedVersion, installKind: "unknown", runtimeOwner: null,
|
|
116
|
+
updateRoute: "owner-action", updateReason: "legacy-ocx", targetVersion: null, updateInFlight: null }, deps.now()));
|
|
117
|
+
}
|
|
118
|
+
case "offline": return outcome("offline", "ssh-failed");
|
|
119
|
+
case "failed": return outcome("failed", verdict.reason);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { withoutCarriedFields, type ChildObservation, type ChildOp, type ChildOperationSummary } from "./child-observations";
|
|
3
|
+
import type { ObserveOutcome } from "./child-observe";
|
|
4
|
+
import type { LinkRecord, LinkStore } from "./store";
|
|
5
|
+
|
|
6
|
+
// ChildOp is declared once, in child-observations.ts; wp2 admits "observe" only. 030 moves the job types to
|
|
7
|
+
// child-ops-types.ts and extends this engine with its runners.
|
|
8
|
+
export type ChildItemState = "queued" | "running" | "succeeded" | "up-to-date" | "busy" | "offline" | "refused"
|
|
9
|
+
| "owner-action" | "unsupported" | "failed" | "uncertain";
|
|
10
|
+
export interface ChildJobItem {
|
|
11
|
+
linkId: string; alias: string; state: ChildItemState; reason: string | null; hint?: string;
|
|
12
|
+
fromVersion?: string; toVersion?: string; startedAt: string | null; finishedAt: string | null;
|
|
13
|
+
}
|
|
14
|
+
export interface ChildJob {
|
|
15
|
+
schema: "ocx.link.child-job/1"; jobId: string; op: ChildOp; trigger: "manual" | "auto";
|
|
16
|
+
restart: "none" | "app-server" | "codex"; state: "queued" | "running" | "done"; createdAt: string; finishedAt: string | null; items: ChildJobItem[];
|
|
17
|
+
}
|
|
18
|
+
export type SubmitResult = { ok: true; job: ChildJob } | { ok: false; code: "link_not_found" | "link_operation_in_progress" | "no_eligible_links" };
|
|
19
|
+
export interface ChildOpsEngine {
|
|
20
|
+
submit(request: { op: "observe"; linkIds: readonly string[] | "all"; trigger: "manual" | "auto" }): SubmitResult;
|
|
21
|
+
/** A structuredClone snapshot. */
|
|
22
|
+
job(jobId: string): ChildJob | undefined;
|
|
23
|
+
activeJob(linkId: string): { jobId: string; op: ChildOp; state: "queued" | "running" } | null;
|
|
24
|
+
/** Resolves once no job of this engine is queued or running. */
|
|
25
|
+
settled(): Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export const CHILD_JOB_SCHEMA = "ocx.link.child-job/1";
|
|
29
|
+
export const CHILD_OPS_CONCURRENCY = 3;
|
|
30
|
+
export const CHILD_JOB_RETENTION_MS = 60 * 60 * 1000;
|
|
31
|
+
export const CHILD_JOB_RETENTION_COUNT = 32;
|
|
32
|
+
|
|
33
|
+
const errorName = (error: unknown): string => error instanceof Error ? error.name : "unknown";
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The D11 job model: one in-memory registry, one engine-wide lock per link, at most 3 items running across every job
|
|
37
|
+
* of the engine, finished jobs kept one hour and at most 32. A Home restart loses the jobs only; the observation cache
|
|
38
|
+
* keeps each Child's last result. Items carry closed tokens, never remote text. No timers: retention is applied on
|
|
39
|
+
* each submit and read.
|
|
40
|
+
*/
|
|
41
|
+
export function createChildOpsEngine(deps: {
|
|
42
|
+
readStore: () => LinkStore; observe: (record: LinkRecord) => Promise<ObserveOutcome>;
|
|
43
|
+
/** Production: updateChildObservations(file => patchChildObservation(file, linkId, patch, now())). */
|
|
44
|
+
writeObservation: (linkId: string, patch: Partial<ChildObservation>) => void;
|
|
45
|
+
now?: () => Date; jobId?: () => string; concurrency?: number;
|
|
46
|
+
}): ChildOpsEngine {
|
|
47
|
+
const now = deps.now ?? (() => new Date());
|
|
48
|
+
const newJobId = deps.jobId ?? (() => `ljob_${randomBytes(8).toString("hex")}`);
|
|
49
|
+
const concurrency = Math.max(1, deps.concurrency ?? CHILD_OPS_CONCURRENCY);
|
|
50
|
+
const jobs = new Map<string, ChildJob>();
|
|
51
|
+
const locks = new Map<string, string>();
|
|
52
|
+
const idle = new Set<() => void>();
|
|
53
|
+
// One engine-wide queue: the concurrency limit bounds SSH sessions across jobs, not per job.
|
|
54
|
+
const pending: Array<{ job: ChildJob; item: ChildJobItem }> = [];
|
|
55
|
+
let active = 0;
|
|
56
|
+
|
|
57
|
+
const write = (linkId: string, patch: Partial<ChildObservation>): void => {
|
|
58
|
+
try { deps.writeObservation(linkId, patch); } catch (error) {
|
|
59
|
+
// The file is a cache and the job document already carries the result.
|
|
60
|
+
console.warn(`[link] child observation write failed linkId=${linkId} error=${errorName(error)}`);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const running = (): boolean => [...jobs.values()].some(job => job.state !== "done");
|
|
64
|
+
const prune = (): void => {
|
|
65
|
+
const cutoff = now().getTime() - CHILD_JOB_RETENTION_MS;
|
|
66
|
+
const finished = [...jobs.values()].filter(job => job.state === "done");
|
|
67
|
+
for (const job of finished) if (Date.parse(job.finishedAt!) < cutoff) jobs.delete(job.jobId);
|
|
68
|
+
const kept = finished.filter(job => jobs.has(job.jobId)).sort((a, b) => Date.parse(a.finishedAt!) - Date.parse(b.finishedAt!));
|
|
69
|
+
for (const job of kept.slice(0, Math.max(0, kept.length - CHILD_JOB_RETENTION_COUNT))) jobs.delete(job.jobId);
|
|
70
|
+
};
|
|
71
|
+
/** `ran` is false for an item that never touched its link (busy): the link's lastOperation belongs to its holder. */
|
|
72
|
+
const finishItem = (job: ChildJob, item: ChildJobItem, state: ChildItemState, reason: string | null, ran = true): void => {
|
|
73
|
+
item.state = state;
|
|
74
|
+
item.reason = reason;
|
|
75
|
+
item.finishedAt = now().toISOString();
|
|
76
|
+
if (!ran) return;
|
|
77
|
+
if (locks.get(item.linkId) === job.jobId) locks.delete(item.linkId);
|
|
78
|
+
const summary: ChildOperationSummary = { op: job.op, jobId: job.jobId, state, reason, finishedAt: item.finishedAt };
|
|
79
|
+
write(item.linkId, { lastOperation: summary });
|
|
80
|
+
};
|
|
81
|
+
const finishJob = (job: ChildJob): void => {
|
|
82
|
+
if (job.state === "done" || job.items.some(item => item.state === "queued" || item.state === "running")) return;
|
|
83
|
+
job.state = "done";
|
|
84
|
+
job.finishedAt = now().toISOString();
|
|
85
|
+
if (!running()) { for (const resolve of idle) resolve(); idle.clear(); }
|
|
86
|
+
};
|
|
87
|
+
const runItem = async (job: ChildJob, item: ChildJobItem): Promise<void> => {
|
|
88
|
+
item.state = "running";
|
|
89
|
+
item.startedAt = now().toISOString();
|
|
90
|
+
if (job.state === "queued") job.state = "running";
|
|
91
|
+
let record: LinkRecord | undefined;
|
|
92
|
+
try { record = deps.readStore().links.find(link => link.id === item.linkId); } catch { record = undefined; }
|
|
93
|
+
if (!record) { finishItem(job, item, "refused", "link-removed"); return; }
|
|
94
|
+
let outcome: ObserveOutcome;
|
|
95
|
+
try { outcome = await deps.observe(record); } catch (error) {
|
|
96
|
+
console.warn(`[link] child observe failed linkId=${item.linkId} error=${errorName(error)}`);
|
|
97
|
+
finishItem(job, item, "failed", "observe-error");
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
if (outcome.observation) write(item.linkId, withoutCarriedFields(outcome.observation));
|
|
101
|
+
finishItem(job, item, outcome.state, outcome.reason);
|
|
102
|
+
};
|
|
103
|
+
const pump = (): void => {
|
|
104
|
+
while (active < concurrency && pending.length > 0) {
|
|
105
|
+
const { job, item } = pending.shift()!;
|
|
106
|
+
active += 1;
|
|
107
|
+
void runItem(job, item).finally(() => {
|
|
108
|
+
active -= 1;
|
|
109
|
+
finishJob(job);
|
|
110
|
+
pump();
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
return {
|
|
116
|
+
submit(request) {
|
|
117
|
+
prune();
|
|
118
|
+
const store = deps.readStore();
|
|
119
|
+
let records: LinkRecord[];
|
|
120
|
+
if (request.linkIds === "all") {
|
|
121
|
+
records = store.links;
|
|
122
|
+
if (records.length === 0) return { ok: false, code: "no_eligible_links" };
|
|
123
|
+
} else {
|
|
124
|
+
records = [];
|
|
125
|
+
for (const linkId of request.linkIds) {
|
|
126
|
+
const record = store.links.find(link => link.id === linkId);
|
|
127
|
+
if (!record) return { ok: false, code: "link_not_found" };
|
|
128
|
+
records.push(record);
|
|
129
|
+
}
|
|
130
|
+
if (records.length === 1 && locks.has(records[0]!.id)) return { ok: false, code: "link_operation_in_progress" };
|
|
131
|
+
}
|
|
132
|
+
const jobId = newJobId();
|
|
133
|
+
const createdAt = now().toISOString();
|
|
134
|
+
const job: ChildJob = { schema: CHILD_JOB_SCHEMA, jobId, op: request.op, trigger: request.trigger, restart: "none", state: "queued",
|
|
135
|
+
createdAt, finishedAt: null, items: records.map(record => ({ linkId: record.id, alias: record.alias, state: "queued" as const, reason: null,
|
|
136
|
+
startedAt: null, finishedAt: null })) };
|
|
137
|
+
jobs.set(jobId, job);
|
|
138
|
+
for (const item of job.items) {
|
|
139
|
+
if (locks.has(item.linkId)) finishItem(job, item, "busy", "link-operation-in-progress", false);
|
|
140
|
+
else { locks.set(item.linkId, jobId); pending.push({ job, item }); }
|
|
141
|
+
}
|
|
142
|
+
pump();
|
|
143
|
+
finishJob(job);
|
|
144
|
+
return { ok: true, job: structuredClone(job) };
|
|
145
|
+
},
|
|
146
|
+
job(jobId) {
|
|
147
|
+
prune();
|
|
148
|
+
const job = jobs.get(jobId);
|
|
149
|
+
return job ? structuredClone(job) : undefined;
|
|
150
|
+
},
|
|
151
|
+
activeJob(linkId) {
|
|
152
|
+
const jobId = locks.get(linkId);
|
|
153
|
+
const job = jobId ? jobs.get(jobId) : undefined;
|
|
154
|
+
if (!job || job.state === "done") return null;
|
|
155
|
+
return { jobId: job.jobId, op: job.op, state: job.state };
|
|
156
|
+
},
|
|
157
|
+
settled() {
|
|
158
|
+
if (!running()) return Promise.resolve();
|
|
159
|
+
return new Promise<void>(resolve => { idle.add(resolve); });
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|