@skaile/workspaces 0.53.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/{asset-feeds-OEGJ6NOF.js → asset-feeds-677S5NX7.js} +7 -7
  3. package/dist/{asset-feeds-OEGJ6NOF.js.map → asset-feeds-677S5NX7.js.map} +1 -1
  4. package/dist/asset-manager/index.js +5 -5
  5. package/dist/asset-manager/installer.js +4 -4
  6. package/dist/{chunk-VGT2R662.js → chunk-43JDPQJ4.js} +3 -3
  7. package/dist/{chunk-VGT2R662.js.map → chunk-43JDPQJ4.js.map} +1 -1
  8. package/dist/{chunk-EOINYN5T.js → chunk-DW5MIJK3.js} +3 -3
  9. package/dist/{chunk-EOINYN5T.js.map → chunk-DW5MIJK3.js.map} +1 -1
  10. package/dist/{chunk-VE2UIJ7Y.js → chunk-EXNTTJGP.js} +3 -43
  11. package/dist/chunk-EXNTTJGP.js.map +1 -0
  12. package/dist/{chunk-7ZWLZ5H3.js → chunk-FLRHP3UC.js} +3 -3
  13. package/dist/{chunk-7ZWLZ5H3.js.map → chunk-FLRHP3UC.js.map} +1 -1
  14. package/dist/{chunk-V4BGVOJC.js → chunk-K5JIAHDV.js} +6 -6
  15. package/dist/{chunk-V4BGVOJC.js.map → chunk-K5JIAHDV.js.map} +1 -1
  16. package/dist/{chunk-3IHBGDCG.js → chunk-KSISPZV3.js} +2 -2
  17. package/dist/{chunk-3IHBGDCG.js.map → chunk-KSISPZV3.js.map} +1 -1
  18. package/dist/{chunk-WD2NRI3T.js → chunk-PLQVAEM2.js} +2 -2
  19. package/dist/{chunk-WD2NRI3T.js.map → chunk-PLQVAEM2.js.map} +1 -1
  20. package/dist/{chunk-TCNYSHPM.js → chunk-SFVEHSCI.js} +4 -4
  21. package/dist/{chunk-TCNYSHPM.js.map → chunk-SFVEHSCI.js.map} +1 -1
  22. package/dist/{chunk-QLLFCQU5.js → chunk-WSQ5J7CE.js} +403 -1469
  23. package/dist/chunk-WSQ5J7CE.js.map +1 -0
  24. package/dist/{chunk-BXC5547R.js → chunk-XD7GYMAU.js} +3 -3
  25. package/dist/{chunk-BXC5547R.js.map → chunk-XD7GYMAU.js.map} +1 -1
  26. package/dist/cli/index.js +30 -32
  27. package/dist/cli/index.js.map +1 -1
  28. package/dist/connectors/config.js +4 -4
  29. package/dist/connectors/index.js +5 -7
  30. package/dist/connectors/src/config.d.ts +1 -74
  31. package/dist/connectors/src/config.d.ts.map +1 -1
  32. package/dist/connectors/src/connector-manager.d.ts +13 -137
  33. package/dist/connectors/src/connector-manager.d.ts.map +1 -1
  34. package/dist/connectors/src/connector-types.d.ts +3 -25
  35. package/dist/connectors/src/connector-types.d.ts.map +1 -1
  36. package/dist/connectors/src/fleet-utils.d.ts +2 -30
  37. package/dist/connectors/src/fleet-utils.d.ts.map +1 -1
  38. package/dist/connectors/src/fs-utils.d.ts +1 -2
  39. package/dist/connectors/src/fs-utils.d.ts.map +1 -1
  40. package/dist/connectors/src/index.d.ts +2 -12
  41. package/dist/connectors/src/index.d.ts.map +1 -1
  42. package/dist/connectors/src/watcher.d.ts +1 -5
  43. package/dist/connectors/src/watcher.d.ts.map +1 -1
  44. package/dist/core/index.js +3 -3
  45. package/dist/deploy/index.js +3 -3
  46. package/dist/{ensure-sources-GJOXWVWO.js → ensure-sources-OCMHK7LT.js} +5 -5
  47. package/dist/{ensure-sources-GJOXWVWO.js.map → ensure-sources-OCMHK7LT.js.map} +1 -1
  48. package/dist/factory-assets/connectors/deploy.js +5 -7
  49. package/dist/factory-assets/connectors/devserver.js +5 -7
  50. package/dist/factory-assets/connectors/flow/adapter.js +5 -7
  51. package/dist/factory-assets/connectors/flow/engine.js +3 -3
  52. package/dist/factory-assets/connectors/flow/run-flow.js +6 -8
  53. package/dist/factory-assets/connectors/flow.js +5 -7
  54. package/dist/factory-assets/connectors/git.js +5 -7
  55. package/dist/factory-assets/connectors/gmail.js +5 -7
  56. package/dist/factory-assets/connectors/googledrive/CONNECTOR.md +14 -128
  57. package/dist/factory-assets/connectors/googledrive/driver.d.ts +6 -13
  58. package/dist/factory-assets/connectors/googledrive/driver.d.ts.map +1 -1
  59. package/dist/factory-assets/connectors/googledrive.js +5 -7
  60. package/dist/factory-assets/connectors/local.js +5 -7
  61. package/dist/factory-assets/connectors/mattermost.js +5 -7
  62. package/dist/factory-assets/connectors/memory.js +5 -7
  63. package/dist/factory-assets/connectors/minio.js +5 -7
  64. package/dist/factory-assets/connectors/postgres.js +5 -7
  65. package/dist/factory-assets/connectors/s3.js +5 -7
  66. package/dist/factory-assets/connectors/sharepoint/CONNECTOR.md +13 -159
  67. package/dist/factory-assets/connectors/sharepoint/driver.d.ts +6 -12
  68. package/dist/factory-assets/connectors/sharepoint/driver.d.ts.map +1 -1
  69. package/dist/factory-assets/connectors/sharepoint.js +5 -7
  70. package/dist/factory-assets/connectors/sqlite.js +5 -7
  71. package/dist/factory-assets/connectors/static-server.js +5 -7
  72. package/dist/factory-assets/connectors/tunnel.js +5 -7
  73. package/dist/factory-assets/connectors/webdav/CONNECTOR.md +13 -118
  74. package/dist/factory-assets/connectors/webdav/driver.d.ts +6 -15
  75. package/dist/factory-assets/connectors/webdav/driver.d.ts.map +1 -1
  76. package/dist/factory-assets/connectors/webdav.js +5 -7
  77. package/dist/factory-assets/connectors/xstate-store.js +5 -7
  78. package/dist/factory-assets/connectors/xstate.js +5 -7
  79. package/dist/{flows-AGPIE6JM.js → flows-36PZESON.js} +4 -4
  80. package/dist/{flows-AGPIE6JM.js.map → flows-36PZESON.js.map} +1 -1
  81. package/dist/library/index.js +4 -4
  82. package/dist/library/install.js +3 -3
  83. package/dist/{open-library-ERKRGH4B.js → open-library-WRFYABFP.js} +7 -7
  84. package/dist/{open-library-ERKRGH4B.js.map → open-library-WRFYABFP.js.map} +1 -1
  85. package/dist/{paths-D6RUQ522.js → paths-EUNVMONC.js} +5 -5
  86. package/dist/{paths-D6RUQ522.js.map → paths-EUNVMONC.js.map} +1 -1
  87. package/dist/{plugin-store-SGNJTBYS.js → plugin-store-35KIMX6W.js} +5 -5
  88. package/dist/{plugin-store-SGNJTBYS.js.map → plugin-store-35KIMX6W.js.map} +1 -1
  89. package/dist/runner/index.js +7 -9
  90. package/dist/sdk/asset-manager.js +5 -5
  91. package/dist/sdk/core.js +3 -3
  92. package/dist/sdk/flow.js +3 -3
  93. package/dist/sdk/index.js +7 -9
  94. package/dist/sdk/index.js.map +1 -1
  95. package/dist/sdk/runner.js +7 -9
  96. package/dist/{setup-IV2JFW3T.js → setup-HM6HATAC.js} +5 -5
  97. package/dist/{setup-IV2JFW3T.js.map → setup-HM6HATAC.js.map} +1 -1
  98. package/dist/{source-FGOMQMZT.js → source-EZ5Y3CKP.js} +8 -8
  99. package/dist/{source-FGOMQMZT.js.map → source-EZ5Y3CKP.js.map} +1 -1
  100. package/dist/{store-client-GJT2XQ5Z.js → store-client-BUUF7BPK.js} +5 -5
  101. package/dist/{store-client-GJT2XQ5Z.js.map → store-client-BUUF7BPK.js.map} +1 -1
  102. package/dist/tui/index.js +7 -9
  103. package/dist/tui/index.js.map +1 -1
  104. package/dist/workspace-plugin/adapters/mcp.js +3 -3
  105. package/dist/workspace-plugin/adapters/omp.js +3 -3
  106. package/dist/workspace-plugin/index.js +1 -1
  107. package/package.json +1 -13
  108. package/dist/chunk-OVRSNIKJ.js +0 -72
  109. package/dist/chunk-OVRSNIKJ.js.map +0 -1
  110. package/dist/chunk-QLLFCQU5.js.map +0 -1
  111. package/dist/chunk-RAIRWFAN.js +0 -843
  112. package/dist/chunk-RAIRWFAN.js.map +0 -1
  113. package/dist/chunk-VE2UIJ7Y.js.map +0 -1
  114. package/dist/connectors/rclone-config.d.ts +0 -2
  115. package/dist/connectors/rclone-config.js +0 -4
  116. package/dist/connectors/rclone-config.js.map +0 -1
  117. package/dist/connectors/rclone.d.ts +0 -2
  118. package/dist/connectors/rclone.js +0 -5
  119. package/dist/connectors/rclone.js.map +0 -1
  120. package/dist/connectors/src/fleet-health-gate.d.ts +0 -105
  121. package/dist/connectors/src/fleet-health-gate.d.ts.map +0 -1
  122. package/dist/connectors/src/mount-placeholder.d.ts +0 -131
  123. package/dist/connectors/src/mount-placeholder.d.ts.map +0 -1
  124. package/dist/connectors/src/rclone-config/googledrive.d.ts +0 -59
  125. package/dist/connectors/src/rclone-config/googledrive.d.ts.map +0 -1
  126. package/dist/connectors/src/rclone-config/index.d.ts +0 -9
  127. package/dist/connectors/src/rclone-config/index.d.ts.map +0 -1
  128. package/dist/connectors/src/rclone-config/onedrive.d.ts +0 -48
  129. package/dist/connectors/src/rclone-config/onedrive.d.ts.map +0 -1
  130. package/dist/connectors/src/rclone-config/sanitize.d.ts +0 -9
  131. package/dist/connectors/src/rclone-config/sanitize.d.ts.map +0 -1
  132. package/dist/connectors/src/rclone-config/webdav.d.ts +0 -50
  133. package/dist/connectors/src/rclone-config/webdav.d.ts.map +0 -1
  134. package/dist/connectors/src/rclone-process-manager.d.ts +0 -316
  135. package/dist/connectors/src/rclone-process-manager.d.ts.map +0 -1
  136. package/dist/connectors/src/rclone-token-refresh.d.ts +0 -84
  137. package/dist/connectors/src/rclone-token-refresh.d.ts.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../connectors/src/fs-utils.ts","../connectors/src/port-pool.ts","../connectors/src/watcher.ts","../connectors/src/rclone-process-manager.ts"],"names":["mkdir"],"mappings":";;;;;;;;;;AAkCA,eAAsB,aAAA,CAAc,KAAa,GAAA,EAA6B;AAC5E,EAAA,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AACpC,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,CAAM,KAAK,GAAK,CAAA;AAAA,EACxB,SAAS,GAAA,EAAK;AACZ,IAAA,GAAA,EAAK,MAAM,4DAAA,EAAyD;AAAA,MAClE,IAAA,EAAM,GAAA;AAAA,MACN,OAAO,GAAA,YAAe,KAAA,GA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KAAA;AACT","file":"chunk-RAIRWFAN.js","sourcesContent":["/**\n * Shared filesystem helpers for connector infrastructure.\n *\n * @docLink packages/connectors/api-reference#fs-utils\n */\n\nimport { chmod, mkdir } from \"node:fs/promises\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * mkdir(recursive) + chmod 0o770 in one call. The post-mkdir `chmod` is the\n * load-bearing piece: `mkdir(mode:)` is ANDed with the process umask\n * (typically 022 → effective mode 0o750), which strips the group-write bit\n * that `fusermount3` requires on the rclone mountpoint and rclone needs on\n * its vfs cache directory. Explicit `chmod` is umask-immune.\n *\n * EPERM on `chmod` is swallowed: when a foreign uid pre-created the\n * directory (a stray uid-1000 process inside the container or a host-side\n * platform process writing through the project bind-mount), the runner\n * cannot chmod it. The platform's agent container entrypoint runs as root\n * and heals the subtree on the next restart — see\n * `platform/docker/agent/entrypoint.sh` `_skaile_heal_ownership`. A debug\n * line is emitted when a logger is supplied so the rare-but-real heal\n * trigger is observable in session logs without adding noise on the happy\n * path.\n *\n * The chmod is *idempotent* (the syscall always fires, but a no-op when\n * the mode is already 0o770), not a no-op — kernel behaviour for chmod is\n * \"set\", not \"set-if-different\".\n *\n * @param dir Absolute or relative path to ensure exists at mode 0o770.\n * @param log Optional logger. When provided, EPERM-on-chmod emits a\n * `debug`-level entry under whatever taxonomy the caller's logger uses.\n */\nexport async function ensureDirMode(dir: string, log?: Logger): Promise<void> {\n await mkdir(dir, { recursive: true });\n try {\n await chmod(dir, 0o770);\n } catch (err) {\n log?.debug(\"chmod 0770 skipped (EPERM — entrypoint heal expected)\", {\n path: dir,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","/**\n * PortPool — allocates ports from a [min, max] range, checks OS for collisions.\n */\n\nimport { createConnection } from \"node:net\";\n\n/**\n * Allocates TCP ports from a `[min, max]` range with OS-level collision detection.\n * Used by service connector adapters (devserver, static-server) to assign local ports.\n * @docLink packages/connectors/api-reference#port-pool\n */\nexport class PortPool {\n private readonly min: number;\n private readonly max: number;\n private readonly inUse = new Set<number>();\n\n constructor(range: [number, number]) {\n this.min = range[0];\n this.max = range[1];\n }\n\n /** Allocate the next free port from the range. Checks OS for collisions. */\n async allocate(): Promise<number> {\n for (let port = this.min; port <= this.max; port++) {\n if (this.inUse.has(port)) continue;\n if (!(await PortPool.isPortFree(port))) {\n this.inUse.add(port);\n continue;\n }\n this.inUse.add(port);\n return port;\n }\n throw new Error(`No free port in range ${this.min}-${this.max}`);\n }\n\n /** Mark a port as in-use (for explicit port args or registered instances). */\n reserve(port: number): void {\n this.inUse.add(port);\n }\n\n /** Return a port to the pool. */\n release(port: number): void {\n this.inUse.delete(port);\n }\n\n /** Check if a port is currently tracked as in-use. */\n isInUse(port: number): boolean {\n return this.inUse.has(port);\n }\n\n /** Quick TCP connect test — returns true if nothing is listening. */\n static isPortFree(port: number, host = \"127.0.0.1\"): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = createConnection({ port, host });\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve(false);\n });\n socket.once(\"error\", () => {\n socket.destroy();\n resolve(true);\n });\n socket.setTimeout(500, () => {\n socket.destroy();\n resolve(true);\n });\n });\n }\n}\n","/**\n * Shared filesystem watcher factory for mountable adapters.\n *\n * Uses chokidar for cross-platform, debounced file watching.\n *\n * Automatically reads .gitignore from the watched directory and merges\n * those patterns into chokidar's ignore list. This prevents scanning\n * large generated directories (node_modules, dist, .next, etc.) that\n * most projects already declare as ignored.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n// Static import so bun --compile bundles chokidar into the binary. A dynamic\n// `await import(\"chokidar\")` is not seen by the compiler's static analyzer\n// and fails at runtime inside the /$bunfs/ virtual filesystem.\nimport chokidar from \"chokidar\";\nimport type { ConnectorChangeEvent } from \"./connector-types.js\";\nimport type { WatchHandle, WatchOptions } from \"./shared-types.js\";\n\n/**\n * Convert a glob pattern to a matcher function.\n *\n * Chokidar 5 changed string matchers to exact equality (`===`) instead of\n * glob matching. We convert our patterns to functions so chokidar can still\n * filter correctly.\n */\nfunction globToMatcher(pattern: string): (path: string) => boolean {\n // Simple segment-name patterns: **/NAME/** or **/NAME\n // Match any path that contains /NAME/ or ends with /NAME\n const segmentMatch = pattern.match(/^\\*\\*\\/([^*/?]+)\\/\\*\\*$/);\n if (segmentMatch) {\n const name = segmentMatch[1];\n return (p: string) => p.includes(`/${name}/`) || p.endsWith(`/${name}`) || p === name;\n }\n\n // Dot-prefixed segment: **/.NAME or **/.NAME/**\n const dotSegment = pattern.match(/^\\*\\*\\/(\\.[\\w#]+)(?:\\/\\*\\*)?$/);\n if (dotSegment) {\n const name = dotSegment[1];\n return (p: string) => p.includes(`/${name}/`) || p.endsWith(`/${name}`) || p === name;\n }\n\n // Extension wildcard: **/*.EXT.* or **/*.EXT\n const extMatch = pattern.match(/^\\*\\*\\/\\*(\\.\\w+(?:\\.\\*)?)/);\n if (extMatch) {\n const suffix = extMatch[1];\n if (suffix.endsWith(\".*\")) {\n // e.g. **/*.tmp.* -> match any file with .tmp. in it\n const base = suffix.slice(0, -2);\n return (p: string) => p.includes(base);\n }\n return (p: string) => p.endsWith(suffix);\n }\n\n // Suffix wildcard: **/*SUFFIX (e.g. **/*~)\n const suffixMatch = pattern.match(/^\\*\\*\\/\\*(.+)$/);\n if (suffixMatch) {\n const sfx = suffixMatch[1];\n return (p: string) => p.endsWith(sfx);\n }\n\n // Fallback: convert simple globs to regex\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \".*\");\n const re = new RegExp(`^${escaped}$`);\n return (p: string) => re.test(p);\n}\n\nconst DEFAULT_IGNORED: Array<string | ((path: string) => boolean)> = [\n (p: string) => p.includes(\"/.git/\") || p.endsWith(\"/.git\"),\n (p: string) => p.includes(\"/node_modules/\") || p.endsWith(\"/node_modules\"),\n (p: string) => p.includes(\"/.connectors/\") || p.endsWith(\"/.connectors\"),\n // Atomic-write tempfiles (Bun.write creates `<name>.tmp.<pid>.<ts>` then renames).\n // These vanish between readdir and fs.watch, causing EINVAL that crashes the process.\n (p: string) => /\\.tmp\\.\\d/.test(p),\n // Editor swap/backup files that also race with save operations.\n (p: string) => p.endsWith(\".swp\"),\n (p: string) => p.endsWith(\".swx\"),\n (p: string) => p.includes(\"/.#\"),\n (p: string) => p.endsWith(\"~\"),\n];\n/**\n * Default chokidar `awaitWriteFinish` stability threshold (ms). Exported so the\n * rclone process manager can reuse the same write-stabilization concept when\n * gating a flush on a quiescent mount.\n */\nexport const DEFAULT_DEBOUNCE_MS = 150;\n\n/**\n * Parse a .gitignore file into glob patterns suitable for chokidar's `ignored` option.\n * Handles comments, blank lines, directory patterns, and root-relative patterns.\n * Negation patterns (!) are skipped - chokidar cannot un-ignore.\n */\nfunction parseGitignore(rootDir: string): Array<(path: string) => boolean> {\n const gitignorePath = join(rootDir, \".gitignore\");\n if (!existsSync(gitignorePath)) return [];\n\n try {\n const content = readFileSync(gitignorePath, \"utf-8\");\n const matchers: Array<(path: string) => boolean> = [];\n\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\") || line.startsWith(\"!\")) continue;\n\n let pattern = line;\n\n // Strip leading / (root-relative -> convert to rootDir-relative)\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.slice(1);\n } else if (!pattern.includes(\"/\")) {\n // Bare name like \"node_modules\" or \"*.log\" -> match anywhere\n pattern = `**/${pattern}`;\n }\n\n // Directory pattern (trailing /) -> ensure it matches contents too\n if (pattern.endsWith(\"/\")) {\n matchers.push(globToMatcher(`${pattern}**`));\n } else {\n matchers.push(globToMatcher(pattern));\n // Also match as directory (e.g. \"dist\" should match \"dist/\" and \"dist/**\")\n if (!pattern.includes(\"*\") && !pattern.includes(\".\")) {\n matchers.push(globToMatcher(`${pattern}/**`));\n }\n }\n }\n\n return matchers;\n } catch {\n return [];\n }\n}\n\ntype ChokidarAction = \"create\" | \"edit\" | \"delete\";\n\nconst CHOKIDAR_EVENT_MAP: Record<string, ChokidarAction> = {\n add: \"create\",\n change: \"edit\",\n unlink: \"delete\",\n addDir: \"create\",\n unlinkDir: \"delete\",\n};\n\n/**\n * Create a cross-platform filesystem watcher on `rootDir` using chokidar.\n * Auto-reads `.gitignore` from `rootDir` and merges those patterns into the ignore list.\n * @param rootDir - Absolute path to the directory to watch.\n * @param callback - Called with each `ConnectorChangeEvent` (create / edit / delete).\n * @param options - Debounce interval and additional ignore patterns.\n * @returns A `WatchHandle` — call `.close()` to stop watching.\n * @docLink packages/connectors/api-reference#create-fs-watcher\n */\nexport async function createFsWatcher(\n rootDir: string,\n callback: (event: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n): Promise<WatchHandle> {\n const log = createLogger({ kind: \"connector\", subkind: \"watcher\", instance: rootDir });\n const gitignorePatterns = parseGitignore(rootDir);\n // Convert any remaining string patterns from options to matcher functions\n // (chokidar 5 treats strings as exact equality, not globs)\n const optionsIgnored = (options?.ignored ?? []).map((entry) =>\n typeof entry === \"string\" ? globToMatcher(entry) : entry,\n );\n const ignored = [...DEFAULT_IGNORED, ...gitignorePatterns, ...optionsIgnored];\n const debounceMs = options?.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n\n const watcher = chokidar.watch(rootDir, {\n ignoreInitial: true,\n ignored,\n awaitWriteFinish: { stabilityThreshold: debounceMs, pollInterval: 50 },\n usePolling: false,\n });\n\n // Swallow transient watch errors (EINVAL/ENOENT when a file vanishes between\n // readdir and fs.watch). Without this handler, chokidar rethrows and the\n // agent process dies.\n watcher.on(\"error\", (err) => {\n const message = err instanceof Error ? err.message : String(err);\n log.warn(\"watcher error (non-fatal)\", { message });\n });\n\n for (const [chokidarEvent, action] of Object.entries(CHOKIDAR_EVENT_MAP)) {\n (watcher as { on(event: string, fn: (fullPath: string) => void): void }).on(\n chokidarEvent,\n (fullPath: string) => {\n const rel = relative(rootDir, fullPath);\n if (!rel || rel.startsWith(\"..\")) return;\n // Normalize to forward slashes\n const normalizedPath = rel.split(\"\\\\\").join(\"/\");\n callback({ path: normalizedPath, action, source: \"filesystem\" });\n },\n );\n }\n\n return {\n close: () => watcher.close(),\n };\n}\n","/**\n * RcloneProcessManager — supervises an rclone FUSE subprocess per mount.\n *\n * Responsibilities:\n * - Spawn rclone with a per-mount config + cache dir, wait for the FUSE\n * mountpoint to appear, then return a handle.\n * - Pipe rclone's JSON-formatted log lines into the parent driver's\n * {@link Logger} via a child source `${driverName}+rclone`.\n * - Coordinate graceful stop (flush → SIGTERM → fusermount fallback).\n * - Expose `flush` (POST /vfs/refresh + poll /vfs/stats), `statSize`\n * (operations/stat → authoritative remote size, backing the read-path\n * stale-tail gate) and `status` (process liveness + cache-dir size).\n *\n * Cross-link: see `workspaces/core/CLAUDE.md` § Logging for the\n * `createLogger` / `LogStore` contract, and\n * `_devlog/specs/2026-05-01-debug-logging-design.md` for the source taxonomy.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n cp,\n mkdir,\n readdir,\n readFile,\n rename,\n rm,\n stat,\n unlink,\n writeFile,\n} from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { ensureDirMode } from \"./fs-utils.js\";\nimport { PortPool } from \"./port-pool.js\";\nimport { DEFAULT_DEBOUNCE_MS } from \"./watcher.js\";\n\n/** Module-level pool for rclone remote-control (rc) ports. */\nconst RCLONE_RC_PORTS = new PortPool([55000, 56000]);\n\n/** Default rclone `--vfs-write-back` delay; raised from 5s so a rapidly-rewritten file settles before upload (avoids mid-write \"sizes differ\" aborts). */\nexport const DEFAULT_VFS_WRITE_BACK = \"30s\";\n\n/** Consecutive failed upload retries for one object before a stuck-upload error is surfaced. */\nexport const DEFAULT_UPLOAD_STUCK_THRESHOLD = 3;\n\n/**\n * Stabilization gate defaults for {@link RcloneProcessManager.flush}. Before\n * forcing an upload we wait until the vfs cache dir has had no write for\n * `thresholdMs`, bounded by `timeoutMs` so close/hibernate never blocks\n * forever. `pollMs` reuses the watcher's write-stabilization debounce.\n */\nconst STABILIZE_THRESHOLD_MS = 1_500;\nconst STABILIZE_TIMEOUT_MS = 30_000;\nconst STABILIZE_POLL_MS = DEFAULT_DEBOUNCE_MS;\n\n/**\n * Spawn-time configuration for a single rclone FUSE mount.\n * @docLink packages/connectors/api-reference#rclone-spawn-config\n */\nexport interface RcloneSpawnConfig {\n /** Logical mount id; used as `instance` and as part of the rclone config filename. */\n mountId: string;\n /**\n * Driver name (e.g. \"sharepoint\", \"webdav\"); used to derive the rclone\n * subprocess child logger subkind: `${driverName}+rclone`.\n */\n driverName: string;\n /** Absolute path inside the container where rclone will FUSE-mount. Created if missing. */\n mountPoint: string;\n /** Absolute path inside the container for the vfs cache. Created if missing. */\n cacheDir: string;\n /** Full INI text for rclone.conf (one [remote] section, named `skaile-<mountId>`). */\n rcloneConfig: string;\n /** Remote spec, e.g. `skaile-foo:/Clients/KADK`. */\n remote: string;\n /** rclone --vfs-cache-mode value. */\n vfsCacheMode: \"minimal\" | \"writes\" | \"full\";\n /** Per-mount cache size cap. Default: '5G'. */\n cacheMaxSize?: string;\n /** Per-mount cache age cap. Default: '168h'. */\n cacheMaxAge?: string;\n /**\n * Skip rclone's post-transfer size + checksum verification by appending\n * `--ignore-size --ignore-checksum`. Default: false (verification on).\n *\n * Escape hatch for remotes that mutate uploaded bytes server-side (notably\n * SharePoint Online normalising LF→CRLF on text/html), which makes the\n * remote object a different size/hash than the local source. rclone reads\n * that as `corrupted on transfer`, deletes the upload, and retries forever,\n * so the file never durably lands. Enabling this trades integrity\n * verification for sync-ability and must only be set by drivers that have\n * confirmed the mutation is benign. Off-by-default; wired per-driver, never\n * globally.\n */\n ignoreSizeCheck?: boolean;\n /**\n * rclone `--vfs-write-back` delay (e.g. '30s', '1m'). Controls how long a\n * dirty file sits before rclone starts uploading it. Default:\n * {@link DEFAULT_VFS_WRITE_BACK}. Raise it when the agent rewrites files\n * faster than they upload, to avoid mid-write \"sizes differ\" aborts.\n */\n vfsWriteBack?: string;\n /**\n * Consecutive upload retries for one object before {@link onUploadStuck}\n * fires. Default: {@link DEFAULT_UPLOAD_STUCK_THRESHOLD}.\n */\n uploadStuckThreshold?: number;\n /**\n * Optional hook invoked once per object when its upload has failed\n * `uploadStuckThreshold` times in a row. spawn() always also logs an\n * error-level entry through the `${driverName}+rclone` child logger; this\n * hook lets callers surface the stranded file elsewhere (e.g. a sync event).\n */\n onUploadStuck?: (object: string, tries: number) => void;\n /**\n * Optional hook invoked when rclone reports an OAuth auth failure (notably\n * `invalid_client` / `couldn't fetch token`, the symptom of an expired\n * access token that rclone cannot self-refresh). Wired by the mount driver\n * to the reactive arm of its token-refresh controller. Fires per matching\n * log line; the controller dedupes via its in-flight guard + cooldown.\n */\n onAuthError?: () => void;\n /**\n * Parent driver Logger — already tagged\n * `{kind:\"mount\", subkind:<driver>, instance:<mountId>}` by ConnectorManager.\n * Used for manager-level events; rclone subprocess events go through the\n * derived `child({subkind: \\`${driverName}+rclone\\`})` logger.\n */\n log: Logger;\n}\n\n/**\n * Handle returned by `RcloneProcessManager.spawn()` once the FUSE mountpoint is confirmed.\n * @docLink packages/connectors/api-reference#rclone-handle\n */\nexport interface RcloneHandle {\n /** OS process id of the rclone subprocess. */\n pid: number;\n /** Confirmed FUSE mountpoint (echo of input). */\n mountPoint: string;\n /** Cache directory (echo of input). */\n cacheDir: string;\n /** The local rc API address rclone is bound to, e.g. '127.0.0.1:54321'. */\n rcAddr: string;\n}\n\ninterface InternalEntry {\n proc: ChildProcess;\n configPath: string;\n port: number;\n mountPoint: string;\n cacheDir: string;\n /** The full spawn config, retained so `reconfigure` can recycle the process. */\n spawnConfig: RcloneSpawnConfig;\n log: Logger;\n rcloneLog: Logger;\n /**\n * Last few stderr lines for diagnostic purposes (used in spawn-failure\n * messages).\n */\n recentStderr: string[];\n}\n\nconst HANDLES = new Map<number, InternalEntry>();\n\n/**\n * Manages rclone FUSE subprocesses for mount drivers. Stateless across instances —\n * the internal handle registry is module-scoped so a fresh `RcloneProcessManager`\n * can still find handles created by a previous instance.\n * @docLink packages/connectors/api-reference#rclone-process-manager\n */\nexport class RcloneProcessManager {\n /**\n * @param now Injectable clock (ms) used only to timestamp the quarantine dir\n * on a poisoned-cache reset, so the move-aside name is deterministic in tests.\n */\n constructor(private readonly now: () => number = Date.now) {}\n\n /**\n * Spawn an rclone FUSE mount with one-shot poisoned-cache recovery. Delegates\n * to {@link spawnOnce}; if that fails specifically because the persistent VFS\n * cache was poisoned (a prior container SIGKILLed mid-write left `vfs`/`vfsMeta`\n * referencing missing backing files), quarantine the cache and retry the mount\n * exactly once on a clean rebuild from the authoritative remote.\n *\n * The retry is single-shot and bounded: if the fresh-cache mount also fails the\n * cause is connectivity/token (not the cache), so the error propagates without\n * a second reset — never a reset/respawn loop. A non-poison failure, or a\n * poison failure with nothing to quarantine, propagates immediately.\n */\n async spawn(config: RcloneSpawnConfig): Promise<RcloneHandle> {\n try {\n return await this.spawnOnce(config);\n } catch (err) {\n if (!(err instanceof CachePoisonedMountError)) throw err;\n let quarantined: string | null;\n try {\n quarantined = await quarantineCacheDir(config.cacheDir, this.now());\n } catch (qErr) {\n // Quarantine itself failed (disk full, EPERM) — surface the ORIGINAL\n // mount error, not the quarantine error, so triage sees the real cause.\n config.log.warn(\"rclone vfs-cache quarantine failed — surfacing original mount error\", {\n cacheDir: config.cacheDir,\n error: qErr instanceof Error ? qErr.message : String(qErr),\n });\n throw err;\n }\n if (!quarantined) {\n // Nothing to quarantine — not actually a poisoned cache; rethrow.\n throw err;\n }\n config.log.warn(\n \"rclone mount failed on a poisoned vfs cache — quarantined it and retrying the mount once\",\n { cacheDir: config.cacheDir, quarantined },\n );\n // Single retry on the now-clean cache. If this also fails, propagate —\n // do NOT quarantine/retry again (the cause is no longer the cache).\n return await this.spawnOnce(config);\n }\n }\n\n /**\n * Spawn an rclone FUSE mount. Resolves once the mountpoint is confirmed\n * present in `/proc/self/mounts`. Throws on timeout, on early exit, or\n * if invariants are violated. A readiness-timeout accompanied by the\n * poisoned-cache log signature throws {@link CachePoisonedMountError} so the\n * public {@link spawn} can apply its quarantine-and-retry recovery.\n */\n protected async spawnOnce(config: RcloneSpawnConfig): Promise<RcloneHandle> {\n if (!path.isAbsolute(config.mountPoint)) {\n throw new Error(`mountPoint must be absolute: ${config.mountPoint}`);\n }\n if (!path.isAbsolute(config.cacheDir)) {\n throw new Error(`cacheDir must be absolute: ${config.cacheDir}`);\n }\n\n // Defence-in-depth: the per-connector driver already chmods these via\n // ensureDirMode, but direct callers that bypass the driver still need\n // mountPoint and cacheDir to be group-writable for fusermount3 / vfs.\n await ensureDirMode(config.mountPoint, config.log);\n await ensureDirMode(config.cacheDir, config.log);\n\n const configPath = path.join(\n tmpdir(),\n `rclone-${config.mountId}-${randomBytes(6).toString(\"hex\")}.conf`,\n );\n await writeFile(configPath, config.rcloneConfig, { mode: 0o600 });\n\n const port = await RCLONE_RC_PORTS.allocate();\n const rcAddr = `127.0.0.1:${port}`;\n const rcloneLog = config.log.child({ subkind: `${config.driverName}+rclone` });\n\n config.log.info(\"rclone spawn starting\", {\n mountPoint: config.mountPoint,\n remote: config.remote,\n vfsCacheMode: config.vfsCacheMode,\n });\n\n const args = _buildRcloneArgs(config, { configPath, rcAddr });\n\n const proc = spawn(\"rclone\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\n // Per-process tracker for the upload-stuck observability gate. When an\n // object's upload retry count crosses the threshold we log once at error\n // level (the stream otherwise stays at INFO and the failure is silent).\n const routeCtx: RcloneLogRouteContext = {\n stuckThreshold: config.uploadStuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD,\n alertedObjects: new Set<string>(),\n itemNotFoundCounts: new Map<string, number>(),\n onUploadStuck: (object, tries) => {\n rcloneLog.error(\n \"rclone upload repeatedly failing — file may be stranded in this session's cache\",\n undefined,\n { object, tries, event: \"sync_status\", phase: \"error\" },\n );\n config.onUploadStuck?.(object, tries);\n },\n onAuthError: config.onAuthError,\n };\n\n const recentStderr: string[] = [];\n const stderrTail = (line: string) => {\n recentStderr.push(line);\n if (recentStderr.length > 20) recentStderr.shift();\n };\n\n // Set once if any rclone log line carries the poisoned-cache signature, so a\n // subsequent mount-readiness failure is classified as recoverable. Applied to\n // the RAW line so it matches whether rclone emits JSON or plaintext (the\n // signature is a substring of the JSON-encoded `msg` either way).\n let cachePoisonObserved = false;\n const noteCachePoison = (line: string) => {\n if (!cachePoisonObserved && _isCachePoisonLine(line)) cachePoisonObserved = true;\n };\n\n const stdoutHandler = (line: string) => {\n noteCachePoison(line);\n _routeRcloneLogLine(line, rcloneLog, routeCtx);\n };\n const stderrHandler = (line: string) => {\n stderrTail(line);\n noteCachePoison(line);\n _routeRcloneLogLine(line, rcloneLog, routeCtx);\n };\n\n if (proc.stdout) attachLineSplitter(proc.stdout, stdoutHandler);\n if (proc.stderr) attachLineSplitter(proc.stderr, stderrHandler);\n\n let earlyExitCode: number | null = null;\n let earlyExitSignal: NodeJS.Signals | null = null;\n const earlyExit = new Promise<void>((resolve) => {\n proc.once(\"exit\", (code, signal) => {\n earlyExitCode = code;\n earlyExitSignal = signal;\n resolve();\n });\n });\n\n const mountReady = waitFor(\n async () => {\n if (earlyExitCode !== null || earlyExitSignal !== null) return false;\n return await isMountpoint(config.mountPoint);\n },\n { timeoutMs: 15_000, intervalMs: 100 },\n );\n\n const ready = await Promise.race([mountReady, earlyExit.then(() => false)]);\n\n if (!ready) {\n try {\n if (proc.exitCode === null && proc.signalCode === null) {\n proc.kill(\"SIGKILL\");\n }\n } catch {\n // ignore\n }\n await unlink(configPath).catch(() => {});\n RCLONE_RC_PORTS.release(port);\n const tail =\n recentStderr.length > 0 ? `\\nstderr tail:\\n${recentStderr.slice(-5).join(\"\\n\")}` : \"\";\n const message = `rclone failed to mount ${config.remote} at ${config.mountPoint}${tail}`;\n // A poisoned cache is recoverable — signal spawn() to quarantine + retry.\n if (cachePoisonObserved) {\n throw new CachePoisonedMountError(message);\n }\n throw new Error(message);\n }\n\n const pid = proc.pid;\n if (pid === undefined) {\n // Should never happen if mountReady resolved true, but defend anyway.\n proc.kill(\"SIGKILL\");\n await unlink(configPath).catch(() => {});\n RCLONE_RC_PORTS.release(port);\n throw new Error(\"rclone process has no pid after successful mount\");\n }\n\n const entry: InternalEntry = {\n proc,\n configPath,\n port,\n mountPoint: config.mountPoint,\n cacheDir: config.cacheDir,\n spawnConfig: config,\n log: config.log,\n rcloneLog,\n recentStderr,\n };\n HANDLES.set(pid, entry);\n\n proc.on(\"exit\", (code) => {\n // If the entry is still in the registry, this was unplanned.\n if (HANDLES.has(pid)) {\n config.log.warn(\"rclone exited unexpectedly\", { code, pid });\n }\n });\n\n config.log.info(\"rclone mountpoint confirmed\", { pid });\n\n return { pid, mountPoint: config.mountPoint, cacheDir: config.cacheDir, rcAddr };\n }\n\n /**\n * Stop an rclone subprocess. Attempts a flush first, then SIGTERM, then\n * SIGKILL + fusermount3 if `graceMs` elapses without the mountpoint\n * disappearing.\n *\n * `graceMs` bounds both the flush stabilization gate and the SIGTERM→SIGKILL\n * window — it is *not* a single total wall-clock cap: the flush also waits on\n * rclone's `/vfs/stats` drain (its own 60s ceiling) between the two.\n */\n async stop(handle: RcloneHandle, opts?: { graceMs?: number }): Promise<void> {\n const graceMs = opts?.graceMs ?? 30_000;\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n return;\n }\n\n try {\n // Bound the stabilization gate by graceMs so stop() doesn't silently add\n // the full default stabilize timeout on top of the caller's budget.\n await this.flush(handle, { stabilizeTimeoutMs: graceMs });\n } catch (err) {\n entry.log.warn(\"rclone flush before stop failed\", {\n pid: handle.pid,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n entry.log.info(\"rclone stop initiated\", { pid: handle.pid });\n\n // Remove FIRST so the exit handler doesn't fire the unplanned-exit warning.\n HANDLES.delete(handle.pid);\n\n try {\n entry.proc.kill(\"SIGTERM\");\n } catch {\n // ignore — process may already be gone\n }\n\n const unmounted = await waitFor(async () => !(await isMountpoint(entry.mountPoint)), {\n timeoutMs: graceMs,\n intervalMs: 200,\n });\n\n if (!unmounted) {\n try {\n entry.proc.kill(\"SIGKILL\");\n } catch {\n // ignore\n }\n await new Promise<void>((resolve) => {\n const fuse = spawn(\"fusermount3\", [\"-u\", entry.mountPoint], { stdio: \"ignore\" });\n fuse.once(\"exit\", () => resolve());\n fuse.once(\"error\", () => resolve());\n });\n entry.log.warn(\"rclone hard-killed\", { pid: handle.pid });\n }\n\n RCLONE_RC_PORTS.release(entry.port);\n await unlink(entry.configPath).catch(() => {});\n }\n\n /**\n * Apply a freshly-rendered rclone INI to a running mount by recycling the\n * process: flush + stop the current rclone, then re-spawn at the same\n * mountpoint/cacheDir with the new config. Returns the new handle.\n *\n * rclone holds the OAuth token in memory (baked into the config at spawn);\n * there is no rc command to swap it on a live `onedrive` backend, so a\n * recycle is the reliable way to apply a refreshed token. The vfs cache dir\n * is reused, so the remount revalidates rather than re-downloads. During the\n * brief unmount window the read-only mount-placeholder barrier underneath is\n * exposed (writes fail with EROFS, not EIO) — see ConnectorManager's\n * read-only-until-ready guarantee.\n */\n async reconfigure(handle: RcloneHandle, rcloneConfig: string): Promise<RcloneHandle> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n throw new Error(`rclone handle not found (pid=${handle.pid})`);\n }\n const nextConfig: RcloneSpawnConfig = { ...entry.spawnConfig, rcloneConfig };\n entry.log.info(\"rclone reconfigure — recycling process to apply refreshed credential\", {\n pid: handle.pid,\n });\n await this.stop(handle, { graceMs: 30_000 });\n return this.spawn(nextConfig);\n }\n\n /**\n * Force rclone to upload pending writes, then wait until the in-use\n * counter reaches zero.\n *\n * Before issuing the refresh it waits for the vfs cache dir to go quiescent\n * (no write for `stabilityThresholdMs`, bounded by `stabilizeTimeoutMs`) so a\n * close/hibernate-triggered flush doesn't snapshot a half-written file and\n * trigger rclone's mid-write \"sizes differ\" abort. Pass `stabilize: false`\n * to skip the gate.\n */\n async flush(\n handle: RcloneHandle,\n opts?: { stabilize?: boolean; stabilityThresholdMs?: number; stabilizeTimeoutMs?: number },\n ): Promise<void> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n throw new Error(`rclone handle not found (pid=${handle.pid})`);\n }\n\n if (opts?.stabilize !== false) {\n const thresholdMs = opts?.stabilityThresholdMs ?? STABILIZE_THRESHOLD_MS;\n const timeoutMs = opts?.stabilizeTimeoutMs ?? STABILIZE_TIMEOUT_MS;\n // Scan only the vfs content subtree (agent writes land here). The sibling\n // `vfsMeta/` tree is rclone housekeeping whose churn would never settle.\n const scanDir = await vfsContentDir(entry.cacheDir);\n const quiescent = await awaitQuiescent(scanDir, {\n thresholdMs,\n timeoutMs,\n pollMs: STABILIZE_POLL_MS,\n });\n if (!quiescent) {\n entry.log.warn(\"rclone cache did not stabilize before flush — proceeding anyway\", {\n pid: handle.pid,\n thresholdMs,\n timeoutMs,\n });\n }\n }\n\n const refreshRes = await fetch(`http://${handle.rcAddr}/vfs/refresh?recursive=true`, {\n method: \"POST\",\n });\n if (!refreshRes.ok) {\n const body = await refreshRes.text().catch(() => \"\");\n throw new Error(`rclone /vfs/refresh failed: ${refreshRes.status} ${body}`);\n }\n\n const ok = await waitFor(\n async () => {\n const r = await fetch(`http://${handle.rcAddr}/vfs/stats`, { method: \"GET\" });\n if (!r.ok) return false;\n const body = (await r.json()) as { inUse?: number; [k: string]: unknown };\n return body.inUse === 0;\n },\n { timeoutMs: 60_000, intervalMs: 500 },\n );\n if (!ok) {\n throw new Error(`rclone flush did not drain within 60s (pid=${handle.pid})`);\n }\n }\n\n /**\n * Authoritative remote byte size for a mount-relative path, via rclone's\n * `operations/stat` rc endpoint. Backs the mount read-path stale-tail gate:\n * `operations/stat` hits the backend object directly, so it returns the true\n * remote size even when the VFS cache is serving a non-truncated item (and\n * `statSync` on the FUSE mount reports the inflated length). Returns `null`\n * when the handle is unknown, the object is missing / a directory, or the\n * call fails — the caller then trusts the on-disk bytes.\n */\n async statSize(handle: RcloneHandle, relPath: string): Promise<number | null> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) return null;\n return fetchAuthoritativeSize(handle.rcAddr, entry.spawnConfig.remote, relPath);\n }\n\n /** Liveness + cache-dir size. */\n async status(handle: RcloneHandle): Promise<{ alive: boolean; cacheBytes: number }> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n return { alive: false, cacheBytes: 0 };\n }\n const alive = entry.proc.exitCode === null && entry.proc.signalCode === null;\n const cacheBytes = await dirSize(entry.cacheDir);\n return { alive, cacheBytes };\n }\n}\n\ninterface RcloneJsonLine {\n level?: string;\n msg?: string;\n source?: string;\n time?: string;\n object?: string;\n error?: unknown;\n}\n\n/**\n * Per-process state threaded through {@link _routeRcloneLogLine} so it can\n * detect a sustained upload failure (the same object failing to upload K times\n * in a row) and surface it exactly once, instead of letting rclone retry\n * silently at INFO level forever.\n */\nexport interface RcloneLogRouteContext {\n /** Consecutive retries for one object before {@link onUploadStuck} fires. */\n stuckThreshold?: number;\n /** Objects already alerted on, to fire once and not on every later retry. */\n alertedObjects?: Set<string>;\n /** Per-object consecutive `itemNotFound` count; escalates at {@link stuckThreshold}. */\n itemNotFoundCounts?: Map<string, number>;\n /** Called the first time an object crosses {@link stuckThreshold}. */\n onUploadStuck?: (object: string, tries: number) => void;\n /** Called when a line matches an OAuth auth-failure pattern. */\n onAuthError?: () => void;\n}\n\n/** rclone's vfs write-back failure line: \"... failed to upload try #3, will retry ...\". */\nconst UPLOAD_FAIL_RE = /failed to upload.*?try #(\\d+)/i;\n/** rclone's vfs write-back success line, used to reset the per-object alert. */\nconst UPLOAD_OK_RE = /upload succeeded/i;\n/**\n * OAuth token-level failures rclone emits when the access token is expired and\n * it cannot self-refresh (the Skaile-managed-Entra `client_secret`-stripped\n * case). `invalid_client` / `couldn't fetch token` is the confirmed prod\n * symptom; the rest cover the equivalent MSAL/refresh-grant token failures.\n * Bare HTTP `401` is intentionally excluded — rclone retries many transient\n * 401s internally without needing a token refresh; only these token-level\n * failures mean rclone is stuck.\n */\nconst AUTH_FAIL_RE =\n /invalid_client|couldn'?t fetch token|invalid_grant|InvalidAuthenticationToken/i;\n/**\n * `itemNotFound` = OneDrive/SharePoint Graph 404 on upload: transient (indexing lag,\n * self-heals on respawn) vs permanent (update-session invalidated — fixed in _buildRcloneArgs,\n * not this threshold). Counted per-object; escalates at stuck threshold. See connectors/CLAUDE.md.\n */\nconst ITEM_NOT_FOUND_RE = /itemNotFound/i;\n\n/**\n * rclone's poisoned-VFS-cache signature. A container SIGKILLed mid-write leaves\n * the persistent `--vfs-cache-mode full` write-back cache (`vfs` + `vfsMeta`)\n * inconsistent — entries reference backing files that no longer exist. On the\n * next spawn rclone replays that backlog on every boot, fails to reload, and\n * never attaches the FUSE mountpoint (the readiness probe times out). The two\n * phrasings rclone emits are \"failed to reload item\" and \"failed to add virtual\n * dir entry\"; matching either flags the failure as cache-poisoning so spawn can\n * quarantine the cache and retry once on a clean rebuild from the remote.\n */\nconst CACHE_POISON_RE = /failed to reload item|failed to add virtual dir entry/i;\n\n/**\n * Thrown by {@link RcloneProcessManager.spawnOnce} when a mount-readiness\n * failure was accompanied by the {@link CACHE_POISON_RE} signature, so\n * {@link RcloneProcessManager.spawn} knows the failure is a recoverable\n * poisoned cache (quarantine + single retry) rather than a connectivity/token\n * fault. Its `message` is the full mount-failure detail (including the stderr\n * tail), so surfacing it directly when recovery declines loses no diagnostics.\n */\nexport class CachePoisonedMountError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CachePoisonedMountError\";\n }\n}\n\n/**\n * @internal\n * True when an rclone log line carries the poisoned-VFS-cache signature\n * ({@link CACHE_POISON_RE}). Exported for tests; not part of the public API.\n */\nexport function _isCachePoisonLine(line: string): boolean {\n return CACHE_POISON_RE.test(line);\n}\n\n/**\n * Move a poisoned rclone VFS cache aside so the next spawn rebuilds a clean one\n * from the authoritative remote. Moves `<cacheDir>/vfs` + `<cacheDir>/vfsMeta`\n * (whichever exist) into `<cacheDir>/.corrupt-<ISO>` — a move-aside, never a\n * delete, so any (junk) un-uploaded bytes stay recoverable for forensics. The\n * quarantine dir is nested inside `cacheDir` (not a sibling) so it lives within\n * the per-session cache dir the platform removes wholesale on session close —\n * bounding its lifetime to the session — and rclone only reads its own\n * `vfs`/`vfsMeta` subdirs, so the dotted sibling is inert to the live mount.\n * (A bounded retain-N/reap-after-M GC of repeated resets within one long-lived\n * session is a follow-up; session-close cleanup covers the common case.)\n *\n * Returns the quarantine dir path when anything was moved, else `null` (nothing\n * to quarantine — the failure was not a poisoned cache). `nowMs` is injected for\n * deterministic test timestamps. Exported for tests; not part of the public API.\n */\nexport async function quarantineCacheDir(cacheDir: string, nowMs: number): Promise<string | null> {\n const stamp = new Date(nowMs).toISOString().replace(/[:.]/g, \"-\");\n const quarantineDir = path.join(cacheDir, `.corrupt-${stamp}`);\n // Create the destination parent BEFORE any rename so an ENOENT from rename\n // unambiguously means \"src is missing\" (not \"dst dir absent\"). An empty dir\n // (nothing moved) is cleaned up below.\n await mkdir(quarantineDir, { recursive: true });\n let moved = 0;\n for (const sub of [\"vfs\", \"vfsMeta\"] as const) {\n const src = path.join(cacheDir, sub);\n const dst = path.join(quarantineDir, sub);\n try {\n await rename(src, dst);\n } catch (err) {\n const code = (err as { code?: string } | null)?.code;\n if (code === \"ENOENT\") continue; // this cache sub doesn't exist — skip\n if (code === \"EXDEV\") {\n // Cross-device rename — fall back to copy + rm. Clean up a partial dst if\n // the copy fails, so a retry never sees a half-written quarantine (and\n // src stays put → move-aside semantics hold).\n try {\n await cp(src, dst, { recursive: true });\n } catch (cpErr) {\n await rm(dst, { recursive: true, force: true }).catch(() => undefined);\n throw cpErr;\n }\n await rm(src, { recursive: true, force: true });\n } else {\n throw err;\n }\n }\n moved += 1;\n }\n if (moved === 0) {\n // No cache subdir existed — drop the empty quarantine dir we made.\n await rm(quarantineDir, { recursive: true, force: true }).catch(() => undefined);\n return null;\n }\n return quarantineDir;\n}\n\n/**\n * @internal\n * Route a single rclone log line (JSON or raw) to the appropriate Logger\n * call. Exported for tests; not part of the public API. When `ctx` is\n * supplied, also tracks consecutive upload failures per object and invokes\n * `ctx.onUploadStuck` once the retry count for an object reaches the threshold.\n */\nexport function _routeRcloneLogLine(line: string, log: Logger, ctx?: RcloneLogRouteContext): void {\n const trimmed = line.trim();\n if (trimmed.length === 0) return;\n\n let parsed: RcloneJsonLine | null = null;\n try {\n const candidate = JSON.parse(trimmed);\n if (candidate && typeof candidate === \"object\") parsed = candidate as RcloneJsonLine;\n } catch {\n parsed = null;\n }\n\n if (!parsed) {\n if (ctx) {\n _trackUploadFailure(trimmed, undefined, ctx);\n if (AUTH_FAIL_RE.test(trimmed)) ctx.onAuthError?.();\n if (ITEM_NOT_FOUND_RE.test(trimmed)) _trackItemNotFound(undefined, trimmed, ctx);\n }\n log.info(trimmed);\n return;\n }\n\n const level = (parsed.level ?? \"INFO\").toUpperCase();\n const msg = parsed.msg ?? \"\";\n const data: Record<string, unknown> = {};\n if (parsed.object !== undefined) data.object = parsed.object;\n if (parsed.source !== undefined) data.source = parsed.source;\n\n if (ctx) {\n _trackUploadFailure(msg, parsed.object, ctx);\n const errText = typeof parsed.error === \"string\" ? parsed.error : \"\";\n if (AUTH_FAIL_RE.test(msg) || (errText && AUTH_FAIL_RE.test(errText))) ctx.onAuthError?.();\n if (ITEM_NOT_FOUND_RE.test(msg) || (errText && ITEM_NOT_FOUND_RE.test(errText))) {\n _trackItemNotFound(parsed.object, msg, ctx);\n }\n }\n\n switch (level) {\n case \"DEBUG\":\n log.debug(msg, data);\n break;\n case \"INFO\":\n case \"NOTICE\":\n log.info(msg, data);\n break;\n case \"WARNING\":\n log.warn(msg, data);\n break;\n case \"ERROR\":\n case \"CRITICAL\":\n case \"EMERGENCY\":\n case \"ALERT\":\n log.error(msg, parsed.error, data);\n break;\n default:\n log.info(msg, data);\n break;\n }\n}\n\n/**\n * @internal\n * Inspect one rclone message for an upload retry / success and update the\n * per-object alert state in `ctx`. Fires `onUploadStuck` once when an object's\n * retry count first reaches the threshold; a later success clears the alert so\n * a fresh failure run can re-trigger.\n */\nfunction _trackUploadFailure(\n msg: string,\n object: string | undefined,\n ctx: RcloneLogRouteContext,\n): void {\n const failMatch = UPLOAD_FAIL_RE.exec(msg);\n if (failMatch) {\n const tries = Number(failMatch[1]);\n const key = object ?? extractObjectFromMsg(msg) ?? \"(unknown)\";\n const threshold = ctx.stuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD;\n if (!ctx.alertedObjects) ctx.alertedObjects = new Set<string>();\n const alerted = ctx.alertedObjects;\n if (tries >= threshold && !alerted.has(key)) {\n alerted.add(key);\n ctx.onUploadStuck?.(key, tries);\n }\n return;\n }\n if (UPLOAD_OK_RE.test(msg)) {\n const key = object ?? extractObjectFromMsg(msg);\n if (key) {\n ctx.alertedObjects?.delete(key);\n ctx.itemNotFoundCounts?.delete(key);\n }\n }\n}\n\n/**\n * @internal\n * Track consecutive `itemNotFound` upload failures per object and surface via\n * `onUploadStuck` only once an object crosses the stuck threshold — the same gate\n * the retry-count path uses — rather than on the first occurrence, because\n * itemNotFound is often transient (see {@link ITEM_NOT_FOUND_RE}). A later upload\n * success clears the count (in {@link _trackUploadFailure}). Deduped against\n * `alertedObjects` so it fires at most once per stuck run, and shares that set\n * with the retry tracker so the two paths can't double-fire for one object.\n */\nfunction _trackItemNotFound(\n object: string | undefined,\n msg: string,\n ctx: RcloneLogRouteContext,\n): void {\n const key = object ?? extractObjectFromMsg(msg) ?? \"(unknown)\";\n if (!ctx.itemNotFoundCounts) ctx.itemNotFoundCounts = new Map<string, number>();\n if (!ctx.alertedObjects) ctx.alertedObjects = new Set<string>();\n const count = (ctx.itemNotFoundCounts.get(key) ?? 0) + 1;\n ctx.itemNotFoundCounts.set(key, count);\n const threshold = ctx.stuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD;\n if (count >= threshold && !ctx.alertedObjects.has(key)) {\n ctx.alertedObjects.add(key);\n ctx.onUploadStuck?.(key, count);\n }\n}\n\n/** Best-effort path extraction from a free-text rclone message. */\nfunction extractObjectFromMsg(msg: string): string | undefined {\n const m = /(?:^|\\s)([^\\s:]+\\/[^\\s:]+):/.exec(msg);\n return m?.[1];\n}\n\n/**\n * @internal\n * Build the `rclone mount` argv from a spawn config. Extracted from spawn() so\n * the flag wiring (notably `--vfs-write-back` and the conditional\n * `--ignore-size --ignore-checksum`) is unit-testable without actually\n * launching rclone. Exported for tests; not part of the public API.\n */\nexport function _buildRcloneArgs(\n config: RcloneSpawnConfig,\n io: { configPath: string; rcAddr: string },\n): string[] {\n const args = [\n \"mount\",\n config.remote,\n config.mountPoint,\n \"--config\",\n io.configPath,\n \"--cache-dir\",\n config.cacheDir,\n \"--vfs-cache-mode\",\n config.vfsCacheMode,\n \"--vfs-cache-max-size\",\n config.cacheMaxSize ?? \"5G\",\n \"--vfs-cache-max-age\",\n config.cacheMaxAge ?? \"168h\",\n \"--vfs-write-back\",\n config.vfsWriteBack ?? DEFAULT_VFS_WRITE_BACK,\n \"--vfs-cache-poll-interval\",\n \"60s\",\n \"--rc\",\n \"--rc-addr\",\n io.rcAddr,\n // loopback-only rc server — without no-auth, flush's POST /vfs/refresh 403s,\n // graceful stop fails, and the write-back cache is left dirty. Safe: nothing\n // external can reach 127.0.0.1:<port>.\n \"--rc-no-auth\",\n \"--log-level\",\n \"INFO\",\n \"--use-json-log\",\n \"--allow-other\",\n // The ro-tmpfs deferred-mount barrier is already mounted here; without this\n // rclone aborts with \"directory already mounted\". See mount-placeholder.ts.\n \"--allow-non-empty\",\n ];\n\n // Remotes that rewrite bytes on upload (SharePoint LF→CRLF) make the\n // post-transfer size/hash check fail and rclone rolls the upload back\n // forever. Both flags are needed: a byte change shifts size AND checksum.\n if (config.ignoreSizeCheck) {\n args.push(\"--ignore-size\", \"--ignore-checksum\");\n }\n\n // SharePoint invalidates rclone's resumable upload session on an in-place\n // UPDATE; a single-part PUT below 4Mi avoids it. Match the base driver before\n // any + tag — the fleet path passes \"sharepoint+fleet\". See connectors/CLAUDE.md.\n if (config.driverName.split(\"+\")[0] === \"sharepoint\") {\n args.push(\"--onedrive-upload-cutoff\", \"4Mi\");\n }\n\n return args;\n}\n\n/**\n * @internal\n * Split an rclone mount `remote` (`skaile-<id>:/base/path`) plus a\n * mount-relative path into the `{fs, remote}` pair rclone's `operations/stat`\n * rc command expects: `fs` is the backend root (`skaile-<id>:`) and `remote` is\n * the object path within it. Leading/trailing slashes are normalised away so\n * the join is stable regardless of how either side is slashed. Exported for\n * tests; not part of the public API.\n */\nexport function _operationsStatTarget(\n remote: string,\n relPath: string,\n): { fs: string; remote: string } {\n const colon = remote.indexOf(\":\");\n const fs = colon >= 0 ? remote.slice(0, colon + 1) : remote;\n const base = colon >= 0 ? remote.slice(colon + 1) : \"\";\n const joined = [base, relPath]\n .map((s) => s.replace(/^\\/+|\\/+$/g, \"\"))\n .filter((s) => s.length > 0)\n .join(\"/\");\n return { fs, remote: joined };\n}\n\n/**\n * Query rclone's `operations/stat` rc endpoint for the authoritative remote\n * size of `relPath` under `remote`. Returns the byte size, or `null` when the\n * object is missing, is a directory, the call fails, or the size is absent.\n *\n * Unlike a `statSync` on the FUSE mount, `operations/stat` resolves the object\n * against the backend directly, so it is not subject to the VFS cache's\n * non-truncated stale tail. Pass `fetchImpl` to test without a live rc server.\n */\nexport async function fetchAuthoritativeSize(\n rcAddr: string,\n remote: string,\n relPath: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<number | null> {\n const target = _operationsStatTarget(remote, relPath);\n try {\n const res = await fetchImpl(`http://${rcAddr}/operations/stat`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(target),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { item?: { Size?: number; IsDir?: boolean } | null };\n const item = body.item;\n if (!item || item.IsDir === true) return null;\n return typeof item.Size === \"number\" && item.Size >= 0 ? item.Size : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Poll `dir` until its newest file mtime is at least `thresholdMs` in the past\n * (no write for that long), or `timeoutMs` elapses. Returns true if it went\n * quiescent, false on timeout. An empty/missing dir counts as quiescent.\n */\nexport async function awaitQuiescent(\n dir: string,\n opts: { thresholdMs: number; timeoutMs: number; pollMs: number },\n): Promise<boolean> {\n const deadline = Date.now() + opts.timeoutMs;\n for (;;) {\n const newest = await newestMtimeMs(dir);\n if (newest === null || Date.now() - newest >= opts.thresholdMs) return true;\n if (Date.now() >= deadline) return false;\n await sleep(opts.pollMs);\n }\n}\n\n/**\n * Resolve the rclone vfs content subtree (`<cacheDir>/vfs`) where cached file\n * data — and therefore agent writes — land, falling back to `cacheDir` itself\n * if that subtree doesn't exist yet. Keeps the stabilization gate off rclone's\n * `vfsMeta/` housekeeping tree.\n */\nasync function vfsContentDir(cacheDir: string): Promise<string> {\n const vfs = path.join(cacheDir, \"vfs\");\n try {\n return (await stat(vfs)).isDirectory() ? vfs : cacheDir;\n } catch {\n return cacheDir;\n }\n}\n\n/**\n * Recursively find the most recent file mtime (ms) under `dir`. Returns null if\n * the dir is missing or contains no files. Symlinks are skipped — rclone's\n * cache holds only regular files and dirs.\n */\nasync function newestMtimeMs(dir: string): Promise<number | null> {\n let newest: number | null = null;\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const full = path.join(dir, String(e.name));\n if (e.isDirectory()) {\n const sub = await newestMtimeMs(full);\n if (sub !== null && (newest === null || sub > newest)) newest = sub;\n } else if (e.isFile()) {\n try {\n const s = await stat(full);\n if (newest === null || s.mtimeMs > newest) newest = s.mtimeMs;\n } catch {\n // ignore — file vanished between readdir and stat\n }\n }\n }\n } catch {\n return null;\n }\n return newest;\n}\n\n/**\n * @internal\n * Returns true if a FUSE mount is present at `mountPoint` in the given\n * /proc/self/mounts text. The fstype check (field 3, `fuse.*`) is essential:\n * the deferred-mount barrier leaves a `tmpfs` mounted at the same path, so a\n * path-only match would report the *barrier* as the confirmed mount and mask a\n * dead rclone process. Exported for tests; not part of the public API.\n */\nexport function _fuseMountPresent(procMountsText: string, mountPoint: string): boolean {\n const resolved = path.resolve(mountPoint);\n for (const raw of procMountsText.split(\"\\n\")) {\n if (raw.length === 0) continue;\n const fields = raw.split(/\\s+/);\n const mp = fields[1];\n const fstype = fields[2];\n if (!mp || !fstype) continue;\n // /proc/self/mounts encodes spaces as \\040; cheap decode.\n const decoded = mp.replace(/\\\\040/g, \" \");\n // User-space FUSE only (`fuse` or `fuse.<subtype>`); excludes the `fusectl`\n // kernel control fs. rclone mounts as `fuse.rclone`.\n if (decoded === resolved && (fstype === \"fuse\" || fstype.startsWith(\"fuse.\"))) return true;\n }\n return false;\n}\n\n/** Returns true if a FUSE mount (rclone) is live at `mountPoint`. */\nasync function isMountpoint(mountPoint: string): Promise<boolean> {\n try {\n const text = await readFile(\"/proc/self/mounts\", \"utf8\");\n return _fuseMountPresent(text, mountPoint);\n } catch {\n return false;\n }\n}\n\n/**\n * Poll `check` every `intervalMs` until it returns true or `timeoutMs`\n * elapses. Returns true on success, false on timeout.\n */\nasync function waitFor(\n check: () => Promise<boolean>,\n opts: { timeoutMs: number; intervalMs: number },\n): Promise<boolean> {\n const deadline = Date.now() + opts.timeoutMs;\n while (Date.now() < deadline) {\n if (await check()) return true;\n await sleep(opts.intervalMs);\n }\n return await check();\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/** Wire a Readable to a per-line callback, buffering partial chunks. */\nfunction attachLineSplitter(stream: Readable, onLine: (line: string) => void): void {\n let buffer = \"\";\n stream.setEncoding(\"utf8\");\n stream.on(\"data\", (chunk: string) => {\n buffer += chunk;\n let idx = buffer.indexOf(\"\\n\");\n while (idx >= 0) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n if (line.length > 0) onLine(line);\n idx = buffer.indexOf(\"\\n\");\n }\n });\n stream.on(\"end\", () => {\n if (buffer.length > 0) {\n onLine(buffer);\n buffer = \"\";\n }\n });\n}\n\n/** Recursively sum file sizes under `dir`. Returns 0 if dir does not exist. */\nasync function dirSize(dir: string): Promise<number> {\n let total = 0;\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const full = path.join(dir, String(e.name));\n if (e.isDirectory()) {\n total += await dirSize(full);\n } else if (e.isFile()) {\n try {\n const s = await stat(full);\n total += s.size;\n } catch {\n // ignore\n }\n }\n }\n } catch {\n return 0;\n }\n return total;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../connectors/src/materialized-connectors.ts","../connectors/src/secrets.ts","../connectors/src/config.ts"],"names":[],"mappings":";;;;;;AAiBO,SAAS,2BAAA,CAA4B,UAAkB,IAAA,EAAoC;AAChG,EAAA,MAAM,EAAE,MAAM,IAAA,EAAM,IAAA,KAAS,gBAAA,CAAiB,YAAA,CAAa,QAAA,EAAU,MAAM,CAAC,CAAA;AAC5E,EAAA,MAAM,EAAA,GAAK,MAAA,CAAO,IAAA,CAAK,IAAA,IAAQ,IAAI,CAAA;AACnC,EAAA,MAAM,IAAA,GAA6B;AAAA,IACjC,EAAA;AAAA,IACA,MAAA,EAAQ,MAAA,CAAO,IAAA,CAAK,MAAA,IAAU,EAAE,CAAA;AAAA,IAChC,MAAA,EAAQ,IAAA,CAAK,MAAA,KAAW,YAAA,GAAe,YAAA,GAAe;AAAA,GACxD;AACA,EAAA,IAAI,OAAO,KAAK,KAAA,KAAU,QAAA,IAAY,KAAK,KAAA,EAAO,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AACpE,EAAA,IAAI,OAAO,IAAA,CAAK,IAAA,KAAS,QAAA,EAAU,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACpD,EAAA,IAAI,OAAO,IAA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AAA;AAAA,QACA,eAAA;AAAA,QACA,WAAA,CAAY;AAAA,OACd;AAAA,IACF;AACA,IAAA,OAAO,EAAE,KAAA,EAAO,MAAA,CAAO,KAAA,EAAO,SAAA,EAAW,OAAO,SAAA,EAAU;AAAA,EAC5D;AAIA,EAAA,MAAM,MAAM,WAAA,CAAY,IAAA;AACxB,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI,GAAA,IAAO,OAAA,EAAS,KAAA,GAAQ,OAAA,CAAQ,QAAQ,GAAG,CAAA;AAAA,OAAA,IACtC,GAAA,EAAK,UAAA,CAAW,MAAM,CAAA,EAAG,KAAA,GAAQ,QAAQ,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA;AAAA,OAC7D,KAAA,GAAQ,GAAA;AACb,EAAA,OAAO,EAAE,KAAA,EAAO,SAAA,EAAW,IAAA,EAAK;AAClC","file":"chunk-VE2UIJ7Y.js","sourcesContent":["/**\n * Derive runtime connector declarations from the platform-materialized\n * `.skaile/assets/connector/<name>/CONNECTOR.md` projection.\n *\n * Connector mirror of MCP's `loadMaterializedMcpDeclarations` /\n * `deriveSingleMaterializedMcpDeclaration`. The generated `CONNECTOR.md` carries\n * a RUNTIME declaration (driver/access/auth/mode/options/mount) — distinct from\n * the catalog `CONNECTOR.md` parsed by `core/manifest.ts:fromConnectorMd`\n * (entry/fields). Driver is referenced by name (first-party; resolved via the\n * connector registry — no code-loading).\n */\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parseFrontmatter } from \"@skaile/workspaces/core\";\nimport type { ConnectorDeclaration } from \"./connector-types.js\";\n\n/** Parse a generated CONNECTOR.md (runtime projection) into a ConnectorDeclaration. */\nexport function fromMaterializedConnectorMd(filePath: string, name: string): ConnectorDeclaration {\n const { data: meta, body } = parseFrontmatter(readFileSync(filePath, \"utf8\"));\n const id = String(meta.name ?? name);\n const decl: ConnectorDeclaration = {\n id,\n driver: String(meta.driver ?? \"\"),\n access: meta.access === \"read-write\" ? \"read-write\" : \"read-only\",\n };\n if (typeof meta.label === \"string\" && meta.label) decl.label = meta.label;\n if (typeof meta.auth === \"string\") decl.auth = meta.auth;\n if (typeof meta.providerLinkId === \"string\" && meta.providerLinkId) {\n decl.providerLinkId = meta.providerLinkId;\n }\n if (meta.mode === \"agent\" || meta.mode === \"sync\") decl.mode = meta.mode;\n if (meta.options && typeof meta.options === \"object\" && !Array.isArray(meta.options)) {\n decl.options = meta.options as Record<string, unknown>;\n }\n if (meta.mount && typeof meta.mount === \"object\" && !Array.isArray(meta.mount)) {\n const m = meta.mount as Record<string, unknown>;\n decl.mount = {\n source: String(m.source ?? \"\"),\n ...(m.target !== undefined ? { target: String(m.target) } : {}),\n ...(typeof m.watch === \"boolean\" ? { watch: m.watch } : {}),\n ...(typeof m.exposeAccessToken === \"boolean\"\n ? { exposeAccessToken: m.exposeAccessToken }\n : {}),\n ...(typeof m.accessTokenTTL === \"number\" ? { accessTokenTTL: m.accessTokenTTL } : {}),\n };\n }\n const trimmedBody = body.trim();\n if (trimmedBody.length > 0) decl.instructions = trimmedBody;\n return decl;\n}\n\n/** Provide `.instance.json` config entries as defaults under the declaration's options (the CONNECTOR.md declaration wins on key collision). */\nfunction foldInstanceConfig(decl: ConnectorDeclaration, instancePath: string): void {\n if (!existsSync(instancePath)) return;\n let parsed: { config?: Record<string, unknown> };\n try {\n parsed = JSON.parse(readFileSync(instancePath, \"utf8\"));\n } catch {\n return;\n }\n const config = parsed.config;\n if (!config || typeof config !== \"object\" || Array.isArray(config)) return;\n decl.options = { ...(config as Record<string, unknown>), ...(decl.options ?? {}) };\n}\n\n/** Derive a single materialized connector declaration; null when no CONNECTOR.md. */\nexport function deriveSingleMaterializedConnectorDeclaration(\n connectorAssetsDir: string,\n name: string,\n): ConnectorDeclaration | null {\n const sub = join(connectorAssetsDir, name);\n const md = join(sub, \"CONNECTOR.md\");\n if (!existsSync(md)) return null;\n const decl = fromMaterializedConnectorMd(md, name);\n foldInstanceConfig(decl, join(sub, \".instance.json\"));\n return decl;\n}\n\n/** Scan `<projectDir>/.skaile/assets/connector/*` for materialized connectors. */\nexport function loadMaterializedConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n const root = join(projectDir, \".skaile/assets/connector\");\n if (!existsSync(root)) return [];\n const out: ConnectorDeclaration[] = [];\n for (const name of readdirSync(root)) {\n try {\n const sub = join(root, name);\n if (!statSync(sub).isDirectory()) continue;\n const decl = deriveSingleMaterializedConnectorDeclaration(root, name);\n if (decl) out.push(decl);\n } catch {\n // Per-directory failure is isolated — one bad asset never aborts the scan.\n }\n }\n return out;\n}\n","/**\n * Secret provider abstraction.\n *\n * Decouples credential resolution from process.env so secrets can be\n * provisioned over the transport bridge instead of living in the\n * container's environment.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n\nconst log = createLogger({ kind: \"connector\", subkind: \"secrets\" });\n\n// ── Interfaces ──────────────────────────────────────────────────────────────\n\n/**\n * Read-only secret resolution. Adapters receive this interface.\n * @docLink packages/connectors/api-reference#secret-provider\n */\nexport interface SecretProvider {\n /**\n * Resolve a credential reference.\n *\n * @param ref - Credential reference such as \"env:GIT_TOKEN\",\n * \"oauth:google:user@example.com\", or an inline literal.\n * @returns The resolved secret value or undefined if not found.\n */\n resolve(ref: string): string | undefined;\n /**\n * Check whether a reference can be resolved.\n *\n * @param ref - Reference to check.\n * @returns True if resolve(ref) would return a non-undefined value.\n */\n has(ref: string): boolean;\n /**\n * Return all ref strings this provider can currently resolve.\n *\n * @returns All resolvable refs (used by forge UI and ConnectorFieldMissingError).\n */\n capabilities(): string[];\n}\n\n/**\n * Extends `SecretProvider` with the ability to load secrets at runtime via `provision()`.\n * @docLink packages/connectors/api-reference#provisionable-secret-provider\n */\nexport interface ProvisionableSecretProvider extends SecretProvider {\n /** Store a batch of key-value secrets. Keys are bare names (no prefix). */\n provision(secrets: Record<string, string>): void;\n}\n\n// ── Implementations ─────────────────────────────────────────────────────────\n\n/**\n * In-memory secret store. Secrets are provisioned over the transport bridge\n * and stored in a private Map — never touching the filesystem or process.env.\n *\n * Supports ref prefixes:\n * `\"env:KEY\"` — looks up KEY in the store\n * `\"vault:KEY\"` — looks up KEY in the store (future vault compat)\n * (no prefix) — returned as an inline value (backwards compat for non-chain usages)\n * @docLink packages/connectors/api-reference#in-memory-secret-provider\n */\nexport class InMemorySecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n /**\n * Store a batch of key-value secrets.\n *\n * @param secrets - Key-value map of secret names to values. Keys are bare names (no prefix).\n */\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return this.store.get(ref.slice(4));\n if (ref.startsWith(\"vault:\")) return this.store.get(ref.slice(6));\n // Bare key: check store first, then fall back to inline literal\n const stored = this.store.get(ref);\n if (stored !== undefined) return stored;\n return ref;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `env:${k}`);\n }\n}\n\n/**\n * Delegates to `process.env`. Used in CLI/standalone mode.\n * Does NOT pass through inline literals — returns `undefined` for any ref\n * that does not start with `\"env:\"`. Use `InMemorySecretProvider` for inline\n * literals in non-chain contexts.\n * @docLink packages/connectors/api-reference#env-secret-provider\n */\nexport class EnvSecretProvider implements SecretProvider {\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return process.env[ref.slice(4)];\n return undefined; // no inline passthrough\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return Object.keys(process.env).map((k) => `env:${k}`);\n }\n}\n\n/**\n * Pre-minted credential entry. Mirrors the discriminated `CredentialMint`\n * shape from `@skaile/workspaces/types` but redeclared here to keep this package\n * free of cross-package type dependencies.\n *\n * The failure branch carries the platform-side `code` + `message` so the\n * `ConnectorManager`'s wrapped mediator can surface the real reason instead of\n * a generic \"no pre-mint\" placeholder when a mint comes back as `ok: false`.\n */\nexport type PreMintedCredential =\n | { ok: true; token: string; expiresAt: string | null; mintedAt?: string }\n | {\n ok: false;\n code?: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\";\n message?: string;\n };\n\n/**\n * Pre-minted credential store. Holds short-lived tokens delivered upfront in\n * the v3 `session_init` envelope so the runner never has to call back to the\n * platform during mount setup.\n *\n * Resolves refs of the form `mount:<id>`, `connector:<id>`, and `mcp:<id>`.\n * Returns `undefined` for any other ref so the chain falls through to the\n * next provider (`EnvSecretProvider` for `pat:env:NAME`, etc.).\n *\n * Tokens can be added/removed at runtime via {@link set} / {@link unset} so\n * `runner.add_mount` / `runner.add_connector` / `runner.add_mcp` capabilities\n * stay strictly in-process — no round trip to the platform to mint while\n * the resource is hot-attached.\n *\n * For callers that need the full mint metadata (expiry timestamp, mintedAt\n * audit fields), use {@link mintFor} instead of the bare `resolve`. The\n * `ConnectorManager` consults this for the `auth: backend` initial-mint path so\n * the driver retains the original expiry semantics.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/connectors/api-reference#pre-minted-secret-provider\n */\nexport class PreMintedSecretProvider implements SecretProvider {\n private readonly mints = new Map<string, PreMintedCredential>();\n\n /**\n * Seed pre-minted credentials from the v3 `session_init.credentials` map.\n *\n * Failed mints (`ok: false`) are stored too so callers can distinguish\n * \"not pre-minted\" from \"pre-minted but failed\"; {@link resolve} treats\n * both as `undefined`.\n *\n * @param credentials Optional initial `{ mounts, connectors, mcp }` map.\n */\n constructor(credentials?: {\n mounts?: Record<string, PreMintedCredential>;\n connectors?: Record<string, PreMintedCredential>;\n mcp?: Record<string, PreMintedCredential>;\n }) {\n if (!credentials) return;\n for (const [id, mint] of Object.entries(credentials.mounts ?? {})) {\n this.mints.set(`mount:${id}`, mint);\n }\n for (const [id, mint] of Object.entries(credentials.connectors ?? {})) {\n this.mints.set(`connector:${id}`, mint);\n }\n for (const [id, mint] of Object.entries(credentials.mcp ?? {})) {\n this.mints.set(`mcp:${id}`, mint);\n }\n }\n\n /**\n * Insert (or replace) a pre-minted credential. Used by\n * `runner.add_mount` / `runner.add_connector` / `runner.add_mcp` capability\n * handlers when the platform delivers new credentials mid-session.\n */\n set(kind: \"mount\" | \"connector\" | \"mcp\", id: string, mint: PreMintedCredential): void {\n this.mints.set(`${kind}:${id}`, mint);\n }\n\n /**\n * Remove a stored pre-minted credential. Used by the\n * `runner.remove_resource` capability handler.\n */\n unset(kind: \"mount\" | \"connector\" | \"mcp\", id: string): boolean {\n return this.mints.delete(`${kind}:${id}`);\n }\n\n /**\n * Look up the full {@link PreMintedCredential} for a `mount:` /\n * `connector:` / `mcp:` keyed entry. Callers that only need the token use\n * {@link resolve} via the chain; callers that need expiry / audit\n * metadata (e.g. ConnectorManager) use this entry point.\n */\n mintFor(kind: \"mount\" | \"connector\" | \"mcp\", id: string): PreMintedCredential | undefined {\n return this.mints.get(`${kind}:${id}`);\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (!(ref.startsWith(\"mount:\") || ref.startsWith(\"connector:\") || ref.startsWith(\"mcp:\")))\n return undefined;\n const mint = this.mints.get(ref);\n return mint?.ok ? mint.token : undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.mints.entries()].filter(([, m]) => m.ok).map(([k]) => k);\n }\n}\n\n/**\n * Forge session secret provider. Secrets are provisioned from the Forge settings\n * panel over the transport bridge. Only handles `\"forge:\"` prefixed refs — returns\n * `undefined` for all others.\n * @docLink packages/connectors/api-reference#forge-secret-provider\n */\nexport class ForgeSecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"forge:\")) return this.store.get(ref.slice(6));\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `forge:${k}`);\n }\n}\n\n/**\n * Thrown when an OAuth-secured connector field requires user authorization before\n * it can be resolved. Contains the redirect URL to open in the user's browser.\n * @docLink packages/connectors/api-reference#o-auth-required-error\n */\nexport class OAuthRequiredError extends Error {\n readonly oauthRef: string;\n readonly authUrl: string;\n readonly state: string;\n\n /**\n * @param oauthRef - The 'oauth:<service>:<account>' ref that triggered the error\n * @param authUrl - Browser URL to open for OAuth authorization\n * @param state - OAuth state token for CSRF protection and callback correlation\n */\n constructor(oauthRef: string, authUrl: string, state: string) {\n super(`OAuth authorization required for ${oauthRef}`);\n this.name = \"OAuthRequiredError\";\n this.oauthRef = oauthRef;\n this.authUrl = authUrl;\n this.state = state;\n }\n}\n\n/**\n * Shape of an OAuth token bundle stored by `OAuthSecretProvider`.\n * @docLink packages/connectors/api-reference#o-auth-token-bundle\n */\nexport interface OAuthTokenBundle {\n accessToken: string;\n refreshToken?: string;\n /** Unix timestamp in ms */\n expiry?: number;\n}\n\n/**\n * Return value of `OAuthSecretProvider.initiateFlow()`. Contains the URL and CSRF state token.\n * @docLink packages/connectors/api-reference#o-auth-flow-request\n */\nexport interface OAuthFlowRequest {\n authUrl: string;\n state: string;\n}\n\n/**\n * OAuth token provider. Handles `\"oauth:<service>:<account>\"` refs.\n * Callers must call `chain.prepareRef()` before `chain.resolve()` for `oauth:` refs.\n * @docLink packages/connectors/api-reference#o-auth-secret-provider\n */\nexport interface OAuthSecretProvider extends SecretProvider {\n /**\n * Ensure the token for this ref is fresh.\n * Refreshes if expired.\n * Throws OAuthRequiredError if no token exists and user authorization is needed.\n */\n ensureFresh(ref: string): Promise<void>;\n\n /** Initiate the OAuth authorization flow. Returns URL to open in the user's browser. */\n initiateFlow(oauthService: string, account: string): Promise<OAuthFlowRequest>;\n\n /** Exchange authorization code for tokens and store the bundle. */\n completeFlow(state: string, code: string): Promise<void>;\n}\n\n/**\n * Abstract base for vault-backed secret providers (1Password, KeePass). Subclasses\n * implement `prefix` and `loadKeys()`. Locked until `unlock(credential)` is called.\n * @docLink packages/connectors/api-reference#locked-secret-provider\n */\nexport abstract class LockedSecretProvider implements SecretProvider {\n locked = true;\n protected readonly store = new Map<string, string>();\n abstract readonly prefix: string;\n\n async unlock(credential: string): Promise<void> {\n await this.loadKeys(credential);\n this.locked = false;\n }\n\n protected abstract loadKeys(credential: string): Promise<void>;\n\n resolve(ref: string): string | undefined {\n if (this.locked) return undefined;\n if (!ref.startsWith(this.prefix)) return undefined;\n return this.store.get(ref.slice(this.prefix.length));\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n if (this.locked) return [];\n return [...this.store.keys()].map((k) => `${this.prefix}${k}`);\n }\n}\n\n// ── Known provider prefixes ──────────────────────────────────────────────────\n\nconst KNOWN_PREFIXES = [\n \"env:\",\n \"forge:\",\n \"op:\",\n \"kp:\",\n \"oauth:\",\n \"mount:\",\n \"connector:\",\n \"mcp:\",\n] as const;\n\nfunction getPrefix(ref: string): string | undefined {\n return KNOWN_PREFIXES.find((p) => ref.startsWith(p));\n}\n\n/**\n * Chains multiple `SecretProvider` instances into a single resolver.\n * - Prefixed refs (`env:`, `forge:`, `op:`, `kp:`, `oauth:`) are routed to the first provider that can resolve them.\n * - Bare refs waterfall through all providers in order.\n * - Plain literals in `skaile.yaml` options are NOT passed to the chain; `ConnectorManager` handles them before calling `resolve()`.\n * @docLink packages/connectors/api-reference#secret-provider-chain\n */\nexport class SecretProviderChain implements SecretProvider {\n /**\n * @param providers - Ordered list of providers. For prefixed refs, the first\n * provider that can resolve wins. For bare refs, waterfall through all in order.\n */\n constructor(private readonly providers: SecretProvider[]) {}\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n const prefix = getPrefix(ref);\n log.debug(\"resolve secret\", { ref, prefix: prefix ?? \"(bare)\" });\n if (prefix) {\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n // Waterfall for bare refs\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n const all = this.providers.flatMap((p) => p.capabilities());\n return [...new Set(all)];\n }\n\n /** Returns the first provider that can resolve this ref. */\n providerFor(ref: string): SecretProvider | undefined {\n for (const p of this.providers) {\n if (p.resolve(ref) !== undefined) return p;\n }\n return undefined;\n }\n\n /**\n * Calls ensureFresh(ref) on the owning provider if it implements OAuthSecretProvider.\n * No-op for providers that don't have ensureFresh().\n *\n * @param ref - Must be an \"oauth:\" prefixed ref for this to have any effect.\n * Calls ensureFresh() on the owning OAuthSecretProvider.\n */\n async prepareRef(ref: string): Promise<void> {\n const owner = this.providerFor(ref);\n if (\n owner &&\n \"ensureFresh\" in owner &&\n typeof (owner as OAuthSecretProvider).ensureFresh === \"function\"\n ) {\n try {\n await (owner as OAuthSecretProvider).ensureFresh(ref);\n } catch (err) {\n log.error(\"secret provider ensureFresh failed\", err, { ref });\n throw err;\n }\n }\n }\n}\n","/**\n * Load connector declarations from skaile.yaml.\n *\n * The top-level `mounts:` key is no longer accepted (hard cut as of Task 11).\n * Filesystem-projected backends must be declared under `connectors:` with a\n * `mount:` sub-block. See `docs/migration-mounts-to-connectors.md`.\n */\n\nimport type { ConnectorDeclaration as WorkspaceConnector } from \"@skaile/workspaces/core\";\nimport { resolveSkWorkspaceConfig } from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type {\n ConnectorDeclaration,\n TokenMediator,\n TokenMediatorResult,\n} from \"./connector-types.js\";\nimport { loadMaterializedConnectorDeclarations } from \"./materialized-connectors.js\";\n\nconst configLog = createLogger({ kind: \"connector\", subkind: \"config\" });\n\n/**\n * Read `skaile.yaml` in `projectDir` and return all declared connectors as `ConnectorDeclaration[]`.\n *\n * Throws a migration error when the legacy top-level `mounts:` key is present.\n *\n * @param projectDir - Root of the workspace (directory containing `skaile.yaml`).\n * @returns Merged array of connector declarations from `skaile.yaml` and the materialized\n * `.skaile/assets/connector/*` disk projection (Phase 2.5); empty array if neither source\n * contributes any entries. `skaile.yaml` wins on id collision.\n * @docLink packages/connectors/api-reference#load-connector-declarations\n */\nexport function loadConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n const config = resolveSkWorkspaceConfig(projectDir);\n\n // Hard cut: reject legacy top-level `mounts:` key with an actionable message.\n if (config.mounts && config.mounts.length > 0) {\n throw new Error(\n \"'mounts:' is no longer supported — move entries under 'connectors:' with a 'mount:' sub-block. See docs/migration-mounts-to-connectors.md\",\n );\n }\n\n const yamlDecls =\n config.connectors && config.connectors.length > 0\n ? config.connectors.map(workspaceConnectorToDeclaration)\n : [];\n\n // Library-assigned connectors reach the runner via the materialized disk\n // projection (Phase 2.5). skaile.yaml is explicit user config — it wins on id\n // collision; the shadowed materialized connector is logged, not silently dropped.\n const byId = new Map<string, ConnectorDeclaration>();\n for (const d of yamlDecls) byId.set(d.id, d);\n for (const d of loadMaterializedConnectorDeclarations(projectDir)) {\n if (byId.has(d.id)) {\n configLog.warn(\n `materialized connector '${d.id}' shadowed by an explicit skaile.yaml connector`,\n );\n continue;\n }\n byId.set(d.id, d);\n }\n return [...byId.values()];\n}\n\nfunction workspaceConnectorToDeclaration(c: WorkspaceConnector): ConnectorDeclaration {\n const decl: ConnectorDeclaration = {\n id: c.id,\n driver: c.driver,\n access: c.access ?? \"read-only\",\n auth: c.auth,\n options: c.options,\n };\n\n // Backend-auth routing key for live token refresh; dropping it breaks git mount mint.\n if (c.providerLinkId) decl.providerLinkId = c.providerLinkId;\n\n // Map the optional mount sub-block when present.\n if (c.mount) {\n decl.mount = {\n source: c.mount.source,\n target: c.mount.target,\n watch: c.mount.watch,\n exposeAccessToken: c.mount.exposeAccessToken,\n accessTokenTTL: c.mount.accessTokenTTL,\n };\n }\n\n return decl;\n}\n\nimport type { ForgeSecretProvider, SecretProvider } from \"./secrets.js\";\nimport { EnvSecretProvider, InMemorySecretProvider, SecretProviderChain } from \"./secrets.js\";\n\n/**\n * Build a `SecretProviderChain` for Forge session context.\n * `OAuthSecretProvider` is not wired here — it must be provided externally\n * (the Forge session manager constructs it and passes it in).\n * @param forgeProvider - The Forge-provisioned secret store.\n * @param extraProviders - Additional providers prepended to the chain (e.g. an OAuth provider).\n * @returns A chain that routes `forge:` refs to the Forge store and `env:` refs to process.env.\n * @docLink packages/connectors/api-reference#create-forge-secret-provider-chain\n */\nexport function createForgeSecretProviderChain(\n forgeProvider: ForgeSecretProvider,\n extraProviders: SecretProvider[] = [],\n): SecretProviderChain {\n return new SecretProviderChain([...extraProviders, forgeProvider, new EnvSecretProvider()]);\n}\n\n/**\n * Build a `SecretProviderChain` for CLI/standalone context.\n * `EnvSecretProvider` takes priority; `extraSecrets` are loaded into an `InMemorySecretProvider`.\n * @param extraSecrets - Inline secrets injected into memory (e.g. tokens passed via CLI flags).\n * @returns A chain that resolves `env:` refs from process.env plus any inline extras.\n * @docLink packages/connectors/api-reference#create-cli-secret-provider-chain\n */\nexport function createCliSecretProviderChain(\n extraSecrets: Record<string, string> = {},\n): SecretProviderChain {\n const mem = new InMemorySecretProvider();\n if (Object.keys(extraSecrets).length > 0) {\n mem.provision(extraSecrets);\n }\n return new SecretProviderChain([new EnvSecretProvider(), mem]);\n}\n\n// ── Auth grammar (mount-side, Tier 2 credential tiers) ───────────────────────\n\n/**\n * Provider kind for a mount auth ref.\n *\n * Two values are accepted:\n * - `pat` — static personal access token resolved via the secrets chain\n * (standalone CLI / non-platform contexts).\n * - `backend` — token minted by the platform's credential mediator over the\n * transport (`request_access_token` round-trip). Provider\n * dispatch (OAuth, GitHub App, ...) lives backend-side; the\n * runner stays provider-agnostic.\n *\n * @docLink packages/connectors/api-reference#mount-auth-kind\n */\nexport type MountAuthKind = \"pat\" | \"backend\";\n\n/**\n * Parsed mount `auth:` field.\n *\n * - `pat` → `value` is the inner secret ref (e.g. `env:NAME`).\n * - `backend` → `value` is empty (sentinel only); the runner asks the\n * backend for tokens via `request_access_token`.\n *\n * @docLink packages/connectors/api-reference#mount-auth-ref\n */\nexport interface MountAuthRef {\n kind: MountAuthKind;\n /** Prefix-stripped payload — see kind for shape. Empty for `backend`. */\n value: string;\n /** Original auth string from the declaration, kept for diagnostics. */\n raw: string;\n}\n\n/**\n * Thrown when a mount declaration's `auth:` field uses the legacy bare `env:NAME` grammar\n * or any other unrecognized form. Migrate to `pat:env:NAME` (standalone) or `backend`\n * (platform-mediated).\n * @docLink packages/connectors/api-reference#legacy-auth-grammar-error\n */\nexport class LegacyAuthGrammarError extends Error {\n readonly auth: string;\n constructor(auth: string, mountId?: string) {\n const where = mountId ? ` on mount '${mountId}'` : \"\";\n super(\n `Legacy or unrecognized auth grammar${where} ('${auth}'). ` +\n `Replace with one of:\\n` +\n ` - backend (platform-mediated, recommended)\\n` +\n ` - pat:env:NAME (standalone CLI / static token)\\n` +\n `See _devlog/specs/2026-05-06-tier-2-credential-mediation.md.`,\n );\n this.name = \"LegacyAuthGrammarError\";\n this.auth = auth;\n }\n}\n\n/**\n * Resolve the `auth: backend` initial mint for a given mount or connector id\n * by querying the secrets chain with a `${kind}:${id}` ref. Returns the\n * resolved bearer token or `undefined` if no pre-minted credential is\n * available.\n *\n * Used by the runner when wiring `ConnectorManager` to\n * answer initial-mint requests from `PreMintedSecretProvider` without\n * round-tripping to the platform. Drivers continue to receive a\n * `tokenMediator` for refresh + retry-401 paths.\n *\n * @param kind Resource family (`mount` or `connector`).\n * @param id Resource declaration id.\n * @param chain Secrets chain. Pass `undefined` to return `undefined`.\n * @returns The pre-minted token, or `undefined` if not stored on the chain.\n * @docLink packages/connectors/api-reference#resolve-backend-auth-for\n */\nexport function resolveBackendAuthFor(\n kind: \"mount\" | \"connector\",\n id: string,\n chain: import(\"./secrets.js\").SecretProvider | undefined,\n): string | undefined {\n if (!chain) return undefined;\n return chain.resolve(`${kind}:${id}`);\n}\n\n/**\n * Parse a mount-side auth ref into a typed `MountAuthRef`.\n *\n * Accepted forms:\n * - `backend` — platform-mediated mint via `request_access_token`.\n * - `pat:env:NAME` — static PAT resolved from the secrets chain.\n *\n * Rejects bare `env:NAME` (legacy) and provider-prefixed grammars (`oauth:`,\n * `github-app:`) — those moved backend-side as part of Tier-2 mediation.\n * Returns `undefined` when `auth` is absent or empty.\n *\n * @param auth - Raw `auth:` value from the mount declaration.\n * @param mountId - Optional mount id included in error messages.\n * @returns Parsed `MountAuthRef` or `undefined`.\n * @throws {LegacyAuthGrammarError} for any unrecognized grammar.\n * @docLink packages/connectors/api-reference#resolve-auth-ref\n */\nexport function resolveAuthRef(\n auth: string | undefined,\n mountId?: string,\n): MountAuthRef | undefined {\n if (!auth) return undefined;\n\n if (auth === \"backend\") {\n return { kind: \"backend\", value: \"\", raw: auth };\n }\n if (auth.startsWith(\"pat:\")) {\n return { kind: \"pat\", value: auth.slice(\"pat:\".length), raw: auth };\n }\n\n // Legacy bare `env:NAME` and the deprecated provider-prefixed grammars\n // (`oauth:`, `github-app:`) all land here.\n throw new LegacyAuthGrammarError(auth, mountId);\n}\n\n// ── rclone mount credential bridge (auth: backend) ───────────────────────────\n\n/**\n * Thrown when the backend credential mediator refuses or cannot deliver a\n * mount credential for an `auth: backend` rclone connector. Carries the\n * wire-format error code so callers can branch on it. Mirrors the git driver's\n * `TokenMediatorError`, but lives here so all three rclone drivers share it.\n *\n * @docLink packages/connectors/api-reference#mount-token-mediator-error\n */\nexport class MountTokenMediatorError extends Error {\n readonly code: Extract<TokenMediatorResult, { ok: false }>[\"code\"];\n readonly connectorId: string;\n constructor(\n message: string,\n code: Extract<TokenMediatorResult, { ok: false }>[\"code\"],\n connectorId: string,\n ) {\n super(`Mount connector '${connectorId}': backend mediator ${code} — ${message}`);\n this.name = \"MountTokenMediatorError\";\n this.code = code;\n this.connectorId = connectorId;\n }\n}\n\n/**\n * Resolve the credential *string* an rclone mount driver feeds into its\n * `parseAuthBlob` / `parseAuth` helper.\n *\n * Two cases, branched on `declaration.auth`:\n * - `backend` → the credential is minted by the platform mediator. Calls\n * `tokenMediator({connectorId, reason: 'initial'})` and returns\n * the result's `token` string verbatim (already a JSON blob for\n * sharepoint/googledrive, or a `user:pass`/bearer string for\n * webdav). Throws `MountTokenMediatorError` when the mediator\n * refuses, or a plain `Error` when no mediator is wired (the\n * standalone CLI has none — `env:`/inline auth is the path there).\n * - anything else (`env:NAME`, inline, undefined) → resolves through the\n * secrets chain (or a direct `env:`/literal lookup when no chain\n * is wired) and NEVER touches the mediator.\n *\n * For `auth: backend` the mediator also surfaces the access token's expiry,\n * which the rclone drivers use to arm a proactive refresh tick (the\n * client_secret is stripped from Skaile-managed Entra blobs, so rclone cannot\n * self-refresh) — see {@link resolveMountCredential}.\n *\n * @param declaration - The connector declaration (supplies `auth` + `id`).\n * @param secrets - Secrets chain for the legacy `env:`/inline path.\n * @param tokenMediator - Backend mediator, present only for platform sessions.\n * @returns The credential string, or `undefined` when no auth is declared.\n * @throws {MountTokenMediatorError} when the mediator refuses an `auth: backend` mint.\n * @docLink packages/connectors/api-reference#resolve-mount-credential-string\n */\nexport async function resolveMountCredentialString(\n declaration: ConnectorDeclaration,\n secrets: import(\"./secrets.js\").SecretProvider | undefined,\n tokenMediator: TokenMediator | undefined,\n): Promise<string | undefined> {\n return (await resolveMountCredential(declaration, secrets, tokenMediator, \"initial\")).token;\n}\n\n/**\n * The credential string an rclone mount driver feeds into `parseAuthBlob` /\n * `parseAuth`, paired with the access token's ISO expiry (`null` for static\n * credentials / the legacy env path).\n */\nexport interface ResolvedMountCredential {\n /** The credential string, or `undefined` when no auth is declared. */\n token: string | undefined;\n /** ISO-8601 expiry of the access token, or `null` if unknown / static. */\n expiresAt: string | null;\n}\n\n/**\n * Resolve a mount credential together with its expiry. The richer companion of\n * {@link resolveMountCredentialString}: rclone drivers use the returned\n * `expiresAt` to arm a proactive token-refresh tick, and re-call this with\n * `reason: 'refresh'` (or `'retry-401'` on the reactive path) to re-mint.\n *\n * Branches on `declaration.auth` exactly like `resolveMountCredentialString`:\n * `backend` mints through the mediator (and fails closed on refusal / empty\n * token); everything else resolves through the secrets chain (or a direct\n * `env:`/literal lookup when no chain is wired) with a `null` expiry and never\n * touches the mediator.\n *\n * @throws {MountTokenMediatorError} when the mediator refuses an `auth: backend` mint.\n * @docLink packages/connectors/api-reference#resolve-mount-credential\n */\nexport async function resolveMountCredential(\n declaration: ConnectorDeclaration,\n secrets: import(\"./secrets.js\").SecretProvider | undefined,\n tokenMediator: TokenMediator | undefined,\n reason: \"initial\" | \"refresh\" | \"retry-401\" = \"initial\",\n): Promise<ResolvedMountCredential> {\n if (declaration.auth === \"backend\") {\n if (!tokenMediator) {\n throw new Error(\n `Connector '${declaration.id}' uses 'auth: backend' but no token mediator is wired ` +\n `(standalone has none — use env:/inline auth instead).`,\n );\n }\n const result = await tokenMediator({ connectorId: declaration.id, reason });\n if (!result.ok) {\n throw new MountTokenMediatorError(result.message, result.code, declaration.id);\n }\n // Fail closed: an empty backend-minted token is a mediator bug. webdav would\n // otherwise silently fall back to an anonymous mount instead of erroring.\n if (!result.token) {\n throw new MountTokenMediatorError(\n \"mediator returned an empty token\",\n \"backend-error\",\n declaration.id,\n );\n }\n return { token: result.token, expiresAt: result.expiresAt };\n }\n\n // Non-backend auth resolves through the chain; with no chain wired (standalone)\n // fall back to a direct env:/literal lookup so inline + env: refs still resolve.\n const ref = declaration.auth;\n let token: string | undefined;\n if (ref && secrets) token = secrets.resolve(ref);\n else if (ref?.startsWith(\"env:\")) token = process.env[ref.slice(4)];\n else token = ref;\n return { token, expiresAt: null };\n}\n"]}
