@skaile/workspaces 3.4.2 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/{asset-feeds-JJTN5PGH.js → asset-feeds-ATPO3XUG.js} +4 -4
  3. package/dist/{asset-feeds-JJTN5PGH.js.map → asset-feeds-ATPO3XUG.js.map} +1 -1
  4. package/dist/asset-manager/index.js +1 -1
  5. package/dist/{chunk-KSHCQ777.js → chunk-3DNCPQAR.js} +2 -2
  6. package/dist/{chunk-KSHCQ777.js.map → chunk-3DNCPQAR.js.map} +1 -1
  7. package/dist/{chunk-R6OLT7E4.js → chunk-6JKBM75L.js} +21 -12
  8. package/dist/chunk-6JKBM75L.js.map +1 -0
  9. package/dist/{chunk-KF52XLUH.js → chunk-AWAO3NQS.js} +3 -3
  10. package/dist/{chunk-KF52XLUH.js.map → chunk-AWAO3NQS.js.map} +1 -1
  11. package/dist/{chunk-MEPZOB3K.js → chunk-BVAZQTZE.js} +3 -3
  12. package/dist/{chunk-MEPZOB3K.js.map → chunk-BVAZQTZE.js.map} +1 -1
  13. package/dist/{chunk-JISWIYUA.js → chunk-CEFK3X3Q.js} +2 -2
  14. package/dist/{chunk-JISWIYUA.js.map → chunk-CEFK3X3Q.js.map} +1 -1
  15. package/dist/{chunk-WE7DETAK.js → chunk-DEESOYQ3.js} +3 -3
  16. package/dist/{chunk-WE7DETAK.js.map → chunk-DEESOYQ3.js.map} +1 -1
  17. package/dist/{chunk-GWUGD4FQ.js → chunk-JA36A5KR.js} +2 -2
  18. package/dist/{chunk-GWUGD4FQ.js.map → chunk-JA36A5KR.js.map} +1 -1
  19. package/dist/{chunk-XDIVJ7G6.js → chunk-SHCY6EUI.js} +41 -4
  20. package/dist/chunk-SHCY6EUI.js.map +1 -0
  21. package/dist/{chunk-Z6URZI2W.js → chunk-TMYDZFN2.js} +6 -6
  22. package/dist/{chunk-Z6URZI2W.js.map → chunk-TMYDZFN2.js.map} +1 -1
  23. package/dist/{chunk-R6X57YZA.js → chunk-W6YGCNAY.js} +20 -12
  24. package/dist/chunk-W6YGCNAY.js.map +1 -0
  25. package/dist/{chunk-SG67QMLI.js → chunk-YPOH6ZEV.js} +6 -6
  26. package/dist/{chunk-SG67QMLI.js.map → chunk-YPOH6ZEV.js.map} +1 -1
  27. package/dist/cli/index.js +26 -26
  28. package/dist/connectors/index.js +1 -1
  29. package/dist/{ensure-sources-NLJJ6EDJ.js → ensure-sources-P5FKSI65.js} +4 -4
  30. package/dist/{ensure-sources-NLJJ6EDJ.js.map → ensure-sources-P5FKSI65.js.map} +1 -1
  31. package/dist/factory-assets/connectors/box.js +1 -1
  32. package/dist/factory-assets/connectors/deploy.js +1 -1
  33. package/dist/factory-assets/connectors/devserver.js +1 -1
  34. package/dist/factory-assets/connectors/flow/adapter.js +1 -1
  35. package/dist/factory-assets/connectors/flow/index.d.ts +1 -0
  36. package/dist/factory-assets/connectors/flow/index.d.ts.map +1 -1
  37. package/dist/factory-assets/connectors/flow/orchestrator-turn.d.ts +67 -0
  38. package/dist/factory-assets/connectors/flow/orchestrator-turn.d.ts.map +1 -0
  39. package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
  40. package/dist/factory-assets/connectors/flow/run-flow.js +2 -2
  41. package/dist/factory-assets/connectors/flow.js +1 -1
  42. package/dist/factory-assets/connectors/git.js +1 -1
  43. package/dist/factory-assets/connectors/gmail.js +1 -1
  44. package/dist/factory-assets/connectors/googledrive.js +1 -1
  45. package/dist/factory-assets/connectors/local.js +1 -1
  46. package/dist/factory-assets/connectors/mattermost.js +1 -1
  47. package/dist/factory-assets/connectors/memory.js +1 -1
  48. package/dist/factory-assets/connectors/minio.js +1 -1
  49. package/dist/factory-assets/connectors/postgres.js +1 -1
  50. package/dist/factory-assets/connectors/s3.js +1 -1
  51. package/dist/factory-assets/connectors/sharepoint.js +1 -1
  52. package/dist/factory-assets/connectors/sqlite.js +1 -1
  53. package/dist/factory-assets/connectors/static-server.js +1 -1
  54. package/dist/factory-assets/connectors/tunnel.js +1 -1
  55. package/dist/factory-assets/connectors/webdav.js +1 -1
  56. package/dist/factory-assets/connectors/xstate-store.js +1 -1
  57. package/dist/factory-assets/connectors/xstate.js +1 -1
  58. package/dist/{helpers-ZGTNTGMV.js → helpers-22HKRUKL.js} +4 -4
  59. package/dist/{helpers-ZGTNTGMV.js.map → helpers-22HKRUKL.js.map} +1 -1
  60. package/dist/{library-publish-457SD4QQ.js → library-publish-76BDM7MG.js} +6 -6
  61. package/dist/{library-publish-457SD4QQ.js.map → library-publish-76BDM7MG.js.map} +1 -1
  62. package/dist/{open-library-RA6VLD4L.js → open-library-ZOKLO2XK.js} +5 -5
  63. package/dist/{open-library-RA6VLD4L.js.map → open-library-ZOKLO2XK.js.map} +1 -1
  64. package/dist/{project-TXHKK7NR.js → project-PNQHHRJ5.js} +5 -5
  65. package/dist/{project-TXHKK7NR.js.map → project-PNQHHRJ5.js.map} +1 -1
  66. package/dist/runner/index.js +4 -4
  67. package/dist/runner/src/serve.d.ts.map +1 -1
  68. package/dist/sdk/asset-manager.js +1 -1
  69. package/dist/sdk/index.js +4 -4
  70. package/dist/sdk/runner.js +4 -4
  71. package/dist/sdk/store.js +1 -1
  72. package/dist/{source-IFIP5TXM.js → source-MFQ27MXE.js} +6 -6
  73. package/dist/{source-IFIP5TXM.js.map → source-MFQ27MXE.js.map} +1 -1
  74. package/dist/{source-manifest-publish-43KI3KHL.js → source-manifest-publish-2YYS3LX3.js} +7 -7
  75. package/dist/{source-manifest-publish-43KI3KHL.js.map → source-manifest-publish-2YYS3LX3.js.map} +1 -1
  76. package/dist/store/index.js +1 -1
  77. package/dist/tui/index.js +4 -4
  78. package/dist/types/src/events.d.ts +43 -1
  79. package/dist/types/src/events.d.ts.map +1 -1
  80. package/dist/types/src/index.d.ts +1 -1
  81. package/dist/types/src/index.d.ts.map +1 -1
  82. package/dist/workspace-plugin/index.js +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-R6OLT7E4.js.map +0 -1
  85. package/dist/chunk-R6X57YZA.js.map +0 -1
  86. package/dist/chunk-XDIVJ7G6.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 3.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#554](https://github.com/skaile-ai/workspaces/pull/554) [`d98cd9d`](https://github.com/skaile-ai/workspaces/commit/d98cd9d3dfece1545c2b93ee1ed372dcf4cc8162) Thanks [@peteralbert](https://github.com/peteralbert)! - Emit the orchestrator prompt as a `flow_prompt` event so hosts can show what the
8
+ agent was actually asked. Every flow turn rebuilds the full
9
+ `# Flow Execution Context` prompt and hands it to the driver; nothing about it
10
+ ever reached the event stream, so a host consuming the stream saw the agent
11
+ replying to input it could not read.
12
+
13
+ A new persistent `FlowPromptEvent` (`type: "flow_prompt"`) joins the `AgentEvent`
14
+ union carrying the verbatim `prompt`, the run/flow identity (`runId`, `flowId`,
15
+ `flowName`), the stimulus kind plus its telemetry label, and the `nodeId` for the
16
+ three node-scoped stimuli. The prompt goes out unredacted and untruncated — it is
17
+ the same string the driver receives, not a re-render — because a host that
18
+ rendered anything else would be showing input the agent never saw. The stimulus
19
+ payload (user text, node input) is not repeated on the event: it is already
20
+ inside `prompt`.
21
+
22
+ All four orchestrator-turn call sites now route through one
23
+ `driveOrchestratorTurn` helper that builds the prompt, emits the event, then
24
+ awaits the turn — the stimulus bus and the inline sub-flow runner, in the
25
+ runner's `serve` (hosted sessions) and in `runFlow`/`resumeFlow` (CLI runs). The
26
+ helper lives with the flow connector rather than the runner because the CLI entry
27
+ is one of its callers and `factory-assets` must not statically import `runner`.
28
+ An inline sub-flow turn announces the **child** flow's `flowId`/`flowName`. Turns
29
+ that never happen (gated off, or a run already done/failed/cancelled) announce
30
+ nothing, and subprompt nodes — which run on their own isolated driver — are
31
+ unchanged.
32
+
33
+ Purely additive to the event union, but the event is non-transient: hosts start
34
+ persisting a multi-KB row per orchestrator turn without opting in. See
35
+ `MIGRATION.md` for what that means for renderers and storage.
36
+
3
37
  ## 3.4.2
4
38
 
5
39
  ### Patch Changes
