@skaile/workspaces 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/{asset-feeds-PTZBWJEL.js → asset-feeds-Y66NCOQZ.js} +4 -4
  3. package/dist/{asset-feeds-PTZBWJEL.js.map → asset-feeds-Y66NCOQZ.js.map} +1 -1
  4. package/dist/asset-manager/index.js +1 -1
  5. package/dist/asset-manager/src/index.d.ts.map +1 -1
  6. package/dist/{chunk-NTYCGPZ3.js → chunk-7VGRRH2L.js} +6 -6
  7. package/dist/{chunk-NTYCGPZ3.js.map → chunk-7VGRRH2L.js.map} +1 -1
  8. package/dist/{chunk-EA73UA42.js → chunk-BSXBOKL6.js} +2 -2
  9. package/dist/{chunk-EA73UA42.js.map → chunk-BSXBOKL6.js.map} +1 -1
  10. package/dist/{chunk-Y5B5272E.js → chunk-MB6563TL.js} +16 -3
  11. package/dist/chunk-MB6563TL.js.map +1 -0
  12. package/dist/{chunk-SH55Z5QA.js → chunk-O3D4KYFG.js} +3 -3
  13. package/dist/{chunk-SH55Z5QA.js.map → chunk-O3D4KYFG.js.map} +1 -1
  14. package/dist/{chunk-SNN6O7ON.js → chunk-PP2LOT4W.js} +43 -7
  15. package/dist/chunk-PP2LOT4W.js.map +1 -0
  16. package/dist/{chunk-HIATVS2E.js → chunk-SZY7X4M2.js} +3 -3
  17. package/dist/{chunk-HIATVS2E.js.map → chunk-SZY7X4M2.js.map} +1 -1
  18. package/dist/{chunk-M4UKIJ5K.js → chunk-TC3GLA5D.js} +28 -13
  19. package/dist/chunk-TC3GLA5D.js.map +1 -0
  20. package/dist/{chunk-X7G2CCW4.js → chunk-TITPPC54.js} +3 -3
  21. package/dist/{chunk-X7G2CCW4.js.map → chunk-TITPPC54.js.map} +1 -1
  22. package/dist/{chunk-NRWDQBZ7.js → chunk-VBRXFLIP.js} +3 -3
  23. package/dist/{chunk-NRWDQBZ7.js.map → chunk-VBRXFLIP.js.map} +1 -1
  24. package/dist/{chunk-MY7TSVO7.js → chunk-Y3UCU4ZK.js} +6 -2
  25. package/dist/chunk-Y3UCU4ZK.js.map +1 -0
  26. package/dist/{chunk-OJ7G56I7.js → chunk-Y6FV73IH.js} +57 -3
  27. package/dist/chunk-Y6FV73IH.js.map +1 -0
  28. package/dist/cli/index.js +69 -40
  29. package/dist/cli/index.js.map +1 -1
  30. package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
  31. package/dist/cli/src/commands/library-index.d.ts +12 -2
  32. package/dist/cli/src/commands/library-index.d.ts.map +1 -1
  33. package/dist/cli/src/commands/library-publish.d.ts.map +1 -1
  34. package/dist/cli/src/commands/manage.d.ts.map +1 -1
  35. package/dist/cli/src/commands/publish-core.d.ts +24 -0
  36. package/dist/cli/src/commands/publish-core.d.ts.map +1 -1
  37. package/dist/cli/src/commands/session-logs/remote-query.d.ts.map +1 -1
  38. package/dist/cli/src/commands/session-logs/remote-tail.d.ts.map +1 -1
  39. package/dist/cli/src/commands/session-logs/superjson-transformer.d.ts +12 -0
  40. package/dist/cli/src/commands/session-logs/superjson-transformer.d.ts.map +1 -0
  41. package/dist/cli/src/commands/source-manifest-publish.d.ts.map +1 -1
  42. package/dist/cli/src/commands/store.d.ts.map +1 -1
  43. package/dist/cli/src/store-auth.d.ts +11 -0
  44. package/dist/cli/src/store-auth.d.ts.map +1 -1
  45. package/dist/cli/src/store-publisher.d.ts +24 -1
  46. package/dist/cli/src/store-publisher.d.ts.map +1 -1
  47. package/dist/connectors/config.js +1 -1
  48. package/dist/connectors/index.js +2 -2
  49. package/dist/connectors/src/config.d.ts +21 -0
  50. package/dist/connectors/src/config.d.ts.map +1 -1
  51. package/dist/connectors/src/index.d.ts +1 -1
  52. package/dist/connectors/src/index.d.ts.map +1 -1
  53. package/dist/{ensure-sources-ORACQA4I.js → ensure-sources-NXBYK5GP.js} +4 -4
  54. package/dist/{ensure-sources-ORACQA4I.js.map → ensure-sources-NXBYK5GP.js.map} +1 -1
  55. package/dist/factory-assets/connectors/box.js +2 -2
  56. package/dist/factory-assets/connectors/deploy.js +2 -2
  57. package/dist/factory-assets/connectors/devserver.js +2 -2
  58. package/dist/factory-assets/connectors/flow/adapter.js +2 -2
  59. package/dist/factory-assets/connectors/flow/run-flow.js +3 -3
  60. package/dist/factory-assets/connectors/flow.js +2 -2
  61. package/dist/factory-assets/connectors/git.js +2 -2
  62. package/dist/factory-assets/connectors/gmail.js +2 -2
  63. package/dist/factory-assets/connectors/googledrive.js +2 -2
  64. package/dist/factory-assets/connectors/local.js +2 -2
  65. package/dist/factory-assets/connectors/mattermost.js +2 -2
  66. package/dist/factory-assets/connectors/memory.js +2 -2
  67. package/dist/factory-assets/connectors/minio.js +2 -2
  68. package/dist/factory-assets/connectors/postgres.js +2 -2
  69. package/dist/factory-assets/connectors/s3.js +2 -2
  70. package/dist/factory-assets/connectors/sharepoint.js +2 -2
  71. package/dist/factory-assets/connectors/sqlite.js +2 -2
  72. package/dist/factory-assets/connectors/static-server.js +2 -2
  73. package/dist/factory-assets/connectors/tunnel.js +2 -2
  74. package/dist/factory-assets/connectors/webdav.js +2 -2
  75. package/dist/factory-assets/connectors/xstate-store.js +2 -2
  76. package/dist/factory-assets/connectors/xstate.js +2 -2
  77. package/dist/{helpers-SXGIHFCF.js → helpers-DN4MWOHB.js} +4 -4
  78. package/dist/{helpers-SXGIHFCF.js.map → helpers-DN4MWOHB.js.map} +1 -1
  79. package/dist/{library-publish-NQQFPOUY.js → library-publish-TPWFSO3Q.js} +24 -8
  80. package/dist/library-publish-TPWFSO3Q.js.map +1 -0
  81. package/dist/{open-library-ODW2PJ2J.js → open-library-ST2VFQTK.js} +5 -5
  82. package/dist/{open-library-ODW2PJ2J.js.map → open-library-ST2VFQTK.js.map} +1 -1
  83. package/dist/runner/index.js +4 -4
  84. package/dist/runner/src/resources.d.ts +8 -2
  85. package/dist/runner/src/resources.d.ts.map +1 -1
  86. package/dist/runner/src/serve.d.ts.map +1 -1
  87. package/dist/runner/src/session-builder.d.ts +10 -0
  88. package/dist/runner/src/session-builder.d.ts.map +1 -1
  89. package/dist/sdk/asset-manager.js +1 -1
  90. package/dist/sdk/index.js +4 -4
  91. package/dist/sdk/runner.js +4 -4
  92. package/dist/{source-KPH66TXY.js → source-R4TWF424.js} +6 -6
  93. package/dist/{source-KPH66TXY.js.map → source-R4TWF424.js.map} +1 -1
  94. package/dist/{source-manifest-publish-HJ5G4CTH.js → source-manifest-publish-FXDK2BCI.js} +12 -10
  95. package/dist/source-manifest-publish-FXDK2BCI.js.map +1 -0
  96. package/dist/tui/index.js +4 -4
  97. package/dist/workspace-plugin/index.js +1 -1
  98. package/package.json +1 -1
  99. package/dist/chunk-M4UKIJ5K.js.map +0 -1
  100. package/dist/chunk-MY7TSVO7.js.map +0 -1
  101. package/dist/chunk-OJ7G56I7.js.map +0 -1
  102. package/dist/chunk-SNN6O7ON.js.map +0 -1
  103. package/dist/chunk-Y5B5272E.js.map +0 -1
  104. package/dist/library-publish-NQQFPOUY.js.map +0 -1
  105. package/dist/source-manifest-publish-HJ5G4CTH.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../cli/src/store-auth.ts","../cli/src/store-client.ts"],"names":["readFileSync"],"mappings":";;;;;;AAsBA,SAAS,YAAA,GAAwD;AAC/D,EAAA,MAAM,QAAA,GAAW,WAAA,CAAY,EAAE,CAAA,CAAE,SAAS,WAAW,CAAA;AACrD,EAAA,MAAM,SAAA,GAAY,WAAW,QAAQ,CAAA,CAAE,OAAO,QAAQ,CAAA,CAAE,OAAO,WAAW,CAAA;AAC1E,EAAA,OAAO,EAAE,UAAU,SAAA,EAAU;AAC/B;AAUA,SAAS,kBAAkB,GAAA,EAAqB;AAC9C,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC/B;AAQO,SAAS,mBAAA,GAAuC;AACrD,EAAA,MAAM,OAAO,OAA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AA;AAAA,EACtB;AACF;AASO,SAAS,oBAAA,GAAgC;AAC9C,EAAA,OAAO,aAAA,CAAc,qBAAqB,CAAA;AAC5C","file":"chunk-MB6563TL.js","sourcesContent":["/**\n * Keycloak Device Authorization Grant (RFC 8628) for the store CLI: a public\n * device-flow client (`skaile-store-cli`) issues a plain realm JWT the store's\n * `AuthGuard` accepts — a CLI can't use the storefront's confidential browser\n * client. Tokens cache at `~/.skaile/auth.json` (0600, shared with `store/cli`);\n * `getAccessToken` refreshes transparently. All targets are env-overridable.\n *\n * @docLink cli/dev-guide#store-auth\n */\nimport { createHash, randomBytes } from \"node:crypto\";\nimport { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\n/**\n * A PKCE (RFC 7636) `code_verifier` + its S256 `code_challenge`. Keycloak\n * enforces PKCE on the `skaile-store-cli` device flow (the device-authorization\n * request 400s with \"Missing parameter: code_challenge_method\" otherwise), so\n * every `deviceLogin` mints a fresh pair: the challenge goes on the device-auth\n * request, the verifier on the matching token poll. `base64url` (no padding)\n * per the spec.\n */\nfunction makePkcePair(): { verifier: string; challenge: string } {\n const verifier = randomBytes(32).toString(\"base64url\");\n const challenge = createHash(\"sha256\").update(verifier).digest(\"base64url\");\n return { verifier, challenge };\n}\n\n/** Resolved auth targets — every field has a prod default, all env-overridable. */\nexport interface StoreAuthConfig {\n keycloakUrl: string;\n realm: string;\n clientId: string;\n authFile: string;\n}\n\nfunction trimTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, \"\");\n}\n\n/**\n * Load the auth config. Defaults target the production store\n * (`auth.skaile.ai`, realm `skaile-store`, public client `skaile-store-cli`);\n * override with `SKAILE_KEYCLOAK_URL` / `SKAILE_STORE_REALM` /\n * `SKAILE_STORE_CLI_CLIENT` / `SKAILE_AUTH_FILE` for dev or a preview deploy.\n */\nexport function loadStoreAuthConfig(): StoreAuthConfig {\n const home = process.env.SKAILE_HOME ?? join(homedir(), \".skaile\");\n return {\n keycloakUrl: trimTrailingSlash(process.env.SKAILE_KEYCLOAK_URL ?? \"https://auth.skaile.ai\"),\n realm: process.env.SKAILE_STORE_REALM ?? \"skaile-store\",\n clientId: process.env.SKAILE_STORE_CLI_CLIENT ?? \"skaile-store-cli\",\n authFile: process.env.SKAILE_AUTH_FILE ?? join(home, \"auth.json\"),\n };\n}\n\n/** Keycloak OIDC endpoints derived from the realm base. */\nfunction oidc(config: StoreAuthConfig): { deviceAuth: string; token: string } {\n const base = `${config.keycloakUrl}/realms/${config.realm}/protocol/openid-connect`;\n return { deviceAuth: `${base}/auth/device`, token: `${base}/token` };\n}\n\nexport interface StoredAuth {\n access_token: string;\n refresh_token?: string;\n /** Epoch ms when the access token expires (with a safety margin already applied). */\n expires_at: number;\n}\n\ninterface TokenResponse {\n access_token: string;\n refresh_token?: string;\n expires_in?: number;\n error?: string;\n error_description?: string;\n}\n\ninterface DeviceAuthResponse {\n device_code: string;\n user_code: string;\n verification_uri: string;\n verification_uri_complete?: string;\n interval?: number;\n expires_in: number;\n}\n\n/** Refresh this many ms before real expiry so an in-flight call never 401s. */\nconst EXPIRY_MARGIN_MS = 30_000;\n\n/** Injectable seams so the poll loop is unit-testable without real time or network. */\nexport interface AuthDeps {\n fetchImpl?: typeof fetch;\n sleep?: (ms: number) => Promise<void>;\n /** Called once with the verification URL + user code (default: write to stderr). */\n onPrompt?: (url: string, userCode: string) => void;\n}\n\nfunction readAuth(config: StoreAuthConfig): StoredAuth | null {\n try {\n const parsed = JSON.parse(readFileSync(config.authFile, \"utf-8\"));\n // Reject a corrupt / hand-edited file rather than treat it as a session.\n if (parsed && typeof parsed.access_token === \"string\") return parsed as StoredAuth;\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * The caller's store identity, decoded LOCALLY from the cached token's JWT\n * payload (no network, no signature check — this is an author-side hint, not an\n * authorization decision). Returns `null` when not signed in or the token is\n * unreadable. `githubLogin` is the verified GitHub handle (the preferred\n * publisher namespace); `username` is the Keycloak `preferred_username`.\n */\nexport function getStoreIdentity(\n config: StoreAuthConfig = loadStoreAuthConfig(),\n): { username?: string; githubLogin?: string } | null {\n const auth = readAuth(config);\n if (!auth) return null;\n try {\n const payload = auth.access_token.split(\".\")[1];\n const json = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf-8\"));\n const username = typeof json.preferred_username === \"string\" ? json.preferred_username : undefined;\n const githubLogin = typeof json.github_login === \"string\" ? json.github_login : undefined;\n return username || githubLogin ? { username, githubLogin } : null;\n } catch {\n return null;\n }\n}\n\nfunction writeAuth(config: StoreAuthConfig, auth: StoredAuth): void {\n mkdirSync(dirname(config.authFile), { recursive: true });\n writeFileSync(config.authFile, JSON.stringify(auth, null, 2), { mode: 0o600 });\n chmodSync(config.authFile, 0o600);\n}\n\n/** Remove the cached session (sign out). */\nexport function logout(config: StoreAuthConfig): void {\n try {\n rmSync(config.authFile);\n } catch {\n // already absent — nothing to do\n }\n}\n\n/** True when a cached, well-formed session exists (validity/refresh resolved on use). */\nexport function hasStoredAuth(config: StoreAuthConfig): boolean {\n return readAuth(config) !== null;\n}\n\nfunction tokenToStored(token: TokenResponse): StoredAuth {\n return {\n access_token: token.access_token,\n refresh_token: token.refresh_token,\n expires_at: Date.now() + (token.expires_in ?? 300) * 1000 - EXPIRY_MARGIN_MS,\n };\n}\n\nconst defaultSleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\nfunction defaultPrompt(url: string, userCode: string): void {\n process.stderr.write(\n `\\nTo sign in, open:\\n\\n ${url}\\n\\nand enter the code: ${userCode}\\n\\nWaiting for approval…\\n`,\n );\n}\n\n/**\n * Run the device flow to completion, persisting tokens on success. Prints the\n * verification URL + user code for the operator to approve in a browser.\n */\nexport async function deviceLogin(\n config: StoreAuthConfig,\n deps: AuthDeps = {},\n): Promise<StoredAuth> {\n const fetchImpl = deps.fetchImpl ?? fetch;\n const sleep = deps.sleep ?? defaultSleep;\n const onPrompt = deps.onPrompt ?? defaultPrompt;\n const endpoints = oidc(config);\n const pkce = makePkcePair();\n\n const deviceRes = await fetchImpl(endpoints.deviceAuth, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n client_id: config.clientId,\n scope: \"openid profile\",\n code_challenge: pkce.challenge,\n code_challenge_method: \"S256\",\n }),\n });\n if (!deviceRes.ok) {\n throw new Error(\n `Device authorization request failed (${deviceRes.status}): ${await deviceRes.text()}`,\n );\n }\n const device = (await deviceRes.json()) as DeviceAuthResponse;\n\n onPrompt(device.verification_uri_complete ?? device.verification_uri, device.user_code);\n\n const intervalMs = (device.interval ?? 5) * 1000;\n const deadline = Date.now() + device.expires_in * 1000;\n let waitMs = intervalMs;\n\n while (Date.now() < deadline) {\n await sleep(waitMs);\n const tokenRes = await fetchImpl(endpoints.token, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n device_code: device.device_code,\n client_id: config.clientId,\n code_verifier: pkce.verifier,\n }),\n });\n const token = (await tokenRes.json()) as TokenResponse;\n if (tokenRes.ok) {\n const stored = tokenToStored(token);\n writeAuth(config, stored);\n return stored;\n }\n // RFC 8628 §3.5 pending / slow-down handling.\n if (token.error === \"authorization_pending\") continue;\n if (token.error === \"slow_down\") {\n waitMs += 5_000;\n continue;\n }\n throw new Error(`Sign-in failed: ${token.error_description ?? token.error ?? \"unknown error\"}`);\n }\n throw new Error(\"Sign-in timed out before approval.\");\n}\n\n/** Exchange a refresh token for a fresh access token; persist on success. */\nasync function refresh(\n config: StoreAuthConfig,\n refreshToken: string,\n fetchImpl: typeof fetch,\n): Promise<StoredAuth> {\n const res = await fetchImpl(oidc(config).token, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n grant_type: \"refresh_token\",\n refresh_token: refreshToken,\n client_id: config.clientId,\n }),\n });\n const token = (await res.json()) as TokenResponse;\n if (!res.ok) {\n throw new Error(\n `Token refresh failed: ${token.error_description ?? token.error ?? res.status}`,\n );\n }\n const stored = tokenToStored(token);\n writeAuth(config, stored);\n return stored;\n}\n\n/**\n * Return a valid access token, refreshing if it is expired (or about to). Throws\n * a clear \"run `skaile store login`\" error when there is no usable session.\n */\nexport async function getAccessToken(\n config: StoreAuthConfig,\n deps: AuthDeps = {},\n): Promise<string> {\n const fetchImpl = deps.fetchImpl ?? fetch;\n const auth = readAuth(config);\n if (!auth) throw new Error(\"Not signed in. Run `skaile store login` first.\");\n if (Date.now() < auth.expires_at) return auth.access_token;\n if (!auth.refresh_token) throw new Error(\"Session expired. Run `skaile store login` again.\");\n try {\n return (await refresh(config, auth.refresh_token, fetchImpl)).access_token;\n } catch {\n throw new Error(\"Session expired and refresh failed. Run `skaile store login` again.\");\n }\n}\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { globalSettingsPath, mapLegacyFields } from \"@skaile/workspaces/core\";\nimport { type AuthDeps, getAccessToken, hasStoredAuth, loadStoreAuthConfig } from \"./store-auth.ts\";\n\n/**\n * Connection configuration for the AI Asset Store API. `jwt` is normally left\n * null here and filled per-call by the caller from {@link getStoreToken} (the\n * device-flow session); it stays on the type for the `{ ...config, jwt }` spread.\n *\n * @docLink cli/dev-guide#store-client\n */\nexport interface StoreConfig {\n url: string;\n jwt: string | null;\n}\n\n/**\n * Read the store API base URL (settings `storeUrl` → `SKAILE_STORE_URL` →\n * default). Auth is not read here — it lives in the device-flow session; see\n * {@link getStoreToken}.\n *\n * @docLink cli/dev-guide#store-client\n */\nexport function getStoreConfig(): StoreConfig {\n const settingsPath = globalSettingsPath();\n let settings: Record<string, any> = {};\n if (existsSync(settingsPath)) {\n try {\n settings = mapLegacyFields(JSON.parse(readFileSync(settingsPath, \"utf-8\")));\n } catch {\n settings = {};\n }\n }\n return {\n url: settings.storeUrl ?? process.env.SKAILE_STORE_URL ?? \"https://api.skaile.store\",\n jwt: null,\n };\n}\n\n/**\n * Return a valid store access token (Keycloak device-flow session, refreshed if\n * needed). Throws a \"run `skaile store login`\" error when there is no session.\n * This is the auth source for every `/api/v1/*` publisher call.\n */\nexport function getStoreToken(deps?: AuthDeps): Promise<string> {\n return getAccessToken(loadStoreAuthConfig(), deps);\n}\n\n/**\n * Make an authenticated HTTP request to the store REST API.\n *\n * @param config - Store connection config (URL + auth token).\n * @param path - API path (e.g. `/api/assets`).\n * @param opts - Optional method, body, query params, extra headers, and\n * `timeoutMs` (default 1500). Publisher calls pass a longer timeout because\n * they trigger server-side clone/sync work.\n * @returns Parsed JSON response body.\n * @docLink cli/dev-guide#store-client\n */\nexport async function storeFetch<T = any>(\n config: StoreConfig,\n path: string,\n opts?: {\n method?: string;\n body?: unknown;\n params?: Record<string, string>;\n headers?: Record<string, string>;\n timeoutMs?: number;\n },\n): Promise<T> {\n let url = `${config.url}${path}`;\n if (opts?.params) {\n const sp = new URLSearchParams(opts.params);\n url += `?${sp}`;\n }\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n ...(opts?.headers ?? {}),\n };\n if (config.jwt) {\n headers.Authorization = `Bearer ${config.jwt}`;\n }\n\n const fetchOpts: RequestInit = {\n method: opts?.method ?? \"GET\",\n headers,\n };\n if (opts?.body) {\n fetchOpts.body = JSON.stringify(opts.body);\n }\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), opts?.timeoutMs ?? 1_500);\n try {\n const res = await fetch(url, { ...fetchOpts, signal: controller.signal });\n if (!res.ok) {\n const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));\n // Prefer the store's human-readable `message` (e.g. \"Namespace '@x' is\n // reserved … Sign in with GitHub to claim it\") over the bare `error` code\n // (`UNPROCESSABLE_CONTENT`) — the message is the actionable part.\n const b = body as { message?: string; error?: string };\n throw new Error(b.message ?? b.error ?? `Store API error: ${res.status}`);\n }\n return res.json() as Promise<T>;\n } finally {\n clearTimeout(timeout);\n }\n}\n\n/**\n * Return `true` when a store session exists (a Keycloak device-flow token cached\n * at `~/.skaile/auth.json`). Validity/refresh is resolved on use via\n * {@link getStoreToken}.\n *\n * @docLink cli/dev-guide#store-client\n */\nexport function isStoreAuthenticated(): boolean {\n return hasStoredAuth(loadStoreAuthConfig());\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { softDepName } from './chunk-MY7TSVO7.js';
