@skaile/workspaces 0.41.3 → 0.41.5

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 (48) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/asset-manager/index.js +1 -1
  3. package/dist/{chunk-Z6DAVEDZ.js → chunk-2ZI2FFFN.js} +3 -3
  4. package/dist/{chunk-Z6DAVEDZ.js.map → chunk-2ZI2FFFN.js.map} +1 -1
  5. package/dist/{chunk-C5UK3JK7.js → chunk-5VJVSYXX.js} +18 -9
  6. package/dist/chunk-5VJVSYXX.js.map +1 -0
  7. package/dist/{chunk-BKJLWPRR.js → chunk-ACB3AOII.js} +3 -3
  8. package/dist/{chunk-BKJLWPRR.js.map → chunk-ACB3AOII.js.map} +1 -1
  9. package/dist/{chunk-YG3CG6QR.js → chunk-IODU6UDT.js} +2 -2
  10. package/dist/{chunk-YG3CG6QR.js.map → chunk-IODU6UDT.js.map} +1 -1
  11. package/dist/{chunk-S4XVD4T3.js → chunk-JILPU5VI.js} +4 -4
  12. package/dist/{chunk-S4XVD4T3.js.map → chunk-JILPU5VI.js.map} +1 -1
  13. package/dist/{chunk-BNBHHVZ5.js → chunk-TNYWP6EQ.js} +2 -2
  14. package/dist/{chunk-BNBHHVZ5.js.map → chunk-TNYWP6EQ.js.map} +1 -1
  15. package/dist/cli/index.js +6 -6
  16. package/dist/connectors/index.js +2 -2
  17. package/dist/connectors/rclone.js +1 -1
  18. package/dist/connectors/src/rclone-process-manager.d.ts +2 -0
  19. package/dist/connectors/src/rclone-process-manager.d.ts.map +1 -1
  20. package/dist/factory-assets/connectors/deploy.js +2 -2
  21. package/dist/factory-assets/connectors/devserver.js +2 -2
  22. package/dist/factory-assets/connectors/flow/adapter.js +2 -2
  23. package/dist/factory-assets/connectors/flow/run-flow.js +3 -3
  24. package/dist/factory-assets/connectors/flow.js +2 -2
  25. package/dist/factory-assets/connectors/git.js +2 -2
  26. package/dist/factory-assets/connectors/gmail.js +2 -2
  27. package/dist/factory-assets/connectors/googledrive.js +2 -2
  28. package/dist/factory-assets/connectors/local.js +2 -2
  29. package/dist/factory-assets/connectors/mattermost.js +2 -2
  30. package/dist/factory-assets/connectors/memory.js +2 -2
  31. package/dist/factory-assets/connectors/minio.js +2 -2
  32. package/dist/factory-assets/connectors/postgres.js +2 -2
  33. package/dist/factory-assets/connectors/s3.js +2 -2
  34. package/dist/factory-assets/connectors/sharepoint.js +2 -2
  35. package/dist/factory-assets/connectors/sqlite.js +2 -2
  36. package/dist/factory-assets/connectors/static-server.js +2 -2
  37. package/dist/factory-assets/connectors/tunnel.js +2 -2
  38. package/dist/factory-assets/connectors/webdav.js +2 -2
  39. package/dist/factory-assets/connectors/xstate-store.js +2 -2
  40. package/dist/factory-assets/connectors/xstate.js +2 -2
  41. package/dist/runner/index.js +4 -4
  42. package/dist/sdk/asset-manager.js +1 -1
  43. package/dist/sdk/index.js +4 -4
  44. package/dist/sdk/runner.js +4 -4
  45. package/dist/tui/index.js +4 -4
  46. package/dist/workspace-plugin/index.js +1 -1
  47. package/package.json +1 -1
  48. package/dist/chunk-C5UK3JK7.js.map +0 -1