@@ -65,7 +65,7 @@ async function libraryAssets() {
65
65
  const domains = [];
66
66
  try {
67
67
  const [{ openLibraryManager }, { skaileHomeDir }, { getGlobalCacheDir }] = await Promise.all([
68
- import('./open-library-RA6VLD4L.js'),
68
+ import('./open-library-ZOKLO2XK.js'),
69
69
  import('./library/index.js'),
70
70
  import('./core/index.js')
71
71
  ]);
@@ -98,7 +98,7 @@ async function libraryAssets() {
98
98
  async function storeAssets(projectDir) {
99
99
  const notes = [];
100
100
  try {
101
- const { resolveCatalogSource } = await import('./open-library-RA6VLD4L.js');
101
+ const { resolveCatalogSource } = await import('./open-library-ZOKLO2XK.js');
102
102
  const { source, close } = await resolveCatalogSource({ projectDir });
103
103
  try {
104
104
  const assets = await source.listAssets();
@@ -202,5 +202,5 @@ function dedupeBySlug(domains) {
202
202
  }
203
203
 
204
204
  export { gatherAssetFeeds };
205
- //# sourceMappingURL=asset-feeds-JJTN5PGH.js.map
206
- //# sourceMappingURL=asset-feeds-JJTN5PGH.js.map
205
+ //# sourceMappingURL=asset-feeds-ATPO3XUG.js.map
206
+ //# sourceMappingURL=asset-feeds-ATPO3XUG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/asset-feeds.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAqFA,SAAS,QAAQ,CAAA,EAAmB;AAClC,EAAA,OAAO,CAAA,CAAE,KAAA,CAAW,IAAA,CAAA,GAAG,CAAA,CAAE,KAAK,GAAG,CAAA;AACnC;AAGA,eAAe,cAAc,IAAA,EAAmC;AAC9D,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,WAAA,MAAiB,EAAE,IAAA,EAAM,QAAA,EAAU,MAAK,IAAK,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC1D,IAAA,IAAI,SAAS,kBAA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,SAAS,aAAa,OAAA,EAA2C;AAC/D,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,MAAuB,EAAC;AAC9B,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,IAAI,CAAA,EAAG;AACtB,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,IAAI,CAAA;AACf,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT","file":"asset-feeds-JJTN5PGH.js","sourcesContent":["/**\n * asset-feeds.ts — gather installable assets from every feed the manage TUI\n * surfaces.\n *\n * Four feeds, normalized into `CatalogEntry`:\n * - **Project sources** — `skaile.yaml` `sources:` entries (scanned via\n * `AssetManager.search()`; the new `sources:` field is merged into the\n * legacy repositories map in `AssetManager.loadConfig`).\n * - **Local libraries** — user authoring places from `LocalIndex` (filesystem\n * scan of each library's `path`).\n * - **Factory assets** — the bundled first-party `factory-assets` tree\n * (`factoryAssetRoots()`), scanned from disk. Always present; no network.\n * - **Remote store** — the configured catalog source when `catalog.url` is\n * not `local`. Failures are non-fatal — they surface as notes.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n type AssetKind,\n type CatalogDomain,\n type CatalogEntry,\n factoryAssetRoots,\n parseFrontmatter,\n scanRepo,\n walkDir,\n} from \"@skaile/workspaces/core\";\nimport {\n assignDomain,\n buildDomainIndex,\n DOMAIN_MD_FILENAME,\n type DomainMd,\n parseDomainMd,\n} from \"@skaile/workspaces/discovery\";\n\n/** One non-fatal note returned to the caller for surfacing in the UI. */\nexport interface FeedNote {\n feed: \"sources\" | \"libraries\" | \"store\" | \"factory\";\n message: string;\n}\n\n/**\n * Which feed an asset came from. This is the top-level grouping axis in the\n * manage TUI (\"where is this skill coming from?\") and is intentionally distinct\n * from `publisher` (asset-intrinsic identity): the same publisher can legitimately\n * appear under more than one origin (e.g. a github repo you added as a `source`\n * that is also listed in the remote `store`).\n */\nexport type AssetOrigin = \"source\" | \"library\" | \"factory\" | \"store\";\n\n/** A catalog entry tagged with the feed it was gathered from. */\nexport interface OriginEntry {\n origin: AssetOrigin;\n entry: CatalogEntry;\n /**\n * Second-level grouping label for the manage tree. Defaults (when unset) to the\n * entry's `publisher`; the source feed sets it to the source's short repo name\n * so the Sources band groups by source — \"which repo did this come from\" — not\n * by the asset-intrinsic publisher.\n */\n group?: string;\n}\n\nexport interface AssetFeedResult {\n entries: OriginEntry[];\n /**\n * Display-only domain metadata, keyed (by the consumer) on `slug`. Populated\n * from the store's `catalog.listDomains` when the connected catalog source\n * exposes it; empty otherwise. The manage TUI joins `entry.domainSlug` → a\n * domain for grouping headers, descriptions, and relation badges.\n */\n domains: CatalogDomain[];\n notes: FeedNote[];\n}\n\n// ── Domain stamping (on-disk feeds) ──────────────────────────────────────────\n//\n// `scanRepo` (the source / library / factory scan path) does not read the\n// `DOMAIN.md` sidecars, so its entries arrive with no `domainSlug` and render\n// flat under their publisher band. We re-derive the grouping here from the\n// root's `DOMAIN.md` files (the same sidecars the remote store computes\n// server-side), and fall back to the repo/source name for any entry no domain\n// claims so it still groups instead of landing in the synthetic \"no domain\" pile.\n\n/** Repo-relative POSIX path (DOMAIN.md slugs are matched whole-segment, `/`-joined). */\nfunction toPosix(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/** Parse every `DOMAIN.md` sidecar under `root` into a {@link DomainMd}. */\nasync function loadDomainMds(root: string): Promise<DomainMd[]> {\n const out: DomainMd[] = [];\n for await (const { path: filePath, name } of walkDir(root)) {\n if (name !== DOMAIN_MD_FILENAME) continue;\n try {\n const { data } = parseFrontmatter(readFileSync(filePath, \"utf8\"));\n out.push(parseDomainMd(toPosix(path.relative(root, filePath)), data));\n } catch {}\n }\n return out;\n}\n\n/**\n * Stamp `domainSlug` onto every entry scanned from `root` using the root's\n * `DOMAIN.md` sidecars. Returns the `CatalogDomain` registry for the real\n * domains, plus a synthetic fallback domain when any entry used the fallback.\n * Mutates `entries` in place (sets `entry.domainSlug`).\n *\n * `synthesizeFallback` (default true): entries no domain claims fall back to\n * `fallbackSlug` (the repo/source name). Pass `false` when the caller already\n * groups these entries one level up (e.g. the source feed groups by source\n * node) — unmatched entries then get no domain (`\"\"`) and hang directly under\n * that parent, instead of nesting under a same-named fallback domain.\n */\nasync function stampDomains(\n root: string,\n fallbackSlug: string,\n entries: CatalogEntry[],\n synthesizeFallback = true,\n): Promise<CatalogDomain[]> {\n const domainMds = await loadDomainMds(root);\n const assignables = entries.map((entry) => ({\n entry,\n ref: `${entry.kind}:${entry.name}`,\n relativePath: toPosix(path.relative(root, entry.source)),\n }));\n\n let usedFallback = false;\n for (const a of assignables) {\n const slug = assignDomain(a.relativePath, domainMds);\n if (slug) a.entry.domainSlug = slug;\n else if (synthesizeFallback) {\n a.entry.domainSlug = fallbackSlug;\n usedFallback = true;\n } else a.entry.domainSlug = \"\";\n }\n\n const { index } = buildDomainIndex(assignables, domainMds);\n const catalog: CatalogDomain[] = Object.values(index).map((d) => ({\n slug: d.slug,\n title: d.title,\n ...(d.description ? { description: d.description } : {}),\n ...(d.relation ? { relation: d.relation } : {}),\n ...(d.order !== undefined ? { order: d.order } : {}),\n ...(d.recommended[0] ? { recommendedRef: d.recommended[0] } : {}),\n }));\n if (usedFallback) catalog.push({ slug: fallbackSlug, title: fallbackSlug });\n return catalog;\n}\n\n/**\n * Pull assets from local libraries (the authoring places under\n * `~/.skaile/libraries/<name>/`, not the `~/.skaile/cache/sources/` cache). Each\n * library's `path` is scanned with `scanRepo` and grouped under the bare library\n * name (`group: <name>`) so the manage TUI shows a clean `<name>` band — no\n * `library:` prefix and no redundant same-named fallback domain (mirrors the\n * source feed).\n */\nasync function libraryAssets(): Promise<{\n entries: OriginEntry[];\n domains: CatalogDomain[];\n notes: FeedNote[];\n}> {\n const notes: FeedNote[] = [];\n const domains: CatalogDomain[] = [];\n try {\n const [{ openLibraryManager }, { skaileHomeDir }, { getGlobalCacheDir }] = await Promise.all([\n import(\"./open-library.ts\"),\n import(\"@skaile/workspaces/library\"),\n import(\"@skaile/workspaces/core\"),\n ]);\n const { manager, close } = await openLibraryManager();\n try {\n // Authoring libraries are the rows that are NOT source clones. index.db\n // rows predating the cache migration still carry the legacy\n // ~/.skaile/sources path, so exclude both roots.\n const newRoot = getGlobalCacheDir();\n const legacyRoot = path.join(skaileHomeDir(), \"sources\");\n const libs = (await manager.listLibraries()).filter(\n (l) => !l.path.startsWith(newRoot) && !l.path.startsWith(legacyRoot),\n );\n const entries: OriginEntry[] = [];\n for (const lib of libs) {\n if (!existsSync(lib.path)) continue;\n // Scan + group under the bare library name. `synthesizeFallback: false`\n // (as the source feed does) keeps domainless assets directly under the\n // library band instead of a redundant same-named fallback domain.\n const libEntries = [...(await scanRepo(lib.path, lib.name))];\n domains.push(...(await stampDomains(lib.path, lib.name, libEntries, false)));\n for (const entry of libEntries) entries.push({ origin: \"library\", entry, group: lib.name });\n }\n return { entries, domains, notes };\n } finally {\n close();\n }\n } catch (err) {\n notes.push({\n feed: \"libraries\",\n message: err instanceof Error ? err.message : String(err),\n });\n return { entries: [], domains, notes };\n }\n}\n\n/**\n * Pull a (best-effort) snapshot of the connected remote store catalog.\n *\n * - Returns no entries when the resolved catalog is local-only or the host\n * is unreachable (the failure becomes a note, not an exception).\n * - Maps `CatalogAsset` → `CatalogEntry`, carrying `publisher`, `repo`, and\n * `category` straight through and using `source = \"store://<id>\"`; per-file\n * `source` paths are not available for remote assets so the canonical ref is\n * a stable placeholder.\n */\nasync function storeAssets(projectDir: string): Promise<{\n entries: CatalogEntry[];\n domains: CatalogDomain[];\n notes: FeedNote[];\n}> {\n const notes: FeedNote[] = [];\n try {\n const { resolveCatalogSource } = await import(\"./open-library.ts\");\n const { source, close } = await resolveCatalogSource({ projectDir });\n try {\n const assets = await source.listAssets();\n const entries: CatalogEntry[] = assets.map((a) => ({\n name: a.name,\n kind: (a.kind as AssetKind) ?? \"skill\",\n description: a.description ?? \"\",\n source: `store://${a.id}`,\n publisher: a.publisher,\n repo: a.repo,\n domainSlug: a.domainSlug,\n category: a.category,\n version: a.version,\n requires: [],\n dependencies: [],\n }));\n // Domains are optional on the catalog source — only the store backend\n // (post Part 4 `catalog.listDomains`) exposes them. Duck-type the call so\n // older sources and the local catalog degrade to no domains, not an error.\n const domains = await loadDomains(source);\n return { entries, domains, notes };\n } finally {\n close();\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // Local-only catalog throws a recognizable message — silence it; absence\n // is the user's choice, not an error.\n if (!/local/i.test(msg)) {\n notes.push({ feed: \"store\", message: msg });\n }\n return { entries: [], domains: [], notes };\n }\n}\n\n/** Optional `listDomains` capability — returns `[]` when the source lacks it. */\nasync function loadDomains(source: unknown): Promise<CatalogDomain[]> {\n const fn = (source as { listDomains?: () => Promise<CatalogDomain[]> }).listDomains;\n if (typeof fn !== \"function\") return [];\n const domains = await fn.call(source);\n return Array.isArray(domains) ? domains : [];\n}\n\n/** The slice of `AssetManager` the source feed needs (kept narrow for tests). */\ninterface AssetManagerLike {\n search: () => Promise<CatalogEntry[]>;\n searchRepoRoots: () => { repoName: string; root: string }[];\n}\n\n/**\n * Project-source feed: leans on `AssetManager.search()`, which now merges\n * `skaile.yaml`'s `sources:` field into the repositories map, then stamps\n * `DOMAIN.md`-derived domain grouping onto the scanned entries via\n * `searchRepoRoots()`.\n */\nasync function sourceAssets(\n am: AssetManagerLike,\n): Promise<{ entries: OriginEntry[]; domains: CatalogDomain[] }> {\n // The bundled factory tree is injected into the repositories map as an implicit\n // source, so `am.search()` returns it too. It has its own `factory` origin band,\n // so drop it here — otherwise the same first-party skills list twice under Sources.\n const factoryPrefixes = factoryAssetRoots().map((r) => (r.endsWith(path.sep) ? r : r + path.sep));\n const isFactoryPath = (p: string) =>\n factoryPrefixes.some((fp) => p === fp.slice(0, -1) || p.startsWith(fp));\n\n const all = (await am.search()).filter((e) => !isFactoryPath(e.source));\n const entries: OriginEntry[] = [];\n const domains: CatalogDomain[] = [];\n // Group each source's entries under the source node (its short repo name), not\n // the publisher: under Sources the navigational question is \"which repo did\n // this come from\". Each entry's `source` (absolute manifest path) lives under\n // exactly one declared root, so group + stamp by prefix. The cache slug is\n // URL-keyed `github.com/<org>/<repo>` — take the trailing segment.\n for (const { repoName, root } of am.searchRepoRoots()) {\n if (isFactoryPath(root)) continue;\n const prefix = root.endsWith(path.sep) ? root : root + path.sep;\n const owned = all.filter((e) => e.source === root || e.source.startsWith(prefix));\n if (owned.length === 0) continue;\n const sourceName = repoName.split(\"/\").pop() || repoName;\n // No synthetic fallback domain — the source node already groups these, so a\n // same-named fallback would just nest the source under itself.\n domains.push(...(await stampDomains(root, sourceName, owned, false)));\n for (const entry of owned) entries.push({ origin: \"source\", entry, group: sourceName });\n }\n return { entries, domains };\n}\n\n/**\n * Factory-asset feed: scan the bundled first-party `factory-assets` tree(s)\n * resolved by `factoryAssetRoots()` (the `SKAILE_FACTORY_ASSETS_DIR` override\n * layer ahead of the bundled tree). Local disk only, no network — the entries are\n * the built-in skills / connectors / bundles that ship with `@skaile/workspaces`.\n * `factoryAssetRoots()` already dedupes, so the env override pointing at the\n * bundled dir collapses to one root.\n */\nasync function factoryAssets(): Promise<{\n entries: CatalogEntry[];\n domains: CatalogDomain[];\n notes: FeedNote[];\n}> {\n const notes: FeedNote[] = [];\n const domains: CatalogDomain[] = [];\n try {\n const entries: CatalogEntry[] = [];\n for (const root of factoryAssetRoots()) {\n const rootEntries = [...(await scanRepo(root, \"skaile-factory\"))];\n domains.push(...(await stampDomains(root, \"skaile-factory\", rootEntries)));\n entries.push(...rootEntries);\n }\n return { entries, domains, notes };\n } catch (err) {\n notes.push({\n feed: \"factory\",\n message: err instanceof Error ? err.message : String(err),\n });\n return { entries: [], domains, notes };\n }\n}\n\n/** Tag a flat entry list with a single origin. */\nfunction tag(origin: AssetOrigin, entries: CatalogEntry[]): OriginEntry[] {\n return entries.map((entry) => ({ origin, entry }));\n}\n\n/**\n * Run all feeds and return a single normalized result.\n *\n * Feeds run in parallel where possible — the store fetch is the slow one\n * (one HTTP call) and is fired alongside the local library walk. The factory\n * scan is local disk only, so it runs inline.\n */\nexport async function gatherAssetFeeds(\n am: AssetManagerLike,\n projectDir: string,\n): Promise<AssetFeedResult> {\n const [libs, store] = await Promise.all([libraryAssets(), storeAssets(projectDir)]);\n const factory = await factoryAssets();\n const src = await sourceAssets(am);\n return {\n entries: [\n ...src.entries,\n ...libs.entries,\n ...tag(\"factory\", factory.entries),\n ...tag(\"store\", store.entries),\n ],\n // Store domains first (server-curated), then the on-disk feeds; dedupe by\n // slug, first-wins, so a store-served domain shadows a same-slug local one.\n domains: dedupeBySlug([...store.domains, ...src.domains, ...libs.domains, ...factory.domains]),\n notes: [...libs.notes, ...store.notes, ...factory.notes],\n };\n}\n\n/** First-wins dedupe of a domain list by `slug`. */\nfunction dedupeBySlug(domains: CatalogDomain[]): CatalogDomain[] {\n const seen = new Set<string>();\n const out: CatalogDomain[] = [];\n for (const d of domains) {\n if (seen.has(d.slug)) continue;\n seen.add(d.slug);\n out.push(d);\n }\n return out;\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/asset-feeds.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAqFA,SAAS,QAAQ,CAAA,EAAmB;AAClC,EAAA,OAAO,CAAA,CAAE,KAAA,CAAW,IAAA,CAAA,GAAG,CAAA,CAAE,KAAK,GAAG,CAAA;AACnC;AAGA,eAAe,cAAc,IAAA,EAAmC;AAC9D,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,WAAA,MAAiB,EAAE,IAAA,EAAM,QAAA,EAAU,MAAK,IAAK,OAAA,CAAQ,IAAI,CAAA,EAAG;AAC1D,IAAA,IAAI,SAAS,kBAAA,EAAoB;AACjC,IAAA,IAAI;AACF,MAAA,MAAM,EAAE,IAAA,EAAK,GAAI,iBAAiB,YAAA,CAAa,QAAA,EAAU,MAAM,C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B,EAAA,KAAA,MAAW,KAAK,OAAA,EAAS;AACvB,IAAA,IAAI,IAAA,CAAK,GAAA,CAAI,CAAA,CAAE,IAAI,CAAA,EAAG;AACtB,IAAA,IAAA,CAAK,GAAA,CAAI,EAAE,IAAI,CAAA;AACf,IAAA,GAAA,CAAI,KAAK,CAAC,CAAA;AAAA,EACZ;AACA,EAAA,OAAO,GAAA;AACT","file":"asset-feeds-ATPO3XUG.js","sourcesContent":["/**\n * asset-feeds.ts — gather installable assets from every feed the manage TUI\n * surfaces.\n *\n * Four feeds, normalized into `CatalogEntry`:\n * - **Project sources** — `skaile.yaml` `sources:` entries (scanned via\n * `AssetManager.search()`; the new `sources:` field is merged into the\n * legacy repositories map in `AssetManager.loadConfig`).\n * - **Local libraries** — user authoring places from `LocalIndex` (filesystem\n * scan of each library's `path`).\n * - **Factory assets** — the bundled first-party `factory-assets` tree\n * (`factoryAssetRoots()`), scanned from disk. Always present; no network.\n * - **Remote store** — the configured catalog source when `catalog.url` is\n * not `local`. Failures are non-fatal — they surface as notes.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport {\n type AssetKind,\n type CatalogDomain,\n type CatalogEntry,\n factoryAssetRoots,\n parseFrontmatter,\n scanRepo,\n walkDir,\n} from \"@skaile/workspaces/core\";\nimport {\n assignDomain,\n buildDomainIndex,\n DOMAIN_MD_FILENAME,\n type DomainMd,\n parseDomainMd,\n} from \"@skaile/workspaces/discovery\";\n\n/** One non-fatal note returned to the caller for surfacing in the UI. */\nexport interface FeedNote {\n feed: \"sources\" | \"libraries\" | \"store\" | \"factory\";\n message: string;\n}\n\n/**\n * Which feed an asset came from. This is the top-level grouping axis in the\n * manage TUI (\"where is this skill coming from?\") and is intentionally distinct\n * from `publisher` (asset-intrinsic identity): the same publisher can legitimately\n * appear under more than one origin (e.g. a github repo you added as a `source`\n * that is also listed in the remote `store`).\n */\nexport type AssetOrigin = \"source\" | \"library\" | \"factory\" | \"store\";\n\n/** A catalog entry tagged with the feed it was gathered from. */\nexport interface OriginEntry {\n origin: AssetOrigin;\n entry: CatalogEntry;\n /**\n * Second-level grouping label for the manage tree. Defaults (when unset) to the\n * entry's `publisher`; the source feed sets it to the source's short repo name\n * so the Sources band groups by source — \"which repo did this come from\" — not\n * by the asset-intrinsic publisher.\n */\n group?: string;\n}\n\nexport interface AssetFeedResult {\n entries: OriginEntry[];\n /**\n * Display-only domain metadata, keyed (by the consumer) on `slug`. Populated\n * from the store's `catalog.listDomains` when the connected catalog source\n * exposes it; empty otherwise. The manage TUI joins `entry.domainSlug` → a\n * domain for grouping headers, descriptions, and relation badges.\n */\n domains: CatalogDomain[];\n notes: FeedNote[];\n}\n\n// ── Domain stamping (on-disk feeds) ──────────────────────────────────────────\n//\n// `scanRepo` (the source / library / factory scan path) does not read the\n// `DOMAIN.md` sidecars, so its entries arrive with no `domainSlug` and render\n// flat under their publisher band. We re-derive the grouping here from the\n// root's `DOMAIN.md` files (the same sidecars the remote store computes\n// server-side), and fall back to the repo/source name for any entry no domain\n// claims so it still groups instead of landing in the synthetic \"no domain\" pile.\n\n/** Repo-relative POSIX path (DOMAIN.md slugs are matched whole-segment, `/`-joined). */\nfunction toPosix(p: string): string {\n return p.split(path.sep).join(\"/\");\n}\n\n/** Parse every `DOMAIN.md` sidecar under `root` into a {@link DomainMd}. */\nasync function loadDomainMds(root: string): Promise<DomainMd[]> {\n const out: DomainMd[] = [];\n for await (const { path: filePath, name } of walkDir(root)) {\n if (name !== DOMAIN_MD_FILENAME) continue;\n try {\n const { data } = parseFrontmatter(readFileSync(filePath, \"utf8\"));\n out.push(parseDomainMd(toPosix(path.relative(root, filePath)), data));\n } catch {}\n }\n return out;\n}\n\n/**\n * Stamp `domainSlug` onto every entry scanned from `root` using the root's\n * `DOMAIN.md` sidecars. Returns the `CatalogDomain` registry for the real\n * domains, plus a synthetic fallback domain when any entry used the fallback.\n * Mutates `entries` in place (sets `entry.domainSlug`).\n *\n * `synthesizeFallback` (default true): entries no domain claims fall back to\n * `fallbackSlug` (the repo/source name). Pass `false` when the caller already\n * groups these entries one level up (e.g. the source feed groups by source\n * node) — unmatched entries then get no domain (`\"\"`) and hang directly under\n * that parent, instead of nesting under a same-named fallback domain.\n */\nasync function stampDomains(\n root: string,\n fallbackSlug: string,\n entries: CatalogEntry[],\n synthesizeFallback = true,\n): Promise<CatalogDomain[]> {\n const domainMds = await loadDomainMds(root);\n const assignables = entries.map((entry) => ({\n entry,\n ref: `${entry.kind}:${entry.name}`,\n relativePath: toPosix(path.relative(root, entry.source)),\n }));\n\n let usedFallback = false;\n for (const a of assignables) {\n const slug = assignDomain(a.relativePath, domainMds);\n if (slug) a.entry.domainSlug = slug;\n else if (synthesizeFallback) {\n a.entry.domainSlug = fallbackSlug;\n usedFallback = true;\n } else a.entry.domainSlug = \"\";\n }\n\n const { index } = buildDomainIndex(assignables, domainMds);\n const catalog: CatalogDomain[] = Object.values(index).map((d) => ({\n slug: d.slug,\n title: d.title,\n ...(d.description ? { description: d.description } : {}),\n ...(d.relation ? { relation: d.relation } : {}),\n ...(d.order !== undefined ? { order: d.order } : {}),\n ...(d.recommended[0] ? { recommendedRef: d.recommended[0] } : {}),\n }));\n if (usedFallback) catalog.push({ slug: fallbackSlug, title: fallbackSlug });\n return catalog;\n}\n\n/**\n * Pull assets from local libraries (the authoring places under\n * `~/.skaile/libraries/<name>/`, not the `~/.skaile/cache/sources/` cache). Each\n * library's `path` is scanned with `scanRepo` and grouped under the bare library\n * name (`group: <name>`) so the manage TUI shows a clean `<name>` band — no\n * `library:` prefix and no redundant same-named fallback domain (mirrors the\n * source feed).\n */\nasync function libraryAssets(): Promise<{\n entries: OriginEntry[];\n domains: CatalogDomain[];\n notes: FeedNote[];\n}> {\n const notes: FeedNote[] = [];\n const domains: CatalogDomain[] = [];\n try {\n const [{ openLibraryManager }, { skaileHomeDir }, { getGlobalCacheDir }] = await Promise.all([\n import(\"./open-library.ts\"),\n import(\"@skaile/workspaces/library\"),\n import(\"@skaile/workspaces/core\"),\n ]);\n const { manager, close } = await openLibraryManager();\n try {\n // Authoring libraries are the rows that are NOT source clones. index.db\n // rows predating the cache migration still carry the legacy\n // ~/.skaile/sources path, so exclude both roots.\n const newRoot = getGlobalCacheDir();\n const legacyRoot = path.join(skaileHomeDir(), \"sources\");\n const libs = (await manager.listLibraries()).filter(\n (l) => !l.path.startsWith(newRoot) && !l.path.startsWith(legacyRoot),\n );\n const entries: OriginEntry[] = [];\n for (const lib of libs) {\n if (!existsSync(lib.path)) continue;\n // Scan + group under the bare library name. `synthesizeFallback: false`\n // (as the source feed does) keeps domainless assets directly under the\n // library band instead of a redundant same-named fallback domain.\n const libEntries = [...(await scanRepo(lib.path, lib.name))];\n domains.push(...(await stampDomains(lib.path, lib.name, libEntries, false)));\n for (const entry of libEntries) entries.push({ origin: \"library\", entry, group: lib.name });\n }\n return { entries, domains, notes };\n } finally {\n close();\n }\n } catch (err) {\n notes.push({\n feed: \"libraries\",\n message: err instanceof Error ? err.message : String(err),\n });\n return { entries: [], domains, notes };\n }\n}\n\n/**\n * Pull a (best-effort) snapshot of the connected remote store catalog.\n *\n * - Returns no entries when the resolved catalog is local-only or the host\n * is unreachable (the failure becomes a note, not an exception).\n * - Maps `CatalogAsset` → `CatalogEntry`, carrying `publisher`, `repo`, and\n * `category` straight through and using `source = \"store://<id>\"`; per-file\n * `source` paths are not available for remote assets so the canonical ref is\n * a stable placeholder.\n */\nasync function storeAssets(projectDir: string): Promise<{\n entries: CatalogEntry[];\n domains: CatalogDomain[];\n notes: FeedNote[];\n}> {\n const notes: FeedNote[] = [];\n try {\n const { resolveCatalogSource } = await import(\"./open-library.ts\");\n const { source, close } = await resolveCatalogSource({ projectDir });\n try {\n const assets = await source.listAssets();\n const entries: CatalogEntry[] = assets.map((a) => ({\n name: a.name,\n kind: (a.kind as AssetKind) ?? \"skill\",\n description: a.description ?? \"\",\n source: `store://${a.id}`,\n publisher: a.publisher,\n repo: a.repo,\n domainSlug: a.domainSlug,\n category: a.category,\n version: a.version,\n requires: [],\n dependencies: [],\n }));\n // Domains are optional on the catalog source — only the store backend\n // (post Part 4 `catalog.listDomains`) exposes them. Duck-type the call so\n // older sources and the local catalog degrade to no domains, not an error.\n const domains = await loadDomains(source);\n return { entries, domains, notes };\n } finally {\n close();\n }\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n // Local-only catalog throws a recognizable message — silence it; absence\n // is the user's choice, not an error.\n if (!/local/i.test(msg)) {\n notes.push({ feed: \"store\", message: msg });\n }\n return { entries: [], domains: [], notes };\n }\n}\n\n/** Optional `listDomains` capability — returns `[]` when the source lacks it. */\nasync function loadDomains(source: unknown): Promise<CatalogDomain[]> {\n const fn = (source as { listDomains?: () => Promise<CatalogDomain[]> }).listDomains;\n if (typeof fn !== \"function\") return [];\n const domains = await fn.call(source);\n return Array.isArray(domains) ? domains : [];\n}\n\n/** The slice of `AssetManager` the source feed needs (kept narrow for tests). */\ninterface AssetManagerLike {\n search: () => Promise<CatalogEntry[]>;\n searchRepoRoots: () => { repoName: string; root: string }[];\n}\n\n/**\n * Project-source feed: leans on `AssetManager.search()`, which now merges\n * `skaile.yaml`'s `sources:` field into the repositories map, then stamps\n * `DOMAIN.md`-derived domain grouping onto the scanned entries via\n * `searchRepoRoots()`.\n */\nasync function sourceAssets(\n am: AssetManagerLike,\n): Promise<{ entries: OriginEntry[]; domains: CatalogDomain[] }> {\n // The bundled factory tree is injected into the repositories map as an implicit\n // source, so `am.search()` returns it too. It has its own `factory` origin band,\n // so drop it here — otherwise the same first-party skills list twice under Sources.\n const factoryPrefixes = factoryAssetRoots().map((r) => (r.endsWith(path.sep) ? r : r + path.sep));\n const isFactoryPath = (p: string) =>\n factoryPrefixes.some((fp) => p === fp.slice(0, -1) || p.startsWith(fp));\n\n const all = (await am.search()).filter((e) => !isFactoryPath(e.source));\n const entries: OriginEntry[] = [];\n const domains: CatalogDomain[] = [];\n // Group each source's entries under the source node (its short repo name), not\n // the publisher: under Sources the navigational question is \"which repo did\n // this come from\". Each entry's `source` (absolute manifest path) lives under\n // exactly one declared root, so group + stamp by prefix. The cache slug is\n // URL-keyed `github.com/<org>/<repo>` — take the trailing segment.\n for (const { repoName, root } of am.searchRepoRoots()) {\n if (isFactoryPath(root)) continue;\n const prefix = root.endsWith(path.sep) ? root : root + path.sep;\n const owned = all.filter((e) => e.source === root || e.source.startsWith(prefix));\n if (owned.length === 0) continue;\n const sourceName = repoName.split(\"/\").pop() || repoName;\n // No synthetic fallback domain — the source node already groups these, so a\n // same-named fallback would just nest the source under itself.\n domains.push(...(await stampDomains(root, sourceName, owned, false)));\n for (const entry of owned) entries.push({ origin: \"source\", entry, group: sourceName });\n }\n return { entries, domains };\n}\n\n/**\n * Factory-asset feed: scan the bundled first-party `factory-assets` tree(s)\n * resolved by `factoryAssetRoots()` (the `SKAILE_FACTORY_ASSETS_DIR` override\n * layer ahead of the bundled tree). Local disk only, no network — the entries are\n * the built-in skills / connectors / bundles that ship with `@skaile/workspaces`.\n * `factoryAssetRoots()` already dedupes, so the env override pointing at the\n * bundled dir collapses to one root.\n */\nasync function factoryAssets(): Promise<{\n entries: CatalogEntry[];\n domains: CatalogDomain[];\n notes: FeedNote[];\n}> {\n const notes: FeedNote[] = [];\n const domains: CatalogDomain[] = [];\n try {\n const entries: CatalogEntry[] = [];\n for (const root of factoryAssetRoots()) {\n const rootEntries = [...(await scanRepo(root, \"skaile-factory\"))];\n domains.push(...(await stampDomains(root, \"skaile-factory\", rootEntries)));\n entries.push(...rootEntries);\n }\n return { entries, domains, notes };\n } catch (err) {\n notes.push({\n feed: \"factory\",\n message: err instanceof Error ? err.message : String(err),\n });\n return { entries: [], domains, notes };\n }\n}\n\n/** Tag a flat entry list with a single origin. */\nfunction tag(origin: AssetOrigin, entries: CatalogEntry[]): OriginEntry[] {\n return entries.map((entry) => ({ origin, entry }));\n}\n\n/**\n * Run all feeds and return a single normalized result.\n *\n * Feeds run in parallel where possible — the store fetch is the slow one\n * (one HTTP call) and is fired alongside the local library walk. The factory\n * scan is local disk only, so it runs inline.\n */\nexport async function gatherAssetFeeds(\n am: AssetManagerLike,\n projectDir: string,\n): Promise<AssetFeedResult> {\n const [libs, store] = await Promise.all([libraryAssets(), storeAssets(projectDir)]);\n const factory = await factoryAssets();\n const src = await sourceAssets(am);\n return {\n entries: [\n ...src.entries,\n ...libs.entries,\n ...tag(\"factory\", factory.entries),\n ...tag(\"store\", store.entries),\n ],\n // Store domains first (server-curated), then the on-disk feeds; dedupe by\n // slug, first-wins, so a store-served domain shadows a same-slug local one.\n domains: dedupeBySlug([...store.domains, ...src.domains, ...libs.domains, ...factory.domains]),\n notes: [...libs.notes, ...store.notes, ...factory.notes],\n };\n}\n\n/** First-wins dedupe of a domain list by `slug`. */\nfunction dedupeBySlug(domains: CatalogDomain[]): CatalogDomain[] {\n const seen = new Set<string>();\n const out: CatalogDomain[] = [];\n for (const d of domains) {\n if (seen.has(d.slug)) continue;\n seen.add(d.slug);\n out.push(d);\n }\n return out;\n}\n"]}
@@ -1,4 +1,4 @@
1
- export { AssetManager, FACTORY_SOURCE_URL, MissingManifestError, NON_DEPLOYABLE_KINDS, normalizeRepoUrl, parseCanonicalLockKey, parseRefTolerant, renderMcpServerConfig, softDepName } from '../chunk-JISWIYUA.js';
1
+ export { AssetManager, FACTORY_SOURCE_URL, MissingManifestError, NON_DEPLOYABLE_KINDS, normalizeRepoUrl, parseCanonicalLockKey, parseRefTolerant, renderMcpServerConfig, softDepName } from '../chunk-CEFK3X3Q.js';
2
2
  import '../chunk-OCLCDB7G.js';
3
3
  import '../chunk-PW4SJE3X.js';
4
4
  import '../chunk-UKJMQZV6.js';
@@ -713,5 +713,5 @@ var AgentStore = class _AgentStore {
713
713
  };
714
714
 
715
715
  export { AgentStore, ResourceClient };
716
- //# sourceMappingURL=chunk-KSHCQ777.js.map
717
- //# sourceMappingURL=chunk-KSHCQ777.js.map
716
+ //# sourceMappingURL=chunk-3DNCPQAR.js.map
717
+ //# sourceMappingURL=chunk-3DNCP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Ae,EAAE,IAAA,EAAM,QAAQ,OAAA,EAAS,IAAA,CAAK,gBAAgB,CAAA;AAClE,IAAA,IAAA,CAAK,cAAA,GAAiB,EAAA;AACtB,IAAA,IAAA,CAAK,iBAAA,GAAoB,IAAA;AACzB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EAEQ,cAAA,CAAe,SAAoC,QAAA,EAAyB;AAClF,IAAA,IAAA,CAAK,IAAA,EAAA;AACL,IAAA,IAAA,CAAK,SAAA,GAAY;AAAA,MACf,GAAG,IAAA,CAAK,SAAA;AAAA,MACR;AAAA,QACE,EAAA,EAAI,OAAO,UAAA,EAAW;AAAA,QACtB,KAAK,IAAA,CAAK,IAAA;AAAA,QACV,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAAA,QAClC,SAAA,EAAW,KAAK,QAAA,CAAS,SAAA;AAAA,QACzB,GAAI,QAAA,GAAW,EAAE,QAAA,KAAa,EAAC;AAAA,QAC/B;AAAA;AACF,KACF;AAAA,EACF;AAAA,EAEQ,OAAA,GAAgB;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AACjB,IAAA,KAAA,MAAW,QAAA,IAAY,KAAK,UAAA,EAAY;AACtC,MAAA,QAAA,EAAS;AAAA,IACX;AAAA,EACF;AACF","file":"chunk-KSHCQ777.js","sourcesContent":["import type {\n AgentEvent,\n ConnectorContent,\n ConnectorEntry,\n ConnectorInfo,\n ConnectorResponseEvent,\n ConnectorStatusEvent,\n ListOptions,\n MountInfo,\n SearchOptions,\n} from \"@skaile/workspaces/types\";\nimport type {\n ConnectorStatus,\n ResourceClientSnapshot,\n StoreTransport,\n SubscribableStore,\n} from \"./types.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * Lazy resource browser for agent connectors.\n *\n * Provides a reactive list of connected mounts and connectors, and\n * request/response methods for browsing connector contents. Shares\n * the same transport (`send` + `onEvent`) as `AgentStore`.\n * @docLink packages/store/concepts#resource-client\n */\nexport class ResourceClient implements SubscribableStore<ResourceClientSnapshot> {\n private readonly _send: StoreTransport[\"send\"];\n private _mounts: readonly MountInfo[] = [];\n private _connectors: readonly ConnectorInfo[] = [];\n\n /** Live connection status per connector, keyed by connector ID. Updated by connector_status events. */\n connectorStatus: Map<string, ConnectorStatus> = new Map();\n\n private _snapshot: ResourceClientSnapshot | null = null;\n private readonly _listeners = new Set<() => void>();\n private readonly _pendingRequests = new Map<\n string,\n {\n resolve: (event: ConnectorResponseEvent) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n private readonly _unsubEvent: () => void;\n\n /**\n * @param transport - Shared transport (same instance as the AgentStore for this session).\n */\n constructor(transport: StoreTransport) {\n this._send = transport.send;\n this._unsubEvent = transport.onEvent((event) => this._handleEvent(event));\n }\n\n // -- Reactive state --------------------------------------------------------\n\n /** Mounts available in this session, populated from `resources_available` events. */\n get mounts(): readonly MountInfo[] {\n return this._mounts;\n }\n\n /** Tool-based connectors available in this session, populated from `resources_available` events. */\n get connectors(): readonly ConnectorInfo[] {\n return this._connectors;\n }\n\n // -- Resource operations ---------------------------------------------------\n\n /**\n * List directory entries at the given path within a connector.\n *\n * @param connectorId - ID of the connector to query.\n * @param path - Directory path to list. Omit for the connector root.\n * @param opts - Optional pagination and filter options.\n * @returns Array of entries (files, directories, etc.) at the given path.\n * @throws If the request times out or the connector returns an error.\n */\n async list(connectorId: string, path?: string, opts?: ListOptions): Promise<ConnectorEntry[]> {\n const response = await this._request(connectorId, \"list\", path, opts);\n return (response.data as ConnectorEntry[]) ?? [];\n }\n\n /**\n * Read the content of a single resource.\n *\n * @param connectorId - ID of the connector to query.\n * @param path - Full path to the resource within the connector.\n * @returns The resource content object.\n * @throws If the request times out or the connector returns an error.\n */\n async read(connectorId: string, path: string): Promise<ConnectorContent> {\n const response = await this._request(connectorId, \"read\", path);\n return response.data as ConnectorContent;\n }\n\n /**\n * Write content to a resource, creating it if it does not exist.\n *\n * @param connectorId - ID of the connector to write to.\n * @param path - Full path to the resource within the connector.\n * @param content - Content to write.\n * @throws If the request times out or the connector returns an error.\n */\n async write(connectorId: string, path: string, content: ConnectorContent): Promise<void> {\n await this._request(connectorId, \"write\", path, undefined, content);\n }\n\n /**\n * Delete a resource from a connector.\n *\n * @param connectorId - ID of the connector to delete from.\n * @param path - Full path to the resource within the connector.\n * @throws If the request times out or the connector returns an error.\n */\n async delete(connectorId: string, path: string): Promise<void> {\n await this._request(connectorId, \"delete\", path);\n }\n\n /**\n * Full-text search within a connector.\n *\n * @param connectorId - ID of the connector to search.\n * @param query - Search query string.\n * @param opts - Optional search options (e.g. path prefix, result limit).\n * @returns Matching entries, ordered by relevance as determined by the connector.\n * @throws If the request times out or the connector returns an error.\n */\n async search(\n connectorId: string,\n query: string,\n opts?: SearchOptions,\n ): Promise<ConnectorEntry[]> {\n const response = await this._request(connectorId, \"search\", query, opts);\n return (response.data as ConnectorEntry[]) ?? [];\n }\n\n // -- useSyncExternalStore interface ----------------------------------------\n\n /**\n * Register a change listener. Called after every resource availability change.\n *\n * Conforms to the `subscribe` parameter of React's `useSyncExternalStore`.\n *\n * @param listener - Callback invoked whenever mounts or connectors change.\n * @returns Unsubscribe function — call to stop receiving notifications.\n */\n subscribe = (listener: () => void): (() => void) => {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n };\n\n /**\n * Return the current immutable resource snapshot.\n *\n * A new object is produced lazily after each `resources_available` event.\n * Conforms to the `getSnapshot` parameter of React's `useSyncExternalStore`.\n */\n getSnapshot = (): ResourceClientSnapshot => {\n if (!this._snapshot) {\n this._snapshot = { mounts: this._mounts, connectors: this._connectors };\n }\n return this._snapshot;\n };\n\n // -- Connector config mutations --------------------------------------------\n\n /**\n * Send a `connector_config` add command to wire a new connector at runtime,\n * without restarting the session. The runner receives this command and\n * calls `ConnectorManager.connect()`, which fires a `connector_status` event\n * back to the store once the connector is live.\n *\n * @param declaration - Connector declaration (id, driver, access level, options).\n */\n addConnector(declaration: {\n id: string;\n driver: string;\n access?: \"read-only\" | \"read-write\";\n options?: Record<string, unknown>;\n }): void {\n this._send({ type: \"connector_config\", action: \"add\", declaration });\n }\n\n /**\n * Send a `connector_config` remove command to disconnect a connector by ID\n * without restarting the session.\n *\n * @param connectorId - ID of the connector to disconnect and remove.\n */\n removeConnector(connectorId: string): void {\n this._send({ type: \"connector_config\", action: \"remove\", connectorId });\n }\n\n /**\n * Send a `connector_config` refresh command to reconnect all configured\n * connectors (e.g. after a credentials change).\n */\n refreshConnectors(): void {\n this._send({ type: \"connector_config\", action: \"refresh\" });\n }\n\n // -- Cleanup ---------------------------------------------------------------\n\n /**\n * Unsubscribe from transport events, reject all pending requests, and\n * clear all change listeners.\n *\n * All in-flight `list`/`read`/`write`/`delete`/`search` calls will reject\n * with `\"ResourceClient disposed\"`.\n */\n dispose(): void {\n this._unsubEvent();\n for (const [, pending] of this._pendingRequests) {\n clearTimeout(pending.timer);\n pending.reject(new Error(\"ResourceClient disposed\"));\n }\n this._pendingRequests.clear();\n this._listeners.clear();\n }\n\n // -- Internal --------------------------------------------------------------\n\n private _handleEvent(event: AgentEvent): void {\n if (event.type === \"connector_status\") {\n const e = event as ConnectorStatusEvent;\n const existing = this.connectorStatus.get(e.connectorId);\n const next = new Map(this.connectorStatus);\n next.set(e.connectorId, {\n id: e.connectorId,\n driver:\n existing?.driver ?? this._connectors.find((c) => c.id === e.connectorId)?.driver ?? \"\",\n state: e.status,\n ...(e.error !== undefined ? { error: e.error } : {}),\n ...(e.latencyMs !== undefined ? { latencyMs: e.latencyMs } : {}),\n lastUpdated: new Date(),\n });\n this.connectorStatus = next;\n for (const listener of this._listeners) {\n listener();\n }\n return;\n }\n\n if (event.type === \"resources_available\") {\n this._mounts = event.mounts;\n this._connectors = event.connectors;\n this._snapshot = null;\n for (const listener of this._listeners) {\n listener();\n }\n return;\n }\n\n if (event.type === \"resource_response\") {\n const pending = this._pendingRequests.get(event.requestId);\n if (!pending) return;\n\n clearTimeout(pending.timer);\n this._pendingRequests.delete(event.requestId);\n\n if (event.error) {\n pending.reject(new Error(event.error));\n } else {\n pending.resolve(event);\n }\n }\n }\n\n private _request(\n connectorId: string,\n operation: \"list\" | \"read\" | \"write\" | \"delete\" | \"search\",\n path?: string,\n options?: ListOptions | SearchOptions,\n content?: ConnectorContent,\n ): Promise<ConnectorResponseEvent> {\n const requestId = crypto.randomUUID();\n\n return new Promise<ConnectorResponseEvent>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingRequests.delete(requestId);\n reject(\n new Error(\n `Resource request timed out after ${DEFAULT_TIMEOUT_MS}ms: ${operation} ${connectorId}${path ? ` ${path}` : \"\"}`,\n ),\n );\n }, DEFAULT_TIMEOUT_MS);\n\n this._pendingRequests.set(requestId, { resolve, reject, timer });\n\n this._send({\n type: \"resource_request\",\n requestId,\n connectorId,\n operation,\n ...(path !== undefined ? { path } : {}),\n ...(options ? { options } : {}),\n ...(content ? { content } : {}),\n });\n });\n }\n}\n","import type {\n AgentCommand,\n AgentEvent,\n AgentPhase,\n Capability,\n IncompatibleProtocolEvent,\n Message,\n ProtocolInfoEvent,\n RenderInvokedEvent,\n} from \"@skaile/workspaces/types\";\nimport type {\n AgentClientLike,\n AgentStoreOptions,\n AgentStoreSnapshot,\n ConnectionStatus,\n SubscribableStore,\n} from \"./types.js\";\n\nconst DEFAULT_PAGE_SIZE = 50;\n\n/** Conservative equality for plain JSON data; unsupported or unverifiable values fail open. */\nfunction isSameJsonValue<T>(a: T | undefined, b: T, conservativeCommandInput = false): boolean {\n const aObjects = new WeakSet<object>();\n const bObjects = new WeakSet<object>();\n\n const compare = (left: unknown, right: unknown): boolean => {\n if (left === null || right === null) return left === right;\n if (typeof left !== typeof right) return false;\n\n switch (typeof left) {\n case \"string\":\n case \"boolean\":\n return left === right;\n case \"number\":\n return (\n Number.isFinite(left) &&\n Number.isFinite(right) &&\n !Object.is(left, -0) &&\n !Object.is(right, -0) &&\n left === right\n );\n case \"object\":\n break;\n default:\n return false;\n }\n\n const leftObject = left as object;\n const rightObject = right as object;\n if (aObjects.has(leftObject) || bObjects.has(rightObject)) return false;\n if (conservativeCommandInput) {\n if (leftObject === rightObject || bObjects.has(leftObject) || aObjects.has(rightObject)) {\n return false;\n }\n }\n aObjects.add(leftObject);\n bObjects.add(rightObject);\n\n const leftIsArray = Array.isArray(leftObject);\n if (leftIsArray !== Array.isArray(rightObject)) return false;\n\n const leftPrototype = Object.getPrototypeOf(leftObject);\n const rightPrototype = Object.getPrototypeOf(rightObject);\n const leftHasPlainPrototype = leftIsArray\n ? leftPrototype === Array.prototype\n : leftPrototype === Object.prototype || leftPrototype === null;\n const rightHasPlainPrototype = leftIsArray\n ? rightPrototype === Array.prototype\n : rightPrototype === Object.prototype || rightPrototype === null;\n if (\n !leftHasPlainPrototype ||\n !rightHasPlainPrototype ||\n leftPrototype !== rightPrototype ||\n !Object.isExtensible(leftObject) ||\n !Object.isExtensible(rightObject)\n ) {\n return false;\n }\n\n const leftKeys = Reflect.ownKeys(leftObject);\n const rightKeys = Reflect.ownKeys(rightObject);\n if (\n leftKeys.length !== rightKeys.length ||\n leftKeys.some((key) => typeof key !== \"string\") ||\n rightKeys.some((key) => typeof key !== \"string\")\n ) {\n return false;\n }\n\n if (leftIsArray) {\n const leftLengthDescriptor = Object.getOwnPropertyDescriptor(leftObject, \"length\");\n const rightLengthDescriptor = Object.getOwnPropertyDescriptor(rightObject, \"length\");\n const leftLength = leftLengthDescriptor?.value;\n const rightLength = rightLengthDescriptor?.value;\n if (\n !leftLengthDescriptor ||\n !(\"value\" in leftLengthDescriptor) ||\n !leftLengthDescriptor.writable ||\n leftLengthDescriptor.enumerable ||\n leftLengthDescriptor.configurable ||\n !rightLengthDescriptor ||\n !(\"value\" in rightLengthDescriptor) ||\n !rightLengthDescriptor.writable ||\n rightLengthDescriptor.enumerable ||\n rightLengthDescriptor.configurable ||\n typeof leftLength !== \"number\" ||\n leftLength !== rightLength ||\n leftKeys.length !== leftLength + 1\n ) {\n return false;\n }\n\n for (let index = 0; index < leftLength; index++) {\n const key = String(index);\n const leftDescriptor = Object.getOwnPropertyDescriptor(leftObject, key);\n const rightDescriptor = Object.getOwnPropertyDescriptor(rightObject, key);\n if (\n !leftDescriptor?.enumerable ||\n !(\"value\" in leftDescriptor) ||\n !leftDescriptor.writable ||\n !leftDescriptor.configurable ||\n !rightDescriptor?.enumerable ||\n !(\"value\" in rightDescriptor) ||\n !rightDescriptor.writable ||\n !rightDescriptor.configurable ||\n !compare(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n }\n\n for (let index = 0; index < leftKeys.length; index++) {\n const leftKey = leftKeys[index] as string;\n const rightKey = rightKeys[index] as string;\n if (leftKey !== rightKey) return false;\n\n const leftDescriptor = Object.getOwnPropertyDescriptor(leftObject, leftKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(rightObject, rightKey);\n if (\n !leftDescriptor?.enumerable ||\n !(\"value\" in leftDescriptor) ||\n !leftDescriptor.writable ||\n !leftDescriptor.configurable ||\n !rightDescriptor?.enumerable ||\n !(\"value\" in rightDescriptor) ||\n !rightDescriptor.writable ||\n !rightDescriptor.configurable ||\n !compare(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n };\n\n try {\n const same = compare(a, b);\n if (!same || !conservativeCommandInput) return same;\n structuredClone(a);\n structuredClone(b);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Headless reactive store for agent conversation state.\n *\n * Framework-agnostic — works with React (`useSyncExternalStore`),\n * Vue (`shallowRef` + `subscribe`), or any other UI framework.\n *\n * Accepts a minimal transport interface (`send` + `onEvent`) so it works\n * with WebSocket, tRPC, SSE, or any other delivery mechanism.\n * @docLink packages/store/concepts#agent-store\n */\nexport class AgentStore implements SubscribableStore<AgentStoreSnapshot> {\n private readonly _options: AgentStoreOptions;\n private _messages: Message[];\n private _streamingText = \"\";\n private _cancelledText = \"\";\n private _status: ConnectionStatus = \"idle\";\n private _phase: AgentPhase = \"idle\";\n private _pendingQuestion: AgentStoreSnapshot[\"pendingQuestion\"] = null;\n private _error: AgentStoreSnapshot[\"error\"] = null;\n private _isAllLoaded: boolean;\n private _seq: number;\n private _streamingFlushed = true;\n /** Shared state per store namespace — new Map instance on every mutation. */\n private _sharedState: Map<string, Record<string, unknown>> = new Map();\n /** Protocol v2 capability registry — new Map instance on every mutation. */\n private _capabilities: Map<string, Capability> = new Map();\n /** Protocol v2 active render invocations — new Map instance on every mutation. */\n private _activeRenderInvocations: Map<string, RenderInvokedEvent> = new Map();\n /** Protocol v2 — most recent `protocol_info` event from the runner. */\n private _protocolInfo: ProtocolInfoEvent | null = null;\n /** Protocol v2 — latest incompatible-protocol notice. */\n private _incompatibleProtocol: IncompatibleProtocolEvent | null = null;\n\n private _snapshot: AgentStoreSnapshot | null = null;\n private readonly _listeners = new Set<() => void>();\n private readonly _unsubEvent: () => void;\n private readonly _unsubStatus: (() => void) | undefined;\n\n /**\n * @param options - Store configuration including transport and optional pagination support.\n */\n constructor(options: AgentStoreOptions) {\n this._options = options;\n this._messages = options.initialMessages ? [...options.initialMessages] : [];\n this._isAllLoaded = !options.loadMessages;\n this._seq = this._messages.reduce((max, m) => Math.max(max, m.seq), 0);\n\n this._unsubEvent = options.onEvent((event) => this._handleEvent(event));\n this._unsubStatus = options.onStatusChange?.((status) => this.setStatus(status));\n }\n\n // -- Reactive state --------------------------------------------------------\n\n /** Accumulated conversation messages, oldest first. */\n get messages(): readonly Message[] {\n return this._messages;\n }\n\n /** Text currently streaming from the agent. Empty when not streaming. */\n get streamingText(): string {\n return this._streamingText;\n }\n\n /** Current connection lifecycle state. */\n get status(): ConnectionStatus {\n return this._status;\n }\n\n /** Current agent execution phase (e.g. `\"idle\"`, `\"thinking\"`, `\"executing\"`). */\n get phase(): AgentPhase {\n return this._phase;\n }\n\n /** The pending question the agent is waiting for the user to answer, or null. */\n get pendingQuestion(): AgentStoreSnapshot[\"pendingQuestion\"] {\n return this._pendingQuestion;\n }\n\n /** Most recent error, or null when no error is active. */\n get error(): AgentStoreSnapshot[\"error\"] {\n return this._error;\n }\n\n /** Partial text that was visible when the user cancelled. Empty when not cancelled. */\n get cancelledText(): string {\n return this._cancelledText;\n }\n\n /** True when there are no more older messages to load via pagination. */\n get isAllLoaded(): boolean {\n return this._isAllLoaded;\n }\n\n // -- Commands --------------------------------------------------------------\n\n /**\n * Send a user prompt to the agent and optimistically update local state.\n *\n * Clears any previous error and cancelled text, sets phase to `\"thinking\"`,\n * and appends the prompt as a local message before forwarding to the agent.\n *\n * @param text - The user's prompt text.\n */\n prompt(text: string): void {\n // A prompt sent mid-turn (sender interjecting while the agent streams) is a\n // boundary: finalize the in-flight text before this prompt so the two don't\n // merge into one bubble. No-op at turn start (nothing streaming).\n this._flushStreaming();\n this._error = null;\n this._cancelledText = \"\";\n this._streamingFlushed = false;\n this._phase = \"thinking\";\n this._appendMessage({ type: \"prompt\", prompt: text }, \"user\");\n this._options.send({ type: \"prompt\", prompt: text });\n this._notify();\n }\n\n /**\n * Send a reply to the agent's pending question.\n *\n * Clears the pending question locally before forwarding the reply command.\n *\n * @param answer - The user's answer text.\n * @param question - The sub-question being answered, verbatim from its\n * `question` event. Required for correctness in hosts that surface several\n * queued questions at once ({@link pendingQuestion} tracks only the latest,\n * so those hosts drive this from their own message history): without it the\n * agent files the answer under its next unanswered sub-question, which\n * mismatches any non-sequential reply.\n */\n reply(answer: string, question?: string): void {\n this._pendingQuestion = null;\n // Answering a pending question resumes the agent turn — restore the busy\n // phase (mirrors prompt()) so the thinking indicator reappears immediately\n // rather than after the agent's first resumed event lands.\n this._phase = \"thinking\";\n const command = {\n type: \"reply\",\n answer,\n ...(question !== undefined ? { question } : {}),\n } as const;\n this._appendMessage(command, \"user\");\n this._options.send(command);\n this._notify();\n }\n\n /**\n * Cancel the current agent turn.\n *\n * Preserves partial streaming text in {@link cancelledText} so the UI can\n * display it. Clears streaming state, sets phase to `\"cancelling\"` (not\n * yet confirmed idle — see {@link AgentPhase}), and sends a `cancel`\n * command to the agent.\n */\n cancel(): void {\n // Preserve partial streaming text so the UI can still display it\n this._cancelledText = this._streamingText;\n this._streamingText = \"\";\n this._streamingFlushed = true;\n this._phase = \"cancelling\";\n this._options.send({ type: \"cancel\" });\n this._notify();\n }\n\n /**\n * Update shared state for a store namespace.\n *\n * Sends a `state_update` command to the agent and optimistically\n * updates local state so the change is reflected immediately.\n *\n * @param store - Store namespace (e.g. \"app\", \"component:render-123\").\n * @param state - Full state snapshot (replaces previous).\n */\n updateState(store: string, state: Record<string, unknown>): void {\n this._options.send({ type: \"state_update\", store, state });\n if (isSameJsonValue(this._sharedState.get(store), state, true)) return;\n // Optimistic local update\n this._sharedState = new Map(this._sharedState);\n this._sharedState.set(store, state);\n this._notify();\n }\n\n /**\n * Send an arbitrary command to the agent.\n *\n * Use this for commands that don't have a dedicated convenience method\n * (e.g. `ui_interaction`). No local state changes — the command is\n * forwarded as-is to the transport.\n *\n * @param cmd - The command to send.\n */\n send(cmd: AgentCommand): void {\n this._options.send(cmd);\n }\n\n /**\n * Load the previous page of messages and prepend them to the current list.\n *\n * No-op when `loadMessages` was not provided at construction time or when\n * all history has already been loaded ({@link isAllLoaded} is true).\n * Sets {@link isAllLoaded} to true once the server returns fewer messages\n * than the configured page size.\n */\n async loadPreviousMessages(): Promise<void> {\n if (!this._options.loadMessages || this._isAllLoaded) return;\n\n const pageSize = this._options.pageSize ?? DEFAULT_PAGE_SIZE;\n const before = this._messages.length > 0 ? this._messages[0].seq : undefined;\n const older = await this._options.loadMessages({ before, limit: pageSize });\n\n if (older.length < pageSize) this._isAllLoaded = true;\n\n const existingIds = new Set(this._messages.map((m) => m.id));\n const unique = older.filter((m) => !existingIds.has(m.id));\n this._messages = [...unique, ...this._messages];\n\n this._notify();\n }\n\n // -- External control ------------------------------------------------------\n\n /**\n * Programmatically update the connection status.\n *\n * Called by transport wrappers that cannot use the `onStatusChange`\n * callback (e.g. tRPC subscriptions that track status externally).\n *\n * Writing the status the store already holds is a no-op: it neither rotates\n * the snapshot nor notifies listeners.\n *\n * @param status - The new connection status.\n */\n setStatus(status: ConnectionStatus): void {\n if (this._status === status) return;\n this._status = status;\n this._notify();\n }\n\n // -- useSyncExternalStore interface ----------------------------------------\n\n /**\n * Register a change listener. Called synchronously after every state change.\n *\n * Conforms to the `subscribe` parameter of React's `useSyncExternalStore`.\n *\n * @param listener - Callback invoked whenever state changes.\n * @returns Unsubscribe function — call to stop receiving notifications.\n */\n subscribe = (listener: () => void): (() => void) => {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n };\n\n /**\n * Return the current immutable state snapshot.\n *\n * A new object is produced lazily on the first call after each state change.\n * Subsequent calls return the same cached object until the next change.\n * Conforms to the `getSnapshot` parameter of React's `useSyncExternalStore`.\n */\n getSnapshot = (): AgentStoreSnapshot => {\n if (!this._snapshot) {\n this._snapshot = {\n messages: this._messages,\n streamingText: this._streamingText,\n cancelledText: this._cancelledText,\n status: this._status,\n phase: this._phase,\n pendingQuestion: this._pendingQuestion,\n error: this._error,\n isAllLoaded: this._isAllLoaded,\n sharedState: this._sharedState,\n capabilities: this._capabilities,\n activeRenderInvocations: this._activeRenderInvocations,\n protocolInfo: this._protocolInfo,\n incompatibleProtocol: this._incompatibleProtocol,\n };\n }\n return this._snapshot;\n };\n\n // -- Cleanup ---------------------------------------------------------------\n\n /**\n * Unsubscribe from transport events and clear all change listeners.\n *\n * Call this when the component or service that owns the store unmounts or\n * shuts down to prevent memory leaks.\n */\n dispose(): void {\n this._unsubEvent();\n this._unsubStatus?.();\n this._listeners.clear();\n }\n\n // -- Factory ---------------------------------------------------------------\n\n /**\n * Create an {@link AgentStore} connected to a duck-typed agent client.\n *\n * Adapts the client's `send`/`onEvent`/`offEvent` API to the\n * {@link StoreTransport} interface expected by the constructor, without\n * creating a hard runtime dependency on `@skaile/workspaces/client`.\n *\n * @param client - Any object implementing {@link AgentClientLike}.\n * @param opts - Optional store configuration.\n * @param opts.sessionId - Session ID for message envelopes (defaults to a new UUID).\n * @param opts.initialMessages - Messages to pre-populate the store with.\n *\n * @example\n * ```ts\n * const store = AgentStore.fromClient(agentClient, { sessionId: 'sess-123' })\n * ```\n */\n static fromClient(\n client: AgentClientLike,\n opts?: { sessionId?: string; initialMessages?: Message[] },\n ): AgentStore {\n return new AgentStore({\n sessionId: opts?.sessionId ?? crypto.randomUUID(),\n send: (cmd) => client.send(cmd),\n onEvent: (handler) => {\n client.onEvent(handler);\n return () => client.offEvent(handler);\n },\n initialMessages: opts?.initialMessages,\n });\n }\n\n // -- Internal --------------------------------------------------------------\n\n private _handleEvent(event: AgentEvent): void {\n switch (event.type) {\n case \"text\":\n this._cancelledText = \"\";\n this._streamingText += event.content;\n this._streamingFlushed = false;\n break;\n\n case \"finished\":\n this._cancelledText = \"\";\n this._flushStreaming();\n this._appendMessage(event);\n // A cancelled finished is synthetic (persisted immediately for reload-\n // durability) and precedes the driver's real abort/kill sequence — stay\n // \"cancelling\" until the later, genuine status event reports \"idle\".\n if (!event.cancelled) this._phase = \"idle\";\n this._pendingQuestion = null;\n break;\n\n case \"status\":\n // While cancelling, the driver's interrupt/unwind window can still emit\n // stale \"working\" statuses for already-buffered tool activity — ignore\n // anything but the genuine idle confirmation.\n if (this._phase === \"cancelling\" && event.phase !== \"idle\") return;\n // The bridge re-emits phase:\"working\" on every tool call, so most status\n // events in a turn carry the phase we already hold. `_notify()` rotates\n // the snapshot, so notifying for them re-renders consumers for nothing.\n if (this._phase === event.phase) return;\n this._phase = event.phase;\n break;\n\n case \"user_message\":\n // A peer's message mid-turn is a boundary: finalize the in-flight text\n // so it renders before the interjection. Flush-only — the peer message\n // is delivered via the host's history, not this transient echo. The\n // flush is internally conditional, so an echo arriving while nothing is\n // streaming (the common case — peers talk between turns) changed no\n // state and notifying for it was a pure fanout.\n if (!this._flushStreaming()) return;\n break;\n\n case \"tool_call\":\n case \"tool_result\":\n case \"file_changed\":\n case \"subagent\":\n case \"dev_server\":\n case \"handoff\":\n case \"question_reply\":\n // Flush in-flight text first so each text block becomes its own\n // Message, interleaved with tool activity in order — otherwise text\n // before and after a tool call merges into one wall-of-text blob.\n this._flushStreaming();\n this._appendMessage(event);\n break;\n\n case \"question\":\n // A pending question is a human-in-the-loop pause — the agent is waiting\n // for the user, not working. Reset to idle (like finished/error) so any\n // phase-derived busy indicator clears until the user replies.\n this._flushStreaming();\n this._phase = \"idle\";\n this._pendingQuestion = event;\n this._appendMessage(event);\n break;\n\n case \"error\":\n this._error = { message: event.message, fatal: event.fatal };\n this._streamingText = \"\";\n this._streamingFlushed = true;\n this._phase = \"idle\";\n this._appendMessage(event);\n break;\n\n case \"state_changed\": {\n // Accumulate state per store namespace (notify only — no message).\n // Re-emits of unchanged state are routine, not exceptional: `serve.ts`\n // replays every namespace on connect (`buildStoreSnapshotReplay`), on a\n // seeded execution, on re-registering an already-registered store, and\n // immediately after registration — and the `xstate-store` adapter is\n // equality-free, so writing a key its current value emits too. Each of\n // those rebuilt the Map and rotated the snapshot for identical state.\n if (isSameJsonValue(this._sharedState.get(event.store), event.state)) return;\n this._sharedState = new Map(this._sharedState);\n this._sharedState.set(event.store, event.state);\n break;\n }\n\n // ── Protocol v2 ────────────────────────────────────────────────────────\n\n case \"capability_register\": {\n // TRANSIENT — accumulate v2 capabilities into the registry (no message).\n // The gateway replays the whole set on every (re)attach; a byte-identical\n // replay must not rotate the Map identity or notify, or a reconnect storm\n // compounds into an unbounded render loop in consumers.\n if (\n event.capabilities.every((cap) => isSameJsonValue(this._capabilities.get(cap.name), cap))\n ) {\n return;\n }\n this._capabilities = new Map(this._capabilities);\n for (const cap of event.capabilities) {\n this._capabilities.set(cap.name, cap);\n }\n break;\n }\n\n case \"capability_deregister\": {\n // TRANSIENT — drop capabilities by name. Names we never had are a no-op:\n // rebuilding the Map for them would notify with an identical registry.\n const present = event.names.filter((name) => this._capabilities.has(name));\n if (present.length === 0) return;\n this._capabilities = new Map(this._capabilities);\n for (const name of present) {\n this._capabilities.delete(name);\n }\n break;\n }\n\n case \"render_invoked\":\n // TRANSIENT — record latest render invocation (frontend pairs with\n // the matching `Capability.render` for placement).\n this._activeRenderInvocations = new Map(this._activeRenderInvocations);\n this._activeRenderInvocations.set(event.callId, event);\n break;\n\n case \"protocol_info\": {\n // TRANSIENT — runner announced its protocol version. It announces on\n // every attach, so tab mounts, StrictMode remounts and SSE reconnects\n // almost always carry the version we already hold. `ProtocolInfoEvent`\n // is nothing but `version`, and `ProtocolVersion` is exactly three\n // numbers, so the field comparison is complete, not conservative.\n //\n // A fresh announcement also retires any incompatibility notice: the\n // platform restarts the session on `incompatible_protocol`, and this\n // event is the replacement container introducing itself. Nothing cleared\n // `_incompatibleProtocol` before, so the restart banner was sticky for\n // the life of the store even though the platform's debug pane documents\n // this clear as already happening. Guarding without clearing would make\n // that permanent, since a repeat announcement would never get here.\n const held = this._protocolInfo?.version;\n const sameVersion =\n held !== undefined &&\n held.major === event.version.major &&\n held.minor === event.version.minor &&\n held.patch === event.version.patch;\n if (sameVersion && this._incompatibleProtocol === null) return;\n // Keep the held event object when the version is unchanged so consumers\n // with an effect keyed on `snapshot.protocolInfo` do not re-fire.\n if (!sameVersion) this._protocolInfo = event;\n this._incompatibleProtocol = null;\n break;\n }\n\n case \"incompatible_protocol\":\n // TRANSIENT — runner detected version drift; platform restarts session.\n this._incompatibleProtocol = event;\n break;\n\n case \"capability_invoked\":\n // Backend intercepts client-side invocations and dispatches them\n // through V2CapabilityRegistryService — frontends should not see\n // these. Drop silently if one slips through.\n return;\n\n case \"resource_response\":\n case \"resources_available\":\n // Transient — handled by ResourceClient, not AgentStore\n return;\n\n default:\n // The switch names 22 of `AgentEvent`'s 54 members. The other 32 —\n // `log_entry` above all, one per line of container output — hold no\n // AgentStore state, so falling through to the trailing `_notify()`\n // rotated the snapshot and re-rendered every consumer for state that\n // had not changed. Unlike the guarded cases this was not a replay\n // artifact: it happened on every single occurrence. Hosts that need\n // these events (log panels, mount indicators, typing bubbles) read them\n // off the transport upstream of the store, not out of the snapshot.\n //\n // Deliberately not an `assertNever` exhaustiveness check: that is a\n // compile error while 32 members are unnamed, and naming all 54 would\n // enumerate events the store holds no state for just to satisfy it.\n return;\n }\n\n this._notify();\n }\n\n /**\n * Finalize buffered streaming text as a `text` Message.\n *\n * @returns true when text was flushed; false when there was nothing to flush,\n * so callers can skip a notify that would change nothing.\n */\n private _flushStreaming(): boolean {\n if (this._streamingFlushed || !this._streamingText) return false;\n this._appendMessage({ type: \"text\", content: this._streamingText });\n this._streamingText = \"\";\n this._streamingFlushed = true;\n return true;\n }\n\n private _appendMessage(payload: AgentCommand | AgentEvent, senderId?: string): void {\n this._seq++;\n this._messages = [\n ...this._messages,\n {\n id: crypto.randomUUID(),\n seq: this._seq,\n timestamp: new Date().toISOString(),\n sessionId: this._options.sessionId,\n ...(senderId ? { senderId } : {}),\n payload,\n },\n ];\n }\n\n private _notify(): void {\n this._snapshot = null;\n for (const listener of this._listeners) {\n listener();\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../store/src/resource-client.ts","../store/src/store.ts"],"names":[],"mappings":";AAkBA,IAAM,kBAAA,GAAqB,GAAA;AAUpB,IAAM,iBAAN,MAA0E;AAAA,EAC9D,KAAA;AAAA,EACT,UAAgC,EAAC;AAAA,EACjC,cAAwC,EAAC;AAAA;AAAA,EAGjD,eAAA,uBAAoD,GAAA,EAAI;AAAA,EAEhD,SAAA,GAA2C,IAAA;AAAA,EAClC,UAAA,uBAAiB,GAAA,EAAgB;AAAA,EACjC,gBAAA,uBAAuB,GAAA,EAOtC;AAAA,EACe,WAAA;AAAA;AAAA;AAAA;AAAA,EAKjB,YAAY,SAAA,EAA2B;AACrC,IAAA,IAAA,CAAK,QAAQ,SAAA,CAAU,IAAA;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,UAAU,OAAA,CAAQ,CAAC,UAAU,IAAA,CAAK,YAAA,CAAa,KAAK,CAAC,CAAA;AAAA,EAC1E;AAAA;AAAA;AAAA,EAKA,IAAI,MAAA,GAA+B;AACjC,IAA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AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,IAAA;AACjB,IAAA,KAAA,MAAW,QAAA,IAAY,KAAK,UAAA,EAAY;AACtC,MAAA,QAAA,EAAS;AAAA,IACX;AAAA,EACF;AACF","file":"chunk-3DNCPQAR.js","sourcesContent":["import type {\n AgentEvent,\n ConnectorContent,\n ConnectorEntry,\n ConnectorInfo,\n ConnectorResponseEvent,\n ConnectorStatusEvent,\n ListOptions,\n MountInfo,\n SearchOptions,\n} from \"@skaile/workspaces/types\";\nimport type {\n ConnectorStatus,\n ResourceClientSnapshot,\n StoreTransport,\n SubscribableStore,\n} from \"./types.js\";\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/**\n * Lazy resource browser for agent connectors.\n *\n * Provides a reactive list of connected mounts and connectors, and\n * request/response methods for browsing connector contents. Shares\n * the same transport (`send` + `onEvent`) as `AgentStore`.\n * @docLink packages/store/concepts#resource-client\n */\nexport class ResourceClient implements SubscribableStore<ResourceClientSnapshot> {\n private readonly _send: StoreTransport[\"send\"];\n private _mounts: readonly MountInfo[] = [];\n private _connectors: readonly ConnectorInfo[] = [];\n\n /** Live connection status per connector, keyed by connector ID. Updated by connector_status events. */\n connectorStatus: Map<string, ConnectorStatus> = new Map();\n\n private _snapshot: ResourceClientSnapshot | null = null;\n private readonly _listeners = new Set<() => void>();\n private readonly _pendingRequests = new Map<\n string,\n {\n resolve: (event: ConnectorResponseEvent) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n }\n >();\n private readonly _unsubEvent: () => void;\n\n /**\n * @param transport - Shared transport (same instance as the AgentStore for this session).\n */\n constructor(transport: StoreTransport) {\n this._send = transport.send;\n this._unsubEvent = transport.onEvent((event) => this._handleEvent(event));\n }\n\n // -- Reactive state --------------------------------------------------------\n\n /** Mounts available in this session, populated from `resources_available` events. */\n get mounts(): readonly MountInfo[] {\n return this._mounts;\n }\n\n /** Tool-based connectors available in this session, populated from `resources_available` events. */\n get connectors(): readonly ConnectorInfo[] {\n return this._connectors;\n }\n\n // -- Resource operations ---------------------------------------------------\n\n /**\n * List directory entries at the given path within a connector.\n *\n * @param connectorId - ID of the connector to query.\n * @param path - Directory path to list. Omit for the connector root.\n * @param opts - Optional pagination and filter options.\n * @returns Array of entries (files, directories, etc.) at the given path.\n * @throws If the request times out or the connector returns an error.\n */\n async list(connectorId: string, path?: string, opts?: ListOptions): Promise<ConnectorEntry[]> {\n const response = await this._request(connectorId, \"list\", path, opts);\n return (response.data as ConnectorEntry[]) ?? [];\n }\n\n /**\n * Read the content of a single resource.\n *\n * @param connectorId - ID of the connector to query.\n * @param path - Full path to the resource within the connector.\n * @returns The resource content object.\n * @throws If the request times out or the connector returns an error.\n */\n async read(connectorId: string, path: string): Promise<ConnectorContent> {\n const response = await this._request(connectorId, \"read\", path);\n return response.data as ConnectorContent;\n }\n\n /**\n * Write content to a resource, creating it if it does not exist.\n *\n * @param connectorId - ID of the connector to write to.\n * @param path - Full path to the resource within the connector.\n * @param content - Content to write.\n * @throws If the request times out or the connector returns an error.\n */\n async write(connectorId: string, path: string, content: ConnectorContent): Promise<void> {\n await this._request(connectorId, \"write\", path, undefined, content);\n }\n\n /**\n * Delete a resource from a connector.\n *\n * @param connectorId - ID of the connector to delete from.\n * @param path - Full path to the resource within the connector.\n * @throws If the request times out or the connector returns an error.\n */\n async delete(connectorId: string, path: string): Promise<void> {\n await this._request(connectorId, \"delete\", path);\n }\n\n /**\n * Full-text search within a connector.\n *\n * @param connectorId - ID of the connector to search.\n * @param query - Search query string.\n * @param opts - Optional search options (e.g. path prefix, result limit).\n * @returns Matching entries, ordered by relevance as determined by the connector.\n * @throws If the request times out or the connector returns an error.\n */\n async search(\n connectorId: string,\n query: string,\n opts?: SearchOptions,\n ): Promise<ConnectorEntry[]> {\n const response = await this._request(connectorId, \"search\", query, opts);\n return (response.data as ConnectorEntry[]) ?? [];\n }\n\n // -- useSyncExternalStore interface ----------------------------------------\n\n /**\n * Register a change listener. Called after every resource availability change.\n *\n * Conforms to the `subscribe` parameter of React's `useSyncExternalStore`.\n *\n * @param listener - Callback invoked whenever mounts or connectors change.\n * @returns Unsubscribe function — call to stop receiving notifications.\n */\n subscribe = (listener: () => void): (() => void) => {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n };\n\n /**\n * Return the current immutable resource snapshot.\n *\n * A new object is produced lazily after each `resources_available` event.\n * Conforms to the `getSnapshot` parameter of React's `useSyncExternalStore`.\n */\n getSnapshot = (): ResourceClientSnapshot => {\n if (!this._snapshot) {\n this._snapshot = { mounts: this._mounts, connectors: this._connectors };\n }\n return this._snapshot;\n };\n\n // -- Connector config mutations --------------------------------------------\n\n /**\n * Send a `connector_config` add command to wire a new connector at runtime,\n * without restarting the session. The runner receives this command and\n * calls `ConnectorManager.connect()`, which fires a `connector_status` event\n * back to the store once the connector is live.\n *\n * @param declaration - Connector declaration (id, driver, access level, options).\n */\n addConnector(declaration: {\n id: string;\n driver: string;\n access?: \"read-only\" | \"read-write\";\n options?: Record<string, unknown>;\n }): void {\n this._send({ type: \"connector_config\", action: \"add\", declaration });\n }\n\n /**\n * Send a `connector_config` remove command to disconnect a connector by ID\n * without restarting the session.\n *\n * @param connectorId - ID of the connector to disconnect and remove.\n */\n removeConnector(connectorId: string): void {\n this._send({ type: \"connector_config\", action: \"remove\", connectorId });\n }\n\n /**\n * Send a `connector_config` refresh command to reconnect all configured\n * connectors (e.g. after a credentials change).\n */\n refreshConnectors(): void {\n this._send({ type: \"connector_config\", action: \"refresh\" });\n }\n\n // -- Cleanup ---------------------------------------------------------------\n\n /**\n * Unsubscribe from transport events, reject all pending requests, and\n * clear all change listeners.\n *\n * All in-flight `list`/`read`/`write`/`delete`/`search` calls will reject\n * with `\"ResourceClient disposed\"`.\n */\n dispose(): void {\n this._unsubEvent();\n for (const [, pending] of this._pendingRequests) {\n clearTimeout(pending.timer);\n pending.reject(new Error(\"ResourceClient disposed\"));\n }\n this._pendingRequests.clear();\n this._listeners.clear();\n }\n\n // -- Internal --------------------------------------------------------------\n\n private _handleEvent(event: AgentEvent): void {\n if (event.type === \"connector_status\") {\n const e = event as ConnectorStatusEvent;\n const existing = this.connectorStatus.get(e.connectorId);\n const next = new Map(this.connectorStatus);\n next.set(e.connectorId, {\n id: e.connectorId,\n driver:\n existing?.driver ?? this._connectors.find((c) => c.id === e.connectorId)?.driver ?? \"\",\n state: e.status,\n ...(e.error !== undefined ? { error: e.error } : {}),\n ...(e.latencyMs !== undefined ? { latencyMs: e.latencyMs } : {}),\n lastUpdated: new Date(),\n });\n this.connectorStatus = next;\n for (const listener of this._listeners) {\n listener();\n }\n return;\n }\n\n if (event.type === \"resources_available\") {\n this._mounts = event.mounts;\n this._connectors = event.connectors;\n this._snapshot = null;\n for (const listener of this._listeners) {\n listener();\n }\n return;\n }\n\n if (event.type === \"resource_response\") {\n const pending = this._pendingRequests.get(event.requestId);\n if (!pending) return;\n\n clearTimeout(pending.timer);\n this._pendingRequests.delete(event.requestId);\n\n if (event.error) {\n pending.reject(new Error(event.error));\n } else {\n pending.resolve(event);\n }\n }\n }\n\n private _request(\n connectorId: string,\n operation: \"list\" | \"read\" | \"write\" | \"delete\" | \"search\",\n path?: string,\n options?: ListOptions | SearchOptions,\n content?: ConnectorContent,\n ): Promise<ConnectorResponseEvent> {\n const requestId = crypto.randomUUID();\n\n return new Promise<ConnectorResponseEvent>((resolve, reject) => {\n const timer = setTimeout(() => {\n this._pendingRequests.delete(requestId);\n reject(\n new Error(\n `Resource request timed out after ${DEFAULT_TIMEOUT_MS}ms: ${operation} ${connectorId}${path ? ` ${path}` : \"\"}`,\n ),\n );\n }, DEFAULT_TIMEOUT_MS);\n\n this._pendingRequests.set(requestId, { resolve, reject, timer });\n\n this._send({\n type: \"resource_request\",\n requestId,\n connectorId,\n operation,\n ...(path !== undefined ? { path } : {}),\n ...(options ? { options } : {}),\n ...(content ? { content } : {}),\n });\n });\n }\n}\n","import type {\n AgentCommand,\n AgentEvent,\n AgentPhase,\n Capability,\n IncompatibleProtocolEvent,\n Message,\n ProtocolInfoEvent,\n RenderInvokedEvent,\n} from \"@skaile/workspaces/types\";\nimport type {\n AgentClientLike,\n AgentStoreOptions,\n AgentStoreSnapshot,\n ConnectionStatus,\n SubscribableStore,\n} from \"./types.js\";\n\nconst DEFAULT_PAGE_SIZE = 50;\n\n/** Conservative equality for plain JSON data; unsupported or unverifiable values fail open. */\nfunction isSameJsonValue<T>(a: T | undefined, b: T, conservativeCommandInput = false): boolean {\n const aObjects = new WeakSet<object>();\n const bObjects = new WeakSet<object>();\n\n const compare = (left: unknown, right: unknown): boolean => {\n if (left === null || right === null) return left === right;\n if (typeof left !== typeof right) return false;\n\n switch (typeof left) {\n case \"string\":\n case \"boolean\":\n return left === right;\n case \"number\":\n return (\n Number.isFinite(left) &&\n Number.isFinite(right) &&\n !Object.is(left, -0) &&\n !Object.is(right, -0) &&\n left === right\n );\n case \"object\":\n break;\n default:\n return false;\n }\n\n const leftObject = left as object;\n const rightObject = right as object;\n if (aObjects.has(leftObject) || bObjects.has(rightObject)) return false;\n if (conservativeCommandInput) {\n if (leftObject === rightObject || bObjects.has(leftObject) || aObjects.has(rightObject)) {\n return false;\n }\n }\n aObjects.add(leftObject);\n bObjects.add(rightObject);\n\n const leftIsArray = Array.isArray(leftObject);\n if (leftIsArray !== Array.isArray(rightObject)) return false;\n\n const leftPrototype = Object.getPrototypeOf(leftObject);\n const rightPrototype = Object.getPrototypeOf(rightObject);\n const leftHasPlainPrototype = leftIsArray\n ? leftPrototype === Array.prototype\n : leftPrototype === Object.prototype || leftPrototype === null;\n const rightHasPlainPrototype = leftIsArray\n ? rightPrototype === Array.prototype\n : rightPrototype === Object.prototype || rightPrototype === null;\n if (\n !leftHasPlainPrototype ||\n !rightHasPlainPrototype ||\n leftPrototype !== rightPrototype ||\n !Object.isExtensible(leftObject) ||\n !Object.isExtensible(rightObject)\n ) {\n return false;\n }\n\n const leftKeys = Reflect.ownKeys(leftObject);\n const rightKeys = Reflect.ownKeys(rightObject);\n if (\n leftKeys.length !== rightKeys.length ||\n leftKeys.some((key) => typeof key !== \"string\") ||\n rightKeys.some((key) => typeof key !== \"string\")\n ) {\n return false;\n }\n\n if (leftIsArray) {\n const leftLengthDescriptor = Object.getOwnPropertyDescriptor(leftObject, \"length\");\n const rightLengthDescriptor = Object.getOwnPropertyDescriptor(rightObject, \"length\");\n const leftLength = leftLengthDescriptor?.value;\n const rightLength = rightLengthDescriptor?.value;\n if (\n !leftLengthDescriptor ||\n !(\"value\" in leftLengthDescriptor) ||\n !leftLengthDescriptor.writable ||\n leftLengthDescriptor.enumerable ||\n leftLengthDescriptor.configurable ||\n !rightLengthDescriptor ||\n !(\"value\" in rightLengthDescriptor) ||\n !rightLengthDescriptor.writable ||\n rightLengthDescriptor.enumerable ||\n rightLengthDescriptor.configurable ||\n typeof leftLength !== \"number\" ||\n leftLength !== rightLength ||\n leftKeys.length !== leftLength + 1\n ) {\n return false;\n }\n\n for (let index = 0; index < leftLength; index++) {\n const key = String(index);\n const leftDescriptor = Object.getOwnPropertyDescriptor(leftObject, key);\n const rightDescriptor = Object.getOwnPropertyDescriptor(rightObject, key);\n if (\n !leftDescriptor?.enumerable ||\n !(\"value\" in leftDescriptor) ||\n !leftDescriptor.writable ||\n !leftDescriptor.configurable ||\n !rightDescriptor?.enumerable ||\n !(\"value\" in rightDescriptor) ||\n !rightDescriptor.writable ||\n !rightDescriptor.configurable ||\n !compare(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n }\n\n for (let index = 0; index < leftKeys.length; index++) {\n const leftKey = leftKeys[index] as string;\n const rightKey = rightKeys[index] as string;\n if (leftKey !== rightKey) return false;\n\n const leftDescriptor = Object.getOwnPropertyDescriptor(leftObject, leftKey);\n const rightDescriptor = Object.getOwnPropertyDescriptor(rightObject, rightKey);\n if (\n !leftDescriptor?.enumerable ||\n !(\"value\" in leftDescriptor) ||\n !leftDescriptor.writable ||\n !leftDescriptor.configurable ||\n !rightDescriptor?.enumerable ||\n !(\"value\" in rightDescriptor) ||\n !rightDescriptor.writable ||\n !rightDescriptor.configurable ||\n !compare(leftDescriptor.value, rightDescriptor.value)\n ) {\n return false;\n }\n }\n return true;\n };\n\n try {\n const same = compare(a, b);\n if (!same || !conservativeCommandInput) return same;\n structuredClone(a);\n structuredClone(b);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Headless reactive store for agent conversation state.\n *\n * Framework-agnostic — works with React (`useSyncExternalStore`),\n * Vue (`shallowRef` + `subscribe`), or any other UI framework.\n *\n * Accepts a minimal transport interface (`send` + `onEvent`) so it works\n * with WebSocket, tRPC, SSE, or any other delivery mechanism.\n * @docLink packages/store/concepts#agent-store\n */\nexport class AgentStore implements SubscribableStore<AgentStoreSnapshot> {\n private readonly _options: AgentStoreOptions;\n private _messages: Message[];\n private _streamingText = \"\";\n private _cancelledText = \"\";\n private _status: ConnectionStatus = \"idle\";\n private _phase: AgentPhase = \"idle\";\n private _pendingQuestion: AgentStoreSnapshot[\"pendingQuestion\"] = null;\n private _error: AgentStoreSnapshot[\"error\"] = null;\n private _isAllLoaded: boolean;\n private _seq: number;\n private _streamingFlushed = true;\n /** Shared state per store namespace — new Map instance on every mutation. */\n private _sharedState: Map<string, Record<string, unknown>> = new Map();\n /** Protocol v2 capability registry — new Map instance on every mutation. */\n private _capabilities: Map<string, Capability> = new Map();\n /** Protocol v2 active render invocations — new Map instance on every mutation. */\n private _activeRenderInvocations: Map<string, RenderInvokedEvent> = new Map();\n /** Protocol v2 — most recent `protocol_info` event from the runner. */\n private _protocolInfo: ProtocolInfoEvent | null = null;\n /** Protocol v2 — latest incompatible-protocol notice. */\n private _incompatibleProtocol: IncompatibleProtocolEvent | null = null;\n\n private _snapshot: AgentStoreSnapshot | null = null;\n private readonly _listeners = new Set<() => void>();\n private readonly _unsubEvent: () => void;\n private readonly _unsubStatus: (() => void) | undefined;\n\n /**\n * @param options - Store configuration including transport and optional pagination support.\n */\n constructor(options: AgentStoreOptions) {\n this._options = options;\n this._messages = options.initialMessages ? [...options.initialMessages] : [];\n this._isAllLoaded = !options.loadMessages;\n this._seq = this._messages.reduce((max, m) => Math.max(max, m.seq), 0);\n\n this._unsubEvent = options.onEvent((event) => this._handleEvent(event));\n this._unsubStatus = options.onStatusChange?.((status) => this.setStatus(status));\n }\n\n // -- Reactive state --------------------------------------------------------\n\n /** Accumulated conversation messages, oldest first. */\n get messages(): readonly Message[] {\n return this._messages;\n }\n\n /** Text currently streaming from the agent. Empty when not streaming. */\n get streamingText(): string {\n return this._streamingText;\n }\n\n /** Current connection lifecycle state. */\n get status(): ConnectionStatus {\n return this._status;\n }\n\n /** Current agent execution phase (e.g. `\"idle\"`, `\"thinking\"`, `\"executing\"`). */\n get phase(): AgentPhase {\n return this._phase;\n }\n\n /** The pending question the agent is waiting for the user to answer, or null. */\n get pendingQuestion(): AgentStoreSnapshot[\"pendingQuestion\"] {\n return this._pendingQuestion;\n }\n\n /** Most recent error, or null when no error is active. */\n get error(): AgentStoreSnapshot[\"error\"] {\n return this._error;\n }\n\n /** Partial text that was visible when the user cancelled. Empty when not cancelled. */\n get cancelledText(): string {\n return this._cancelledText;\n }\n\n /** True when there are no more older messages to load via pagination. */\n get isAllLoaded(): boolean {\n return this._isAllLoaded;\n }\n\n // -- Commands --------------------------------------------------------------\n\n /**\n * Send a user prompt to the agent and optimistically update local state.\n *\n * Clears any previous error and cancelled text, sets phase to `\"thinking\"`,\n * and appends the prompt as a local message before forwarding to the agent.\n *\n * @param text - The user's prompt text.\n */\n prompt(text: string): void {\n // A prompt sent mid-turn (sender interjecting while the agent streams) is a\n // boundary: finalize the in-flight text before this prompt so the two don't\n // merge into one bubble. No-op at turn start (nothing streaming).\n this._flushStreaming();\n this._error = null;\n this._cancelledText = \"\";\n this._streamingFlushed = false;\n this._phase = \"thinking\";\n this._appendMessage({ type: \"prompt\", prompt: text }, \"user\");\n this._options.send({ type: \"prompt\", prompt: text });\n this._notify();\n }\n\n /**\n * Send a reply to the agent's pending question.\n *\n * Clears the pending question locally before forwarding the reply command.\n *\n * @param answer - The user's answer text.\n * @param question - The sub-question being answered, verbatim from its\n * `question` event. Required for correctness in hosts that surface several\n * queued questions at once ({@link pendingQuestion} tracks only the latest,\n * so those hosts drive this from their own message history): without it the\n * agent files the answer under its next unanswered sub-question, which\n * mismatches any non-sequential reply.\n */\n reply(answer: string, question?: string): void {\n this._pendingQuestion = null;\n // Answering a pending question resumes the agent turn — restore the busy\n // phase (mirrors prompt()) so the thinking indicator reappears immediately\n // rather than after the agent's first resumed event lands.\n this._phase = \"thinking\";\n const command = {\n type: \"reply\",\n answer,\n ...(question !== undefined ? { question } : {}),\n } as const;\n this._appendMessage(command, \"user\");\n this._options.send(command);\n this._notify();\n }\n\n /**\n * Cancel the current agent turn.\n *\n * Preserves partial streaming text in {@link cancelledText} so the UI can\n * display it. Clears streaming state, sets phase to `\"cancelling\"` (not\n * yet confirmed idle — see {@link AgentPhase}), and sends a `cancel`\n * command to the agent.\n */\n cancel(): void {\n // Preserve partial streaming text so the UI can still display it\n this._cancelledText = this._streamingText;\n this._streamingText = \"\";\n this._streamingFlushed = true;\n this._phase = \"cancelling\";\n this._options.send({ type: \"cancel\" });\n this._notify();\n }\n\n /**\n * Update shared state for a store namespace.\n *\n * Sends a `state_update` command to the agent and optimistically\n * updates local state so the change is reflected immediately.\n *\n * @param store - Store namespace (e.g. \"app\", \"component:render-123\").\n * @param state - Full state snapshot (replaces previous).\n */\n updateState(store: string, state: Record<string, unknown>): void {\n this._options.send({ type: \"state_update\", store, state });\n if (isSameJsonValue(this._sharedState.get(store), state, true)) return;\n // Optimistic local update\n this._sharedState = new Map(this._sharedState);\n this._sharedState.set(store, state);\n this._notify();\n }\n\n /**\n * Send an arbitrary command to the agent.\n *\n * Use this for commands that don't have a dedicated convenience method\n * (e.g. `ui_interaction`). No local state changes — the command is\n * forwarded as-is to the transport.\n *\n * @param cmd - The command to send.\n */\n send(cmd: AgentCommand): void {\n this._options.send(cmd);\n }\n\n /**\n * Load the previous page of messages and prepend them to the current list.\n *\n * No-op when `loadMessages` was not provided at construction time or when\n * all history has already been loaded ({@link isAllLoaded} is true).\n * Sets {@link isAllLoaded} to true once the server returns fewer messages\n * than the configured page size.\n */\n async loadPreviousMessages(): Promise<void> {\n if (!this._options.loadMessages || this._isAllLoaded) return;\n\n const pageSize = this._options.pageSize ?? DEFAULT_PAGE_SIZE;\n const before = this._messages.length > 0 ? this._messages[0].seq : undefined;\n const older = await this._options.loadMessages({ before, limit: pageSize });\n\n if (older.length < pageSize) this._isAllLoaded = true;\n\n const existingIds = new Set(this._messages.map((m) => m.id));\n const unique = older.filter((m) => !existingIds.has(m.id));\n this._messages = [...unique, ...this._messages];\n\n this._notify();\n }\n\n // -- External control ------------------------------------------------------\n\n /**\n * Programmatically update the connection status.\n *\n * Called by transport wrappers that cannot use the `onStatusChange`\n * callback (e.g. tRPC subscriptions that track status externally).\n *\n * Writing the status the store already holds is a no-op: it neither rotates\n * the snapshot nor notifies listeners.\n *\n * @param status - The new connection status.\n */\n setStatus(status: ConnectionStatus): void {\n if (this._status === status) return;\n this._status = status;\n this._notify();\n }\n\n // -- useSyncExternalStore interface ----------------------------------------\n\n /**\n * Register a change listener. Called synchronously after every state change.\n *\n * Conforms to the `subscribe` parameter of React's `useSyncExternalStore`.\n *\n * @param listener - Callback invoked whenever state changes.\n * @returns Unsubscribe function — call to stop receiving notifications.\n */\n subscribe = (listener: () => void): (() => void) => {\n this._listeners.add(listener);\n return () => this._listeners.delete(listener);\n };\n\n /**\n * Return the current immutable state snapshot.\n *\n * A new object is produced lazily on the first call after each state change.\n * Subsequent calls return the same cached object until the next change.\n * Conforms to the `getSnapshot` parameter of React's `useSyncExternalStore`.\n */\n getSnapshot = (): AgentStoreSnapshot => {\n if (!this._snapshot) {\n this._snapshot = {\n messages: this._messages,\n streamingText: this._streamingText,\n cancelledText: this._cancelledText,\n status: this._status,\n phase: this._phase,\n pendingQuestion: this._pendingQuestion,\n error: this._error,\n isAllLoaded: this._isAllLoaded,\n sharedState: this._sharedState,\n capabilities: this._capabilities,\n activeRenderInvocations: this._activeRenderInvocations,\n protocolInfo: this._protocolInfo,\n incompatibleProtocol: this._incompatibleProtocol,\n };\n }\n return this._snapshot;\n };\n\n // -- Cleanup ---------------------------------------------------------------\n\n /**\n * Unsubscribe from transport events and clear all change listeners.\n *\n * Call this when the component or service that owns the store unmounts or\n * shuts down to prevent memory leaks.\n */\n dispose(): void {\n this._unsubEvent();\n this._unsubStatus?.();\n this._listeners.clear();\n }\n\n // -- Factory ---------------------------------------------------------------\n\n /**\n * Create an {@link AgentStore} connected to a duck-typed agent client.\n *\n * Adapts the client's `send`/`onEvent`/`offEvent` API to the\n * {@link StoreTransport} interface expected by the constructor, without\n * creating a hard runtime dependency on `@skaile/workspaces/client`.\n *\n * @param client - Any object implementing {@link AgentClientLike}.\n * @param opts - Optional store configuration.\n * @param opts.sessionId - Session ID for message envelopes (defaults to a new UUID).\n * @param opts.initialMessages - Messages to pre-populate the store with.\n *\n * @example\n * ```ts\n * const store = AgentStore.fromClient(agentClient, { sessionId: 'sess-123' })\n * ```\n */\n static fromClient(\n client: AgentClientLike,\n opts?: { sessionId?: string; initialMessages?: Message[] },\n ): AgentStore {\n return new AgentStore({\n sessionId: opts?.sessionId ?? crypto.randomUUID(),\n send: (cmd) => client.send(cmd),\n onEvent: (handler) => {\n client.onEvent(handler);\n return () => client.offEvent(handler);\n },\n initialMessages: opts?.initialMessages,\n });\n }\n\n // -- Internal --------------------------------------------------------------\n\n private _handleEvent(event: AgentEvent): void {\n switch (event.type) {\n case \"text\":\n this._cancelledText = \"\";\n this._streamingText += event.content;\n this._streamingFlushed = false;\n break;\n\n case \"finished\":\n this._cancelledText = \"\";\n this._flushStreaming();\n this._appendMessage(event);\n // A cancelled finished is synthetic (persisted immediately for reload-\n // durability) and precedes the driver's real abort/kill sequence — stay\n // \"cancelling\" until the later, genuine status event reports \"idle\".\n if (!event.cancelled) this._phase = \"idle\";\n this._pendingQuestion = null;\n break;\n\n case \"status\":\n // While cancelling, the driver's interrupt/unwind window can still emit\n // stale \"working\" statuses for already-buffered tool activity — ignore\n // anything but the genuine idle confirmation.\n if (this._phase === \"cancelling\" && event.phase !== \"idle\") return;\n // The bridge re-emits phase:\"working\" on every tool call, so most status\n // events in a turn carry the phase we already hold. `_notify()` rotates\n // the snapshot, so notifying for them re-renders consumers for nothing.\n if (this._phase === event.phase) return;\n this._phase = event.phase;\n break;\n\n case \"user_message\":\n // A peer's message mid-turn is a boundary: finalize the in-flight text\n // so it renders before the interjection. Flush-only — the peer message\n // is delivered via the host's history, not this transient echo. The\n // flush is internally conditional, so an echo arriving while nothing is\n // streaming (the common case — peers talk between turns) changed no\n // state and notifying for it was a pure fanout.\n if (!this._flushStreaming()) return;\n break;\n\n case \"tool_call\":\n case \"tool_result\":\n case \"file_changed\":\n case \"subagent\":\n case \"dev_server\":\n case \"handoff\":\n case \"question_reply\":\n // Flush in-flight text first so each text block becomes its own\n // Message, interleaved with tool activity in order — otherwise text\n // before and after a tool call merges into one wall-of-text blob.\n this._flushStreaming();\n this._appendMessage(event);\n break;\n\n case \"question\":\n // A pending question is a human-in-the-loop pause — the agent is waiting\n // for the user, not working. Reset to idle (like finished/error) so any\n // phase-derived busy indicator clears until the user replies.\n this._flushStreaming();\n this._phase = \"idle\";\n this._pendingQuestion = event;\n this._appendMessage(event);\n break;\n\n case \"error\":\n this._error = { message: event.message, fatal: event.fatal };\n this._streamingText = \"\";\n this._streamingFlushed = true;\n this._phase = \"idle\";\n this._appendMessage(event);\n break;\n\n case \"state_changed\": {\n // Accumulate state per store namespace (notify only — no message).\n // Re-emits of unchanged state are routine, not exceptional: `serve.ts`\n // replays every namespace on connect (`buildStoreSnapshotReplay`), on a\n // seeded execution, on re-registering an already-registered store, and\n // immediately after registration — and the `xstate-store` adapter is\n // equality-free, so writing a key its current value emits too. Each of\n // those rebuilt the Map and rotated the snapshot for identical state.\n if (isSameJsonValue(this._sharedState.get(event.store), event.state)) return;\n this._sharedState = new Map(this._sharedState);\n this._sharedState.set(event.store, event.state);\n break;\n }\n\n // ── Protocol v2 ────────────────────────────────────────────────────────\n\n case \"capability_register\": {\n // TRANSIENT — accumulate v2 capabilities into the registry (no message).\n // The gateway replays the whole set on every (re)attach; a byte-identical\n // replay must not rotate the Map identity or notify, or a reconnect storm\n // compounds into an unbounded render loop in consumers.\n if (\n event.capabilities.every((cap) => isSameJsonValue(this._capabilities.get(cap.name), cap))\n ) {\n return;\n }\n this._capabilities = new Map(this._capabilities);\n for (const cap of event.capabilities) {\n this._capabilities.set(cap.name, cap);\n }\n break;\n }\n\n case \"capability_deregister\": {\n // TRANSIENT — drop capabilities by name. Names we never had are a no-op:\n // rebuilding the Map for them would notify with an identical registry.\n const present = event.names.filter((name) => this._capabilities.has(name));\n if (present.length === 0) return;\n this._capabilities = new Map(this._capabilities);\n for (const name of present) {\n this._capabilities.delete(name);\n }\n break;\n }\n\n case \"render_invoked\":\n // TRANSIENT — record latest render invocation (frontend pairs with\n // the matching `Capability.render` for placement).\n this._activeRenderInvocations = new Map(this._activeRenderInvocations);\n this._activeRenderInvocations.set(event.callId, event);\n break;\n\n case \"protocol_info\": {\n // TRANSIENT — runner announced its protocol version. It announces on\n // every attach, so tab mounts, StrictMode remounts and SSE reconnects\n // almost always carry the version we already hold. `ProtocolInfoEvent`\n // is nothing but `version`, and `ProtocolVersion` is exactly three\n // numbers, so the field comparison is complete, not conservative.\n //\n // A fresh announcement also retires any incompatibility notice: the\n // platform restarts the session on `incompatible_protocol`, and this\n // event is the replacement container introducing itself. Nothing cleared\n // `_incompatibleProtocol` before, so the restart banner was sticky for\n // the life of the store even though the platform's debug pane documents\n // this clear as already happening. Guarding without clearing would make\n // that permanent, since a repeat announcement would never get here.\n const held = this._protocolInfo?.version;\n const sameVersion =\n held !== undefined &&\n held.major === event.version.major &&\n held.minor === event.version.minor &&\n held.patch === event.version.patch;\n if (sameVersion && this._incompatibleProtocol === null) return;\n // Keep the held event object when the version is unchanged so consumers\n // with an effect keyed on `snapshot.protocolInfo` do not re-fire.\n if (!sameVersion) this._protocolInfo = event;\n this._incompatibleProtocol = null;\n break;\n }\n\n case \"incompatible_protocol\":\n // TRANSIENT — runner detected version drift; platform restarts session.\n this._incompatibleProtocol = event;\n break;\n\n case \"capability_invoked\":\n // Backend intercepts client-side invocations and dispatches them\n // through V2CapabilityRegistryService — frontends should not see\n // these. Drop silently if one slips through.\n return;\n\n case \"resource_response\":\n case \"resources_available\":\n // Transient — handled by ResourceClient, not AgentStore\n return;\n\n default:\n // The switch names 22 of `AgentEvent`'s 56 members. The other 34 —\n // `log_entry` above all, one per line of container output — hold no\n // AgentStore state, so falling through to the trailing `_notify()`\n // rotated the snapshot and re-rendered every consumer for state that\n // had not changed. Unlike the guarded cases this was not a replay\n // artifact: it happened on every single occurrence. Hosts that need\n // these events (log panels, mount indicators, typing bubbles) read them\n // off the transport upstream of the store, not out of the snapshot.\n //\n // Deliberately not an `assertNever` exhaustiveness check: that is a\n // compile error while 34 members are unnamed, and naming all 56 would\n // enumerate events the store holds no state for just to satisfy it.\n return;\n }\n\n this._notify();\n }\n\n /**\n * Finalize buffered streaming text as a `text` Message.\n *\n * @returns true when text was flushed; false when there was nothing to flush,\n * so callers can skip a notify that would change nothing.\n */\n private _flushStreaming(): boolean {\n if (this._streamingFlushed || !this._streamingText) return false;\n this._appendMessage({ type: \"text\", content: this._streamingText });\n this._streamingText = \"\";\n this._streamingFlushed = true;\n return true;\n }\n\n private _appendMessage(payload: AgentCommand | AgentEvent, senderId?: string): void {\n this._seq++;\n this._messages = [\n ...this._messages,\n {\n id: crypto.randomUUID(),\n seq: this._seq,\n timestamp: new Date().toISOString(),\n sessionId: this._options.sessionId,\n ...(senderId ? { senderId } : {}),\n payload,\n },\n ];\n }\n\n private _notify(): void {\n this._snapshot = null;\n for (const listener of this._listeners) {\n listener();\n }\n }\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { initTelemetry } from './chunk-4R6DROGN.js';
2
2
  import { parseSkillFrontmatter, validateFlowVersions } from './chunk-4VTBZ2MF.js';
3
- import { FlowAdapter, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner } from './chunk-XDIVJ7G6.js';
3
+ import { FlowAdapter, SessionNodeExecutor, SessionSubpromptRunner, SessionInlineSubFlowRunner, driveOrchestratorTurn } from './chunk-SHCY6EUI.js';
4
4
  import { loadFlow, flowLookupRoots, findFlowFileInRoots, FLOW_FILE_EXTENSIONS } from './chunk-HBF7A7JB.js';
5
- import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-HGFKNJA5.js';
5
+ import { renderStimulusPrompt } from './chunk-HGFKNJA5.js';
6
6
  import { flowSkillVersionPins } from './chunk-ELPR5XBG.js';
7
7
  import { resolveSettings, resolveApiKey } from './chunk-AZPXCHDK.js';
8
8
  import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-IP3GXHOB.js';
@@ -165,18 +165,22 @@ async function runFlow(opts) {
165
165
  await driver.start();
166
166
  driverStarted = true;
167
167
  };
168
+ const emitFlowPrompt = (event) => {
169
+ opts.onEvent?.(event);
170
+ };
168
171
  const inlineSubFlowRunner = new SessionInlineSubFlowRunner({
169
172
  resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),
170
173
  nodeExecutor,
171
174
  subpromptRunner,
172
175
  driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {
173
176
  await ensureDriverStarted();
174
- await awaitAgentEnd(
175
- driver,
176
- buildOrchestratorPrompt(childFlow, execution, stimulus),
177
- opts.onEvent,
178
- turnTimeoutMs
179
- );
177
+ await driveOrchestratorTurn({
178
+ flow: childFlow,
179
+ execution,
180
+ stimulus,
181
+ emit: emitFlowPrompt,
182
+ deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs)
183
+ });
180
184
  }
181
185
  });
182
186
  let flowAdapterRef = null;
@@ -207,9 +211,14 @@ async function runFlow(opts) {
207
211
  return;
208
212
  }
209
213
  if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;
210
- const fullPrompt = buildOrchestratorPrompt(flow, execution, stimulus);
211
214
  await ensureDriverStarted();
212
- await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);
215
+ await driveOrchestratorTurn({
216
+ flow,
217
+ execution,
218
+ stimulus,
219
+ emit: emitFlowPrompt,
220
+ deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs)
221
+ });
213
222
  },
214
223
  log: flowLog
215
224
  });
@@ -512,5 +521,5 @@ function walkForSkill(dir, skillId) {
512
521
  }
513
522
 
514
523
  export { resolveFlowPath, resumeFlow, runFlow };
515
- //# sourceMappingURL=chunk-R6OLT7E4.js.map
516
- //# sourceMappingURL=chunk-R6OLT7E4.js.map
524
+ //# sourceMappingURL=chunk-6JKBM75L.js.map
525
+ //# sourceMappingURL=chunk-6JKBM75L.js.map