1
+ import { softDepName } from './chunk-Y3UCU4ZK.js';
2
2
  import pc from 'picocolors';
3
3
 
4
4
  var S = {
@@ -94,5 +94,5 @@ function formatRelativeTime(date) {
94
94
  }
95
95
 
96
96
  export { KIND_COL_WIDTH, S, bareSoftDepName, colorRef, fitWidth, formatRelativeTime, formatSoftDepAddPreview, formatSoftDepHint, formatSoftDepRemovePreview, formatSoftDepSection, kindColor, kindColorPad, logErr, logInfo, logOk, logWarn };
97
- //# sourceMappingURL=chunk-SH55Z5QA.js.map
98
- //# sourceMappingURL=chunk-SH55Z5QA.js.map
97
+ //# sourceMappingURL=chunk-O3D4KYFG.js.map
98
+ //# sourceMappingURL=chunk-O3D4KYFG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/helpers.ts"],"names":[],"mappings":";;;AAQO,IAAM,CAAA,GAAI;AAAA,EACf,KAAA,EAAO,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,EAAA,CAAG,IAAA,CAAK,CAAC,CAAC,CAAA;AAAA,EACxC,GAAA,EAAK,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,CAAC,CAAA;AAAA,EAC7B,OAAA,EAAS,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,CAAC,CAAA;AAAA,EACjC,IAAA,EAAM,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,CAAC,CAAA;AAAA,EAC9B,GAAA,EAAK,CAAC,CAAA,KAAc,EAAA,CAAG,IAAI,CAAC,CAAA;AAAA,EAC5B,EAAA,EAAI,CAAC,CAAA,KAAc,EAAA,CAAG,MAAM,CA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A,IAAI,OAAA,CAAQ,MAAA,KAAW,CAAA,EAAG,OAAO,EAAA;AACjC,EAAA,OAAO,CAAA,CAAE,IAAI,CAAA,SAAA,EAAY,IAAI,iBAAiB,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,WAAA,CAAa,CAAA;AAC/E;AAGO,SAAS,mBAAmB,IAAA,EAAoB;AACrD,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,EAAI,GAAI,KAAK,OAAA,EAAQ;AACvC,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,IAAA,GAAO,GAAI,CAAA;AACtC,EAAA,IAAI,OAAA,GAAU,IAAI,OAAO,UAAA;AACzB,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,OAAA,GAAU,EAAE,CAAA;AACvC,EAAA,IAAI,OAAA,GAAU,EAAA,EAAI,OAAO,CAAA,EAAG,OAAO,CAAA,KAAA,CAAA;AACnC,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,OAAA,GAAU,EAAE,CAAA;AACrC,EAAA,IAAI,KAAA,GAAQ,EAAA,EAAI,OAAO,CAAA,EAAG,KAAK,CAAA,KAAA,CAAA;AAC/B,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,KAAA,GAAQ,EAAE,CAAA;AAClC,EAAA,OAAO,GAAG,IAAI,CAAA,KAAA,CAAA;AAChB","file":"chunk-SH55Z5QA.js","sourcesContent":["import { softDepName } from \"@skaile/workspaces/asset-manager\";\nimport pc from \"picocolors\";\n\n/**\n * Terminal styling helpers used across all CLI commands.\n *\n * @docLink cli/dev-guide#helpers\n */\nexport const S = {\n brand: (s: string) => pc.cyan(pc.bold(s)),\n cmd: (s: string) => pc.cyan(s),\n heading: (s: string) => pc.bold(s),\n bold: (s: string) => pc.bold(s),\n dim: (s: string) => pc.dim(s),\n ok: (s: string) => pc.green(s),\n warn: (s: string) => pc.yellow(s),\n err: (s: string) => pc.red(s),\n label: (s: string) => pc.dim(s),\n rule: (w = 40) => pc.dim(\"─\".repeat(w)),\n};\n\nconst KIND_COLORS: Record<string, (s: string) => string> = {\n skill: pc.blue,\n agent: pc.magenta,\n prompt: pc.yellow,\n flow: pc.green,\n bundle: pc.cyan,\n contract: pc.red,\n connector: pc.green,\n mount: pc.green,\n knowledge: pc.cyan,\n persona: pc.cyan,\n ruleset: pc.cyan,\n \"mcp-server\": pc.magenta,\n};\n\n/**\n * Fit a plain (ANSI-free) string into exactly `width` columns: truncate with a\n * trailing `…` when too long, pad with spaces when too short. Keeps fixed-width\n * columns from overflowing the row when a value (e.g. an asset name) is wider\n * than its budget.\n */\nexport function fitWidth(s: string, width: number): string {\n if (width <= 0) return \"\";\n if (s.length > width) return width === 1 ? \"…\" : `${s.slice(0, width - 1)}…`;\n return s.padEnd(width);\n}\n\n/** Color-code an asset kind string. */\nexport function kindColor(kind: string): string {\n const colorFn = KIND_COLORS[kind] ?? pc.dim;\n return colorFn(kind);\n}\n\n/**\n * Widest kind label (`mcp-server`); the default kind-column width fits it so\n * long kinds don't shove the rest of the row out of alignment.\n */\nexport const KIND_COL_WIDTH = 10;\n\n/**\n * Color-code an asset kind string fit to exactly `width` columns — pads short\n * kinds, truncates over-long ones (via {@link fitWidth}) so the column can never\n * overflow and break row alignment.\n */\nexport function kindColorPad(kind: string, width = KIND_COL_WIDTH): string {\n const colorFn = KIND_COLORS[kind] ?? pc.dim;\n return colorFn(fitWidth(kind, width));\n}\n\n/** Color-code a \"kind:name\" reference string. */\nexport function colorRef(ref: string): string {\n const colonIdx = ref.indexOf(\":\");\n if (colonIdx === -1) return ref;\n const kind = ref.slice(0, colonIdx);\n const rest = ref.slice(colonIdx);\n return `${kindColor(kind)}${rest}`;\n}\n\n/**\n * Print a success line prefixed with a green check mark.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logOk(msg: string) {\n console.log(` ${pc.green(\"✓\")} ${msg}`);\n}\n/**\n * Print an error line prefixed with a red cross to stderr.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logErr(msg: string) {\n console.error(` ${pc.red(\"✗\")} ${msg}`);\n}\n/**\n * Print a warning line prefixed with a yellow exclamation mark.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logWarn(msg: string) {\n console.log(` ${pc.yellow(\"!\")} ${msg}`);\n}\n/**\n * Print an info line prefixed with a dim dot.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logInfo(msg: string) {\n console.log(` ${pc.dim(\"·\")} ${msg}`);\n}\n\n/**\n * Bare asset name of a canonical soft-dep target ref (`@pub/name@ver` → `name`),\n * for compact rendering in `info` / `tree` / `why`. Delegates to the asset-manager\n * parser (the soft-dep read surface) so the two never diverge.\n */\nexport function bareSoftDepName(ref: string): string {\n return softDepName(ref);\n}\n\n/**\n * The report-only soft-dep hint line shared by the `add` no-TTY branch and the\n * `install` surface, so the two user-facing wordings can't drift. Appends a\n * runnable `skaile add` suffix only when the target has a parseable ref.\n */\nexport function formatSoftDepHint(edge: { from: string; to: string; toRef?: string }): string {\n const suffix = edge.toRef ? ` — run \\`skaile add ${edge.toRef}\\` to include it.` : \"\";\n return `${bareSoftDepName(edge.from)} references ${bareSoftDepName(edge.to)} (soft dependency)${suffix}`;\n}\n\n/**\n * Build the \"Soft dependencies (inferred)\" section for `skaile info`. Returns one\n * header line plus one line per soft-dep target, each marked `(soft)` to read\n * differently from a typed `requires`. Empty array when there are no soft deps,\n * so the caller prints nothing.\n */\nexport function formatSoftDepSection(targets: string[]): string[] {\n if (targets.length === 0) return [];\n const out = [` ${S.label(\"Soft dependencies (inferred)\")}:`];\n for (const t of targets) out.push(` ${S.dim(\"·\")} ${t} ${S.dim(\"(soft)\")}`);\n return out;\n}\n\n/**\n * Footer line previewing the soft deps that *adding* the highlighted asset would\n * reference (manage TUI). \"references\" + \"not auto-added\" makes clear the pull is\n * report-only. Empty string when there are no targets, so the caller clears.\n */\nexport function formatSoftDepAddPreview(name: string, targets: string[]): string {\n if (targets.length === 0) return \"\";\n return S.dim(`${name} references ${targets.join(\", \")} (soft dep, not auto-added)`);\n}\n\n/**\n * Footer line previewing the soft deps that *removing* the highlighted asset\n * would orphan (manage TUI) — symmetric with {@link formatSoftDepAddPreview}.\n * Empty string when nothing would be orphaned, so the caller clears.\n */\nexport function formatSoftDepRemovePreview(name: string, targets: string[]): string {\n if (targets.length === 0) return \"\";\n return S.dim(`removing ${name} would orphan ${targets.join(\", \")} (soft dep)`);\n}\n\n/** Format a Date as a human-readable relative time string (e.g. \"5m ago\"). */\nexport function formatRelativeTime(date: Date): string {\n const diff = Date.now() - date.getTime();\n const seconds = Math.floor(diff / 1000);\n if (seconds < 60) return \"just now\";\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n return `${days}d ago`;\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/helpers.ts"],"names":[],"mappings":";;;AAQO,IAAM,CAAA,GAAI;AAAA,EACf,KAAA,EAAO,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,EAAA,CAAG,IAAA,CAAK,CAAC,CAAC,CAAA;AAAA,EACxC,GAAA,EAAK,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,CAAC,CAAA;AAAA,EAC7B,OAAA,EAAS,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,CAAC,CAAA;AAAA,EACjC,IAAA,EAAM,CAAC,CAAA,KAAc,EAAA,CAAG,KAAK,CAAC,CAAA;AAAA,EAC9B,GAAA,EAAK,CAAC,CAAA,KAAc,EAAA,CAAG,IAAI,CAAC,CAAA;AAAA,EAC5B,EAAA,EAAI,CAAC,CAAA,KAAc,EAAA,CAAG,MAAM,CAAC,CAAA;AAAA,EAC7B,IAAA,EAAM,CAAC,CAAA,KAAc,EAAA,C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jC,EAAA,OAAO,CAAA,CAAE,IAAI,CAAA,SAAA,EAAY,IAAI,iBAAiB,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,WAAA,CAAa,CAAA;AAC/E;AAGO,SAAS,mBAAmB,IAAA,EAAoB;AACrD,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,EAAI,GAAI,KAAK,OAAA,EAAQ;AACvC,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,IAAA,GAAO,GAAI,CAAA;AACtC,EAAA,IAAI,OAAA,GAAU,IAAI,OAAO,UAAA;AACzB,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,KAAA,CAAM,OAAA,GAAU,EAAE,CAAA;AACvC,EAAA,IAAI,OAAA,GAAU,EAAA,EAAI,OAAO,CAAA,EAAG,OAAO,CAAA,KAAA,CAAA;AACnC,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,OAAA,GAAU,EAAE,CAAA;AACrC,EAAA,IAAI,KAAA,GAAQ,EAAA,EAAI,OAAO,CAAA,EAAG,KAAK,CAAA,KAAA,CAAA;AAC/B,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,KAAA,GAAQ,EAAE,CAAA;AAClC,EAAA,OAAO,GAAG,IAAI,CAAA,KAAA,CAAA;AAChB","file":"chunk-O3D4KYFG.js","sourcesContent":["import { softDepName } from \"@skaile/workspaces/asset-manager\";\nimport pc from \"picocolors\";\n\n/**\n * Terminal styling helpers used across all CLI commands.\n *\n * @docLink cli/dev-guide#helpers\n */\nexport const S = {\n brand: (s: string) => pc.cyan(pc.bold(s)),\n cmd: (s: string) => pc.cyan(s),\n heading: (s: string) => pc.bold(s),\n bold: (s: string) => pc.bold(s),\n dim: (s: string) => pc.dim(s),\n ok: (s: string) => pc.green(s),\n warn: (s: string) => pc.yellow(s),\n err: (s: string) => pc.red(s),\n label: (s: string) => pc.dim(s),\n rule: (w = 40) => pc.dim(\"─\".repeat(w)),\n};\n\nconst KIND_COLORS: Record<string, (s: string) => string> = {\n skill: pc.blue,\n agent: pc.magenta,\n prompt: pc.yellow,\n flow: pc.green,\n bundle: pc.cyan,\n contract: pc.red,\n connector: pc.green,\n mount: pc.green,\n knowledge: pc.cyan,\n persona: pc.cyan,\n ruleset: pc.cyan,\n \"mcp-server\": pc.magenta,\n};\n\n/**\n * Fit a plain (ANSI-free) string into exactly `width` columns: truncate with a\n * trailing `…` when too long, pad with spaces when too short. Keeps fixed-width\n * columns from overflowing the row when a value (e.g. an asset name) is wider\n * than its budget.\n */\nexport function fitWidth(s: string, width: number): string {\n if (width <= 0) return \"\";\n if (s.length > width) return width === 1 ? \"…\" : `${s.slice(0, width - 1)}…`;\n return s.padEnd(width);\n}\n\n/** Color-code an asset kind string. */\nexport function kindColor(kind: string): string {\n const colorFn = KIND_COLORS[kind] ?? pc.dim;\n return colorFn(kind);\n}\n\n/**\n * Widest kind label (`mcp-server`); the default kind-column width fits it so\n * long kinds don't shove the rest of the row out of alignment.\n */\nexport const KIND_COL_WIDTH = 10;\n\n/**\n * Color-code an asset kind string fit to exactly `width` columns — pads short\n * kinds, truncates over-long ones (via {@link fitWidth}) so the column can never\n * overflow and break row alignment.\n */\nexport function kindColorPad(kind: string, width = KIND_COL_WIDTH): string {\n const colorFn = KIND_COLORS[kind] ?? pc.dim;\n return colorFn(fitWidth(kind, width));\n}\n\n/** Color-code a \"kind:name\" reference string. */\nexport function colorRef(ref: string): string {\n const colonIdx = ref.indexOf(\":\");\n if (colonIdx === -1) return ref;\n const kind = ref.slice(0, colonIdx);\n const rest = ref.slice(colonIdx);\n return `${kindColor(kind)}${rest}`;\n}\n\n/**\n * Print a success line prefixed with a green check mark.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logOk(msg: string) {\n console.log(` ${pc.green(\"✓\")} ${msg}`);\n}\n/**\n * Print an error line prefixed with a red cross to stderr.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logErr(msg: string) {\n console.error(` ${pc.red(\"✗\")} ${msg}`);\n}\n/**\n * Print a warning line prefixed with a yellow exclamation mark.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logWarn(msg: string) {\n console.log(` ${pc.yellow(\"!\")} ${msg}`);\n}\n/**\n * Print an info line prefixed with a dim dot.\n *\n * @param msg - Message to display.\n * @docLink cli/dev-guide#helpers\n */\nexport function logInfo(msg: string) {\n console.log(` ${pc.dim(\"·\")} ${msg}`);\n}\n\n/**\n * Bare asset name of a canonical soft-dep target ref (`@pub/name@ver` → `name`),\n * for compact rendering in `info` / `tree` / `why`. Delegates to the asset-manager\n * parser (the soft-dep read surface) so the two never diverge.\n */\nexport function bareSoftDepName(ref: string): string {\n return softDepName(ref);\n}\n\n/**\n * The report-only soft-dep hint line shared by the `add` no-TTY branch and the\n * `install` surface, so the two user-facing wordings can't drift. Appends a\n * runnable `skaile add` suffix only when the target has a parseable ref.\n */\nexport function formatSoftDepHint(edge: { from: string; to: string; toRef?: string }): string {\n const suffix = edge.toRef ? ` — run \\`skaile add ${edge.toRef}\\` to include it.` : \"\";\n return `${bareSoftDepName(edge.from)} references ${bareSoftDepName(edge.to)} (soft dependency)${suffix}`;\n}\n\n/**\n * Build the \"Soft dependencies (inferred)\" section for `skaile info`. Returns one\n * header line plus one line per soft-dep target, each marked `(soft)` to read\n * differently from a typed `requires`. Empty array when there are no soft deps,\n * so the caller prints nothing.\n */\nexport function formatSoftDepSection(targets: string[]): string[] {\n if (targets.length === 0) return [];\n const out = [` ${S.label(\"Soft dependencies (inferred)\")}:`];\n for (const t of targets) out.push(` ${S.dim(\"·\")} ${t} ${S.dim(\"(soft)\")}`);\n return out;\n}\n\n/**\n * Footer line previewing the soft deps that *adding* the highlighted asset would\n * reference (manage TUI). \"references\" + \"not auto-added\" makes clear the pull is\n * report-only. Empty string when there are no targets, so the caller clears.\n */\nexport function formatSoftDepAddPreview(name: string, targets: string[]): string {\n if (targets.length === 0) return \"\";\n return S.dim(`${name} references ${targets.join(\", \")} (soft dep, not auto-added)`);\n}\n\n/**\n * Footer line previewing the soft deps that *removing* the highlighted asset\n * would orphan (manage TUI) — symmetric with {@link formatSoftDepAddPreview}.\n * Empty string when nothing would be orphaned, so the caller clears.\n */\nexport function formatSoftDepRemovePreview(name: string, targets: string[]): string {\n if (targets.length === 0) return \"\";\n return S.dim(`removing ${name} would orphan ${targets.join(\", \")} (soft dep)`);\n}\n\n/** Format a Date as a human-readable relative time string (e.g. \"5m ago\"). */\nexport function formatRelativeTime(date: Date): string {\n const diff = Date.now() - date.getTime();\n const seconds = Math.floor(diff / 1000);\n if (seconds < 60) return \"just now\";\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24) return `${hours}h ago`;\n const days = Math.floor(hours / 24);\n return `${days}d ago`;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { getStoreConfig, getStoreToken, storeFetch } from './chunk-Y5B5272E.js';
2
- import { logErr, logWarn, logOk, logInfo } from './chunk-SH55Z5QA.js';
1
+ import { getStoreConfig, getStoreToken, storeFetch } from './chunk-MB6563TL.js';
2
+ import { S, logErr, logWarn, logOk, logInfo } from './chunk-O3D4KYFG.js';
3
3
 
4
4
  // cli/src/store-publisher.ts
5
5
  function makeHttpPublisherClient(config = getStoreConfig(), timeoutMs = 2e4) {
@@ -20,11 +20,43 @@ function makeHttpPublisherClient(config = getStoreConfig(), timeoutMs = 2e4) {
20
20
  body,
21
21
  ...dryRun ? { params: { dryRun: "1" } } : {}
22
22
  }),
23
- assetUnpublish: (id) => call(`/api/v1/assets/${id}/unpublish`, { method: "POST", body: {} })
23
+ assetUnpublish: (id) => call(`/api/v1/assets/${id}/unpublish`, { method: "POST", body: {} }),
24
+ namespaceAvailability: (ns) => call(`/api/v1/namespaces/${encodeURIComponent(ns)}/availability`)
24
25
  };
