@skaile/workspaces 3.16.0 → 3.16.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/dist/{asset-feeds-6UC7CUTI.js → asset-feeds-TS76HDGE.js} +4 -4
- package/dist/{asset-feeds-6UC7CUTI.js.map → asset-feeds-TS76HDGE.js.map} +1 -1
- package/dist/asset-manager/index.js +1 -1
- package/dist/bridge/index.js +1 -1
- package/dist/bridge/src/normalizer.d.ts.map +1 -1
- package/dist/{chunk-X2665LP2.js → chunk-4J24AU4Q.js} +3 -3
- package/dist/{chunk-X2665LP2.js.map → chunk-4J24AU4Q.js.map} +1 -1
- package/dist/{chunk-JNCORFRK.js → chunk-5FCBPIOK.js} +8 -4
- package/dist/chunk-5FCBPIOK.js.map +1 -0
- package/dist/{chunk-ER4UOIUS.js → chunk-775OMGVP.js} +3 -3
- package/dist/{chunk-ER4UOIUS.js.map → chunk-775OMGVP.js.map} +1 -1
- package/dist/{chunk-PMYZRX6M.js → chunk-EVQDXN27.js} +2 -2
- package/dist/{chunk-PMYZRX6M.js.map → chunk-EVQDXN27.js.map} +1 -1
- package/dist/{chunk-MFWIWPJP.js → chunk-GP2AYOC2.js} +2 -2
- package/dist/{chunk-MFWIWPJP.js.map → chunk-GP2AYOC2.js.map} +1 -1
- package/dist/{chunk-IVWJHELM.js → chunk-OEK2ACRR.js} +6 -6
- package/dist/{chunk-IVWJHELM.js.map → chunk-OEK2ACRR.js.map} +1 -1
- package/dist/{chunk-6HTQNNOX.js → chunk-PCDNZROC.js} +6 -6
- package/dist/{chunk-6HTQNNOX.js.map → chunk-PCDNZROC.js.map} +1 -1
- package/dist/{chunk-SZ7VJQK3.js → chunk-QA52GQQN.js} +6 -6
- package/dist/{chunk-SZ7VJQK3.js.map → chunk-QA52GQQN.js.map} +1 -1
- package/dist/{chunk-GWQZ2ECO.js → chunk-QG6C3XOS.js} +3 -3
- package/dist/{chunk-GWQZ2ECO.js.map → chunk-QG6C3XOS.js.map} +1 -1
- package/dist/{chunk-3DNCPQAR.js → chunk-RTM4SFLA.js} +9 -3
- package/dist/chunk-RTM4SFLA.js.map +1 -0
- package/dist/{chunk-KLDWNSDN.js → chunk-U2UNQBXB.js} +3 -3
- package/dist/{chunk-KLDWNSDN.js.map → chunk-U2UNQBXB.js.map} +1 -1
- package/dist/{chunk-CL4TYERP.js → chunk-VC2MWHRH.js} +3 -3
- package/dist/{chunk-CL4TYERP.js.map → chunk-VC2MWHRH.js.map} +1 -1
- package/dist/cli/index.js +28 -28
- package/dist/connectors/index.js +2 -2
- package/dist/{ensure-sources-VJZUHSFZ.js → ensure-sources-I2F6XBDJ.js} +4 -4
- package/dist/{ensure-sources-VJZUHSFZ.js.map → ensure-sources-I2F6XBDJ.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +2 -2
- package/dist/factory-assets/connectors/deploy.js +2 -2
- package/dist/factory-assets/connectors/devserver.js +2 -2
- package/dist/factory-assets/connectors/flow/adapter.js +2 -2
- package/dist/factory-assets/connectors/flow/run-flow.js +3 -3
- package/dist/factory-assets/connectors/flow.js +2 -2
- package/dist/factory-assets/connectors/git.js +2 -2
- package/dist/factory-assets/connectors/gmail.js +2 -2
- package/dist/factory-assets/connectors/googledrive.js +2 -2
- package/dist/factory-assets/connectors/local.js +2 -2
- package/dist/factory-assets/connectors/mattermost.js +2 -2
- package/dist/factory-assets/connectors/memory.js +2 -2
- package/dist/factory-assets/connectors/minio.js +2 -2
- package/dist/factory-assets/connectors/postgres.js +2 -2
- package/dist/factory-assets/connectors/s3.js +2 -2
- package/dist/factory-assets/connectors/sharepoint.js +2 -2
- package/dist/factory-assets/connectors/sqlite.js +2 -2
- package/dist/factory-assets/connectors/static-server.js +2 -2
- package/dist/factory-assets/connectors/tunnel.js +2 -2
- package/dist/factory-assets/connectors/webdav.js +2 -2
- package/dist/factory-assets/connectors/xstate-store.js +2 -2
- package/dist/factory-assets/connectors/xstate.js +2 -2
- package/dist/{helpers-EEYMGGLO.js → helpers-Y66CM6LO.js} +4 -4
- package/dist/{helpers-EEYMGGLO.js.map → helpers-Y66CM6LO.js.map} +1 -1
- package/dist/{library-publish-37UBVMC3.js → library-publish-SNUOWBUD.js} +6 -6
- package/dist/{library-publish-37UBVMC3.js.map → library-publish-SNUOWBUD.js.map} +1 -1
- package/dist/{open-library-JYVUN4CY.js → open-library-IO4TSO2H.js} +5 -5
- package/dist/{open-library-JYVUN4CY.js.map → open-library-IO4TSO2H.js.map} +1 -1
- package/dist/{project-DKQACM3N.js → project-OR524CQ3.js} +5 -5
- package/dist/{project-DKQACM3N.js.map → project-OR524CQ3.js.map} +1 -1
- package/dist/runner/index.js +5 -5
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/bridge.js +1 -1
- package/dist/sdk/index.js +5 -5
- package/dist/sdk/runner.js +5 -5
- package/dist/sdk/store.js +1 -1
- package/dist/{setup-7FJNMKFA.js → setup-5OG442AZ.js} +3 -3
- package/dist/{setup-7FJNMKFA.js.map → setup-5OG442AZ.js.map} +1 -1
- package/dist/{source-CT6RH3CJ.js → source-DTV7VK3C.js} +6 -6
- package/dist/{source-CT6RH3CJ.js.map → source-DTV7VK3C.js.map} +1 -1
- package/dist/{source-manifest-publish-VBENANBT.js → source-manifest-publish-HC3K7D63.js} +7 -7
- package/dist/{source-manifest-publish-VBENANBT.js.map → source-manifest-publish-HC3K7D63.js.map} +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/src/store.d.ts.map +1 -1
- package/dist/tui/index.js +5 -5
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3DNCPQAR.js.map +0 -1
- package/dist/chunk-JNCORFRK.js.map +0 -1
package/dist/{source-manifest-publish-VBENANBT.js.map → source-manifest-publish-HC3K7D63.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../cli/src/commands/source-manifest-publish.ts"],"names":[],"mappings":";;;;;;;;;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a,IAAA,CAAK,KAAA,GAAQ,QAAA,CAAS,IAAA,CAAK,KAAK,CAAA,GAAI,MAAA;AACvD,EAAA,MAAM,cAAc,MAAM,GAAA,CAAI,gBAAA,CAAiB,MAAA,CAAO,EAAE,CAAA,EAAG,MAAA;AAAA,IACzD,CAAC,CAAA,KAAM,CAAA,CAAE,cAAc,CAAC,UAAA,IAAc,EAAE,IAAA,KAAS,UAAA;AAAA,GACnD;AACA,EAAA,IAAI,UAAA,CAAW,WAAW,CAAA,EAAG;AAC3B,IAAA,OAAA,CAAQ,qDAAgD,CAAA;AACxD,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,KAAA,MAAW,KAAK,UAAA,EAAY;AAC1B,IAAA,IAAI;AACF,MAAA,MAAM,GAAA,CAAI,cAAA,CAAe,CAAA,CAAE,EAAE,CAAA;AAC7B,MAAA,MAAA,CAAO,KAAK,CAAA,EAAG,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,CAAE,CAAA;AAAA,IACnC,SAAS,GAAA,EAAK;AACZ,MAAA,OAAA;AAAA,QACE,CAAA,eAAA,EAAkB,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OACzF;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA,UAAA,CAAY,CAAA;AACzC,EAAA,KAAA,MAAW,CAAA,IAAK,MAAA,EAAQ,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC1C","file":"source-manifest-publish-VBENANBT.js","sourcesContent":["/**\n * `skaile source manifest publish` / `yank` — the curator-publish flow. Takes a\n * locally-curated sidecar manifest (over a foreign public GitHub repo) and:\n *\n * 1. Pushes the curated `skaile.manifest.yaml` to the curator's OWN public\n * \"sidecar\" repo (bytes stay in the foreign source; the sidecar holds only\n * the manifest pointing at it).\n * 2. Registers the foreign source + the sidecar (url + pinned commit) with the\n * store, syncs it, and publishes each curated asset.\n *\n * `yank` is the inverse: unpublish each currently-published asset of the source.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * (default HTTP client); git side-effects go through an injectable `spawn`. Both\n * seams keep the pure helpers + orchestration unit/integration-testable without a\n * live store or a real remote.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport {\n decodeSkaileManifest,\n encodeSkaileManifest,\n type SkPublishManifest,\n sourceCacheKey,\n} from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { makeHttpPublisherClient, type PublisherClient } from \"../store-publisher.ts\";\nimport { isStoreAuthenticated } from \"../store-client.ts\";\nimport { bareName, publishToStore, refFor } from \"./publish-core.ts\";\nimport { sourceClonePath } from \"./source.ts\";\nimport { resolveSourceArg } from \"./source-manifest.ts\";\n\n/** The fixed filename a sidecar repo carries at its root. */\nconst SIDECAR_MANIFEST_FILENAME = \"skaile.manifest.yaml\";\n\n/** Injectable spawn contract — the subset of `spawnSync` these helpers use. */\ntype SpawnLike = typeof spawnSync;\n\n/**\n * Return a copy of `manifest` normalized for publication under `namespace`:\n * the top-level `publisher` is set to `namespace` and every per-asset\n * `publisher` override is removed so all assets inherit the top-level one.\n * Pure — the input is not mutated.\n */\nexport function normalizePublishedManifest(\n manifest: SkPublishManifest,\n namespace: string,\n): SkPublishManifest {\n const assets = (manifest.assets ?? []).map((a) => {\n const { publisher: _drop, ...rest } = a;\n return rest;\n });\n return { ...manifest, publisher: namespace, assets };\n}\n\n// ── Sidecar-repo association (~/.skaile/settings.json) ────────────────────────\n\n/**\n * Path to the user settings file — the same `~/.skaile/settings.json` the store\n * client reads tokens from. Resolves the `.skaile` root exactly as `getStoreRoot`\n * does (`SKAILE_HOME` when set — it IS the `.skaile` dir — else `~/.skaile`), so\n * the sidecar association lives beside the store manifests under one convention\n * and tests isolate through the same `SKAILE_HOME` seam.\n */\nfunction settingsFile(): string {\n const root = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\n return join(root, \"settings.json\");\n}\n\nfunction readSettings(): Record<string, any> {\n const file = settingsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, \"utf-8\"));\n } catch {\n return {};\n }\n}\n\n/**\n * The sidecar repo URL previously associated with a source `slug`, if any.\n * Reads `settings.sidecarRepos?.[slug]?.repo`.\n */\nexport function getSidecarRepo(slug: string): string | undefined {\n const settings = readSettings();\n return settings.sidecarRepos?.[slug]?.repo;\n}\n\n/**\n * Persist the sidecar repo URL for a source `slug`, preserving every other\n * settings key. Stored as an object (`{ repo }`) so a `path` (or other fields)\n * can be added later without a schema migration.\n */\nexport function saveSidecarRepo(slug: string, repo: string): void {\n const file = settingsFile();\n mkdirSync(dirname(file), { recursive: true });\n const settings = readSettings();\n const sidecarRepos = { ...(settings.sidecarRepos ?? {}) };\n sidecarRepos[slug] = { ...(sidecarRepos[slug] ?? {}), repo };\n settings.sidecarRepos = sidecarRepos;\n writeFileSync(file, JSON.stringify(settings, null, 2), \"utf-8\");\n}\n\n// ── Sidecar push ──────────────────────────────────────────────────────────────\n\n/**\n * Run a git command in `cwd` via the injected spawn, throwing with the captured\n * stderr on failure. Returns trimmed stdout.\n */\nfunction git(spawn: SpawnLike, cwd: string, args: string[]): string {\n const res = spawn(\"git\", [\"-C\", cwd, ...args], { encoding: \"utf-8\" });\n if (res.status !== 0) {\n const stderr = (res.stderr ?? \"\").toString().trim();\n throw new Error(`git ${args.join(\" \")} failed: ${stderr || `exit ${res.status}`}`);\n }\n return (res.stdout ?? \"\").toString().trim();\n}\n\n/**\n * Clone the curator's sidecar repo, write the curated manifest at its root, and\n * commit + push. Returns the pushed commit sha (used to pin the store source).\n *\n * Idempotent re-publish: when the manifest is unchanged `git commit` fails with\n * \"nothing to commit\" — we swallow that and return the current HEAD so a no-op\n * re-run still yields a valid pin. Any push/auth failure surfaces as a thrown\n * Error carrying git's stderr.\n */\nexport function pushSidecarManifest(opts: {\n sidecarRepoUrl: string;\n manifestText: string;\n spawn?: SpawnLike;\n}): { commitSha: string } {\n const spawn = opts.spawn ?? spawnSync;\n // Dedicated dir next to the source clone cache; wipe any stale clone first so\n // a re-publish always starts from a clean shallow checkout of the remote.\n const cloneDir = `${sourceClonePath(sourceCacheKey(opts.sidecarRepoUrl))}-sidecar-push`;\n rmSync(cloneDir, { recursive: true, force: true });\n mkdirSync(dirname(cloneDir), { recursive: true });\n\n // The clone is scratch — always remove it afterwards (success or failure) so a\n // failed push never leaves a stale checkout in the cache dir.\n try {\n const cloneRes = spawn(\"git\", [\"clone\", \"--depth\", \"1\", opts.sidecarRepoUrl, cloneDir], {\n encoding: \"utf-8\",\n });\n if (cloneRes.status !== 0) {\n const stderr = (cloneRes.stderr ?? \"\").toString().trim();\n throw new Error(\n `git clone ${opts.sidecarRepoUrl} failed: ${stderr || `exit ${cloneRes.status}`}`,\n );\n }\n\n writeFileSync(join(cloneDir, SIDECAR_MANIFEST_FILENAME), opts.manifestText, \"utf-8\");\n git(spawn, cloneDir, [\"add\", SIDECAR_MANIFEST_FILENAME]);\n\n // Fixed bot identity via -c so the commit succeeds regardless of the curator's\n // git config (the sidecar push is a machine action, not authored work).\n const commitRes = spawn(\n \"git\",\n [\n \"-C\",\n cloneDir,\n \"-c\",\n \"user.email=publish@skaile.store\",\n \"-c\",\n \"user.name=skaile\",\n \"commit\",\n \"-m\",\n \"chore(sidecar): publish curated manifest\",\n ],\n { encoding: \"utf-8\" },\n );\n if (commitRes.status !== 0) {\n const out = `${commitRes.stdout ?? \"\"}${commitRes.stderr ?? \"\"}`;\n // Nothing changed → idempotent re-publish; keep the existing HEAD.\n if (!/nothing to commit/i.test(out)) {\n throw new Error(`git commit failed: ${out.trim() || `exit ${commitRes.status}`}`);\n }\n } else {\n // `push origin HEAD` (not a bare `push`) so a fresh sidecar repo with an\n // unborn/renamed default branch still gets its branch created on the remote.\n git(spawn, cloneDir, [\"push\", \"origin\", \"HEAD\"]);\n }\n\n return { commitSha: git(spawn, cloneDir, [\"rev-parse\", \"HEAD\"]) };\n } finally {\n rmSync(cloneDir, { recursive: true, force: true });\n }\n}\n\n// ── Orchestration ───────────────────────────────────────────────────────────\n\n/**\n * `source manifest publish <src>` — publish a curated sidecar manifest to the\n * store. See the module header for the full flow. Store calls go through\n * `client` (default HTTP); git side-effects through `spawn` (default\n * `spawnSync`). The auth gate is enforced only for the default HTTP client so\n * injected fakes bypass it.\n */\nexport async function runPublish(\n arg: string,\n opts: {\n projectDir: string;\n as?: string;\n sidecarRepo?: string;\n ref?: string;\n dryRun?: boolean;\n },\n client?: PublisherClient,\n spawn: SpawnLike = spawnSync,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug, manifestFile } = resolveSourceArg(arg, opts.projectDir);\n\n if (!existsSync(manifestFile)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(manifestFile)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n const { manifest, diagnostics } = decodeSkaileManifest(readFileSync(manifestFile, \"utf-8\"));\n if (diagnostics.some((d) => d.severity === \"error\")) {\n for (const d of diagnostics.filter((x) => x.severity === \"error\")) {\n logErr(`${d.code}: ${d.message}`);\n }\n logErr(\n \"The curated manifest has errors — fix them with `skaile source manifest edit` / \" +\n \"`verify` before publishing.\",\n );\n process.exit(1);\n }\n\n // A real publish makes store calls (+ `me()` when `--as` is omitted), so it\n // needs a token. `--dry-run` is an offline preview: never gate it on auth.\n const authed = injected || isStoreAuthenticated();\n if (!opts.dryRun && !authed) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n // Namespace: `--as` wins; else the caller's verified identity. Prefer the\n // GitHub handle (`githubLogin`) over the store login (`username`) — for a user\n // whose login differs from their GitHub handle the login namespace may be\n // reserved (matches the CLI's `resolveLibraryPublisher` precedence). In an\n // unauthenticated dry-run we cannot call `me()`, so show a placeholder.\n let namespace: string;\n if (opts.as) namespace = opts.as;\n else if (authed) {\n const me = await pub.me();\n // `||` not `??`: an empty-string githubLogin (partially-connected account) is\n // not a usable namespace — fall back to the login rather than publish under \"\".\n namespace = me.githubLogin || me.username;\n } else namespace = \"<your store username>\";\n\n const normalized = normalizePublishedManifest(manifest, namespace);\n const publishedText = encodeSkaileManifest(normalized);\n\n const wouldBeRefs = (normalized.assets ?? []).map((a) =>\n refFor(a.kind, namespace, a.name, a.version ?? normalized.version),\n );\n\n if (opts.dryRun) {\n const sidecar = opts.sidecarRepo ?? getSidecarRepo(slug) ?? \"<none — pass --sidecar-repo>\";\n logInfo(`Publish plan for ${S.bold(slug)}:`);\n logInfo(` namespace: ${namespace}`);\n logInfo(` sidecar repo: ${sidecar}`);\n logInfo(` source ref: ${opts.ref ?? \"main\"}`);\n logInfo(` would publish ${wouldBeRefs.length} asset(s):`);\n for (const r of wouldBeRefs) logInfo(` ${r}`);\n return;\n }\n\n const sidecarRepoUrl = opts.sidecarRepo ?? getSidecarRepo(slug);\n if (!sidecarRepoUrl) {\n logErr(\n \"No sidecar repo associated with this source. Pass \" +\n `${S.cmd(\"--sidecar-repo https://github.com/<you>/<repo>\")} — it must be a ` +\n \"PUBLIC GitHub repo you own; the curated manifest is committed there and the \" +\n \"store pins to that commit.\",\n );\n process.exit(1);\n }\n if (opts.sidecarRepo) saveSidecarRepo(slug, sidecarRepoUrl);\n\n const { commitSha } = pushSidecarManifest({ sidecarRepoUrl, manifestText: publishedText, spawn });\n logOk(`Pushed curated manifest to ${S.dim(sidecarRepoUrl)} @ ${commitSha.slice(0, 10)}.`);\n\n // The FOREIGN repo's ref to ingest (branch/sha). Defaults to `main`.\n const sourceRef = opts.ref ?? \"main\";\n\n const { published } = await publishToStore({\n sourceUrl: url,\n ref: sourceRef,\n sidecar: { url: sidecarRepoUrl, ref: commitSha },\n manifest: normalized,\n client: pub,\n });\n\n if (published.length > 0) {\n logInfo(`Consumers can now install them with \\`skaile add ${published[0]}\\`.`);\n }\n}\n\n/**\n * `source manifest yank <src>` — unpublish the source's published assets (all,\n * or the single asset matching `opts.asset`'s name). Auth-gated like publish.\n */\nexport async function runYank(\n arg: string,\n opts: { projectDir: string; asset?: string },\n client?: PublisherClient,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug } = resolveSourceArg(arg, opts.projectDir);\n\n if (!injected && !isStoreAuthenticated()) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n const rows = await pub.sourcesList();\n const source = rows.find((r) => r.url === url);\n if (!source) {\n logErr(`Source \"${slug}\" is not registered in the store — nothing to yank.`);\n process.exit(1);\n }\n\n // Optionally narrow to a single asset by name (accept a bare name or a ref).\n const targetName = opts.asset ? bareName(opts.asset) : undefined;\n const candidates = (await pub.sourceCandidates(source.id)).filter(\n (c) => c.published && (!targetName || c.name === targetName),\n );\n if (candidates.length === 0) {\n logWarn(\"No published assets matched — nothing to yank.\");\n return;\n }\n\n const yanked: string[] = [];\n for (const c of candidates) {\n try {\n await pub.assetUnpublish(c.id);\n yanked.push(`${c.kind}:${c.name}`);\n } catch (err) {\n logWarn(\n `Failed to yank ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Yanked ${yanked.length} asset(s):`);\n for (const r of yanked) logInfo(` ${r}`);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../cli/src/commands/source-manifest-publish.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,IAAM,yBAAA,GAA4B,sBAAA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,MAAA;AACvD,EAAA,MAAM,cAAc,MAAM,GAAA,CAAI,gBAAA,CAAiB,MAAA,CAAO,EAAE,CAAA,EAAG,MAAA;AAAA,IACzD,CAAC,CAAA,KAAM,CAAA,CAAE,cAAc,CAAC,UAAA,IAAc,EAAE,IAAA,KAAS,UAAA;AAAA,GACnD;AACA,EAAA,IAAI,UAAA,CAAW,WAAW,CAAA,EAAG;AAC3B,IAAA,OAAA,CAAQ,qDAAgD,CAAA;AACxD,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,KAAA,MAAW,KAAK,UAAA,EAAY;AAC1B,IAAA,IAAI;AACF,MAAA,MAAM,GAAA,CAAI,cAAA,CAAe,CAAA,CAAE,EAAE,CAAA;AAC7B,MAAA,MAAA,CAAO,KAAK,CAAA,EAAG,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,CAAE,CAAA;AAAA,IACnC,SAAS,GAAA,EAAK;AACZ,MAAA,OAAA;AAAA,QACE,CAAA,eAAA,EAAkB,CAAA,CAAE,IAAI,CAAA,CAAA,EAAI,CAAA,CAAE,IAAI,CAAA,EAAA,EAAK,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC,CAAA;AAAA,OACzF;AAAA,IACF;AAAA,EACF;AAEA,EAAA,KAAA,CAAM,CAAA,OAAA,EAAU,MAAA,CAAO,MAAM,CAAA,UAAA,CAAY,CAAA;AACzC,EAAA,KAAA,MAAW,CAAA,IAAK,MAAA,EAAQ,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC1C","file":"source-manifest-publish-HC3K7D63.js","sourcesContent":["/**\n * `skaile source manifest publish` / `yank` — the curator-publish flow. Takes a\n * locally-curated sidecar manifest (over a foreign public GitHub repo) and:\n *\n * 1. Pushes the curated `skaile.manifest.yaml` to the curator's OWN public\n * \"sidecar\" repo (bytes stay in the foreign source; the sidecar holds only\n * the manifest pointing at it).\n * 2. Registers the foreign source + the sidecar (url + pinned commit) with the\n * store, syncs it, and publishes each curated asset.\n *\n * `yank` is the inverse: unpublish each currently-published asset of the source.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * (default HTTP client); git side-effects go through an injectable `spawn`. Both\n * seams keep the pure helpers + orchestration unit/integration-testable without a\n * live store or a real remote.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport {\n decodeSkaileManifest,\n encodeSkaileManifest,\n type SkPublishManifest,\n sourceCacheKey,\n} from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport { makeHttpPublisherClient, type PublisherClient } from \"../store-publisher.ts\";\nimport { isStoreAuthenticated } from \"../store-client.ts\";\nimport { bareName, publishToStore, refFor } from \"./publish-core.ts\";\nimport { sourceClonePath } from \"./source.ts\";\nimport { resolveSourceArg } from \"./source-manifest.ts\";\n\n/** The fixed filename a sidecar repo carries at its root. */\nconst SIDECAR_MANIFEST_FILENAME = \"skaile.manifest.yaml\";\n\n/** Injectable spawn contract — the subset of `spawnSync` these helpers use. */\ntype SpawnLike = typeof spawnSync;\n\n/**\n * Return a copy of `manifest` normalized for publication under `namespace`:\n * the top-level `publisher` is set to `namespace` and every per-asset\n * `publisher` override is removed so all assets inherit the top-level one.\n * Pure — the input is not mutated.\n */\nexport function normalizePublishedManifest(\n manifest: SkPublishManifest,\n namespace: string,\n): SkPublishManifest {\n const assets = (manifest.assets ?? []).map((a) => {\n const { publisher: _drop, ...rest } = a;\n return rest;\n });\n return { ...manifest, publisher: namespace, assets };\n}\n\n// ── Sidecar-repo association (~/.skaile/settings.json) ────────────────────────\n\n/**\n * Path to the user settings file — the same `~/.skaile/settings.json` the store\n * client reads tokens from. Resolves the `.skaile` root exactly as `getStoreRoot`\n * does (`SKAILE_HOME` when set — it IS the `.skaile` dir — else `~/.skaile`), so\n * the sidecar association lives beside the store manifests under one convention\n * and tests isolate through the same `SKAILE_HOME` seam.\n */\nfunction settingsFile(): string {\n const root = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\n return join(root, \"settings.json\");\n}\n\nfunction readSettings(): Record<string, any> {\n const file = settingsFile();\n if (!existsSync(file)) return {};\n try {\n return JSON.parse(readFileSync(file, \"utf-8\"));\n } catch {\n return {};\n }\n}\n\n/**\n * The sidecar repo URL previously associated with a source `slug`, if any.\n * Reads `settings.sidecarRepos?.[slug]?.repo`.\n */\nexport function getSidecarRepo(slug: string): string | undefined {\n const settings = readSettings();\n return settings.sidecarRepos?.[slug]?.repo;\n}\n\n/**\n * Persist the sidecar repo URL for a source `slug`, preserving every other\n * settings key. Stored as an object (`{ repo }`) so a `path` (or other fields)\n * can be added later without a schema migration.\n */\nexport function saveSidecarRepo(slug: string, repo: string): void {\n const file = settingsFile();\n mkdirSync(dirname(file), { recursive: true });\n const settings = readSettings();\n const sidecarRepos = { ...(settings.sidecarRepos ?? {}) };\n sidecarRepos[slug] = { ...(sidecarRepos[slug] ?? {}), repo };\n settings.sidecarRepos = sidecarRepos;\n writeFileSync(file, JSON.stringify(settings, null, 2), \"utf-8\");\n}\n\n// ── Sidecar push ──────────────────────────────────────────────────────────────\n\n/**\n * Run a git command in `cwd` via the injected spawn, throwing with the captured\n * stderr on failure. Returns trimmed stdout.\n */\nfunction git(spawn: SpawnLike, cwd: string, args: string[]): string {\n const res = spawn(\"git\", [\"-C\", cwd, ...args], { encoding: \"utf-8\" });\n if (res.status !== 0) {\n const stderr = (res.stderr ?? \"\").toString().trim();\n throw new Error(`git ${args.join(\" \")} failed: ${stderr || `exit ${res.status}`}`);\n }\n return (res.stdout ?? \"\").toString().trim();\n}\n\n/**\n * Clone the curator's sidecar repo, write the curated manifest at its root, and\n * commit + push. Returns the pushed commit sha (used to pin the store source).\n *\n * Idempotent re-publish: when the manifest is unchanged `git commit` fails with\n * \"nothing to commit\" — we swallow that and return the current HEAD so a no-op\n * re-run still yields a valid pin. Any push/auth failure surfaces as a thrown\n * Error carrying git's stderr.\n */\nexport function pushSidecarManifest(opts: {\n sidecarRepoUrl: string;\n manifestText: string;\n spawn?: SpawnLike;\n}): { commitSha: string } {\n const spawn = opts.spawn ?? spawnSync;\n // Dedicated dir next to the source clone cache; wipe any stale clone first so\n // a re-publish always starts from a clean shallow checkout of the remote.\n const cloneDir = `${sourceClonePath(sourceCacheKey(opts.sidecarRepoUrl))}-sidecar-push`;\n rmSync(cloneDir, { recursive: true, force: true });\n mkdirSync(dirname(cloneDir), { recursive: true });\n\n // The clone is scratch — always remove it afterwards (success or failure) so a\n // failed push never leaves a stale checkout in the cache dir.\n try {\n const cloneRes = spawn(\"git\", [\"clone\", \"--depth\", \"1\", opts.sidecarRepoUrl, cloneDir], {\n encoding: \"utf-8\",\n });\n if (cloneRes.status !== 0) {\n const stderr = (cloneRes.stderr ?? \"\").toString().trim();\n throw new Error(\n `git clone ${opts.sidecarRepoUrl} failed: ${stderr || `exit ${cloneRes.status}`}`,\n );\n }\n\n writeFileSync(join(cloneDir, SIDECAR_MANIFEST_FILENAME), opts.manifestText, \"utf-8\");\n git(spawn, cloneDir, [\"add\", SIDECAR_MANIFEST_FILENAME]);\n\n // Fixed bot identity via -c so the commit succeeds regardless of the curator's\n // git config (the sidecar push is a machine action, not authored work).\n const commitRes = spawn(\n \"git\",\n [\n \"-C\",\n cloneDir,\n \"-c\",\n \"user.email=publish@skaile.store\",\n \"-c\",\n \"user.name=skaile\",\n \"commit\",\n \"-m\",\n \"chore(sidecar): publish curated manifest\",\n ],\n { encoding: \"utf-8\" },\n );\n if (commitRes.status !== 0) {\n const out = `${commitRes.stdout ?? \"\"}${commitRes.stderr ?? \"\"}`;\n // Nothing changed → idempotent re-publish; keep the existing HEAD.\n if (!/nothing to commit/i.test(out)) {\n throw new Error(`git commit failed: ${out.trim() || `exit ${commitRes.status}`}`);\n }\n } else {\n // `push origin HEAD` (not a bare `push`) so a fresh sidecar repo with an\n // unborn/renamed default branch still gets its branch created on the remote.\n git(spawn, cloneDir, [\"push\", \"origin\", \"HEAD\"]);\n }\n\n return { commitSha: git(spawn, cloneDir, [\"rev-parse\", \"HEAD\"]) };\n } finally {\n rmSync(cloneDir, { recursive: true, force: true });\n }\n}\n\n// ── Orchestration ───────────────────────────────────────────────────────────\n\n/**\n * `source manifest publish <src>` — publish a curated sidecar manifest to the\n * store. See the module header for the full flow. Store calls go through\n * `client` (default HTTP); git side-effects through `spawn` (default\n * `spawnSync`). The auth gate is enforced only for the default HTTP client so\n * injected fakes bypass it.\n */\nexport async function runPublish(\n arg: string,\n opts: {\n projectDir: string;\n as?: string;\n sidecarRepo?: string;\n ref?: string;\n dryRun?: boolean;\n },\n client?: PublisherClient,\n spawn: SpawnLike = spawnSync,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug, manifestFile } = resolveSourceArg(arg, opts.projectDir);\n\n if (!existsSync(manifestFile)) {\n logErr(\n `No curated manifest for \"${slug}\" at ${S.dim(manifestFile)} — ` +\n \"run `skaile source manifest init` first.\",\n );\n process.exit(1);\n }\n\n const { manifest, diagnostics } = decodeSkaileManifest(readFileSync(manifestFile, \"utf-8\"));\n if (diagnostics.some((d) => d.severity === \"error\")) {\n for (const d of diagnostics.filter((x) => x.severity === \"error\")) {\n logErr(`${d.code}: ${d.message}`);\n }\n logErr(\n \"The curated manifest has errors — fix them with `skaile source manifest edit` / \" +\n \"`verify` before publishing.\",\n );\n process.exit(1);\n }\n\n // A real publish makes store calls (+ `me()` when `--as` is omitted), so it\n // needs a token. `--dry-run` is an offline preview: never gate it on auth.\n const authed = injected || isStoreAuthenticated();\n if (!opts.dryRun && !authed) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n // Namespace: `--as` wins; else the caller's verified identity. Prefer the\n // GitHub handle (`githubLogin`) over the store login (`username`) — for a user\n // whose login differs from their GitHub handle the login namespace may be\n // reserved (matches the CLI's `resolveLibraryPublisher` precedence). In an\n // unauthenticated dry-run we cannot call `me()`, so show a placeholder.\n let namespace: string;\n if (opts.as) namespace = opts.as;\n else if (authed) {\n const me = await pub.me();\n // `||` not `??`: an empty-string githubLogin (partially-connected account) is\n // not a usable namespace — fall back to the login rather than publish under \"\".\n namespace = me.githubLogin || me.username;\n } else namespace = \"<your store username>\";\n\n const normalized = normalizePublishedManifest(manifest, namespace);\n const publishedText = encodeSkaileManifest(normalized);\n\n const wouldBeRefs = (normalized.assets ?? []).map((a) =>\n refFor(a.kind, namespace, a.name, a.version ?? normalized.version),\n );\n\n if (opts.dryRun) {\n const sidecar = opts.sidecarRepo ?? getSidecarRepo(slug) ?? \"<none — pass --sidecar-repo>\";\n logInfo(`Publish plan for ${S.bold(slug)}:`);\n logInfo(` namespace: ${namespace}`);\n logInfo(` sidecar repo: ${sidecar}`);\n logInfo(` source ref: ${opts.ref ?? \"main\"}`);\n logInfo(` would publish ${wouldBeRefs.length} asset(s):`);\n for (const r of wouldBeRefs) logInfo(` ${r}`);\n return;\n }\n\n const sidecarRepoUrl = opts.sidecarRepo ?? getSidecarRepo(slug);\n if (!sidecarRepoUrl) {\n logErr(\n \"No sidecar repo associated with this source. Pass \" +\n `${S.cmd(\"--sidecar-repo https://github.com/<you>/<repo>\")} — it must be a ` +\n \"PUBLIC GitHub repo you own; the curated manifest is committed there and the \" +\n \"store pins to that commit.\",\n );\n process.exit(1);\n }\n if (opts.sidecarRepo) saveSidecarRepo(slug, sidecarRepoUrl);\n\n const { commitSha } = pushSidecarManifest({ sidecarRepoUrl, manifestText: publishedText, spawn });\n logOk(`Pushed curated manifest to ${S.dim(sidecarRepoUrl)} @ ${commitSha.slice(0, 10)}.`);\n\n // The FOREIGN repo's ref to ingest (branch/sha). Defaults to `main`.\n const sourceRef = opts.ref ?? \"main\";\n\n const { published } = await publishToStore({\n sourceUrl: url,\n ref: sourceRef,\n sidecar: { url: sidecarRepoUrl, ref: commitSha },\n manifest: normalized,\n client: pub,\n });\n\n if (published.length > 0) {\n logInfo(`Consumers can now install them with \\`skaile add ${published[0]}\\`.`);\n }\n}\n\n/**\n * `source manifest yank <src>` — unpublish the source's published assets (all,\n * or the single asset matching `opts.asset`'s name). Auth-gated like publish.\n */\nexport async function runYank(\n arg: string,\n opts: { projectDir: string; asset?: string },\n client?: PublisherClient,\n): Promise<void> {\n const injected = client !== undefined;\n const pub = client ?? makeHttpPublisherClient();\n\n const { url, slug } = resolveSourceArg(arg, opts.projectDir);\n\n if (!injected && !isStoreAuthenticated()) {\n logErr(\"Not signed in — run `skaile store login` first.\");\n process.exit(1);\n }\n\n const rows = await pub.sourcesList();\n const source = rows.find((r) => r.url === url);\n if (!source) {\n logErr(`Source \"${slug}\" is not registered in the store — nothing to yank.`);\n process.exit(1);\n }\n\n // Optionally narrow to a single asset by name (accept a bare name or a ref).\n const targetName = opts.asset ? bareName(opts.asset) : undefined;\n const candidates = (await pub.sourceCandidates(source.id)).filter(\n (c) => c.published && (!targetName || c.name === targetName),\n );\n if (candidates.length === 0) {\n logWarn(\"No published assets matched — nothing to yank.\");\n return;\n }\n\n const yanked: string[] = [];\n for (const c of candidates) {\n try {\n await pub.assetUnpublish(c.id);\n yanked.push(`${c.kind}:${c.name}`);\n } catch (err) {\n logWarn(\n `Failed to yank ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Yanked ${yanked.length} asset(s):`);\n for (const r of yanked) logInfo(` ${r}`);\n}\n"]}
|
package/dist/store/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../store/src/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,YAAY,EAEZ,UAAU,EAGV,OAAO,EAGR,MAAM,0BAA0B,CAAC;AAClC,OAAO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;IACH,SAAS,GAAI,UAAU,MAAM,IAAI,KAAG,CAAC,MAAM,IAAI,CAAC,CAG9C;IAEF;;;;;;OAMG;IACH,WAAW,QAAO,kBAAkB,CAmBlC;IAIF;;;;;OAKG;IACH,OAAO,IAAI,IAAI;IAQf;;;;;;;;;;;;;;;;OAgBG;IACH,MAAM,CAAC,UAAU,CACf,MAAM,EAAE,eAAe,EACvB,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,OAAO,EAAE,CAAA;KAAE,GACzD,UAAU;IAcb,OAAO,CAAC,YAAY;IA2MpB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAQvB,OAAO,CAAC,cAAc;IAetB,OAAO,CAAC,OAAO;CAMhB"}
|
package/dist/tui/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { createAgentSession } from '../chunk-
|
|
2
|
-
import '../chunk-
|
|
1
|
+
import { createAgentSession } from '../chunk-OEK2ACRR.js';
|
|
2
|
+
import '../chunk-EVQDXN27.js';
|
|
3
3
|
import '../chunk-X5YPJV4N.js';
|
|
4
4
|
import '../chunk-W3UDISS2.js';
|
|
5
5
|
import '../chunk-O7SG5PC2.js';
|
|
@@ -7,14 +7,14 @@ import '../chunk-7QBNJTTQ.js';
|
|
|
7
7
|
import '../chunk-GTS2FODO.js';
|
|
8
8
|
import '../chunk-WQ7DE5UC.js';
|
|
9
9
|
import '../chunk-32NA4TVC.js';
|
|
10
|
-
import '../chunk-
|
|
10
|
+
import '../chunk-4J24AU4Q.js';
|
|
11
11
|
import '../chunk-4R6DROGN.js';
|
|
12
12
|
import '../chunk-3XXQPHGL.js';
|
|
13
13
|
import '../chunk-7BUZQVRR.js';
|
|
14
14
|
import '../chunk-NC5YXVZF.js';
|
|
15
|
-
import '../chunk-
|
|
15
|
+
import '../chunk-VC2MWHRH.js';
|
|
16
16
|
import { loadConnectorDeclarations } from '../chunk-5KSIVLOX.js';
|
|
17
|
-
import '../chunk-
|
|
17
|
+
import '../chunk-5FCBPIOK.js';
|
|
18
18
|
import '../chunk-3NCGSSCU.js';
|
|
19
19
|
import '../chunk-RRVQAE5D.js';
|
|
20
20
|
import '../chunk-GURXUF2J.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { PluginStore, WorkspacePlugin, buildClaudePluginFiles, resolveProjectDir } from '../chunk-
|
|
1
|
+
export { PluginStore, WorkspacePlugin, buildClaudePluginFiles, resolveProjectDir } from '../chunk-EVQDXN27.js';
|
|
2
2
|
export { err, ok, okJson } from '../chunk-X5YPJV4N.js';
|
|
3
3
|
import '../chunk-FTG7CRFD.js';
|
|
4
4
|
import '../chunk-W4IPN3DD.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skaile/workspaces",
|
|
3
|
-
"version": "3.16.
|
|
3
|
+
"version": "3.16.1",
|
|
4
4
|
"description": "Skaile workspaces runtime — types, core, bridge, runner, store, connectors, and supporting layers as one publishable package",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"packageManager": "bun@1.3.9",
|
|
@@ -1 +0,0 @@
|
|
|
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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W,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-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 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/normalizer.ts","../bridge/src/runtime.ts","../bridge/src/validation.ts"],"names":[],"mappings":";;;;;AAgBA,SAAS,kBAAkB,KAAA,EAAyC;AAClE,EAAA,OAAO;AAAA,IACL,GAAI,MAAM,MAAA,GAAS,EAAE,QAAQ,KAAA,CAAM,MAAA,KAAW,EAAC;AAAA,IAC/C,GAAI,MAAM,UAAA,GAAa,EAAE,YAAY,KAAA,CAAM,UAAA,KAAe,EAAC;AAAA,IAC3D,GAAI,OAAO,KAAA,CAAM,aAAA,KAAkB,QAAA,GAAW,EAAE,aAAA,EAAe,KAAA,CAAM,aAAA,EAAc,GAAI,EAAC;AAAA,IACxF,GAAI,OAAO,KAAA,CAAM,aAAA,KAAkB,QAAA,GAAW,EAAE,aAAA,EAAe,KAAA,CAAM,aAAA,EAAc,GAAI;AAAC,GAC1F;AACF;AAWO,IAAM,kBAAN,MAAsB;AAAA,EACnB,eAAA,uBAAsB,GAAA,EAAoB;AAAA,EAC1C,wBAAA,GAA2B,KAAA;AAAA,EAC3B,qBAAA,GAAwB,KAAA;AAAA;AAAA,EAExB,eAAA,GAAkB,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAO1B,UAAU,KAAA,EAAuC;AAC/C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,eAAA;AACH,QAAA,OAAO,IAAA,CAAK,kBAAA,CAAmB,KAAA,CAAM,OAAO,CAAA;AAAA,MAE9C,KAAK,gBAAA;AACH,QAAA,OAAO,IAAA,CAAK,oBAAoB,KAAK,CAAA;AAAA,MAEvC,KAAK,aAAA;AACH,QAAA,OAAO,EAAC;AAAA,MAEV,KAAK,UAAA;AACH,QAAA,OAAO,IAAA,CAAK,aAAA,CAAc,KAAA,CAAM,WAAW,CAAA;AAAA,MAE7C,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AA,EAAO,KAAA,EAAO,CAAA,kBAAA,EAAqB,MAAM,CAAA,CAAA,EAAG;AAAA,EAC3D,SAAS,GAAA,EAAU;AACjB,IAAA,IAAI,GAAA,CAAI,SAAS,YAAA,EAAc,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,wBAAA,EAAyB;AACnF,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,GAAA,CAAI,WAAW,eAAA,EAAgB;AAAA,EAC5D;AACF","file":"chunk-JNCORFRK.js","sourcesContent":["/**\n * EventNormalizer — converts bridge-level AgentEvent (raw driver events) to\n * skaile-agent-types AgentEvent (normalized, human-readable events).\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call reset() between sessions.\n */\n\nimport type { AgentEvent as NormalizedEvent } from \"@skaile/workspaces/types\";\nimport { classifyClaudeSdkError } from \"./error-classifier.js\";\nimport type { AgentMessage, AgentEvent as BridgeEvent, ContentBlock } from \"./types.js\";\n\n/**\n * The optional usage keys a `result` event carries, in the shape both\n * `finished` and a result-sourced `error` emit them. Absent keys stay absent.\n */\nfunction resultUsageFields(event: BridgeEvent & { type: \"result\" }) {\n return {\n ...(event.tokens ? { tokens: event.tokens } : {}),\n ...(event.modelUsage ? { modelUsage: event.modelUsage } : {}),\n ...(typeof event.contextTokens === \"number\" ? { contextTokens: event.contextTokens } : {}),\n ...(typeof event.contextWindow === \"number\" ? { contextWindow: event.contextWindow } : {}),\n };\n}\n\n/**\n * Converts raw bridge-level {@link BridgeEvent} payloads into normalized\n * `@skaile/workspaces/types` `AgentEvent` payloads consumed by the runner and transport.\n *\n * Stateful: tracks active subagents and dev-server detection across a session.\n * Call {@link EventNormalizer.reset} between sessions to clear accumulated state.\n *\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport class EventNormalizer {\n private activeSubagents = new Map<string, string>();\n private devServerStartingEmitted = false;\n private devServerReadyEmitted = false;\n /** True when message_update deltas have been emitted for the current message. */\n private hasStreamedText = false;\n\n /**\n * Convert a single bridge event into zero or more normalized events.\n * One bridge event can produce multiple normalized events (e.g., a message_start\n * with text + tool_use blocks produces both text and tool_call events).\n */\n normalize(event: BridgeEvent): NormalizedEvent[] {\n switch (event.type) {\n case \"message_start\":\n return this.handleMessageStart(event.message);\n\n case \"message_update\":\n return this.handleMessageUpdate(event);\n\n case \"message_end\":\n return [];\n\n case \"turn_end\":\n return this.handleTurnEnd(event.toolResults);\n\n case \"result\":\n return this.handleResult(event);\n\n case \"error\":\n return [\n {\n type: \"error\",\n message: event.error,\n fatal: event.fatal ?? true,\n category: event.detail?.category,\n ...(event.detail?.hint ? { hint: event.detail.hint } : {}),\n },\n ];\n\n case \"tool_call\":\n // Already handled in message_start — emit status only\n return [{ type: \"status\", phase: \"working\" }];\n\n case \"tool_execution_end\":\n return [];\n\n case \"agent_end\":\n return [{ type: \"status\", phase: \"idle\" }];\n\n case \"commands_available\":\n // Pass through to transport — the gateway caches this event\n return [event as unknown as NormalizedEvent];\n\n case \"session_info\":\n // Pass through to transport — the forge layer stores the OMP session ID\n return [event as unknown as NormalizedEvent];\n\n case \"ui_render\":\n case \"ui_render_update\":\n case \"ui_clear\":\n // Pass through verbatim — drivers that implement the Agent UI Protocol emit these directly\n return [event as unknown as NormalizedEvent];\n\n default:\n return [];\n }\n }\n\n /** Clear all stateful tracking between sessions. */\n reset(): void {\n this.activeSubagents.clear();\n this.devServerStartingEmitted = false;\n this.devServerReadyEmitted = false;\n this.hasStreamedText = false;\n }\n\n // ---------------------------------------------------------------------------\n // message_start → text, tool_call, question, subagent\n // ---------------------------------------------------------------------------\n\n private handleMessageStart(message: AgentMessage): NormalizedEvent[] {\n // Only process assistant messages. Drivers (e.g. omp) may echo the user's\n // message as a message_start with role:\"user\" before streaming the response.\n // Emitting a text event for that echo would prepend the user's input to the\n // assistant bubble on the frontend.\n if (message.role !== \"assistant\") return [];\n\n const events: NormalizedEvent[] = [];\n const blocks = this.getContentBlocks(message);\n\n for (const block of blocks) {\n if (block.type === \"text\" && block.text) {\n // Skip full text if we already streamed it via message_update deltas\n if (!this.hasStreamedText) {\n events.push({ type: \"text\", content: block.text });\n }\n } else if (block.type === \"tool_use\" && block.name) {\n events.push(...this.handleToolUse(block));\n }\n }\n\n this.hasStreamedText = false;\n return events;\n }\n\n private handleToolUse(block: ContentBlock): NormalizedEvent[] {\n const name = block.name!;\n const input = (block.input ?? {}) as Record<string, unknown>;\n\n if (name === \"AskUserQuestion\") {\n return this.handleAskUserQuestion(input);\n }\n if (name === \"Agent\") {\n return this.handleAgentToolUse(block, input);\n }\n return this.handleGenericToolUse(name, input);\n }\n\n private handleAskUserQuestion(input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n // Claude SDK sends { questions: [{ question, header, options: [{ label, description }] }] }\n // Legacy/simple format sends { question: string, options?: string[] }\n const questions = input.questions;\n if (Array.isArray(questions)) {\n for (const q of questions) {\n const qObj = q as Record<string, unknown>;\n const question = String(qObj.question ?? \"\");\n const rawOpts = qObj.options;\n const options = Array.isArray(rawOpts)\n ? rawOpts.map((o: any) => (typeof o === \"string\" ? o : String(o.label ?? o)))\n : undefined;\n events.push({ type: \"question\", question, options });\n }\n } else {\n const question = String(input.question ?? input.text ?? \"\");\n const rawOptions = input.options;\n const options = Array.isArray(rawOptions) ? rawOptions.map(String) : undefined;\n events.push({ type: \"question\", question, options });\n }\n return events;\n }\n\n private handleAgentToolUse(\n block: ContentBlock,\n input: Record<string, unknown>,\n ): NormalizedEvent[] {\n const agentName = String(input.subagent_type ?? input.description ?? \"unknown\");\n const description = String(input.description ?? input.prompt ?? \"\").slice(0, 200);\n if (block.id) {\n this.activeSubagents.set(block.id, agentName);\n }\n return [\n { type: \"subagent\", name: agentName, status: \"started\", description },\n { type: \"status\", phase: \"working\" },\n ];\n }\n\n private handleGenericToolUse(name: string, input: Record<string, unknown>): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_call\",\n tool: name,\n input,\n summary: summarizeToolCall(name, input),\n });\n events.push({ type: \"status\", phase: \"working\" });\n\n if (name === \"Bash\" && typeof input.command === \"string\") {\n const devEvent = this.detectDevServerStarting(input.command);\n if (devEvent) events.push(devEvent);\n }\n\n return events;\n }\n\n // ---------------------------------------------------------------------------\n // message_update → streaming text\n // ---------------------------------------------------------------------------\n\n private handleMessageUpdate(event: BridgeEvent): NormalizedEvent[] {\n const delta = (event as any)._textDelta as string | undefined;\n if (delta) {\n this.hasStreamedText = true;\n return [{ type: \"text\", content: delta }];\n }\n return [];\n }\n\n // ---------------------------------------------------------------------------\n // turn_end → tool_result, subagent finished, file_changed, dev_server\n // ---------------------------------------------------------------------------\n\n private handleTurnEnd(toolResults?: AgentMessage[]): NormalizedEvent[] {\n if (!toolResults?.length) return [];\n\n const events: NormalizedEvent[] = [];\n\n for (const result of toolResults) {\n const toolName = result.toolName ?? \"unknown\";\n const outputData = result.data ?? result.content;\n const output = typeof outputData === \"string\" ? outputData : JSON.stringify(outputData);\n\n // Check if this is a subagent result\n if (toolName === \"Agent\" || this.isSubagentResult(result)) {\n events.push(...this.handleSubagentResult(result, output));\n } else {\n events.push(...this.handleToolResult(toolName, outputData, output));\n }\n }\n\n return events;\n }\n\n private handleSubagentResult(result: AgentMessage, output: string): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n const agentName = this.resolveSubagentName(result);\n const description = output.slice(0, 200);\n events.push({ type: \"subagent\", name: agentName, status: \"finished\", description });\n\n if (agentName === \"dev-server\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private handleToolResult(\n toolName: string,\n outputData: unknown,\n output: string,\n ): NormalizedEvent[] {\n const events: NormalizedEvent[] = [];\n events.push({\n type: \"tool_result\",\n tool: toolName,\n output: outputData,\n summary: summarizeToolResult(toolName, outputData),\n });\n\n // Detect file changes from Write/Edit results\n const fileEvents = detectFileChanges(toolName, outputData);\n if (fileEvents.length > 0) events.push(...fileEvents);\n\n // Detect dev server from Bash output\n if (toolName === \"Bash\") {\n const devEvent = this.detectDevServerReady(output);\n if (devEvent) events.push(devEvent);\n }\n return events;\n }\n\n private isSubagentResult(result: AgentMessage): boolean {\n // Check if the tool result's id maps to a tracked subagent\n if (result.toolName && this.activeSubagents.has(result.toolName)) return true;\n return false;\n }\n\n private resolveSubagentName(result: AgentMessage): string {\n // toolName on bridge AgentMessage is resolved from toolIdToName in the driver\n const name = result.toolName ? this.activeSubagents.get(result.toolName) : undefined;\n if (name) {\n this.activeSubagents.delete(result.toolName!);\n return name;\n }\n return result.toolName ?? \"unknown\";\n }\n\n // ---------------------------------------------------------------------------\n // result → finished or error\n // ---------------------------------------------------------------------------\n\n private handleResult(event: BridgeEvent & { type: \"result\" }): NormalizedEvent[] {\n const usage = resultUsageFields(event);\n if (event.subtype === \"success\") {\n return [\n {\n type: \"finished\",\n summary: event.summary ?? \"Task completed\",\n costUsd: event.costUsd ?? 0,\n ...usage,\n },\n ];\n }\n\n const errors = event.errors ?? [];\n // Run the same classifier the claude-sdk driver uses on its `error`\n // event so the result-error path also surfaces a category and hint\n // (drivers other than claude-sdk emit `result` without a paired\n // `error`, so this is the only place they get classified).\n const detail = classifyClaudeSdkError({ errors, subtype: event.subtype });\n // The turn billed even though it failed: carry its usage so a ledger\n // that only writes on `finished` can write here too. Unlike the finished\n // branch, no `costUsd: 0` fallback — an absent figure stays absent.\n return [\n {\n type: \"error\",\n message: `Agent stopped: ${event.subtype}${errors.length ? ` — ${errors.join(\"; \")}` : \"\"}`,\n fatal: event.subtype === \"error_during_execution\",\n category: detail.category,\n ...(detail.hint ? { hint: detail.hint } : {}),\n ...(typeof event.costUsd === \"number\" ? { costUsd: event.costUsd } : {}),\n ...usage,\n },\n ];\n }\n\n // ---------------------------------------------------------------------------\n // Dev server detection\n // ---------------------------------------------------------------------------\n\n private detectDevServerStarting(command: string): NormalizedEvent | null {\n if (this.devServerStartingEmitted) return null;\n const cmd = command.toLowerCase();\n const isFrontendStart =\n (cmd.includes(\"pnpm run dev\") || cmd.includes(\"pnpm dev\") || cmd.includes(\"vite\")) &&\n (cmd.includes(\"frontend\") || cmd.includes(\"dev:preview\"));\n if (isFrontendStart) {\n this.devServerStartingEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"starting\" };\n }\n return null;\n }\n\n private detectDevServerReady(text: string): NormalizedEvent | null {\n if (this.devServerReadyEmitted) return null;\n\n const explicitMatch = text.match(/DEVSERVER_READY:(https?:\\/\\/[^\\s\"\\\\]+)/);\n if (explicitMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: explicitMatch[1]!, status: \"ready\" };\n }\n\n const viteMatch = text.match(/Local:\\s+(https?:\\/\\/localhost:\\d+)/);\n if (viteMatch) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: viteMatch[1]!, status: \"ready\" };\n }\n\n if (text.includes(\"FRONTEND_READY\")) {\n this.devServerReadyEmitted = true;\n return { type: \"dev_server\", url: \"http://localhost:3000\", status: \"ready\" };\n }\n\n return null;\n }\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n private getContentBlocks(message: AgentMessage): ContentBlock[] {\n if (Array.isArray(message.content)) return message.content;\n if (typeof message.content === \"string\" && message.content) {\n return [{ type: \"text\", text: message.content }];\n }\n return [];\n }\n}\n\n// ---------------------------------------------------------------------------\n// Pure helper functions (exported for reuse)\n// ---------------------------------------------------------------------------\n\n/**\n * Produce a human-readable one-line summary of a tool call for the activity log.\n *\n * Returns a string like `$ git status` for Bash, `Read src/index.ts` for Read, etc.\n * Falls back to `ToolName({...input...})` for unrecognised tools.\n *\n * @param tool - Tool name (e.g. `\"Bash\"`, `\"Write\"`, `\"Grep\"`).\n * @param input - Tool input record passed to the call.\n * @returns A short display string suitable for the activity feed.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolCall(tool: string, input: Record<string, unknown>): string {\n switch (tool) {\n case \"Bash\":\n return `$ ${String(input.command ?? \"\").slice(0, 200)}`;\n case \"Write\":\n return `Create ${String(input.file_path)}`;\n case \"Edit\":\n return `Edit ${String(input.file_path)}`;\n case \"Read\":\n return `Read ${String(input.file_path)}`;\n case \"Glob\":\n return `Find ${String(input.pattern)}`;\n case \"Grep\":\n return `Search for ${String(input.pattern)}`;\n default:\n return `${tool}(${JSON.stringify(input).slice(0, 100)})`;\n }\n}\n\n/** Extract plain text from an Anthropic content-block array (e.g. tool results returned by Claude SDK). */\nfunction extractContentBlockText(blocks: unknown[]): string | null {\n const textBlocks = blocks.filter(\n (b): b is { type: \"text\"; text: string } =>\n typeof b === \"object\" &&\n b !== null &&\n (b as Record<string, unknown>).type === \"text\" &&\n typeof (b as Record<string, unknown>).text === \"string\",\n );\n if (textBlocks.length === 0) return null;\n return textBlocks.map((b) => b.text).join(\"\\n\");\n}\n\n/**\n * Produce a human-readable one-line summary of a tool result for the activity log.\n *\n * Handles Bash stdout/stderr, Write/Edit file paths, ApplyPatch change counts, and\n * Anthropic content-block arrays. Falls back to `JSON.stringify` for unknown shapes.\n *\n * @param tool - Tool name.\n * @param result - Raw tool result payload.\n * @returns A short display string, truncated to 200 characters.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function summarizeToolResult(tool: string, result: unknown): string {\n // Handle Anthropic content-block arrays: [{ type: \"text\", text: \"...\" }, ...]\n if (Array.isArray(result)) {\n const text = extractContentBlockText(result);\n return (text ?? JSON.stringify(result)).slice(0, 200);\n }\n if (typeof result !== \"object\" || !result) {\n return String(result).slice(0, 200);\n }\n const r = result as Record<string, unknown>;\n switch (tool) {\n case \"Bash\": {\n const stderr = String(r.stderr ?? \"\").trim();\n if (stderr) return `stderr: ${stderr.slice(0, 200)}`;\n return (\n String(r.stdout ?? \"\")\n .trim()\n .slice(0, 200) || \"(no output)\"\n );\n }\n case \"Write\":\n return `${String(r.type)}: ${String(r.filePath)}`;\n case \"Edit\":\n return `Edited ${String(r.filePath)}`;\n case \"ApplyPatch\":\n return `${Array.isArray(r.changes) ? r.changes.length : 0} file changes`;\n default:\n return JSON.stringify(result).slice(0, 200);\n }\n}\n\n/**\n * Detect file-change events from a tool result, returning zero or more `file_changed` events.\n *\n * Handles `Write` (single create/edit), `Edit` (single edit), and `ApplyPatch` (multi-file\n * patch with per-change `kind` classification). Returns an empty array for all other tools.\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns Array of `file_changed` normalized events.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChanges(toolName: string, result: unknown): NormalizedEvent[] {\n if (typeof result !== \"object\" || !result) return [];\n const r = result as Record<string, unknown>;\n\n if (toolName === \"Write\" && r.filePath) {\n return [\n {\n type: \"file_changed\",\n path: String(r.filePath),\n action: r.type === \"create\" ? \"create\" : \"edit\",\n },\n ];\n }\n if (toolName === \"Edit\" && r.filePath) {\n return [{ type: \"file_changed\", path: String(r.filePath), action: \"edit\" }];\n }\n if (toolName === \"ApplyPatch\" && Array.isArray(r.changes)) {\n return r.changes\n .filter(\n (change): change is { path: string; kind: \"add\" | \"delete\" | \"update\" } =>\n typeof change === \"object\" &&\n change !== null &&\n typeof (change as Record<string, unknown>).path === \"string\" &&\n typeof (change as Record<string, unknown>).kind === \"string\",\n )\n .map((change) => ({\n type: \"file_changed\" as const,\n path: change.path,\n action: change.kind === \"add\" ? \"create\" : change.kind === \"delete\" ? \"delete\" : \"edit\",\n }));\n }\n\n return [];\n}\n\n/**\n * Backward-compatible single-event helper; returns the first `file_changed` event or `null`.\n *\n * Prefer {@link detectFileChanges} for multi-file patches (e.g. `ApplyPatch`).\n *\n * @param toolName - Name of the tool that produced the result.\n * @param result - Raw tool result payload.\n * @returns First detected `file_changed` event, or `null`.\n * @docLink packages/bridge/api-reference#normalizer\n */\nexport function detectFileChange(toolName: string, result: unknown): NormalizedEvent | null {\n return detectFileChanges(toolName, result)[0] ?? null;\n}\n","/**\n * BridgeRuntime — implements IAgentRuntime from @skaile/workspaces/types by wrapping\n * an AgentDriver + EventNormalizer. This is the primary integration point for\n * consumers that want normalized events from any driver.\n */\n\nimport type {\n AgentEvent,\n AgentReconfigureOptions,\n AgentRuntimeConfig,\n IAgentRuntime,\n} from \"@skaile/workspaces/types\";\n\nimport { EventNormalizer } from \"./normalizer.js\";\nimport { createDriver } from \"./registry.js\";\nimport type { AgentConfig, AgentDriver } from \"./types.js\";\n\n/**\n * Implements `IAgentRuntime` from `@skaile/workspaces/types` by wrapping an {@link AgentDriver}\n * and an {@link EventNormalizer}.\n *\n * This is the primary integration point for consumers that want normalized `AgentEvent`\n * payloads from any driver without managing the driver lifecycle directly. Create via\n * {@link createRuntime} to avoid coupling to `BridgeRuntime` directly.\n *\n * @docLink packages/bridge/api-reference#runtime\n */\nexport class BridgeRuntime implements IAgentRuntime {\n private driver: AgentDriver | null = null;\n private normalizer = new EventNormalizer();\n private handlers = new Set<(event: AgentEvent) => void>();\n private boundEventHandler: ((event: any) => void) | null = null;\n private driverId: string;\n\n constructor(driverId: string = \"claude-sdk\") {\n this.driverId = driverId;\n }\n\n async start(config: AgentRuntimeConfig): Promise<void> {\n // Dispose previous driver if any\n if (this.driver) {\n await this.dispose();\n }\n\n this.normalizer.reset();\n\n const bridgeConfig: AgentConfig = {\n cwd: config.cwd,\n provider: config.provider,\n model: config.model,\n systemPrompt: config.systemPrompt,\n apiKeys: config.apiKeys,\n env: config.env,\n agentDir: config.agentDir,\n sessionId: config.sessionId,\n resumeSessionId: config.resumeSessionId,\n maxTurns: config.maxTurns,\n };\n\n this.driver = await createDriver(this.driverId, bridgeConfig);\n\n // Wire bridge events through normalizer to handlers\n this.boundEventHandler = (bridgeEvent: any) => {\n const normalized = this.normalizer.normalize(bridgeEvent);\n for (const event of normalized) {\n for (const handler of this.handlers) {\n handler(event);\n }\n }\n };\n this.driver.on(\"agent-event\", this.boundEventHandler);\n\n await this.driver.start();\n }\n\n async configure(_config: AgentReconfigureOptions): Promise<void> {\n // Runtime reconfiguration for BridgeRuntime is a no-op for now.\n // Future: reconnect connectors, reload ai-assets, update subagents.\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.driver) throw new Error(\"Runtime not started — call start() first\");\n await this.driver.prompt(message);\n }\n\n async reply(answer: string): Promise<void> {\n // Mirror serve.ts handleReply: an answer must resume the paused turn. Falling through to\n // prompt() would deny the question as superseded and drop the structured answer.\n if (this.driver?.hasPendingQuestion() && this.driver.answerQuestion(answer)) return;\n await this.prompt(answer);\n }\n\n async abort(): Promise<void> {\n if (this.driver) {\n await this.driver.abort();\n }\n }\n\n async dispose(): Promise<void> {\n if (this.driver) {\n if (this.boundEventHandler) {\n this.driver.off(\"agent-event\", this.boundEventHandler);\n this.boundEventHandler = null;\n }\n this.driver.kill();\n this.driver = null;\n }\n this.normalizer.reset();\n }\n\n onEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.add(handler);\n }\n\n offEvent(handler: (event: AgentEvent) => void): void {\n this.handlers.delete(handler);\n }\n\n get isRunning(): boolean {\n return this.driver?.isRunning ?? false;\n }\n}\n\n/**\n * Factory function to create a {@link BridgeRuntime} with the specified driver.\n *\n * @param driverId - Registered driver id (default: `\"claude-sdk\"`).\n * @returns A new `IAgentRuntime` wrapping the selected driver with event normalization.\n * @docLink packages/bridge/api-reference#runtime\n */\nexport function createRuntime(driverId: string = \"claude-sdk\"): IAgentRuntime {\n return new BridgeRuntime(driverId);\n}\n","/** Provider API key validation — hits each provider's models endpoint to verify the key works. */\n\nimport { PROVIDER_ENDPOINTS, resolveProviderModelsUrl } from \"./provider-endpoints.js\";\n\n/**\n * Result of an API key validation check performed by {@link validateApiKey}.\n *\n * @docLink packages/bridge/api-reference#validation\n */\nexport interface ValidationResult {\n /** `true` when the API key was accepted by the provider's models endpoint. */\n ok: boolean;\n /** Human-readable error description when `ok` is `false`. */\n error?: string;\n}\n\n/**\n * Validate an API key by sending a lightweight GET request to the provider's models endpoint.\n *\n * Returns `{ ok: true }` when the provider accepts the key (HTTP 2xx). Returns\n * `{ ok: false, error }` on 401/403 (invalid key), other HTTP errors, network failures,\n * or unsupported providers. Requests time out after 8 seconds.\n *\n * @param provider - Provider name matching a key in the shared `PROVIDER_ENDPOINTS` map\n * (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * @param key - API key to validate.\n * @param options - Optional base-URL / environment overrides; defaults to the\n * provider's own API, or its `baseUrlEnv` value when one is set.\n * @returns Validation result with optional error description.\n * @docLink packages/bridge/api-reference#validation\n */\nexport async function validateApiKey(\n provider: string,\n key: string,\n options: { baseUrl?: string; env?: Record<string, string | undefined> } = {},\n): Promise<ValidationResult> {\n const endpoint = PROVIDER_ENDPOINTS[provider];\n if (!endpoint) return { ok: false, error: `Unknown provider: ${provider}` };\n\n // Validate against the same endpoint discovery/dispatch use: behind a gateway\n // the key is the gateway's, and the provider's public API would reject it.\n let url =\n resolveProviderModelsUrl(provider, {\n baseUrl: options.baseUrl,\n env: options.env ?? process.env,\n }) ?? endpoint.url;\n if (endpoint.queryParam) url += `?${endpoint.queryParam}=${encodeURIComponent(key)}`;\n\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 8000);\n\n const response = await fetch(url, {\n method: \"GET\",\n headers: endpoint.headers(key),\n signal: controller.signal,\n });\n\n clearTimeout(timeout);\n\n if (response.ok) return { ok: true };\n\n const status = response.status;\n if (status === 401 || status === 403) {\n return { ok: false, error: \"Invalid API key (authentication failed)\" };\n }\n return { ok: false, error: `API returned HTTP ${status}` };\n } catch (err: any) {\n if (err.name === \"AbortError\") return { ok: false, error: \"Request timed out (8s)\" };\n return { ok: false, error: err.message ?? \"Network error\" };\n }\n}\n"]}
|