@@ -225,6 +225,7 @@ var RcloneProcessManager = class {
225
225
  const routeCtx = {
226
226
  stuckThreshold: config.uploadStuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD,
227
227
  alertedObjects: /* @__PURE__ */ new Set(),
228
+ itemNotFoundCounts: /* @__PURE__ */ new Map(),
228
229
  onUploadStuck: (object, tries) => {
229
230
  rcloneLog.error(
230
231
  "rclone upload repeatedly failing \u2014 file may be stranded in this session's cache",
@@ -464,7 +465,7 @@ function _routeRcloneLogLine(line, log, ctx) {
464
465
  if (ctx) {
465
466
  _trackUploadFailure(trimmed, void 0, ctx);
466
467
  if (AUTH_FAIL_RE.test(trimmed)) ctx.onAuthError?.();
467
- if (ITEM_NOT_FOUND_RE.test(trimmed)) _trackNonRetryableUpload(void 0, trimmed, ctx);
468
+ if (ITEM_NOT_FOUND_RE.test(trimmed)) _trackItemNotFound(void 0, trimmed, ctx);
468
469
  }
469
470
  log.info(trimmed);
470
471
  return;
@@ -479,7 +480,7 @@ function _routeRcloneLogLine(line, log, ctx) {
479
480
  const errText = typeof parsed.error === "string" ? parsed.error : "";
480
481
  if (AUTH_FAIL_RE.test(msg) || errText && AUTH_FAIL_RE.test(errText)) ctx.onAuthError?.();
481
482
  if (ITEM_NOT_FOUND_RE.test(msg) || errText && ITEM_NOT_FOUND_RE.test(errText)) {
482
- _trackNonRetryableUpload(parsed.object, msg, ctx);
483
+ _trackItemNotFound(parsed.object, msg, ctx);
483
484
  }
484
485
  }
485
486
  switch (level) {
@@ -520,15 +521,23 @@ function _trackUploadFailure(msg, object, ctx) {
520
521
  }
521
522
  if (UPLOAD_OK_RE.test(msg)) {
522
523
  const key = object ?? extractObjectFromMsg(msg);
523
- if (key) ctx.alertedObjects?.delete(key);
524
+ if (key) {
525
+ ctx.alertedObjects?.delete(key);
526
+ ctx.itemNotFoundCounts?.delete(key);
527
+ }
524
528
  }
525
529
  }
526
- function _trackNonRetryableUpload(object, msg, ctx) {
530
+ function _trackItemNotFound(object, msg, ctx) {
527
531
  const key = object ?? extractObjectFromMsg(msg) ?? "(unknown)";
532
+ if (!ctx.itemNotFoundCounts) ctx.itemNotFoundCounts = /* @__PURE__ */ new Map();
528
533
  if (!ctx.alertedObjects) ctx.alertedObjects = /* @__PURE__ */ new Set();
529
- if (ctx.alertedObjects.has(key)) return;
530
- ctx.alertedObjects.add(key);
531
- ctx.onUploadStuck?.(key, 1);
534
+ const count = (ctx.itemNotFoundCounts.get(key) ?? 0) + 1;
535
+ ctx.itemNotFoundCounts.set(key, count);
536
+ const threshold = ctx.stuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD;
537
+ if (count >= threshold && !ctx.alertedObjects.has(key)) {
538
+ ctx.alertedObjects.add(key);
539
+ ctx.onUploadStuck?.(key, count);
540
+ }
532
541
  }
533
542
  function extractObjectFromMsg(msg) {
534
543
  const m = /(?:^|\s)([^\s:]+\/[^\s:]+):/.exec(msg);
@@ -689,5 +698,5 @@ async function dirSize(dir) {
689
698
  }
690
699
 
691
700
  export { DEFAULT_UPLOAD_STUCK_THRESHOLD, DEFAULT_VFS_WRITE_BACK, PortPool, RcloneProcessManager, _buildRcloneArgs, _fuseMountPresent, _routeRcloneLogLine, awaitQuiescent, createFsWatcher, ensureDirMode };
692
- //# sourceMappingURL=chunk-C5UK3JK7.js.map
693
- //# sourceMappingURL=chunk-C5UK3JK7.js.map
701
+ //# sourceMappingURL=chunk-5VJVSYXX.js.map
702
+ //# sourceMappingURL=chunk-5VJVSYXX.js.map
@@ -0,0 +1 @@
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":[],"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,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACvD,CAAA;AAAA,EACH;AACF;ACjCO,IAAM,QAAA,GAAN,MAAM,SAAA,CAAS;AAAA,EACH,GAAA;AAAA,EACA,GAAA;AAAA,EACA,KAAA,uBAAY,GAAA,EAAY;AAAA,EAEzC,YAAY,KAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,GAAA,GAAM,MAAM,CAAC,CAAA;AAClB,IAAA,IAAA,CAAK,GAAA,GAAM,MAAM,CAAC,CAAA;AAAA,EACpB;AAAA;AAAA,EA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K,KAAK,MAAA,CAAO,CAAA,CAAE,IAAI,CAAC,CAAA;AAC1C,MAAA,IAAI,CAAA,CAAE,aAAY,EAAG;AACnB,QAAA,KAAA,IAAS,MAAM,QAAQ,IAAI,CAAA;AAAA,MAC7B,CAAA,MAAA,IAAW,CAAA,CAAE,MAAA,EAAO,EAAG;AACrB,QAAA,IAAI;AACF,UAAA,MAAM,CAAA,GAAI,MAAM,IAAA,CAAK,IAAI,CAAA;AACzB,UAAA,KAAA,IAAS,CAAA,CAAE,IAAA;AAAA,QACb,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT","file":"chunk-5VJVSYXX.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) and `status`\n * (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 { readdir, readFile, stat, unlink, writeFile } 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 * 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.\n */\n async spawn(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 const stdoutHandler = (line: string) => {\n _routeRcloneLogLine(line, rcloneLog, routeCtx);\n };\n const stderrHandler = (line: string) => {\n stderrTail(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 throw new Error(`rclone failed to mount ${config.remote} at ${config.mountPoint}${tail}`);\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 /** 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` is the OneDrive/SharePoint Graph 404 on an upload target. It is\n * NOT necessarily permanent: a stale VFS dir-cache parent-id (a folder deleted\n * and recreated remotely) or OneDrive's new-folder indexing lag both surface as\n * itemNotFound yet clear once rclone re-lists the parent (a respawn rebuilds the\n * in-memory dir-cache from the remote). Escalating on the FIRST occurrence\n * misclassifies those transient 404s as \"remote gone\" and trips a premature\n * recycle/quarantine — confirmed on prod where the parent dir + driveId were\n * valid throughout. So treat it like any other upload failure: count consecutive\n * occurrences per object and surface only once it crosses the stuck threshold (a\n * genuinely-vanished target keeps failing and still escalates; quarantine-replay\n * is the safety net either way).\n */\nconst ITEM_NOT_FOUND_RE = /itemNotFound/i;\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 return args;\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,6 +1,6 @@
1
1
  import { initTelemetry } from './chunk-4R6DROGN.js';
2
2
  import { parseSkillFrontmatter, validateFlowVersions } from './chunk-GXC3TYMQ.js';
3
- import { FlowAdapter } from './chunk-Z6DAVEDZ.js';
3
+ import { FlowAdapter } from './chunk-2ZI2FFFN.js';
4
4
  import { loadFlow } from './chunk-X46FY45B.js';
5
5
  import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-DEYYRFQU.js';
6
6
  import { resolveSettings } from './chunk-MVXXAXDW.js';
@@ -389,5 +389,5 @@ function walkForSkill(dir, skillId) {
389
389
  }
390
390
 
391
391
  export { resumeFlow, runFlow };
392
- //# sourceMappingURL=chunk-BKJLWPRR.js.map
393
- //# sourceMappingURL=chunk-BKJLWPRR.js.map
392
+ //# sourceMappingURL=chunk-ACB3AO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AY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-BKJLWPRR.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
1
+ {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ,uBAAA;AAAA,IACA,kBAAA;AAAA,IACA,wBAAA;AAAA,IACA,kBAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,IAAA,CAAK,QAAQ,CAAA;AACnC,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,IAAY,eAAA,CAAgB,KAAK,UAAU,CAAA;AACjE,EAAA,MAAM,QAAA,GAAW,MAAM,eAAA,CAAgB,IAAA,CAAK,UAAA,EAAY;AAAA,IACtD,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,OAAO,IAAA,CAAK;AAAA,GACb,CAAA;AAED,EAAA,MAAM,UAAU,UAAA,CAAW;AAAA,IACzB,QAAQ,IAAA,CAAK,EAAA;AAAA,IACb,YAAY,IAAA,CAAK,UAAA;AAAA,IACjB,QAAA;AAAA,IACA,MAAA,EAAQ,SAAS,MAAA,IAAU,KAAA;AAAA,IAC3B,UAAU,QAAA,CAA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a,KAAa,OAAA,EAAgC;AACjE,EAAA,KAAA,MAAW,KAAA,IAAS,GAAG,WAAA,CAAY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-ACB3AOII.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
@@ -303,5 +303,5 @@ function resolveProjectDir(additionalEnvVars) {
303
303
  }
304
304
 
305
305
  export { PluginStore, WorkspacePlugin, buildClaudePluginFiles, resolveProjectDir };
306
- //# sourceMappingURL=chunk-YG3CG6QR.js.map
307
- //# sourceMappingURL=chunk-YG3CG6QR.js.map
306
+ //# sourceMappingURL=chunk-IODU6UDT.js.map
307
+ //# sourceMappingURL=chunk-IODU6UDT.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../workspace-plugin/src/adapters/claude-code.ts","../workspace-plugin/src/store.ts","../workspace-plugin/src/plugin.ts","../workspace-plugin/src/utils/project-dir.ts"],"names":["err"],"mappings":";;;;;;AAeA,IAAM,WAAA,GAAc;AAAA,EAClB,IAAA,EAAM,QAAA;AAAA,EACN,OAAA,EAAS,OAAA;AAAA,EACT,WAAA,EAAa,yEAAA;AAAA,EACb,MAAA,EAAQ,EAAE,IAAA,EAAM,WAAA,EAAa,KAAK,8BAAA,EAA+B;AAAA,EACjE,UAAA,EAAY,yCAAA;AAAA,EACZ,QAAA,EAAU,CAAC,QAAA,EAAU,YAAA,EAAc,aAAa,WAAW,CAAA;AAAA,EAC3D,KAAA,EAAO,oBAAA;AAAA,EACP,UAAA,EAAY,aAAA;AAAA,EACZ,UAAA,EAAY;AAAA,IACV,gBAAA,EAAkB;AAAA,MAChB,IAAA,EAAM,QAAA;AAAA,MACN,KAAA,EAAO,kBAAA;AAAA,MACP,WAAA,EAAa;AAAA;AACf;AAEJ,CAAA;AAOA,IAAM,UAAA,GAAa;AAAA,EACjB,KAAA,EAAO;AAAA,IACL,YAAA,EAAc,CAAC,EAAE,KAAA,EAAO,CAAC,EAAE,IA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BAAA,EAAkB,GAAI,MAAM,OAAO,oCAAmB,CAAA;AAC9D,IAAA,MAAM,kBAAkB,IAAI,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAM,eAAA,GAAsC;AAC1C,IAAA,MAAM,EAAE,eAAA,EAAgB,GAAI,MAAM,OAAO,oCAAmB,CAAA;AAC5D,IAAA,OAAO,gBAAgB,IAAI,CAAA;AAAA,EAC7B;AAAA,EAEA,MAAM,uBAAA,GAA2C;AAC/C,IAAA,MAAM,EAAE,uBAAA,EAAwB,GAAI,MAAM,OAAO,oCAAmB,CAAA;AACpE,IAAA,OAAO,uBAAA,CAAwB,KAAK,UAAU,CAAA;AAAA,EAChD;AAAA,EAEA,MAAM,kBAAA,CAAmB,KAAA,EAAe,IAAA,EAAiC;AACvE,IAAA,MAAM,EAAE,kBAAA,EAAmB,GAAI,MAAM,OAAO,oCAAmB,CAAA;AAC/D,IAAA,OAAO,kBAAA,CAAmB,IAAA,EAAM,KAAA,EAAO,IAAI,CAAA;AAAA,EAC7C;AACF;;;AC1OO,SAAS,kBAAkB,iBAAA,EAAsC;AACtE,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,kBAAA,EAAoB,OAAO,QAAQ,GAAA,CAAI,kBAAA;AACvD,EAAA,KAAA,MAAW,GAAA,IAAO,iBAAA,IAAqB,EAAC,EAAG;AACzC,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAC3B,IAAA,IAAI,KAAK,OAAO,GAAA;AAAA,EAClB;AACA,EAAA,OAAO,QAAQ,GAAA,EAAI;AACrB","file":"chunk-YG3CG6QR.js","sourcesContent":["// ── Claude Code plugin-directory generator (STATELESS) ──────────────────────\n// Generates the contents of a Claude Code plugin directory\n// (`.claude/plugins/skaile/`) as an in-memory file map. No plugin instance or\n// boot() is required — safe to call from install commands.\n//\n// The previous standalone `@skaile/workspace-plugin-claude` package shipped\n// these as static files plus loose `.mjs` hook scripts; they are now\n// CLI-owned templates. Hooks invoke the `skaile` binary directly\n// (`skaile plugin hook <event>`) and MCP runs via `skaile mcp-server` — no\n// generated script files, no shebang, no runtime assumption.\n\n/**\n * The Claude Code plugin manifest. `name` is `skaile`; `hooks` and\n * `mcpServers` point at sibling files in the generated directory.\n */\nconst PLUGIN_JSON = {\n name: \"skaile\",\n version: \"0.1.0\",\n description: \"Skaile workspace — connectors, mounts, skills, flows, shared state\",\n author: { name: \"skaile-ai\", url: \"https://github.com/skaile-ai\" },\n repository: \"https://github.com/skaile-ai/workspaces\",\n keywords: [\"skaile\", \"connectors\", \"workspace\", \"ai-assets\"],\n hooks: \"./hooks/hooks.json\",\n mcpServers: \"./.mcp.json\",\n userConfig: {\n skaile_yaml_path: {\n type: \"string\",\n title: \"skaile.yaml path\",\n description: \"Override path to skaile.yaml (default: auto-detect from project root)\",\n },\n },\n};\n\n/**\n * Hook wiring. Each lifecycle event invokes the `skaile` binary directly —\n * no loose `.mjs` scripts. `skaile plugin hook <event>` resolves the project\n * directory itself (`CLAUDE_PROJECT_DIR` / cwd) and always exits 0.\n */\nconst HOOKS_JSON = {\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-start\" }] }],\n SessionEnd: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-end\" }] }],\n UserPromptSubmit: [\n { hooks: [{ type: \"command\", command: \"skaile plugin hook user-prompt-submit\" }] },\n ],\n },\n};\n\n/**\n * MCP server wiring. Spawns `skaile mcp-server` — a stdio MCP subprocess that\n * runs on plain Node (no Claude Agent SDK).\n */\nconst MCP_JSON = {\n mcpServers: {\n \"skaile-workspace\": {\n command: \"skaile\",\n args: [\"mcp-server\"],\n env: {},\n },\n },\n};\n\n/**\n * Build the Claude Code plugin directory as an in-memory file map.\n *\n * Returns `{ relativePath: contents }` for every file the installer must\n * write under `<projectDir>/.claude/plugins/skaile/`. The installer is also\n * responsible for populating `skills/` from the project's `.skaile/skills/`.\n *\n * Stateless — no plugin instance, no `boot()`. The generated artifacts carry\n * no project-specific paths: hooks and the MCP server resolve the project\n * directory themselves at runtime.\n *\n * @returns A map of plugin-relative file paths to their string contents.\n *\n * @docLink packages/workspace-plugin/concepts#adapters\n */\nexport function buildClaudePluginFiles(): Record<string, string> {\n return {\n \".claude-plugin/plugin.json\": `${JSON.stringify(PLUGIN_JSON, null, 2)}\\n`,\n \"hooks/hooks.json\": `${JSON.stringify(HOOKS_JSON, null, 2)}\\n`,\n \".mcp.json\": `${JSON.stringify(MCP_JSON, null, 2)}\\n`,\n \"skills/.gitkeep\": \"\",\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\ninterface Subscriber {\n regex: RegExp;\n handler: (key: string, value: unknown) => void;\n}\n\n/**\n * Disk-backed reactive key-value store for plugin state.\n *\n * Keeps an in-memory map that can be flushed to / loaded from a JSON file.\n * Supports glob-style subscriptions (`connector:*`, `*`).\n *\n * State is persisted to `<projectDir>/.skaile/plugin-state.json`.\n * The instance is available on {@link WorkspacePlugin} as the public `store`\n * field after `boot()` resolves.\n *\n * @docLink packages/workspace-plugin/concepts#plugin-store\n */\nexport class PluginStore {\n private readonly statePath: string;\n private data: Map<string, unknown> = new Map();\n private subscribers: Subscriber[] = [];\n\n constructor(statePath: string) {\n this.statePath = statePath;\n }\n\n /** Synchronous read from in-memory map. */\n get<T>(key: string): T | undefined {\n return this.data.get(key) as T | undefined;\n }\n\n /** Write to in-memory map and notify matching subscribers. */\n set<T>(key: string, value: T): void {\n this.data.set(key, value);\n this.notify(key, value);\n }\n\n /** Remove key and notify matching subscribers. */\n delete(key: string): void {\n this.data.delete(key);\n this.notify(key, undefined);\n }\n\n /**\n * Subscribe to changes matching a glob-style pattern.\n * `*` matches any sequence of characters.\n * Returns an unsubscribe function.\n */\n subscribe(pattern: string, handler: (key: string, value: unknown) => void): () => void {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regexStr = `^${escaped.replace(/\\*/g, \".*\")}$`;\n const sub: Subscriber = { regex: new RegExp(regexStr), handler };\n this.subscribers.push(sub);\n\n return () => {\n const idx = this.subscribers.indexOf(sub);\n if (idx !== -1) this.subscribers.splice(idx, 1);\n };\n }\n\n /** Rehydrate from disk JSON. Missing file = empty store (no throw). */\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n this.data = new Map(Object.entries(parsed));\n }\n } catch (e: unknown) {\n // Missing file or invalid JSON — start with empty store\n }\n }\n\n /** Write entire store to disk as JSON. Creates parent dirs if needed. */\n async flush(): Promise<void> {\n const obj = Object.fromEntries(this.data);\n const json = JSON.stringify(obj, null, 2);\n await mkdir(dirname(this.statePath), { recursive: true });\n await writeFile(this.statePath, json, \"utf-8\");\n }\n\n private notify(key: string, value: unknown): void {\n for (const sub of this.subscribers) {\n if (sub.regex.test(key)) {\n sub.handler(key, value);\n }\n }\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { PluginStore } from \"./store.js\";\n\n/**\n * Construction options for {@link WorkspacePlugin}.\n *\n * At minimum `projectDir` must be supplied. All other fields are optional\n * and are pre-resolved by the caller when available (e.g. the runner already\n * knows `driver`/`provider`/`model` from its own settings resolution).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport interface WorkspacePluginOpts {\n projectDir: string;\n /**\n * Active connector manager. The unified `ConnectorManager` owns both\n * filesystem-face (mountable) and tool-face connectors.\n */\n connectorManager?: ConnectorManager;\n bootOwned?: boolean;\n onLog?: (msg: string) => void;\n /** Pre-resolved driver type (avoids needing boot() to read settings). */\n driver?: string;\n /** Pre-resolved provider. */\n provider?: string;\n /** Pre-resolved model. */\n model?: string;\n}\n\n/**\n * Shared runtime core for the skaile workspace plugin.\n *\n * Manages the full lifecycle (`boot` → tools available → `shutdown`) and\n * surfaces workspace capabilities — mounts, connectors, flows, skills,\n * sessions, and config validation — through two adapter backends:\n *\n * - **MCP, in-process** (runner): call {@link buildWorkspaceMcpServer} for the\n * Claude Agent SDK server the runner embeds into its `query()` call.\n * - **MCP, stdio** (`skaile mcp-server`): call {@link runMcpServerStdio} for a\n * raw `@modelcontextprotocol/sdk` server — no Claude Agent SDK.\n * - **OMP**: call {@link buildOmpToolSet} for the 13-tool native subset and\n * {@link buildOmpExtensionSource} for the generated extension file.\n *\n * Two boot modes are supported via {@link WorkspacePluginOpts.bootOwned}:\n * - `bootOwned: false` (default) — managers injected externally by the runner.\n * - `bootOwned: true` — plugin owns the full manager lifecycle (standalone MCP\n * subprocess or OMP extension).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport class WorkspacePlugin {\n readonly projectDir: string;\n connectorManager: ConnectorManager | null;\n readonly store: PluginStore;\n\n private readonly bootOwned: boolean;\n private readonly onLog: (msg: string) => void;\n private readonly log: Logger = createLogger({\n kind: \"mcp\",\n subkind: \"skaile-workspace\",\n });\n driver?: string;\n provider?: string;\n model?: string;\n\n constructor(opts: WorkspacePluginOpts) {\n this.projectDir = opts.projectDir;\n this.connectorManager = opts.connectorManager ?? null;\n this.store = new PluginStore(join(opts.projectDir, \".skaile\", \"plugin-state.json\"));\n this.bootOwned = opts.bootOwned ?? false;\n if (opts.driver) this.driver = opts.driver;\n if (opts.provider) this.provider = opts.provider;\n if (opts.model) this.model = opts.model;\n this.onLog = opts.onLog ?? (() => {});\n this.log.debug(\"plugin constructed\", {\n driver: opts.driver,\n hasConnectors: !!opts.connectorManager,\n provider: opts.provider,\n model: opts.model,\n bootOwned: this.bootOwned,\n });\n }\n\n async boot(): Promise<void> {\n if (!this.bootOwned) {\n // Managers were injected externally — resolve settings only (non-fatal)\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n await this.store.load();\n return;\n }\n\n // bootOwned: we own the managers lifecycle\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n\n try {\n const {\n ConnectorManager,\n loadConnectorDeclarations,\n registerBuiltinConnectors,\n createCliSecretProviderChain,\n } = await import(\"@skaile/workspaces/connectors\");\n\n registerBuiltinConnectors();\n\n const secrets = createCliSecretProviderChain();\n\n const connectorDecls = await loadConnectorDeclarations(this.projectDir);\n const cm = new ConnectorManager(this.projectDir, { secrets });\n await cm.connectAll(connectorDecls);\n this.connectorManager = cm;\n\n this.log.info(\"workspace plugin booted\", {\n connectors: connectorDecls.length,\n });\n this.onLog(`WorkspacePlugin booted: ${connectorDecls.length} connectors`);\n } catch (err) {\n this.log.warn(\"workspace plugin boot warning\", {\n error: err instanceof Error ? err.message : String(err),\n });\n this.onLog(`WorkspacePlugin boot warning: ${err}`);\n }\n\n await this.store.load();\n }\n\n async reload(): Promise<void> {\n if (!this.bootOwned) return;\n await this.shutdown();\n await this.boot();\n }\n\n async shutdown(): Promise<void> {\n this.log.info(\"workspace plugin shutdown\");\n await this.store.flush();\n if (!this.bootOwned) return;\n try {\n await (this.connectorManager as any)?.disconnectAll?.();\n } catch {\n /* best-effort */\n }\n this.connectorManager = null;\n }\n\n buildSystemPromptSection(driver?: string): string {\n const d = driver ?? this.driver ?? \"unknown\";\n // The unified ConnectorManager owns both mountable (filesystem-face) and\n // tool-face connectors. Filesystem-face connectors expose a `mountPath`.\n const all = (this.connectorManager as any)?.listConnectors?.() ?? [];\n const mounts = (all as any[]).filter((c) => typeof c.mountPath === \"string\");\n const connectors = (all as any[]).filter((c) => typeof c.mountPath !== \"string\");\n const lines = [\"## Workspace (skaile)\", \"\", `Driver: ${d}`, `Project: ${this.projectDir}`];\n if (mounts.length > 0) {\n lines.push(\"\", \"Mounts:\");\n for (const v of mounts) {\n lines.push(` · ${v.id} (${v.driver}) → ${v.mountPath ?? \"(unmounted)\"}`);\n }\n }\n if (connectors.length > 0) {\n lines.push(\"\", \"Connectors:\");\n for (const c of connectors) {\n lines.push(` · ${c.id} (${c.driver})`);\n }\n }\n lines.push(\"\", \"Use workspace_info for full details. Use workspace_validate to check health.\");\n\n for (const name of [\"SOUL.md\", \"RULES.md\"]) {\n const skaileOverride = join(this.projectDir, \".skaile\", name);\n const rootFile = join(this.projectDir, name);\n for (const candidate of [skaileOverride, rootFile]) {\n try {\n const content = readFileSync(candidate, \"utf-8\").trim();\n if (content) {\n lines.push(\"\", `## ${name.replace(\".md\", \"\")}`, \"\", content);\n break;\n }\n } catch {\n // file not found, try next\n }\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Build the in-process Claude Agent SDK MCP server (runner embedding).\n * Returns `null` when `@anthropic-ai/claude-agent-sdk` is unavailable.\n */\n async buildWorkspaceMcpServer(): Promise<unknown | null> {\n this.log.info(\"building workspace MCP server\");\n try {\n const { buildWorkspaceMcpServer } = await import(\"./adapters/mcp.js\");\n const server = await buildWorkspaceMcpServer(this);\n if (server) this.log.info(\"workspace MCP server ready\");\n else this.log.debug(\"workspace MCP server skipped (no tools)\");\n return server;\n } catch (err) {\n this.log.error(\"workspace MCP server build failed\", err);\n throw err;\n }\n }\n\n /**\n * Build the raw `@modelcontextprotocol/sdk` stdio MCP server — no Claude\n * Agent SDK. Used by the `skaile mcp-server` subprocess. The returned\n * server is not yet connected to a transport.\n */\n async buildWorkspaceMcpStdioServer(): Promise<unknown> {\n this.log.info(\"building workspace stdio MCP server\");\n const { buildWorkspaceMcpStdioServer } = await import(\"./adapters/mcp.js\");\n return buildWorkspaceMcpStdioServer(this);\n }\n\n /**\n * Build and run the stdio MCP server: builds the raw\n * `@modelcontextprotocol/sdk` server and connects a `StdioServerTransport`.\n * Used by the `skaile mcp-server` subprocess.\n */\n async runMcpServerStdio(): Promise<void> {\n this.log.info(\"starting workspace stdio MCP server\");\n const { runMcpServerStdio } = await import(\"./adapters/mcp.js\");\n await runMcpServerStdio(this);\n }\n\n async buildOmpToolSet(): Promise<unknown[]> {\n const { buildOmpToolSet } = await import(\"./adapters/omp.js\");\n return buildOmpToolSet(this);\n }\n\n async buildOmpExtensionSource(): Promise<string> {\n const { buildOmpExtensionSource } = await import(\"./adapters/omp.js\");\n return buildOmpExtensionSource(this.projectDir);\n }\n\n async handleSlashCommand(group: string, args: string[]): Promise<string> {\n const { handleSlashCommand } = await import(\"./adapters/omp.js\");\n return handleSlashCommand(this, group, args);\n }\n}\n","// utils/project-dir.ts\n// Centralised project-directory resolution used by all plugin entry points.\n\n/**\n * Resolve the skaile project directory from environment variables.\n *\n * Resolution order:\n * 1. `SKAILE_PROJECT_DIR` (always checked first)\n * 2. Any additional env var keys supplied by the caller (in order)\n * 3. `process.cwd()` as final fallback\n *\n * @param additionalEnvVars - Optional list of extra environment variable names\n * to check before falling back to `process.cwd()`.\n * @returns Absolute path to the resolved project directory.\n *\n * @example\n * // Claude Code — also checks CLAUDE_PROJECT_DIR\n * const projectDir = resolveProjectDir([\"CLAUDE_PROJECT_DIR\"]);\n *\n * // OMP / standalone — SKAILE_PROJECT_DIR or cwd only\n * const projectDir = resolveProjectDir();\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport function resolveProjectDir(additionalEnvVars?: string[]): string {\n if (process.env.SKAILE_PROJECT_DIR) return process.env.SKAILE_PROJECT_DIR;\n for (const key of additionalEnvVars ?? []) {\n const val = process.env[key];\n if (val) return val;\n }\n return process.cwd();\n}\n"]}
1
+ {"version":3,"sources":["../workspace-plugin/src/adapters/claude-code.ts","../workspace-plugin/src/store.ts","../workspace-plugin/src/plugin.ts","../workspace-plugin/src/utils/project-dir.ts"],"names":["err"],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,EAAO,IAAI,CAAA;AAAA,EAC7C;AACF;;;AC1OO,SAAS,kBAAkB,iBAAA,EAAsC;AACtE,EAAA,IAAI,OAAA,CAAQ,GAAA,CAAI,kBAAA,EAAoB,OAAO,QAAQ,GAAA,CAAI,kBAAA;AACvD,EAAA,KAAA,MAAW,GAAA,IAAO,iBAAA,IAAqB,EAAC,EAAG;AACzC,IAAA,MAAM,GAAA,GAAM,OAAA,CAAQ,GAAA,CAAI,GAAG,CAAA;AAC3B,IAAA,IAAI,KAAK,OAAO,GAAA;AAAA,EAClB;AACA,EAAA,OAAO,QAAQ,GAAA,EAAI;AACrB","file":"chunk-IODU6UDT.js","sourcesContent":["// ── Claude Code plugin-directory generator (STATELESS) ──────────────────────\n// Generates the contents of a Claude Code plugin directory\n// (`.claude/plugins/skaile/`) as an in-memory file map. No plugin instance or\n// boot() is required — safe to call from install commands.\n//\n// The previous standalone `@skaile/workspace-plugin-claude` package shipped\n// these as static files plus loose `.mjs` hook scripts; they are now\n// CLI-owned templates. Hooks invoke the `skaile` binary directly\n// (`skaile plugin hook <event>`) and MCP runs via `skaile mcp-server` — no\n// generated script files, no shebang, no runtime assumption.\n\n/**\n * The Claude Code plugin manifest. `name` is `skaile`; `hooks` and\n * `mcpServers` point at sibling files in the generated directory.\n */\nconst PLUGIN_JSON = {\n name: \"skaile\",\n version: \"0.1.0\",\n description: \"Skaile workspace — connectors, mounts, skills, flows, shared state\",\n author: { name: \"skaile-ai\", url: \"https://github.com/skaile-ai\" },\n repository: \"https://github.com/skaile-ai/workspaces\",\n keywords: [\"skaile\", \"connectors\", \"workspace\", \"ai-assets\"],\n hooks: \"./hooks/hooks.json\",\n mcpServers: \"./.mcp.json\",\n userConfig: {\n skaile_yaml_path: {\n type: \"string\",\n title: \"skaile.yaml path\",\n description: \"Override path to skaile.yaml (default: auto-detect from project root)\",\n },\n },\n};\n\n/**\n * Hook wiring. Each lifecycle event invokes the `skaile` binary directly —\n * no loose `.mjs` scripts. `skaile plugin hook <event>` resolves the project\n * directory itself (`CLAUDE_PROJECT_DIR` / cwd) and always exits 0.\n */\nconst HOOKS_JSON = {\n hooks: {\n SessionStart: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-start\" }] }],\n SessionEnd: [{ hooks: [{ type: \"command\", command: \"skaile plugin hook session-end\" }] }],\n UserPromptSubmit: [\n { hooks: [{ type: \"command\", command: \"skaile plugin hook user-prompt-submit\" }] },\n ],\n },\n};\n\n/**\n * MCP server wiring. Spawns `skaile mcp-server` — a stdio MCP subprocess that\n * runs on plain Node (no Claude Agent SDK).\n */\nconst MCP_JSON = {\n mcpServers: {\n \"skaile-workspace\": {\n command: \"skaile\",\n args: [\"mcp-server\"],\n env: {},\n },\n },\n};\n\n/**\n * Build the Claude Code plugin directory as an in-memory file map.\n *\n * Returns `{ relativePath: contents }` for every file the installer must\n * write under `<projectDir>/.claude/plugins/skaile/`. The installer is also\n * responsible for populating `skills/` from the project's `.skaile/skills/`.\n *\n * Stateless — no plugin instance, no `boot()`. The generated artifacts carry\n * no project-specific paths: hooks and the MCP server resolve the project\n * directory themselves at runtime.\n *\n * @returns A map of plugin-relative file paths to their string contents.\n *\n * @docLink packages/workspace-plugin/concepts#adapters\n */\nexport function buildClaudePluginFiles(): Record<string, string> {\n return {\n \".claude-plugin/plugin.json\": `${JSON.stringify(PLUGIN_JSON, null, 2)}\\n`,\n \"hooks/hooks.json\": `${JSON.stringify(HOOKS_JSON, null, 2)}\\n`,\n \".mcp.json\": `${JSON.stringify(MCP_JSON, null, 2)}\\n`,\n \"skills/.gitkeep\": \"\",\n };\n}\n","import { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\ninterface Subscriber {\n regex: RegExp;\n handler: (key: string, value: unknown) => void;\n}\n\n/**\n * Disk-backed reactive key-value store for plugin state.\n *\n * Keeps an in-memory map that can be flushed to / loaded from a JSON file.\n * Supports glob-style subscriptions (`connector:*`, `*`).\n *\n * State is persisted to `<projectDir>/.skaile/plugin-state.json`.\n * The instance is available on {@link WorkspacePlugin} as the public `store`\n * field after `boot()` resolves.\n *\n * @docLink packages/workspace-plugin/concepts#plugin-store\n */\nexport class PluginStore {\n private readonly statePath: string;\n private data: Map<string, unknown> = new Map();\n private subscribers: Subscriber[] = [];\n\n constructor(statePath: string) {\n this.statePath = statePath;\n }\n\n /** Synchronous read from in-memory map. */\n get<T>(key: string): T | undefined {\n return this.data.get(key) as T | undefined;\n }\n\n /** Write to in-memory map and notify matching subscribers. */\n set<T>(key: string, value: T): void {\n this.data.set(key, value);\n this.notify(key, value);\n }\n\n /** Remove key and notify matching subscribers. */\n delete(key: string): void {\n this.data.delete(key);\n this.notify(key, undefined);\n }\n\n /**\n * Subscribe to changes matching a glob-style pattern.\n * `*` matches any sequence of characters.\n * Returns an unsubscribe function.\n */\n subscribe(pattern: string, handler: (key: string, value: unknown) => void): () => void {\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const regexStr = `^${escaped.replace(/\\*/g, \".*\")}$`;\n const sub: Subscriber = { regex: new RegExp(regexStr), handler };\n this.subscribers.push(sub);\n\n return () => {\n const idx = this.subscribers.indexOf(sub);\n if (idx !== -1) this.subscribers.splice(idx, 1);\n };\n }\n\n /** Rehydrate from disk JSON. Missing file = empty store (no throw). */\n async load(): Promise<void> {\n try {\n const raw = await readFile(this.statePath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n this.data = new Map(Object.entries(parsed));\n }\n } catch (e: unknown) {\n // Missing file or invalid JSON — start with empty store\n }\n }\n\n /** Write entire store to disk as JSON. Creates parent dirs if needed. */\n async flush(): Promise<void> {\n const obj = Object.fromEntries(this.data);\n const json = JSON.stringify(obj, null, 2);\n await mkdir(dirname(this.statePath), { recursive: true });\n await writeFile(this.statePath, json, \"utf-8\");\n }\n\n private notify(key: string, value: unknown): void {\n for (const sub of this.subscribers) {\n if (sub.regex.test(key)) {\n sub.handler(key, value);\n }\n }\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { PluginStore } from \"./store.js\";\n\n/**\n * Construction options for {@link WorkspacePlugin}.\n *\n * At minimum `projectDir` must be supplied. All other fields are optional\n * and are pre-resolved by the caller when available (e.g. the runner already\n * knows `driver`/`provider`/`model` from its own settings resolution).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport interface WorkspacePluginOpts {\n projectDir: string;\n /**\n * Active connector manager. The unified `ConnectorManager` owns both\n * filesystem-face (mountable) and tool-face connectors.\n */\n connectorManager?: ConnectorManager;\n bootOwned?: boolean;\n onLog?: (msg: string) => void;\n /** Pre-resolved driver type (avoids needing boot() to read settings). */\n driver?: string;\n /** Pre-resolved provider. */\n provider?: string;\n /** Pre-resolved model. */\n model?: string;\n}\n\n/**\n * Shared runtime core for the skaile workspace plugin.\n *\n * Manages the full lifecycle (`boot` → tools available → `shutdown`) and\n * surfaces workspace capabilities — mounts, connectors, flows, skills,\n * sessions, and config validation — through two adapter backends:\n *\n * - **MCP, in-process** (runner): call {@link buildWorkspaceMcpServer} for the\n * Claude Agent SDK server the runner embeds into its `query()` call.\n * - **MCP, stdio** (`skaile mcp-server`): call {@link runMcpServerStdio} for a\n * raw `@modelcontextprotocol/sdk` server — no Claude Agent SDK.\n * - **OMP**: call {@link buildOmpToolSet} for the 13-tool native subset and\n * {@link buildOmpExtensionSource} for the generated extension file.\n *\n * Two boot modes are supported via {@link WorkspacePluginOpts.bootOwned}:\n * - `bootOwned: false` (default) — managers injected externally by the runner.\n * - `bootOwned: true` — plugin owns the full manager lifecycle (standalone MCP\n * subprocess or OMP extension).\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport class WorkspacePlugin {\n readonly projectDir: string;\n connectorManager: ConnectorManager | null;\n readonly store: PluginStore;\n\n private readonly bootOwned: boolean;\n private readonly onLog: (msg: string) => void;\n private readonly log: Logger = createLogger({\n kind: \"mcp\",\n subkind: \"skaile-workspace\",\n });\n driver?: string;\n provider?: string;\n model?: string;\n\n constructor(opts: WorkspacePluginOpts) {\n this.projectDir = opts.projectDir;\n this.connectorManager = opts.connectorManager ?? null;\n this.store = new PluginStore(join(opts.projectDir, \".skaile\", \"plugin-state.json\"));\n this.bootOwned = opts.bootOwned ?? false;\n if (opts.driver) this.driver = opts.driver;\n if (opts.provider) this.provider = opts.provider;\n if (opts.model) this.model = opts.model;\n this.onLog = opts.onLog ?? (() => {});\n this.log.debug(\"plugin constructed\", {\n driver: opts.driver,\n hasConnectors: !!opts.connectorManager,\n provider: opts.provider,\n model: opts.model,\n bootOwned: this.bootOwned,\n });\n }\n\n async boot(): Promise<void> {\n if (!this.bootOwned) {\n // Managers were injected externally — resolve settings only (non-fatal)\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n await this.store.load();\n return;\n }\n\n // bootOwned: we own the managers lifecycle\n try {\n const { resolveSettings } = await import(\"@skaile/workspaces/core\");\n const settings = await resolveSettings(this.projectDir);\n this.driver = settings.driver ?? \"omp\";\n this.provider = settings.provider;\n this.model = settings.model;\n } catch {\n /* non-fatal */\n }\n\n try {\n const {\n ConnectorManager,\n loadConnectorDeclarations,\n registerBuiltinConnectors,\n createCliSecretProviderChain,\n } = await import(\"@skaile/workspaces/connectors\");\n\n registerBuiltinConnectors();\n\n const secrets = createCliSecretProviderChain();\n\n const connectorDecls = await loadConnectorDeclarations(this.projectDir);\n const cm = new ConnectorManager(this.projectDir, { secrets });\n await cm.connectAll(connectorDecls);\n this.connectorManager = cm;\n\n this.log.info(\"workspace plugin booted\", {\n connectors: connectorDecls.length,\n });\n this.onLog(`WorkspacePlugin booted: ${connectorDecls.length} connectors`);\n } catch (err) {\n this.log.warn(\"workspace plugin boot warning\", {\n error: err instanceof Error ? err.message : String(err),\n });\n this.onLog(`WorkspacePlugin boot warning: ${err}`);\n }\n\n await this.store.load();\n }\n\n async reload(): Promise<void> {\n if (!this.bootOwned) return;\n await this.shutdown();\n await this.boot();\n }\n\n async shutdown(): Promise<void> {\n this.log.info(\"workspace plugin shutdown\");\n await this.store.flush();\n if (!this.bootOwned) return;\n try {\n await (this.connectorManager as any)?.disconnectAll?.();\n } catch {\n /* best-effort */\n }\n this.connectorManager = null;\n }\n\n buildSystemPromptSection(driver?: string): string {\n const d = driver ?? this.driver ?? \"unknown\";\n // The unified ConnectorManager owns both mountable (filesystem-face) and\n // tool-face connectors. Filesystem-face connectors expose a `mountPath`.\n const all = (this.connectorManager as any)?.listConnectors?.() ?? [];\n const mounts = (all as any[]).filter((c) => typeof c.mountPath === \"string\");\n const connectors = (all as any[]).filter((c) => typeof c.mountPath !== \"string\");\n const lines = [\"## Workspace (skaile)\", \"\", `Driver: ${d}`, `Project: ${this.projectDir}`];\n if (mounts.length > 0) {\n lines.push(\"\", \"Mounts:\");\n for (const v of mounts) {\n lines.push(` · ${v.id} (${v.driver}) → ${v.mountPath ?? \"(unmounted)\"}`);\n }\n }\n if (connectors.length > 0) {\n lines.push(\"\", \"Connectors:\");\n for (const c of connectors) {\n lines.push(` · ${c.id} (${c.driver})`);\n }\n }\n lines.push(\"\", \"Use workspace_info for full details. Use workspace_validate to check health.\");\n\n for (const name of [\"SOUL.md\", \"RULES.md\"]) {\n const skaileOverride = join(this.projectDir, \".skaile\", name);\n const rootFile = join(this.projectDir, name);\n for (const candidate of [skaileOverride, rootFile]) {\n try {\n const content = readFileSync(candidate, \"utf-8\").trim();\n if (content) {\n lines.push(\"\", `## ${name.replace(\".md\", \"\")}`, \"\", content);\n break;\n }\n } catch {\n // file not found, try next\n }\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Build the in-process Claude Agent SDK MCP server (runner embedding).\n * Returns `null` when `@anthropic-ai/claude-agent-sdk` is unavailable.\n */\n async buildWorkspaceMcpServer(): Promise<unknown | null> {\n this.log.info(\"building workspace MCP server\");\n try {\n const { buildWorkspaceMcpServer } = await import(\"./adapters/mcp.js\");\n const server = await buildWorkspaceMcpServer(this);\n if (server) this.log.info(\"workspace MCP server ready\");\n else this.log.debug(\"workspace MCP server skipped (no tools)\");\n return server;\n } catch (err) {\n this.log.error(\"workspace MCP server build failed\", err);\n throw err;\n }\n }\n\n /**\n * Build the raw `@modelcontextprotocol/sdk` stdio MCP server — no Claude\n * Agent SDK. Used by the `skaile mcp-server` subprocess. The returned\n * server is not yet connected to a transport.\n */\n async buildWorkspaceMcpStdioServer(): Promise<unknown> {\n this.log.info(\"building workspace stdio MCP server\");\n const { buildWorkspaceMcpStdioServer } = await import(\"./adapters/mcp.js\");\n return buildWorkspaceMcpStdioServer(this);\n }\n\n /**\n * Build and run the stdio MCP server: builds the raw\n * `@modelcontextprotocol/sdk` server and connects a `StdioServerTransport`.\n * Used by the `skaile mcp-server` subprocess.\n */\n async runMcpServerStdio(): Promise<void> {\n this.log.info(\"starting workspace stdio MCP server\");\n const { runMcpServerStdio } = await import(\"./adapters/mcp.js\");\n await runMcpServerStdio(this);\n }\n\n async buildOmpToolSet(): Promise<unknown[]> {\n const { buildOmpToolSet } = await import(\"./adapters/omp.js\");\n return buildOmpToolSet(this);\n }\n\n async buildOmpExtensionSource(): Promise<string> {\n const { buildOmpExtensionSource } = await import(\"./adapters/omp.js\");\n return buildOmpExtensionSource(this.projectDir);\n }\n\n async handleSlashCommand(group: string, args: string[]): Promise<string> {\n const { handleSlashCommand } = await import(\"./adapters/omp.js\");\n return handleSlashCommand(this, group, args);\n }\n}\n","// utils/project-dir.ts\n// Centralised project-directory resolution used by all plugin entry points.\n\n/**\n * Resolve the skaile project directory from environment variables.\n *\n * Resolution order:\n * 1. `SKAILE_PROJECT_DIR` (always checked first)\n * 2. Any additional env var keys supplied by the caller (in order)\n * 3. `process.cwd()` as final fallback\n *\n * @param additionalEnvVars - Optional list of extra environment variable names\n * to check before falling back to `process.cwd()`.\n * @returns Absolute path to the resolved project directory.\n *\n * @example\n * // Claude Code — also checks CLAUDE_PROJECT_DIR\n * const projectDir = resolveProjectDir([\"CLAUDE_PROJECT_DIR\"]);\n *\n * // OMP / standalone — SKAILE_PROJECT_DIR or cwd only\n * const projectDir = resolveProjectDir();\n *\n * @docLink packages/workspace-plugin/concepts#workspaceplugin-lifecycle\n */\nexport function resolveProjectDir(additionalEnvVars?: string[]): string {\n if (process.env.SKAILE_PROJECT_DIR) return process.env.SKAILE_PROJECT_DIR;\n for (const key of additionalEnvVars ?? []) {\n const val = process.env[key];\n if (val) return val;\n }\n return process.cwd();\n}\n"]}