25
26
  }
26
27
 
27
28
  // cli/src/commands/publish-core.ts
29
+ function formatNamespaceAvailability(a) {
30
+ switch (a.status) {
31
+ case "owned-by-you":
32
+ case "available":
33
+ return `${S.ok("\u2713")} ${a.message}`;
34
+ case "claimable-by-you":
35
+ return `${S.warn("!")} ${a.message}`;
36
+ default:
37
+ return `${S.err("\u2717")} ${a.message}`;
38
+ }
39
+ }
40
+ async function preflightNamespace(client, namespace) {
41
+ let a;
42
+ try {
43
+ a = await client.namespaceAvailability(namespace);
44
+ } catch {
45
+ return { ok: true };
46
+ }
47
+ switch (a.status) {
48
+ case "owned-by-you":
49
+ case "available":
50
+ return { ok: true };
51
+ case "claimable-by-you":
52
+ return {
53
+ ok: false,
54
+ message: `@${namespace} isn't yours yet \u2014 claim it in the store first${a.claimMethod ? ` (${a.claimMethod})` : ""}, then re-run. ${a.message}`
55
+ };
56
+ default:
57
+ return { ok: false, message: `Cannot publish under @${namespace} \u2014 ${a.message}` };
58
+ }
59
+ }
28
60
  function matchCandidatesToManifest(candidates, manifest) {
29
61
  const wanted = new Set((manifest.assets ?? []).map((a) => `${a.kind}:${a.name}`));
30
62
  return candidates.filter((c) => wanted.has(`${c.kind}:${c.name}`));
@@ -58,7 +90,11 @@ async function publishToStore(opts) {
58
90
  const added = await pub.sourcesAdd({
59
91
  url: sourceUrl,
60
92
  ref,
61
- ...sidecar ? { sidecarUrl: sidecar.url, sidecarRef: sidecar.ref } : {}
93
+ ...sidecar ? { sidecarUrl: sidecar.url, sidecarRef: sidecar.ref } : {},
94
+ // Publish under the manifest's declared namespace; the store resolves a
95
+ // claimed Publisher when it differs from the caller's login, else defaults
96
+ // to `@<username>`. Omitted when the manifest carries no publisher.
97
+ ...manifest.publisher ? { namespace: manifest.publisher } : {}
62
98
  });
63
99
  sourceId = added.id;
64
100
  } catch (err) {
@@ -117,6 +153,6 @@ async function publishToStore(opts) {
117
153
  return { published };
118
154
  }
119
155
 
120
- export { bareName, makeHttpPublisherClient, publishToStore, refFor };
121
- //# sourceMappingURL=chunk-SNN6O7ON.js.map
122
- //# sourceMappingURL=chunk-SNN6O7ON.js.map
156
+ export { bareName, formatNamespaceAvailability, makeHttpPublisherClient, preflightNamespace, publishToStore, refFor };
157
+ //# sourceMappingURL=chunk-PP2LOT4W.js.map
158
+ //# sourceMappingURL=chunk-PP2LOT4W.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../cli/src/store-publisher.ts","../cli/src/commands/publish-core.ts"],"names":[],"mappings":";;;;AA+FO,SAAS,uBAAA,CACd,MAAA,GAAsB,cAAA,EAAe,EACrC,YAAY,GAAA,EACK;AAGjB,EAAA,MAAM,IAAA,GAAO,OACX,IAAA,EACA,IAAA,KACe;AACf,IAAA,MAAM,GAAA,GAAM,MAAM,aAAA,EAAc;AAChC,IAAA,OAAO,UAAA,CAAc,EAAE,GAAG,MAAA,EAAQ,GAAA,EAAI,EAAG,IAAA,EAAM,EAAE,SAAA,EAAW,GAAG,IAAA,EAAM,CAAA;AAAA,EACvE,CAAA;AACA,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAM,IAAA,CAAK,YAAY,CAAA;AAAA,IAC3B,UAAA,EAAY,CAAC,IAAA,KAAS,IAAA,CAAK,mBAAmB,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,CAAA;AAAA,IACtE,WAAA,EAAa,MAAM,IAAA,CAAK,iBAAiB,CAAA;AAAA,IACzC,UAAA,EAAY,CAAC,EAAA,KAAO,IAAA,CAAK,CAAA,gBAAA,EAAmB,EAAE,CAAA,KAAA,CAAA,EAAS,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,IAAI,CAAA;AAAA,IACnF,QAAQ,CAAC,KAAA,KAAU,IAAA,CAAK,CAAA,aAAA,EAAgB,KAAK,CAAA,CAAE,CAAA;AAAA,IAC/C,kBAAkB,CAAC,EAAA,KAAO,IAAA,CAAK,CAAA,gBAAA,EAAmB,EAAE,CAAA,WAAA,CAAa,CAAA;AAAA,IACjE,cAAc,CAAC,EAAA,KA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A,CAAY,CAAA;AAC/C,EAAA,KAAA,MAAW,CAAA,IAAK,SAAA,EAAW,OAAA,CAAQ,CAAA,EAAA,EAAK,CAAC,CAAA,CAAE,CAAA;AAC3C,EAAA,OAAO,EAAE,SAAA,EAAU;AACrB","file":"chunk-PP2LOT4W.js","sourcesContent":["/**\n * Typed REST client for the AI Asset Store **publisher** surface — the\n * curator-publish flow (`skaile source manifest publish` / `yank`). Thin\n * wrappers over {@link storeFetch}; every method maps 1:1 to an `/api/v1/…`\n * endpoint. The {@link PublisherClient} interface is injectable so the\n * orchestration in `commands/source-manifest-publish.ts` can be unit-tested\n * against a fake without a live store.\n *\n * @docLink cli/dev-guide#store-publisher\n */\n\nimport { getStoreConfig, getStoreToken, type StoreConfig, storeFetch } from \"./store-client.ts\";\n\n/**\n * The publisher REST surface used by the curator-publish flow. Kept minimal —\n * only the endpoints `runPublish` / `runYank` actually call. Response shapes\n * are narrowed to the fields the orchestration reads (the server returns more).\n */\nexport interface PublisherClient {\n /**\n * Identity of the caller. `username` is the Keycloak login (personal-tier\n * namespace); `githubLogin` is the verified GitHub handle when connected —\n * the namespace to publish under when it differs from the login.\n */\n me(): Promise<{ username: string; githubLogin?: string | null }>;\n /** Register (or re-register) a source; returns the created/existing row id. */\n sourcesAdd(body: {\n url: string;\n ref: string;\n sidecarUrl?: string;\n sidecarRef?: string;\n /**\n * Target publisher namespace (the manifest's `publisher`). When it differs\n * from the caller's login username, the store resolves the CLAIMED Publisher\n * for it (the store must already have the claim). Omitted → the store\n * defaults to `@<username>` (personal).\n */\n namespace?: string;\n }): Promise<{ id: string }>;\n /** List sources — used to recover an id when `sourcesAdd` rejects a dup url. */\n sourcesList(): Promise<Array<{ id: string; url: string }>>;\n /** Kick off a source sync; returns the async job id to poll. */\n sourceSync(id: string): Promise<{ jobId: string }>;\n /** Poll a job's terminal status + per-item results. */\n jobGet(\n jobId: string,\n ): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }>;\n /** Discovered publishable candidates for a synced source. */\n sourceCandidates(id: string): Promise<\n Array<{\n id: string;\n name: string;\n version: string;\n kind: string;\n published: boolean;\n assetRoot: string;\n }>\n >;\n /** Per-asset preview — the discovered file set + resolved candidate metadata. */\n assetPreview(id: string): Promise<{\n discoveredFiles: string[];\n candidate: { name: string; version: string; kind: string; publisherNamespace: string };\n }>;\n /**\n * Publish one asset. `dryRun` returns the would-be `{ manifest }` without\n * launching a job; the normal path returns `{ jobId }`.\n */\n assetPublish(\n id: string,\n body: { ref: string; files: string[] },\n dryRun?: boolean,\n ): Promise<{ jobId?: string; manifest?: unknown }>;\n /** Retract a published asset. Response body is ignored. */\n assetUnpublish(id: string): Promise<unknown>;\n /**\n * Read-only \"can I publish under `@<ns>` right now, and if not, what's the\n * path?\" probe. Backs the `publish --dry-run` namespace status line; its\n * `message` is store-authored and meant to be surfaced verbatim.\n */\n namespaceAvailability(ns: string): Promise<{\n namespace: string;\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n claimMethod?: string;\n message: string;\n }>;\n}\n\n/**\n * Construct the real HTTP-backed {@link PublisherClient}. Every call carries a\n * longer timeout than the default store client because publish/sync trigger\n * server-side clone work.\n *\n * @param config - Store connection config; defaults to {@link getStoreConfig}.\n * @param timeoutMs - Per-request abort timeout (default 20s).\n */\nexport function makeHttpPublisherClient(\n config: StoreConfig = getStoreConfig(),\n timeoutMs = 20_000,\n): PublisherClient {\n // Acquire a fresh Keycloak token per call (device-flow session in\n // ~/.skaile/auth.json, refreshed on demand) rather than a static config.jwt.\n const call = async <T>(\n path: string,\n opts?: { method?: string; body?: unknown; params?: Record<string, string> },\n ): Promise<T> => {\n const jwt = await getStoreToken();\n return storeFetch<T>({ ...config, jwt }, path, { timeoutMs, ...opts });\n };\n return {\n me: () => call(\"/api/v1/me\"),\n sourcesAdd: (body) => call(\"/api/v1/sources\", { method: \"POST\", body }),\n sourcesList: () => call(\"/api/v1/sources\"),\n sourceSync: (id) => call(`/api/v1/sources/${id}/sync`, { method: \"POST\", body: {} }),\n jobGet: (jobId) => call(`/api/v1/jobs/${jobId}`),\n sourceCandidates: (id) => call(`/api/v1/sources/${id}/candidates`),\n assetPreview: (id) => call(`/api/v1/assets/${id}/preview`),\n assetPublish: (id, body, dryRun) =>\n call(`/api/v1/assets/${id}/publish`, {\n method: \"POST\",\n body,\n ...(dryRun ? { params: { dryRun: \"1\" } } : {}),\n }),\n assetUnpublish: (id) => call(`/api/v1/assets/${id}/unpublish`, { method: \"POST\", body: {} }),\n namespaceAvailability: (ns) =>\n call(`/api/v1/namespaces/${encodeURIComponent(ns)}/availability`),\n };\n}\n","/**\n * Shared store-interaction core for the two publish front-ends — the curator\n * sidecar flow (`source manifest publish`) and the first-party library flow\n * (`library publish`). Both differ only in their git side-effects + how they\n * resolve the source repo; the store orchestration below (register → sync →\n * candidates → per-asset preview+publish) is identical.\n *\n * The store REST surface is reached through the injectable {@link PublisherClient}\n * so the orchestration stays unit/integration-testable without a live store.\n *\n * @docLink cli/commands/source#manifest-publish\n */\n\nimport type { SkPublishManifest } from \"@skaile/workspaces/core\";\nimport { logErr, logInfo, logOk, logWarn, S } from \"../helpers.ts\";\nimport type { PublisherClient } from \"../store-publisher.ts\";\n\n/**\n * One-line rendering of a namespace-availability probe for a `--dry-run` plan.\n * The `message` is store-authored (identical to what a real publish would echo)\n * — we only prepend a status glyph so the reader sees green/amber/red at a\n * glance without the CLI re-deriving any authorization logic.\n */\nexport function formatNamespaceAvailability(a: {\n status: \"owned-by-you\" | \"claimable-by-you\" | \"reserved\" | \"available\";\n message: string;\n}): string {\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return `${S.ok(\"✓\")} ${a.message}`;\n case \"claimable-by-you\":\n return `${S.warn(\"!\")} ${a.message}`;\n default:\n return `${S.err(\"✗\")} ${a.message}`;\n }\n}\n\n/**\n * Preflight the target namespace against the store's availability probe BEFORE a\n * publish does any irreversible work (a public git push). Returns `{ ok: false }`\n * with a guided message for `reserved` (not yours) and `claimable-by-you` (must\n * claim first) — the two states a real publish would reject — so the caller can\n * abort with actionable guidance instead of a raw 422 after pushing bytes.\n *\n * The probe is advisory: any failure (offline, older store) returns `{ ok: true }`\n * so the store stays the authority and a valid publish is never blocked.\n */\nexport async function preflightNamespace(\n client: PublisherClient,\n namespace: string,\n): Promise<{ ok: boolean; message?: string }> {\n let a: Awaited<ReturnType<PublisherClient[\"namespaceAvailability\"]>>;\n try {\n a = await client.namespaceAvailability(namespace);\n } catch {\n return { ok: true };\n }\n switch (a.status) {\n case \"owned-by-you\":\n case \"available\":\n return { ok: true };\n case \"claimable-by-you\":\n return {\n ok: false,\n message:\n `@${namespace} isn't yours yet — claim it in the store first` +\n `${a.claimMethod ? ` (${a.claimMethod})` : \"\"}, then re-run. ${a.message}`,\n };\n default: // reserved, or any unrecognized future status (fail safe → block)\n return { ok: false, message: `Cannot publish under @${namespace} — ${a.message}` };\n }\n}\n\n/** One candidate row shape the matcher operates on (kind + name are the key). */\ninterface CandidateLike {\n kind: string;\n name: string;\n}\n\n/**\n * Keep only candidates whose `(kind, name)` pair is declared in the manifest.\n * The backend may merge extra assets from the base repo into the candidate\n * list; a publish only touches what the manifest curated/declared.\n */\nexport function matchCandidatesToManifest<T extends CandidateLike>(\n candidates: T[],\n manifest: SkPublishManifest,\n): T[] {\n const wanted = new Set((manifest.assets ?? []).map((a) => `${a.kind}:${a.name}`));\n return candidates.filter((c) => wanted.has(`${c.kind}:${c.name}`));\n}\n\n/** A canonical ref string `kind:@publisher/name[#version]` for reporting. */\nexport function refFor(kind: string, publisher: string, name: string, version?: string): string {\n const base = `${kind}:@${publisher}/${name}`;\n return version ? `${base}#${version}` : base;\n}\n\n/** The bare asset name from a `kind:@publisher/name#version` ref or a plain name. */\nexport function bareName(ref: string): string {\n const afterKind = ref.includes(\":\") ? ref.slice(ref.indexOf(\":\") + 1) : ref;\n const afterScope = afterKind.includes(\"/\")\n ? afterKind.slice(afterKind.indexOf(\"/\") + 1)\n : afterKind;\n return afterScope.split(\"#\")[0];\n}\n\n/**\n * Poll a job until it leaves `running` or the deadline passes. Returns the last\n * observed state — the caller MUST treat a still-`running` result as a timeout\n * (not success), since it means the deadline was hit before the job finished.\n */\nexport async function pollJob(\n client: PublisherClient,\n jobId: string,\n intervalMs = 1_500,\n timeoutMs = 60_000,\n): Promise<{ status: string; items?: Array<{ label: string; status: string; error?: string }> }> {\n const deadline = Date.now() + timeoutMs;\n let job = await client.jobGet(jobId);\n while (job.status === \"running\" && Date.now() < deadline) {\n await new Promise((r) => setTimeout(r, intervalMs));\n job = await client.jobGet(jobId);\n }\n return job;\n}\n\n/**\n * True when a `sourcesAdd` rejection is a duplicate-URL conflict (the source is\n * already registered) — the only error the publish flow recovers from by looking\n * the existing row up. Every other failure (auth, 5xx, network) must propagate.\n */\nexport function isDupSourceError(err: unknown): boolean {\n const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();\n return /\\b409\\b|conflict|duplicate|already exists|already registered|unique/.test(msg);\n}\n\n/**\n * Register + sync the source, then publish its curated/declared candidates —\n * the store-side steps shared by both publish front-ends. Git side-effects (the\n * sidecar push, or the library commit+push) happen in the caller *before* this;\n * this function is purely store interaction.\n *\n * The sidecar front-end passes `sidecar` (so `sourcesAdd` carries the sidecar\n * pin); the library front-end omits it (the source repo IS the manifest host).\n * `assetName`, when set, narrows publication to the single candidate of that\n * name. Fatal store states (`sourcesAdd` non-dup failure) surface; sync failures\n * and empty candidate sets `process.exit(1)` with the same messages as before.\n */\nexport async function publishToStore(opts: {\n sourceUrl: string;\n ref: string;\n sidecar?: { url: string; ref: string };\n manifest: SkPublishManifest;\n assetName?: string;\n client: PublisherClient;\n}): Promise<{ published: string[] }> {\n const { sourceUrl, ref, sidecar, manifest, assetName, client: pub } = opts;\n\n let sourceId: string;\n try {\n const added = await pub.sourcesAdd({\n url: sourceUrl,\n ref,\n ...(sidecar ? { sidecarUrl: sidecar.url, sidecarRef: sidecar.ref } : {}),\n // Publish under the manifest's declared namespace; the store resolves a\n // claimed Publisher when it differs from the caller's login, else defaults\n // to `@<username>`. Omitted when the manifest carries no publisher.\n ...(manifest.publisher ? { namespace: manifest.publisher } : {}),\n });\n sourceId = added.id;\n } catch (err) {\n // Only a duplicate-url conflict is recoverable (source already registered);\n // auth/5xx/network failures must surface, not silently reuse a stale row.\n if (!isDupSourceError(err)) throw err;\n const rows = await pub.sourcesList();\n const found = rows.find((r) => r.url === sourceUrl);\n if (!found) {\n throw new Error(\n `Source ${sourceUrl} looked already-registered but no owned row matched: ` +\n `${err instanceof Error ? err.message : String(err)}`,\n );\n }\n sourceId = found.id;\n }\n\n const { jobId } = await pub.sourceSync(sourceId);\n const job = await pollJob(pub, jobId);\n if (job.status === \"failed\" || job.status === \"cancelled\") {\n const failed = (job.items ?? []).filter((i) => i.status === \"failed\");\n for (const i of failed) logErr(`sync: ${i.label}: ${i.error ?? \"failed\"}`);\n logErr(`Source sync ${job.status}.`);\n process.exit(1);\n }\n // A still-`running` job means the poll deadline was hit — do NOT proceed on an\n // unfinished sync (it would read incomplete candidates).\n if (job.status === \"running\") {\n logErr(\"Source sync timed out before completing — re-run `publish`, or check the store.\");\n process.exit(1);\n }\n\n let candidates = matchCandidatesToManifest(await pub.sourceCandidates(sourceId), manifest);\n if (assetName) candidates = candidates.filter((c) => c.name === assetName);\n if (candidates.length === 0) {\n logWarn(\"No candidates discovered — check the manifest and the source ref.\");\n process.exit(1);\n }\n\n const published: string[] = [];\n for (const c of candidates) {\n try {\n const preview = await pub.assetPreview(c.id);\n const res = await pub.assetPublish(c.id, { ref, files: preview.discoveredFiles });\n // Publish is async — wait for the job so we only report refs that actually\n // landed, not ones whose import is still in flight or about to fail.\n if (res.jobId) {\n const pubJob = await pollJob(pub, res.jobId);\n if (pubJob.status !== \"succeeded\") {\n const errs = (pubJob.items ?? [])\n .filter((i) => i.status === \"failed\")\n .map((i) => i.error)\n .filter(Boolean);\n logWarn(\n `Publish of ${c.kind}:${c.name} did not succeed (${pubJob.status})` +\n (errs.length ? `: ${errs.join(\"; \")}` : \"\"),\n );\n continue;\n }\n }\n published.push(refFor(c.kind, preview.candidate.publisherNamespace, c.name, c.version));\n } catch (err) {\n logWarn(\n `Failed to publish ${c.kind}:${c.name}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n logOk(`Published ${published.length} asset(s):`);\n for (const r of published) logInfo(` ${r}`);\n return { published };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { initTelemetry } from './chunk-4R6DROGN.js';
2
2
  import { parseSkillFrontmatter, validateFlowVersions } from './chunk-GXC3TYMQ.js';
3
- import { FlowAdapter } from './chunk-NRWDQBZ7.js';
3
+ import { FlowAdapter } from './chunk-VBRXFLIP.js';
4
4
  import { loadFlow } from './chunk-4N5XR5DQ.js';
5
5
  import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-DEYYRFQU.js';
6
6
  import { resolveSettings } from './chunk-5NZ56R63.js';
@@ -389,5 +389,5 @@ function walkForSkill(dir, skillId) {
389
389
  }
390
390
 
391
391
  export { resumeFlow, runFlow };
392
- //# sourceMappingURL=chunk-HIATVS2E.js.map
393
- //# sourceMappingURL=chunk-HIATVS2E.js.map
392
+ //# sourceMappingURL=chunk-SZY7X4M2.js.map
393
+ //# sourceMappingURL=chunk-SZY7X4M2.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ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,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-HIATVS2E.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
1
+ {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,E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IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-SZY7X4M2.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { WorkspacePlugin } from './chunk-EA73UA42.js';
1
+ import { WorkspacePlugin } from './chunk-BSXBOKL6.js';
2
2
  import { WebSocketServerTransport } from './chunk-WQ7DE5UC.js';
3
3
  import { assembleSystemPrompt, buildCapabilitiesPromptSection } from './chunk-W3UDISS2.js';
4
4
  import { EventNormalizer } from './chunk-HKX5VSWQ.js';
@@ -6,8 +6,8 @@ import { SUPPORTED_CLOUDS, CLOUD_SECRET_ENV_KEYS } from './chunk-ISQWMBKD.js';
6
6
  import { classifyClaudeSdkError } from './chunk-GAH4YRCI.js';
7
7
  import { createDriver } from './chunk-TNSCHS4I.js';
8
8
  import { deployCatalogEntry, undeployCatalogEntry } from './chunk-LV2HPH3C.js';
9
- import { registerBuiltinConnectors, buildConnectorPromptSection, findMissingPackages, installNpmPackages, ConnectorManager, ConnectorStartupError, buildSdkConnectorTools } from './chunk-NRWDQBZ7.js';
10
- import { loadConnectorDeclarations, SecretProviderChain, PreMintedSecretProvider, InMemorySecretProvider, deriveSingleMaterializedConnectorDeclaration } from './chunk-OJ7G56I7.js';
9
+ import { registerBuiltinConnectors, buildConnectorPromptSection, findMissingPackages, installNpmPackages, ConnectorManager, ConnectorStartupError, buildSdkConnectorTools } from './chunk-VBRXFLIP.js';
10
+ import { loadConnectorDeclarations, SecretProviderChain, PreMintedSecretProvider, InMemorySecretProvider, resolvedConfigToDeclarations, deriveSingleMaterializedConnectorDeclaration } from './chunk-Y6FV73IH.js';
11
11
  import { renderStimulusPrompt, buildOrchestratorPrompt } from './chunk-DEYYRFQU.js';
12
12
  import { PROTOCOL_VERSION } from './chunk-PK7Q7MC7.js';
13
13
  import { resolveSettings, resolveApiKey, providerEnvKey } from './chunk-5NZ56R63.js';
@@ -1429,7 +1429,7 @@ function buildMcpPromptSection(declarations) {
1429
1429
  }
1430
1430
 
1431
1431
  // runner/src/resources.ts
1432
- async function buildAgentResources(projectDir, driverType, _onLog, watch, secretProvider, sessionMeta, tokenMediator, preMintedSecrets, deferFilesystemMounts, capabilityRegistry) {
1432
+ async function buildAgentResources(projectDir, driverType, _onLog, watch, secretProvider, sessionMeta, tokenMediator, preMintedSecrets, deferFilesystemMounts, capabilityRegistry, fallbackConnectorDeclarations) {
1433
1433
  const resLog = createLogger({
1434
1434
  kind: "runner",
1435
1435
  subkind: "resources",
@@ -1457,7 +1457,13 @@ async function buildAgentResources(projectDir, driverType, _onLog, watch, secret
1457
1457
  resLog.warn("runtime asset warning", { code: w.code, message: w.message });
1458
1458
  }
1459
1459
  await maybeInstallNpmPeerDeps(runtimeAssets, projectDir, resLog);
1460
- const connectorDeclarations = loadConnectorDeclarations(projectDir);
1460
+ const diskDeclarations = loadConnectorDeclarations(projectDir);
1461
+ const connectorDeclarations = diskDeclarations.length > 0 ? diskDeclarations : fallbackConnectorDeclarations ?? [];
1462
+ if (diskDeclarations.length === 0 && connectorDeclarations.length > 0) {
1463
+ resLog.info("no disk connector declarations \u2014 using session_init resolvedConfig fallback", {
1464
+ count: connectorDeclarations.length
1465
+ });
1466
+ }
1461
1467
  let resourceManager = null;
1462
1468
  if (connectorDeclarations.length > 0) {
1463
1469
  resourceManager = await connectAllConnectors(
@@ -1816,7 +1822,8 @@ async function createAgentSession(config) {
1816
1822
  config.tokenMediator,
1817
1823
  config.preMintedSecrets,
1818
1824
  config.deferFilesystemMounts,
1819
- config.capabilityRegistry
1825
+ config.capabilityRegistry,
1826
+ config.fallbackConnectorDeclarations
1820
1827
  );
1821
1828
  const wsConfig = wsConfigOverride ?? resolveSkWorkspaceConfig(projectDir);
1822
1829
  const contextSection = buildContextSection(wsConfig.agent?.context);
@@ -4332,7 +4339,7 @@ async function startAgentServer(opts) {
4332
4339
  );
4333
4340
  }
4334
4341
  const effectiveCloudConfig = cloudConfigFromProfile(profile);
4335
- function buildSessionConfig(secretProvider2, apiKey, cloudSecrets) {
4342
+ function buildSessionConfig(secretProvider2, apiKey, cloudSecrets, fallbackConnectorDeclarations) {
4336
4343
  return {
4337
4344
  projectDir: opts.projectDir,
4338
4345
  agentDir,
@@ -4415,7 +4422,10 @@ async function startAgentServer(opts) {
4415
4422
  // through `host.refresh_credential` via this mediator.
4416
4423
  tokenMediator: connectorTokenMediator,
4417
4424
  ...preMintedSecrets ? { preMintedSecrets } : {},
4418
- ...aiProviderConfigId ? { aiProviderConfigId } : {}
4425
+ ...aiProviderConfigId ? { aiProviderConfigId } : {},
4426
+ // Disk-first fallback: only consumed when skaile.yaml + materialized
4427
+ // assets yield zero connector declarations (broker mode has no yaml).
4428
+ ...fallbackConnectorDeclarations?.length ? { fallbackConnectorDeclarations } : {}
4419
4429
  };
4420
4430
  }
4421
4431
  let resolveSessionReady;
@@ -4929,7 +4939,7 @@ async function startAgentServer(opts) {
4929
4939
  }
4930
4940
  return initialAiCredentialExpiresAt;
4931
4941
  }
4932
- async function buildSessionFromInit(secrets) {
4942
+ async function buildSessionFromInit(secrets, fallbackConnectorDeclarations) {
4933
4943
  let apiKeyFromSecrets;
4934
4944
  let cloudSecrets;
4935
4945
  if (effectiveCloud === "default") {
@@ -4943,7 +4953,12 @@ async function startAgentServer(opts) {
4943
4953
  projectDir: opts.projectDir
4944
4954
  }));
4945
4955
  }
4946
- sessionConfig = buildSessionConfig(secretProvider, apiKeyFromSecrets, cloudSecrets);
4956
+ sessionConfig = buildSessionConfig(
4957
+ secretProvider,
4958
+ apiKeyFromSecrets,
4959
+ cloudSecrets,
4960
+ fallbackConnectorDeclarations
4961
+ );
4947
4962
  if (!agentSession) {
4948
4963
  agentSession = await createAgentSession(sessionConfig);
4949
4964
  emitSystemPromptComposed(agentSession, sendEvent);
@@ -5266,7 +5281,7 @@ async function startAgentServer(opts) {
5266
5281
  capabilitySignature: computeCapabilitySignature(capabilityRegistry.list())
5267
5282
  });
5268
5283
  const buildSession = async () => {
5269
- await buildSessionFromInit(cmd.secrets);
5284
+ await buildSessionFromInit(cmd.secrets, resolvedConfigToDeclarations(cmd.resolvedConfig));
5270
5285
  const cfg = {
5271
5286
  aiResources: cmd.resolvedConfig.aiResources,
5272
5287
  subagents: cmd.resolvedConfig.subagents,
@@ -5925,5 +5940,5 @@ function touchSession(state) {
5925
5940
  }
5926
5941
 
5927
5942
  export { CLAUDE_CODE_CREDENTIALS_KEY, COMPILE_MANIFEST_FILENAME, CapabilityRegistry, DEFAULT_CAPABILITY_CALL_TIMEOUT_MS, DEFAULT_COALESCE_MS, MarkdownStreamer, PreInitRingSink, agentDefinitionExists, bootstrapCapabilityRegistry, bootstrapRunnerLogStore, buildAgentResources, buildClientCapabilityHandler, buildConnectorTokenMediator, buildContextSection, buildEnvironmentSection, buildResourcesAvailablePayload, builtinCapabilities, capabilityLogInstance, clearPreInitRingSink, clearSession, compileComposition, computeCapabilitySignature, connectorRefreshKind, createAgentSession, createSessionStimulusBus, defineCapability, deleteSession, dispatchRunnerCapabilityInvocation, emitSystemPromptComposed, ensureGitConfigInclude, extractClaudeAiOauthExpiresAt, getPreInitRingSink, handleMountResourceRequest, handleResourceRequest, installPreInitRingSink, listSessions, loadAgentManifest, loadCompileManifest, loadCompileManifestFromDir, loadSession, loadSessionById, mcpAuthSecretKey, newSession, registerCompositionCapabilities, rejectCapabilityOnApprovalDeny, resetRunnerLogStore, resolveAgentComposition, resolveAgentMixins, resolveBinding, resolveCapabilityCallTimeoutMs, resolveCapabilityResult, resolveComposition, resolveMixin, runAgentChat, saveSession, setCurrentSession, startAgentServer, touchSession, writeClaudeCodeCredentialsFile };
5928
- //# sourceMappingURL=chunk-M4UKIJ5K.js.map
5929
- //# sourceMappingURL=chunk-M4UKIJ5K.js.map
5943
+ //# sourceMappingURL=chunk-TC3GLA5D.js.map
5944
+ //# sourceMappingURL=chunk-TC3GLA5D.js.map