mirror of
https://github.com/claude-code-best/claude-code.git
synced 2026-06-17 13:55:50 +00:00
* fix: harden ACP communication boundaries Harden ACP communication boundaries Remote ACP sessions now cannot widen permission mode through untrusted metadata or client payloads. WebSocket ACP ingress measures payloads by bytes before binary decode, and prompt queue handoff keeps exactly one prompt active while queued prompts are drained FIFO. Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent Constraint: WebSocket payload limits must be byte-based and checked before binary decode Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing Confidence: high Scope-risk: moderate Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build Not-tested: Manual live ACP/RCS session against an external client * fix: restore repository verification gates Keep the full repository test, typecheck, build, and Biome lint gates usable after the ACP fix pass. This commit is intentionally separate from the ACP behavior change: it fixes Windows-safe Langfuse home redaction, removes stale lint suppressions, resolves Biome warning/info diagnostics, and keeps env expansion tests explicit without template-placeholder lint noise. Constraint: The project completion contract requires full typecheck, lint, test, and build evidence Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims Confidence: high Scope-risk: narrow Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build Not-tested: Manual Langfuse export against a real external Langfuse service * fix: harden ACP failure boundaries after review Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter. Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed Confidence: high Scope-risk: moderate Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bunx tsc --noEmit Tested: bunx biome lint src/ packages/acp-link/src/ Tested: bun run test:all Tested: bun run build Not-tested: Manual end-to-end ACP client session over a real editor WebSocket * fix: prevent ACP coverage runs from seeing partial mocks GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module. This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure. Constraint: bun:test mock.module is process-global inside a worker. Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution. Rejected: Keep per-file helper copies | duplication would let restore semantics drift again. Confidence: high Scope-risk: narrow Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests. Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov Tested: bunx tsc --noEmit Tested: bun run lint Tested: git diff --check Not-tested: Linux runner directly before push * fix: normalize ACP bypass requests without warning noise The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path. This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order. Constraint: CI output should not contain expected warning noise for covered policy branches. Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch. Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site. Confidence: high Scope-risk: narrow Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass. Tested: bun test packages/acp-link/src/__tests__/server.test.ts Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0 Tested: bun run test:all Tested: bun run lint Tested: bunx tsc --noEmit Tested: git diff --check * fix: harden ACP bypass and CI warning gates ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state. Constraint: CI must stay warning-clean without hiding real ACP permission failures Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path Confidence: high Scope-risk: moderate Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts Tested: bun run test:all Tested: bun run lint Tested: bun run build:vite with zero warning matches Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches Not-tested: GitHub Actions result after this push * fix: remove remaining CI warning noise The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics. Constraint: Do not use shell log filtering to hide warnings after they happen Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find Confidence: high Scope-risk: narrow Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects Tested: bunx tsc --noEmit --pretty false Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts Tested: bun run build:vite with zero warning matches Not-tested: GitHub Actions result after this push * fix: reject unauthorized ACP bypass and harden CI actions ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings. CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token. Constraint: Must not hide warnings with test isolation or log filtering Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope Confidence: high Scope-risk: moderate Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false Tested: bunx tsc --noEmit --pretty false Tested: bun run lint Tested: bun run test:all Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0 Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR * fix: resolve dependency audit findings precisely Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified. Constraint: no audit ignores or warning suppression Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution Confidence: high Scope-risk: moderate Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: keep ACP auth tokens out of URLs Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change. Constraint: token must not be embedded in the URL Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs Confidence: high Scope-risk: moderate Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code Tested: targeted ACP/RCS transport tests Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks * fix: normalize WebFetch request headers Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline. Constraint: preserve header semantics without widening the fetch surface Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites Confidence: high Scope-risk: narrow Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically Tested: targeted WebFetch header tests Not-tested: unrelated fetch backend behavior beyond header normalization * fix: harden ACP remote auth surfaces Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist. Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string. Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data. Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries. Confidence: high Scope-risk: moderate Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>. Tested: bunx tsc --noEmit --pretty false Tested: bun run typecheck in packages/remote-control-server Tested: bun run build in packages/acp-link Tested: bun run lint Tested: bun audit Tested: focused RCS/acp-link/web tests, 160 pass Tested: Edge headless browser WebSocket subprotocol handshake Tested: bun run test:all, 3669 pass Tested: bun run build:vite Tested: bun run build Not-tested: Manual end-to-end relay with a live external ACP agent * fix: resolve CI dependency override lookup The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating. Constraint: Do not add a new root dependency for a transitive smoke test. Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync. Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface. Confidence: high Scope-risk: narrow Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting. Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check --------- Co-authored-by: unraid <local@unraid.local>
440 lines
15 KiB
TypeScript
440 lines
15 KiB
TypeScript
/**
|
|
* Auto-install logic for the official Anthropic marketplace.
|
|
*
|
|
* This module handles automatically installing the official marketplace
|
|
* on startup for new users, with appropriate checks for:
|
|
* - Enterprise policy restrictions
|
|
* - Git availability
|
|
* - Previous installation attempts
|
|
*/
|
|
|
|
import { join } from 'path'
|
|
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../../services/analytics/growthbook.js'
|
|
import { logEvent } from '../../services/analytics/index.js'
|
|
import { getGlobalConfig, saveGlobalConfig } from '../config.js'
|
|
import { logForDebugging } from '../debug.js'
|
|
import { isEnvTruthy } from '../envUtils.js'
|
|
import { toError } from '../errors.js'
|
|
import { logError } from '../log.js'
|
|
import { checkGitAvailable, markGitUnavailable } from './gitAvailability.js'
|
|
import { isSourceAllowedByPolicy } from './marketplaceHelpers.js'
|
|
import {
|
|
addMarketplaceSource,
|
|
getMarketplacesCacheDir,
|
|
loadKnownMarketplacesConfig,
|
|
saveKnownMarketplacesConfig,
|
|
} from './marketplaceManager.js'
|
|
import {
|
|
OFFICIAL_MARKETPLACE_NAME,
|
|
OFFICIAL_MARKETPLACE_SOURCE,
|
|
} from './officialMarketplace.js'
|
|
import { fetchOfficialMarketplaceFromGcs } from './officialMarketplaceGcs.js'
|
|
|
|
/**
|
|
* Reason why the official marketplace was not installed
|
|
*/
|
|
export type OfficialMarketplaceSkipReason =
|
|
| 'already_attempted'
|
|
| 'already_installed'
|
|
| 'policy_blocked'
|
|
| 'git_unavailable'
|
|
| 'gcs_unavailable'
|
|
| 'unknown'
|
|
|
|
/**
|
|
* Check if official marketplace auto-install is disabled via environment variable.
|
|
*/
|
|
export function isOfficialMarketplaceAutoInstallDisabled(): boolean {
|
|
return isEnvTruthy(
|
|
process.env.CLAUDE_CODE_DISABLE_OFFICIAL_MARKETPLACE_AUTOINSTALL,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Configuration for retry logic
|
|
*/
|
|
export const RETRY_CONFIG = {
|
|
MAX_ATTEMPTS: 10,
|
|
INITIAL_DELAY_MS: 60 * 60 * 1000, // 1 hour
|
|
BACKOFF_MULTIPLIER: 2,
|
|
MAX_DELAY_MS: 7 * 24 * 60 * 60 * 1000, // 1 week
|
|
}
|
|
|
|
/**
|
|
* Calculate next retry delay using exponential backoff
|
|
*/
|
|
function calculateNextRetryDelay(retryCount: number): number {
|
|
const delay =
|
|
RETRY_CONFIG.INITIAL_DELAY_MS *
|
|
RETRY_CONFIG.BACKOFF_MULTIPLIER ** retryCount
|
|
return Math.min(delay, RETRY_CONFIG.MAX_DELAY_MS)
|
|
}
|
|
|
|
/**
|
|
* Determine if installation should be retried based on failure reason and retry state
|
|
*/
|
|
function shouldRetryInstallation(
|
|
config: ReturnType<typeof getGlobalConfig>,
|
|
): boolean {
|
|
// If never attempted, should try
|
|
if (!config.officialMarketplaceAutoInstallAttempted) {
|
|
return true
|
|
}
|
|
|
|
// If already installed successfully, don't retry
|
|
if (config.officialMarketplaceAutoInstalled) {
|
|
return false
|
|
}
|
|
|
|
const failReason = config.officialMarketplaceAutoInstallFailReason
|
|
const retryCount = config.officialMarketplaceAutoInstallRetryCount || 0
|
|
const nextRetryTime = config.officialMarketplaceAutoInstallNextRetryTime
|
|
const now = Date.now()
|
|
|
|
// Check if we've exceeded max attempts
|
|
if (retryCount >= RETRY_CONFIG.MAX_ATTEMPTS) {
|
|
return false
|
|
}
|
|
|
|
// Permanent failures - don't retry
|
|
if (failReason === 'policy_blocked') {
|
|
return false
|
|
}
|
|
|
|
// Check if enough time has passed for next retry
|
|
if (nextRetryTime && now < nextRetryTime) {
|
|
return false
|
|
}
|
|
|
|
// Retry for temporary failures (unknown), semi-permanent (git_unavailable),
|
|
// and legacy state (undefined failReason from before retry logic existed)
|
|
return (
|
|
failReason === 'unknown' ||
|
|
failReason === 'git_unavailable' ||
|
|
failReason === 'gcs_unavailable' ||
|
|
failReason === undefined
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Result of the auto-install check
|
|
*/
|
|
export type OfficialMarketplaceCheckResult = {
|
|
/** Whether the marketplace was successfully installed */
|
|
installed: boolean
|
|
/** Whether the installation was skipped (and why) */
|
|
skipped: boolean
|
|
/** Reason for skipping, if applicable */
|
|
reason?: OfficialMarketplaceSkipReason
|
|
/** Whether saving retry metadata to config failed */
|
|
configSaveFailed?: boolean
|
|
}
|
|
|
|
/**
|
|
* Check and install the official marketplace on startup.
|
|
*
|
|
* This function is designed to be called as a fire-and-forget operation
|
|
* during startup. It will:
|
|
* 1. Check if installation was already attempted
|
|
* 2. Check if marketplace is already installed
|
|
* 3. Check enterprise policy restrictions
|
|
* 4. Check git availability
|
|
* 5. Attempt installation
|
|
* 6. Record the result in GlobalConfig
|
|
*
|
|
* @returns Result indicating whether installation succeeded or was skipped
|
|
*/
|
|
export async function checkAndInstallOfficialMarketplace(): Promise<OfficialMarketplaceCheckResult> {
|
|
const config = getGlobalConfig()
|
|
|
|
// Check if we should retry installation
|
|
if (!shouldRetryInstallation(config)) {
|
|
const reason: OfficialMarketplaceSkipReason =
|
|
config.officialMarketplaceAutoInstallFailReason ?? 'already_attempted'
|
|
logForDebugging(`Official marketplace auto-install skipped: ${reason}`)
|
|
return {
|
|
installed: false,
|
|
skipped: true,
|
|
reason,
|
|
}
|
|
}
|
|
|
|
try {
|
|
// Check if auto-install is disabled via env var
|
|
if (isOfficialMarketplaceAutoInstallDisabled()) {
|
|
logForDebugging(
|
|
'Official marketplace auto-install disabled via env var, skipping',
|
|
)
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: false,
|
|
officialMarketplaceAutoInstallFailReason: 'policy_blocked',
|
|
}))
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: false,
|
|
skipped: true,
|
|
policy_blocked: true,
|
|
})
|
|
return { installed: false, skipped: true, reason: 'policy_blocked' }
|
|
}
|
|
|
|
// Check if marketplace is already installed
|
|
const knownMarketplaces = await loadKnownMarketplacesConfig()
|
|
if (knownMarketplaces[OFFICIAL_MARKETPLACE_NAME]) {
|
|
logForDebugging(
|
|
`Official marketplace '${OFFICIAL_MARKETPLACE_NAME}' already installed, skipping`,
|
|
)
|
|
// Mark as attempted so we don't check again
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: true,
|
|
}))
|
|
return { installed: false, skipped: true, reason: 'already_installed' }
|
|
}
|
|
|
|
// Check enterprise policy restrictions
|
|
if (!isSourceAllowedByPolicy(OFFICIAL_MARKETPLACE_SOURCE)) {
|
|
logForDebugging(
|
|
'Official marketplace blocked by enterprise policy, skipping',
|
|
)
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: false,
|
|
officialMarketplaceAutoInstallFailReason: 'policy_blocked',
|
|
}))
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: false,
|
|
skipped: true,
|
|
policy_blocked: true,
|
|
})
|
|
return { installed: false, skipped: true, reason: 'policy_blocked' }
|
|
}
|
|
|
|
// inc-5046: try GCS mirror first — doesn't need git, doesn't hit GitHub.
|
|
// Backend (anthropic#317037) publishes a marketplace zip to the same
|
|
// bucket as the native binary. If GCS succeeds, register the marketplace
|
|
// with source:'github' (still true — GCS is a mirror) and skip git
|
|
// entirely.
|
|
const cacheDir = getMarketplacesCacheDir()
|
|
const installLocation = join(cacheDir, OFFICIAL_MARKETPLACE_NAME)
|
|
const gcsSha = await fetchOfficialMarketplaceFromGcs(
|
|
installLocation,
|
|
cacheDir,
|
|
)
|
|
if (gcsSha !== null) {
|
|
const known = await loadKnownMarketplacesConfig()
|
|
known[OFFICIAL_MARKETPLACE_NAME] = {
|
|
source: OFFICIAL_MARKETPLACE_SOURCE,
|
|
installLocation,
|
|
lastUpdated: new Date().toISOString(),
|
|
}
|
|
await saveKnownMarketplacesConfig(known)
|
|
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: true,
|
|
officialMarketplaceAutoInstallFailReason: undefined,
|
|
officialMarketplaceAutoInstallRetryCount: undefined,
|
|
officialMarketplaceAutoInstallLastAttemptTime: undefined,
|
|
officialMarketplaceAutoInstallNextRetryTime: undefined,
|
|
}))
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: true,
|
|
skipped: false,
|
|
via_gcs: true,
|
|
})
|
|
return { installed: true, skipped: false }
|
|
}
|
|
// GCS failed (404 until backend writes, or network). Fall through to git
|
|
// ONLY if the kill-switch allows — same gate as refreshMarketplace().
|
|
if (
|
|
!getFeatureValue_CACHED_MAY_BE_STALE(
|
|
'tengu_plugin_official_mkt_git_fallback',
|
|
true,
|
|
)
|
|
) {
|
|
logForDebugging(
|
|
'Official marketplace GCS failed; git fallback disabled by flag — skipping install',
|
|
)
|
|
// Same retry-with-backoff metadata as git_unavailable below — transient
|
|
// GCS failures should retry with exponential backoff, not give up.
|
|
const retryCount =
|
|
(config.officialMarketplaceAutoInstallRetryCount || 0) + 1
|
|
const now = Date.now()
|
|
const nextRetryTime = now + calculateNextRetryDelay(retryCount)
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: false,
|
|
officialMarketplaceAutoInstallFailReason: 'gcs_unavailable',
|
|
officialMarketplaceAutoInstallRetryCount: retryCount,
|
|
officialMarketplaceAutoInstallLastAttemptTime: now,
|
|
officialMarketplaceAutoInstallNextRetryTime: nextRetryTime,
|
|
}))
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: false,
|
|
skipped: true,
|
|
gcs_unavailable: true,
|
|
retry_count: retryCount,
|
|
})
|
|
return { installed: false, skipped: true, reason: 'gcs_unavailable' }
|
|
}
|
|
|
|
// Check git availability
|
|
const gitAvailable = await checkGitAvailable()
|
|
if (!gitAvailable) {
|
|
logForDebugging(
|
|
'Git not available, skipping official marketplace auto-install',
|
|
)
|
|
const retryCount =
|
|
(config.officialMarketplaceAutoInstallRetryCount || 0) + 1
|
|
const now = Date.now()
|
|
const nextRetryDelay = calculateNextRetryDelay(retryCount)
|
|
const nextRetryTime = now + nextRetryDelay
|
|
|
|
let configSaveFailed = false
|
|
try {
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: false,
|
|
officialMarketplaceAutoInstallFailReason: 'git_unavailable',
|
|
officialMarketplaceAutoInstallRetryCount: retryCount,
|
|
officialMarketplaceAutoInstallLastAttemptTime: now,
|
|
officialMarketplaceAutoInstallNextRetryTime: nextRetryTime,
|
|
}))
|
|
} catch (saveError) {
|
|
configSaveFailed = true
|
|
// Log the error properly so it gets tracked
|
|
const configError = toError(saveError)
|
|
logError(configError)
|
|
|
|
logForDebugging(
|
|
`Failed to save marketplace auto-install git_unavailable state: ${saveError}`,
|
|
{ level: 'error' },
|
|
)
|
|
}
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: false,
|
|
skipped: true,
|
|
git_unavailable: true,
|
|
retry_count: retryCount,
|
|
})
|
|
return {
|
|
installed: false,
|
|
skipped: true,
|
|
reason: 'git_unavailable',
|
|
configSaveFailed,
|
|
}
|
|
}
|
|
|
|
// Attempt installation
|
|
logForDebugging('Attempting to auto-install official marketplace')
|
|
await addMarketplaceSource(OFFICIAL_MARKETPLACE_SOURCE)
|
|
|
|
// Success
|
|
logForDebugging('Successfully auto-installed official marketplace')
|
|
const previousRetryCount =
|
|
config.officialMarketplaceAutoInstallRetryCount || 0
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: true,
|
|
// Clear retry metadata on success
|
|
officialMarketplaceAutoInstallFailReason: undefined,
|
|
officialMarketplaceAutoInstallRetryCount: undefined,
|
|
officialMarketplaceAutoInstallLastAttemptTime: undefined,
|
|
officialMarketplaceAutoInstallNextRetryTime: undefined,
|
|
}))
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: true,
|
|
skipped: false,
|
|
retry_count: previousRetryCount,
|
|
})
|
|
return { installed: true, skipped: false }
|
|
} catch (error) {
|
|
// Handle installation failure
|
|
const errorMessage = error instanceof Error ? error.message : String(error)
|
|
|
|
// On macOS, /usr/bin/git is an xcrun shim that always exists on PATH, so
|
|
// checkGitAvailable() (which only does `which git`) passes even without
|
|
// Xcode CLT installed. The shim then fails at clone time with
|
|
// "xcrun: error: invalid active developer path (...)". Poison the memoized
|
|
// availability check so other git callers in this session skip cleanly,
|
|
// then return silently without recording any attempt state — next startup
|
|
// tries fresh (no backoff machinery for what is effectively "git absent").
|
|
if (errorMessage.includes('xcrun: error:')) {
|
|
markGitUnavailable()
|
|
logForDebugging(
|
|
'Official marketplace auto-install: git is a non-functional macOS xcrun shim, treating as git_unavailable',
|
|
)
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: false,
|
|
skipped: true,
|
|
git_unavailable: true,
|
|
macos_xcrun_shim: true,
|
|
})
|
|
return {
|
|
installed: false,
|
|
skipped: true,
|
|
reason: 'git_unavailable',
|
|
}
|
|
}
|
|
|
|
logForDebugging(
|
|
`Failed to auto-install official marketplace: ${errorMessage}`,
|
|
{ level: 'error' },
|
|
)
|
|
logError(toError(error))
|
|
|
|
const retryCount =
|
|
(config.officialMarketplaceAutoInstallRetryCount || 0) + 1
|
|
const now = Date.now()
|
|
const nextRetryDelay = calculateNextRetryDelay(retryCount)
|
|
const nextRetryTime = now + nextRetryDelay
|
|
|
|
let configSaveFailed = false
|
|
try {
|
|
saveGlobalConfig(current => ({
|
|
...current,
|
|
officialMarketplaceAutoInstallAttempted: true,
|
|
officialMarketplaceAutoInstalled: false,
|
|
officialMarketplaceAutoInstallFailReason: 'unknown',
|
|
officialMarketplaceAutoInstallRetryCount: retryCount,
|
|
officialMarketplaceAutoInstallLastAttemptTime: now,
|
|
officialMarketplaceAutoInstallNextRetryTime: nextRetryTime,
|
|
}))
|
|
} catch (saveError) {
|
|
configSaveFailed = true
|
|
// Log the error properly so it gets tracked
|
|
const configError = toError(saveError)
|
|
logError(configError)
|
|
|
|
logForDebugging(
|
|
`Failed to save marketplace auto-install failure state: ${saveError}`,
|
|
{ level: 'error' },
|
|
)
|
|
|
|
// Still return the failure result even if config save failed
|
|
// This ensures we report the installation failure correctly
|
|
}
|
|
logEvent('tengu_official_marketplace_auto_install', {
|
|
installed: false,
|
|
skipped: true,
|
|
failed: true,
|
|
retry_count: retryCount,
|
|
})
|
|
|
|
return {
|
|
installed: false,
|
|
skipped: true,
|
|
reason: 'unknown',
|
|
configSaveFailed,
|
|
}
|
|
}
|
|
}
|