@skaile/workspaces 3.4.0 → 3.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/dist/{asset-feeds-CBY723RG.js → asset-feeds-JJTN5PGH.js} +7 -7
  3. package/dist/{asset-feeds-CBY723RG.js.map → asset-feeds-JJTN5PGH.js.map} +1 -1
  4. package/dist/asset-manager/catalog-deployer.js +3 -3
  5. package/dist/asset-manager/index.js +6 -6
  6. package/dist/asset-manager/installer.js +4 -4
  7. package/dist/bridge/drivers/claude-sdk.js +34 -5
  8. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  9. package/dist/bridge/drivers/codex.js +1 -1
  10. package/dist/bridge/drivers/continue.js +2 -2
  11. package/dist/bridge/drivers/echo.js +1 -1
  12. package/dist/bridge/drivers/gemini.js +3 -3
  13. package/dist/bridge/drivers/goose.js +2 -2
  14. package/dist/bridge/drivers/omp.js +1 -1
  15. package/dist/bridge/drivers/opencode.js +2 -2
  16. package/dist/bridge/drivers/qwen.js +3 -3
  17. package/dist/bridge/index.js +5 -5
  18. package/dist/bridge/src/drivers/claude-sdk.d.ts +16 -0
  19. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  20. package/dist/bridge/src/types.d.ts +17 -0
  21. package/dist/bridge/src/types.d.ts.map +1 -1
  22. package/dist/{chunk-VFL4STB7.js → chunk-33ZEIMFJ.js} +2 -2
  23. package/dist/{chunk-VFL4STB7.js.map → chunk-33ZEIMFJ.js.map} +1 -1
  24. package/dist/{chunk-AXFOJ2UG.js → chunk-3UU3D2Q3.js} +3 -3
  25. package/dist/{chunk-AXFOJ2UG.js.map → chunk-3UU3D2Q3.js.map} +1 -1
  26. package/dist/{chunk-SUGDZOYZ.js → chunk-AFA7NYN2.js} +21 -2
  27. package/dist/chunk-AFA7NYN2.js.map +1 -0
  28. package/dist/{chunk-6BV24JPZ.js → chunk-AZPXCHDK.js} +4 -4
  29. package/dist/{chunk-6BV24JPZ.js.map → chunk-AZPXCHDK.js.map} +1 -1
  30. package/dist/{chunk-PHJ2DU6D.js → chunk-BC5MXJZA.js} +3 -3
  31. package/dist/{chunk-PHJ2DU6D.js.map → chunk-BC5MXJZA.js.map} +1 -1
  32. package/dist/{chunk-3UGP7I2Y.js → chunk-GWUGD4FQ.js} +2 -2
  33. package/dist/{chunk-3UGP7I2Y.js.map → chunk-GWUGD4FQ.js.map} +1 -1
  34. package/dist/{chunk-3Q7JDLLH.js → chunk-HBF7A7JB.js} +3 -3
  35. package/dist/{chunk-3Q7JDLLH.js.map → chunk-HBF7A7JB.js.map} +1 -1
  36. package/dist/{chunk-RD6MMBHQ.js → chunk-IP3GXHOB.js} +2 -3
  37. package/dist/chunk-IP3GXHOB.js.map +1 -0
  38. package/dist/{chunk-OI36ITDV.js → chunk-JISWIYUA.js} +7 -7
  39. package/dist/{chunk-OI36ITDV.js.map → chunk-JISWIYUA.js.map} +1 -1
  40. package/dist/{chunk-U2KIY532.js → chunk-KF52XLUH.js} +3 -3
  41. package/dist/{chunk-U2KIY532.js.map → chunk-KF52XLUH.js.map} +1 -1
  42. package/dist/{chunk-2Y2AWWWM.js → chunk-M5D2QNTY.js} +3 -3
  43. package/dist/{chunk-2Y2AWWWM.js.map → chunk-M5D2QNTY.js.map} +1 -1
  44. package/dist/{chunk-MR3LQTGA.js → chunk-MEPZOB3K.js} +4 -4
  45. package/dist/{chunk-MR3LQTGA.js.map → chunk-MEPZOB3K.js.map} +1 -1
  46. package/dist/{chunk-PEGIQ67F.js → chunk-O7WKKINT.js} +4 -4
  47. package/dist/{chunk-PEGIQ67F.js.map → chunk-O7WKKINT.js.map} +1 -1
  48. package/dist/{chunk-BJ7QIUBM.js → chunk-OCLCDB7G.js} +4 -4
  49. package/dist/{chunk-BJ7QIUBM.js.map → chunk-OCLCDB7G.js.map} +1 -1
  50. package/dist/{chunk-3A3ETJFD.js → chunk-QJQL2DGN.js} +4 -4
  51. package/dist/{chunk-3A3ETJFD.js.map → chunk-QJQL2DGN.js.map} +1 -1
  52. package/dist/{chunk-S5N33NGZ.js → chunk-R6OLT7E4.js} +6 -6
  53. package/dist/{chunk-S5N33NGZ.js.map → chunk-R6OLT7E4.js.map} +1 -1
  54. package/dist/{chunk-DFZ6QENJ.js → chunk-R6X57YZA.js} +35 -16
  55. package/dist/chunk-R6X57YZA.js.map +1 -0
  56. package/dist/{chunk-SJQ7544V.js → chunk-SG67QMLI.js} +7 -7
  57. package/dist/{chunk-SJQ7544V.js.map → chunk-SG67QMLI.js.map} +1 -1
  58. package/dist/{chunk-KBXYT5HD.js → chunk-SH572OBN.js} +3 -3
  59. package/dist/{chunk-KBXYT5HD.js.map → chunk-SH572OBN.js.map} +1 -1
  60. package/dist/{chunk-ZCIK44M7.js → chunk-UTMZU56B.js} +3 -3
  61. package/dist/{chunk-ZCIK44M7.js.map → chunk-UTMZU56B.js.map} +1 -1
  62. package/dist/{chunk-A7XP4C7C.js → chunk-WAFHQDLK.js} +3 -3
  63. package/dist/{chunk-A7XP4C7C.js.map → chunk-WAFHQDLK.js.map} +1 -1
  64. package/dist/{chunk-BYPQHEI4.js → chunk-WE7DETAK.js} +5 -5
  65. package/dist/{chunk-BYPQHEI4.js.map → chunk-WE7DETAK.js.map} +1 -1
  66. package/dist/{chunk-P6V5GORE.js → chunk-XDIVJ7G6.js} +7 -7
  67. package/dist/{chunk-P6V5GORE.js.map → chunk-XDIVJ7G6.js.map} +1 -1
  68. package/dist/{chunk-POYF2P7E.js → chunk-Z6URZI2W.js} +9 -9
  69. package/dist/{chunk-POYF2P7E.js.map → chunk-Z6URZI2W.js.map} +1 -1
  70. package/dist/cli/index.js +45 -45
  71. package/dist/connectors/config.js +4 -4
  72. package/dist/connectors/index.js +8 -8
  73. package/dist/core/index.js +3 -3
  74. package/dist/core/runtime-assets.js +2 -2
  75. package/dist/core/src/workspace-config.d.ts +0 -2
  76. package/dist/core/src/workspace-config.d.ts.map +1 -1
  77. package/dist/core/workspace-config.js +1 -1
  78. package/dist/deploy/index.js +3 -3
  79. package/dist/{ensure-sources-O6AWQXAY.js → ensure-sources-NLJJ6EDJ.js} +9 -9
  80. package/dist/{ensure-sources-O6AWQXAY.js.map → ensure-sources-NLJJ6EDJ.js.map} +1 -1
  81. package/dist/factory-assets/connectors/box.js +8 -8
  82. package/dist/factory-assets/connectors/deploy.js +8 -8
  83. package/dist/factory-assets/connectors/devserver.js +8 -8
  84. package/dist/factory-assets/connectors/flow/adapter.js +8 -8
  85. package/dist/factory-assets/connectors/flow/engine.js +4 -4
  86. package/dist/factory-assets/connectors/flow/run-flow.js +9 -9
  87. package/dist/factory-assets/connectors/flow.js +8 -8
  88. package/dist/factory-assets/connectors/git.js +8 -8
  89. package/dist/factory-assets/connectors/gmail.js +8 -8
  90. package/dist/factory-assets/connectors/googledrive.js +8 -8
  91. package/dist/factory-assets/connectors/local.js +8 -8
  92. package/dist/factory-assets/connectors/mattermost.js +8 -8
  93. package/dist/factory-assets/connectors/memory.js +8 -8
  94. package/dist/factory-assets/connectors/minio.js +8 -8
  95. package/dist/factory-assets/connectors/postgres.js +8 -8
  96. package/dist/factory-assets/connectors/s3.js +8 -8
  97. package/dist/factory-assets/connectors/sharepoint.js +8 -8
  98. package/dist/factory-assets/connectors/sqlite.js +8 -8
  99. package/dist/factory-assets/connectors/static-server.js +8 -8
  100. package/dist/factory-assets/connectors/tunnel.js +8 -8
  101. package/dist/factory-assets/connectors/webdav.js +8 -8
  102. package/dist/factory-assets/connectors/xstate-store.js +8 -8
  103. package/dist/factory-assets/connectors/xstate.js +8 -8
  104. package/dist/{flows-66NOT5N6.js → flows-4PIPK2S6.js} +6 -6
  105. package/dist/{flows-66NOT5N6.js.map → flows-4PIPK2S6.js.map} +1 -1
  106. package/dist/{helpers-QUGRH2MW.js → helpers-ZGTNTGMV.js} +9 -9
  107. package/dist/{helpers-QUGRH2MW.js.map → helpers-ZGTNTGMV.js.map} +1 -1
  108. package/dist/library/index.js +4 -4
  109. package/dist/library/install.js +3 -3
  110. package/dist/{library-publish-TCT652H4.js → library-publish-457SD4QQ.js} +13 -13
  111. package/dist/{library-publish-TCT652H4.js.map → library-publish-457SD4QQ.js.map} +1 -1
  112. package/dist/{open-library-6OSZX2O6.js → open-library-RA6VLD4L.js} +11 -11
  113. package/dist/{open-library-6OSZX2O6.js.map → open-library-RA6VLD4L.js.map} +1 -1
  114. package/dist/{paths-ESJHWGBR.js → paths-S7UESJKT.js} +6 -6
  115. package/dist/{paths-ESJHWGBR.js.map → paths-S7UESJKT.js.map} +1 -1
  116. package/dist/{plugin-store-3BYOBKYT.js → plugin-store-5SJX2PRR.js} +5 -5
  117. package/dist/{plugin-store-3BYOBKYT.js.map → plugin-store-5SJX2PRR.js.map} +1 -1
  118. package/dist/{project-5RGSHTZ7.js → project-TXHKK7NR.js} +10 -10
  119. package/dist/{project-5RGSHTZ7.js.map → project-TXHKK7NR.js.map} +1 -1
  120. package/dist/resolver/index.js +3 -3
  121. package/dist/runner/index.js +11 -11
  122. package/dist/runner/src/compaction/orchestrator.d.ts +23 -2
  123. package/dist/runner/src/compaction/orchestrator.d.ts.map +1 -1
  124. package/dist/sdk/asset-manager.js +6 -6
  125. package/dist/sdk/bridge.js +5 -5
  126. package/dist/sdk/core.js +3 -3
  127. package/dist/sdk/flow.js +4 -4
  128. package/dist/sdk/index.js +11 -11
  129. package/dist/sdk/resolver.js +3 -3
  130. package/dist/sdk/runner.js +11 -11
  131. package/dist/{setup-X2T3NW7P.js → setup-4TE4XIDD.js} +7 -7
  132. package/dist/{setup-X2T3NW7P.js.map → setup-4TE4XIDD.js.map} +1 -1
  133. package/dist/{skills-TYMTW4V4.js → skills-OBJX3VYG.js} +5 -5
  134. package/dist/{skills-TYMTW4V4.js.map → skills-OBJX3VYG.js.map} +1 -1
  135. package/dist/{source-JS3G5P6Z.js → source-IFIP5TXM.js} +12 -12
  136. package/dist/{source-JS3G5P6Z.js.map → source-IFIP5TXM.js.map} +1 -1
  137. package/dist/{source-manifest-publish-Y7BOFFO4.js → source-manifest-publish-43KI3KHL.js} +14 -14
  138. package/dist/{source-manifest-publish-Y7BOFFO4.js.map → source-manifest-publish-43KI3KHL.js.map} +1 -1
  139. package/dist/tui/index.js +11 -11
  140. package/dist/types/src/events.d.ts +1 -1
  141. package/dist/types/src/events.d.ts.map +1 -1
  142. package/dist/workspace-plugin/adapters/mcp.js +4 -4
  143. package/dist/workspace-plugin/adapters/omp.js +7 -7
  144. package/dist/workspace-plugin/index.js +1 -1
  145. package/package.json +1 -1
  146. package/dist/chunk-DFZ6QENJ.js.map +0 -1
  147. package/dist/chunk-RD6MMBHQ.js.map +0 -1
  148. package/dist/chunk-SUGDZOYZ.js.map +0 -1
@@ -1,6 +1,6 @@
1
- import { logErr, logOk, colorRef, logInfo, S, logWarn, formatSoftDepHint } from './chunk-U2KIY532.js';
2
- import { AssetManager } from './chunk-OI36ITDV.js';
3
- import { readLock } from './chunk-6BV24JPZ.js';
1
+ import { logErr, logOk, colorRef, logInfo, S, logWarn, formatSoftDepHint } from './chunk-KF52XLUH.js';
2
+ import { AssetManager } from './chunk-JISWIYUA.js';
3
+ import { readLock } from './chunk-AZPXCHDK.js';
4
4
  import { SUPPORTED_DRIVER_TARGETS } from './chunk-MENCWIHW.js';
5
5
  import { parseAssetRef } from './chunk-GEEW6SY2.js';
6
6
  import path from 'path';
