@skaile/workspaces 0.41.5 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +85 -0
- package/dist/{asset-feeds-FKD5AB2R.js → asset-feeds-UPJJGR3O.js} +8 -8
- package/dist/{asset-feeds-FKD5AB2R.js.map → asset-feeds-UPJJGR3O.js.map} +1 -1
- package/dist/asset-manager/index.js +6 -6
- package/dist/asset-manager/installer.js +5 -5
- package/dist/bridge/drivers/claude-sdk.js +112 -7
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +1 -1
- package/dist/bridge/drivers/continue.js +2 -2
- package/dist/bridge/drivers/echo.js +1 -1
- package/dist/bridge/drivers/gemini.js +3 -3
- package/dist/bridge/drivers/goose.js +2 -2
- package/dist/bridge/drivers/omp.js +1 -1
- package/dist/bridge/drivers/opencode.js +2 -2
- package/dist/bridge/drivers/qwen.js +3 -3
- package/dist/bridge/index.js +2 -2
- package/dist/bridge/src/drivers/claude-sdk.d.ts +6 -0
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/drivers/sanitize-assistant-text.d.ts +53 -0
- package/dist/bridge/src/drivers/sanitize-assistant-text.d.ts.map +1 -0
- package/dist/{chunk-J4RF5ABK.js → chunk-2BEDUMTA.js} +3 -3
- package/dist/{chunk-J4RF5ABK.js.map → chunk-2BEDUMTA.js.map} +1 -1
- package/dist/{chunk-IODU6UDT.js → chunk-2MVQ7UAT.js} +2 -2
- package/dist/{chunk-IODU6UDT.js.map → chunk-2MVQ7UAT.js.map} +1 -1
- package/dist/{chunk-5VJVSYXX.js → chunk-3HUUP3JC.js} +41 -3
- package/dist/chunk-3HUUP3JC.js.map +1 -0
- package/dist/{chunk-SBGHNXJD.js → chunk-3K2CYDBT.js} +17 -7
- package/dist/chunk-3K2CYDBT.js.map +1 -0
- package/dist/{chunk-ACB3AOII.js → chunk-4MO456BV.js} +5 -5
- package/dist/{chunk-ACB3AOII.js.map → chunk-4MO456BV.js.map} +1 -1
- package/dist/{chunk-5IXCNMMU.js → chunk-5C3QJSOD.js} +3 -3
- package/dist/{chunk-5IXCNMMU.js.map → chunk-5C3QJSOD.js.map} +1 -1
- package/dist/{chunk-B5PEERRZ.js → chunk-6IDBWPK2.js} +7 -4
- package/dist/chunk-6IDBWPK2.js.map +1 -0
- package/dist/{chunk-TNYWP6EQ.js → chunk-7I4IBYHE.js} +6 -6
- package/dist/{chunk-TNYWP6EQ.js.map → chunk-7I4IBYHE.js.map} +1 -1
- package/dist/{chunk-3KX5W3ZU.js → chunk-7WLJW457.js} +4 -4
- package/dist/{chunk-3KX5W3ZU.js.map → chunk-7WLJW457.js.map} +1 -1
- package/dist/{chunk-ZJ27BHIH.js → chunk-BXYMGZCI.js} +3 -3
- package/dist/{chunk-ZJ27BHIH.js.map → chunk-BXYMGZCI.js.map} +1 -1
- package/dist/{chunk-2JCUYKUN.js → chunk-G6FJZG4C.js} +2 -2
- package/dist/{chunk-2JCUYKUN.js.map → chunk-G6FJZG4C.js.map} +1 -1
- package/dist/{chunk-NQDJQ7WB.js → chunk-GJI6FZ56.js} +8 -4
- package/dist/chunk-GJI6FZ56.js.map +1 -0
- package/dist/{chunk-JAOXG3LL.js → chunk-HVCZLD5Z.js} +4 -4
- package/dist/{chunk-JAOXG3LL.js.map → chunk-HVCZLD5Z.js.map} +1 -1
- package/dist/{chunk-MO2VGW6U.js → chunk-K5TROTFK.js} +3 -3
- package/dist/{chunk-MO2VGW6U.js.map → chunk-K5TROTFK.js.map} +1 -1
- package/dist/{chunk-MVXXAXDW.js → chunk-KYQNWFJV.js} +3 -3
- package/dist/{chunk-MVXXAXDW.js.map → chunk-KYQNWFJV.js.map} +1 -1
- package/dist/{chunk-KM6DCR7A.js → chunk-OCAQH66V.js} +2 -2
- package/dist/{chunk-KM6DCR7A.js.map → chunk-OCAQH66V.js.map} +1 -1
- package/dist/{chunk-X4FCLBI7.js → chunk-R4H6EJW5.js} +7 -5
- package/dist/chunk-R4H6EJW5.js.map +1 -0
- package/dist/{chunk-U3TV7SRR.js → chunk-RSK6FDMV.js} +3 -3
- package/dist/{chunk-U3TV7SRR.js.map → chunk-RSK6FDMV.js.map} +1 -1
- package/dist/{chunk-TB342H55.js → chunk-SURALYSM.js} +4 -4
- package/dist/{chunk-TB342H55.js.map → chunk-SURALYSM.js.map} +1 -1
- package/dist/{chunk-2ZI2FFFN.js → chunk-U3RYXSI4.js} +188 -76
- package/dist/chunk-U3RYXSI4.js.map +1 -0
- package/dist/{chunk-JILPU5VI.js → chunk-VGAHSWDE.js} +98 -50
- package/dist/chunk-VGAHSWDE.js.map +1 -0
- package/dist/{chunk-4NZD7423.js → chunk-WJ3RP2FS.js} +3 -3
- package/dist/{chunk-4NZD7423.js.map → chunk-WJ3RP2FS.js.map} +1 -1
- package/dist/{chunk-4ZACMAT3.js → chunk-Z3GAAIJK.js} +4 -4
- package/dist/{chunk-4ZACMAT3.js.map → chunk-Z3GAAIJK.js.map} +1 -1
- package/dist/cli/index.js +34 -34
- package/dist/connectors/config.js +5 -5
- package/dist/connectors/index.js +7 -7
- package/dist/connectors/rclone.js +1 -1
- package/dist/connectors/src/connector-manager.d.ts +13 -0
- package/dist/connectors/src/connector-manager.d.ts.map +1 -1
- package/dist/connectors/src/connector-types.d.ts +26 -0
- package/dist/connectors/src/connector-types.d.ts.map +1 -1
- package/dist/connectors/src/fleet-health-gate.d.ts +53 -36
- package/dist/connectors/src/fleet-health-gate.d.ts.map +1 -1
- package/dist/connectors/src/fleet-utils.d.ts +11 -2
- package/dist/connectors/src/fleet-utils.d.ts.map +1 -1
- package/dist/connectors/src/index.d.ts +3 -3
- package/dist/connectors/src/index.d.ts.map +1 -1
- package/dist/connectors/src/materialized-connectors.d.ts.map +1 -1
- package/dist/connectors/src/mount-placeholder.d.ts +19 -0
- package/dist/connectors/src/mount-placeholder.d.ts.map +1 -1
- package/dist/connectors/src/rclone-process-manager.d.ts +36 -2
- package/dist/connectors/src/rclone-process-manager.d.ts.map +1 -1
- package/dist/core/index.js +4 -4
- package/dist/core/manifest.js +1 -1
- package/dist/core/runtime-assets.js +3 -3
- package/dist/core/src/index.d.ts +1 -1
- package/dist/core/src/index.d.ts.map +1 -1
- package/dist/core/src/manifest.d.ts +11 -0
- package/dist/core/src/manifest.d.ts.map +1 -1
- package/dist/core/src/workspace-config.d.ts +2 -0
- package/dist/core/src/workspace-config.d.ts.map +1 -1
- package/dist/core/workspace-config.js +2 -2
- package/dist/deploy/index.js +4 -4
- package/dist/discovery/index.js +2 -2
- package/dist/{ensure-sources-EWK7EXKN.js → ensure-sources-TZHDV3BF.js} +8 -8
- package/dist/{ensure-sources-EWK7EXKN.js.map → ensure-sources-TZHDV3BF.js.map} +1 -1
- package/dist/factory-assets/connectors/deploy.js +7 -7
- package/dist/factory-assets/connectors/devserver.js +7 -7
- package/dist/factory-assets/connectors/flow/adapter.js +7 -7
- package/dist/factory-assets/connectors/flow/engine.js +4 -4
- package/dist/factory-assets/connectors/flow/run-flow.js +8 -8
- package/dist/factory-assets/connectors/flow.js +7 -7
- package/dist/factory-assets/connectors/git.js +7 -7
- package/dist/factory-assets/connectors/gmail.js +7 -7
- package/dist/factory-assets/connectors/googledrive/driver.d.ts.map +1 -1
- package/dist/factory-assets/connectors/googledrive.js +7 -7
- package/dist/factory-assets/connectors/local.js +7 -7
- package/dist/factory-assets/connectors/mattermost.js +7 -7
- package/dist/factory-assets/connectors/memory.js +7 -7
- package/dist/factory-assets/connectors/minio.js +7 -7
- package/dist/factory-assets/connectors/postgres.js +7 -7
- package/dist/factory-assets/connectors/s3.js +7 -7
- package/dist/factory-assets/connectors/sharepoint/driver.d.ts.map +1 -1
- package/dist/factory-assets/connectors/sharepoint.js +7 -7
- package/dist/factory-assets/connectors/sqlite.js +7 -7
- package/dist/factory-assets/connectors/static-server.js +7 -7
- package/dist/factory-assets/connectors/tunnel.js +7 -7
- package/dist/factory-assets/connectors/webdav/driver.d.ts.map +1 -1
- package/dist/factory-assets/connectors/webdav.js +7 -7
- package/dist/factory-assets/connectors/xstate-store.js +7 -7
- package/dist/factory-assets/connectors/xstate.js +7 -7
- package/dist/{flows-3MBK2PDN.js → flows-KTBCZ5GQ.js} +3 -3
- package/dist/{flows-3MBK2PDN.js.map → flows-KTBCZ5GQ.js.map} +1 -1
- package/dist/library/index.js +6 -6
- package/dist/library/install.js +4 -4
- package/dist/{open-library-QSIPFN5N.js → open-library-EV7UCOFU.js} +9 -9
- package/dist/{open-library-QSIPFN5N.js.map → open-library-EV7UCOFU.js.map} +1 -1
- package/dist/{paths-KNLBYALO.js → paths-7H5CSBLQ.js} +7 -7
- package/dist/{paths-KNLBYALO.js.map → paths-7H5CSBLQ.js.map} +1 -1
- package/dist/{plugin-store-CL6CTREE.js → plugin-store-LGLN2QUX.js} +6 -6
- package/dist/{plugin-store-CL6CTREE.js.map → plugin-store-LGLN2QUX.js.map} +1 -1
- package/dist/runner/index.js +11 -11
- package/dist/runner/src/fleet-health-flag-dispatcher.d.ts +3 -2
- package/dist/runner/src/fleet-health-flag-dispatcher.d.ts.map +1 -1
- package/dist/runner/src/mcp-prompt.d.ts +8 -0
- package/dist/runner/src/mcp-prompt.d.ts.map +1 -0
- package/dist/runner/src/resource-handler.d.ts +1 -7
- package/dist/runner/src/resource-handler.d.ts.map +1 -1
- package/dist/runner/src/resources.d.ts +6 -0
- package/dist/runner/src/resources.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts +8 -2
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/runner/src/session-builder.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +6 -6
- package/dist/sdk/bridge.js +2 -2
- package/dist/sdk/core.js +4 -4
- package/dist/sdk/flow.js +4 -4
- package/dist/sdk/index.js +11 -11
- package/dist/sdk/runner.js +11 -11
- package/dist/sdk/session.js +1 -1
- package/dist/session/index.js +1 -1
- package/dist/session/src/dispatcher.d.ts +8 -0
- package/dist/session/src/dispatcher.d.ts.map +1 -1
- package/dist/{setup-345XOCH3.js → setup-EVNPECSY.js} +8 -8
- package/dist/{setup-345XOCH3.js.map → setup-EVNPECSY.js.map} +1 -1
- package/dist/{store-client-W3HKRE46.js → store-client-4XN7IB3R.js} +7 -7
- package/dist/{store-client-W3HKRE46.js.map → store-client-4XN7IB3R.js.map} +1 -1
- package/dist/tui/index.js +11 -11
- package/dist/types/src/events.d.ts +1 -1
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +1 -1
- package/dist/workspace-plugin/adapters/omp.js +3 -3
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2ZI2FFFN.js.map +0 -1
- package/dist/chunk-5VJVSYXX.js.map +0 -1
- package/dist/chunk-B5PEERRZ.js.map +0 -1
- package/dist/chunk-JILPU5VI.js.map +0 -1
- package/dist/chunk-NQDJQ7WB.js.map +0 -1
- package/dist/chunk-SBGHNXJD.js.map +0 -1
- package/dist/chunk-X4FCLBI7.js.map +0 -1
|
@@ -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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A,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT","file":"chunk-3HUUP3JC.js","sourcesContent":["/**\n * Shared filesystem helpers for connector infrastructure.\n *\n * @docLink packages/connectors/api-reference#fs-utils\n */\n\nimport { chmod, mkdir } from \"node:fs/promises\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * mkdir(recursive) + chmod 0o770 in one call. The post-mkdir `chmod` is the\n * load-bearing piece: `mkdir(mode:)` is ANDed with the process umask\n * (typically 022 → effective mode 0o750), which strips the group-write bit\n * that `fusermount3` requires on the rclone mountpoint and rclone needs on\n * its vfs cache directory. Explicit `chmod` is umask-immune.\n *\n * EPERM on `chmod` is swallowed: when a foreign uid pre-created the\n * directory (a stray uid-1000 process inside the container or a host-side\n * platform process writing through the project bind-mount), the runner\n * cannot chmod it. The platform's agent container entrypoint runs as root\n * and heals the subtree on the next restart — see\n * `platform/docker/agent/entrypoint.sh` `_skaile_heal_ownership`. A debug\n * line is emitted when a logger is supplied so the rare-but-real heal\n * trigger is observable in session logs without adding noise on the happy\n * path.\n *\n * The chmod is *idempotent* (the syscall always fires, but a no-op when\n * the mode is already 0o770), not a no-op — kernel behaviour for chmod is\n * \"set\", not \"set-if-different\".\n *\n * @param dir Absolute or relative path to ensure exists at mode 0o770.\n * @param log Optional logger. When provided, EPERM-on-chmod emits a\n * `debug`-level entry under whatever taxonomy the caller's logger uses.\n */\nexport async function ensureDirMode(dir: string, log?: Logger): Promise<void> {\n await mkdir(dir, { recursive: true });\n try {\n await chmod(dir, 0o770);\n } catch (err) {\n log?.debug(\"chmod 0770 skipped (EPERM — entrypoint heal expected)\", {\n path: dir,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","/**\n * PortPool — allocates ports from a [min, max] range, checks OS for collisions.\n */\n\nimport { createConnection } from \"node:net\";\n\n/**\n * Allocates TCP ports from a `[min, max]` range with OS-level collision detection.\n * Used by service connector adapters (devserver, static-server) to assign local ports.\n * @docLink packages/connectors/api-reference#port-pool\n */\nexport class PortPool {\n private readonly min: number;\n private readonly max: number;\n private readonly inUse = new Set<number>();\n\n constructor(range: [number, number]) {\n this.min = range[0];\n this.max = range[1];\n }\n\n /** Allocate the next free port from the range. Checks OS for collisions. */\n async allocate(): Promise<number> {\n for (let port = this.min; port <= this.max; port++) {\n if (this.inUse.has(port)) continue;\n if (!(await PortPool.isPortFree(port))) {\n this.inUse.add(port);\n continue;\n }\n this.inUse.add(port);\n return port;\n }\n throw new Error(`No free port in range ${this.min}-${this.max}`);\n }\n\n /** Mark a port as in-use (for explicit port args or registered instances). */\n reserve(port: number): void {\n this.inUse.add(port);\n }\n\n /** Return a port to the pool. */\n release(port: number): void {\n this.inUse.delete(port);\n }\n\n /** Check if a port is currently tracked as in-use. */\n isInUse(port: number): boolean {\n return this.inUse.has(port);\n }\n\n /** Quick TCP connect test — returns true if nothing is listening. */\n static isPortFree(port: number, host = \"127.0.0.1\"): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = createConnection({ port, host });\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve(false);\n });\n socket.once(\"error\", () => {\n socket.destroy();\n resolve(true);\n });\n socket.setTimeout(500, () => {\n socket.destroy();\n resolve(true);\n });\n });\n }\n}\n","/**\n * Shared filesystem watcher factory for mountable adapters.\n *\n * Uses chokidar for cross-platform, debounced file watching.\n *\n * Automatically reads .gitignore from the watched directory and merges\n * those patterns into chokidar's ignore list. This prevents scanning\n * large generated directories (node_modules, dist, .next, etc.) that\n * most projects already declare as ignored.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n// Static import so bun --compile bundles chokidar into the binary. A dynamic\n// `await import(\"chokidar\")` is not seen by the compiler's static analyzer\n// and fails at runtime inside the /$bunfs/ virtual filesystem.\nimport chokidar from \"chokidar\";\nimport type { ConnectorChangeEvent } from \"./connector-types.js\";\nimport type { WatchHandle, WatchOptions } from \"./shared-types.js\";\n\n/**\n * Convert a glob pattern to a matcher function.\n *\n * Chokidar 5 changed string matchers to exact equality (`===`) instead of\n * glob matching. We convert our patterns to functions so chokidar can still\n * filter correctly.\n */\nfunction globToMatcher(pattern: string): (path: string) => boolean {\n // Simple segment-name patterns: **/NAME/** or **/NAME\n // Match any path that contains /NAME/ or ends with /NAME\n const segmentMatch = pattern.match(/^\\*\\*\\/([^*/?]+)\\/\\*\\*$/);\n if (segmentMatch) {\n const name = segmentMatch[1];\n return (p: string) => p.includes(`/${name}/`) || p.endsWith(`/${name}`) || p === name;\n }\n\n // Dot-prefixed segment: **/.NAME or **/.NAME/**\n const dotSegment = pattern.match(/^\\*\\*\\/(\\.[\\w#]+)(?:\\/\\*\\*)?$/);\n if (dotSegment) {\n const name = dotSegment[1];\n return (p: string) => p.includes(`/${name}/`) || p.endsWith(`/${name}`) || p === name;\n }\n\n // Extension wildcard: **/*.EXT.* or **/*.EXT\n const extMatch = pattern.match(/^\\*\\*\\/\\*(\\.\\w+(?:\\.\\*)?)/);\n if (extMatch) {\n const suffix = extMatch[1];\n if (suffix.endsWith(\".*\")) {\n // e.g. **/*.tmp.* -> match any file with .tmp. in it\n const base = suffix.slice(0, -2);\n return (p: string) => p.includes(base);\n }\n return (p: string) => p.endsWith(suffix);\n }\n\n // Suffix wildcard: **/*SUFFIX (e.g. **/*~)\n const suffixMatch = pattern.match(/^\\*\\*\\/\\*(.+)$/);\n if (suffixMatch) {\n const sfx = suffixMatch[1];\n return (p: string) => p.endsWith(sfx);\n }\n\n // Fallback: convert simple globs to regex\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \".*\");\n const re = new RegExp(`^${escaped}$`);\n return (p: string) => re.test(p);\n}\n\nconst DEFAULT_IGNORED: Array<string | ((path: string) => boolean)> = [\n (p: string) => p.includes(\"/.git/\") || p.endsWith(\"/.git\"),\n (p: string) => p.includes(\"/node_modules/\") || p.endsWith(\"/node_modules\"),\n (p: string) => p.includes(\"/.connectors/\") || p.endsWith(\"/.connectors\"),\n // Atomic-write tempfiles (Bun.write creates `<name>.tmp.<pid>.<ts>` then renames).\n // These vanish between readdir and fs.watch, causing EINVAL that crashes the process.\n (p: string) => /\\.tmp\\.\\d/.test(p),\n // Editor swap/backup files that also race with save operations.\n (p: string) => p.endsWith(\".swp\"),\n (p: string) => p.endsWith(\".swx\"),\n (p: string) => p.includes(\"/.#\"),\n (p: string) => p.endsWith(\"~\"),\n];\n/**\n * Default chokidar `awaitWriteFinish` stability threshold (ms). Exported so the\n * rclone process manager can reuse the same write-stabilization concept when\n * gating a flush on a quiescent mount.\n */\nexport const DEFAULT_DEBOUNCE_MS = 150;\n\n/**\n * Parse a .gitignore file into glob patterns suitable for chokidar's `ignored` option.\n * Handles comments, blank lines, directory patterns, and root-relative patterns.\n * Negation patterns (!) are skipped - chokidar cannot un-ignore.\n */\nfunction parseGitignore(rootDir: string): Array<(path: string) => boolean> {\n const gitignorePath = join(rootDir, \".gitignore\");\n if (!existsSync(gitignorePath)) return [];\n\n try {\n const content = readFileSync(gitignorePath, \"utf-8\");\n const matchers: Array<(path: string) => boolean> = [];\n\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\") || line.startsWith(\"!\")) continue;\n\n let pattern = line;\n\n // Strip leading / (root-relative -> convert to rootDir-relative)\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.slice(1);\n } else if (!pattern.includes(\"/\")) {\n // Bare name like \"node_modules\" or \"*.log\" -> match anywhere\n pattern = `**/${pattern}`;\n }\n\n // Directory pattern (trailing /) -> ensure it matches contents too\n if (pattern.endsWith(\"/\")) {\n matchers.push(globToMatcher(`${pattern}**`));\n } else {\n matchers.push(globToMatcher(pattern));\n // Also match as directory (e.g. \"dist\" should match \"dist/\" and \"dist/**\")\n if (!pattern.includes(\"*\") && !pattern.includes(\".\")) {\n matchers.push(globToMatcher(`${pattern}/**`));\n }\n }\n }\n\n return matchers;\n } catch {\n return [];\n }\n}\n\ntype ChokidarAction = \"create\" | \"edit\" | \"delete\";\n\nconst CHOKIDAR_EVENT_MAP: Record<string, ChokidarAction> = {\n add: \"create\",\n change: \"edit\",\n unlink: \"delete\",\n addDir: \"create\",\n unlinkDir: \"delete\",\n};\n\n/**\n * Create a cross-platform filesystem watcher on `rootDir` using chokidar.\n * Auto-reads `.gitignore` from `rootDir` and merges those patterns into the ignore list.\n * @param rootDir - Absolute path to the directory to watch.\n * @param callback - Called with each `ConnectorChangeEvent` (create / edit / delete).\n * @param options - Debounce interval and additional ignore patterns.\n * @returns A `WatchHandle` — call `.close()` to stop watching.\n * @docLink packages/connectors/api-reference#create-fs-watcher\n */\nexport async function createFsWatcher(\n rootDir: string,\n callback: (event: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n): Promise<WatchHandle> {\n const log = createLogger({ kind: \"connector\", subkind: \"watcher\", instance: rootDir });\n const gitignorePatterns = parseGitignore(rootDir);\n // Convert any remaining string patterns from options to matcher functions\n // (chokidar 5 treats strings as exact equality, not globs)\n const optionsIgnored = (options?.ignored ?? []).map((entry) =>\n typeof entry === \"string\" ? globToMatcher(entry) : entry,\n );\n const ignored = [...DEFAULT_IGNORED, ...gitignorePatterns, ...optionsIgnored];\n const debounceMs = options?.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n\n const watcher = chokidar.watch(rootDir, {\n ignoreInitial: true,\n ignored,\n awaitWriteFinish: { stabilityThreshold: debounceMs, pollInterval: 50 },\n usePolling: false,\n });\n\n // Swallow transient watch errors (EINVAL/ENOENT when a file vanishes between\n // readdir and fs.watch). Without this handler, chokidar rethrows and the\n // agent process dies.\n watcher.on(\"error\", (err) => {\n const message = err instanceof Error ? err.message : String(err);\n log.warn(\"watcher error (non-fatal)\", { message });\n });\n\n for (const [chokidarEvent, action] of Object.entries(CHOKIDAR_EVENT_MAP)) {\n (watcher as { on(event: string, fn: (fullPath: string) => void): void }).on(\n chokidarEvent,\n (fullPath: string) => {\n const rel = relative(rootDir, fullPath);\n if (!rel || rel.startsWith(\"..\")) return;\n // Normalize to forward slashes\n const normalizedPath = rel.split(\"\\\\\").join(\"/\");\n callback({ path: normalizedPath, action, source: \"filesystem\" });\n },\n );\n }\n\n return {\n close: () => watcher.close(),\n };\n}\n","/**\n * RcloneProcessManager — supervises an rclone FUSE subprocess per mount.\n *\n * Responsibilities:\n * - Spawn rclone with a per-mount config + cache dir, wait for the FUSE\n * mountpoint to appear, then return a handle.\n * - Pipe rclone's JSON-formatted log lines into the parent driver's\n * {@link Logger} via a child source `${driverName}+rclone`.\n * - Coordinate graceful stop (flush → SIGTERM → fusermount fallback).\n * - Expose `flush` (POST /vfs/refresh + poll /vfs/stats), `statSize`\n * (operations/stat → authoritative remote size, backing the read-path\n * stale-tail gate) and `status` (process liveness + cache-dir size).\n *\n * Cross-link: see `workspaces/core/CLAUDE.md` § Logging for the\n * `createLogger` / `LogStore` contract, and\n * `_devlog/specs/2026-05-01-debug-logging-design.md` for the source taxonomy.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { 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 /**\n * Authoritative remote byte size for a mount-relative path, via rclone's\n * `operations/stat` rc endpoint. Backs the mount read-path stale-tail gate:\n * `operations/stat` hits the backend object directly, so it returns the true\n * remote size even when the VFS cache is serving a non-truncated item (and\n * `statSync` on the FUSE mount reports the inflated length). Returns `null`\n * when the handle is unknown, the object is missing / a directory, or the\n * call fails — the caller then trusts the on-disk bytes.\n */\n async statSize(handle: RcloneHandle, relPath: string): Promise<number | null> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) return null;\n return fetchAuthoritativeSize(handle.rcAddr, entry.spawnConfig.remote, relPath);\n }\n\n /** Liveness + cache-dir size. */\n async status(handle: RcloneHandle): Promise<{ alive: boolean; cacheBytes: number }> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n return { alive: false, cacheBytes: 0 };\n }\n const alive = entry.proc.exitCode === null && entry.proc.signalCode === null;\n const cacheBytes = await dirSize(entry.cacheDir);\n return { alive, cacheBytes };\n }\n}\n\ninterface RcloneJsonLine {\n level?: string;\n msg?: string;\n source?: string;\n time?: string;\n object?: string;\n error?: unknown;\n}\n\n/**\n * Per-process state threaded through {@link _routeRcloneLogLine} so it can\n * detect a sustained upload failure (the same object failing to upload K times\n * in a row) and surface it exactly once, instead of letting rclone retry\n * silently at INFO level forever.\n */\nexport interface RcloneLogRouteContext {\n /** Consecutive retries for one object before {@link onUploadStuck} fires. */\n stuckThreshold?: number;\n /** Objects already alerted on, to fire once and not on every later retry. */\n alertedObjects?: Set<string>;\n /** Per-object consecutive `itemNotFound` count; escalates at {@link stuckThreshold}. */\n itemNotFoundCounts?: Map<string, number>;\n /** Called the first time an object crosses {@link stuckThreshold}. */\n onUploadStuck?: (object: string, tries: number) => void;\n /** Called when a line matches an OAuth auth-failure pattern. */\n onAuthError?: () => void;\n}\n\n/** rclone's vfs write-back failure line: \"... failed to upload try #3, will retry ...\". */\nconst UPLOAD_FAIL_RE = /failed to upload.*?try #(\\d+)/i;\n/** rclone's vfs write-back success line, used to reset the per-object alert. */\nconst UPLOAD_OK_RE = /upload succeeded/i;\n/**\n * OAuth token-level failures rclone emits when the access token is expired and\n * it cannot self-refresh (the Skaile-managed-Entra `client_secret`-stripped\n * case). `invalid_client` / `couldn't fetch token` is the confirmed prod\n * symptom; the rest cover the equivalent MSAL/refresh-grant token failures.\n * Bare HTTP `401` is intentionally excluded — rclone retries many transient\n * 401s internally without needing a token refresh; only these token-level\n * failures mean rclone is stuck.\n */\nconst AUTH_FAIL_RE =\n /invalid_client|couldn'?t fetch token|invalid_grant|InvalidAuthenticationToken/i;\n/**\n * `itemNotFound` 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 * @internal\n * Split an rclone mount `remote` (`skaile-<id>:/base/path`) plus a\n * mount-relative path into the `{fs, remote}` pair rclone's `operations/stat`\n * rc command expects: `fs` is the backend root (`skaile-<id>:`) and `remote` is\n * the object path within it. Leading/trailing slashes are normalised away so\n * the join is stable regardless of how either side is slashed. Exported for\n * tests; not part of the public API.\n */\nexport function _operationsStatTarget(\n remote: string,\n relPath: string,\n): { fs: string; remote: string } {\n const colon = remote.indexOf(\":\");\n const fs = colon >= 0 ? remote.slice(0, colon + 1) : remote;\n const base = colon >= 0 ? remote.slice(colon + 1) : \"\";\n const joined = [base, relPath]\n .map((s) => s.replace(/^\\/+|\\/+$/g, \"\"))\n .filter((s) => s.length > 0)\n .join(\"/\");\n return { fs, remote: joined };\n}\n\n/**\n * Query rclone's `operations/stat` rc endpoint for the authoritative remote\n * size of `relPath` under `remote`. Returns the byte size, or `null` when the\n * object is missing, is a directory, the call fails, or the size is absent.\n *\n * Unlike a `statSync` on the FUSE mount, `operations/stat` resolves the object\n * against the backend directly, so it is not subject to the VFS cache's\n * non-truncated stale tail. Pass `fetchImpl` to test without a live rc server.\n */\nexport async function fetchAuthoritativeSize(\n rcAddr: string,\n remote: string,\n relPath: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<number | null> {\n const target = _operationsStatTarget(remote, relPath);\n try {\n const res = await fetchImpl(`http://${rcAddr}/operations/stat`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(target),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { item?: { Size?: number; IsDir?: boolean } | null };\n const item = body.item;\n if (!item || item.IsDir === true) return null;\n return typeof item.Size === \"number\" && item.Size >= 0 ? item.Size : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Poll `dir` until its newest file mtime is at least `thresholdMs` in the past\n * (no write for that long), or `timeoutMs` elapses. Returns true if it went\n * quiescent, false on timeout. An empty/missing dir counts as quiescent.\n */\nexport async function awaitQuiescent(\n dir: string,\n opts: { thresholdMs: number; timeoutMs: number; pollMs: number },\n): Promise<boolean> {\n const deadline = Date.now() + opts.timeoutMs;\n for (;;) {\n const newest = await newestMtimeMs(dir);\n if (newest === null || Date.now() - newest >= opts.thresholdMs) return true;\n if (Date.now() >= deadline) return false;\n await sleep(opts.pollMs);\n }\n}\n\n/**\n * Resolve the rclone vfs content subtree (`<cacheDir>/vfs`) where cached file\n * data — and therefore agent writes — land, falling back to `cacheDir` itself\n * if that subtree doesn't exist yet. Keeps the stabilization gate off rclone's\n * `vfsMeta/` housekeeping tree.\n */\nasync function vfsContentDir(cacheDir: string): Promise<string> {\n const vfs = path.join(cacheDir, \"vfs\");\n try {\n return (await stat(vfs)).isDirectory() ? vfs : cacheDir;\n } catch {\n return cacheDir;\n }\n}\n\n/**\n * Recursively find the most recent file mtime (ms) under `dir`. Returns null if\n * the dir is missing or contains no files. Symlinks are skipped — rclone's\n * cache holds only regular files and dirs.\n */\nasync function newestMtimeMs(dir: string): Promise<number | null> {\n let newest: number | null = null;\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const full = path.join(dir, String(e.name));\n if (e.isDirectory()) {\n const sub = await newestMtimeMs(full);\n if (sub !== null && (newest === null || sub > newest)) newest = sub;\n } else if (e.isFile()) {\n try {\n const s = await stat(full);\n if (newest === null || s.mtimeMs > newest) newest = s.mtimeMs;\n } catch {\n // ignore — file vanished between readdir and stat\n }\n }\n }\n } catch {\n return null;\n }\n return newest;\n}\n\n/**\n * @internal\n * Returns true if a FUSE mount is present at `mountPoint` in the given\n * /proc/self/mounts text. The fstype check (field 3, `fuse.*`) is essential:\n * the deferred-mount barrier leaves a `tmpfs` mounted at the same path, so a\n * path-only match would report the *barrier* as the confirmed mount and mask a\n * dead rclone process. Exported for tests; not part of the public API.\n */\nexport function _fuseMountPresent(procMountsText: string, mountPoint: string): boolean {\n const resolved = path.resolve(mountPoint);\n for (const raw of procMountsText.split(\"\\n\")) {\n if (raw.length === 0) continue;\n const fields = raw.split(/\\s+/);\n const mp = fields[1];\n const fstype = fields[2];\n if (!mp || !fstype) continue;\n // /proc/self/mounts encodes spaces as \\040; cheap decode.\n const decoded = mp.replace(/\\\\040/g, \" \");\n // User-space FUSE only (`fuse` or `fuse.<subtype>`); excludes the `fusectl`\n // kernel control fs. rclone mounts as `fuse.rclone`.\n if (decoded === resolved && (fstype === \"fuse\" || fstype.startsWith(\"fuse.\"))) return true;\n }\n return false;\n}\n\n/** Returns true if a FUSE mount (rclone) is live at `mountPoint`. */\nasync function isMountpoint(mountPoint: string): Promise<boolean> {\n try {\n const text = await readFile(\"/proc/self/mounts\", \"utf8\");\n return _fuseMountPresent(text, mountPoint);\n } catch {\n return false;\n }\n}\n\n/**\n * Poll `check` every `intervalMs` until it returns true or `timeoutMs`\n * elapses. Returns true on success, false on timeout.\n */\nasync function waitFor(\n check: () => Promise<boolean>,\n opts: { timeoutMs: number; intervalMs: number },\n): Promise<boolean> {\n const deadline = Date.now() + opts.timeoutMs;\n while (Date.now() < deadline) {\n if (await check()) return true;\n await sleep(opts.intervalMs);\n }\n return await check();\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/** Wire a Readable to a per-line callback, buffering partial chunks. */\nfunction attachLineSplitter(stream: Readable, onLine: (line: string) => void): void {\n let buffer = \"\";\n stream.setEncoding(\"utf8\");\n stream.on(\"data\", (chunk: string) => {\n buffer += chunk;\n let idx = buffer.indexOf(\"\\n\");\n while (idx >= 0) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n if (line.length > 0) onLine(line);\n idx = buffer.indexOf(\"\\n\");\n }\n });\n stream.on(\"end\", () => {\n if (buffer.length > 0) {\n onLine(buffer);\n buffer = \"\";\n }\n });\n}\n\n/** Recursively sum file sizes under `dir`. Returns 0 if dir does not exist. */\nasync function dirSize(dir: string): Promise<number> {\n let total = 0;\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const full = path.join(dir, String(e.name));\n if (e.isDirectory()) {\n total += await dirSize(full);\n } else if (e.isFile()) {\n try {\n const s = await stat(full);\n total += s.size;\n } catch {\n // ignore\n }\n }\n }\n } catch {\n return 0;\n }\n return total;\n}\n"]}
|
|
@@ -371,6 +371,14 @@ var SessionDispatcher = class {
|
|
|
371
371
|
* wraps them in a `<conversation_history>` block. The current user
|
|
372
372
|
* message (just persisted) is excluded since it is already the prompt.
|
|
373
373
|
*
|
|
374
|
+
* Each turn is rendered as a self-closing `<turn role="...">` element
|
|
375
|
+
* rather than a bare `[User]:` / `[Assistant]:` transcript line. A plain
|
|
376
|
+
* role-prefixed transcript invites the model to *continue* it — completing
|
|
377
|
+
* the next `[User]:` turn as plaintext inside its own answer (a fabricated
|
|
378
|
+
* follow-up that swallows the real next message). XML-tagged, explicitly
|
|
379
|
+
* read-only turns remove that completion affordance while preserving the
|
|
380
|
+
* same information.
|
|
381
|
+
*
|
|
374
382
|
* Returns the original prompt unchanged if there is no prior history.
|
|
375
383
|
*/
|
|
376
384
|
async enrichPromptWithHistory(currentPrompt) {
|
|
@@ -384,19 +392,21 @@ var SessionDispatcher = class {
|
|
|
384
392
|
if (history.length === 0) {
|
|
385
393
|
return currentPrompt;
|
|
386
394
|
}
|
|
387
|
-
const
|
|
395
|
+
const esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
396
|
+
const turns = history.map((m) => {
|
|
388
397
|
const p = m.payload;
|
|
389
398
|
if (p.type === "prompt") {
|
|
390
|
-
return
|
|
399
|
+
return `<turn role="user">${esc(String(p.prompt ?? ""))}</turn>`;
|
|
391
400
|
}
|
|
392
401
|
const content = String(p.summary ?? p.question ?? "");
|
|
393
|
-
return
|
|
402
|
+
return `<turn role="assistant">${esc(content)}</turn>`;
|
|
394
403
|
});
|
|
395
404
|
return `<conversation_history>
|
|
396
|
-
|
|
405
|
+
The following is prior conversation context, provided read-only so you have continuity. Do NOT continue, echo, or complete it \u2014 it is history, not a turn for you to extend. Respond only to the user message that follows the closing tag.
|
|
406
|
+
${turns.join("\n")}
|
|
397
407
|
</conversation_history>
|
|
398
408
|
|
|
399
|
-
|
|
409
|
+
` + currentPrompt;
|
|
400
410
|
}
|
|
401
411
|
async handleAgentEvent(event, mentions) {
|
|
402
412
|
if (this._compacting) {
|
|
@@ -502,5 +512,5 @@ function isAgentAddressed(mentions) {
|
|
|
502
512
|
}
|
|
503
513
|
|
|
504
514
|
export { SessionDispatcher, isAgentAddressed, isMentioned, parseMentions };
|
|
505
|
-
//# sourceMappingURL=chunk-
|
|
506
|
-
//# sourceMappingURL=chunk-
|
|
515
|
+
//# sourceMappingURL=chunk-3K2CYDBT.js.map
|
|
516
|
+
//# sourceMappingURL=chunk-3K2CYDBT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../session/src/dispatcher.ts","../session/src/mentions.ts"],"names":[],"mappings":";;;AAsDA,IAAM,eAAA,uBAAsB,GAAA,CAAI;AAAA,EAC9B,kBAAA;AAAA,EACA,mBAAA;AAAA,EACA,qBAAA;AAAA,EACA,oBAAA;AAAA,EACA,eAAA;AAAA,EACA,QAAA;AAAA,EACA,cAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AA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AS,WAAA,CAAY,KAAK,CAAA;AACvC,MAAA,IAAI,IAAA,EAAM;AACR,QAAA,QAAA,CAAS,IAAA,CAAK;AAAA,UACZ,IAAA,EAAM,MAAA;AAAA,UACN,QAAQ,IAAA,CAAK,MAAA;AAAA,UACb,MAAM,IAAA,CAAK,IAAA;AAAA,UACX,MAAA;AAAA,UACA;AAAA,SACD,CAAA;AAAA,MACH;AAAA,IACF;AAAA,EACF;AAGA,EAAA,OAAO,QAAA;AACT;AAcO,SAAS,WAAA,CAAY,QAAgB,QAAA,EAA8B;AACxE,EAAA,KAAA,MAAW,KAAK,QAAA,EAAU;AACxB,IAAA,IAAI,EAAE,IAAA,KAAS,MAAA,IAAU,CAAA,CAAE,MAAA,KAAW,QAAQ,OAAO,IAAA;AACrD,IAAA,IAAI,CAAA,CAAE,SAAS,OAAA,IAAW,CAAA,CAAE,SAAS,QAAA,CAAS,MAAM,GAAG,OAAO,IAAA;AAAA,EAChE;AACA,EAAA,OAAO,KAAA;AACT;AAOA,IAAM,+BAA0C,IAAI,GAAA,CAAI,CAAC,OAAA,EAAS,MAAA,EAAQ,KAAK,CAAC,CAAA;AAYzE,SAAS,iBAAiB,QAAA,EAA8B;AAC7D,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,OAAA,IAAW,YAAA,CAAa,GAAA,CAAI,CAAA,CAAE,KAAK,CAAC,CAAA;AAC7E","file":"chunk-3K2CYDBT.js","sourcesContent":["import type { AgentClient } from \"@skaile/workspaces/client\";\nimport type {\n AgentCommand,\n AgentEvent,\n ConnectorRequestCommand,\n ConnectorResponseEvent,\n Mention,\n ReplyRef,\n} from \"@skaile/workspaces/types\";\nimport type { Message, MessageStore, SubscriberInfo, SubscriberTransport } from \"./types.js\";\n\n/**\n * Construction options for {@link SessionDispatcher}.\n *\n * All three infrastructure objects (`client`, `store`, `transport`) are\n * injected by the caller so the dispatcher remains testable and framework-agnostic.\n *\n * @docLink packages/session/api-reference#session-dispatcher\n */\nexport interface SessionDispatcherOptions {\n /** Unique identifier for the session this dispatcher manages. */\n sessionId: string;\n /** Connected agent client used to send commands and receive events. */\n client: AgentClient;\n /** Persistence layer for all non-transient messages. */\n store: MessageStore;\n /** Fan-out transport for broadcasting events to connected frontends. */\n transport: SubscriberTransport;\n /**\n * When true, the dispatcher prepends conversation history to every prompt\n * command sent to the agent. Enable for agents without native session\n * continuity (e.g. mock mode). Agents with native multi-turn support\n * (Claude SDK, OMP) should set this to false to avoid duplicate context.\n * Default: false.\n */\n injectConversationHistory?: boolean;\n /** Max conversation history messages to include in enriched prompts (default: 50). */\n historyLimit?: number;\n /**\n * Optional callback to transform prompt text before forwarding to the agent.\n * The original (untransformed) prompt is persisted and broadcast to subscribers.\n * Applied after conversation history enrichment. Use this to inject context\n * (e.g. UI state) that the agent should see but subscribers should not.\n */\n transformPrompt?: (prompt: string, senderId: string | undefined, replyTo?: ReplyRef) => string;\n}\n\n/**\n * Command and event types classified as transient RPC — high-frequency,\n * ephemeral, and not part of the conversation history.\n *\n * Matching payloads are forwarded and broadcast but never persisted\n * or assigned a sequence number, preventing bloat in the message log.\n */\nconst TRANSIENT_TYPES = new Set([\n \"resource_request\",\n \"resource_response\",\n \"resources_available\",\n \"commands_available\",\n \"state_changed\",\n \"typing\",\n \"user_message\",\n // OMP session tracking — forwarded to subscribers but not persisted\n \"session_info\",\n // Structured log forwarding — high-volume; persisted in per-session SQLite, not the message store\n \"log_entry\",\n // Generic connector dispatch — system RPC, not chat messages.\n // Replaces the 6 typed flow commands removed in Protocol 2.2 (Phase 4 of the\n // flow-connector extraction). `connector_mutate` against the `flow` connector\n // is now how hosts drive flow execution between turns.\n \"connector_mutate\",\n \"connector_query\",\n \"connector_query_response\",\n]);\n\n/**\n * Bridges a single agent session between an {@link AgentClient} and one or more\n * frontend subscribers.\n *\n * Responsibilities:\n * - Persists every non-transient command and event as a {@link Message} with a\n * monotonic sequence number via the injected {@link MessageStore}.\n * - Fans agent events out to all connected frontends via the injected\n * {@link SubscriberTransport}.\n * - Optionally enriches prompt commands with conversation history so agents\n * without native multi-turn support maintain context across turns.\n *\n * **Lifecycle:** call {@link init} before any other method, and {@link disconnect}\n * when the session ends.\n *\n * @example\n * ```ts\n * const dispatcher = new SessionDispatcher({\n * sessionId: 'sess-123',\n * client: agentClient,\n * store: prismaMessageStore,\n * transport: trpcTransport,\n * })\n * await dispatcher.init()\n * const history = await dispatcher.subscribe('ws-conn-abc', { limit: 50 })\n * const msg = await dispatcher.sendCommand({ type: 'prompt', prompt: 'Hello' }, 'user-42')\n * await dispatcher.disconnect()\n * ```\n *\n * @docLink packages/session/api-reference#session-dispatcher\n */\nexport class SessionDispatcher {\n /** The session identifier this dispatcher is bound to. */\n readonly sessionId: string;\n private client: AgentClient;\n private store: MessageStore;\n private transport: SubscriberTransport;\n private subscribers: Set<string> = new Set();\n private subscriberMeta: Map<string, SubscriberInfo> = new Map();\n private seq: number = 0;\n private _availableResources: { mounts: unknown[]; connectors: unknown[] } = {\n mounts: [],\n connectors: [],\n };\n\n /** Whether to inject conversation history into prompt commands. */\n private readonly injectConversationHistory: boolean;\n /** Maximum number of history messages to include in enriched prompts. */\n private readonly historyLimit: number;\n /** Optional prompt transformer applied before forwarding (after persistence). */\n private _transformPrompt?: (\n prompt: string,\n senderId: string | undefined,\n replyTo?: ReplyRef,\n ) => string;\n /** Whether the dispatcher is currently in compaction mode. */\n private _compacting = false;\n /** Accumulated text content during compaction. */\n private _compactionText = \"\";\n\n /**\n * One-shot waiters registered via {@link onceNextFinished}. Each is invoked\n * exactly once with the text of the next `finished` assistant event, then\n * the list is cleared. Backs the A2A router's synchronous `ask` answer\n * capture.\n */\n private nextFinishedWaiters: Array<(text: string) => void> = [];\n /**\n * Text streamed by the agent since the last `finished` event. Used as the\n * fallback answer text for {@link onceNextFinished} when a `finished` event\n * carries an empty `summary` (drivers that stream `text` chunks and leave\n * the summary blank).\n */\n private _turnText = \"\";\n\n /**\n * @param opts - Dispatcher configuration — see {@link SessionDispatcherOptions}.\n */\n constructor(opts: SessionDispatcherOptions) {\n this.sessionId = opts.sessionId;\n this.client = opts.client;\n this.store = opts.store;\n this.transport = opts.transport;\n this.injectConversationHistory = opts.injectConversationHistory ?? false;\n this.historyLimit = opts.historyLimit ?? 50;\n this._transformPrompt = opts.transformPrompt;\n }\n\n /**\n * Replace the prompt transformer at runtime.\n *\n * Useful when additional context (e.g. a UI state cache) becomes available\n * after the dispatcher is constructed but before the first prompt is sent.\n */\n set transformPrompt(fn:\n | ((prompt: string, senderId: string | undefined, replyTo?: ReplyRef) => string)\n | undefined,) {\n this._transformPrompt = fn;\n }\n\n /**\n * Initialize the dispatcher for this session.\n *\n * Restores the monotonic sequence counter from the store and wires up the\n * agent event listener. Must be called once before any other method.\n *\n * @throws If {@link MessageStore.getLatestSeq} rejects.\n */\n async init(): Promise<void> {\n this.seq = await this.store.getLatestSeq(this.sessionId);\n this.client.onEvent((event: AgentEvent) => {\n void this.handleAgentEvent(event);\n });\n }\n\n /**\n * Register a frontend subscriber and return recent message history.\n *\n * Subsequent agent events are pushed to this subscriber via the\n * {@link SubscriberTransport} until {@link unsubscribe} is called.\n *\n * @param subscriberId - Opaque connection ID (e.g. WebSocket session ID).\n * @param opts - Optional subscription options.\n * @param opts.limit - Number of recent messages to return (default: 50).\n * @returns Recent messages ordered by seq ascending.\n */\n async subscribe(\n subscriberId: string,\n opts?: { limit?: number; userId?: string; roles?: string[] },\n ): Promise<Message[]> {\n this.subscribers.add(subscriberId);\n if (opts?.userId !== undefined || opts?.roles !== undefined) {\n this.subscriberMeta.set(subscriberId, {\n userId: opts.userId,\n roles: opts.roles,\n });\n }\n return this.store.getMessages(this.sessionId, {\n limit: opts?.limit ?? 50,\n });\n }\n\n /**\n * Remove a frontend subscriber and release transport resources.\n *\n * @param subscriberId - The ID passed to {@link subscribe}.\n */\n unsubscribe(subscriberId: string): void {\n this.subscribers.delete(subscriberId);\n this.subscriberMeta.delete(subscriberId);\n this.transport.remove(subscriberId);\n }\n\n /**\n * Send a command from a frontend to the agent.\n *\n * Persistent commands are wrapped in a Message envelope and stored before\n * forwarding. Transient commands (resource RPC) are forwarded directly\n * without persistence — returns null in that case.\n *\n * For `prompt` commands, the original message is persisted, but an enriched\n * version (with conversation history prepended) is sent to the agent so it\n * maintains context across turns.\n *\n * @param command - The command to dispatch to the agent (a prompt or tool result).\n * @param senderId - ID of the user sending the command, if known.\n * @param mentions - Resolved mention objects extracted from the prompt text.\n * @param visibility - Optional platform visibility envelope (F-23). When\n * `visibilityMode` is `HumansOnly`, or `Private` without the `\"__agent__\"`\n * sentinel in `privateRecipientIds` (B-30), the message is persisted and\n * broadcast to subscribers but NOT forwarded to the agent.\n * @param outgoingPrefix - Optional text prepended to the outgoing command's\n * user-text field ({@link command.prompt} / `command.answer` /\n * `command.content`) AFTER persistence but BEFORE history enrichment and\n * {@link transformPrompt}. The persisted {@link Message} envelope is built\n * from the original `command` and never sees the prefix. Use this to\n * inject one-shot wake-time context (Option B1 pending restoration\n * prompt) that the agent must see but UI subscribers must not.\n * @returns The persisted Message envelope, or null for transient command types.\n */\n async sendCommand(\n command: AgentCommand,\n senderId?: string,\n mentions?: Mention[],\n visibility?: NonNullable<Message[\"visibility\"]>,\n outgoingPrefix?: string,\n ): Promise<Message | null> {\n if (!this.shouldPersist(command)) {\n this.client.send(command);\n return null;\n }\n // Persist the original command (unenriched/untransformed/un-prefixed).\n // `outgoingPrefix` is intentionally NOT applied here — it must only\n // reach the agent client, never the MessageStore.\n const message = this.createMessage(command, senderId);\n // @TODO: Code-Review: v1 back-compat — mentions field no longer used by Protocol v2+ persistence layers; remove once platform PrismaMessageStore is migrated\n if (mentions?.length) message.mentions = mentions;\n // F-23: platform-extension visibility metadata (3.2.0). The platform\n // MessageStore reads this off the envelope and writes the\n // Message.visibilityMode column + recipient rows atomically with\n // the message itself — no post-send patch, no race window where a\n // concurrent send could mis-tag the wrong message id.\n if (visibility) message.visibility = visibility;\n await this.store.append(message);\n\n // Build the outgoing command — enrich and transform prompt commands\n // while leaving the persisted message untouched.\n let outgoing: AgentCommand = command;\n if (command.type === \"prompt\") {\n let prompt = command.prompt;\n // Restoration prefix lands FIRST (innermost) so the user's typed\n // text remains adjacent to its own framing, with history and reply\n // preambles wrapping the combined block from the outside in.\n if (outgoingPrefix) {\n prompt = `${outgoingPrefix}${prompt}`;\n }\n if (this.injectConversationHistory) {\n prompt = await this.enrichPromptWithHistory(prompt);\n }\n if (this._transformPrompt) {\n prompt = this._transformPrompt(prompt, senderId, command.replyTo);\n }\n if (prompt !== command.prompt) {\n outgoing = { ...command, prompt };\n }\n } else if (outgoingPrefix && command.type === \"reply\") {\n // `reply` carries user text in `answer`. Prefix is invisible to\n // subscribers (who see the persisted Message.payload.answer) but\n // visible to the agent driver.\n outgoing = { ...command, answer: `${outgoingPrefix}${command.answer}` };\n } else if (outgoingPrefix && command.type === \"custom_message\") {\n // `custom_message` carries user text in `content`. Same persist/send\n // split as the `reply` branch above.\n outgoing = { ...command, content: `${outgoingPrefix}${command.content}` };\n }\n\n // F-23 P3 review (B1) — HumansOnly visibility means the message is\n // intended for human recipients only; the agent must NOT see the\n // prompt content. Persist + broadcast (humans read it via\n // SubscriberTransport) but skip the agent forward. This closes a\n // critical privacy hole where `@user: secret` was persisted with\n // visibilityMode='HumansOnly' yet still reached the LLM. Threads\n // starting HumansOnly stay agent-invisible even on Public follow-ups\n // (parent-thread visibility threading is intentionally out of scope\n // for v1; only the immediate message is gated). See\n // platform/_concept/plans/f-23-p3-review-blockers.md.\n if (visibility?.visibilityMode === \"HumansOnly\") {\n return message;\n }\n\n // B-30 — Private visibility (F-23 `@mention_` underscore suffix) means the\n // message is addressed to an explicit recipient set. The agent is only a\n // recipient when the sender wrote `@agent_`, which the platform encodes as\n // the `\"__agent__\"` sentinel in `privateRecipientIds`. When the sentinel is\n // absent the message is a private human-to-human exchange: persist +\n // broadcast (the named human recipients read it via SubscriberTransport)\n // but skip the agent forward so the LLM never sees private content.\n if (\n visibility?.visibilityMode === \"Private\" &&\n !visibility.privateRecipientIds?.includes(\"__agent__\")\n ) {\n return message;\n }\n\n this.client.send(outgoing);\n return message;\n }\n\n /**\n * Persist a synthetic event (not received from the agent) and broadcast it.\n *\n * Used by the platform to inject events like a partial-text `finished` record\n * before a cancel command.\n *\n * @param event - The agent event to persist.\n * @param mentions - Resolved mentions from the originating command.\n */\n async persistEvent(event: AgentEvent, mentions?: Mention[]): Promise<Message | null> {\n return this.handleAgentEvent(event, mentions);\n }\n\n /**\n * Load paginated message history for this session.\n *\n * @param opts.before - Return messages with seq strictly less than this value.\n * @param opts.limit - Maximum number of messages to return.\n */\n async getMessages(opts?: { before?: number; limit?: number }): Promise<Message[]> {\n return this.store.getMessages(this.sessionId, opts);\n }\n\n /**\n * Available mounts and connectors captured from the most recent\n * `resources_available` event emitted by the agent on connect.\n *\n * Empty until the agent emits the event or {@link seedResources} is called.\n */\n get availableResources(): { mounts: unknown[]; connectors: unknown[] } {\n return this._availableResources;\n }\n\n /**\n * Seed the available resources from an external cache.\n *\n * This is needed when the dispatcher is created after the agent has already\n * emitted `resources_available` on WebSocket connect. Without seeding, the\n * dispatcher would report an empty resource list until the next reconnect.\n *\n * @param resources - Resource handles to register before the session starts.\n */\n seedResources(resources: { mounts: unknown[]; connectors: unknown[] }): void {\n const empty =\n this._availableResources.mounts.length === 0 &&\n this._availableResources.connectors.length === 0;\n if (empty && (resources.mounts.length > 0 || resources.connectors.length > 0)) {\n this._availableResources = resources;\n }\n }\n\n /**\n * Deliver a prompt to the agent that triggers a turn but is NOT persisted.\n *\n * Unlike {@link sendCommand}, this never touches the {@link MessageStore}:\n * the prompt is forwarded straight to the agent client. The caller owns\n * persistence of whatever conversation rows should represent this turn.\n *\n * Used by the platform's A2A router to deliver a `from-peer` prompt to a\n * target session: the router writes the authoritative A2A `Message` rows\n * itself, so persisting the framed prompt here too would create an extra,\n * un-attributed plain `prompt` row. The dispatcher's job for this prompt is\n * delivery only.\n *\n * The agent still produces a normal turn, so an A2A `ask` round-trip can\n * capture the answer via {@link onceNextFinished}.\n *\n * @param prompt - The fully-formed prompt text to deliver to the agent.\n */\n deliverPrompt(prompt: string): void {\n this.client.send({ type: \"prompt\", prompt });\n }\n\n /**\n * Send a resource request and await the correlated response.\n *\n * This is a convenience method for request/response resource RPC.\n * The request is transient (not persisted). A one-shot event listener\n * waits for the matching `resource_response` by `requestId`.\n *\n * @param command - A ConnectorRequestCommand (caller must set requestId).\n * @param timeoutMs - How long to wait before rejecting (default: 30s).\n */\n async requestResource(\n command: ConnectorRequestCommand,\n timeoutMs = 30_000,\n ): Promise<ConnectorResponseEvent> {\n return new Promise<ConnectorResponseEvent>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.client.offEvent(handler);\n reject(\n new Error(\n `Resource request timed out after ${timeoutMs}ms: ${command.operation} ${command.connectorId}`,\n ),\n );\n }, timeoutMs);\n\n const handler = (event: AgentEvent) => {\n if (event.type === \"resource_response\" && event.requestId === command.requestId) {\n clearTimeout(timer);\n this.client.offEvent(handler);\n resolve(event);\n }\n };\n\n this.client.onEvent(handler);\n this.client.send(command);\n });\n }\n\n /**\n * Broadcast a transient event to all subscribers without persisting it.\n *\n * Used for ephemeral signals like typing indicators or user-command\n * echoes that other subscribers need to see in real time.\n */\n broadcast(event: AgentEvent): void {\n for (const subscriberId of this.subscribers) {\n this.transport.send(subscriberId, event);\n }\n }\n\n /** Disconnect the agent client and clean up all subscribers. */\n async disconnect(): Promise<void> {\n for (const id of this.subscribers) {\n this.transport.remove(id);\n }\n this.subscribers.clear();\n this.subscriberMeta.clear();\n // Clear any pending A2A waiters so they don't leak if the session\n // disconnects before the target ever emits a `finished` event.\n this.nextFinishedWaiters = [];\n await this.client.dispose();\n }\n\n /**\n * Enter compaction mode. While active, events from the agent are captured\n * but NOT persisted. Text content is accumulated for the snapshot.\n */\n beginCompaction(): void {\n this._compacting = true;\n this._compactionText = \"\";\n }\n\n /**\n * Exit compaction mode and return the accumulated text.\n * The caller is responsible for creating and emitting the snapshot event.\n */\n endCompaction(): string {\n this._compacting = false;\n const text = this._compactionText;\n this._compactionText = \"\";\n return text;\n }\n\n /** Whether the dispatcher is currently in compaction mode. */\n get isCompacting(): boolean {\n return this._compacting;\n }\n\n /**\n * Register a one-shot callback fired with the text of this session's next\n * finished assistant turn. Returns an unsubscribe function.\n *\n * Semantics:\n * - The callback fires **at most once** — on the first `finished` event\n * observed after registration. Later finished turns do not re-fire it.\n * - A waiter registered after a `finished` event waits for the *following*\n * one. The hook captures the *next* finished turn, not a past one.\n * - The answer text is the `finished` event's `summary`; when that is\n * empty (drivers that stream `text` and leave the summary blank), the\n * text accumulated since the previous finished turn is used instead.\n * - Calling the returned function removes the waiter; if it has already\n * fired this is a no-op.\n *\n * Used by the platform's A2A router (`A2ARouterService.ask`) to capture a\n * peer session's answer to a `from-peer` question. v1 captures the first\n * finished turn after delivery — see the busy-target notes in the A2A\n * design spec for the known turn-matching limitation.\n *\n * @param cb - Invoked once with the next finished turn's text.\n * @returns Unsubscribe function that removes this waiter.\n */\n onceNextFinished(cb: (text: string) => void): () => void {\n this.nextFinishedWaiters.push(cb);\n return () => {\n const idx = this.nextFinishedWaiters.indexOf(cb);\n if (idx !== -1) {\n this.nextFinishedWaiters.splice(idx, 1);\n }\n };\n }\n\n // -- Private ----------------------------------------------------------------\n\n /**\n * Build an enriched prompt by prepending conversation history.\n *\n * Loads recent persisted messages, formats user/assistant turns, and\n * wraps them in a `<conversation_history>` block. The current user\n * message (just persisted) is excluded since it is already the prompt.\n *\n * Each turn is rendered as a self-closing `<turn role=\"...\">` element\n * rather than a bare `[User]:` / `[Assistant]:` transcript line. A plain\n * role-prefixed transcript invites the model to *continue* it — completing\n * the next `[User]:` turn as plaintext inside its own answer (a fabricated\n * follow-up that swallows the real next message). XML-tagged, explicitly\n * read-only turns remove that completion affordance while preserving the\n * same information.\n *\n * Returns the original prompt unchanged if there is no prior history.\n */\n private async enrichPromptWithHistory(currentPrompt: string): Promise<string> {\n const messages = await this.store.getMessages(this.sessionId, {\n limit: this.historyLimit,\n });\n\n // Filter to conversation-relevant types and exclude the message we just appended\n const history = messages\n .filter((m) => {\n const type = m.payload.type;\n return type === \"prompt\" || type === \"finished\" || type === \"question\";\n })\n .slice(0, -1); // Exclude the current message (last by seq)\n\n if (history.length === 0) {\n return currentPrompt;\n }\n\n // Escape so message content (which may itself contain `</turn>` or other\n // angle brackets) cannot break out of the XML structure or inject a forged\n // turn. The model reads entity-encoded text fine; this is read-only context.\n const esc = (s: string): string =>\n s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\");\n\n const turns = history.map((m) => {\n const p = m.payload as Record<string, unknown>;\n if (p.type === \"prompt\") {\n return `<turn role=\"user\">${esc(String(p.prompt ?? \"\"))}</turn>`;\n }\n // finished (assistant response) or question\n const content = String(p.summary ?? p.question ?? \"\");\n return `<turn role=\"assistant\">${esc(content)}</turn>`;\n });\n\n return (\n \"<conversation_history>\\n\" +\n \"The following is prior conversation context, provided read-only so you \" +\n \"have continuity. Do NOT continue, echo, or complete it — it is history, \" +\n \"not a turn for you to extend. Respond only to the user message that \" +\n \"follows the closing tag.\\n\" +\n `${turns.join(\"\\n\")}\\n` +\n \"</conversation_history>\\n\\n\" +\n currentPrompt\n );\n }\n\n private async handleAgentEvent(event: AgentEvent, mentions?: Mention[]): Promise<Message | null> {\n // ── Compaction mode: capture text but don't persist ─────────────────\n if (this._compacting) {\n if (event.type === \"text\") {\n this._compactionText += (event as { content: string }).content;\n }\n // Still broadcast to subscribers (UI shows compaction progress)\n for (const subscriberId of this.subscribers) {\n this.transport.send(subscriberId, event);\n }\n return null;\n }\n\n // Capture resource metadata when the server announces available resources\n if (event.type === \"resources_available\") {\n const payload = event as { mounts?: unknown[]; connectors?: unknown[] };\n this._availableResources = {\n mounts: payload.mounts ?? [],\n connectors: payload.connectors ?? [],\n };\n }\n\n // ── onceNextFinished — one-shot \"next finished turn\" answer capture ──\n // Accumulate streamed text across the turn so the answer is available\n // even when a driver emits an empty `finished.summary`. On `finished`,\n // drain every queued waiter exactly once, then reset the accumulator.\n if (event.type === \"text\") {\n this._turnText += (event as { content: string }).content;\n } else if (event.type === \"finished\") {\n const summary = (event as { summary?: string }).summary ?? \"\";\n const answer = summary.length > 0 ? summary : this._turnText;\n this._turnText = \"\";\n if (this.nextFinishedWaiters.length > 0) {\n const waiters = this.nextFinishedWaiters;\n this.nextFinishedWaiters = [];\n for (const cb of waiters) {\n cb(answer);\n }\n }\n }\n\n let message: Message | null = null;\n if (this.shouldPersist(event)) {\n message = this.createMessage(event);\n if (mentions?.length) message.mentions = mentions;\n await this.store.append(message);\n }\n\n for (const subscriberId of this.subscribers) {\n this.transport.send(subscriberId, event);\n }\n return message;\n }\n\n private shouldPersist(payload: AgentCommand | AgentEvent): boolean {\n return !TRANSIENT_TYPES.has(payload.type);\n }\n\n private createMessage(payload: AgentCommand | AgentEvent, senderId?: string): Message {\n this.seq++;\n return {\n id: crypto.randomUUID(),\n seq: this.seq,\n timestamp: new Date().toISOString(),\n sessionId: this.sessionId,\n ...(senderId ? { senderId } : {}),\n payload,\n };\n }\n}\n","import type { Mention, MentionGroup } from \"@skaile/workspaces/types\";\nimport { MENTION_GROUPS } from \"@skaile/workspaces/types\";\n\n/**\n * Re-exported from `@skaile/workspaces/types` so consumers can import mention\n * types directly from `@skaile/workspaces/session` without a separate dependency.\n */\nexport type { Mention, MentionGroup };\n\n// ---------------------------------------------------------------------------\n// MentionResolver\n// ---------------------------------------------------------------------------\n\n/**\n * Consumer-provided resolver that maps @mention tokens to users and groups.\n *\n * The platform provides an implementation backed by Prisma and the live\n * presence service. Tests use lightweight mocks.\n *\n * @example\n * ```ts\n * const resolver: MentionResolver = {\n * resolveUser: (name) => db.users.findByName(name),\n * resolveGroup: (group) => presence.getMemberIds(group),\n * getOnlineUserIds: () => presence.getOnlineIds(),\n * }\n * ```\n *\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport interface MentionResolver {\n /**\n * Resolve a `@name` token to a user record.\n *\n * @param name - The token after the `@` symbol (case-insensitive lookup).\n * @returns User record, or null if the name is not found.\n */\n resolveUser(name: string): { userId: string; name: string } | null;\n /**\n * Resolve a group mention token to the list of member user IDs.\n *\n * @param group - The well-known group name (e.g. `\"agent\"`, `\"all\"`).\n * @returns Array of member user IDs belonging to the group.\n */\n resolveGroup(group: MentionGroup): string[];\n /** Return the IDs of users currently online (used by the `here` and `humans_here` groups). */\n getOnlineUserIds(): string[];\n}\n\n// ---------------------------------------------------------------------------\n// parseMentions\n// ---------------------------------------------------------------------------\n\nconst MENTION_RE = /@(\\w+)/g;\nconst MENTION_GROUP_SET: ReadonlySet<string> = new Set(MENTION_GROUPS);\n\n/**\n * Scan `text` for @token patterns and return resolved {@link Mention} objects.\n *\n * - Well-known group tokens (`agent`, `humans`, `humans_here`, `here`, `all`)\n * are resolved via {@link MentionResolver.resolveGroup}.\n * - All other tokens are resolved via {@link MentionResolver.resolveUser}.\n * - Tokens that cannot be resolved are silently ignored.\n * - Results are sorted by character offset ascending.\n *\n * @param text - Raw message text to scan for `@token` patterns.\n * @param resolver - Resolver that maps tokens to users and groups.\n * @returns Resolved mentions ordered by position in text.\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport function parseMentions(text: string, resolver: MentionResolver): Mention[] {\n const mentions: Mention[] = [];\n\n for (const match of text.matchAll(MENTION_RE)) {\n const token = match[1]!;\n const offset = match.index!;\n const length = match[0].length; // includes the @\n\n if (MENTION_GROUP_SET.has(token)) {\n const group = token as MentionGroup;\n mentions.push({\n type: \"group\",\n group,\n resolved: resolver.resolveGroup(group),\n offset,\n length,\n });\n } else {\n const user = resolver.resolveUser(token);\n if (user) {\n mentions.push({\n type: \"user\",\n userId: user.userId,\n name: user.name,\n offset,\n length,\n });\n }\n }\n }\n\n // matchAll iterates left-to-right, so mentions are already offset-ascending.\n return mentions;\n}\n\n// ---------------------------------------------------------------------------\n// isMentioned\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true if `userId` is directly mentioned or is a member of any\n * group mention's resolved list.\n *\n * @param userId - The user ID to check (e.g. from the auth context).\n * @param mentions - Parsed mentions from {@link parseMentions}.\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport function isMentioned(userId: string, mentions: Mention[]): boolean {\n for (const m of mentions) {\n if (m.type === \"user\" && m.userId === userId) return true;\n if (m.type === \"group\" && m.resolved.includes(userId)) return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// isAgentAddressed\n// ---------------------------------------------------------------------------\n\n/** Groups that include the agent in their resolved membership. */\nconst AGENT_GROUPS: ReadonlySet<MentionGroup> = new Set([\"agent\", \"here\", \"all\"]);\n\n/**\n * Returns true if the agent is addressed by any mention in the list.\n *\n * The groups `@agent`, `@here`, and `@all` address the agent. `@humans`\n * and `@humans_here` do not. Individual user mentions are also not matched\n * here — agent addressing is group-based.\n *\n * @param mentions - Parsed mentions from {@link parseMentions}.\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport function isAgentAddressed(mentions: Mention[]): boolean {\n return mentions.some((m) => m.type === \"group\" && AGENT_GROUPS.has(m.group));\n}\n"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { initTelemetry } from './chunk-4R6DROGN.js';
|
|
2
2
|
import { parseSkillFrontmatter, validateFlowVersions } from './chunk-GXC3TYMQ.js';
|
|
3
|
-
import { FlowAdapter } from './chunk-
|
|
3
|
+
import { FlowAdapter } from './chunk-U3RYXSI4.js';
|
|
4
4
|
import { loadFlow } from './chunk-X46FY45B.js';
|
|
5
5
|
import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-DEYYRFQU.js';
|
|
6
|
-
import { resolveSettings } from './chunk-
|
|
7
|
-
import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-
|
|
6
|
+
import { resolveSettings } from './chunk-KYQNWFJV.js';
|
|
7
|
+
import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-GJI6FZ56.js';
|
|
8
8
|
import { createLogger } from './chunk-JB35MVBN.js';
|
|
9
9
|
import fs from 'fs';
|
|
10
10
|
import path from 'path';
|
|
@@ -389,5 +389,5 @@ function walkForSkill(dir, skillId) {
|
|
|
389
389
|
}
|
|
390
390
|
|
|
391
391
|
export { resumeFlow, runFlow };
|
|
392
|
-
//# sourceMappingURL=chunk-
|
|
393
|
-
//# sourceMappingURL=chunk-
|
|
392
|
+
//# sourceMappingURL=chunk-4MO456BV.js.map
|
|
393
|
+
//# sourceMappingURL=chunk-4MO456BV.js.map
|
|
@@ -1 +1 @@
|
|
|
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,C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A,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,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"]}
|
|
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,MAA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,GACH,KAAA,CAA+C,KAAA,IAC/C,KAAA,CAA+B,OAAA,IAChC,aAAA;AACF,QAAA,IAAA,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,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-4MO456BV.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,6 +1,6 @@
|
|
|
1
1
|
import { PROVIDER_ENDPOINTS } from './chunk-BMQKMOQY.js';
|
|
2
2
|
import { classifyClaudeSdkError } from './chunk-GAH4YRCI.js';
|
|
3
|
-
import { createDriver } from './chunk-
|
|
3
|
+
import { createDriver } from './chunk-OCAQH66V.js';
|
|
4
4
|
|
|
5
5
|
// bridge/src/normalizer.ts
|
|
6
6
|
var EventNormalizer = class {
|
|
@@ -458,5 +458,5 @@ async function validateApiKey(provider, key) {
|
|
|
458
458
|
}
|
|
459
459
|
|
|
460
460
|
export { BridgeRuntime, EventNormalizer, createRuntime, detectFileChange, detectFileChanges, summarizeToolCall, summarizeToolResult, validateApiKey };
|
|
461
|
-
//# sourceMappingURL=chunk-
|
|
462
|
-
//# sourceMappingURL=chunk-
|
|
461
|
+
//# sourceMappingURL=chunk-5C3QJSOD.js.map
|
|
462
|
+
//# sourceMappingURL=chunk-5C3QJSOD.js.map
|