@@ -1,2 +0,0 @@
1
- // Auto-generated by _scripts/emit-dts-sidecars.ts — do not edit by hand.
2
- export * from "./src/rclone-config/index.js";
@@ -1,4 +0,0 @@
1
- export { renderGoogleDriveConfig, renderOneDriveConfig, renderWebDAVConfig } from '../chunk-OVRSNIKJ.js';
2
- import '../chunk-NSBPE2FW.js';
3
- //# sourceMappingURL=rclone-config.js.map
4
- //# sourceMappingURL=rclone-config.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"rclone-config.js"}
@@ -1,2 +0,0 @@
1
- // Auto-generated by _scripts/emit-dts-sidecars.ts — do not edit by hand.
2
- export * from "./src/rclone-process-manager.js";
@@ -1,5 +0,0 @@
1
- export { CachePoisonedMountError, DEFAULT_UPLOAD_STUCK_THRESHOLD, DEFAULT_VFS_WRITE_BACK, RcloneProcessManager, _buildRcloneArgs, _fuseMountPresent, _isCachePoisonLine, _operationsStatTarget, _routeRcloneLogLine, awaitQuiescent, fetchAuthoritativeSize, quarantineCacheDir } from '../chunk-RAIRWFAN.js';
2
- import '../chunk-JB35MVBN.js';
3
- import '../chunk-NSBPE2FW.js';
4
- //# sourceMappingURL=rclone.js.map
5
- //# sourceMappingURL=rclone.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"rclone.js"}
@@ -1,105 +0,0 @@
1
- /**
2
- * FleetHealthGate — health-aware read-only gating for a single fleet-managed mount.
3
- *
4
- * Why this exists: a fleet-managed mount is bound live by the host fleet rclone,
5
- * so it is excluded from the boot-time no-phantom-workspace barrier (the host
6
- * already put real content at the target — a static barrier would shadow it).
7
- * That exclusion is only safe while the fleet rclone is healthy. When it wedges —
8
- * returning `EIO`, or degrading to an empty-but-writable view — the agent cannot
9
- * tell "empty because broken" from "empty workspace" and writes a phantom
10
- * workspace that diverges from the remote (the 2026-06-04 incident, except fleet
11
- * mounts sit outside the barrier).
12
- *
13
- * This gate closes that window. It dynamically drives a `MountPlaceholderBarrier`
14
- * over the *live* fleet target across THREE surfaces, because read availability
15
- * and write availability are independent:
16
- * - open = `remove(target)` — no barrier; live bind exposed read-write.
17
- * - ro = `exposeReadOnly(target)` — content visible, writes blocked. The
18
- * mount is live and READABLE but uploads are degraded; masking the
19
- * visible content would be wrong, so it is left read-only-readable.
20
- * - masked = `establish(target)` — opaque read-only tmpfs. The mount is not
21
- * live / unreadable; there is nothing trustworthy to show.
22
- *
23
- * Verdict → surface: `healthy` → open, `degraded` → ro, `error` → masked.
24
- *
25
- * Invariants:
26
- * - FAIL-CLOSED: if a barrier op throws, the target is treated as gated read-
27
- * only (masked). A known-unhealthy fleet mount is never left writable.
28
- * - HYSTERESIS: a surface change applies only after a verdict repeats
29
- * `threshold` times — moving toward writable uses `healthyThreshold`, moving
30
- * away (ro/masked) uses `unhealthyThreshold` — so a single transient blip
31
- * does not flap surfaces.
32
- * - IDEMPOTENT: barrier ops fire only on an actual surface change, so steady-
33
- * state polling does no mount work.
34
- */
35
- import type { Logger } from "@skaile/workspaces/types";
36
- import type { FleetHealthVerdict } from "./fleet-utils.js";
37
- import type { MountPlaceholderBarrier } from "./mount-placeholder.js";
38
- /** The barrier surface currently applied (or being transitioned to) over the target. */
39
- export type FleetGateSurface = "open" | "ro" | "masked";
40
- export interface FleetHealthGateOptions {
41
- /** Consecutive unhealthy observations required to gate (default 2). */
42
- unhealthyThreshold?: number;
43
- /** Consecutive healthy observations required to ungate (default 2). */
44
- healthyThreshold?: number;
45
- /**
46
- * The surface the barrier already holds when the gate is constructed. Defaults
47
- * to `"open"` (no barrier — the normal fleet path). Set to `"masked"` when a
48
- * gate is created lazily over a target that already carries a static boot-time
49
- * barrier, so the first recovering verdict actually removes it.
50
- */
51
- initialSurface?: FleetGateSurface;
52
- }
53
- type Surface = FleetGateSurface;
54
- /**
55
- * Per-target health gate. Construct one per fleet-managed mount target; feed it
56
- * verdicts via `observe()`; tear it down with `dispose()` (removes the gate if
57
- * any barrier is established, so teardown leaves nothing un-writable that should
58
- * not be — caller controls ordering relative to connector disconnect).
59
- */
60
- export declare class FleetHealthGate {
61
- private readonly target;
62
- private readonly barrier;
63
- private readonly log?;
64
- private readonly unhealthyThreshold;
65
- private readonly healthyThreshold;
66
- /** The barrier surface actually applied to the target right now. */
67
- private surface;
68
- /**
69
- * The surface the most recently *enqueued* transition will settle on.
70
- * Hysteresis and re-enqueue de-duping are measured against this, not
71
- * `surface`, so verdicts arriving while a (slow, async) barrier op is still in
72
- * flight are counted toward the post-transition surface, not the stale one.
73
- */
74
- private pendingSurface;
75
- /** The surface of the *current* same-verdict run, and its length. */
76
- private runSurface;
77
- private runLength;
78
- /** Serialises barrier ops so overlapping observe() calls can't race. */
79
- private transition;
80
- constructor(target: string, barrier: MountPlaceholderBarrier, log?: Logger | undefined, opts?: FleetHealthGateOptions);
81
- /** True while any read-only barrier (ro or masked) is established. */
82
- get isGated(): boolean;
83
- /** The currently-applied surface (test/observability hook). */
84
- get currentSurface(): Surface;
85
- /** The mount target this gate guards (recovery-probe lookup). */
86
- get mountTarget(): string;
87
- /**
88
- * Feed one health verdict. Applies hysteresis, then drives the barrier toward
89
- * the target surface on a change. Resolves once the (possibly no-op)
90
- * transition is applied. Never throws — a failed barrier op stays gated
91
- * (fail-closed).
92
- */
93
- observe(verdict: FleetHealthVerdict): Promise<void>;
94
- /**
95
- * Tear the gate down. If any barrier is established (or in flight), removes it
96
- * so a leftover read-only surface is not leaked. Call only after the connector
97
- * above the target is disconnected (top-down, no leaked mount).
98
- */
99
- dispose(): Promise<void>;
100
- private enqueue;
101
- /** Drive the barrier to `desired`, fail-closed to `masked` on any throw. */
102
- private apply;
103
- }
104
- export {};
105
- //# sourceMappingURL=fleet-health-gate.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fleet-health-gate.d.ts","sourceRoot":"","sources":["../../../connectors/src/fleet-health-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AACvD,OAAO,KAAK,EAAE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C;IAmBnD;;;;OAIG;IACH,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAMxB,OAAO,CAAC,OAAO;IAKf,4EAA4E;YAC9D,KAAK;CAmDpB"}
@@ -1,131 +0,0 @@
1
- /**
2
- * MountPlaceholderBarrier — a read-only barrier at a deferred mount target.
3
- *
4
- * Why this exists: `connectAll({ deferMounts: true })` brings rclone-backed
5
- * filesystem mounts up in the background, after `session_init_ack`. Until the
6
- * real mount is live, the target would otherwise be a bare, writable local dir.
7
- * An agent that goes live in that window cannot tell "empty because unmounted"
8
- * from "empty workspace" and writes a phantom workspace that diverges from the
9
- * remote (confirmed in prod 2026-06-04 — see
10
- * `_devlog/entries/2026-06-04-readonly-deferred-mount-barrier.md`).
11
- *
12
- * The guarantee must hold at the filesystem layer, not just as an LLM notice:
13
- * a plain `chmod` is bypassable because the owning uid can chmod back, whereas
14
- * a read-only mount cannot. So the default barrier mounts a read-only tmpfs
15
- * over the target (the container already has CAP_SYS_ADMIN for FUSE). When that
16
- * is not available it degrades to a `chmod 0o555` — strictly better than a
17
- * writable dir, with a loud error so the degraded state is observable.
18
- *
19
- * Lifecycle, driven by `ConnectorManager`:
20
- * 1. `establish(target)` — synchronously in the eager phase, before ack.
21
- * 2. `prepareForStackedMount(target)` — immediately before the deferred
22
- * connector's in-container rclone mount. Lifts the barrier to read-write
23
- * (remount rw / chmod 0o755) so `fusermount3` can mount over the target —
24
- * it requires WRITE access to the mountpoint and a `ro` tmpfs denies it for
25
- * every uid. The tmpfs stays mounted and is shadowed by the real mount.
26
- * 3a. `onMountLive(target)` — the real rclone mount stacks on top and provides
27
- * write access (it physically shadows the placeholder); no fs change is
28
- * needed. In the degraded chmod mode the sentinel is cleaned up.
29
- * 3b. `restoreBarrier(target)` — instead of 3a, when the mount FAILED:
30
- * re-assert read-only so a failed mount never leaves the target writable.
31
- * 4. `remove(target)` — on teardown, after the rclone mount above it is gone.
32
- *
33
- * `exposeReadOnly(target)` is an out-of-band downgrade (driven by the fleet
34
- * health gate): when the underlying mount is live and readable but writes are
35
- * degraded, it removes any opaque mask and read-only-binds the live target so
36
- * the real content stays visible while writes are blocked — read and write
37
- * availability are independent, so masking visible content would be wrong.
38
- */
39
- import type { Logger } from "@skaile/workspaces/types";
40
- /** Dropped into the placeholder so a peeking agent/operator sees why it is read-only. */
41
- export declare const NOT_READY_SENTINEL = ".skaile-workspace-not-ready";
42
- /**
43
- * A read-only barrier over a deferred mount target. Injected into
44
- * `ConnectorManager` so tests can substitute a hermetic implementation.
45
- */
46
- export interface MountPlaceholderBarrier {
47
- /** Make `target` read-only and drop the sentinel. Idempotent per target. */
48
- establish(target: string, log?: Logger): Promise<void>;
49
- /**
50
- * Make `target` writable to the mounting uid so an in-container FUSE mount
51
- * (rclone) can stack on top. `fusermount3` requires WRITE access to the
52
- * mountpoint and a `ro` tmpfs / `0o555` dir denies it for *every* uid — so the
53
- * barrier must be lifted before the real mount spawns, not after. Called by
54
- * `ConnectorManager` immediately before a deferred connector's mount. The
55
- * tmpfs stays mounted (shadowed by the real mount once it lands), so the bare
56
- * underlying dir is never exposed as a writable phantom target. Optional:
57
- * absent on hermetic test fakes. Idempotent per target.
58
- */
59
- prepareForStackedMount?(target: string, log?: Logger): Promise<void>;
60
- /**
61
- * Re-assert the read-only barrier after a deferred mount attempt FAILED, so a
62
- * failed mount never leaves the target writable. The inverse of
63
- * `prepareForStackedMount`. Optional.
64
- */
65
- restoreBarrier?(target: string, log?: Logger): Promise<void>;
66
- /**
67
- * Signal that the real mount is now live on top of `target` and provides
68
- * write access. The placeholder stays tracked so `remove()` still tears it
69
- * down on teardown.
70
- */
71
- onMountLive(target: string, log?: Logger): Promise<void>;
72
- /**
73
- * Downgrade the barrier to a READ-ONLY surface that still exposes the live
74
- * content underneath, instead of the opaque mask `establish` puts up. Used
75
- * when the underlying mount is live and fully READABLE but writes are degraded
76
- * (e.g. fleet upload errors): read and write availability are independent, so
77
- * masking the readable content is wrong — the agent should still see it,
78
- * read-only. Removes any opaque tmpfs first (revealing the propagated bind),
79
- * then read-only-binds the live target onto itself so writes fail for every
80
- * uid while reads succeed. Idempotent per target. Optional: absent on hermetic
81
- * test fakes (callers fall back to `establish`).
82
- */
83
- exposeReadOnly?(target: string, log?: Logger): Promise<void>;
84
- /** Tear the barrier down. Call only after any mount stacked above it is gone. */
85
- remove(target: string, log?: Logger): Promise<void>;
86
- /**
87
- * True when the barrier currently OPAQUELY masks `target` (an `establish`-mode
88
- * tmpfs shadows the real content). The recovery probe needs this: over an opaque
89
- * mask a direct `stat`/`readdir` reads the mask (mode 0555, always "healthy") and
90
- * cannot see a recovered host mount, so the manager falls back to the mount
91
- * table; non-opaque surfaces (chmod / ro-bind) expose the live inode directly.
92
- * Optional: absent on hermetic test fakes (the manager treats absent as
93
- * not-opaque, so the live inode is read directly). Idempotent per target.
94
- */
95
- isOpaque?(target: string): boolean;
96
- }
97
- /** Runs an external command, rejecting on non-zero exit or spawn error. */
98
- export type CommandRunner = (cmd: string, args: string[]) => Promise<void>;
99
- /**
100
- * Creates the target directory. Injectable so tests can simulate a live/broken
101
- * FUSE mountpoint (EEXIST / ENOTCONN) deterministically; defaults to a recursive
102
- * `mkdir`.
103
- */
104
- export type MkdirFn = (target: string) => Promise<void>;
105
- /**
106
- * Default barrier: a read-only tmpfs over the target, with a `chmod 0o555`
107
- * fallback when mounting is unavailable. The tmpfs root is left mode 0o755
108
- * (owner-traversable, owned by the mounting uid so `fusermount3` can later
109
- * stack the real mount on top) and made unwritable by the `ro` mount flag, not
110
- * by stripping mode bits — a `ro` mount blocks writes for every uid.
111
- */
112
- export declare class RoMountPlaceholderBarrier implements MountPlaceholderBarrier {
113
- private readonly run;
114
- private readonly mkdirFn;
115
- private readonly modes;
116
- constructor(opts?: {
117
- run?: CommandRunner;
118
- mkdirFn?: MkdirFn;
119
- });
120
- establish(target: string, log?: Logger): Promise<void>;
121
- prepareForStackedMount(target: string, log?: Logger): Promise<void>;
122
- restoreBarrier(target: string, log?: Logger): Promise<void>;
123
- onMountLive(target: string, log?: Logger): Promise<void>;
124
- exposeReadOnly(target: string, log?: Logger): Promise<void>;
125
- isOpaque(target: string): boolean;
126
- remove(target: string, log?: Logger): Promise<void>;
127
- private chmodFallback;
128
- }
129
- /** Shared default barrier instance used by `ConnectorManager` unless overridden. */
130
- export declare const defaultMountPlaceholderBarrier: MountPlaceholderBarrier;
131
- //# sourceMappingURL=mount-placeholder.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mount-placeholder.d.ts","sourceRoot":"","sources":["../../../connectors/src/mount-placeholder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAKH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAEvD,yFAAyF;AACzF,eAAO,MAAM,kBAAkB,gCAAgC,CAAC;AA2BhE;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACtC,4EAA4E;IAC5E,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACvD;;;;;;;;;OASG;IACH,sBAAsB,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACrE;;;;OAIG;IACH,cAAc,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D;;;;OAIG;IACH,WAAW,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACzD;;;;;;;;;;OAUG;IACH,cAAc,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC7D,iFAAiF;IACjF,MAAM,CAAC,MAA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