@@ -82,7 +82,7 @@ async function runRefInstall(ref, opts) {
82
82
  const spinner2 = p.spinner();
83
83
  spinner2.start(`Installing ${ref}`);
84
84
  try {
85
- const { openCatalogSource, openLibrary } = await import('./open-library-6OSZX2O6.js');
85
+ const { openCatalogSource, openLibrary } = await import('./open-library-RA6VLD4L.js');
86
86
  const catalog = await openCatalogSource({ projectDir: path.resolve(opts.projectDir) });
87
87
  if (!supportsInstallManifest(catalog)) {
88
88
  throw new Error(
@@ -122,7 +122,7 @@ async function runYamlInstall(opts) {
122
122
  return;
123
123
  }
124
124
  try {
125
- const { ensureSourcesCloned } = await import('./ensure-sources-O6AWQXAY.js');
125
+ const { ensureSourcesCloned } = await import('./ensure-sources-NLJJ6EDJ.js');
126
126
  const hydrate = ensureSourcesCloned(projectDir, { quiet: true });
127
127
  if (hydrate.cloned.length > 0) {
128
128
  logOk(`Cloned source(s): ${hydrate.cloned.join(", ")}`);
@@ -288,5 +288,5 @@ function makeCleanCommand() {
288
288
  }
289
289
 
290
290
  export { makeCheckCommand, makeCleanCommand, makeInstallCommand, reportInstalledSoftDeps, runPointerOnlyInstall, supportsInstallManifest };
291
- //# sourceMappingURL=chunk-SJQ7544V.js.map
292
- //# sourceMappingURL=chunk-SJQ7544V.js.map
291
+ //# sourceMappingURL=chunk-SG67QMLI.js.map
292
+ //# sourceMappingURL=chunk-SG67QMLI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/commands/project.ts"],"names":["spinner","confirm"],"mappings":";;;;;;;;;AAmBA,IAAM,QAAA,GAAW,uEAAA;AAGjB,SAAS,gBAAgB,GAAA,EAAsB;AAC7C,EAAA,IAAI;AACF,IAAA,aAAA,CAAc,GAAG,CAAA;AACjB,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAqBO,SAAS,wBAAwB,MAAA,EAAkD;AACxF,EAAA,OACE,OAAQ,QAAgE,kBAAA,KACxE,UAAA;AAEJ;AAwCA,eAAsB,qBAAA,CACpB,KACA,IAAA,EACmC;AACnC,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,cAAc,GAAG,CAAA;AAAA,EAC/B,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,qBAAA,EAAwB,GAAG,CAAA,kBAAA,EAAgB,QAAQ,CAAA,EAAA,EAAK,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,KACpG;AAA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AA;AAAA,MAC/B;AAAA,IACF;AACA,IAAA,IAAI,KAAK,GAAA,EAAK;AACZ,MAAA,OAAA,CAAQ,GAAA,EAAI;AACZ,MAAA,KAAA,CAAM,sBAAsB,CAAA;AAAA,IAC9B;AAAA,EACF,CAAC,CAAA;AACL","file":"chunk-SJQ7544V.js","sourcesContent":["import path from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport { AssetManager } from \"@skaile/workspaces/asset-manager\";\nimport {\n type DriverTarget,\n parseAssetRef,\n readLock,\n SUPPORTED_DRIVER_TARGETS,\n} from \"@skaile/workspaces/core\";\nimport type { InstallManifest } from \"@skaile/workspaces/types\";\nimport { Command } from \"commander\";\nimport { colorRef, formatSoftDepHint, logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\n\n/**\n * Canonical asset-ref shape accepted by `skaile install <ref>`:\n * `kind:@<publisher>/<name>#<version>` (the `#` version sigil). Validated via\n * `parseAssetRef` so the CLI shares the single canonical grammar; the legacy\n * trailing-`@version` shape is rejected.\n */\nconst REF_HINT = \"kind:@<publisher>/<name>#<version> (e.g. skill:@skaile/use-exa#1.0.0)\";\n\n/** True when `ref` parses as a canonical asset ref. */\nfunction isValidAssetRef(ref: string): boolean {\n try {\n parseAssetRef(ref);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Minimal catalog-source surface the pointer-only install path needs.\n * `RemoteCatalogSource` satisfies this — narrowing keeps {@link runPointerOnlyInstall}\n * testable with a hand-rolled stub.\n */\nexport interface InstallManifestSource {\n getInstallManifest(ref: string): Promise<InstallManifest>;\n}\n\n/**\n * Capability check: is this catalog source able to serve install manifests?\n *\n * `openCatalogSource` returns a `RemoteCatalogSource | RestCatalogSource`.\n * Only the tRPC-framed `RemoteCatalogSource` implements `getInstallManifest`;\n * the REST-framed `RestCatalogSource` (the default for any catalog URL other\n * than `https://skaile.store`) does not. Calling it unconditionally would be a\n * runtime `TypeError`, so the pointer-only install path must capability-detect\n * first and fail with a clear, actionable message.\n */\nexport function supportsInstallManifest(source: unknown): source is InstallManifestSource {\n return (\n typeof (source as { getInstallManifest?: unknown } | null | undefined)?.getInstallManifest ===\n \"function\"\n );\n}\n\n/**\n * Minimal library surface the pointer-only install path needs.\n * `LocalIndex` satisfies this.\n */\nexport interface InstallLibrary {\n install(manifest: InstallManifest): Promise<{ installPath: string }>;\n}\n\n/**\n * Result of a pointer-only catalog install.\n */\nexport interface PointerOnlyInstallResult {\n /** Absolute path the verified asset bytes were written to. */\n installPath: string;\n /** The pinned upstream commit SHA the asset was fetched at. */\n commitSha: string;\n /** Number of files in the install manifest. */\n fileCount: number;\n}\n\n/**\n * Pointer-only catalog install — the `skaile install <ref>` code path.\n *\n * 1. Resolves the pointer-only {@link InstallManifest} from the Catalog.\n * 2. Hands it to the library, which fetches each file's bytes directly from\n * the upstream repo at the pinned commit, verifies every per-file SHA256\n * plus the composite SHA256, and only then writes the verified files.\n *\n * Both dependencies are injected so the function is unit-testable without a\n * network round-trip. In production the CLI passes a `RemoteCatalogSource`\n * and a `LocalIndex`.\n *\n * @param ref - Asset ref (`<publisher>/<name>@<version>`, optional leading `@`).\n * @param deps - Injected catalog source + library.\n * @returns The install path, pinned commit SHA, and file count.\n * @throws When the ref is malformed, the manifest cannot be resolved, or any\n * hash verification fails. The underlying error message is surfaced as-is.\n */\nexport async function runPointerOnlyInstall(\n ref: string,\n deps: { catalog: InstallManifestSource; library: InstallLibrary },\n): Promise<PointerOnlyInstallResult> {\n let requested: ReturnType<typeof parseAssetRef>;\n try {\n requested = parseAssetRef(ref);\n } catch (e) {\n throw new Error(\n `malformed asset ref '${ref}' — expected ${REF_HINT}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const manifest = await deps.catalog.getInstallManifest(ref);\n // [M1] Identity check: the catalog must not install a different asset than\n // requested. Compare the PARSED refs (kind/publisher/name/pin) so equivalent\n // spellings (optional `kind:`, default `skill`) are treated as the same ref.\n const got = parseAssetRef(manifest.ref);\n if (\n got.kind !== requested.kind ||\n got.publisher !== requested.publisher ||\n got.name !== requested.name ||\n got.pin !== requested.pin\n ) {\n throw new Error(\n `catalog identity mismatch: requested '${ref}' but the catalog returned a manifest for '${manifest.ref}'`,\n );\n }\n const { installPath } = await deps.library.install(manifest);\n return {\n installPath,\n commitSha: manifest.source.commitSha,\n fileCount: manifest.files.length,\n };\n}\n\n/**\n * Creates the `skaile install` command.\n *\n * Two modes, selected by argument shape:\n *\n * - `skaile install` (no positional arg) — reads `skaile.yaml` and deploys all\n * declared assets (and their transitive dependencies) to the configured\n * driver target directory. Supports `--locked` for CI-mode install from a\n * lock file.\n * - `skaile install <publisher>/<name>@<version>` — pointer-only catalog\n * install: resolves the pointer-only install manifest from the configured\n * Catalog, fetches each file's bytes directly from the upstream repo at the\n * pinned commit, verifies every per-file + the composite SHA256, then writes\n * the verified files into the local Library.\n *\n * @returns Configured {@link Command} ready for `program.addCommand()`.\n * @docLink cli/commands/project#make-install-command\n */\nexport function makeInstallCommand(): Command {\n return new Command(\"install\")\n .description(`Install dependencies from skaile.yaml, or a single asset by ref (${REF_HINT})`)\n .argument(\"[ref]\", `Asset ref to install from the Catalog (${REF_HINT})`)\n .option(\"--locked\", \"Install from lock file (CI mode — fails on drift)\")\n .option(\"--project-dir <path>\", \"Project directory\", process.cwd())\n .option(\"--target <agent>\", \"Agent framework\", \"claude-code\")\n .option(\n \"--global\",\n \"Install the global SSOT (~/.skaile/skaile.yaml), fanning out to every global backend\",\n )\n .option(\n \"--backend <ids>\",\n \"Comma-separated global backends to install into (default: all resolved); implies --global\",\n )\n .option(\n \"--link\",\n \"symlink local-path assets instead of copying (dev loop; machine-local, not for committing)\",\n )\n .action(runInstallCommand);\n}\n\n/** Options shape accepted by the `skaile install` command action. */\ninterface InstallCommandOptions {\n locked?: boolean;\n projectDir: string;\n target: string;\n global?: boolean;\n backend?: string;\n link?: boolean;\n}\n\n/**\n * Parse a `--backend a,b` value into validated {@link DriverTarget}s, exiting on\n * an unknown id. Returns `undefined` when the flag is absent (resolve the full\n * global set instead).\n */\nfunction parseBackendFilter(raw: string | undefined): DriverTarget[] | undefined {\n if (!raw) return undefined;\n const ids = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n const out: DriverTarget[] = [];\n for (const id of ids) {\n if (!(SUPPORTED_DRIVER_TARGETS as string[]).includes(id)) {\n logErr(`unknown backend '${id}' — expected one of: ${SUPPORTED_DRIVER_TARGETS.join(\", \")}`);\n process.exit(1);\n }\n out.push(id as DriverTarget);\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * `skaile install` action body. Dispatches by argument shape:\n * a positional `ref` selects pointer-only catalog install, otherwise the\n * legacy `skaile.yaml` install path runs.\n */\nasync function runInstallCommand(\n ref: string | undefined,\n opts: InstallCommandOptions,\n): Promise<void> {\n // ── Pointer-only catalog install: `skaile install <ref>` ──────────────\n if (ref !== undefined) {\n await runRefInstall(ref, opts);\n return;\n }\n\n // ── Legacy install: `skaile install` reads skaile.yaml ────────────────\n await runYamlInstall(opts);\n}\n\n/** Pointer-only catalog install path for `skaile install <ref>`. */\nasync function runRefInstall(ref: string, opts: InstallCommandOptions): Promise<void> {\n if (!isValidAssetRef(ref)) {\n logErr(`malformed asset ref '${ref}' — expected ${REF_HINT}`);\n process.exit(1);\n }\n const spinner = p.spinner();\n spinner.start(`Installing ${ref}`);\n try {\n const { openCatalogSource, openLibrary } = await import(\"../open-library.ts\");\n const catalog = await openCatalogSource({ projectDir: path.resolve(opts.projectDir) });\n // [H2] REST-framed catalogs (the default for any catalog URL other\n // than https://skaile.store) cannot serve install manifests. Detect\n // and fail clearly rather than throwing a runtime TypeError.\n if (!supportsInstallManifest(catalog)) {\n throw new Error(\n \"pointer-only install (skaile install <ref>) requires a tRPC-framed Catalog. \" +\n \"The configured catalog uses REST framing, which does not serve install \" +\n \"manifests. Set catalog.url to https://skaile.store, or catalog.framing: trpc, \" +\n \"in ~/.skaile/config.yaml.\",\n );\n }\n const library = await openLibrary();\n try {\n const result = await runPointerOnlyInstall(ref, { catalog, library });\n spinner.stop(\"Done\");\n logOk(`Installed ${colorRef(ref)}`);\n logInfo(`Path: ${S.dim(result.installPath)}`);\n logInfo(`Commit: ${S.dim(result.commitSha)}`);\n logInfo(`Files: ${S.dim(String(result.fileCount))}`);\n logInfo(\n S.dim(`Installed globally (see Path above) — use \\`skaile add ${ref}\\` to deploy into this project.`),\n );\n } finally {\n library.close();\n }\n } catch (err) {\n spinner.stop(\"Failed\");\n const msg = err instanceof Error ? err.message : String(err);\n if (/unreachable/i.test(msg)) {\n logErr(`asset uninstallable — source commit no longer available (${msg})`);\n } else {\n logErr(msg);\n }\n process.exit(1);\n }\n}\n\n/** Legacy install path for bare `skaile install` (reads skaile.yaml). */\nasync function runYamlInstall(opts: InstallCommandOptions): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n\n const backends = parseBackendFilter(opts.backend);\n // `--backend` implies `--global`.\n if (opts.global || backends) {\n await runGlobalInstall(opts, backends);\n return;\n }\n\n // Hydrate sources declared in skaile.yaml before resolving assets, so\n // freshly checked-out projects pull their source clones automatically.\n try {\n const { ensureSourcesCloned } = await import(\"../ensure-sources.ts\");\n const hydrate = ensureSourcesCloned(projectDir, { quiet: true });\n if (hydrate.cloned.length > 0) {\n logOk(`Cloned source(s): ${hydrate.cloned.join(\", \")}`);\n }\n if (hydrate.failed.length > 0) {\n logErr(`Failed to clone source(s): ${hydrate.failed.join(\", \")}`);\n }\n } catch (err) {\n logWarn(`source hydration skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const am = new AssetManager({\n projectDir,\n driverTarget: opts.target as DriverTarget,\n });\n const spinner = p.spinner();\n spinner.start(opts.locked ? \"Installing from lock file\" : \"Installing dependencies\");\n try {\n const result = await am.install({ locked: opts.locked, link: opts.link });\n spinner.stop(\"Done\");\n if (result.deployed.length > 0) {\n for (const d of result.deployed) logOk(d);\n }\n if (result.removed.length > 0) {\n for (const r of result.removed) logWarn(`Removed: ${r}`);\n }\n if (result.deployed.length === 0 && result.removed.length === 0) {\n logInfo(\"Nothing to install (already up to date).\");\n }\n if (result.missing.length > 0) {\n for (const m of result.missing) logErr(`Missing: ${m}`);\n // Partial-miss must fail the process — CI can't otherwise distinguish a\n // clean install from \"half the assets never resolved\".\n process.exitCode = 1;\n }\n if (result.lockWritten) {\n logInfo(`Lock file written: ${S.dim(\"skaile.lock.yaml\")}`);\n }\n // Report-only: surface soft deps the declared assets reference but aren't\n // present. Never a prompt — install is a batch/CI path. Skipped under\n // --locked: that mode is \"restore exactly\", so an `add` nudge would jar.\n if (!opts.locked) await reportInstalledSoftDeps(am);\n } catch (err) {\n spinner.stop(\"Failed\");\n logErr(String(err));\n process.exit(1);\n }\n}\n\n/**\n * Report (never prompt) the body-link soft deps that the declared assets\n * reference but that aren't in the project — the `install` counterpart to the\n * `add`-time soft-dep surface. `install` is a batch/CI path (often non-TTY), so\n * it only ever prints a hint: pulling stays an explicit `skaile add`. Best-effort\n * — `reportSoftDeps` swallows any index failure and returns `[]`.\n */\nexport async function reportInstalledSoftDeps(\n am: Pick<AssetManager, \"listDeclared\" | \"reportSoftDeps\">,\n onHint: (line: string) => void = (l) => logInfo(S.dim(l)),\n): Promise<void> {\n try {\n const declared = (await am.listDeclared()).map((d) => d.ref);\n if (declared.length === 0) return;\n const edges = await am.reportSoftDeps(declared);\n for (const edge of edges) onHint(formatSoftDepHint(edge));\n } catch {\n // Best-effort: a soft-dep report must never fail an install that succeeded.\n }\n}\n\n/**\n * Global cross-backend install: deploy every dep declared in the global SSOT\n * (`~/.skaile/skaile.yaml`) into each resolved global backend's dir under `~`,\n * write the global lock (`~/.skaile/skaile.lock.yaml`), then print per-backend\n * state. `backends` is the `--backend` filter (omit for the full resolved set).\n */\nasync function runGlobalInstall(\n opts: InstallCommandOptions,\n backends: DriverTarget[] | undefined,\n): Promise<void> {\n const am = new AssetManager({\n projectDir: path.resolve(opts.projectDir),\n global: true,\n backends,\n });\n const spinner = p.spinner();\n spinner.start(\"Installing global dependencies\");\n try {\n const result = await am.install({ locked: opts.locked, link: opts.link });\n spinner.stop(\"Done\");\n if (result.deployed.length > 0) for (const d of result.deployed) logOk(d);\n if (result.removed.length > 0) for (const r of result.removed) logWarn(`Removed: ${r}`);\n if (result.deployed.length === 0 && result.removed.length === 0)\n logInfo(\"Nothing to install (already up to date).\");\n if (result.missing.length > 0) {\n for (const m of result.missing) logErr(`Missing: ${m}`);\n process.exitCode = 1;\n }\n if (result.lockWritten) logInfo(`Global lock written: ${S.dim(\"~/.skaile/skaile.lock.yaml\")}`);\n\n // Per-backend reconciliation summary so a partial fan-out is visible.\n const state = am.globalState({});\n const byBackend = new Map<string, number>();\n for (const s of state)\n if (s.state === \"installed\") byBackend.set(s.backend, (byBackend.get(s.backend) ?? 0) + 1);\n for (const [backend, n] of byBackend) logInfo(`${backend}: ${n} installed`);\n } catch (err) {\n spinner.stop(\"Failed\");\n logErr(String(err));\n process.exit(1);\n }\n}\n\n/**\n * Creates the `skaile check` command.\n *\n * Scans all deployed assets for unmet dependency requirements **and** the\n * declared set for deps that resolved into the lock but never materialized, and\n * exits with code 1 if either is found. `doctor()` alone only walks *deployed*\n * assets' `requires`, so a declared dep whose bytes never landed (e.g. a\n * store-sourced `mcp-server`) used to report \"satisfied\" (#462).\n *\n * @returns Configured {@link Command} ready for `program.addCommand()`.\n * @docLink cli/commands/project#make-check-command\n */\nexport function makeCheckCommand(): Command {\n return new Command(\"check\")\n .description(\"Check for unmet requirements\")\n .option(\"--project-dir <path>\", \"Project directory\", process.cwd())\n .action(async (opts) => {\n const am = new AssetManager({ projectDir: path.resolve(opts.projectDir) });\n const issues = await am.doctor();\n // A project with no (or an unreadable) skaile.yaml has no declared set to\n // reconcile — treat it as drift-free so `check` behaves as it always has.\n let drifted: Awaited<ReturnType<typeof am.listDeclared>> = [];\n try {\n drifted = (await am.listDeclared()).filter((d) => d.state === \"drift\");\n } catch {\n // ignored — doctor() below is still authoritative for deployed assets.\n }\n if (issues.length === 0 && drifted.length === 0) {\n logOk(\"All dependencies satisfied.\");\n } else {\n for (const i of issues) {\n logErr(\n `${i.assetKind}:${i.assetName} requires ${i.depKind}:${i.depName} (${i.inRepos ? \"fixable\" : \"not found\"})`,\n );\n }\n for (const d of drifted) {\n logErr(`${d.ref} is declared and locked but not materialized — run \\`skaile install\\``);\n }\n process.exit(1);\n }\n });\n}\n\n/**\n * Creates the `skaile clean` command.\n *\n * Removes all skaile-managed assets tracked in `skaile.lock.yaml` from the\n * workspace. With `--all` also removes history, patches, repos, and the lock\n * file itself. Preserves unmanaged (manually placed) assets.\n *\n * @returns Configured {@link Command} ready for `program.addCommand()`.\n * @docLink cli/commands/project#make-clean-command\n */\nexport function makeCleanCommand(): Command {\n return new Command(\"clean\")\n .description(\"Remove all skaile-managed assets from the workspace\")\n .option(\"--all\", \"Full reset: also remove history, patches, repos, and lock file\")\n .option(\"--dry-run\", \"Show what would be removed without doing it\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"--project-dir <path>\", \"Project directory\", process.cwd())\n .option(\"--target <agent>\", \"Agent framework\", \"claude-code\")\n .action(async (opts) => {\n const am = new AssetManager({\n projectDir: path.resolve(opts.projectDir),\n driverTarget: opts.target as DriverTarget,\n });\n\n // Preview: load lock file to show what will be cleaned\n const lock = readLock(path.resolve(opts.projectDir, \"skaile.lock.yaml\"));\n\n if (!lock || Object.keys(lock.assets).length === 0) {\n logInfo(\"Nothing to clean (no skaile-managed assets found).\");\n return;\n }\n\n const assetRefs = Object.keys(lock.assets);\n console.log();\n console.log(` ${S.heading(\"Assets to remove:\")} ${S.dim(`(${assetRefs.length})`)}`);\n for (const ref of assetRefs) {\n console.log(` ${colorRef(ref)}`);\n }\n\n if (opts.all) {\n console.log();\n console.log(` ${S.heading(\"Also removing:\")}`);\n console.log(` ${S.dim(\".skaile/history.yaml\")}`);\n console.log(` ${S.dim(\".skaile/patches/\")}`);\n console.log(` ${S.dim(\"skaile.lock.yaml\")}`);\n }\n\n if (opts.dryRun) {\n console.log();\n logInfo(\"Dry run — no changes made.\");\n return;\n }\n\n if (!opts.yes) {\n const confirm = await p.confirm({ message: \"Proceed?\" });\n if (p.isCancel(confirm) || !confirm) {\n logInfo(\"Cancelled.\");\n return;\n }\n }\n\n const result = am.clean({ all: opts.all });\n\n console.log();\n for (const r of result.removed) {\n logOk(`Removed ${r}`);\n }\n for (const s of result.skipped) {\n logWarn(`Skipped ${s.ref}: ${s.reason}`);\n }\n if (result.unmanaged.length > 0) {\n console.log();\n logInfo(`Kept ${result.unmanaged.length} unmanaged asset(s):`);\n for (const u of result.unmanaged) {\n console.log(` ${S.dim(u)}`);\n }\n }\n if (opts.all) {\n console.log();\n logOk(\"Full reset complete.\");\n }\n });\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/commands/project.ts"],"names":["spinner","confirm"],"mappings":";;;;;;;;;AAmBA,IAAM,QAAA,GAAW,uEAAA;AAGjB,SAAS,gBAAgB,GAAA,EAAsB;AAC7C,EAAA,IAAI;AACF,IAAA,aAAA,CAAc,GAAG,CAAA;AACjB,IAAA,OAAO,IAAA;AAAA,EACT,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAqBO,SAAS,wBAAwB,MAAA,EAAkD;AACxF,EAAA,OACE,OAAQ,QAAgE,kBAAA,KACxE,UAAA;AAEJ;AAwCA,eAAsB,qBAAA,CACpB,KACA,IAAA,EACmC;AACnC,EAAA,IAAI,SAAA;AACJ,EAAA,IAAI;AACF,IAAA,SAAA,GAAY,cAAc,GAAG,CAAA;AAAA,EAC/B,SAAS,CAAA,EAAG;AACV,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,qBAAA,EAAwB,GAAG,CAAA,kBAAA,EAAgB,QAAQ,CAAA,EAAA,EAAK,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,KACpG;AAAA,EACF;AACA,EAAA,MAAM,QAAA,GAAW,MAAM,IAAA,CAAK,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A,EAAK;AACZ,MAAA,OAAA,CAAQ,GAAA,EAAI;AACZ,MAAA,KAAA,CAAM,sBAAsB,CAAA;AAAA,IAC9B;AAAA,EACF,CAAC,CAAA;AACL","file":"chunk-SG67QMLI.js","sourcesContent":["import path from \"node:path\";\nimport * as p from \"@clack/prompts\";\nimport { AssetManager } from \"@skaile/workspaces/asset-manager\";\nimport {\n type DriverTarget,\n parseAssetRef,\n readLock,\n SUPPORTED_DRIVER_TARGETS,\n} from \"@skaile/workspaces/core\";\nimport type { InstallManifest } from \"@skaile/workspaces/types\";\nimport { Command } from \"commander\";\nimport { colorRef, formatSoftDepHint, logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\n\n/**\n * Canonical asset-ref shape accepted by `skaile install <ref>`:\n * `kind:@<publisher>/<name>#<version>` (the `#` version sigil). Validated via\n * `parseAssetRef` so the CLI shares the single canonical grammar; the legacy\n * trailing-`@version` shape is rejected.\n */\nconst REF_HINT = \"kind:@<publisher>/<name>#<version> (e.g. skill:@skaile/use-exa#1.0.0)\";\n\n/** True when `ref` parses as a canonical asset ref. */\nfunction isValidAssetRef(ref: string): boolean {\n try {\n parseAssetRef(ref);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Minimal catalog-source surface the pointer-only install path needs.\n * `RemoteCatalogSource` satisfies this — narrowing keeps {@link runPointerOnlyInstall}\n * testable with a hand-rolled stub.\n */\nexport interface InstallManifestSource {\n getInstallManifest(ref: string): Promise<InstallManifest>;\n}\n\n/**\n * Capability check: is this catalog source able to serve install manifests?\n *\n * `openCatalogSource` returns a `RemoteCatalogSource | RestCatalogSource`.\n * Only the tRPC-framed `RemoteCatalogSource` implements `getInstallManifest`;\n * the REST-framed `RestCatalogSource` (the default for any catalog URL other\n * than `https://skaile.store`) does not. Calling it unconditionally would be a\n * runtime `TypeError`, so the pointer-only install path must capability-detect\n * first and fail with a clear, actionable message.\n */\nexport function supportsInstallManifest(source: unknown): source is InstallManifestSource {\n return (\n typeof (source as { getInstallManifest?: unknown } | null | undefined)?.getInstallManifest ===\n \"function\"\n );\n}\n\n/**\n * Minimal library surface the pointer-only install path needs.\n * `LocalIndex` satisfies this.\n */\nexport interface InstallLibrary {\n install(manifest: InstallManifest): Promise<{ installPath: string }>;\n}\n\n/**\n * Result of a pointer-only catalog install.\n */\nexport interface PointerOnlyInstallResult {\n /** Absolute path the verified asset bytes were written to. */\n installPath: string;\n /** The pinned upstream commit SHA the asset was fetched at. */\n commitSha: string;\n /** Number of files in the install manifest. */\n fileCount: number;\n}\n\n/**\n * Pointer-only catalog install — the `skaile install <ref>` code path.\n *\n * 1. Resolves the pointer-only {@link InstallManifest} from the Catalog.\n * 2. Hands it to the library, which fetches each file's bytes directly from\n * the upstream repo at the pinned commit, verifies every per-file SHA256\n * plus the composite SHA256, and only then writes the verified files.\n *\n * Both dependencies are injected so the function is unit-testable without a\n * network round-trip. In production the CLI passes a `RemoteCatalogSource`\n * and a `LocalIndex`.\n *\n * @param ref - Asset ref (`<publisher>/<name>@<version>`, optional leading `@`).\n * @param deps - Injected catalog source + library.\n * @returns The install path, pinned commit SHA, and file count.\n * @throws When the ref is malformed, the manifest cannot be resolved, or any\n * hash verification fails. The underlying error message is surfaced as-is.\n */\nexport async function runPointerOnlyInstall(\n ref: string,\n deps: { catalog: InstallManifestSource; library: InstallLibrary },\n): Promise<PointerOnlyInstallResult> {\n let requested: ReturnType<typeof parseAssetRef>;\n try {\n requested = parseAssetRef(ref);\n } catch (e) {\n throw new Error(\n `malformed asset ref '${ref}' — expected ${REF_HINT}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n const manifest = await deps.catalog.getInstallManifest(ref);\n // [M1] Identity check: the catalog must not install a different asset than\n // requested. Compare the PARSED refs (kind/publisher/name/pin) so equivalent\n // spellings (optional `kind:`, default `skill`) are treated as the same ref.\n const got = parseAssetRef(manifest.ref);\n if (\n got.kind !== requested.kind ||\n got.publisher !== requested.publisher ||\n got.name !== requested.name ||\n got.pin !== requested.pin\n ) {\n throw new Error(\n `catalog identity mismatch: requested '${ref}' but the catalog returned a manifest for '${manifest.ref}'`,\n );\n }\n const { installPath } = await deps.library.install(manifest);\n return {\n installPath,\n commitSha: manifest.source.commitSha,\n fileCount: manifest.files.length,\n };\n}\n\n/**\n * Creates the `skaile install` command.\n *\n * Two modes, selected by argument shape:\n *\n * - `skaile install` (no positional arg) — reads `skaile.yaml` and deploys all\n * declared assets (and their transitive dependencies) to the configured\n * driver target directory. Supports `--locked` for CI-mode install from a\n * lock file.\n * - `skaile install <publisher>/<name>@<version>` — pointer-only catalog\n * install: resolves the pointer-only install manifest from the configured\n * Catalog, fetches each file's bytes directly from the upstream repo at the\n * pinned commit, verifies every per-file + the composite SHA256, then writes\n * the verified files into the local Library.\n *\n * @returns Configured {@link Command} ready for `program.addCommand()`.\n * @docLink cli/commands/project#make-install-command\n */\nexport function makeInstallCommand(): Command {\n return new Command(\"install\")\n .description(`Install dependencies from skaile.yaml, or a single asset by ref (${REF_HINT})`)\n .argument(\"[ref]\", `Asset ref to install from the Catalog (${REF_HINT})`)\n .option(\"--locked\", \"Install from lock file (CI mode — fails on drift)\")\n .option(\"--project-dir <path>\", \"Project directory\", process.cwd())\n .option(\"--target <agent>\", \"Agent framework\", \"claude-code\")\n .option(\n \"--global\",\n \"Install the global SSOT (~/.skaile/skaile.yaml), fanning out to every global backend\",\n )\n .option(\n \"--backend <ids>\",\n \"Comma-separated global backends to install into (default: all resolved); implies --global\",\n )\n .option(\n \"--link\",\n \"symlink local-path assets instead of copying (dev loop; machine-local, not for committing)\",\n )\n .action(runInstallCommand);\n}\n\n/** Options shape accepted by the `skaile install` command action. */\ninterface InstallCommandOptions {\n locked?: boolean;\n projectDir: string;\n target: string;\n global?: boolean;\n backend?: string;\n link?: boolean;\n}\n\n/**\n * Parse a `--backend a,b` value into validated {@link DriverTarget}s, exiting on\n * an unknown id. Returns `undefined` when the flag is absent (resolve the full\n * global set instead).\n */\nfunction parseBackendFilter(raw: string | undefined): DriverTarget[] | undefined {\n if (!raw) return undefined;\n const ids = raw\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n const out: DriverTarget[] = [];\n for (const id of ids) {\n if (!(SUPPORTED_DRIVER_TARGETS as string[]).includes(id)) {\n logErr(`unknown backend '${id}' — expected one of: ${SUPPORTED_DRIVER_TARGETS.join(\", \")}`);\n process.exit(1);\n }\n out.push(id as DriverTarget);\n }\n return out.length > 0 ? out : undefined;\n}\n\n/**\n * `skaile install` action body. Dispatches by argument shape:\n * a positional `ref` selects pointer-only catalog install, otherwise the\n * legacy `skaile.yaml` install path runs.\n */\nasync function runInstallCommand(\n ref: string | undefined,\n opts: InstallCommandOptions,\n): Promise<void> {\n // ── Pointer-only catalog install: `skaile install <ref>` ──────────────\n if (ref !== undefined) {\n await runRefInstall(ref, opts);\n return;\n }\n\n // ── Legacy install: `skaile install` reads skaile.yaml ────────────────\n await runYamlInstall(opts);\n}\n\n/** Pointer-only catalog install path for `skaile install <ref>`. */\nasync function runRefInstall(ref: string, opts: InstallCommandOptions): Promise<void> {\n if (!isValidAssetRef(ref)) {\n logErr(`malformed asset ref '${ref}' — expected ${REF_HINT}`);\n process.exit(1);\n }\n const spinner = p.spinner();\n spinner.start(`Installing ${ref}`);\n try {\n const { openCatalogSource, openLibrary } = await import(\"../open-library.ts\");\n const catalog = await openCatalogSource({ projectDir: path.resolve(opts.projectDir) });\n // [H2] REST-framed catalogs (the default for any catalog URL other\n // than https://skaile.store) cannot serve install manifests. Detect\n // and fail clearly rather than throwing a runtime TypeError.\n if (!supportsInstallManifest(catalog)) {\n throw new Error(\n \"pointer-only install (skaile install <ref>) requires a tRPC-framed Catalog. \" +\n \"The configured catalog uses REST framing, which does not serve install \" +\n \"manifests. Set catalog.url to https://skaile.store, or catalog.framing: trpc, \" +\n \"in ~/.skaile/config.yaml.\",\n );\n }\n const library = await openLibrary();\n try {\n const result = await runPointerOnlyInstall(ref, { catalog, library });\n spinner.stop(\"Done\");\n logOk(`Installed ${colorRef(ref)}`);\n logInfo(`Path: ${S.dim(result.installPath)}`);\n logInfo(`Commit: ${S.dim(result.commitSha)}`);\n logInfo(`Files: ${S.dim(String(result.fileCount))}`);\n logInfo(\n S.dim(`Installed globally (see Path above) — use \\`skaile add ${ref}\\` to deploy into this project.`),\n );\n } finally {\n library.close();\n }\n } catch (err) {\n spinner.stop(\"Failed\");\n const msg = err instanceof Error ? err.message : String(err);\n if (/unreachable/i.test(msg)) {\n logErr(`asset uninstallable — source commit no longer available (${msg})`);\n } else {\n logErr(msg);\n }\n process.exit(1);\n }\n}\n\n/** Legacy install path for bare `skaile install` (reads skaile.yaml). */\nasync function runYamlInstall(opts: InstallCommandOptions): Promise<void> {\n const projectDir = path.resolve(opts.projectDir);\n\n const backends = parseBackendFilter(opts.backend);\n // `--backend` implies `--global`.\n if (opts.global || backends) {\n await runGlobalInstall(opts, backends);\n return;\n }\n\n // Hydrate sources declared in skaile.yaml before resolving assets, so\n // freshly checked-out projects pull their source clones automatically.\n try {\n const { ensureSourcesCloned } = await import(\"../ensure-sources.ts\");\n const hydrate = ensureSourcesCloned(projectDir, { quiet: true });\n if (hydrate.cloned.length > 0) {\n logOk(`Cloned source(s): ${hydrate.cloned.join(\", \")}`);\n }\n if (hydrate.failed.length > 0) {\n logErr(`Failed to clone source(s): ${hydrate.failed.join(\", \")}`);\n }\n } catch (err) {\n logWarn(`source hydration skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n\n const am = new AssetManager({\n projectDir,\n driverTarget: opts.target as DriverTarget,\n });\n const spinner = p.spinner();\n spinner.start(opts.locked ? \"Installing from lock file\" : \"Installing dependencies\");\n try {\n const result = await am.install({ locked: opts.locked, link: opts.link });\n spinner.stop(\"Done\");\n if (result.deployed.length > 0) {\n for (const d of result.deployed) logOk(d);\n }\n if (result.removed.length > 0) {\n for (const r of result.removed) logWarn(`Removed: ${r}`);\n }\n if (result.deployed.length === 0 && result.removed.length === 0) {\n logInfo(\"Nothing to install (already up to date).\");\n }\n if (result.missing.length > 0) {\n for (const m of result.missing) logErr(`Missing: ${m}`);\n // Partial-miss must fail the process — CI can't otherwise distinguish a\n // clean install from \"half the assets never resolved\".\n process.exitCode = 1;\n }\n if (result.lockWritten) {\n logInfo(`Lock file written: ${S.dim(\"skaile.lock.yaml\")}`);\n }\n // Report-only: surface soft deps the declared assets reference but aren't\n // present. Never a prompt — install is a batch/CI path. Skipped under\n // --locked: that mode is \"restore exactly\", so an `add` nudge would jar.\n if (!opts.locked) await reportInstalledSoftDeps(am);\n } catch (err) {\n spinner.stop(\"Failed\");\n logErr(String(err));\n process.exit(1);\n }\n}\n\n/**\n * Report (never prompt) the body-link soft deps that the declared assets\n * reference but that aren't in the project — the `install` counterpart to the\n * `add`-time soft-dep surface. `install` is a batch/CI path (often non-TTY), so\n * it only ever prints a hint: pulling stays an explicit `skaile add`. Best-effort\n * — `reportSoftDeps` swallows any index failure and returns `[]`.\n */\nexport async function reportInstalledSoftDeps(\n am: Pick<AssetManager, \"listDeclared\" | \"reportSoftDeps\">,\n onHint: (line: string) => void = (l) => logInfo(S.dim(l)),\n): Promise<void> {\n try {\n const declared = (await am.listDeclared()).map((d) => d.ref);\n if (declared.length === 0) return;\n const edges = await am.reportSoftDeps(declared);\n for (const edge of edges) onHint(formatSoftDepHint(edge));\n } catch {\n // Best-effort: a soft-dep report must never fail an install that succeeded.\n }\n}\n\n/**\n * Global cross-backend install: deploy every dep declared in the global SSOT\n * (`~/.skaile/skaile.yaml`) into each resolved global backend's dir under `~`,\n * write the global lock (`~/.skaile/skaile.lock.yaml`), then print per-backend\n * state. `backends` is the `--backend` filter (omit for the full resolved set).\n */\nasync function runGlobalInstall(\n opts: InstallCommandOptions,\n backends: DriverTarget[] | undefined,\n): Promise<void> {\n const am = new AssetManager({\n projectDir: path.resolve(opts.projectDir),\n global: true,\n backends,\n });\n const spinner = p.spinner();\n spinner.start(\"Installing global dependencies\");\n try {\n const result = await am.install({ locked: opts.locked, link: opts.link });\n spinner.stop(\"Done\");\n if (result.deployed.length > 0) for (const d of result.deployed) logOk(d);\n if (result.removed.length > 0) for (const r of result.removed) logWarn(`Removed: ${r}`);\n if (result.deployed.length === 0 && result.removed.length === 0)\n logInfo(\"Nothing to install (already up to date).\");\n if (result.missing.length > 0) {\n for (const m of result.missing) logErr(`Missing: ${m}`);\n process.exitCode = 1;\n }\n if (result.lockWritten) logInfo(`Global lock written: ${S.dim(\"~/.skaile/skaile.lock.yaml\")}`);\n\n // Per-backend reconciliation summary so a partial fan-out is visible.\n const state = am.globalState({});\n const byBackend = new Map<string, number>();\n for (const s of state)\n if (s.state === \"installed\") byBackend.set(s.backend, (byBackend.get(s.backend) ?? 0) + 1);\n for (const [backend, n] of byBackend) logInfo(`${backend}: ${n} installed`);\n } catch (err) {\n spinner.stop(\"Failed\");\n logErr(String(err));\n process.exit(1);\n }\n}\n\n/**\n * Creates the `skaile check` command.\n *\n * Scans all deployed assets for unmet dependency requirements **and** the\n * declared set for deps that resolved into the lock but never materialized, and\n * exits with code 1 if either is found. `doctor()` alone only walks *deployed*\n * assets' `requires`, so a declared dep whose bytes never landed (e.g. a\n * store-sourced `mcp-server`) used to report \"satisfied\" (#462).\n *\n * @returns Configured {@link Command} ready for `program.addCommand()`.\n * @docLink cli/commands/project#make-check-command\n */\nexport function makeCheckCommand(): Command {\n return new Command(\"check\")\n .description(\"Check for unmet requirements\")\n .option(\"--project-dir <path>\", \"Project directory\", process.cwd())\n .action(async (opts) => {\n const am = new AssetManager({ projectDir: path.resolve(opts.projectDir) });\n const issues = await am.doctor();\n // A project with no (or an unreadable) skaile.yaml has no declared set to\n // reconcile — treat it as drift-free so `check` behaves as it always has.\n let drifted: Awaited<ReturnType<typeof am.listDeclared>> = [];\n try {\n drifted = (await am.listDeclared()).filter((d) => d.state === \"drift\");\n } catch {\n // ignored — doctor() below is still authoritative for deployed assets.\n }\n if (issues.length === 0 && drifted.length === 0) {\n logOk(\"All dependencies satisfied.\");\n } else {\n for (const i of issues) {\n logErr(\n `${i.assetKind}:${i.assetName} requires ${i.depKind}:${i.depName} (${i.inRepos ? \"fixable\" : \"not found\"})`,\n );\n }\n for (const d of drifted) {\n logErr(`${d.ref} is declared and locked but not materialized — run \\`skaile install\\``);\n }\n process.exit(1);\n }\n });\n}\n\n/**\n * Creates the `skaile clean` command.\n *\n * Removes all skaile-managed assets tracked in `skaile.lock.yaml` from the\n * workspace. With `--all` also removes history, patches, repos, and the lock\n * file itself. Preserves unmanaged (manually placed) assets.\n *\n * @returns Configured {@link Command} ready for `program.addCommand()`.\n * @docLink cli/commands/project#make-clean-command\n */\nexport function makeCleanCommand(): Command {\n return new Command(\"clean\")\n .description(\"Remove all skaile-managed assets from the workspace\")\n .option(\"--all\", \"Full reset: also remove history, patches, repos, and lock file\")\n .option(\"--dry-run\", \"Show what would be removed without doing it\")\n .option(\"-y, --yes\", \"Skip confirmation prompt\")\n .option(\"--project-dir <path>\", \"Project directory\", process.cwd())\n .option(\"--target <agent>\", \"Agent framework\", \"claude-code\")\n .action(async (opts) => {\n const am = new AssetManager({\n projectDir: path.resolve(opts.projectDir),\n driverTarget: opts.target as DriverTarget,\n });\n\n // Preview: load lock file to show what will be cleaned\n const lock = readLock(path.resolve(opts.projectDir, \"skaile.lock.yaml\"));\n\n if (!lock || Object.keys(lock.assets).length === 0) {\n logInfo(\"Nothing to clean (no skaile-managed assets found).\");\n return;\n }\n\n const assetRefs = Object.keys(lock.assets);\n console.log();\n console.log(` ${S.heading(\"Assets to remove:\")} ${S.dim(`(${assetRefs.length})`)}`);\n for (const ref of assetRefs) {\n console.log(` ${colorRef(ref)}`);\n }\n\n if (opts.all) {\n console.log();\n console.log(` ${S.heading(\"Also removing:\")}`);\n console.log(` ${S.dim(\".skaile/history.yaml\")}`);\n console.log(` ${S.dim(\".skaile/patches/\")}`);\n console.log(` ${S.dim(\"skaile.lock.yaml\")}`);\n }\n\n if (opts.dryRun) {\n console.log();\n logInfo(\"Dry run — no changes made.\");\n return;\n }\n\n if (!opts.yes) {\n const confirm = await p.confirm({ message: \"Proceed?\" });\n if (p.isCancel(confirm) || !confirm) {\n logInfo(\"Cancelled.\");\n return;\n }\n }\n\n const result = am.clean({ all: opts.all });\n\n console.log();\n for (const r of result.removed) {\n logOk(`Removed ${r}`);\n }\n for (const s of result.skipped) {\n logWarn(`Skipped ${s.ref}: ${s.reason}`);\n }\n if (result.unmanaged.length > 0) {\n console.log();\n logInfo(`Kept ${result.unmanaged.length} unmanaged asset(s):`);\n for (const u of result.unmanaged) {\n console.log(` ${S.dim(u)}`);\n }\n }\n if (opts.all) {\n console.log();\n logOk(\"Full reset complete.\");\n }\n });\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { resolveSkWorkspaceConfig, readLinks, getGlobalCacheDir, sourceCacheKey } from './chunk-RD6MMBHQ.js';
1
+ import { resolveSkWorkspaceConfig, readLinks, getGlobalCacheDir, sourceCacheKey } from './chunk-IP3GXHOB.js';
2
2
  import { scanDirectory, tryWithFsDeadline } from './chunk-VQ4P7UYE.js';
3
3
  import { existsSync, readFileSync } from 'fs';
4
4
  import { lstat, stat } from 'fs/promises';
@@ -219,5 +219,5 @@ function findCatalogEntry(entries, query) {
219
219
  }
220
220
 
221
221
  export { FACTORY_ASSETS_REPO_NAME, factoryAssetRoots, resolveFactoryAssetsRoot, resolveFactoryAssetsRootOrNull, resolvePackagedAssetsDir, resolveRuntimeAssets, resolveWorkspacesPackageRoot };
222
- //# sourceMappingURL=chunk-KBXYT5HD.js.map
223
- //# sourceMappingURL=chunk-KBXYT5HD.js.map
222
+ //# sourceMappingURL=chunk-SH572OBN.js.map
223
+ //# sourceMappingURL=chunk-SH572OBN.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../core/src/runtime-assets.ts"],"names":["resolvePath","require"],"mappings":";;;;;;;;AAsDA,SAAS,sBACP,OAAA,EACmC;AACnC,EAAA,MAAM,aAAa,iBAAA,EAAkB;AACrC,EAAA,MAAM,MAAyC,EAAC;AAChD,EAAA,KAAA,MAAW,CAAA,IAAK,OAAA,I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AAe,IAAI,CAAA,2BAAA,CAAA;AAC5B;AAEA,SAAS,gBAAA,CACP,SACA,KAAA,EACiC;AACjC,EAAA,IAAI,MAAM,IAAA,EAAM;AACd,IAAA,OAAO,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,KAAA,CAAM,IAAA,IAAQ,CAAA,CAAE,IAAA,KAAS,KAAA,CAAM,IAAI,CAAA;AAAA,EAC3E;AACA,EAAA,MAAM,OAAA,GAAU,QAAQ,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,IAAA,KAAS,MAAM,IAAI,CAAA;AAC3D,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,QAAQ,CAAC,CAAA;AAE1C,EAAA,OAAO,MAAA;AACT","file":"chunk-KBXYT5HD.js","sourcesContent":["/**\n * Runtime asset resolution — read `skaile.yaml`, scan all declared repositories\n * (including the built-in `factory-assets/` directory as an implicit default),\n * and produce a unified view of connector catalog entries plus the implicit refs\n * that the `skaile.yaml` `connectors:` section adds to the dependency graph.\n *\n * This module is the single source of truth for \"which connectors does this\n * project see at runtime, and where do their implementations live on disk\".\n * Both the runner (serve, REPL, flow) and the platform's mid-session\n * `add_resource` flow consume `RuntimeAssetsResult.catalogEntries` and pass\n * it into `ConnectorManager` for catalog-based resolution.\n *\n * `factory-assets/` is the single first-party content tree (built-in connectors\n * + first-party skills + bundles) shipped inside the `@skaile/workspaces`\n * package — not a standalone package.\n *\n * It resolves to an **ordered list of roots** ({@link factoryAssetRoots}), not a\n * single dir. The bundled tree is always the baseline; an optional\n * `SKAILE_FACTORY_ASSETS_DIR` (legacy: `SKAILE_BASE_ASSETS_DIR`) is layered\n * **in front** as an additive override source — the agent container points it at\n * `/app/factory-assets/` (or a bind-mounted host dir) to ship updated skills /\n * flows / bundles / connector manifests without rebuilding the image. The two\n * roots resolve uniformly across every consumer (connector catalog scan, skill /\n * flow / completion discovery, the asset-manager factory source):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir, when set and existing (override layer).\n * 2. the bundled tree via {@link resolvePackagedAssetsDir} — the in-repo source\n * `packages/workspaces/factory-assets/` during dev, else the published\n * `dist/factory-assets/` after install (always-present baseline).\n *\n * Override semantics are **env-first**: on a name conflict the env root wins and\n * the bundled root fills the rest. Connector *code* still loads via the package's\n * static `exports` map, so the env root can override/add skills, flows, bundles,\n * and connector **manifests/metadata**, but cannot ship a new executable\n * connector — its `.js` is not on the package's import graph.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { lstat, stat } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { tryWithFsDeadline } from \"./fs-deadline.js\";\nimport { scanDirectory } from \"./manifest.js\";\nimport type { CatalogEntry } from \"./models.js\";\nimport { getGlobalCacheDir, readLinks, sourceCacheKey } from \"./repo-manager.js\";\nimport type { SourceDeclaration, SourceEntry } from \"./workspace-config.js\";\nimport { resolveSkWorkspaceConfig } from \"./workspace-config.js\";\n\n/**\n * Map declared `sources[]` to internal `SourceDeclaration`s keyed by the\n * collision-free {@link sourceCacheKey} (`<host>/<owner>/<repo>`), pointing at\n * the unified machine-cache clone path (`getGlobalCacheDir()/<key>/`). Keyed by\n * the same function every other cache writer/reader uses so the path resolves.\n */\nfunction sourcesToDeclarations(\n sources: SourceEntry[] | undefined,\n): Record<string, SourceDeclaration> {\n const sourcesDir = getGlobalCacheDir();\n const out: Record<string, SourceDeclaration> = {};\n for (const s of sources ?? []) {\n const key = sourceCacheKey(s.url);\n if (out[key]) continue;\n out[key] = { path: join(sourcesDir, key), url: s.url, branch: s.pin };\n }\n return out;\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/**\n * Catalog entry filtered to mount/connector kinds. Same shape as `CatalogEntry`.\n * @docLink packages/core/concepts#runtime-catalog-entry\n */\nexport type RuntimeCatalogEntry = CatalogEntry;\n\n/**\n * Implicit catalog reference derived from a `connectors:` declaration in `skaile.yaml`.\n * Each connector driver becomes an implicit ref that must be resolved in the catalog.\n * @docLink packages/core/concepts#runtime-asset-ref\n */\nexport interface RuntimeAssetRef {\n kind: \"connector\";\n /** Driver name — matches `RuntimeCatalogEntry.name`. */\n name: string;\n /** Source declaration id from `skaile.yaml`. */\n declarationId: string;\n}\n\n/**\n * Aggregated npm packages required by all resolved mount/connector adapters.\n * Populated from `metadata.npm_deps` in each matched catalog entry.\n * @docLink packages/core/concepts#runtime-npm-deps\n */\nexport interface RuntimeNpmDeps {\n required: string[];\n optional: string[];\n}\n\n/**\n * Non-fatal warning emitted during `resolveRuntimeAssets` when a repo is unavailable\n * or a driver is not found in any catalog.\n * @docLink packages/core/concepts#runtime-asset-warning\n */\nexport interface RuntimeAssetWarning {\n /** Stable code for filtering / structured logging. */\n code: \"missing_driver\" | \"repo_unavailable\" | \"invalid_repo_decl\";\n message: string;\n /** Declaration id when applicable. */\n declarationId?: string;\n /** Driver / repository name when applicable. */\n name?: string;\n}\n\n/**\n * Repository name used for the implicit built-in `factory-assets` catalog entry\n * (the in-package connector tree).\n * @docLink packages/core/concepts#factory-assets-repo-name\n */\nexport const FACTORY_ASSETS_REPO_NAME = \"factory-assets\";\n\n/**\n * Repository name for the optional `SKAILE_FACTORY_ASSETS_DIR` override layer,\n * scanned ahead of (and overriding) the bundled {@link FACTORY_ASSETS_REPO_NAME}.\n */\nconst FACTORY_ASSETS_OVERRIDE_REPO_NAME = \"factory-assets:override\";\n\n/**\n * Result of `resolveRuntimeAssets`.\n * The same object is mutated in place by `refresh()`, allowing callers to hold\n * a stable reference and observe updates after a new repository is cloned or\n * a driver is installed mid-session.\n * @docLink packages/core/concepts#runtime-assets-result\n */\nexport interface RuntimeAssetsResult {\n catalogEntries: RuntimeCatalogEntry[];\n implicitRefs: RuntimeAssetRef[];\n requiredNpmDeps: RuntimeNpmDeps;\n warnings: RuntimeAssetWarning[];\n /** Re-scan repositories and re-derive implicit refs. Mutates in place. */\n refresh(): Promise<void>;\n /**\n * Catalog lookup. When `kind` is omitted and multiple entries share the\n * `name`, returns `undefined` (caller must disambiguate).\n */\n findEntry(query: { kind?: \"connector\"; name: string }): RuntimeCatalogEntry | undefined;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Resolve all runtime assets visible to a project by scanning declared repositories.\n *\n * Reads `skaile.yaml`, scans every declared repository (plus the implicit\n * built-in `factory-assets` repo), and derives implicit refs from `mounts:` /\n * `connectors:` declarations. Does not clone or install anything — purely a\n * read-only scan of what is already on disk. URL-only repositories that have\n * not been cloned yet are reported as `repo_unavailable` warnings.\n *\n * @param projectDir - Absolute path to the project workspace root\n * @returns `RuntimeAssetsResult` with catalog entries, implicit refs, npm deps, and warnings\n * @docLink packages/core/concepts#resolve-runtime-assets\n */\nexport async function resolveRuntimeAssets(projectDir: string): Promise<RuntimeAssetsResult> {\n const result: RuntimeAssetsResult = {\n catalogEntries: [],\n implicitRefs: [],\n requiredNpmDeps: { required: [], optional: [] },\n warnings: [],\n refresh: async () => {\n await populate(projectDir, result);\n },\n findEntry: (query) => findCatalogEntry(result.catalogEntries, query),\n };\n\n await populate(projectDir, result);\n return result;\n}\n\n/**\n * Resolve the ordered list of on-disk roots for the built-in `factory-assets`\n * tree (built-in connectors + first-party skills + bundles). This is the single\n * shared resolver every consumer goes through, so the env override and the\n * bundled baseline are honoured uniformly.\n *\n * Order (env-first = override-wins):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir (legacy: `SKAILE_BASE_ASSETS_DIR`),\n * when set and existing — an additive override layer.\n * 2. {@link resolvePackagedAssetsDir} — the bundled tree (in-repo source in dev,\n * `dist/factory-assets/` after install). Always-present baseline.\n *\n * Returns `[]` only when the package cannot be located at all. De-duplicated, so\n * pointing the env var at the bundled dir collapses to one root.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function factoryAssetRoots(): string[] {\n const roots: string[] = [];\n const envDir = process.env.SKAILE_FACTORY_ASSETS_DIR ?? process.env.SKAILE_BASE_ASSETS_DIR;\n // Deliberately still synchronous after #454: both candidates are\n // container-local (the image's `/app/factory-assets/`, or the installed\n // package tree resolved by `resolvePackagedAssetsDir`), never the FUSE\n // workspace mount. The mount-reachable probes on this module's scan path —\n // the project-relative `sources[].path` candidates in `resolveRepoDir` — are\n // async and deadline-bounded.\n if (envDir && existsSync(envDir)) roots.push(resolvePath(envDir));\n const bundled = resolvePackagedAssetsDir(\"factory-assets\");\n if (bundled) roots.push(bundled);\n return [...new Set(roots)];\n}\n\n/**\n * Resolve the primary on-disk root of the `factory-assets` tree — the first of\n * {@link factoryAssetRoots} (the env override when set, else the bundled tree).\n * Prefer {@link factoryAssetRoots} when you need to scan every layer; this\n * single-dir form is for callers that want one canonical path.\n *\n * @returns Absolute path to the highest-precedence `factory-assets` directory\n * @throws When no root can be located\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolveFactoryAssetsRoot(): string {\n const hit = resolveFactoryAssetsRootOrNull();\n if (hit) return hit;\n\n throw new Error(\n `Cannot resolve the factory-assets directory. ` +\n `Set SKAILE_FACTORY_ASSETS_DIR to the on-disk path, ` +\n `ensure @skaile/workspaces is installed, ` +\n `or run from within the @skaile/workspaces package tree.`,\n );\n}\n\n/**\n * Non-throwing variant of {@link resolveFactoryAssetsRoot}: the same\n * env-then-packaged resolution tiers, returning `null` instead of throwing when\n * none locate the directory. Callers that treat a missing factory tree as a\n * soft \"not present\" (e.g. the asset-manager's implicit-source injection) MUST\n * use this so they honour the `SKAILE_FACTORY_ASSETS_DIR` container override\n * identically to the runtime path.\n */\nexport function resolveFactoryAssetsRootOrNull(): string | null {\n return factoryAssetRoots()[0] ?? null;\n}\n\n/**\n * Resolve the `@skaile/workspaces` package root — the directory containing its\n * `package.json`. Tries `require.resolve` first (works when installed as a\n * dependency *and* in-repo via the self-reference), then walks upward from this\n * module looking for a `package.json` whose `name` is `@skaile/workspaces`\n * (bounded to 8 levels). Returns `null` when neither locates it.\n *\n * The single source of truth for finding content shipped inside the package —\n * the unified `factory-assets/` tree (built-in connectors + first-party skills\n * + bundles) resolves through {@link resolvePackagedAssetsDir} on top of this.\n *\n * Memoized: the package location is immutable for the process lifetime, but\n * this sits on the CLI hot path (every `findSkills` / flow / completion call\n * funnels through here), so the `require.resolve` + upward `package.json` walk\n * runs once. `undefined` = not yet computed.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nlet workspacesPackageRootCache: string | null | undefined;\n\nexport function resolveWorkspacesPackageRoot(): string | null {\n if (workspacesPackageRootCache !== undefined) return workspacesPackageRootCache;\n workspacesPackageRootCache = computeWorkspacesPackageRoot();\n return workspacesPackageRootCache;\n}\n\nfunction computeWorkspacesPackageRoot(): string | null {\n try {\n const require = createRequire(import.meta.url);\n return dirname(require.resolve(\"@skaile/workspaces/package.json\"));\n } catch {\n // Fall through to the workspace walk.\n }\n let dir: string;\n try {\n dir = dirname(fileURLToPath(import.meta.url));\n } catch {\n return null;\n }\n for (let i = 0; i < 8; i++) {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n if (pkg.name === \"@skaile/workspaces\") return dir;\n } catch {\n // Ignore malformed package.json and keep walking.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/**\n * Locate a content-asset directory inside the package. Prefers the in-repo\n * **source** dir `<pkgRoot>/<subdir>` when present — in a dev checkout it is the\n * full tree (e.g. `factory-assets/` keeps the connector `.ts` entry files that\n * `dist/` does not) — then the published `dist/<subdir>` copy (what\n * `files: [\"dist\"]` ships, the only one present after `npm i`). Returns `null`\n * when neither exists.\n *\n * `factory-assets/` resolves to the source tree in dev (code + skills + bundles)\n * and to `dist/factory-assets` post-install (compiled connectors + copied\n * manifests/skills/bundles).\n *\n * @param subdir - `\"factory-assets\"` | …\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolvePackagedAssetsDir(subdir: string): string | null {\n const root = resolveWorkspacesPackageRoot();\n if (!root) return null;\n for (const cand of [join(root, subdir), join(root, \"dist\", subdir)]) {\n if (existsSync(cand)) return cand;\n }\n return null;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\nasync function populate(projectDir: string, target: RuntimeAssetsResult): Promise<void> {\n target.catalogEntries = [];\n target.implicitRefs = [];\n target.requiredNpmDeps = { required: [], optional: [] };\n target.warnings = [];\n\n const config = resolveSkWorkspaceConfig(projectDir);\n // Connector catalog scan runs over the project's declared sources[] (resolved\n // to their machine-cache clone paths) plus the implicit factory-assets repo.\n const repositories = buildEffectiveRepositories(sourcesToDeclarations(config.sources));\n const links = readLinks(projectDir);\n\n // Scan each repository for connector entries.\n for (const [name, decl] of Object.entries(repositories)) {\n const repoDir = await resolveRepoDir(name, decl, projectDir, links);\n if (!repoDir) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: repoUnavailableMessage(name, decl),\n });\n continue;\n }\n try {\n // Both factory layers carry the same `factory-assets` provenance — the\n // override repo is an internal scan-order device, not a distinct source.\n const repoName = name === FACTORY_ASSETS_OVERRIDE_REPO_NAME ? FACTORY_ASSETS_REPO_NAME : name;\n const scanned = await scanDirectory(repoDir, repoName);\n const entries = scanned.filter((e) => e.kind === \"connector\");\n target.catalogEntries.push(...entries);\n } catch (err) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: `Failed to scan repository \"${name}\" at ${repoDir}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n });\n }\n }\n\n // De-duplicate by (kind, name), keeping the first occurrence. Scan order is\n // declared sources → env override → bundled baseline, so an env-supplied\n // connector manifest overrides the bundled one and the bundled one fills the\n // rest (the override layer can refresh built-in manifests in place).\n const seen = new Set<string>();\n target.catalogEntries = target.catalogEntries.filter((e) => {\n const key = `${e.kind}:${e.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n // Derive implicit refs from skaile.yaml connectors.\n for (const c of config.connectors ?? []) {\n target.implicitRefs.push({ kind: \"connector\", name: c.driver, declarationId: c.id });\n }\n\n // Validate refs and aggregate npm deps.\n const requiredSet = new Set<string>();\n const optionalSet = new Set<string>();\n for (const ref of target.implicitRefs) {\n const entry = findCatalogEntry(target.catalogEntries, ref);\n if (!entry) {\n target.warnings.push({\n code: \"missing_driver\",\n declarationId: ref.declarationId,\n name: ref.name,\n message:\n `Unknown ${ref.kind} driver \"${ref.name}\" referenced by ${ref.kind} \"${ref.declarationId}\". ` +\n `Run \\`skaile ${ref.kind} catalog\\` to see available drivers, ` +\n `or declare a repository in skaile.yaml that provides this driver.`,\n });\n continue;\n }\n const npm = (entry.metadata?.npm_deps ?? {}) as { required?: string[]; optional?: string[] };\n for (const p of npm.required ?? []) requiredSet.add(p);\n for (const p of npm.optional ?? []) optionalSet.add(p);\n }\n target.requiredNpmDeps.required = [...requiredSet];\n target.requiredNpmDeps.optional = [...optionalSet];\n}\n\n/**\n * Build the effective `repositories` map: caller's declarations first, then the\n * implicit built-in `factory-assets` repos. Each {@link factoryAssetRoots} layer\n * becomes its own repo, the env override inserted **before** the bundled\n * baseline so its connector entries win on the first-match dedup downstream.\n * When the package cannot be located at all, a path-less sentinel under\n * {@link FACTORY_ASSETS_REPO_NAME} drives the `repo_unavailable` warning.\n */\nfunction buildEffectiveRepositories(\n declared: Record<string, SourceDeclaration> | undefined,\n): Record<string, SourceDeclaration> {\n const result: Record<string, SourceDeclaration> = { ...(declared ?? {}) };\n const roots = factoryAssetRoots();\n if (roots.length === 0) {\n // Surface as a warning during scan rather than throwing here — let the\n // caller decide whether factory-assets is required. resolveRepoDir() /\n // repoUnavailableMessage re-discover the failure and emit it.\n if (!result[FACTORY_ASSETS_REPO_NAME]) result[FACTORY_ASSETS_REPO_NAME] = { path: \"\" };\n return result;\n }\n // override-first when both layers exist, so the env root's entries are scanned\n // (and matched) ahead of the bundled baseline.\n const keys =\n roots.length > 1\n ? [FACTORY_ASSETS_OVERRIDE_REPO_NAME, FACTORY_ASSETS_REPO_NAME]\n : [FACTORY_ASSETS_REPO_NAME];\n roots.forEach((dir, i) => {\n const key = keys[i] ?? `${FACTORY_ASSETS_REPO_NAME}:${i}`;\n if (!result[key]) result[key] = { path: dir };\n });\n return result;\n}\n\n/**\n * Resolve a repository declaration to an on-disk directory. Order:\n * 1. Linked override (`.skaile/links.yaml`).\n * 2. Local `path` — relative to `projectDir`.\n * 3. Cloned URL repo at `.skaile/cache/sources/<name>/` (must already exist).\n *\n * Returns `null` when none of these resolve. Does not clone.\n *\n * **Async and deadline-bounded since #454.** Every candidate here is a\n * project-relative or operator-supplied path, so a `sources[].path` of\n * `workspace/my-assets` resolves onto the rclone FUSE mount — the same tree the\n * scan that follows walks. Probing it with `existsSync`/`lstatSync` would park\n * the `skaile serve` event loop *before* the (now async) scan ever ran, which\n * would leave the H2 fix meaningless on the very declaration that triggers it.\n * A probe that misses its deadline reads as \"unavailable\", which is what the\n * caller already does with an absent path — it becomes a `repo_unavailable`\n * warning rather than a stall.\n */\nasync function resolveRepoDir(\n name: string,\n decl: SourceDeclaration,\n projectDir: string,\n links: Record<string, string>,\n): Promise<string | null> {\n // 1. Linked override\n const linked = links[name];\n if (linked && (await pathExists(linked))) return linked;\n\n // 2. Local path\n if (decl.path) {\n const resolved = resolvePath(projectDir, decl.path);\n return (await pathExists(resolved)) ? resolved : null;\n }\n\n // 3. URL repo cloned to project's .skaile/cache/sources/<name> — the\n // project-local clone dir (often a symlink into the global cache, which\n // lives at getGlobalCacheDir()); NOT the global clone root itself.\n if (decl.url) {\n const projectDest = join(projectDir, \".skaile\", \"cache\", \"sources\", name);\n // One `lstat` answers both questions the pre-#454 `existsSync` + `lstatSync`\n // pair asked, and `lstat` (not `stat`) keeps the \"a symlink into the global\n // cache counts\" behaviour intact.\n const found = await tryWithFsDeadline(\n `lstat ${projectDest}`,\n async () => {\n await lstat(projectDest);\n return true;\n },\n false,\n );\n return found ? projectDest : null;\n }\n\n return null;\n}\n\n/** Deadline-bounded `existsSync` replacement — a wedged mount reads as absent. */\nfunction pathExists(path: string): Promise<boolean> {\n return tryWithFsDeadline(\n `stat ${path}`,\n async () => {\n await stat(path);\n return true;\n },\n false,\n );\n}\n\nfunction repoUnavailableMessage(name: string, decl: SourceDeclaration): string {\n if (name === FACTORY_ASSETS_REPO_NAME && !decl.path && !decl.url) {\n return (\n `Cannot resolve the built-in factory-assets. ` +\n `Set SKAILE_FACTORY_ASSETS_DIR or ensure @skaile/workspaces is installed.`\n );\n }\n if (decl.url) {\n return `Repository \"${name}\" (${decl.url}) is not available. Register it as a Library Source via \\`skaile source add\\`.`;\n }\n if (decl.path) {\n return `Repository \"${name}\" path not found: ${decl.path}`;\n }\n return `Repository \"${name}\" has neither url nor path.`;\n}\n\nfunction findCatalogEntry(\n entries: RuntimeCatalogEntry[],\n query: { kind?: \"connector\"; name: string },\n): RuntimeCatalogEntry | undefined {\n if (query.kind) {\n return entries.find((e) => e.kind === query.kind && e.name === query.name);\n }\n const matches = entries.filter((e) => e.name === query.name);\n if (matches.length === 1) return matches[0];\n // 0 or >1 with no kind — caller must disambiguate.\n return undefined;\n}\n"]}
1
+ {"version":3,"sources":["../core/src/runtime-assets.ts"],"names":["resolvePath","require"],"mappings":";;;;;;;;AAsDA,SAAS,sBACP,OAAA,EACmC;AACnC,EAAA,MAAM,aAAa,iBAAA,EAAkB;AACrC,EAAA,MAAM,MAAyC,EAAC;AAChD,EAAA,KAAA,MAAW,CAAA,IAAK,OAAA,IAAW,EAAC,EAAG;AAC7B,IAAA,MAAM,GAAA,GAAM,cAAA,CAAe,CAAA,CAAE,GAAG,CAAA;AAChC,IAAA,IAAI,GAAA,CAAI,GAAG,CAAA,EAAG;AACd,IAAA,GAAA,CAAI,GAAG,CAAA,GAAI,EAAE,IAAA,EAAM,IAAA,CAAK,UAAA,EAAY,GAAG,CAAA,EAAG,GAAA,EAAK,CAAA,CAAE,GAAA,EAAK,MAAA,EAAQ,EAAE,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,EAAA,MAAM,OAAA,GAAU,QAAQ,MAAA,CAAO,CAAC,MAAM,CAAA,CAAE,IAAA,KAAS,MAAM,IAAI,CAAA;AAC3D,EAAA,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,QAAQ,CAAC,CAAA;AAE1C,EAAA,OAAO,MAAA;AACT","file":"chunk-SH572OBN.js","sourcesContent":["/**\n * Runtime asset resolution — read `skaile.yaml`, scan all declared repositories\n * (including the built-in `factory-assets/` directory as an implicit default),\n * and produce a unified view of connector catalog entries plus the implicit refs\n * that the `skaile.yaml` `connectors:` section adds to the dependency graph.\n *\n * This module is the single source of truth for \"which connectors does this\n * project see at runtime, and where do their implementations live on disk\".\n * Both the runner (serve, REPL, flow) and the platform's mid-session\n * `add_resource` flow consume `RuntimeAssetsResult.catalogEntries` and pass\n * it into `ConnectorManager` for catalog-based resolution.\n *\n * `factory-assets/` is the single first-party content tree (built-in connectors\n * + first-party skills + bundles) shipped inside the `@skaile/workspaces`\n * package — not a standalone package.\n *\n * It resolves to an **ordered list of roots** ({@link factoryAssetRoots}), not a\n * single dir. The bundled tree is always the baseline; an optional\n * `SKAILE_FACTORY_ASSETS_DIR` (legacy: `SKAILE_BASE_ASSETS_DIR`) is layered\n * **in front** as an additive override source — the agent container points it at\n * `/app/factory-assets/` (or a bind-mounted host dir) to ship updated skills /\n * flows / bundles / connector manifests without rebuilding the image. The two\n * roots resolve uniformly across every consumer (connector catalog scan, skill /\n * flow / completion discovery, the asset-manager factory source):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir, when set and existing (override layer).\n * 2. the bundled tree via {@link resolvePackagedAssetsDir} — the in-repo source\n * `packages/workspaces/factory-assets/` during dev, else the published\n * `dist/factory-assets/` after install (always-present baseline).\n *\n * Override semantics are **env-first**: on a name conflict the env root wins and\n * the bundled root fills the rest. Connector *code* still loads via the package's\n * static `exports` map, so the env root can override/add skills, flows, bundles,\n * and connector **manifests/metadata**, but cannot ship a new executable\n * connector — its `.js` is not on the package's import graph.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { lstat, stat } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve as resolvePath } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { tryWithFsDeadline } from \"./fs-deadline.js\";\nimport { scanDirectory } from \"./manifest.js\";\nimport type { CatalogEntry } from \"./models.js\";\nimport { getGlobalCacheDir, readLinks, sourceCacheKey } from \"./repo-manager.js\";\nimport type { SourceDeclaration, SourceEntry } from \"./workspace-config.js\";\nimport { resolveSkWorkspaceConfig } from \"./workspace-config.js\";\n\n/**\n * Map declared `sources[]` to internal `SourceDeclaration`s keyed by the\n * collision-free {@link sourceCacheKey} (`<host>/<owner>/<repo>`), pointing at\n * the unified machine-cache clone path (`getGlobalCacheDir()/<key>/`). Keyed by\n * the same function every other cache writer/reader uses so the path resolves.\n */\nfunction sourcesToDeclarations(\n sources: SourceEntry[] | undefined,\n): Record<string, SourceDeclaration> {\n const sourcesDir = getGlobalCacheDir();\n const out: Record<string, SourceDeclaration> = {};\n for (const s of sources ?? []) {\n const key = sourceCacheKey(s.url);\n if (out[key]) continue;\n out[key] = { path: join(sourcesDir, key), url: s.url, branch: s.pin };\n }\n return out;\n}\n\n// ─── Types ────────────────────────────────────────────────────────────────────\n\n/**\n * Catalog entry filtered to mount/connector kinds. Same shape as `CatalogEntry`.\n * @docLink packages/core/concepts#runtime-catalog-entry\n */\nexport type RuntimeCatalogEntry = CatalogEntry;\n\n/**\n * Implicit catalog reference derived from a `connectors:` declaration in `skaile.yaml`.\n * Each connector driver becomes an implicit ref that must be resolved in the catalog.\n * @docLink packages/core/concepts#runtime-asset-ref\n */\nexport interface RuntimeAssetRef {\n kind: \"connector\";\n /** Driver name — matches `RuntimeCatalogEntry.name`. */\n name: string;\n /** Source declaration id from `skaile.yaml`. */\n declarationId: string;\n}\n\n/**\n * Aggregated npm packages required by all resolved mount/connector adapters.\n * Populated from `metadata.npm_deps` in each matched catalog entry.\n * @docLink packages/core/concepts#runtime-npm-deps\n */\nexport interface RuntimeNpmDeps {\n required: string[];\n optional: string[];\n}\n\n/**\n * Non-fatal warning emitted during `resolveRuntimeAssets` when a repo is unavailable\n * or a driver is not found in any catalog.\n * @docLink packages/core/concepts#runtime-asset-warning\n */\nexport interface RuntimeAssetWarning {\n /** Stable code for filtering / structured logging. */\n code: \"missing_driver\" | \"repo_unavailable\" | \"invalid_repo_decl\";\n message: string;\n /** Declaration id when applicable. */\n declarationId?: string;\n /** Driver / repository name when applicable. */\n name?: string;\n}\n\n/**\n * Repository name used for the implicit built-in `factory-assets` catalog entry\n * (the in-package connector tree).\n * @docLink packages/core/concepts#factory-assets-repo-name\n */\nexport const FACTORY_ASSETS_REPO_NAME = \"factory-assets\";\n\n/**\n * Repository name for the optional `SKAILE_FACTORY_ASSETS_DIR` override layer,\n * scanned ahead of (and overriding) the bundled {@link FACTORY_ASSETS_REPO_NAME}.\n */\nconst FACTORY_ASSETS_OVERRIDE_REPO_NAME = \"factory-assets:override\";\n\n/**\n * Result of `resolveRuntimeAssets`.\n * The same object is mutated in place by `refresh()`, allowing callers to hold\n * a stable reference and observe updates after a new repository is cloned or\n * a driver is installed mid-session.\n * @docLink packages/core/concepts#runtime-assets-result\n */\nexport interface RuntimeAssetsResult {\n catalogEntries: RuntimeCatalogEntry[];\n implicitRefs: RuntimeAssetRef[];\n requiredNpmDeps: RuntimeNpmDeps;\n warnings: RuntimeAssetWarning[];\n /** Re-scan repositories and re-derive implicit refs. Mutates in place. */\n refresh(): Promise<void>;\n /**\n * Catalog lookup. When `kind` is omitted and multiple entries share the\n * `name`, returns `undefined` (caller must disambiguate).\n */\n findEntry(query: { kind?: \"connector\"; name: string }): RuntimeCatalogEntry | undefined;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Resolve all runtime assets visible to a project by scanning declared repositories.\n *\n * Reads `skaile.yaml`, scans every declared repository (plus the implicit\n * built-in `factory-assets` repo), and derives implicit refs from `mounts:` /\n * `connectors:` declarations. Does not clone or install anything — purely a\n * read-only scan of what is already on disk. URL-only repositories that have\n * not been cloned yet are reported as `repo_unavailable` warnings.\n *\n * @param projectDir - Absolute path to the project workspace root\n * @returns `RuntimeAssetsResult` with catalog entries, implicit refs, npm deps, and warnings\n * @docLink packages/core/concepts#resolve-runtime-assets\n */\nexport async function resolveRuntimeAssets(projectDir: string): Promise<RuntimeAssetsResult> {\n const result: RuntimeAssetsResult = {\n catalogEntries: [],\n implicitRefs: [],\n requiredNpmDeps: { required: [], optional: [] },\n warnings: [],\n refresh: async () => {\n await populate(projectDir, result);\n },\n findEntry: (query) => findCatalogEntry(result.catalogEntries, query),\n };\n\n await populate(projectDir, result);\n return result;\n}\n\n/**\n * Resolve the ordered list of on-disk roots for the built-in `factory-assets`\n * tree (built-in connectors + first-party skills + bundles). This is the single\n * shared resolver every consumer goes through, so the env override and the\n * bundled baseline are honoured uniformly.\n *\n * Order (env-first = override-wins):\n * 1. `SKAILE_FACTORY_ASSETS_DIR` env dir (legacy: `SKAILE_BASE_ASSETS_DIR`),\n * when set and existing — an additive override layer.\n * 2. {@link resolvePackagedAssetsDir} — the bundled tree (in-repo source in dev,\n * `dist/factory-assets/` after install). Always-present baseline.\n *\n * Returns `[]` only when the package cannot be located at all. De-duplicated, so\n * pointing the env var at the bundled dir collapses to one root.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function factoryAssetRoots(): string[] {\n const roots: string[] = [];\n const envDir = process.env.SKAILE_FACTORY_ASSETS_DIR ?? process.env.SKAILE_BASE_ASSETS_DIR;\n // Deliberately still synchronous after #454: both candidates are\n // container-local (the image's `/app/factory-assets/`, or the installed\n // package tree resolved by `resolvePackagedAssetsDir`), never the FUSE\n // workspace mount. The mount-reachable probes on this module's scan path —\n // the project-relative `sources[].path` candidates in `resolveRepoDir` — are\n // async and deadline-bounded.\n if (envDir && existsSync(envDir)) roots.push(resolvePath(envDir));\n const bundled = resolvePackagedAssetsDir(\"factory-assets\");\n if (bundled) roots.push(bundled);\n return [...new Set(roots)];\n}\n\n/**\n * Resolve the primary on-disk root of the `factory-assets` tree — the first of\n * {@link factoryAssetRoots} (the env override when set, else the bundled tree).\n * Prefer {@link factoryAssetRoots} when you need to scan every layer; this\n * single-dir form is for callers that want one canonical path.\n *\n * @returns Absolute path to the highest-precedence `factory-assets` directory\n * @throws When no root can be located\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolveFactoryAssetsRoot(): string {\n const hit = resolveFactoryAssetsRootOrNull();\n if (hit) return hit;\n\n throw new Error(\n `Cannot resolve the factory-assets directory. ` +\n `Set SKAILE_FACTORY_ASSETS_DIR to the on-disk path, ` +\n `ensure @skaile/workspaces is installed, ` +\n `or run from within the @skaile/workspaces package tree.`,\n );\n}\n\n/**\n * Non-throwing variant of {@link resolveFactoryAssetsRoot}: the same\n * env-then-packaged resolution tiers, returning `null` instead of throwing when\n * none locate the directory. Callers that treat a missing factory tree as a\n * soft \"not present\" (e.g. the asset-manager's implicit-source injection) MUST\n * use this so they honour the `SKAILE_FACTORY_ASSETS_DIR` container override\n * identically to the runtime path.\n */\nexport function resolveFactoryAssetsRootOrNull(): string | null {\n return factoryAssetRoots()[0] ?? null;\n}\n\n/**\n * Resolve the `@skaile/workspaces` package root — the directory containing its\n * `package.json`. Tries `require.resolve` first (works when installed as a\n * dependency *and* in-repo via the self-reference), then walks upward from this\n * module looking for a `package.json` whose `name` is `@skaile/workspaces`\n * (bounded to 8 levels). Returns `null` when neither locates it.\n *\n * The single source of truth for finding content shipped inside the package —\n * the unified `factory-assets/` tree (built-in connectors + first-party skills\n * + bundles) resolves through {@link resolvePackagedAssetsDir} on top of this.\n *\n * Memoized: the package location is immutable for the process lifetime, but\n * this sits on the CLI hot path (every `findSkills` / flow / completion call\n * funnels through here), so the `require.resolve` + upward `package.json` walk\n * runs once. `undefined` = not yet computed.\n *\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nlet workspacesPackageRootCache: string | null | undefined;\n\nexport function resolveWorkspacesPackageRoot(): string | null {\n if (workspacesPackageRootCache !== undefined) return workspacesPackageRootCache;\n workspacesPackageRootCache = computeWorkspacesPackageRoot();\n return workspacesPackageRootCache;\n}\n\nfunction computeWorkspacesPackageRoot(): string | null {\n try {\n const require = createRequire(import.meta.url);\n return dirname(require.resolve(\"@skaile/workspaces/package.json\"));\n } catch {\n // Fall through to the workspace walk.\n }\n let dir: string;\n try {\n dir = dirname(fileURLToPath(import.meta.url));\n } catch {\n return null;\n }\n for (let i = 0; i < 8; i++) {\n const pkgPath = join(dir, \"package.json\");\n if (existsSync(pkgPath)) {\n try {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\")) as { name?: string };\n if (pkg.name === \"@skaile/workspaces\") return dir;\n } catch {\n // Ignore malformed package.json and keep walking.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/**\n * Locate a content-asset directory inside the package. Prefers the in-repo\n * **source** dir `<pkgRoot>/<subdir>` when present — in a dev checkout it is the\n * full tree (e.g. `factory-assets/` keeps the connector `.ts` entry files that\n * `dist/` does not) — then the published `dist/<subdir>` copy (what\n * `files: [\"dist\"]` ships, the only one present after `npm i`). Returns `null`\n * when neither exists.\n *\n * `factory-assets/` resolves to the source tree in dev (code + skills + bundles)\n * and to `dist/factory-assets` post-install (compiled connectors + copied\n * manifests/skills/bundles).\n *\n * @param subdir - `\"factory-assets\"` | …\n * @docLink packages/core/concepts#resolve-factory-assets-root\n */\nexport function resolvePackagedAssetsDir(subdir: string): string | null {\n const root = resolveWorkspacesPackageRoot();\n if (!root) return null;\n for (const cand of [join(root, subdir), join(root, \"dist\", subdir)]) {\n if (existsSync(cand)) return cand;\n }\n return null;\n}\n\n// ─── Internals ────────────────────────────────────────────────────────────────\n\nasync function populate(projectDir: string, target: RuntimeAssetsResult): Promise<void> {\n target.catalogEntries = [];\n target.implicitRefs = [];\n target.requiredNpmDeps = { required: [], optional: [] };\n target.warnings = [];\n\n const config = resolveSkWorkspaceConfig(projectDir);\n // Connector catalog scan runs over the project's declared sources[] (resolved\n // to their machine-cache clone paths) plus the implicit factory-assets repo.\n const repositories = buildEffectiveRepositories(sourcesToDeclarations(config.sources));\n const links = readLinks(projectDir);\n\n // Scan each repository for connector entries.\n for (const [name, decl] of Object.entries(repositories)) {\n const repoDir = await resolveRepoDir(name, decl, projectDir, links);\n if (!repoDir) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: repoUnavailableMessage(name, decl),\n });\n continue;\n }\n try {\n // Both factory layers carry the same `factory-assets` provenance — the\n // override repo is an internal scan-order device, not a distinct source.\n const repoName = name === FACTORY_ASSETS_OVERRIDE_REPO_NAME ? FACTORY_ASSETS_REPO_NAME : name;\n const scanned = await scanDirectory(repoDir, repoName);\n const entries = scanned.filter((e) => e.kind === \"connector\");\n target.catalogEntries.push(...entries);\n } catch (err) {\n target.warnings.push({\n code: \"repo_unavailable\",\n name,\n message: `Failed to scan repository \"${name}\" at ${repoDir}: ${\n err instanceof Error ? err.message : String(err)\n }`,\n });\n }\n }\n\n // De-duplicate by (kind, name), keeping the first occurrence. Scan order is\n // declared sources → env override → bundled baseline, so an env-supplied\n // connector manifest overrides the bundled one and the bundled one fills the\n // rest (the override layer can refresh built-in manifests in place).\n const seen = new Set<string>();\n target.catalogEntries = target.catalogEntries.filter((e) => {\n const key = `${e.kind}:${e.name}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n // Derive implicit refs from skaile.yaml connectors.\n for (const c of config.connectors ?? []) {\n target.implicitRefs.push({ kind: \"connector\", name: c.driver, declarationId: c.id });\n }\n\n // Validate refs and aggregate npm deps.\n const requiredSet = new Set<string>();\n const optionalSet = new Set<string>();\n for (const ref of target.implicitRefs) {\n const entry = findCatalogEntry(target.catalogEntries, ref);\n if (!entry) {\n target.warnings.push({\n code: \"missing_driver\",\n declarationId: ref.declarationId,\n name: ref.name,\n message:\n `Unknown ${ref.kind} driver \"${ref.name}\" referenced by ${ref.kind} \"${ref.declarationId}\". ` +\n `Run \\`skaile ${ref.kind} catalog\\` to see available drivers, ` +\n `or declare a repository in skaile.yaml that provides this driver.`,\n });\n continue;\n }\n const npm = (entry.metadata?.npm_deps ?? {}) as { required?: string[]; optional?: string[] };\n for (const p of npm.required ?? []) requiredSet.add(p);\n for (const p of npm.optional ?? []) optionalSet.add(p);\n }\n target.requiredNpmDeps.required = [...requiredSet];\n target.requiredNpmDeps.optional = [...optionalSet];\n}\n\n/**\n * Build the effective `repositories` map: caller's declarations first, then the\n * implicit built-in `factory-assets` repos. Each {@link factoryAssetRoots} layer\n * becomes its own repo, the env override inserted **before** the bundled\n * baseline so its connector entries win on the first-match dedup downstream.\n * When the package cannot be located at all, a path-less sentinel under\n * {@link FACTORY_ASSETS_REPO_NAME} drives the `repo_unavailable` warning.\n */\nfunction buildEffectiveRepositories(\n declared: Record<string, SourceDeclaration> | undefined,\n): Record<string, SourceDeclaration> {\n const result: Record<string, SourceDeclaration> = { ...(declared ?? {}) };\n const roots = factoryAssetRoots();\n if (roots.length === 0) {\n // Surface as a warning during scan rather than throwing here — let the\n // caller decide whether factory-assets is required. resolveRepoDir() /\n // repoUnavailableMessage re-discover the failure and emit it.\n if (!result[FACTORY_ASSETS_REPO_NAME]) result[FACTORY_ASSETS_REPO_NAME] = { path: \"\" };\n return result;\n }\n // override-first when both layers exist, so the env root's entries are scanned\n // (and matched) ahead of the bundled baseline.\n const keys =\n roots.length > 1\n ? [FACTORY_ASSETS_OVERRIDE_REPO_NAME, FACTORY_ASSETS_REPO_NAME]\n : [FACTORY_ASSETS_REPO_NAME];\n roots.forEach((dir, i) => {\n const key = keys[i] ?? `${FACTORY_ASSETS_REPO_NAME}:${i}`;\n if (!result[key]) result[key] = { path: dir };\n });\n return result;\n}\n\n/**\n * Resolve a repository declaration to an on-disk directory. Order:\n * 1. Linked override (`.skaile/links.yaml`).\n * 2. Local `path` — relative to `projectDir`.\n * 3. Cloned URL repo at `.skaile/cache/sources/<name>/` (must already exist).\n *\n * Returns `null` when none of these resolve. Does not clone.\n *\n * **Async and deadline-bounded since #454.** Every candidate here is a\n * project-relative or operator-supplied path, so a `sources[].path` of\n * `workspace/my-assets` resolves onto the rclone FUSE mount — the same tree the\n * scan that follows walks. Probing it with `existsSync`/`lstatSync` would park\n * the `skaile serve` event loop *before* the (now async) scan ever ran, which\n * would leave the H2 fix meaningless on the very declaration that triggers it.\n * A probe that misses its deadline reads as \"unavailable\", which is what the\n * caller already does with an absent path — it becomes a `repo_unavailable`\n * warning rather than a stall.\n */\nasync function resolveRepoDir(\n name: string,\n decl: SourceDeclaration,\n projectDir: string,\n links: Record<string, string>,\n): Promise<string | null> {\n // 1. Linked override\n const linked = links[name];\n if (linked && (await pathExists(linked))) return linked;\n\n // 2. Local path\n if (decl.path) {\n const resolved = resolvePath(projectDir, decl.path);\n return (await pathExists(resolved)) ? resolved : null;\n }\n\n // 3. URL repo cloned to project's .skaile/cache/sources/<name> — the\n // project-local clone dir (often a symlink into the global cache, which\n // lives at getGlobalCacheDir()); NOT the global clone root itself.\n if (decl.url) {\n const projectDest = join(projectDir, \".skaile\", \"cache\", \"sources\", name);\n // One `lstat` answers both questions the pre-#454 `existsSync` + `lstatSync`\n // pair asked, and `lstat` (not `stat`) keeps the \"a symlink into the global\n // cache counts\" behaviour intact.\n const found = await tryWithFsDeadline(\n `lstat ${projectDest}`,\n async () => {\n await lstat(projectDest);\n return true;\n },\n false,\n );\n return found ? projectDest : null;\n }\n\n return null;\n}\n\n/** Deadline-bounded `existsSync` replacement — a wedged mount reads as absent. */\nfunction pathExists(path: string): Promise<boolean> {\n return tryWithFsDeadline(\n `stat ${path}`,\n async () => {\n await stat(path);\n return true;\n },\n false,\n );\n}\n\nfunction repoUnavailableMessage(name: string, decl: SourceDeclaration): string {\n if (name === FACTORY_ASSETS_REPO_NAME && !decl.path && !decl.url) {\n return (\n `Cannot resolve the built-in factory-assets. ` +\n `Set SKAILE_FACTORY_ASSETS_DIR or ensure @skaile/workspaces is installed.`\n );\n }\n if (decl.url) {\n return `Repository \"${name}\" (${decl.url}) is not available. Register it as a Library Source via \\`skaile source add\\`.`;\n }\n if (decl.path) {\n return `Repository \"${name}\" path not found: ${decl.path}`;\n }\n return `Repository \"${name}\" has neither url nor path.`;\n}\n\nfunction findCatalogEntry(\n entries: RuntimeCatalogEntry[],\n query: { kind?: \"connector\"; name: string },\n): RuntimeCatalogEntry | undefined {\n if (query.kind) {\n return entries.find((e) => e.kind === query.kind && e.name === query.name);\n }\n const matches = entries.filter((e) => e.name === query.name);\n if (matches.length === 1) return matches[0];\n // 0 or >1 with no kind — caller must disambiguate.\n return undefined;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { PROVIDER_ENDPOINTS } from './chunk-V34ZEXSE.js';
2
2
  import { classifyClaudeSdkError } from './chunk-GAH4YRCI.js';
3
- import { createDriver } from './chunk-SUGDZOYZ.js';
3
+ import { createDriver } from './chunk-AFA7NYN2.js';
4
4
 
5
5
  // bridge/src/normalizer.ts
6
6
  var EventNormalizer = class {
@@ -459,5 +459,5 @@ async function validateApiKey(provider, key) {
459
459
  }
460
460
 
461
461
  export { BridgeRuntime, EventNormalizer, createRuntime, detectFileChange, detectFileChanges, summarizeToolCall, summarizeToolResult, validateApiKey };
462
- //# sourceMappingURL=chunk-ZCIK44M7.js.map
463
- //# sourceMappingURL=chunk-ZCIK44M7.js.map
462
+ //# sourceMappingURL=chunk-UTMZU56B.js.map
463
+ //# sourceMappingURL=chunk-UTMZU56B.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/normalizer.ts","../bridge/src/runtime.ts","../bridge/src/validation.ts"],"names":[],"mappings":";;;;;AAqBO,IAAM,kBAAN,MAAsB;AAAA,EACnB,eAAA,uBAAsB,GAAA,EAAoB;AAAA,EAC1C,wBAAA,GAA2B,KAAA;AAAA,EAC3B,qBAAA,GAAwB,KAAA;AAAA;AAAA,EAExB,eAAA,GAAkB,KA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AAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,yCAAA,EAA0C;AAAA,IACvE;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,kBAAA,EAAqB,MAAM,CAAA,CAAA,EAAG;AAAA,EAC3D,SAAS,GAAA,EAAU;AACjB,IAAA,IAAI,GAAA,CAAI,SAAS,YAAA,EAAc,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,wBAAA,EAAyB;AACnF,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,CAAI,WAAW,eAAA,EAAgB;AAAA,EAC5D;AACF","file":"chunk-ZCIK44M7.js","sourcesContent":["/**\n * EventNormalizer — converts bridge-level AgentEvent (raw driver events) to\n * skaile-agent-types AgentEvent (normalized, human-readable events).\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call reset() between sessions.\n */\n\nimport type { AgentEvent as NormalizedEvent } from \"@skaile/workspaces/types\";\nimport { classifyClaudeSdkError } from \"./error-classifier.js\";\nimport type { AgentMessage, AgentEvent as BridgeEvent, ContentBlock } from \"./types.js\";\n\n/**\n * Converts raw bridge-level {@link BridgeEvent} payloads into normalized\n * `@skaile/workspaces/types` `AgentEvent` payloads consumed by the runner and transport.\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call {@link EventNormalizer.reset} between sessions to clear accumulated state.\n *\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport class EventNormalizer {\n private activeSubagents = new Map<string, string>();\n private devServerStartingEmitted = false;\n private devServerReadyEmitted = false;\n /** True when message_update deltas have been emitted for the current message. */\n private hasStreamedText = false;\n\n /**\n * Convert a single bridge event into zero or more normalized events.\n * One bridge event can produce multiple normalized events (e.g., a message_start\n * with text + tool_use blocks produces both text and tool_call events).\n */\n normalize(event: BridgeEvent): NormalizedEvent[] {\n switch (event.type) {\n case \"message_start\":\n return this.handleMessageStart(event.message);\n\n case \"message_update\":\n return this.handleMessageUpdate(event);\n\n case \"message_end\":\n return [];\n\n case \"turn_end\":\n return this.handleTurnEnd(event.toolResults);\n\n case \"result\":\n return this.handleResult(event);\n\n case \"error\":\n return [\n {\n type: \"error\",\n message: event.error,\n fatal: event.fatal ?? true,\n category: event.detail?.category,\n ...(event.detail?.hint ? { hint: event.detail.hint } : {}),\n },\n ];\n\n case \"tool_call\":\n // Already handled in message_start — emit status only\n return [{ type: \"status\", phase: \"working\" }];\n\n case \"tool_execution_end\":\n return [];\n\n case \"agent_end\":\n return [{ type: \"status\", phase: \"idle\" }];\n\n case \"commands_available\":\n // Pass through to transport — the gateway caches this event\n return [event as unknown as NormalizedEvent];\n\n case \"session_info\":\n // Pass through to transport — the forge layer stores the OMP session ID\n return [event as unknown as NormalizedEvent];\n\n case \"ui_render\":\n case \"ui_render_update\":\n case \"ui_clear\":\n // Pass through verbatim — drivers that implement the Agent UI Protocol emit these directly\n return [event as unknown as NormalizedEvent];\n\n default:\n return [];\n }\n }\n\n /** Clear all stateful tracking between sessions. */\n reset(): void {\n this.activeSubagents.clear();\n this.devServerStartingEmitted = false;\n this.devServerReadyEmitted = false;\n this.hasStreamedText = false;\n }\n\n // ---------------------------------------------------------------------------\n // message_start → text, tool_call, question, subagent\n // ---------------------------------------------------------------------------\n\n private handleMessageStart(message: AgentMessage): NormalizedEvent[] {\n // Only process assistant messages. Drivers (e.g. omp) may echo the user's\n // message as a message_start with role:\"user\" before streaming the response.\n // Emitting a text event for that echo would prepend the user's input to the\n // assistant bubble on the frontend.\n if (message.role !== \"assistant\") return [];\n\n const events: NormalizedEvent[] = [];\n const blocks = this.getContentBlocks(message);\n\n for (const block of blocks) {\n if (block.type === \"text\" && block.text) {\n // Skip full text if we already streamed it via message_update deltas\n if (!this.hasStreamedText) {\n events.push({ type: \"text\", content: block.text });\n }\n } else if (block.type === \"tool_use\" && block.name) {\n events.push(...this.handleToolUse(block));\n }\n }\n\n this.hasStreamedText = false;\n return events;\n }\n\n private handleToolUse(block: ContentBlock): NormalizedEvent[] {\n const name = block.name!;\n const input = (block.input ?? {}) as Record<string, unknown>;\n\n if (name === \"AskUserQuestion\") {\n return this.handleAskUserQuestion(input);\n }\n if (name === \"Agent\") {\n return this.handleAgentToolUse(block, input);\n }\n return this.handleGenericToolUse(name, input);\n }\n\n private handleAskUserQuestion(input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n // Claude SDK sends { questions: [{ question, header, options: [{ label, description }] }] }\n // Legacy/simple format sends { question: string, options?: string[] }\n const questions = input.questions;\n if (Array.isArray(questions)) {\n for (const q of questions) {\n const qObj = q as Record<string, unknown>;\n const question = String(qObj.question ?? \"\");\n const rawOpts = qObj.options;\n const options = Array.isArray(rawOpts)\n ? rawOpts.map((o: any) => (typeof o === \"string\" ? o : String(o.label ?? o)))\n : undefined;\n events.push({ type: \"question\", question, options });\n }\n } else {\n const question = String(input.question ?? input.text ?? \"\");\n const rawOptions = input.options;\n const options = Array.isArray(rawOptions) ? rawOptions.map(String) : undefined;\n events.push({ type: \"question\", question, options });\n }\n return events;\n }\n\n private handleAgentToolUse(\n block: ContentBlock,\n input: Record<string, unknown>,\n ): NormalizedEvent[] {\n const agentName = String(input.subagent_type ?? input.description ?? \"unknown\");\n const description = String(input.description ?? input.prompt ?? \"\").slice(0, 200);\n if (block.id) {\n this.activeSubagents.set(block.id, agentName);\n }\n return [\n { type: \"subagent\", name: agentName, status: \"started\", description },\n { type: \"status\", phase: \"working\" },\n ];\n }\n\n private handleGenericToolUse(name: string, input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_call\",\n tool: name,\n input,\n summary: summarizeToolCall(name, input),\n });\n events.push({ type: \"status\", phase: \"working\" });\n\n if (name === \"Bash\" && typeof input.command === \"string\") {\n const devEvent = this.detectDevServerStarting(input.command);\n if (devEvent) events.push(devEvent);\n }\n\n return events;\n }\n\n // ---------------------------------------------------------------------------\n // message_update → streaming text\n // ---------------------------------------------------------------------------\n\n private handleMessageUpdate(event: BridgeEvent): NormalizedEvent[] {\n const delta = (event as any)._textDelta as string | undefined;\n if (delta) {\n this.hasStreamedText = true;\n return [{ type: \"text\", content: delta }];\n }\n return [];\n }\n\n // ---------------------------------------------------------------------------\n // turn_end → tool_result, subagent finished, file_changed, dev_server\n // ---------------------------------------------------------------------------\n\n private handleTurnEnd(toolResults?: AgentMessage[]): NormalizedEvent[] {\n if (!toolResults?.length) return [];\n\n const events: NormalizedEvent[] = [];\n\n for (const result of toolResults) {\n const toolName = result.toolName ?? \"unknown\";\n const outputData = result.data ?? result.content;\n const output = typeof outputData === \"string\" ? outputData : JSON.stringify(outputData);\n\n // Check if this is a subagent result\n if (toolName === \"Agent\" || this.isSubagentResult(result)) {\n events.push(...this.handleSubagentResult(result, output));\n } else {\n events.push(...this.handleToolResult(toolName, outputData, output));\n }\n }\n\n return events;\n }\n\n private handleSubagentResult(result: AgentMessage, output: string): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const agentName = this.resolveSubagentName(result);\n const description = output.slice(0, 200);\n events.push({ type: \"subagent\", name: agentName, status: \"finished\", description });\n\n if (agentName === \"dev-server\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private handleToolResult(\n toolName: string,\n outputData: unknown,\n output: string,\n ): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_result\",\n tool: toolName,\n output: outputData,\n summary: summarizeToolResult(toolName, outputData),\n });\n\n // Detect file changes from Write/Edit results\n const fileEvents = detectFileChanges(toolName, outputData);\n if (fileEvents.length > 0) events.push(...fileEvents);\n\n // Detect dev server from Bash output\n if (toolName === \"Bash\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private isSubagentResult(result: AgentMessage): boolean {\n // Check if the tool result's id maps to a tracked subagent\n if (result.toolName && this.activeSubagents.has(result.toolName)) return true;\n return false;\n }\n\n private resolveSubagentName(result: AgentMessage): string {\n // toolName on bridge AgentMessage is resolved from toolIdToName in the driver\n const name = result.toolName ? this.activeSubagents.get(result.toolName) : undefined;\n if (name) {\n this.activeSubagents.delete(result.toolName!);\n return name;\n }\n return result.toolName ?? \"unknown\";\n }\n\n // ---------------------------------------------------------------------------\n // result → finished or error\n // ---------------------------------------------------------------------------\n\n private handleResult(event: BridgeEvent & { type: \"result\" }): NormalizedEvent[] {\n if (event.subtype === \"success\") {\n return [\n {\n type: \"finished\",\n summary: event.summary ?? \"Task completed\",\n costUsd: event.costUsd ?? 0,\n ...(event.tokens ? { tokens: event.tokens } : {}),\n },\n ];\n }\n\n const errors = event.errors ?? [];\n // Run the same classifier the claude-sdk driver uses on its `error`\n // event so the result-error path also surfaces a category and hint\n // (drivers other than claude-sdk emit `result` without a paired\n // `error`, so this is the only place they get classified).\n const detail = classifyClaudeSdkError({ errors, subtype: event.subtype });\n return [\n {\n type: \"error\",\n message: `Agent stopped: ${event.subtype}${errors.length ? ` — ${errors.join(\"; \")}` : \"\"}`,\n fatal: event.subtype === \"error_during_execution\",\n category: detail.category,\n ...(detail.hint ? { hint: detail.hint } : {}),\n },\n ];\n }\n\n // ---------------------------------------------------------------------------\n // Dev server detection\n // ---------------------------------------------------------------------------\n\n private detectDevServerStarting(command: string): NormalizedEvent | null {\n if (this.devServerStartingEmitted) return null;\n const cmd = command.toLowerCase();\n const isFrontendStart =\n (cmd.includes(\"pnpm run dev\") || cmd.includes(\"pnpm dev\") || cmd.includes(\"vite\")) &&\n (cmd.includes(\"frontend\") || cmd.includes(\"dev:preview\"));\n if (isFrontendStart) {\n this.devServerStartingEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"starting\" };\n }\n return null;\n }\n\n private detectDevServerReady(text: string): NormalizedEvent | null {\n if (this.devServerReadyEmitted) return null;\n\n const explicitMatch = text.match(/DEVSERVER_READY:(https?:\\/\\/[^\\s\"\\\\]+)/);\n if (explicitMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: explicitMatch[1]!, status: \"ready\" };\n }\n\n const viteMatch = text.match(/Local:\\s+(https?:\\/\\/localhost:\\d+)/);\n if (viteMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: viteMatch[1]!, status: \"ready\" };\n }\n\n if (text.includes(\"FRONTEND_READY\")) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"ready\" };\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n private getContentBlocks(message: AgentMessage): ContentBlock[] {\n if (Array.isArray(message.content)) return message.content;\n if (typeof message.content === \"string\" && message.content) {\n return [{ type: \"text\", text: message.content }];\n }\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pure helper functions (exported for reuse)\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a human-readable one-line summary of a tool call for the activity log.\n *\n * Returns a string like `$ git status` for Bash, `Read src/index.ts` for Read, etc.\n * Falls back to `ToolName({...input...})` for unrecognised tools.\n *\n * @param tool - Tool name (e.g. `\"Bash\"`, `\"Write\"`, `\"Grep\"`).\n * @param input - Tool input record passed to the call.\n * @returns A short display string suitable for the activity feed.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolCall(tool: string, input: Record<string, unknown>): string {\n switch (tool) {\n case \"Bash\":\n return `$ ${String(input.command ?? \"\").slice(0, 200)}`;\n case \"Write\":\n return `Create ${String(input.file_path)}`;\n case \"Edit\":\n return `Edit ${String(input.file_path)}`;\n case \"Read\":\n return `Read ${String(input.file_path)}`;\n case \"Glob\":\n return `Find ${String(input.pattern)}`;\n case \"Grep\":\n return `Search for ${String(input.pattern)}`;\n default:\n return `${tool}(${JSON.stringify(input).slice(0, 100)})`;\n }\n}\n\n/** Extract plain text from an Anthropic content-block array (e.g. tool results returned by Claude SDK). */\nfunction extractContentBlockText(blocks: unknown[]): string | null {\n const textBlocks = blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n typeof b === \"object\" &&\n b !== null &&\n (b as Record<string, unknown>).type === \"text\" &&\n typeof (b as Record<string, unknown>).text === \"string\",\n );\n if (textBlocks.length === 0) return null;\n return textBlocks.map((b) => b.text).join(\"\\n\");\n}\n\n/**\n * Produce a human-readable one-line summary of a tool result for the activity log.\n *\n * Handles Bash stdout/stderr, Write/Edit file paths, ApplyPatch change counts, and\n * Anthropic content-block arrays. Falls back to `JSON.stringify` for unknown shapes.\n *\n * @param tool - Tool name.\n * @param result - Raw tool result payload.\n * @returns A short display string, truncated to 200 characters.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolResult(tool: string, result: unknown): string {\n // Handle Anthropic content-block arrays: [{ type: \"text\", text: \"...\" }, ...]\n if (Array.isArray(result)) {\n const text = extractContentBlockText(result);\n return (text ?? JSON.stringify(result)).slice(0, 200);\n }\n if (typeof result !== \"object\" || !result) {\n return String(result).slice(0, 200);\n }\n const r = result as Record<string, unknown>;\n switch (tool) {\n case \"Bash\": {\n const stderr = String(r.stderr ?? \"\").trim();\n if (stderr) return `stderr: ${stderr.slice(0, 200)}`;\n return (\n String(r.stdout ?? \"\")\n .trim()\n .slice(0, 200) || \"(no output)\"\n );\n }\n case \"Write\":\n return `${String(r.type)}: ${String(r.filePath)}`;\n case \"Edit\":\n return `Edited ${String(r.filePath)}`;\n case \"ApplyPatch\":\n return `${Array.isArray(r.changes) ? r.changes.length : 0} file changes`;\n default:\n return JSON.stringify(result).slice(0, 200);\n }\n}\n\n/**\n * Detect file-change events from a tool result, returning zero or more `file_changed` events.\n *\n * Handles `Write` (single create/edit), `Edit` (single edit), and `ApplyPatch` (multi-file\n * patch with per-change `kind` classification). Returns an empty array for all other tools.\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns Array of `file_changed` normalized events.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChanges(toolName: string, result: unknown): NormalizedEvent[] {\n if (typeof result !== \"object\" || !result) return [];\n const r = result as Record<string, unknown>;\n\n if (toolName === \"Write\" && r.filePath) {\n return [\n {\n type: \"file_changed\",\n path: String(r.filePath),\n action: r.type === \"create\" ? \"create\" : \"edit\",\n },\n ];\n }\n if (toolName === \"Edit\" && r.filePath) {\n return [{ type: \"file_changed\", path: String(r.filePath), action: \"edit\" }];\n }\n if (toolName === \"ApplyPatch\" && Array.isArray(r.changes)) {\n return r.changes\n .filter(\n (change): change is { path: string; kind: \"add\" | \"delete\" | \"update\" } =>\n typeof change === \"object\" &&\n change !== null &&\n typeof (change as Record<string, unknown>).path === \"string\" &&\n typeof (change as Record<string, unknown>).kind === \"string\",\n )\n .map((change) => ({\n type: \"file_changed\" as const,\n path: change.path,\n action: change.kind === \"add\" ? \"create\" : change.kind === \"delete\" ? \"delete\" : \"edit\",\n }));\n }\n\n return [];\n}\n\n/**\n * Backward-compatible single-event helper; returns the first `file_changed` event or `null`.\n *\n * Prefer {@link detectFileChanges} for multi-file patches (e.g. `ApplyPatch`).\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns First detected `file_changed` event, or `null`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChange(toolName: string, result: unknown): NormalizedEvent | null {\n return detectFileChanges(toolName, result)[0] ?? null;\n}\n","/**\n * BridgeRuntime — implements IAgentRuntime from @skaile/workspaces/types by wrapping\n * an AgentDriver + EventNormalizer. This is the primary integration point for\n * consumers that want normalized events from any driver.\n */\n\nimport type {\n AgentEvent,\n AgentReconfigureOptions,\n AgentRuntimeConfig,\n IAgentRuntime,\n} from \"@skaile/workspaces/types\";\n\nimport { EventNormalizer } from \"./normalizer.js\";\nimport { createDriver } from \"./registry.js\";\nimport type { AgentConfig, AgentDriver } from \"./types.js\";\n\n/**\n * Implements `IAgentRuntime` from `@skaile/workspaces/types` by wrapping an {@link AgentDriver}\n * and an {@link EventNormalizer}.\n *\n * This is the primary integration point for consumers that want normalized `AgentEvent`\n * payloads from any driver without managing the driver lifecycle directly. Create via\n * {@link createRuntime} to avoid coupling to `BridgeRuntime` directly.\n *\n * @docLink packages/bridge/api-reference#runtime\n */\nexport class BridgeRuntime implements IAgentRuntime {\n private driver: AgentDriver | null = null;\n private normalizer = new EventNormalizer();\n private handlers = new Set<(event: AgentEvent) => void>();\n private boundEventHandler: ((event: any) => void) | null = null;\n private driverId: string;\n\n constructor(driverId: string = \"claude-sdk\") {\n this.driverId = driverId;\n }\n\n async start(config: AgentRuntimeConfig): Promise<void> {\n // Dispose previous driver if any\n if (this.driver) {\n await this.dispose();\n }\n\n this.normalizer.reset();\n\n const bridgeConfig: AgentConfig = {\n cwd: config.cwd,\n provider: config.provider,\n model: config.model,\n systemPrompt: config.systemPrompt,\n apiKeys: config.apiKeys,\n env: config.env,\n agentDir: config.agentDir,\n sessionId: config.sessionId,\n resumeSessionId: config.resumeSessionId,\n maxTurns: config.maxTurns,\n };\n\n this.driver = await createDriver(this.driverId, bridgeConfig);\n\n // Wire bridge events through normalizer to handlers\n this.boundEventHandler = (bridgeEvent: any) => {\n const normalized = this.normalizer.normalize(bridgeEvent);\n for (const event of normalized) {\n for (const handler of this.handlers) {\n handler(event);\n }\n }\n };\n this.driver.on(\"agent-event\", this.boundEventHandler);\n\n await this.driver.start();\n }\n\n async configure(_config: AgentReconfigureOptions): Promise<void> {\n // Runtime reconfiguration for BridgeRuntime is a no-op for now.\n // Future: reconnect connectors, reload ai-assets, update subagents.\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.prompt(message);\n }\n\n async reply(answer: string): Promise<void> {\n // Mirror serve.ts handleReply: an answer must resume the paused turn. Falling through to\n // prompt() would deny the question as superseded and drop the structured answer.\n if (this.driver?.hasPendingQuestion() && this.driver.answerQuestion(answer)) return;\n await this.prompt(answer);\n }\n\n async abort(): Promise<void> {\n if (this.driver) {\n await this.driver.abort();\n }\n }\n\n async dispose(): Promise<void> {\n if (this.driver) {\n if (this.boundEventHandler) {\n this.driver.off(\"agent-event\", this.boundEventHandler);\n this.boundEventHandler = null;\n }\n this.driver.kill();\n this.driver = null;\n }\n this.normalizer.reset();\n }\n\n onEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.add(handler);\n }\n\n offEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.delete(handler);\n }\n\n get isRunning(): boolean {\n return this.driver?.isRunning ?? false;\n }\n}\n\n/**\n * Factory function to create a {@link BridgeRuntime} with the specified driver.\n *\n * @param driverId - Registered driver id (default: `\"claude-sdk\"`).\n * @returns A new `IAgentRuntime` wrapping the selected driver with event normalization.\n * @docLink packages/bridge/api-reference#runtime\n */\nexport function createRuntime(driverId: string = \"claude-sdk\"): IAgentRuntime {\n return new BridgeRuntime(driverId);\n}\n","/** Provider API key validation — hits each provider's models endpoint to verify the key works. */\n\nimport { PROVIDER_ENDPOINTS } from \"./provider-endpoints.js\";\n\n/**\n * Result of an API key validation check performed by {@link validateApiKey}.\n *\n * @docLink packages/bridge/api-reference#validation\n */\nexport interface ValidationResult {\n /** `true` when the API key was accepted by the provider's models endpoint. */\n ok: boolean;\n /** Human-readable error description when `ok` is `false`. */\n error?: string;\n}\n\n/**\n * Validate an API key by sending a lightweight GET request to the provider's models endpoint.\n *\n * Returns `{ ok: true }` when the provider accepts the key (HTTP 2xx). Returns\n * `{ ok: false, error }` on 401/403 (invalid key), other HTTP errors, network failures,\n * or unsupported providers. Requests time out after 8 seconds.\n *\n * @param provider - Provider name matching a key in the shared `PROVIDER_ENDPOINTS` map\n * (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * @param key - API key to validate.\n * @returns Validation result with optional error description.\n * @docLink packages/bridge/api-reference#validation\n */\nexport async function validateApiKey(provider: string, key: string): Promise<ValidationResult> {\n const endpoint = PROVIDER_ENDPOINTS[provider];\n if (!endpoint) return { ok: false, error: `Unknown provider: ${provider}` };\n\n let url = endpoint.url;\n if (endpoint.queryParam) url += `?${endpoint.queryParam}=${encodeURIComponent(key)}`;\n\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8000);\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: endpoint.headers(key),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (response.ok) return { ok: true };\n\n const status = response.status;\n if (status === 401 || status === 403) {\n return { ok: false, error: \"Invalid API key (authentication failed)\" };\n }\n return { ok: false, error: `API returned HTTP ${status}` };\n } catch (err: any) {\n if (err.name === \"AbortError\") return { ok: false, error: \"Request timed out (8s)\" };\n return { ok: false, error: err.message ?? \"Network error\" };\n }\n}\n"]}
1
+ {"version":3,"sources":["../bridge/src/normalizer.ts","../bridge/src/runtime.ts","../bridge/src/validation.ts"],"names":[],"mappings":";;;;;AAqBO,IAAM,kBAAN,MAAsB;AAAA,EACnB,eAAA,uBAAsB,GAAA,EAAoB;AAAA,EAC1C,wBAAA,GAA2B,KAAA;AAAA,EAC3B,qBAAA,GAAwB,KAAA;AAAA;AAAA,EAExB,eAAA,GAAkB,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO1B,UAAU,KAAA,EAAuC;AAC/C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,eAAA;AACH,QAAA,OAAO,IAAA,CAAK,kBAAA,CAAmB,KAAA,CAAM,OAAO,CAAA;AAAA,MAE9C,KAAK,gBAAA;AACH,QAAA,OAAO,IAAA,CAAK,oBAAoB,KAAK,CAAA;AAAA,MAEvC,KAAK,aAAA;AACH,QAAA,OAAO,EAAC;AAAA,MAEV,KAAK,UAAA;AACH,QAAA,OAAO,IAAA,CAAK,aAAA,CAAc,KAAA,CAAM,WAAW,CAAA;AAAA,MAE7C,KAAK,QAAA;AACH,QAAA,OAAO,IAAA,CAAK,aAAa,KAAK,CAAA;AAAA,MAEhC,KAAK,OAAA;AACH,QAAA,OAAO;AAAA,UACL;AAAA,YACE,IAAA,EAAM,OAAA;AAAA,YACN,SAAS,KAAA,CAAM,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AAS,UAAU,CAAA,CAAA,EAAI,kBAAA,CAAmB,GAAG,CAAC,CAAA,CAAA;AAElF,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,IAAI,eAAA,EAAgB;AACvC,IAAA,MAAM,UAAU,UAAA,CAAW,MAAM,UAAA,CAAW,KAAA,IAAS,GAAI,CAAA;AAEzD,IAAA,MAAM,QAAA,GAAW,MAAM,KAAA,CAAM,GAAA,EAAK;AAAA,MAChC,MAAA,EAAQ,KAAA;AAAA,MACR,OAAA,EAAS,QAAA,CAAS,OAAA,CAAQ,GAAG,CAAA;AAAA,MAC7B,QAAQ,UAAA,CAAW;AAAA,KACpB,CAAA;AAED,IAAA,YAAA,CAAa,OAAO,CAAA;AAEpB,IAAA,IAAI,QAAA,CAAS,EAAA,EAAI,OAAO,EAAE,IAAI,IAAA,EAAK;AAEnC,IAAA,MAAM,SAAS,QAAA,CAAS,MAAA;AACxB,IAAA,IAAI,MAAA,KAAW,GAAA,IAAO,MAAA,KAAW,GAAA,EAAK;AACpC,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,yCAAA,EAA0C;AAAA,IACvE;AACA,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,CAAA,kBAAA,EAAqB,MAAM,CAAA,CAAA,EAAG;AAAA,EAC3D,SAAS,GAAA,EAAU;AACjB,IAAA,IAAI,GAAA,CAAI,SAAS,YAAA,EAAc,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,wBAAA,EAAyB;AACnF,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,CAAI,WAAW,eAAA,EAAgB;AAAA,EAC5D;AACF","file":"chunk-UTMZU56B.js","sourcesContent":["/**\n * EventNormalizer — converts bridge-level AgentEvent (raw driver events) to\n * skaile-agent-types AgentEvent (normalized, human-readable events).\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call reset() between sessions.\n */\n\nimport type { AgentEvent as NormalizedEvent } from \"@skaile/workspaces/types\";\nimport { classifyClaudeSdkError } from \"./error-classifier.js\";\nimport type { AgentMessage, AgentEvent as BridgeEvent, ContentBlock } from \"./types.js\";\n\n/**\n * Converts raw bridge-level {@link BridgeEvent} payloads into normalized\n * `@skaile/workspaces/types` `AgentEvent` payloads consumed by the runner and transport.\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call {@link EventNormalizer.reset} between sessions to clear accumulated state.\n *\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport class EventNormalizer {\n private activeSubagents = new Map<string, string>();\n private devServerStartingEmitted = false;\n private devServerReadyEmitted = false;\n /** True when message_update deltas have been emitted for the current message. */\n private hasStreamedText = false;\n\n /**\n * Convert a single bridge event into zero or more normalized events.\n * One bridge event can produce multiple normalized events (e.g., a message_start\n * with text + tool_use blocks produces both text and tool_call events).\n */\n normalize(event: BridgeEvent): NormalizedEvent[] {\n switch (event.type) {\n case \"message_start\":\n return this.handleMessageStart(event.message);\n\n case \"message_update\":\n return this.handleMessageUpdate(event);\n\n case \"message_end\":\n return [];\n\n case \"turn_end\":\n return this.handleTurnEnd(event.toolResults);\n\n case \"result\":\n return this.handleResult(event);\n\n case \"error\":\n return [\n {\n type: \"error\",\n message: event.error,\n fatal: event.fatal ?? true,\n category: event.detail?.category,\n ...(event.detail?.hint ? { hint: event.detail.hint } : {}),\n },\n ];\n\n case \"tool_call\":\n // Already handled in message_start — emit status only\n return [{ type: \"status\", phase: \"working\" }];\n\n case \"tool_execution_end\":\n return [];\n\n case \"agent_end\":\n return [{ type: \"status\", phase: \"idle\" }];\n\n case \"commands_available\":\n // Pass through to transport — the gateway caches this event\n return [event as unknown as NormalizedEvent];\n\n case \"session_info\":\n // Pass through to transport — the forge layer stores the OMP session ID\n return [event as unknown as NormalizedEvent];\n\n case \"ui_render\":\n case \"ui_render_update\":\n case \"ui_clear\":\n // Pass through verbatim — drivers that implement the Agent UI Protocol emit these directly\n return [event as unknown as NormalizedEvent];\n\n default:\n return [];\n }\n }\n\n /** Clear all stateful tracking between sessions. */\n reset(): void {\n this.activeSubagents.clear();\n this.devServerStartingEmitted = false;\n this.devServerReadyEmitted = false;\n this.hasStreamedText = false;\n }\n\n // ---------------------------------------------------------------------------\n // message_start → text, tool_call, question, subagent\n // ---------------------------------------------------------------------------\n\n private handleMessageStart(message: AgentMessage): NormalizedEvent[] {\n // Only process assistant messages. Drivers (e.g. omp) may echo the user's\n // message as a message_start with role:\"user\" before streaming the response.\n // Emitting a text event for that echo would prepend the user's input to the\n // assistant bubble on the frontend.\n if (message.role !== \"assistant\") return [];\n\n const events: NormalizedEvent[] = [];\n const blocks = this.getContentBlocks(message);\n\n for (const block of blocks) {\n if (block.type === \"text\" && block.text) {\n // Skip full text if we already streamed it via message_update deltas\n if (!this.hasStreamedText) {\n events.push({ type: \"text\", content: block.text });\n }\n } else if (block.type === \"tool_use\" && block.name) {\n events.push(...this.handleToolUse(block));\n }\n }\n\n this.hasStreamedText = false;\n return events;\n }\n\n private handleToolUse(block: ContentBlock): NormalizedEvent[] {\n const name = block.name!;\n const input = (block.input ?? {}) as Record<string, unknown>;\n\n if (name === \"AskUserQuestion\") {\n return this.handleAskUserQuestion(input);\n }\n if (name === \"Agent\") {\n return this.handleAgentToolUse(block, input);\n }\n return this.handleGenericToolUse(name, input);\n }\n\n private handleAskUserQuestion(input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n // Claude SDK sends { questions: [{ question, header, options: [{ label, description }] }] }\n // Legacy/simple format sends { question: string, options?: string[] }\n const questions = input.questions;\n if (Array.isArray(questions)) {\n for (const q of questions) {\n const qObj = q as Record<string, unknown>;\n const question = String(qObj.question ?? \"\");\n const rawOpts = qObj.options;\n const options = Array.isArray(rawOpts)\n ? rawOpts.map((o: any) => (typeof o === \"string\" ? o : String(o.label ?? o)))\n : undefined;\n events.push({ type: \"question\", question, options });\n }\n } else {\n const question = String(input.question ?? input.text ?? \"\");\n const rawOptions = input.options;\n const options = Array.isArray(rawOptions) ? rawOptions.map(String) : undefined;\n events.push({ type: \"question\", question, options });\n }\n return events;\n }\n\n private handleAgentToolUse(\n block: ContentBlock,\n input: Record<string, unknown>,\n ): NormalizedEvent[] {\n const agentName = String(input.subagent_type ?? input.description ?? \"unknown\");\n const description = String(input.description ?? input.prompt ?? \"\").slice(0, 200);\n if (block.id) {\n this.activeSubagents.set(block.id, agentName);\n }\n return [\n { type: \"subagent\", name: agentName, status: \"started\", description },\n { type: \"status\", phase: \"working\" },\n ];\n }\n\n private handleGenericToolUse(name: string, input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_call\",\n tool: name,\n input,\n summary: summarizeToolCall(name, input),\n });\n events.push({ type: \"status\", phase: \"working\" });\n\n if (name === \"Bash\" && typeof input.command === \"string\") {\n const devEvent = this.detectDevServerStarting(input.command);\n if (devEvent) events.push(devEvent);\n }\n\n return events;\n }\n\n // ---------------------------------------------------------------------------\n // message_update → streaming text\n // ---------------------------------------------------------------------------\n\n private handleMessageUpdate(event: BridgeEvent): NormalizedEvent[] {\n const delta = (event as any)._textDelta as string | undefined;\n if (delta) {\n this.hasStreamedText = true;\n return [{ type: \"text\", content: delta }];\n }\n return [];\n }\n\n // ---------------------------------------------------------------------------\n // turn_end → tool_result, subagent finished, file_changed, dev_server\n // ---------------------------------------------------------------------------\n\n private handleTurnEnd(toolResults?: AgentMessage[]): NormalizedEvent[] {\n if (!toolResults?.length) return [];\n\n const events: NormalizedEvent[] = [];\n\n for (const result of toolResults) {\n const toolName = result.toolName ?? \"unknown\";\n const outputData = result.data ?? result.content;\n const output = typeof outputData === \"string\" ? outputData : JSON.stringify(outputData);\n\n // Check if this is a subagent result\n if (toolName === \"Agent\" || this.isSubagentResult(result)) {\n events.push(...this.handleSubagentResult(result, output));\n } else {\n events.push(...this.handleToolResult(toolName, outputData, output));\n }\n }\n\n return events;\n }\n\n private handleSubagentResult(result: AgentMessage, output: string): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const agentName = this.resolveSubagentName(result);\n const description = output.slice(0, 200);\n events.push({ type: \"subagent\", name: agentName, status: \"finished\", description });\n\n if (agentName === \"dev-server\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private handleToolResult(\n toolName: string,\n outputData: unknown,\n output: string,\n ): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_result\",\n tool: toolName,\n output: outputData,\n summary: summarizeToolResult(toolName, outputData),\n });\n\n // Detect file changes from Write/Edit results\n const fileEvents = detectFileChanges(toolName, outputData);\n if (fileEvents.length > 0) events.push(...fileEvents);\n\n // Detect dev server from Bash output\n if (toolName === \"Bash\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private isSubagentResult(result: AgentMessage): boolean {\n // Check if the tool result's id maps to a tracked subagent\n if (result.toolName && this.activeSubagents.has(result.toolName)) return true;\n return false;\n }\n\n private resolveSubagentName(result: AgentMessage): string {\n // toolName on bridge AgentMessage is resolved from toolIdToName in the driver\n const name = result.toolName ? this.activeSubagents.get(result.toolName) : undefined;\n if (name) {\n this.activeSubagents.delete(result.toolName!);\n return name;\n }\n return result.toolName ?? \"unknown\";\n }\n\n // ---------------------------------------------------------------------------\n // result → finished or error\n // ---------------------------------------------------------------------------\n\n private handleResult(event: BridgeEvent & { type: \"result\" }): NormalizedEvent[] {\n if (event.subtype === \"success\") {\n return [\n {\n type: \"finished\",\n summary: event.summary ?? \"Task completed\",\n costUsd: event.costUsd ?? 0,\n ...(event.tokens ? { tokens: event.tokens } : {}),\n },\n ];\n }\n\n const errors = event.errors ?? [];\n // Run the same classifier the claude-sdk driver uses on its `error`\n // event so the result-error path also surfaces a category and hint\n // (drivers other than claude-sdk emit `result` without a paired\n // `error`, so this is the only place they get classified).\n const detail = classifyClaudeSdkError({ errors, subtype: event.subtype });\n return [\n {\n type: \"error\",\n message: `Agent stopped: ${event.subtype}${errors.length ? ` — ${errors.join(\"; \")}` : \"\"}`,\n fatal: event.subtype === \"error_during_execution\",\n category: detail.category,\n ...(detail.hint ? { hint: detail.hint } : {}),\n },\n ];\n }\n\n // ---------------------------------------------------------------------------\n // Dev server detection\n // ---------------------------------------------------------------------------\n\n private detectDevServerStarting(command: string): NormalizedEvent | null {\n if (this.devServerStartingEmitted) return null;\n const cmd = command.toLowerCase();\n const isFrontendStart =\n (cmd.includes(\"pnpm run dev\") || cmd.includes(\"pnpm dev\") || cmd.includes(\"vite\")) &&\n (cmd.includes(\"frontend\") || cmd.includes(\"dev:preview\"));\n if (isFrontendStart) {\n this.devServerStartingEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"starting\" };\n }\n return null;\n }\n\n private detectDevServerReady(text: string): NormalizedEvent | null {\n if (this.devServerReadyEmitted) return null;\n\n const explicitMatch = text.match(/DEVSERVER_READY:(https?:\\/\\/[^\\s\"\\\\]+)/);\n if (explicitMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: explicitMatch[1]!, status: \"ready\" };\n }\n\n const viteMatch = text.match(/Local:\\s+(https?:\\/\\/localhost:\\d+)/);\n if (viteMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: viteMatch[1]!, status: \"ready\" };\n }\n\n if (text.includes(\"FRONTEND_READY\")) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"ready\" };\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n private getContentBlocks(message: AgentMessage): ContentBlock[] {\n if (Array.isArray(message.content)) return message.content;\n if (typeof message.content === \"string\" && message.content) {\n return [{ type: \"text\", text: message.content }];\n }\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pure helper functions (exported for reuse)\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a human-readable one-line summary of a tool call for the activity log.\n *\n * Returns a string like `$ git status` for Bash, `Read src/index.ts` for Read, etc.\n * Falls back to `ToolName({...input...})` for unrecognised tools.\n *\n * @param tool - Tool name (e.g. `\"Bash\"`, `\"Write\"`, `\"Grep\"`).\n * @param input - Tool input record passed to the call.\n * @returns A short display string suitable for the activity feed.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolCall(tool: string, input: Record<string, unknown>): string {\n switch (tool) {\n case \"Bash\":\n return `$ ${String(input.command ?? \"\").slice(0, 200)}`;\n case \"Write\":\n return `Create ${String(input.file_path)}`;\n case \"Edit\":\n return `Edit ${String(input.file_path)}`;\n case \"Read\":\n return `Read ${String(input.file_path)}`;\n case \"Glob\":\n return `Find ${String(input.pattern)}`;\n case \"Grep\":\n return `Search for ${String(input.pattern)}`;\n default:\n return `${tool}(${JSON.stringify(input).slice(0, 100)})`;\n }\n}\n\n/** Extract plain text from an Anthropic content-block array (e.g. tool results returned by Claude SDK). */\nfunction extractContentBlockText(blocks: unknown[]): string | null {\n const textBlocks = blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n typeof b === \"object\" &&\n b !== null &&\n (b as Record<string, unknown>).type === \"text\" &&\n typeof (b as Record<string, unknown>).text === \"string\",\n );\n if (textBlocks.length === 0) return null;\n return textBlocks.map((b) => b.text).join(\"\\n\");\n}\n\n/**\n * Produce a human-readable one-line summary of a tool result for the activity log.\n *\n * Handles Bash stdout/stderr, Write/Edit file paths, ApplyPatch change counts, and\n * Anthropic content-block arrays. Falls back to `JSON.stringify` for unknown shapes.\n *\n * @param tool - Tool name.\n * @param result - Raw tool result payload.\n * @returns A short display string, truncated to 200 characters.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolResult(tool: string, result: unknown): string {\n // Handle Anthropic content-block arrays: [{ type: \"text\", text: \"...\" }, ...]\n if (Array.isArray(result)) {\n const text = extractContentBlockText(result);\n return (text ?? JSON.stringify(result)).slice(0, 200);\n }\n if (typeof result !== \"object\" || !result) {\n return String(result).slice(0, 200);\n }\n const r = result as Record<string, unknown>;\n switch (tool) {\n case \"Bash\": {\n const stderr = String(r.stderr ?? \"\").trim();\n if (stderr) return `stderr: ${stderr.slice(0, 200)}`;\n return (\n String(r.stdout ?? \"\")\n .trim()\n .slice(0, 200) || \"(no output)\"\n );\n }\n case \"Write\":\n return `${String(r.type)}: ${String(r.filePath)}`;\n case \"Edit\":\n return `Edited ${String(r.filePath)}`;\n case \"ApplyPatch\":\n return `${Array.isArray(r.changes) ? r.changes.length : 0} file changes`;\n default:\n return JSON.stringify(result).slice(0, 200);\n }\n}\n\n/**\n * Detect file-change events from a tool result, returning zero or more `file_changed` events.\n *\n * Handles `Write` (single create/edit), `Edit` (single edit), and `ApplyPatch` (multi-file\n * patch with per-change `kind` classification). Returns an empty array for all other tools.\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns Array of `file_changed` normalized events.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChanges(toolName: string, result: unknown): NormalizedEvent[] {\n if (typeof result !== \"object\" || !result) return [];\n const r = result as Record<string, unknown>;\n\n if (toolName === \"Write\" && r.filePath) {\n return [\n {\n type: \"file_changed\",\n path: String(r.filePath),\n action: r.type === \"create\" ? \"create\" : \"edit\",\n },\n ];\n }\n if (toolName === \"Edit\" && r.filePath) {\n return [{ type: \"file_changed\", path: String(r.filePath), action: \"edit\" }];\n }\n if (toolName === \"ApplyPatch\" && Array.isArray(r.changes)) {\n return r.changes\n .filter(\n (change): change is { path: string; kind: \"add\" | \"delete\" | \"update\" } =>\n typeof change === \"object\" &&\n change !== null &&\n typeof (change as Record<string, unknown>).path === \"string\" &&\n typeof (change as Record<string, unknown>).kind === \"string\",\n )\n .map((change) => ({\n type: \"file_changed\" as const,\n path: change.path,\n action: change.kind === \"add\" ? \"create\" : change.kind === \"delete\" ? \"delete\" : \"edit\",\n }));\n }\n\n return [];\n}\n\n/**\n * Backward-compatible single-event helper; returns the first `file_changed` event or `null`.\n *\n * Prefer {@link detectFileChanges} for multi-file patches (e.g. `ApplyPatch`).\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns First detected `file_changed` event, or `null`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChange(toolName: string, result: unknown): NormalizedEvent | null {\n return detectFileChanges(toolName, result)[0] ?? null;\n}\n","/**\n * BridgeRuntime — implements IAgentRuntime from @skaile/workspaces/types by wrapping\n * an AgentDriver + EventNormalizer. This is the primary integration point for\n * consumers that want normalized events from any driver.\n */\n\nimport type {\n AgentEvent,\n AgentReconfigureOptions,\n AgentRuntimeConfig,\n IAgentRuntime,\n} from \"@skaile/workspaces/types\";\n\nimport { EventNormalizer } from \"./normalizer.js\";\nimport { createDriver } from \"./registry.js\";\nimport type { AgentConfig, AgentDriver } from \"./types.js\";\n\n/**\n * Implements `IAgentRuntime` from `@skaile/workspaces/types` by wrapping an {@link AgentDriver}\n * and an {@link EventNormalizer}.\n *\n * This is the primary integration point for consumers that want normalized `AgentEvent`\n * payloads from any driver without managing the driver lifecycle directly. Create via\n * {@link createRuntime} to avoid coupling to `BridgeRuntime` directly.\n *\n * @docLink packages/bridge/api-reference#runtime\n */\nexport class BridgeRuntime implements IAgentRuntime {\n private driver: AgentDriver | null = null;\n private normalizer = new EventNormalizer();\n private handlers = new Set<(event: AgentEvent) => void>();\n private boundEventHandler: ((event: any) => void) | null = null;\n private driverId: string;\n\n constructor(driverId: string = \"claude-sdk\") {\n this.driverId = driverId;\n }\n\n async start(config: AgentRuntimeConfig): Promise<void> {\n // Dispose previous driver if any\n if (this.driver) {\n await this.dispose();\n }\n\n this.normalizer.reset();\n\n const bridgeConfig: AgentConfig = {\n cwd: config.cwd,\n provider: config.provider,\n model: config.model,\n systemPrompt: config.systemPrompt,\n apiKeys: config.apiKeys,\n env: config.env,\n agentDir: config.agentDir,\n sessionId: config.sessionId,\n resumeSessionId: config.resumeSessionId,\n maxTurns: config.maxTurns,\n };\n\n this.driver = await createDriver(this.driverId, bridgeConfig);\n\n // Wire bridge events through normalizer to handlers\n this.boundEventHandler = (bridgeEvent: any) => {\n const normalized = this.normalizer.normalize(bridgeEvent);\n for (const event of normalized) {\n for (const handler of this.handlers) {\n handler(event);\n }\n }\n };\n this.driver.on(\"agent-event\", this.boundEventHandler);\n\n await this.driver.start();\n }\n\n async configure(_config: AgentReconfigureOptions): Promise<void> {\n // Runtime reconfiguration for BridgeRuntime is a no-op for now.\n // Future: reconnect connectors, reload ai-assets, update subagents.\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.prompt(message);\n }\n\n async reply(answer: string): Promise<void> {\n // Mirror serve.ts handleReply: an answer must resume the paused turn. Falling through to\n // prompt() would deny the question as superseded and drop the structured answer.\n if (this.driver?.hasPendingQuestion() && this.driver.answerQuestion(answer)) return;\n await this.prompt(answer);\n }\n\n async abort(): Promise<void> {\n if (this.driver) {\n await this.driver.abort();\n }\n }\n\n async dispose(): Promise<void> {\n if (this.driver) {\n if (this.boundEventHandler) {\n this.driver.off(\"agent-event\", this.boundEventHandler);\n this.boundEventHandler = null;\n }\n this.driver.kill();\n this.driver = null;\n }\n this.normalizer.reset();\n }\n\n onEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.add(handler);\n }\n\n offEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.delete(handler);\n }\n\n get isRunning(): boolean {\n return this.driver?.isRunning ?? false;\n }\n}\n\n/**\n * Factory function to create a {@link BridgeRuntime} with the specified driver.\n *\n * @param driverId - Registered driver id (default: `\"claude-sdk\"`).\n * @returns A new `IAgentRuntime` wrapping the selected driver with event normalization.\n * @docLink packages/bridge/api-reference#runtime\n */\nexport function createRuntime(driverId: string = \"claude-sdk\"): IAgentRuntime {\n return new BridgeRuntime(driverId);\n}\n","/** Provider API key validation — hits each provider's models endpoint to verify the key works. */\n\nimport { PROVIDER_ENDPOINTS } from \"./provider-endpoints.js\";\n\n/**\n * Result of an API key validation check performed by {@link validateApiKey}.\n *\n * @docLink packages/bridge/api-reference#validation\n */\nexport interface ValidationResult {\n /** `true` when the API key was accepted by the provider's models endpoint. */\n ok: boolean;\n /** Human-readable error description when `ok` is `false`. */\n error?: string;\n}\n\n/**\n * Validate an API key by sending a lightweight GET request to the provider's models endpoint.\n *\n * Returns `{ ok: true }` when the provider accepts the key (HTTP 2xx). Returns\n * `{ ok: false, error }` on 401/403 (invalid key), other HTTP errors, network failures,\n * or unsupported providers. Requests time out after 8 seconds.\n *\n * @param provider - Provider name matching a key in the shared `PROVIDER_ENDPOINTS` map\n * (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * @param key - API key to validate.\n * @returns Validation result with optional error description.\n * @docLink packages/bridge/api-reference#validation\n */\nexport async function validateApiKey(provider: string, key: string): Promise<ValidationResult> {\n const endpoint = PROVIDER_ENDPOINTS[provider];\n if (!endpoint) return { ok: false, error: `Unknown provider: ${provider}` };\n\n let url = endpoint.url;\n if (endpoint.queryParam) url += `?${endpoint.queryParam}=${encodeURIComponent(key)}`;\n\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8000);\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: endpoint.headers(key),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (response.ok) return { ok: true };\n\n const status = response.status;\n if (status === 401 || status === 403) {\n return { ok: false, error: \"Invalid API key (authentication failed)\" };\n }\n return { ok: false, error: `API returned HTTP ${status}` };\n } catch (err: any) {\n if (err.name === \"AbortError\") return { ok: false, error: \"Request timed out (8s)\" };\n return { ok: false, error: err.message ?? \"Network error\" };\n }\n}\n"]}