{"version":3,"file":"bundled-assets.d.ts","sourceRoot":"","sources":["../../src/core/bundled-assets.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAoBH,kEAAkE;AAClE,eAAO,MAAM,oBAAoB,4BAA4B,CAAC;AAE9D,qGAAqG;AACrG,eAAO,MAAM,mBAAmB,yBAAyB,CAAC;AAQ1D;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,qKAUzB,CAAC;AAEX,wBAAgB,sBAAsB,CAAC,QAAQ,GAAE,MAAsB,GAAG,MAAM,GAAG,SAAS,CAM3F;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,GAAE,MAAsB,GAAG,OAAO,CAWhF;AA+BD;;;;;GAKG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAyB/C;AAED;;;;;;GAMG;AACH,wBAAgB,8BAA8B,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAiCzF","sourcesContent":["/**\n * Keeps the bundled phi extensions, agents and skills copied into the agent dir\n * in sync with the installed package version.\n *\n * They are installed by `scripts/postinstall.cjs`, which does NOT run for\n * `phi update` (it installs with `--ignore-scripts`) nor for the documented\n * `npm install -g --ignore-scripts` install. Without this check an update left\n * the previous version's extensions in place, so their fixes never shipped.\n *\n * The standalone Bun binary never runs postinstall either, and has no node to\n * run it with: process.execPath is the phi executable itself. Its archive stages\n * extensions/phi, agents, skills and the extensions' npm dependencies next to the\n * executable (scripts/build-binaries.sh), and the binary copies them in-process.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport {\n\tcpSync,\n\texistsSync,\n\tlstatSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmdirSync,\n\trmSync,\n\tsymlinkSync,\n\tunlinkSync,\n\twriteFileSync,\n} from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport lockfile from \"proper-lockfile\";\nimport { getAgentDir, getPackageDir, isBunBinary, VERSION } from \"../config.ts\";\n\n/** Written by scripts/postinstall.cjs once the copy succeeded. */\nexport const BUNDLED_ASSETS_STAMP = \".bundled-assets-version\";\n\n/** Held (proper-lockfile directory) while one process re-syncs the agent dir; others wait for it. */\nexport const BUNDLED_ASSETS_LOCK = \".bundled-assets.lock\";\n/** Upper bound of one postinstall run. */\nconst SYNC_TIMEOUT_MS = 60_000;\n/** Longer than SYNC_TIMEOUT_MS: the lock is not refreshed while spawnSync blocks the event loop. */\nconst SYNC_LOCK_STALE_MS = 90_000;\n/** How long a process waits for another one's sync before running its own anyway. */\nconst SYNC_LOCK_WAIT_MS = 75_000;\n\n/**\n * Non phi-internal npm packages the bundled extensions import (typebox and\n * phi-code* resolve through the loader's virtual modules). Keep in sync with\n * `extensionDeps` in scripts/postinstall.cjs and EXTENSION_DEPS in\n * scripts/build-binaries.sh.\n */\nexport const BUNDLED_EXTENSION_DEPS = [\n\t\"sigma-memory\",\n\t\"sigma-agents\",\n\t\"sigma-skills\",\n\t\"zod\",\n\t\"@modelcontextprotocol/sdk\",\n\t\"@ast-grep/napi\",\n\t\"cross-spawn\",\n\t\"ignore\",\n\t\"@phi-code-admin/browser\",\n] as const;\n\nexport function readBundledAssetsStamp(agentDir: string = getAgentDir()): string | undefined {\n\ttry {\n\t\treturn readFileSync(join(agentDir, BUNDLED_ASSETS_STAMP), \"utf8\").trim() || undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * True when a dependency entry exists in <agentDir>/extensions/node_modules but its\n * package.json cannot be reached: a link left dangling when npm moved or removed the\n * package (update, dedupe, other Node prefix). Entries that were never created are fine.\n */\nexport function hasBrokenExtensionLink(agentDir: string = getAgentDir()): boolean {\n\tconst modules = join(agentDir, \"extensions\", \"node_modules\");\n\treturn BUNDLED_EXTENSION_DEPS.some((pkg) => {\n\t\tconst entry = join(modules, pkg);\n\t\ttry {\n\t\t\tlstatSync(entry);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t\treturn !existsSync(join(entry, \"package.json\"));\n\t});\n}\n\nfunction needsSync(agentDir: string): boolean {\n\treturn readBundledAssetsStamp(agentDir) !== VERSION || hasBrokenExtensionLink(agentDir);\n}\n\n/**\n * Takes the sync lock, waiting (bounded) while another process holds it. Returns the\n * release function, or undefined when the lock could not be taken: the caller then\n * syncs without it, as before the lock existed.\n */\nfunction acquireSyncLock(agentDir: string): (() => void) | undefined {\n\tconst deadline = Date.now() + SYNC_LOCK_WAIT_MS;\n\tfor (;;) {\n\t\ttry {\n\t\t\tmkdirSync(agentDir, { recursive: true });\n\t\t\treturn lockfile.lockSync(agentDir, {\n\t\t\t\trealpath: false,\n\t\t\t\tstale: SYNC_LOCK_STALE_MS,\n\t\t\t\tlockfilePath: join(agentDir, BUNDLED_ASSETS_LOCK),\n\t\t\t\t// Best effort: a lock taken over by another process must not crash phi.\n\t\t\t\tonCompromised: () => {},\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif ((error as NodeJS.ErrnoException).code !== \"ELOCKED\" || Date.now() >= deadline) return undefined;\n\t\t\t// Sleep synchronously without burning the CPU (startup is synchronous here).\n\t\t\tAtomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);\n\t\t}\n\t}\n}\n\n/**\n * Re-run the postinstall copy when the stamp does not match this version or when an\n * extension dependency link no longer resolves. One process syncs at a time; the others\n * wait for it and skip their own run once the agent dir is up to date.\n * Best effort: never throws, never blocks startup on failure.\n */\nexport function syncBundledAssetsIfStale(): void {\n\t// PHI_SKIP_POSTINSTALL is the opt-out. CI alone no longer disables the sync: a CI job\n\t// that runs phi needs its extensions like any other run.\n\tif (process.env.PHI_SKIP_POSTINSTALL) return;\n\tconst agentDir = getAgentDir();\n\tif (!needsSync(agentDir)) return;\n\tconst release = acquireSyncLock(agentDir);\n\ttry {\n\t\t// Another process may have finished the same sync while this one waited.\n\t\tif (!needsSync(agentDir)) return;\n\t\tif (isBunBinary) {\n\t\t\tsyncBundledAssetsFromBinaryDir(getPackageDir(), agentDir);\n\t\t\treturn;\n\t\t}\n\t\tconst script = join(getPackageDir(), \"scripts\", \"postinstall.cjs\");\n\t\tif (!existsSync(script)) return;\n\t\t// postinstall.cjs skips itself under CI (an npm install in CI must not touch ~/.phi);\n\t\t// this sync is phi setting up its own agent dir, so CI is removed from its env.\n\t\tconst { CI: _ci, ...env } = process.env;\n\t\tspawnSync(process.execPath, [script], { stdio: \"ignore\", env, timeout: SYNC_TIMEOUT_MS });\n\t} catch {\n\t\t// Ignore: the previous copies keep working; the next start retries.\n\t} finally {\n\t\trelease?.();\n\t}\n}\n\n/**\n * In-process equivalent of postinstall steps 1, 2 and 5 for the Bun binary:\n * copy extensions/phi, agents and skills from the archive into the agent dir,\n * link the extensions' npm dependencies shipped in <archive>/node_modules, then\n * write the version stamp. The stamp is only written when every copy succeeded,\n * so a partial failure is retried on the next start.\n */\nexport function syncBundledAssetsFromBinaryDir(packageDir: string, agentDir: string): void {\n\tconst copies = [\n\t\t{ src: join(packageDir, \"extensions\", \"phi\"), dest: join(agentDir, \"extensions\") },\n\t\t{ src: join(packageDir, \"agents\"), dest: join(agentDir, \"agents\") },\n\t\t{ src: join(packageDir, \"skills\"), dest: join(agentDir, \"skills\") },\n\t];\n\tlet ok = true;\n\tfor (const { src, dest } of copies) {\n\t\tif (!existsSync(src)) continue;\n\t\ttry {\n\t\t\tmkdirSync(dest, { recursive: true });\n\t\t\tfor (const entry of readdirSync(src)) {\n\t\t\t\tcpSync(join(src, entry), join(dest, entry), { recursive: true, force: true });\n\t\t\t}\n\t\t} catch {\n\t\t\tok = false;\n\t\t}\n\t}\n\n\tconst sourceModules = join(packageDir, \"node_modules\");\n\tconst extensionsModules = join(agentDir, \"extensions\", \"node_modules\");\n\tfor (const pkg of BUNDLED_EXTENSION_DEPS) {\n\t\tconst src = join(sourceModules, pkg);\n\t\tif (!existsSync(src)) continue;\n\t\tif (!linkPackage(src, join(extensionsModules, pkg))) ok = false;\n\t}\n\n\tif (!ok) return;\n\ttry {\n\t\twriteFileSync(join(agentDir, BUNDLED_ASSETS_STAMP), VERSION, \"utf8\");\n\t} catch {\n\t\t// Next start retries.\n\t}\n}\n\n/**\n * Junction (no admin rights needed on Windows) to the package shipped next to\n * the executable, so its own dependencies resolve from the archive's node_modules.\n * Falls back to a copy, like postinstall.cjs.\n */\nfunction linkPackage(src: string, dest: string): boolean {\n\ttry {\n\t\tmkdirSync(dirname(dest), { recursive: true });\n\t\tremoveExisting(dest);\n\t\ttry {\n\t\t\tsymlinkSync(src, dest, \"junction\");\n\t\t} catch {\n\t\t\tcpSync(src, dest, { recursive: true, force: true });\n\t\t}\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** Same semantics as removeExisting() in postinstall.cjs (handles dangling junctions). */\nfunction removeExisting(dest: string): void {\n\tlet isLink: boolean;\n\ttry {\n\t\tisLink = lstatSync(dest).isSymbolicLink();\n\t} catch {\n\t\treturn;\n\t}\n\tif (isLink) {\n\t\ttry {\n\t\t\tunlinkSync(dest);\n\t\t\treturn;\n\t\t} catch {\n\t\t\t// try rmdir below\n\t\t}\n\t\ttry {\n\t\t\trmdirSync(dest);\n\t\t\treturn;\n\t\t} catch {\n\t\t\t// fall through\n\t\t}\n\t}\n\trmSync(dest, { recursive: true, force: true });\n}\n"]}