@bitkyc08/opencodex 2.94.0 → 2.95.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/gui/dist/assets/App-8yedBkhm.js +58 -0
- package/gui/dist/assets/App-B4j-Txmb.css +1 -0
- package/gui/dist/assets/{Tray-CZatQdoF.js → Tray-erSMzxPG.js} +1 -1
- package/gui/dist/assets/index-D7DCm5eQ.js +94 -0
- package/gui/dist/assets/quota-summary-BK4VuQNc.js +1 -0
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +10 -3
- package/src/adapters/command-code-project-context.ts +3 -3
- package/src/adapters/kiro/adapter.ts +4 -1
- package/src/adapters/kiro/stream.ts +1 -0
- package/src/adapters/kiro-events.ts +1 -0
- package/src/adapters/openai-chat/messages.ts +20 -7
- package/src/adapters/openai-chat/passthrough.ts +4 -2
- package/src/adapters/openai-chat/single-system.ts +24 -0
- package/src/adapters/openai-responses/muse-tool-catalog.ts +87 -0
- package/src/adapters/openai-responses/passthrough.ts +42 -7
- package/src/adapters/openai-responses/prompt-cache.ts +3 -1
- package/src/adapters/openai-responses/request-strips.ts +23 -4
- package/src/adapters/openai-responses/tool-output-recovery.ts +21 -8
- package/src/adapters/openai-responses/tool-schema.ts +20 -8
- package/src/adapters/opencode-go-additional-tools.ts +39 -6
- package/src/adapters/routed-agent-messages.ts +3 -0
- package/src/adapters/xai-web-search.ts +6 -3
- package/src/adapters/zed-additional-tools.ts +7 -7
- package/src/adapters/zed.ts +1 -6
- package/src/advisor/consult.ts +22 -10
- package/src/advisor/runtime.ts +10 -4
- package/src/bridge/max-output-completion.ts +41 -0
- package/src/bridge/response-json.ts +9 -4
- package/src/bridge/sse.ts +13 -2
- package/src/chatgpt/app-server-shim/bundle-trust-policy.ts +5 -0
- package/src/chatgpt/app-server-shim/launcher.ts +40 -6
- package/src/claude/compatibility.ts +5 -1
- package/src/claude/desktop-3p.ts +27 -6
- package/src/claude/desktop-model-visibility.ts +141 -0
- package/src/claude/desktop-remote-store-io.ts +8 -8
- package/src/claude/inbound-content-options.ts +11 -1
- package/src/claude/intercept/proxy-auth.ts +16 -16
- package/src/cli/account-main.ts +3 -2
- package/src/cli/capabilities-provider-models.ts +7 -0
- package/src/cli/chatgpt-command.ts +1 -1
- package/src/cli/codex-launcher.ts +20 -8
- package/src/cli/codex-shim-autorestore.ts +19 -1
- package/src/cli/dispatch.ts +6 -6
- package/src/cli/doctor.ts +5 -5
- package/src/cli/index.ts +4 -9
- package/src/cli/init.ts +2 -2
- package/src/cli/internal-command.ts +29 -2
- package/src/cli/provider-cc-switch-import.ts +185 -0
- package/src/cli/provider.ts +5 -0
- package/src/cli/registry.ts +1 -0
- package/src/cli/restart-scope.ts +2 -2
- package/src/cli/root.ts +6 -6
- package/src/cli/stop-approval.ts +15 -1
- package/src/cli/v2.ts +69 -19
- package/src/client/machine-api.ts +2 -2
- package/src/clients/config-export.ts +14 -3
- package/src/codex/account-cooldown-response.ts +18 -0
- package/src/codex/app-server-restart-service.ts +2 -2
- package/src/codex/auth-api/login-flow.ts +2 -2
- package/src/codex/auth-api/pool-quota-probe.ts +2 -2
- package/src/codex/auth-context.ts +4 -4
- package/src/codex/catalog/bundled.ts +10 -3
- package/src/codex/catalog/metadata.ts +4 -5
- package/src/codex/catalog/native-omission.ts +28 -0
- package/src/codex/catalog/native-template.ts +58 -0
- package/src/codex/catalog/parsing.ts +3 -29
- package/src/codex/catalog/provider-models.ts +2 -1
- package/src/codex/catalog/retained-sync.ts +15 -5
- package/src/codex/catalog/write-audit.ts +18 -18
- package/src/codex/cli-install-provenance.ts +46 -45
- package/src/codex/cli-update-artifacts.ts +8 -6
- package/src/codex/cli-update-job-store-windows.ts +99 -27
- package/src/codex/cli-update-job-worker.ts +3 -11
- package/src/codex/cli-update-recovery.ts +54 -8
- package/src/codex/cli-update-selection-gate.ts +74 -4
- package/src/codex/cli-windows-plan-provenance.ts +37 -19
- package/src/codex/codex-home-owner.ts +9 -8
- package/src/codex/convergence.ts +13 -3
- package/src/codex/coordinator-doctor.ts +14 -8
- package/src/codex/desktop-app/handoff.ts +1 -1
- package/src/codex/desktop-app-restart.ts +11 -1
- package/src/codex/exec-boundary.ts +26 -5
- package/src/codex/history-provider.ts +11 -10
- package/src/codex/inject/bounded-config-reader.ts +14 -13
- package/src/codex/main-account.ts +6 -6
- package/src/codex/native-main-lock-file.ts +13 -12
- package/src/codex/native-residue.ts +18 -14
- package/src/codex/orca-auth-source.ts +8 -7
- package/src/codex/quota-types.ts +5 -0
- package/src/codex/quota.ts +49 -7
- package/src/codex/role-auto-assign.ts +50 -26
- package/src/codex/role-capability.ts +160 -0
- package/src/codex/role-sizing.ts +24 -6
- package/src/codex/routing/cooldown-math.ts +3 -2
- package/src/codex/runtime.ts +43 -3
- package/src/codex/shim-fingerprint.ts +11 -9
- package/src/codex/shim-inspect.ts +3 -2
- package/src/codex/shim-restore-lock.ts +11 -14
- package/src/codex/shim-state-file.ts +22 -14
- package/src/codex/shim-wrapper-write.ts +7 -6
- package/src/codex/shim.ts +25 -2
- package/src/codex/transition-state.ts +5 -4
- package/src/combos/failover.ts +43 -4
- package/src/config/atomic-write.ts +38 -7
- package/src/config/diagnostics.ts +3 -0
- package/src/config/initialize.ts +6 -6
- package/src/config/load-degrade.ts +2 -0
- package/src/config/process-state.ts +23 -5
- package/src/config/salvage.ts +1 -0
- package/src/config/schema/config-schema.ts +29 -1
- package/src/config/schema/leaf-validators.ts +7 -0
- package/src/config/schema/workflow-budget.ts +43 -0
- package/src/config/tracked-runtime-inspection.ts +188 -0
- package/src/generated/compatibility-version.json +313 -213
- package/src/integrations/aside-profile-context.ts +1 -1
- package/src/integrations/droid-settings.ts +4 -4
- package/src/integrations/hermes-profiles.ts +3 -3
- package/src/lib/bounded-file-read.ts +3 -9
- package/src/lib/bun-runtime-preflight.ts +9 -8
- package/src/lib/file-identity.ts +15 -0
- package/src/lib/local-chat-completion.ts +8 -6
- package/src/lib/local-destinations.ts +32 -3
- package/src/lib/redact-folding.ts +9 -0
- package/src/lib/spend-pool-alias-validation.ts +6 -6
- package/src/lib/state-store-registrations.ts +2 -0
- package/src/lib/test-home-guard.ts +37 -9
- package/src/lib/windows-secret-acl.ts +47 -29
- package/src/lib/workflow-budget-config.ts +39 -0
- package/src/local-credentials/generation.ts +6 -2
- package/src/local-credentials/inventory.ts +132 -8
- package/src/messaging/remote-forward-failure.ts +35 -0
- package/src/messaging/remote-ports.ts +27 -5
- package/src/messaging/remote-process.ts +30 -4
- package/src/messaging/remote-tunnels.ts +80 -15
- package/src/oauth/antigravity-discovery-diagnostics.ts +65 -0
- package/src/oauth/google-antigravity.ts +23 -10
- package/src/oauth/index.ts +2 -0
- package/src/oauth/kiro-device-login.ts +87 -30
- package/src/oauth/kiro-iam-identity-center.ts +107 -0
- package/src/oauth/store.ts +9 -7
- package/src/providers/account-quota-disk.ts +18 -4
- package/src/providers/cc-switch-import-bytes.ts +991 -0
- package/src/providers/cc-switch-import-source.ts +1083 -0
- package/src/providers/cc-switch-import.ts +942 -0
- package/src/providers/derive.ts +6 -0
- package/src/providers/model-discovery-diagnostic.ts +4 -0
- package/src/providers/model-discovery.ts +4 -4
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/model-rename-migration.ts +41 -6
- package/src/providers/quota/report-cache.ts +17 -4
- package/src/providers/quota.ts +2 -2
- package/src/providers/reasoning-metadata.ts +31 -15
- package/src/providers/registry/entries-core.ts +1 -1
- package/src/providers/registry/entries-extended.ts +1 -1
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/model-seeds.ts +2 -1
- package/src/providers/registry/types.ts +3 -1
- package/src/providers/resolved-model-policy.ts +2 -2
- package/src/providers/routed-config.ts +2 -0
- package/src/providers/stale-model-roster-migration.ts +5 -1
- package/src/providers/xai-transport.ts +4 -4
- package/src/remote-control/workspace-codex-runtime.ts +2 -2
- package/src/remote-control/workspace-executor.ts +14 -13
- package/src/responses/custom-tool-compat.ts +2 -1
- package/src/responses/item-provenance.ts +79 -0
- package/src/responses/namespace-tool-compat.ts +21 -3
- package/src/router.ts +21 -2
- package/src/routing/analytics.ts +3 -5
- package/src/routing/fallback-policy.ts +7 -3
- package/src/routing/health.ts +5 -3
- package/src/routing/history/build-file.ts +6 -0
- package/src/routing/history/indexer.ts +158 -31
- package/src/routing/history/ingest.ts +1 -1
- package/src/routing/history/integrity.ts +208 -0
- package/src/routing/history/rebuild-job.ts +20 -6
- package/src/routing/history/rebuild-protocol.ts +2 -1
- package/src/routing/history/rebuild-worker.ts +18 -0
- package/src/routing/history/sqlite-errors.ts +9 -0
- package/src/server/admission-model-scope.ts +21 -4
- package/src/server/advisor-admission-scope.ts +29 -0
- package/src/server/auth-cors.ts +5 -2
- package/src/server/capture-admission-policy.ts +91 -0
- package/src/server/chat-completions.ts +33 -7
- package/src/server/claude-messages.ts +90 -2
- package/src/server/codex-model-list.ts +2 -1
- package/src/server/configured-credentials.ts +5 -0
- package/src/server/index/serve-options.ts +12 -2
- package/src/server/index/websocket-handler.ts +3 -0
- package/src/server/management/agent-settings-routes.ts +34 -9
- package/src/server/management/codex-agent-role-routes.ts +1 -0
- package/src/server/management/codex-role-auto-assign.ts +50 -6
- package/src/server/management/config-routes.ts +15 -4
- package/src/server/management/context.ts +3 -0
- package/src/server/management/native-integration-routes.ts +22 -0
- package/src/server/management/oauth-account-routes.ts +20 -4
- package/src/server/management/provider-overwrite-carry.ts +21 -0
- package/src/server/management/provider-routes.ts +3 -1
- package/src/server/management/route-registry.ts +2 -0
- package/src/server/management/shared.ts +17 -1
- package/src/server/management/workflow-budget-routes.ts +70 -3
- package/src/server/messages-native-eligibility.ts +6 -5
- package/src/server/messages-native-scope.ts +6 -1
- package/src/server/messages-shared.ts +57 -17
- package/src/server/persistent-gui-session.ts +4 -4
- package/src/server/request-log.ts +30 -2
- package/src/server/responses/adapter-delivery.ts +4 -0
- package/src/server/responses/advisor-plan-slot.ts +4 -0
- package/src/server/responses/advisor-slot.ts +73 -46
- package/src/server/responses/codex-auth-error.ts +5 -1
- package/src/server/responses/combo-required-tool-contract.ts +27 -0
- package/src/server/responses/compact.ts +4 -1
- package/src/server/responses/core-combo-failure.ts +2 -0
- package/src/server/responses/core-combo.ts +66 -5
- package/src/server/responses/core-lifetime.ts +4 -0
- package/src/server/responses/core-options.ts +9 -0
- package/src/server/responses/core.ts +2 -0
- package/src/server/responses/jev-model-invoke.ts +4 -2
- package/src/server/responses/passthrough-dispatch.ts +5 -4
- package/src/server/responses/policy-fallback.ts +2 -0
- package/src/server/responses/request-prepare.ts +4 -5
- package/src/server/responses/request-send-budget.ts +2 -1
- package/src/server/responses/request-sidecar-auth.ts +1 -0
- package/src/server/responses/request-transport.ts +2 -3
- package/src/server/responses/run-turn-execution.ts +4 -0
- package/src/server/responses/sidecar-execution.ts +21 -5
- package/src/server/responses-snapshot-repair.ts +18 -4
- package/src/server/responses-undeclared-tool-guard.ts +4 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/service/state-lock.ts +12 -11
- package/src/service-manager-probe.ts +53 -8
- package/src/types/admission-policy.ts +13 -0
- package/src/types/config.ts +25 -0
- package/src/types/provider.ts +10 -0
- package/src/types/request.ts +7 -0
- package/src/types.ts +1 -0
- package/src/update/job.ts +20 -0
- package/src/update/worker-launch.ts +71 -1
- package/src/usage/log.ts +25 -4
- package/src/vision/index.ts +2 -0
- package/src/vision/plan.ts +4 -0
- package/src/vision/routed-describe.ts +38 -23
- package/src/web-search/loop.ts +104 -9
- package/src/web-search/parse.ts +10 -2
- package/gui/dist/assets/App-DMps4OLk.css +0 -1
- package/gui/dist/assets/App-DmvwlhQq.js +0 -58
- package/gui/dist/assets/index-3EPO_KbX.js +0 -94
- package/gui/dist/assets/quota-summary-BHvWg9mi.js +0 -1
|
@@ -40,6 +40,121 @@ function assertParents(path: string): void {
|
|
|
40
40
|
if (p === parse(p).root) break;
|
|
41
41
|
}
|
|
42
42
|
}
|
|
43
|
+
/** Watch classification for one parent directory, per basenames seen there. */
|
|
44
|
+
export type WatchEntry = {
|
|
45
|
+
/**
|
|
46
|
+
* Basenames that are coverage targets themselves: a file whose bytes are scanned or a
|
|
47
|
+
* directory whose whole listing is checked. Every event on these is coverage-relevant
|
|
48
|
+
* -- an in-place content change reconciles exactly like a rename, even when the scan
|
|
49
|
+
* vector ends up identical, because the advance is what proves the observation ran.
|
|
50
|
+
*/
|
|
51
|
+
names: Set<string>;
|
|
52
|
+
/**
|
|
53
|
+
* Basenames watched only as ancestors of a deeper target, paired with the identity
|
|
54
|
+
* recorded at install. A "rename" always reconciles: a replacement is the signal these
|
|
55
|
+
* entries exist to catch. A "change" reconciles too unless the entry re-identifies as
|
|
56
|
+
* the same real directory -- on Windows a directory entry reports "change" whenever a
|
|
57
|
+
* child is added or removed, so this observer's own local-credentials.json save would
|
|
58
|
+
* otherwise re-arm the same reconcile forever. null means the ancestor could not be
|
|
59
|
+
* identified at install, and an unverifiable ancestor reconciles on any event.
|
|
60
|
+
*/
|
|
61
|
+
ancestors: Map<string, { dev: bigint; ino: bigint } | null>;
|
|
62
|
+
/**
|
|
63
|
+
* Identity of each target name at install (watchEntryIdentity). An unmatched 8.3 short
|
|
64
|
+
* name is resolved against these: it reconciles when a target here changed or when the
|
|
65
|
+
* alias is a target. Absent means the entry is treated as unresolvable and reconciles.
|
|
66
|
+
*/
|
|
67
|
+
targetIdentities?: Map<string, string>;
|
|
68
|
+
};
|
|
69
|
+
const CREDENTIAL_TMP_NAME = /^(auth|config|codex-accounts)\.json\.ocx\./i;
|
|
70
|
+
/**
|
|
71
|
+
* Watcher names are compared the way a case-insensitive volume resolves them. Windows and
|
|
72
|
+
* default macOS volumes report a notification under the spelling the writer used, so a
|
|
73
|
+
* credential created as AUTH.JSON reaches the watcher under that name while the scan reads
|
|
74
|
+
* it as auth.json. Folding can only add reconciles on a case-sensitive volume, never drop one.
|
|
75
|
+
*/
|
|
76
|
+
function foldWatchName(name: string): string {
|
|
77
|
+
return name.toLowerCase().replace(/[. ]+$/, "");
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* An 8.3 short name (AUTH~1.JSO, OPENC~1) cannot be mapped back to its long name by
|
|
81
|
+
* spelling; it is resolved by identity instead (see shortNameAction).
|
|
82
|
+
*/
|
|
83
|
+
const SHORT_NAME_ALIAS = /~\d/;
|
|
84
|
+
/** "<dev>:<ino>", "absent", or "unreadable" for one entry of a watched parent. */
|
|
85
|
+
export function watchEntryIdentity(parent: string, child: string): string {
|
|
86
|
+
try {
|
|
87
|
+
const stat = lstatSync(join(parent, child), { bigint: true });
|
|
88
|
+
return `${stat.dev}:${stat.ino}`;
|
|
89
|
+
} catch (error) {
|
|
90
|
+
return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable";
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Windows may report either name of an entry that has both, and a removed entry's short
|
|
95
|
+
* name can no longer be looked up. Such an event is coverage-relevant when a target or
|
|
96
|
+
* ancestor in this parent no longer has its install identity, or when the alias resolves to
|
|
97
|
+
* a target; a change that resolves to a tracked ancestor is that ancestor's tick. Anything
|
|
98
|
+
* else -- this observer's own metadata save under a short spelling -- changed no target.
|
|
99
|
+
*/
|
|
100
|
+
function shortNameAction(parent: string, entry: WatchEntry, event: string, name: string): WatchEventAction {
|
|
101
|
+
const recorded = entry.targetIdentities;
|
|
102
|
+
if (!recorded) return "reconcile";
|
|
103
|
+
const resolved = watchEntryIdentity(parent, name);
|
|
104
|
+
if (resolved === "unreadable") return "reconcile";
|
|
105
|
+
for (const [target, identity] of recorded) {
|
|
106
|
+
const now = watchEntryIdentity(parent, target);
|
|
107
|
+
if (now === "unreadable" || now !== identity) return "reconcile";
|
|
108
|
+
if (resolved !== "absent" && resolved === now) return "reconcile";
|
|
109
|
+
}
|
|
110
|
+
let aliasOfAncestor = false;
|
|
111
|
+
for (const [ancestorName, identity] of entry.ancestors) {
|
|
112
|
+
const now = ancestorIdentity(parent, ancestorName);
|
|
113
|
+
if (identity === null || now === null || now.dev !== identity.dev || now.ino !== identity.ino) return "reconcile";
|
|
114
|
+
if (resolved === `${identity.dev}:${identity.ino}`) aliasOfAncestor = true;
|
|
115
|
+
}
|
|
116
|
+
return aliasOfAncestor && event !== "change" ? "reconcile" : "ignore";
|
|
117
|
+
}
|
|
118
|
+
function foldedLookup<T>(keys: Iterable<T>, key: (item: T) => string, folded: string): T | undefined {
|
|
119
|
+
for (const item of keys) if (foldWatchName(key(item)) === folded) return item;
|
|
120
|
+
return undefined;
|
|
121
|
+
}
|
|
122
|
+
function ancestorIdentity(parent: string, child: string): { dev: bigint; ino: bigint } | null {
|
|
123
|
+
try {
|
|
124
|
+
const stat = lstatSync(join(parent, child), { bigint: true });
|
|
125
|
+
return stat.isDirectory() && !stat.isSymbolicLink() ? { dev: stat.dev, ino: stat.ino } : null;
|
|
126
|
+
} catch { return null; }
|
|
127
|
+
}
|
|
128
|
+
type WatchEventAction = "fail" | "reconcile" | "ignore";
|
|
129
|
+
/**
|
|
130
|
+
* The single (parent, event, name) decision behind the observation watchers, exported so
|
|
131
|
+
* tests can pin every branch without timing-dependent filesystem notifications.
|
|
132
|
+
*/
|
|
133
|
+
export function credentialWatchEventAction(
|
|
134
|
+
parent: string, entry: WatchEntry, event: string, name: string | null,
|
|
135
|
+
): WatchEventAction {
|
|
136
|
+
if (name === null) return "fail";
|
|
137
|
+
const folded = foldWatchName(name);
|
|
138
|
+
if (foldedLookup(entry.names, n => n, folded) !== undefined) return "reconcile";
|
|
139
|
+
const match = foldedLookup(entry.ancestors.entries(), ([n]) => n, folded);
|
|
140
|
+
// A known ancestor whose real name merely looks like write residue or a short name
|
|
141
|
+
// (C:\config.json.ocx.home, C:\ocx~1) goes through the identity check below.
|
|
142
|
+
if (match === undefined) {
|
|
143
|
+
if (CREDENTIAL_TMP_NAME.test(name)) return "reconcile";
|
|
144
|
+
return SHORT_NAME_ALIAS.test(name) ? shortNameAction(parent, entry, event, name) : "ignore";
|
|
145
|
+
}
|
|
146
|
+
const ancestor = match[1];
|
|
147
|
+
// Renames (create/delete/move, including a same-identity rename) are structural and
|
|
148
|
+
// always reconcile; only "change" may be child-list noise from a same-identity dir.
|
|
149
|
+
if (event !== "change" || ancestor === null) return "reconcile";
|
|
150
|
+
try {
|
|
151
|
+
const stat = lstatSync(join(parent, name), { bigint: true });
|
|
152
|
+
if (stat.isDirectory() && !stat.isSymbolicLink() && stat.dev === ancestor.dev && stat.ino === ancestor.ino) {
|
|
153
|
+
return "ignore";
|
|
154
|
+
}
|
|
155
|
+
} catch { /* an ancestor that cannot be re-identified cannot prove the tick is noise */ }
|
|
156
|
+
return "reconcile";
|
|
157
|
+
}
|
|
43
158
|
export function scanLocalCredentials(accounts: readonly string[] = []): { count: number; vector: string; targets: string[] } {
|
|
44
159
|
const home = getConfigDir();
|
|
45
160
|
const codex = getCodexHome();
|
|
@@ -166,6 +281,10 @@ export function scanLocalCredentials(accounts: readonly string[] = []): { count:
|
|
|
166
281
|
const profiles = countLocalNativeProfileSlots(vault, homeId);
|
|
167
282
|
if (profiles.active && !main) throw new Error("Active native profile has no readable auth");
|
|
168
283
|
count += main + profiles.inactive;
|
|
284
|
+
// The whole listing is verified below, so the directory itself is a coverage target:
|
|
285
|
+
// an unknown create/delete must reach a watcher even when the child's own name is not.
|
|
286
|
+
targets.add(shared);
|
|
287
|
+
assertParents(shared);
|
|
169
288
|
if (exists(shared)) {
|
|
170
289
|
if (!lstatSync(shared).isDirectory() || lstatSync(shared).isSymbolicLink()) throw new Error("Unsafe native vault");
|
|
171
290
|
const expected = new Set([`${homeId}.vault.json`, `${homeId}.stages.json`]);
|
|
@@ -223,23 +342,28 @@ export function startLocalCredentialObservation(): { stop(): void; reconcile():
|
|
|
223
342
|
}
|
|
224
343
|
};
|
|
225
344
|
const install = (targets: string[]) => {
|
|
226
|
-
const watched = new Map<string,
|
|
345
|
+
const watched = new Map<string, WatchEntry>();
|
|
227
346
|
for (const target of targets) {
|
|
347
|
+
let leaf = true;
|
|
228
348
|
for (let path = target; dirname(path) !== path; path = dirname(path)) {
|
|
229
349
|
const parent = dirname(path);
|
|
230
350
|
if (!exists(parent)) continue;
|
|
231
351
|
assertParents(path);
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
352
|
+
const entry = watched.get(parent) ?? { names: new Set<string>(), ancestors: new Map(), targetIdentities: new Map<string, string>() };
|
|
353
|
+
const child = path.slice(parent.length + (parent.endsWith("/") || parent.endsWith("\\") ? 0 : 1));
|
|
354
|
+
if (leaf) { entry.names.add(child); entry.targetIdentities?.set(child, watchEntryIdentity(parent, child)); }
|
|
355
|
+
else if (!entry.ancestors.has(child)) entry.ancestors.set(child, ancestorIdentity(parent, child));
|
|
356
|
+
watched.set(parent, entry);
|
|
357
|
+
leaf = false;
|
|
235
358
|
}
|
|
236
359
|
}
|
|
237
360
|
const next: FSWatcher[] = [];
|
|
238
361
|
try {
|
|
239
|
-
for (const [parent,
|
|
240
|
-
const watcher = watch(parent, { persistent: false }, (
|
|
241
|
-
|
|
242
|
-
if (
|
|
362
|
+
for (const [parent, entry] of watched) {
|
|
363
|
+
const watcher = watch(parent, { persistent: false }, (event, name) => {
|
|
364
|
+
const action = credentialWatchEventAction(parent, entry, event, name === null ? null : String(name));
|
|
365
|
+
if (action === "fail") fail();
|
|
366
|
+
else if (action === "reconcile") reconcile();
|
|
243
367
|
});
|
|
244
368
|
watcher.on("error", fail);
|
|
245
369
|
next.push(watcher);
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/** Match fixed SSH bind-failure tokens without retaining any diagnostic bytes. */
|
|
2
|
+
export function remoteForwardFailure(argv: readonly string[], onReady: () => void) {
|
|
3
|
+
const direction = argv.includes("-L") ? "L" : "R";
|
|
4
|
+
const index = argv.indexOf(`-${direction}`), port = argv[index + 1]?.split(":")[1];
|
|
5
|
+
const enabled = index >= 0 && argv.includes("ExitOnForwardFailure=yes") && /^\d+$/.test(port ?? "");
|
|
6
|
+
const failures = !enabled ? []
|
|
7
|
+
: direction === "L" ? ["Could not request local forwarding."]
|
|
8
|
+
: [`remote port forwarding failed for listen port ${port}\r`, `remote port forwarding failed for listen port ${port}\n`];
|
|
9
|
+
const target = argv[index + 1]?.split(":").slice(2).join(":");
|
|
10
|
+
// OpenSSH emits the local-listening announcement BEFORE bind(), so it is not a success receipt.
|
|
11
|
+
const success = direction === "L" ? "debug1: Entering interactive session."
|
|
12
|
+
: `debug1: remote forward success for: listen 127.0.0.1:${port}, connect ${target}`;
|
|
13
|
+
const successes = !enabled ? [] : [`${success}\r`, `${success}\n`];
|
|
14
|
+
const matches = [...failures, ...successes].map((token, index) => {
|
|
15
|
+
const bytes = new TextEncoder().encode(token), prefixes = new Uint32Array(bytes.length);
|
|
16
|
+
for (let i = 1, length = 0; i < bytes.length; i++) {
|
|
17
|
+
while (length && bytes[i] !== bytes[length]) length = prefixes[length - 1]!;
|
|
18
|
+
if (bytes[i] === bytes[length]) length++;
|
|
19
|
+
prefixes[i] = length;
|
|
20
|
+
}
|
|
21
|
+
return { bytes, prefixes, length: 0, success: index >= failures.length };
|
|
22
|
+
});
|
|
23
|
+
let failed = false, ready = false;
|
|
24
|
+
return { enabled, get failed() { return failed; }, get ready() { return ready; }, write(chunk: Uint8Array) {
|
|
25
|
+
if (!enabled || failed || ready) return;
|
|
26
|
+
for (const byte of chunk) for (const match of matches) {
|
|
27
|
+
while (match.length && byte !== match.bytes[match.length]) match.length = match.prefixes[match.length - 1]!;
|
|
28
|
+
if (byte === match.bytes[match.length]) match.length++;
|
|
29
|
+
if (match.length === match.bytes.length) {
|
|
30
|
+
if (match.success) { ready = true; onReady(); } else failed = true;
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
} };
|
|
35
|
+
}
|
|
@@ -8,12 +8,34 @@ type RemoteProcFile = {
|
|
|
8
8
|
close(): Promise<void>;
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
export type RemotePortAllocator = () => { port: number; stop(force?: boolean): void };
|
|
12
|
+
export interface RemotePortReservation { port: number; handoff(): void; release(): void }
|
|
13
|
+
const pendingPorts = new Set<number>();
|
|
14
|
+
const PORT_ALLOCATION_ATTEMPTS = 8;
|
|
15
|
+
const allocateRemotePort: RemotePortAllocator = () => Bun.listen({ hostname: "127.0.0.1", port: 0,
|
|
16
|
+
exclusive: true, socket: { data(socket) { socket.end(); } } });
|
|
17
|
+
|
|
18
|
+
/** Hold the socket until handoff, and the process-local claim until the owned attempt closes. */
|
|
19
|
+
export function reserveRemotePort(allocate = allocateRemotePort, excluded: ReadonlySet<number> = new Set()): RemotePortReservation {
|
|
20
|
+
for (let attempt = 0; attempt < PORT_ALLOCATION_ATTEMPTS; attempt++) {
|
|
21
|
+
const listener = allocate(), port = listener.port;
|
|
22
|
+
if (!validPort(port)) { listener.stop(true); throw remoteError("invalid_port", "Cannot allocate an unprivileged messaging port candidate."); }
|
|
23
|
+
if (pendingPorts.has(port) || excluded.has(port)) { listener.stop(true); continue; }
|
|
24
|
+
pendingPorts.add(port);
|
|
25
|
+
let held = true, released = false;
|
|
26
|
+
const handoff = () => { if (held) { held = false; listener.stop(true); } };
|
|
27
|
+
return { port, handoff, release() {
|
|
28
|
+
if (released) return;
|
|
29
|
+
released = true; handoff(); pendingPorts.delete(port);
|
|
30
|
+
} };
|
|
31
|
+
}
|
|
32
|
+
throw remoteError("forward_port_lost", "Cannot allocate a distinct messaging forward port.");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** A remote stdio helper cannot transfer its socket to sshd; the initiating owner checks SSH failure. */
|
|
12
36
|
export function remotePortCandidate(): number {
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
if (!validPort(port)) throw remoteError("invalid_port", "Cannot allocate an unprivileged messaging port candidate.");
|
|
16
|
-
return port;
|
|
37
|
+
const reservation = reserveRemotePort();
|
|
38
|
+
try { return reservation.port; } finally { reservation.release(); }
|
|
17
39
|
}
|
|
18
40
|
/** Refuse GatewayPorts/public binds; neither port existence nor this scan proves endpoint identity. */
|
|
19
41
|
export async function remotePortIsLoopback(port: number, budget: MessageBudget, capacity: RemoteCapacity,
|
|
@@ -2,9 +2,14 @@ import { linkSshSpawnEnv } from "../link/ssh-runner";
|
|
|
2
2
|
import { MessageBudget } from "./budget";
|
|
3
3
|
import { RemoteCapacity, remoteError, REMOTE_LIMITS } from "./remote-contract";
|
|
4
4
|
import { LocalMessagingError } from "./types";
|
|
5
|
+
import { remoteForwardFailure } from "./remote-forward-failure";
|
|
5
6
|
|
|
6
7
|
export interface RemoteHelper {
|
|
7
8
|
readonly pid: number; readonly exited: Promise<number>; readonly output: Promise<string>;
|
|
9
|
+
readonly forwardReady: Promise<void>;
|
|
10
|
+
readonly forwardFailed?: boolean;
|
|
11
|
+
/** After cleanup: intrinsic I/O or pre-cleanup exit failure, excluding cleanup-induced exits. */
|
|
12
|
+
readonly setupFailure?: Error;
|
|
8
13
|
close(): Promise<void>;
|
|
9
14
|
}
|
|
10
15
|
/** Narrow subprocess seam for offline lifecycle tests; production always uses owned Bun children. */
|
|
@@ -24,13 +29,21 @@ export function spawnRemoteHelper(argv: readonly string[], capacity: RemoteCapac
|
|
|
24
29
|
stdin?: string, env = linkSshSpawnEnv(), options: RemoteHelperOptions = {}): RemoteHelper {
|
|
25
30
|
if (signal?.aborted) throw remoteError("cancelled", "Messaging helper was cancelled before spawn.");
|
|
26
31
|
const release = capacity.reserveHelper(options.purpose ?? "persistent");
|
|
32
|
+
let ready!: () => void, notReady!: (reason: unknown) => void;
|
|
33
|
+
const forwardReady = new Promise<void>((resolve, reject) => { ready = resolve; notReady = reject; });
|
|
34
|
+
void forwardReady.catch(() => {});
|
|
35
|
+
const forwardFailure = remoteForwardFailure(argv, ready);
|
|
36
|
+
if (!forwardFailure.enabled) ready();
|
|
37
|
+
// Command-line options are first-value-wins; only owned forwards request bounded token inspection.
|
|
38
|
+
const spawnArgv = forwardFailure.enabled ? [argv[0]!, "-o", "LogLevel=DEBUG1", ...argv.slice(1)] : [...argv];
|
|
27
39
|
let child: RemoteHelperProcess;
|
|
28
|
-
try { child = options.spawn ? options.spawn(
|
|
29
|
-
: Bun.spawn(
|
|
40
|
+
try { child = options.spawn ? options.spawn(spawnArgv, env)
|
|
41
|
+
: Bun.spawn(spawnArgv, { stdin: "pipe", stdout: "pipe", stderr: "pipe", detached: true, env }); }
|
|
30
42
|
catch { release(); throw remoteError("ssh_unavailable", "The messaging SSH helper could not start."); }
|
|
31
43
|
const readers = [child.stdout.getReader(), child.stderr.getReader()];
|
|
32
44
|
let closing: Promise<void> | undefined;
|
|
33
45
|
let failure: Error | undefined;
|
|
46
|
+
let interrupted = false;
|
|
34
47
|
const cancelledPipes = [false, false];
|
|
35
48
|
const pipeEnds: (() => void)[] = [];
|
|
36
49
|
const naturalPipes = readers.map(() => new Promise<void>(resolve => { pipeEnds.push(resolve); }));
|
|
@@ -45,6 +58,7 @@ export function spawnRemoteHelper(argv: readonly string[], capacity: RemoteCapac
|
|
|
45
58
|
};
|
|
46
59
|
const close = (): Promise<void> => closing ??= (async () => {
|
|
47
60
|
signal?.removeEventListener("abort", abort);
|
|
61
|
+
interrupted = child.exitCode === null;
|
|
48
62
|
signalGroup("SIGTERM");
|
|
49
63
|
const force = setTimeout(() => signalGroup("SIGKILL"), 500);
|
|
50
64
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -65,6 +79,7 @@ export function spawnRemoteHelper(argv: readonly string[], capacity: RemoteCapac
|
|
|
65
79
|
cancelledPipes[index] = true; void reader.cancel().catch(() => {});
|
|
66
80
|
}
|
|
67
81
|
stopOutput(cleanupFailure ?? failure ?? remoteError("ssh_incomplete", "Messaging helper output capture was stopped."));
|
|
82
|
+
notReady(cleanupFailure ?? failure ?? remoteError(child.exitCode !== null && child.exitCode !== 0 && forwardFailure.failed ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward was not confirmed."));
|
|
68
83
|
// Cancellation cannot prove natural EOF; unresolved ownership keeps its helper capacity charged.
|
|
69
84
|
}
|
|
70
85
|
})();
|
|
@@ -78,7 +93,8 @@ export function spawnRemoteHelper(argv: readonly string[], capacity: RemoteCapac
|
|
|
78
93
|
for (;;) {
|
|
79
94
|
const next = await readers[index]!.read();
|
|
80
95
|
if (next.done) { if (!cancelledPipes[index]) pipeEnds[index]!(); break; }
|
|
81
|
-
if (index === 1
|
|
96
|
+
if (index === 1) { forwardFailure.write(next.value); continue; } // No diagnostic bytes are retained or returned.
|
|
97
|
+
if (discarding) continue;
|
|
82
98
|
try {
|
|
83
99
|
bytes += next.value.byteLength;
|
|
84
100
|
if (bytes > 64 * 1024) throw remoteError("ssh_output_limit", "Messaging helper output exceeded its limit.");
|
|
@@ -107,8 +123,18 @@ export function spawnRemoteHelper(argv: readonly string[], capacity: RemoteCapac
|
|
|
107
123
|
if (failure) throw failure; return out;
|
|
108
124
|
})]);
|
|
109
125
|
void output.catch(() => {});
|
|
126
|
+
void output.then(async () => {
|
|
127
|
+
const code = await child.exited;
|
|
128
|
+
if (!forwardFailure.ready) notReady(remoteError(code !== 0 && forwardFailure.failed ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward was not confirmed."));
|
|
129
|
+
}, notReady).catch(notReady);
|
|
110
130
|
void child.exited.then(() => { signal?.removeEventListener("abort", abort); }).catch(() => {});
|
|
111
|
-
return { pid: child.pid, exited: child.exited, output,
|
|
131
|
+
return { pid: child.pid, exited: child.exited, output, forwardReady, get forwardFailed() { return forwardFailure.failed; },
|
|
132
|
+
get setupFailure() {
|
|
133
|
+
if (failure) return failure;
|
|
134
|
+
if (!interrupted && child.exitCode !== null && (child.exitCode !== 0 || !forwardFailure.ready)) {
|
|
135
|
+
return remoteError(child.exitCode !== 0 && forwardFailure.failed ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward setup failed.");
|
|
136
|
+
}
|
|
137
|
+
}, close };
|
|
112
138
|
}
|
|
113
139
|
|
|
114
140
|
/** One bounded batch covers helper startup, stdin, exit and output; errors never include raw output. */
|
|
@@ -3,7 +3,7 @@ import { buildExecArgv, buildTunnelArgv, remoteOcxArgv } from "../link/ssh-argv"
|
|
|
3
3
|
import { MessageBudget } from "./budget";
|
|
4
4
|
import { exactRecord, RemoteCapacity, remoteError, validPort, type RemotePeer } from "./remote-contract";
|
|
5
5
|
import { withRemoteLock, writeRemoteFile } from "./remote-files";
|
|
6
|
-
import {
|
|
6
|
+
import { reserveRemotePort, remotePortIsLoopback, type RemotePortAllocator, type RemotePortReservation } from "./remote-ports";
|
|
7
7
|
import { runRemoteHelper, spawnRemoteHelper, type RemoteHelper } from "./remote-process";
|
|
8
8
|
import type { RemoteMessageStore } from "./remote-store";
|
|
9
9
|
|
|
@@ -14,6 +14,8 @@ export interface RemoteTunnelPair {
|
|
|
14
14
|
export interface RemoteTunnelDeps {
|
|
15
15
|
run?: typeof runRemoteHelper;
|
|
16
16
|
spawn?: typeof spawnRemoteHelper;
|
|
17
|
+
allocatePort?: RemotePortAllocator;
|
|
18
|
+
inspect?: typeof remotePortIsLoopback;
|
|
17
19
|
}
|
|
18
20
|
/** Own one -L/-R pair with shared SSH policy and one setup deadline; never adopt/kill existing tunnels. */
|
|
19
21
|
export async function startRemoteTunnels(store: RemoteMessageStore, peer: RemotePeer, budget: MessageBudget,
|
|
@@ -21,35 +23,92 @@ export async function startRemoteTunnels(store: RemoteMessageStore, peer: Remote
|
|
|
21
23
|
if (!peer.ssh || !peer.hostKey) throw remoteError("return_route_only", "This peer has no initiating SSH enrollment; wait for its return route.");
|
|
22
24
|
const knownHosts = join(store.directory, `${peer.machine.id}.known_hosts`);
|
|
23
25
|
withRemoteLock(store.directory, () => writeRemoteFile(knownHosts, peer.hostKey!));
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
return startRemoteForwardPair({ ssh: peer.ssh, knownHosts, peerPort: peer.port, ownerPort: store.requireEnabled().port },
|
|
27
|
+
budget, capacity, ownerSignal, deps);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface RemoteForwardOptions { ssh: string; knownHosts: string; peerPort: number; ownerPort: number }
|
|
31
|
+
const FORWARD_SETUP_ATTEMPTS = 3;
|
|
32
|
+
|
|
33
|
+
/** Transport-only setup: no messages or authenticated-ready state are published here. */
|
|
34
|
+
export async function startRemoteForwardPair(options: RemoteForwardOptions, budget: MessageBudget,
|
|
35
|
+
capacity: RemoteCapacity, ownerSignal: AbortSignal, deps: RemoteTunnelDeps = {}): Promise<RemoteTunnelPair> {
|
|
36
|
+
const localPorts = new Set<number>(), returnPorts = new Set<number>();
|
|
37
|
+
for (let attempt = 0; attempt < FORWARD_SETUP_ATTEMPTS; attempt++) {
|
|
38
|
+
budget.throwIfEnded();
|
|
39
|
+
if (ownerSignal.aborted) throw remoteError("cancelled", "Messaging tunnel setup was cancelled.");
|
|
40
|
+
const result = exactRecord(JSON.parse(await (deps.run ?? runRemoteHelper)(buildExecArgv({ alias: options.ssh,
|
|
41
|
+
knownHostsFile: options.knownHosts, argv: remoteOcxArgv(["message", "_port"]) }), budget, capacity)), ["port"]);
|
|
42
|
+
budget.throwIfEnded();
|
|
43
|
+
if (!validPort(result.port)) throw remoteError("remote_incompatible", "Remote node did not offer an unprivileged return port.");
|
|
44
|
+
if (returnPorts.has(result.port)) continue;
|
|
45
|
+
returnPorts.add(result.port);
|
|
46
|
+
const reservation = reserveRemotePort(deps.allocatePort, localPorts);
|
|
47
|
+
localPorts.add(reservation.port);
|
|
48
|
+
try { return await startAttempt(options, reservation, result.port, budget, capacity, ownerSignal, deps); }
|
|
49
|
+
catch (error) { if ((error as { code?: string })?.code !== "forward_port_lost") throw error; }
|
|
50
|
+
}
|
|
51
|
+
throw remoteError("forward_port_lost", "Messaging SSH forward ports were lost during bounded setup.");
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function startAttempt(options: RemoteForwardOptions, reservation: RemotePortReservation, returnPort: number,
|
|
55
|
+
budget: MessageBudget, capacity: RemoteCapacity, ownerSignal: AbortSignal, deps: RemoteTunnelDeps): Promise<RemoteTunnelPair> {
|
|
56
|
+
const localPort = reservation.port, helpers: RemoteHelper[] = [], exits: Promise<void>[] = [];
|
|
57
|
+
let lostPort = false;
|
|
58
|
+
let awaitingReceipts = false;
|
|
59
|
+
const setupFailure = (fallback: unknown) => {
|
|
60
|
+
const failures = helpers.flatMap(helper => helper.setupFailure ? [helper.setupFailure] : []);
|
|
61
|
+
return failures.find(error => (error as { code?: string }).code !== "forward_port_lost") ?? failures[0] ?? fallback;
|
|
62
|
+
};
|
|
63
|
+
let cancelReadiness!: (reason: unknown) => void;
|
|
64
|
+
const cancelled = new Promise<never>((_, reject) => { cancelReadiness = reject; });
|
|
65
|
+
void cancelled.catch(() => {});
|
|
28
66
|
let alive = true, closing: Promise<void> | undefined;
|
|
29
67
|
const close = (): Promise<void> => closing ??= (async () => {
|
|
30
68
|
alive = false; ownerSignal.removeEventListener("abort", abort);
|
|
31
69
|
const results = await Promise.allSettled(helpers.map(helper => helper.close()));
|
|
70
|
+
await Promise.allSettled(helpers.map(helper => helper.output));
|
|
71
|
+
reservation.release();
|
|
32
72
|
const failure = results.find(result => result.status === "rejected");
|
|
33
73
|
if (failure?.status === "rejected") throw failure.reason;
|
|
34
74
|
})();
|
|
35
|
-
const abort = () => {
|
|
75
|
+
const abort = () => {
|
|
76
|
+
cancelReadiness(remoteError("cancelled", "Messaging tunnel setup was cancelled."));
|
|
77
|
+
void close().catch(() => {});
|
|
78
|
+
};
|
|
36
79
|
ownerSignal.addEventListener("abort", abort, { once: true });
|
|
37
|
-
const cancelSetup = () => { void close().catch(() => {}); };
|
|
80
|
+
const cancelSetup = () => { cancelReadiness(budget.signal.reason); void close().catch(() => {}); };
|
|
38
81
|
budget.signal.addEventListener("abort", cancelSetup, { once: true });
|
|
39
82
|
try {
|
|
40
|
-
budget.throwIfEnded(); if (ownerSignal.aborted) throw
|
|
41
|
-
for (const [direction, bindPort, targetPort] of [["L", localPort,
|
|
83
|
+
budget.throwIfEnded(); if (ownerSignal.aborted) throw remoteError("cancelled", "Messaging tunnel setup was cancelled.");
|
|
84
|
+
for (const [direction, bindPort, targetPort] of [["L", localPort, options.peerPort], ["R", returnPort, options.ownerPort]] as const) {
|
|
42
85
|
budget.throwIfEnded();
|
|
43
|
-
const
|
|
44
|
-
|
|
86
|
+
const argv = buildTunnelArgv({ alias: options.ssh, knownHostsFile: options.knownHosts, direction, bindPort, targetPort });
|
|
87
|
+
if (direction === "L") reservation.handoff();
|
|
88
|
+
const helper = (deps.spawn ?? spawnRemoteHelper)(argv, capacity, ownerSignal);
|
|
45
89
|
helpers.push(helper);
|
|
46
|
-
|
|
90
|
+
const exit = helper.exited.then(async code => {
|
|
91
|
+
await close();
|
|
92
|
+
await helper.output.catch(() => {});
|
|
93
|
+
if (code !== 0 && helper.forwardFailed) lostPort = true;
|
|
94
|
+
});
|
|
95
|
+
exits.push(exit); void exit.catch(() => {});
|
|
47
96
|
}
|
|
97
|
+
// A competing loopback listener can exist before SSH even starts. Its socket is not a bind receipt.
|
|
98
|
+
awaitingReceipts = true;
|
|
99
|
+
await Promise.race([Promise.all(helpers.map(helper => helper.forwardReady)), cancelled]);
|
|
100
|
+
awaitingReceipts = false;
|
|
101
|
+
const checkAlive = async () => {
|
|
102
|
+
if (alive) return;
|
|
103
|
+
await Promise.all(exits);
|
|
104
|
+
throw setupFailure(remoteError(lostPort ? "forward_port_lost" : "ssh_failed", "Messaging SSH forward setup failed."));
|
|
105
|
+
};
|
|
48
106
|
let ready = false;
|
|
49
107
|
while (!ready) {
|
|
50
108
|
budget.throwIfEnded();
|
|
51
|
-
|
|
52
|
-
ready = await remotePortIsLoopback(localPort, budget, capacity);
|
|
109
|
+
await checkAlive();
|
|
110
|
+
ready = await (deps.inspect ?? remotePortIsLoopback)(localPort, budget, capacity);
|
|
111
|
+
await checkAlive();
|
|
53
112
|
if (!ready) await new Promise<void>((resolve, reject) => {
|
|
54
113
|
const timer = setTimeout(() => { budget.signal.removeEventListener("abort", cancel); resolve(); }, budget.remainingMs(100));
|
|
55
114
|
const cancel = () => { clearTimeout(timer); budget.signal.removeEventListener("abort", cancel); reject(budget.signal.reason); };
|
|
@@ -57,9 +116,15 @@ export async function startRemoteTunnels(store: RemoteMessageStore, peer: Remote
|
|
|
57
116
|
if (budget.signal.aborted) cancel();
|
|
58
117
|
});
|
|
59
118
|
}
|
|
119
|
+
budget.throwIfEnded(); if (ownerSignal.aborted) throw remoteError("cancelled", "Messaging tunnel setup was cancelled.");
|
|
60
120
|
const exited = Promise.race(helpers.map(helper => helper.exited));
|
|
61
121
|
void exited.then(() => close()).catch(() => {});
|
|
62
122
|
return { localPort, returnPort, get alive() { return alive; }, exited, close };
|
|
63
|
-
} catch (error) {
|
|
123
|
+
} catch (error) {
|
|
124
|
+
await close(); budget.throwIfEnded();
|
|
125
|
+
if (ownerSignal.aborted) throw remoteError("cancelled", "Messaging tunnel setup was cancelled.");
|
|
126
|
+
// Sibling shutdown can reject first; classify only after every helper's diagnostics and cleanup settle.
|
|
127
|
+
throw awaitingReceipts ? setupFailure(error) : error;
|
|
128
|
+
}
|
|
64
129
|
finally { budget.signal.removeEventListener("abort", cancelSetup); }
|
|
65
130
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Content-free discovery observations. Never enumerate upstream keys or serialize its objects. */
|
|
2
|
+
function projectValueType(value: unknown): string {
|
|
3
|
+
if (value === undefined) return "absent";
|
|
4
|
+
if (typeof value === "string") return "string";
|
|
5
|
+
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
6
|
+
return typeof (value as { id?: unknown }).id === "string" ? "object-with-id" : "object-without-id";
|
|
7
|
+
}
|
|
8
|
+
return "other";
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function projectTypes(data: unknown): Record<string, string> {
|
|
12
|
+
const object = data && typeof data === "object" && !Array.isArray(data)
|
|
13
|
+
? data as Record<string, unknown> : undefined;
|
|
14
|
+
return {
|
|
15
|
+
cloudaicompanionProject: projectValueType(object?.cloudaicompanionProject),
|
|
16
|
+
projectId: projectValueType(object?.projectId),
|
|
17
|
+
project: projectValueType(object?.project),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Published only when the existing parser did not discover a project; never used for admission.
|
|
22
|
+
* `undefined` means JSON was unparseable or, for HTTP refusals, deliberately not inspected.
|
|
23
|
+
*/
|
|
24
|
+
export function summarizeAntigravityDiscovery(
|
|
25
|
+
stage: "loadCodeAssist" | "onboardUser",
|
|
26
|
+
status: number,
|
|
27
|
+
data: unknown,
|
|
28
|
+
): string {
|
|
29
|
+
const root = data === undefined ? "unparseable" : Array.isArray(data) ? "array"
|
|
30
|
+
: data && typeof data === "object" ? "object" : "other";
|
|
31
|
+
const object = root === "object" ? data as Record<string, unknown> : undefined;
|
|
32
|
+
const done = object?.done === undefined ? "absent" : object.done === true ? "true"
|
|
33
|
+
: object.done === false ? "false" : "other";
|
|
34
|
+
const error = object && Object.hasOwn(object, "error") ? "present" : "absent";
|
|
35
|
+
const outcome = status < 200 || status >= 300 ? "http-refusal"
|
|
36
|
+
: root === "unparseable" ? "unparseable" : root !== "object" ? "invalid-root"
|
|
37
|
+
: stage === "loadCodeAssist" ? "no-project"
|
|
38
|
+
: done !== "true" ? "pending" : error === "present" ? "done-with-error" : "done-without-project";
|
|
39
|
+
return JSON.stringify({
|
|
40
|
+
stage, status, root, outcome, done, error,
|
|
41
|
+
projects: projectTypes(object),
|
|
42
|
+
response: projectTypes(object?.response),
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const DISCOVERY_FAILURE_MESSAGE = "Antigravity login could not discover a Cloud Code Assist project for this account. Ensure the account has Antigravity/Cloud Code Assist access and try again.";
|
|
47
|
+
|
|
48
|
+
/** Only sanitizer outputs can enter this error's public message; raw responses are never retained. */
|
|
49
|
+
export class AntigravityProjectDiscoveryError extends Error {
|
|
50
|
+
#summaries: string[] = [];
|
|
51
|
+
|
|
52
|
+
constructor() {
|
|
53
|
+
super(DISCOVERY_FAILURE_MESSAGE);
|
|
54
|
+
this.name = "AntigravityProjectDiscoveryError";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
observe(stage: "loadCodeAssist" | "onboardUser", status: number, data: unknown): void {
|
|
58
|
+
this.#summaries[stage === "loadCodeAssist" ? 0 : 1] = summarizeAntigravityDiscovery(stage, status, data);
|
|
59
|
+
this.message = this.publicMessage;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
get publicMessage(): string {
|
|
63
|
+
return `${DISCOVERY_FAILURE_MESSAGE} Discovery: ${this.#summaries.join("; ")}`;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -14,6 +14,7 @@ import { generatePKCE } from "./pkce";
|
|
|
14
14
|
import { normalizeOAuthPlan } from "./plan";
|
|
15
15
|
import type { OAuthController, OAuthCredentials } from "./types";
|
|
16
16
|
import { antigravityUserAgent, ANTIGRAVITY_IDE_VERSION } from "../adapters/client-fingerprint";
|
|
17
|
+
import { AntigravityProjectDiscoveryError } from "./antigravity-discovery-diagnostics";
|
|
17
18
|
|
|
18
19
|
const CLIENT_ID = process.env.GOOGLE_ANTIGRAVITY_CLIENT_ID
|
|
19
20
|
|| "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
|
|
@@ -101,15 +102,19 @@ function extractProjectId(data: Record<string, unknown> | undefined): string | u
|
|
|
101
102
|
return undefined;
|
|
102
103
|
}
|
|
103
104
|
|
|
104
|
-
async function loadCodeAssistProject(accessToken: string, signal?: AbortSignal): Promise<{ projectId?: string; plan: string | null; defaultTierId?: string } | undefined> {
|
|
105
|
+
async function loadCodeAssistProject(accessToken: string, signal?: AbortSignal, diagnostics?: AntigravityProjectDiscoveryError): Promise<{ projectId?: string; plan: string | null; defaultTierId?: string } | undefined> {
|
|
105
106
|
const response = await fetch(`${PROD_API}/${API_VERSION}:loadCodeAssist`, {
|
|
106
107
|
method: "POST",
|
|
107
108
|
headers: { Authorization: `Bearer ${accessToken}`, Accept: "*/*", "Content-Type": "application/json", "User-Agent": antigravityUserAgent() },
|
|
108
109
|
body: JSON.stringify({ metadata: { ideType: "ANTIGRAVITY" } }),
|
|
109
110
|
signal: requestSignal(signal),
|
|
110
111
|
});
|
|
111
|
-
if (!response.ok)
|
|
112
|
+
if (!response.ok) {
|
|
113
|
+
diagnostics?.observe("loadCodeAssist", response.status, undefined);
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
112
116
|
const data: unknown = await response.json().catch(() => undefined);
|
|
117
|
+
diagnostics?.observe("loadCodeAssist", response.status, data);
|
|
113
118
|
if (!data || typeof data !== "object" || Array.isArray(data)) return undefined;
|
|
114
119
|
const payload = data as Record<string, unknown>;
|
|
115
120
|
const tier = (value: unknown) => value && typeof value === "object" && "id" in value
|
|
@@ -133,7 +138,7 @@ async function loadCodeAssistProject(accessToken: string, signal?: AbortSignal):
|
|
|
133
138
|
};
|
|
134
139
|
}
|
|
135
140
|
|
|
136
|
-
async function onboardProject(accessToken: string, signal?: AbortSignal, tierId = "free-tier"): Promise<string | undefined> {
|
|
141
|
+
async function onboardProject(accessToken: string, signal?: AbortSignal, tierId = "free-tier", diagnostics?: AntigravityProjectDiscoveryError): Promise<string | undefined> {
|
|
137
142
|
for (let attempt = 0; attempt < ONBOARD_ATTEMPTS; attempt++) {
|
|
138
143
|
if (signal?.aborted) throw signal.reason ?? new Error("Antigravity onboarding aborted");
|
|
139
144
|
const response = await fetch(`${DAILY_API}/${API_VERSION}:onboardUser`, {
|
|
@@ -148,6 +153,7 @@ async function onboardProject(accessToken: string, signal?: AbortSignal, tierId
|
|
|
148
153
|
signal: requestSignal(signal),
|
|
149
154
|
});
|
|
150
155
|
if (!response.ok) {
|
|
156
|
+
diagnostics?.observe("onboardUser", response.status, undefined);
|
|
151
157
|
// Transient (429/5xx): keep polling within the attempt budget. Hard 4xx: give up now.
|
|
152
158
|
if (response.status === 429 || response.status >= 500) {
|
|
153
159
|
await new Promise(resolve => setTimeout(resolve, ONBOARD_POLL_MS));
|
|
@@ -155,7 +161,13 @@ async function onboardProject(accessToken: string, signal?: AbortSignal, tierId
|
|
|
155
161
|
}
|
|
156
162
|
return undefined;
|
|
157
163
|
}
|
|
158
|
-
|
|
164
|
+
let unparseable = false;
|
|
165
|
+
const data = (await response.json().catch(() => { unparseable = true; return {}; })) as Record<string, unknown>;
|
|
166
|
+
// Keep only the last poll, and only sanitized text. Parsing/admission below is unchanged.
|
|
167
|
+
diagnostics?.observe("onboardUser", response.status, unparseable ? undefined : data);
|
|
168
|
+
// A JSON `null` used to end polling with a TypeError on `data.done`; end it explicitly instead,
|
|
169
|
+
// keeping the one-poll budget, so the caller still raises the recorded discovery error.
|
|
170
|
+
if (data === null) return undefined;
|
|
159
171
|
if (data.done === true) {
|
|
160
172
|
return extractProjectId(data.response as Record<string, unknown> | undefined);
|
|
161
173
|
}
|
|
@@ -169,13 +181,13 @@ export async function discoverAntigravityProject(accessToken: string, signal?: A
|
|
|
169
181
|
return (await discoverAntigravityAccount(accessToken, signal)).projectId;
|
|
170
182
|
}
|
|
171
183
|
|
|
172
|
-
async function discoverAntigravityAccount(accessToken: string, signal?: AbortSignal): Promise<{ projectId?: string; plan?: string | null }> {
|
|
173
|
-
const account = await loadCodeAssistProject(accessToken, signal);
|
|
184
|
+
async function discoverAntigravityAccount(accessToken: string, signal?: AbortSignal, diagnostics?: AntigravityProjectDiscoveryError): Promise<{ projectId?: string; plan?: string | null }> {
|
|
185
|
+
const account = await loadCodeAssistProject(accessToken, signal, diagnostics);
|
|
174
186
|
// Once loadCodeAssist answered, an onboarding failure must not discard its tier observation;
|
|
175
187
|
// a missing project still fails login, and cancellation still propagates.
|
|
176
188
|
const projectId = account?.projectId ?? await (account
|
|
177
|
-
? onboardProject(accessToken, signal, account.defaultTierId).catch(error => { if (signal?.aborted) throw error; return undefined; })
|
|
178
|
-
: onboardProject(accessToken, signal));
|
|
189
|
+
? onboardProject(accessToken, signal, account.defaultTierId, diagnostics).catch(error => { if (signal?.aborted) throw error; return undefined; })
|
|
190
|
+
: onboardProject(accessToken, signal, undefined, diagnostics));
|
|
179
191
|
// An unanswered loadCodeAssist observed nothing; only a parsed body may clear a stored label.
|
|
180
192
|
return { projectId, ...(account ? { plan: account.plan } : {}) };
|
|
181
193
|
}
|
|
@@ -248,11 +260,12 @@ class AntigravityOAuthFlow extends OAuthCallbackFlow {
|
|
|
248
260
|
}, this.ctrl.signal);
|
|
249
261
|
const creds = credentialsFromPayload(payload);
|
|
250
262
|
this.ctrl.onProgress?.("Discovering Cloud Code Assist project");
|
|
251
|
-
const
|
|
263
|
+
const diagnostics = new AntigravityProjectDiscoveryError();
|
|
264
|
+
const { projectId, plan } = await discoverAntigravityAccount(creds.access, this.ctrl.signal, diagnostics);
|
|
252
265
|
if (!projectId) {
|
|
253
266
|
// Fail the login rather than persisting a credential that every request would reject for a
|
|
254
267
|
// missing CCA project — otherwise status shows "logged in" while all calls fail closed.
|
|
255
|
-
throw
|
|
268
|
+
throw diagnostics;
|
|
256
269
|
}
|
|
257
270
|
return { ...creds, projectId, plan };
|
|
258
271
|
}
|