@skaile/workspaces 0.17.0 → 0.18.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 (94) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/{asset-feeds-L4ROBIAZ.js → asset-feeds-CQU46DYQ.js} +8 -8
  3. package/dist/{asset-feeds-L4ROBIAZ.js.map → asset-feeds-CQU46DYQ.js.map} +1 -1
  4. package/dist/asset-manager/index.js +6 -6
  5. package/dist/asset-manager/installer.js +5 -5
  6. package/dist/base-assets/connectors/deploy.js +6 -6
  7. package/dist/base-assets/connectors/devserver.js +6 -6
  8. package/dist/base-assets/connectors/flow/adapter.js +6 -6
  9. package/dist/base-assets/connectors/flow/run-flow.js +7 -7
  10. package/dist/base-assets/connectors/flow.js +6 -6
  11. package/dist/base-assets/connectors/git/driver.d.ts +6 -2
  12. package/dist/base-assets/connectors/git/driver.d.ts.map +1 -1
  13. package/dist/base-assets/connectors/git.js +6 -6
  14. package/dist/base-assets/connectors/gmail.js +6 -6
  15. package/dist/base-assets/connectors/googledrive.js +6 -6
  16. package/dist/base-assets/connectors/local.js +6 -6
  17. package/dist/base-assets/connectors/mattermost.js +6 -6
  18. package/dist/base-assets/connectors/memory.js +6 -6
  19. package/dist/base-assets/connectors/minio.js +6 -6
  20. package/dist/base-assets/connectors/postgres.js +6 -6
  21. package/dist/base-assets/connectors/redis.js +6 -6
  22. package/dist/base-assets/connectors/s3.js +6 -6
  23. package/dist/base-assets/connectors/sharepoint.js +6 -6
  24. package/dist/base-assets/connectors/sqlite.js +6 -6
  25. package/dist/base-assets/connectors/static-server.js +6 -6
  26. package/dist/base-assets/connectors/tunnel.js +6 -6
  27. package/dist/base-assets/connectors/webdav.js +6 -6
  28. package/dist/base-assets/connectors/xstate-store.js +6 -6
  29. package/dist/base-assets/connectors/xstate.js +6 -6
  30. package/dist/base-assets/connectors/yjs.js +6 -6
  31. package/dist/{chunk-GKIA2PU5.js → chunk-2GX7BE7Q.js} +3 -3
  32. package/dist/{chunk-GKIA2PU5.js.map → chunk-2GX7BE7Q.js.map} +1 -1
  33. package/dist/{chunk-76CUXLXI.js → chunk-63Y7YN33.js} +2 -2
  34. package/dist/{chunk-76CUXLXI.js.map → chunk-63Y7YN33.js.map} +1 -1
  35. package/dist/{chunk-4BRSVK7Q.js → chunk-ATTIX7H2.js} +3 -3
  36. package/dist/{chunk-4BRSVK7Q.js.map → chunk-ATTIX7H2.js.map} +1 -1
  37. package/dist/{chunk-FNCYNUGS.js → chunk-B3XHLXGD.js} +3 -3
  38. package/dist/{chunk-FNCYNUGS.js.map → chunk-B3XHLXGD.js.map} +1 -1
  39. package/dist/{chunk-J6T5YXLN.js → chunk-BCZRPFVQ.js} +8 -8
  40. package/dist/{chunk-J6T5YXLN.js.map → chunk-BCZRPFVQ.js.map} +1 -1
  41. package/dist/{chunk-ZHLRRT5D.js → chunk-FRPKLIEZ.js} +36 -3
  42. package/dist/chunk-FRPKLIEZ.js.map +1 -0
  43. package/dist/{chunk-SMFZFFIZ.js → chunk-FVWBLAXL.js} +3 -3
  44. package/dist/{chunk-SMFZFFIZ.js.map → chunk-FVWBLAXL.js.map} +1 -1
  45. package/dist/{chunk-6SCFOXJ5.js → chunk-I7HGX4ZE.js} +73 -6
  46. package/dist/chunk-I7HGX4ZE.js.map +1 -0
  47. package/dist/{chunk-42YLNYFK.js → chunk-KIGZYGCM.js} +4 -4
  48. package/dist/{chunk-42YLNYFK.js.map → chunk-KIGZYGCM.js.map} +1 -1
  49. package/dist/{chunk-SOQMVRQL.js → chunk-N2C3A5PS.js} +3 -3
  50. package/dist/{chunk-SOQMVRQL.js.map → chunk-N2C3A5PS.js.map} +1 -1
  51. package/dist/{chunk-PXABRXBP.js → chunk-OIIGCFYM.js} +5 -5
  52. package/dist/{chunk-PXABRXBP.js.map → chunk-OIIGCFYM.js.map} +1 -1
  53. package/dist/{chunk-IY4X7PZN.js → chunk-PBBGKI3L.js} +4 -4
  54. package/dist/{chunk-IY4X7PZN.js.map → chunk-PBBGKI3L.js.map} +1 -1
  55. package/dist/{chunk-KJ2LLWRF.js → chunk-VMUQAISH.js} +3 -3
  56. package/dist/{chunk-KJ2LLWRF.js.map → chunk-VMUQAISH.js.map} +1 -1
  57. package/dist/{chunk-3DS5VIQP.js → chunk-WGPT6FV6.js} +4 -4
  58. package/dist/{chunk-3DS5VIQP.js.map → chunk-WGPT6FV6.js.map} +1 -1
  59. package/dist/{chunk-DG7WFRUM.js → chunk-YVX66WNQ.js} +6 -6
  60. package/dist/{chunk-DG7WFRUM.js.map → chunk-YVX66WNQ.js.map} +1 -1
  61. package/dist/cli/index.js +73 -36
  62. package/dist/cli/index.js.map +1 -1
  63. package/dist/cli/src/commands/manage.d.ts +22 -2
  64. package/dist/cli/src/commands/manage.d.ts.map +1 -1
  65. package/dist/connectors/config.js +5 -5
  66. package/dist/connectors/index.js +6 -6
  67. package/dist/connectors/src/fleet-utils.d.ts +6 -9
  68. package/dist/connectors/src/fleet-utils.d.ts.map +1 -1
  69. package/dist/core/index.js +4 -4
  70. package/dist/core/manifest.js +1 -1
  71. package/dist/core/runtime-assets.js +3 -3
  72. package/dist/core/src/manifest.d.ts.map +1 -1
  73. package/dist/core/workspace-config.js +2 -2
  74. package/dist/discovery/index.js +2 -2
  75. package/dist/{ensure-sources-V26CZNJF.js → ensure-sources-HA6L3FBS.js} +8 -8
  76. package/dist/{ensure-sources-V26CZNJF.js.map → ensure-sources-HA6L3FBS.js.map} +1 -1
  77. package/dist/library/index.js +3 -3
  78. package/dist/{open-library-T6RXQJTQ.js → open-library-ICKZYC5K.js} +6 -6
  79. package/dist/{open-library-T6RXQJTQ.js.map → open-library-ICKZYC5K.js.map} +1 -1
  80. package/dist/runner/index.js +8 -8
  81. package/dist/sdk/asset-manager.js +6 -6
  82. package/dist/sdk/core.js +4 -4
  83. package/dist/sdk/index.js +8 -8
  84. package/dist/sdk/runner.js +8 -8
  85. package/dist/{setup-R6VWIPLL.js → setup-DT4VSWSM.js} +6 -6
  86. package/dist/{setup-R6VWIPLL.js.map → setup-DT4VSWSM.js.map} +1 -1
  87. package/dist/store-client-TZ4L73TH.js +14 -0
  88. package/dist/{store-client-FLD3XUY7.js.map → store-client-TZ4L73TH.js.map} +1 -1
  89. package/dist/tui/index.js +8 -8
  90. package/dist/workspace-plugin/index.js +1 -1
  91. package/package.json +1 -1
  92. package/dist/chunk-6SCFOXJ5.js.map +0 -1
  93. package/dist/chunk-ZHLRRT5D.js.map +0 -1
  94. package/dist/store-client-FLD3XUY7.js +0 -14
@@ -1 +1 @@
1
- {"version":3,"sources":["../base-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ,uBAAA;AAAA,IACA,kBAAA;AAAA,IACA,wBAAA;AAAA,IACA,kBAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,IAAA,CAAK,QAAQ,CAAA;AACnC,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,IAAY,eAAA,CAAgB,KAAK,UAAU,CAAA;AACjE,EAAA,MAAM,QAAA,GAAW,MAAM,eAAA,CAAgB,IAAA,CAAK,UAAA,EAAY;AAAA,IACtD,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,OAAO,I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C,aAAA;AACF,QAAA,IAAA,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,KAAa,OAAA,EAAgC;AACjE,EAAA,KAAA,MAAW,KAAA,IAAS,GAAG,WAAA,CAAY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-PXABRXBP.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `base-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/base-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 → base-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * base-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 { loadFlow } from \"./engine/index.js\";\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 {\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/base-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/base-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/base-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/base-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":["../base-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ,uBAAA;AAAA,IACA,kBAAA;AAAA,IACA,wBAAA;AAAA,IACA,kBAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,IAAA,CAAK,QAAQ,CAAA;AACnC,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,IAAY,eAAA,CAAgB,KAAK,UAAU,CAAA;AACjE,EAAA,MAAM,QAAA,GAAW,MAAM,eAAA,CAAgB,IAAA,CAAK,UAAA,EAAY;AAAA,IACtD,QAAQ,IAAA,CAAK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GAAA,GACH,KAAA,CAA+C,KAAA,IAC/C,KAAA,CAA+B,OAAA,IAChC,aAAA;AACF,QAAA,IAAA,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,KAAa,OAAA,EAAgC;AACjE,EAAA,KAAA,MAAW,KAAA,IAAS,GAAG,WAAA,CAAY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-OIIGCFYM.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `base-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/base-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 → base-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * base-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 { loadFlow } from \"./engine/index.js\";\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 {\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/base-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/base-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/base-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/base-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { logErr } from './chunk-4NDWKA64.js';
2
- import { knowledgeKindProvider } from './chunk-FNCYNUGS.js';
3
- import { createDefaultRegistry } from './chunk-GKIA2PU5.js';
2
+ import { knowledgeKindProvider } from './chunk-B3XHLXGD.js';
3
+ import { createDefaultRegistry } from './chunk-2GX7BE7Q.js';
4
4
  import { flowKindProvider } from './chunk-ICS76R4T.js';
5
5
 
6
6
  // cli/src/open-registry.ts
@@ -97,5 +97,5 @@ async function openLibraryManager() {
97
97
  }
98
98
 
99
99
  export { createFullRegistry, openCatalogSource, openLibrary, openLibraryManager, resolveCatalogSource };
100
- //# sourceMappingURL=chunk-IY4X7PZN.js.map
101
- //# sourceMappingURL=chunk-IY4X7PZN.js.map
100
+ //# sourceMappingURL=chunk-PBBGKI3L.js.map
101
+ //# sourceMappingURL=chunk-PBBGKI3L.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../cli/src/open-registry.ts","../cli/src/open-library.ts"],"names":["source"],"mappings":";;;;;;AA2BO,SAAS,kBAAA,GAAwC;AACtD,EAAA,MAAM,WAAW,qBAAA,EAAsB;AACvC,EAAA,QAAA,CAAS,SAAS,gBAAgB,CAAA;AAClC,E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ps the registry with all built-in providers (9 core + preset)\n * from @skaile/discovery, plus the extension kind providers (flow from\n * @skaile/workspaces/base-assets/connectors/flow/engine, knowledge from @skaile/library).\n *\n * This is the single registration point for the CLI. All code paths\n * that need a registry (source sync, lib-status, etc.) should use this.\n */\n\nimport { flowKindProvider } from \"@skaile/workspaces/base-assets/connectors/flow/engine\";\nimport type { AssetKindRegistry } from \"@skaile/workspaces/discovery\";\nimport { createDefaultRegistry } from \"@skaile/workspaces/discovery\";\nimport { knowledgeKindProvider } from \"@skaile/workspaces/library\";\n\n/**\n * Create a fully-configured AssetKindRegistry with all known providers.\n *\n * Registers:\n * - 9 core kinds (skill, agent, connector, mount, mcp-server, contract, prompt, persona, ruleset)\n * - preset (composition entity)\n * - flow (extension, from @skaile/workspaces/base-assets/connectors/flow/engine)\n * - knowledge (extension, from @skaile/library)\n *\n * @returns An unfrozen registry (auto-freezes on first read)\n */\nexport function createFullRegistry(): AssetKindRegistry {\n const registry = createDefaultRegistry();\n registry.register(flowKindProvider);\n registry.register(knowledgeKindProvider);\n return registry;\n}\n","/**\n * open-library.ts — shared helpers to open the LocalIndex and the configured\n * Catalog source.\n *\n * Lazy-loads the `@skaile/workspaces/library` subpath and returns the\n * LocalIndex instance (backed by `@libsql/client`; runs on Node and Bun).\n * The catalog-source helper reads\n * `~/.skaile/config.yaml` (and project-level overlay if `projectDir` is given)\n * to decide between {@link RemoteCatalogSource} (default — points at\n * `https://skaile.store`) and a {@link LocalCatalogSource} bound to the most\n * recent local library registered via `skaile source add`.\n */\n\nimport { logErr } from \"./helpers.ts\";\nimport { createFullRegistry } from \"./open-registry.ts\";\n\n/**\n * Open the LocalIndex with the full kind registry. Exits with code 1\n * if the library directory cannot be created.\n *\n * @returns A `LocalIndex` instance ready for use.\n * @docLink cli/dev-guide#open-library\n */\nexport async function openLibrary() {\n try {\n const { LocalIndex } = await import(\"@skaile/workspaces/library\");\n return new LocalIndex({ kindRegistry: createFullRegistry() });\n } catch (err) {\n logErr(`Could not open LocalIndex: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n}\n\n/**\n * Resolve the configured **remote** Catalog source for the CLI.\n *\n * Reads `~/.skaile/config.yaml` (plus the optional project-level overlay) and\n * returns a {@link RemoteCatalogSource} pointing at `catalog.url` (default:\n * `https://skaile.store`). The `cache_ttl: 0` config flag flips the source\n * into air-gapped mode: network reads are disabled, only `skaile update`\n * performs refreshes.\n *\n * **Local-mode rejection.** If the resolved config has `catalog.url: local`\n * this helper throws — callers wanting the dispatched local-or-remote source\n * must use {@link resolveCatalogSource}. Remote-only consumers like\n * `skaile update --catalog-only` rely on this strict behaviour.\n *\n * @param opts - Project directory (overlays project config) and explicit overrides.\n * @returns A configured {@link RemoteCatalogSource}.\n * @throws When `catalog.url` is the `local` sentinel.\n * @docLink cli/dev-guide#open-library\n */\nexport async function openCatalogSource(opts?: {\n projectDir?: string;\n baseUrlOverride?: string;\n /** Override the user-config path for tests. */\n userConfigFile?: string;\n}): Promise<\n | import(\"@skaile/workspaces/library\").RemoteCatalogSource\n | import(\"@skaile/workspaces/library\").RestCatalogSource\n> {\n const { resolveConfig, RemoteCatalogSource, RestCatalogSource, isLocalCatalogUrl } = await import(\n \"@skaile/workspaces/library\"\n );\n const cfg = resolveConfig({\n projectDir: opts?.projectDir,\n userConfigFile: opts?.userConfigFile,\n });\n const baseUrl = opts?.baseUrlOverride ?? cfg.catalog.url;\n if (isLocalCatalogUrl(baseUrl)) {\n throw new Error(\n \"catalog.url is set to 'local' — remote catalog is disabled. \" +\n \"Use `skaile source add <path>` + `skaile source sync` for local sources, \" +\n \"or set `catalog.url: https://skaile.store` in ~/.skaile/config.yaml.\",\n );\n }\n const cacheTtlMs = cfg.catalog.cache_ttl * 1000;\n if (cfg.catalog.framing === \"rest\") {\n return new RestCatalogSource({ baseUrl, cacheTtlMs });\n }\n return new RemoteCatalogSource({ baseUrl, cacheTtlMs });\n}\n\n/**\n * Resolved catalog source plus a close handle for releasing any underlying\n * resources (e.g. the `LocalIndex` SQLite connection in local mode).\n *\n * Callers MUST invoke `close()` when done — typically in a `finally` block.\n * For remote-mode sources `close()` is a no-op, but the contract is uniform\n * so consumers don't have to branch.\n *\n * @docLink cli/dev-guide#open-library\n */\nexport interface ResolvedCatalogSource {\n /** The {@link ICatalogSource} ready for use. */\n source: import(\"@skaile/workspaces/library\").ICatalogSource;\n /** Release any underlying resources (SQLite handle in local mode). */\n close(): void;\n}\n\n/**\n * Resolve the configured Catalog source — local or remote — based on\n * `~/.skaile/config.yaml`.\n *\n * Dispatch:\n * - `catalog.url: local` → opens {@link LocalIndex}, picks the most recently\n * registered local library whose `path` still exists on disk, and returns a\n * {@link LocalCatalogSource} bound to that library. Throws if no usable\n * local library is registered.\n * - any URL → returns {@link RemoteCatalogSource} (same as\n * {@link openCatalogSource}).\n *\n * The returned `close()` releases the underlying `LocalIndex` SQLite handle\n * in local mode (no-op in remote mode). Callers MUST invoke it — typically in\n * a `finally` block — to satisfy `library/CLAUDE.md` § \"Notes for Consumers\".\n *\n * @param opts - Project directory (overlays project config) and explicit overrides.\n * @returns A `ResolvedCatalogSource` carrying the source and a close handle.\n * @throws When `local` is configured but no usable local library is registered.\n * @docLink cli/dev-guide#open-library\n */\nexport async function resolveCatalogSource(opts?: {\n projectDir?: string;\n baseUrlOverride?: string;\n /** Override the user-config path for tests. */\n userConfigFile?: string;\n}): Promise<ResolvedCatalogSource> {\n const {\n resolveConfig,\n RemoteCatalogSource,\n RestCatalogSource,\n LocalCatalogSource,\n isLocalCatalogUrl,\n } = await import(\"@skaile/workspaces/library\");\n const cfg = resolveConfig({\n projectDir: opts?.projectDir,\n userConfigFile: opts?.userConfigFile,\n });\n const baseUrl = opts?.baseUrlOverride ?? cfg.catalog.url;\n\n if (isLocalCatalogUrl(baseUrl)) {\n const fs = await import(\"node:fs\");\n const library = await openLibrary();\n try {\n const sources = await library.listSources();\n type LibraryRow = (typeof sources)[number];\n // Type-narrow: `path` is required for local libraries after the filter.\n const usable = sources\n .filter(\n (s): s is LibraryRow & { path: string } =>\n s.backend === \"local\" && typeof s.path === \"string\" && s.path.length > 0,\n )\n .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n if (usable.length === 0) {\n throw new Error(\n \"catalog.url is set to 'local' but no local library is registered. \" +\n \"Run `skaile source add <path>` first, then `skaile source sync`.\",\n );\n }\n\n // Prefer the most recently added library whose path still exists.\n const present = usable.find((s) => fs.existsSync(s.path));\n if (!present) {\n const head = usable[0];\n throw new Error(\n `catalog.url is set to 'local' but every registered local library has a missing path on disk. ` +\n `Most recent: ${head.path} (library ${head.id}). ` +\n `Re-register with \\`skaile source add <existing-path>\\` or run \\`skaile source list\\` to inspect.`,\n );\n }\n\n const source = new LocalCatalogSource(\n library,\n present.id,\n present.path,\n createFullRegistry(),\n );\n return { source, close: () => library.close() };\n } catch (err) {\n // Release the handle on any failure during dispatch — otherwise the\n // SQLite WAL state leaks for the lifetime of the process.\n library.close();\n throw err;\n }\n }\n\n const cacheTtlMs = cfg.catalog.cache_ttl * 1000;\n const source =\n cfg.catalog.framing === \"rest\"\n ? new RestCatalogSource({ baseUrl, cacheTtlMs })\n : new RemoteCatalogSource({ baseUrl, cacheTtlMs });\n return { source, close: () => {} };\n}\n\n/**\n * Open the LibraryManager bound to the active LocalIndex.\n * Caller owns lifetime — must call `close()` (returned helper closes the\n * underlying LocalIndex).\n *\n * @docLink cli/dev-guide#open-library\n */\nexport async function openLibraryManager(): Promise<{\n manager: import(\"@skaile/workspaces/library\").LibraryManager;\n library: import(\"@skaile/workspaces/library\").LocalIndex;\n close: () => void;\n}> {\n const { LibraryManager } = await import(\"@skaile/workspaces/library\");\n const library = await openLibrary();\n const manager = new LibraryManager(library);\n return { manager, library, close: () => library.close() };\n}\n"]}
1
+ {"version":3,"sources":["../cli/src/open-registry.ts","../cli/src/open-library.ts"],"names":["source"],"mappings":";;;;;;AA2BO,SAAS,kBAAA,GAAwC;AACtD,EAAA,MAAM,WAAW,qBAAA,EAAsB;AACvC,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* open-registry.ts — shared helper to create a full AssetKindRegistry.\n *\n * Bootstraps the registry with all built-in providers (9 core + preset)\n * from @skaile/discovery, plus the extension kind providers (flow from\n * @skaile/workspaces/base-assets/connectors/flow/engine, knowledge from @skaile/library).\n *\n * This is the single registration point for the CLI. All code paths\n * that need a registry (source sync, lib-status, etc.) should use this.\n */\n\nimport { flowKindProvider } from \"@skaile/workspaces/base-assets/connectors/flow/engine\";\nimport type { AssetKindRegistry } from \"@skaile/workspaces/discovery\";\nimport { createDefaultRegistry } from \"@skaile/workspaces/discovery\";\nimport { knowledgeKindProvider } from \"@skaile/workspaces/library\";\n\n/**\n * Create a fully-configured AssetKindRegistry with all known providers.\n *\n * Registers:\n * - 9 core kinds (skill, agent, connector, mount, mcp-server, contract, prompt, persona, ruleset)\n * - preset (composition entity)\n * - flow (extension, from @skaile/workspaces/base-assets/connectors/flow/engine)\n * - knowledge (extension, from @skaile/library)\n *\n * @returns An unfrozen registry (auto-freezes on first read)\n */\nexport function createFullRegistry(): AssetKindRegistry {\n const registry = createDefaultRegistry();\n registry.register(flowKindProvider);\n registry.register(knowledgeKindProvider);\n return registry;\n}\n","/**\n * open-library.ts — shared helpers to open the LocalIndex and the configured\n * Catalog source.\n *\n * Lazy-loads the `@skaile/workspaces/library` subpath and returns the\n * LocalIndex instance (backed by `@libsql/client`; runs on Node and Bun).\n * The catalog-source helper reads\n * `~/.skaile/config.yaml` (and project-level overlay if `projectDir` is given)\n * to decide between {@link RemoteCatalogSource} (default — points at\n * `https://skaile.store`) and a {@link LocalCatalogSource} bound to the most\n * recent local library registered via `skaile source add`.\n */\n\nimport { logErr } from \"./helpers.ts\";\nimport { createFullRegistry } from \"./open-registry.ts\";\n\n/**\n * Open the LocalIndex with the full kind registry. Exits with code 1\n * if the library directory cannot be created.\n *\n * @returns A `LocalIndex` instance ready for use.\n * @docLink cli/dev-guide#open-library\n */\nexport async function openLibrary() {\n try {\n const { LocalIndex } = await import(\"@skaile/workspaces/library\");\n return new LocalIndex({ kindRegistry: createFullRegistry() });\n } catch (err) {\n logErr(`Could not open LocalIndex: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\n }\n}\n\n/**\n * Resolve the configured **remote** Catalog source for the CLI.\n *\n * Reads `~/.skaile/config.yaml` (plus the optional project-level overlay) and\n * returns a {@link RemoteCatalogSource} pointing at `catalog.url` (default:\n * `https://skaile.store`). The `cache_ttl: 0` config flag flips the source\n * into air-gapped mode: network reads are disabled, only `skaile update`\n * performs refreshes.\n *\n * **Local-mode rejection.** If the resolved config has `catalog.url: local`\n * this helper throws — callers wanting the dispatched local-or-remote source\n * must use {@link resolveCatalogSource}. Remote-only consumers like\n * `skaile update --catalog-only` rely on this strict behaviour.\n *\n * @param opts - Project directory (overlays project config) and explicit overrides.\n * @returns A configured {@link RemoteCatalogSource}.\n * @throws When `catalog.url` is the `local` sentinel.\n * @docLink cli/dev-guide#open-library\n */\nexport async function openCatalogSource(opts?: {\n projectDir?: string;\n baseUrlOverride?: string;\n /** Override the user-config path for tests. */\n userConfigFile?: string;\n}): Promise<\n | import(\"@skaile/workspaces/library\").RemoteCatalogSource\n | import(\"@skaile/workspaces/library\").RestCatalogSource\n> {\n const { resolveConfig, RemoteCatalogSource, RestCatalogSource, isLocalCatalogUrl } = await import(\n \"@skaile/workspaces/library\"\n );\n const cfg = resolveConfig({\n projectDir: opts?.projectDir,\n userConfigFile: opts?.userConfigFile,\n });\n const baseUrl = opts?.baseUrlOverride ?? cfg.catalog.url;\n if (isLocalCatalogUrl(baseUrl)) {\n throw new Error(\n \"catalog.url is set to 'local' — remote catalog is disabled. \" +\n \"Use `skaile source add <path>` + `skaile source sync` for local sources, \" +\n \"or set `catalog.url: https://skaile.store` in ~/.skaile/config.yaml.\",\n );\n }\n const cacheTtlMs = cfg.catalog.cache_ttl * 1000;\n if (cfg.catalog.framing === \"rest\") {\n return new RestCatalogSource({ baseUrl, cacheTtlMs });\n }\n return new RemoteCatalogSource({ baseUrl, cacheTtlMs });\n}\n\n/**\n * Resolved catalog source plus a close handle for releasing any underlying\n * resources (e.g. the `LocalIndex` SQLite connection in local mode).\n *\n * Callers MUST invoke `close()` when done — typically in a `finally` block.\n * For remote-mode sources `close()` is a no-op, but the contract is uniform\n * so consumers don't have to branch.\n *\n * @docLink cli/dev-guide#open-library\n */\nexport interface ResolvedCatalogSource {\n /** The {@link ICatalogSource} ready for use. */\n source: import(\"@skaile/workspaces/library\").ICatalogSource;\n /** Release any underlying resources (SQLite handle in local mode). */\n close(): void;\n}\n\n/**\n * Resolve the configured Catalog source — local or remote — based on\n * `~/.skaile/config.yaml`.\n *\n * Dispatch:\n * - `catalog.url: local` → opens {@link LocalIndex}, picks the most recently\n * registered local library whose `path` still exists on disk, and returns a\n * {@link LocalCatalogSource} bound to that library. Throws if no usable\n * local library is registered.\n * - any URL → returns {@link RemoteCatalogSource} (same as\n * {@link openCatalogSource}).\n *\n * The returned `close()` releases the underlying `LocalIndex` SQLite handle\n * in local mode (no-op in remote mode). Callers MUST invoke it — typically in\n * a `finally` block — to satisfy `library/CLAUDE.md` § \"Notes for Consumers\".\n *\n * @param opts - Project directory (overlays project config) and explicit overrides.\n * @returns A `ResolvedCatalogSource` carrying the source and a close handle.\n * @throws When `local` is configured but no usable local library is registered.\n * @docLink cli/dev-guide#open-library\n */\nexport async function resolveCatalogSource(opts?: {\n projectDir?: string;\n baseUrlOverride?: string;\n /** Override the user-config path for tests. */\n userConfigFile?: string;\n}): Promise<ResolvedCatalogSource> {\n const {\n resolveConfig,\n RemoteCatalogSource,\n RestCatalogSource,\n LocalCatalogSource,\n isLocalCatalogUrl,\n } = await import(\"@skaile/workspaces/library\");\n const cfg = resolveConfig({\n projectDir: opts?.projectDir,\n userConfigFile: opts?.userConfigFile,\n });\n const baseUrl = opts?.baseUrlOverride ?? cfg.catalog.url;\n\n if (isLocalCatalogUrl(baseUrl)) {\n const fs = await import(\"node:fs\");\n const library = await openLibrary();\n try {\n const sources = await library.listSources();\n type LibraryRow = (typeof sources)[number];\n // Type-narrow: `path` is required for local libraries after the filter.\n const usable = sources\n .filter(\n (s): s is LibraryRow & { path: string } =>\n s.backend === \"local\" && typeof s.path === \"string\" && s.path.length > 0,\n )\n .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n if (usable.length === 0) {\n throw new Error(\n \"catalog.url is set to 'local' but no local library is registered. \" +\n \"Run `skaile source add <path>` first, then `skaile source sync`.\",\n );\n }\n\n // Prefer the most recently added library whose path still exists.\n const present = usable.find((s) => fs.existsSync(s.path));\n if (!present) {\n const head = usable[0];\n throw new Error(\n `catalog.url is set to 'local' but every registered local library has a missing path on disk. ` +\n `Most recent: ${head.path} (library ${head.id}). ` +\n `Re-register with \\`skaile source add <existing-path>\\` or run \\`skaile source list\\` to inspect.`,\n );\n }\n\n const source = new LocalCatalogSource(\n library,\n present.id,\n present.path,\n createFullRegistry(),\n );\n return { source, close: () => library.close() };\n } catch (err) {\n // Release the handle on any failure during dispatch — otherwise the\n // SQLite WAL state leaks for the lifetime of the process.\n library.close();\n throw err;\n }\n }\n\n const cacheTtlMs = cfg.catalog.cache_ttl * 1000;\n const source =\n cfg.catalog.framing === \"rest\"\n ? new RestCatalogSource({ baseUrl, cacheTtlMs })\n : new RemoteCatalogSource({ baseUrl, cacheTtlMs });\n return { source, close: () => {} };\n}\n\n/**\n * Open the LibraryManager bound to the active LocalIndex.\n * Caller owns lifetime — must call `close()` (returned helper closes the\n * underlying LocalIndex).\n *\n * @docLink cli/dev-guide#open-library\n */\nexport async function openLibraryManager(): Promise<{\n manager: import(\"@skaile/workspaces/library\").LibraryManager;\n library: import(\"@skaile/workspaces/library\").LocalIndex;\n close: () => void;\n}> {\n const { LibraryManager } = await import(\"@skaile/workspaces/library\");\n const library = await openLibrary();\n const manager = new LibraryManager(library);\n return { manager, library, close: () => library.close() };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { resolveSkWorkspaceConfig } from './chunk-SOQMVRQL.js';
1
+ import { resolveSkWorkspaceConfig } from './chunk-N2C3A5PS.js';
2
2
  import { createLogger } from './chunk-24UIWON4.js';
3
3
 
4
4
  // connectors/src/secrets.ts
@@ -302,5 +302,5 @@ function resolveAuthRef(auth, mountId) {
302
302
  }
303
303
 
304
304
  export { EnvSecretProvider, ForgeSecretProvider, InMemorySecretProvider, LegacyAuthGrammarError, LockedSecretProvider, OAuthRequiredError, PreMintedSecretProvider, SecretProviderChain, createCliSecretProviderChain, createForgeSecretProviderChain, loadConnectorDeclarations, resolveAuth, resolveAuthRef, resolveBackendAuthFor };
305
- //# sourceMappingURL=chunk-KJ2LLWRF.js.map
306
- //# sourceMappingURL=chunk-KJ2LLWRF.js.map
305
+ //# sourceMappingURL=chunk-VMUQAISH.js.map
306
+ //# sourceMappingURL=chunk-VMUQAISH.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../connectors/src/secrets.ts","../connectors/src/config.ts"],"names":[],"mappings":";;;;AAUA,IAAM,MAAM,YAAA,CAAa,EAAE,MAAM,WAAA,EAAa,OAAA,EAAS,WAAW,CAAA;AAqD3D,IAAM,yBAAN,MAAoE;AAAA,EACxD,KAAA,uBAAY,GAAA,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjD,UAAU,OAAA,EAAuC;AAC/C,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AAClD,MAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AAAA,IAC3B;AAAA,EACF;AAAA,EAEA,QAAQ,GAAA,EAAiC;AACvC,IAAA,IAAI,CAAC,KAAK,OAAO,MAAA;AACjB,IAAA,IAAI,GAAA,CAAI,UAAA,CAAW,MAAM,CAAA,EAAG,OAAO,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,CAAI,KAAA,CAAM,CAAC,CAAC,CAAA;AAC9D,IAAA,IAAI,GAAA,CAAI,UAAA,CAAW,QAAQ,CA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ACoB;AACpB,EAAA,IAAI,CAAC,OAAO,OAAO,MAAA;AACnB,EAAA,OAAO,MAAM,OAAA,CAAQ,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,EAAE,CAAA,CAAE,CAAA;AACtC;AAmBO,SAAS,cAAA,CACd,MACA,OAAA,EAC0B;AAC1B,EAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAElB,EAAA,IAAI,SAAS,SAAA,EAAW;AACtB,IAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,EAAA,EAAI,KAAK,IAAA,EAAK;AAAA,EACjD;AACA,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,MAAM,CAAA,EAAG;AAC3B,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,IAAA,CAAK,MAAM,MAAA,CAAO,MAAM,CAAA,EAAG,GAAA,EAAK,IAAA,EAAK;AAAA,EACpE;AAIA,EAAA,MAAM,IAAI,sBAAA,CAAuB,IAAA,EAAM,OAAO,CAAA;AAChD","file":"chunk-KJ2LLWRF.js","sourcesContent":["/**\n * Secret provider abstraction.\n *\n * Decouples credential resolution from process.env so secrets can be\n * provisioned over the transport bridge instead of living in the\n * container's environment.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n\nconst log = createLogger({ kind: \"connector\", subkind: \"secrets\" });\n\n// ── Interfaces ──────────────────────────────────────────────────────────────\n\n/**\n * Read-only secret resolution. Adapters receive this interface.\n * @docLink packages/connectors/api-reference#secret-provider\n */\nexport interface SecretProvider {\n /**\n * Resolve a credential reference.\n *\n * @param ref - Credential reference such as \"env:GIT_TOKEN\",\n * \"oauth:google:user@example.com\", or an inline literal.\n * @returns The resolved secret value or undefined if not found.\n */\n resolve(ref: string): string | undefined;\n /**\n * Check whether a reference can be resolved.\n *\n * @param ref - Reference to check.\n * @returns True if resolve(ref) would return a non-undefined value.\n */\n has(ref: string): boolean;\n /**\n * Return all ref strings this provider can currently resolve.\n *\n * @returns All resolvable refs (used by forge UI and ConnectorFieldMissingError).\n */\n capabilities(): string[];\n}\n\n/**\n * Extends `SecretProvider` with the ability to load secrets at runtime via `provision()`.\n * @docLink packages/connectors/api-reference#provisionable-secret-provider\n */\nexport interface ProvisionableSecretProvider extends SecretProvider {\n /** Store a batch of key-value secrets. Keys are bare names (no prefix). */\n provision(secrets: Record<string, string>): void;\n}\n\n// ── Implementations ─────────────────────────────────────────────────────────\n\n/**\n * In-memory secret store. Secrets are provisioned over the transport bridge\n * and stored in a private Map — never touching the filesystem or process.env.\n *\n * Supports ref prefixes:\n * `\"env:KEY\"` — looks up KEY in the store\n * `\"vault:KEY\"` — looks up KEY in the store (future vault compat)\n * (no prefix) — returned as an inline value (backwards compat for non-chain usages)\n * @docLink packages/connectors/api-reference#in-memory-secret-provider\n */\nexport class InMemorySecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n /**\n * Store a batch of key-value secrets.\n *\n * @param secrets - Key-value map of secret names to values. Keys are bare names (no prefix).\n */\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return this.store.get(ref.slice(4));\n if (ref.startsWith(\"vault:\")) return this.store.get(ref.slice(6));\n // Bare key: check store first, then fall back to inline literal\n const stored = this.store.get(ref);\n if (stored !== undefined) return stored;\n return ref;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `env:${k}`);\n }\n}\n\n/**\n * Delegates to `process.env`. Used in CLI/standalone mode.\n * Does NOT pass through inline literals — returns `undefined` for any ref\n * that does not start with `\"env:\"`. Use `InMemorySecretProvider` for inline\n * literals in non-chain contexts.\n * @docLink packages/connectors/api-reference#env-secret-provider\n */\nexport class EnvSecretProvider implements SecretProvider {\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return process.env[ref.slice(4)];\n return undefined; // no inline passthrough\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return Object.keys(process.env).map((k) => `env:${k}`);\n }\n}\n\n/**\n * Pre-minted credential entry. Mirrors the discriminated `CredentialMint`\n * shape from `@skaile/workspaces/types` but redeclared here to keep this package\n * free of cross-package type dependencies.\n *\n * The failure branch carries the platform-side `code` + `message` so the\n * `ConnectorManager`'s wrapped mediator can surface the real reason instead of\n * a generic \"no pre-mint\" placeholder when a mint comes back as `ok: false`.\n */\nexport type PreMintedCredential =\n | { ok: true; token: string; expiresAt: string | null; mintedAt?: string }\n | {\n ok: false;\n code?: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\";\n message?: string;\n };\n\n/**\n * Pre-minted credential store. Holds short-lived tokens delivered upfront in\n * the v3 `session_init` envelope so the runner never has to call back to the\n * platform during mount setup.\n *\n * Resolves refs of the form `mount:<id>` and `connector:<id>`. Returns\n * `undefined` for any other ref so the chain falls through to the next\n * provider (`EnvSecretProvider` for `pat:env:NAME`, etc.).\n *\n * Tokens can be added/removed at runtime via {@link set} / {@link unset} so\n * `runner.add_mount` / `runner.add_connector` / `runner.update_credential`\n * capabilities stay strictly in-process — no round trip to the platform to\n * mint while the mount is hot-attached.\n *\n * For callers that need the full mint metadata (expiry timestamp, mintedAt\n * audit fields), use {@link mintFor} instead of the bare `resolve`. The\n * `ConnectorManager` consults this for the `auth: backend` initial-mint path so\n * the driver retains the original expiry semantics.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/connectors/api-reference#pre-minted-secret-provider\n */\nexport class PreMintedSecretProvider implements SecretProvider {\n private readonly mints = new Map<string, PreMintedCredential>();\n\n /**\n * Seed pre-minted credentials from the v3 `session_init.credentials` map.\n *\n * Failed mints (`ok: false`) are stored too so callers can distinguish\n * \"not pre-minted\" from \"pre-minted but failed\"; {@link resolve} treats\n * both as `undefined`.\n *\n * @param credentials Optional initial `{ mounts, connectors }` map.\n */\n constructor(credentials?: {\n mounts?: Record<string, PreMintedCredential>;\n connectors?: Record<string, PreMintedCredential>;\n }) {\n if (!credentials) return;\n for (const [id, mint] of Object.entries(credentials.mounts ?? {})) {\n this.mints.set(`mount:${id}`, mint);\n }\n for (const [id, mint] of Object.entries(credentials.connectors ?? {})) {\n this.mints.set(`connector:${id}`, mint);\n }\n }\n\n /**\n * Insert (or replace) a pre-minted credential. Used by\n * `runner.add_mount` / `runner.add_connector` / `runner.update_credential`\n * capability handlers when the platform delivers new credentials\n * mid-session.\n */\n set(kind: \"mount\" | \"connector\", id: string, mint: PreMintedCredential): void {\n this.mints.set(`${kind}:${id}`, mint);\n }\n\n /**\n * Remove a stored pre-minted credential. Used by the\n * `runner.remove_resource` capability handler.\n */\n unset(kind: \"mount\" | \"connector\", id: string): boolean {\n return this.mints.delete(`${kind}:${id}`);\n }\n\n /**\n * Look up the full {@link PreMintedCredential} for a `mount:` /\n * `connector:` keyed entry. Callers that only need the token use\n * {@link resolve} via the chain; callers that need expiry / audit\n * metadata (e.g. ConnectorManager) use this entry point.\n */\n mintFor(kind: \"mount\" | \"connector\", id: string): PreMintedCredential | undefined {\n return this.mints.get(`${kind}:${id}`);\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (!(ref.startsWith(\"mount:\") || ref.startsWith(\"connector:\"))) return undefined;\n const mint = this.mints.get(ref);\n return mint?.ok ? mint.token : undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.mints.entries()].filter(([, m]) => m.ok).map(([k]) => k);\n }\n}\n\n/**\n * Forge session secret provider. Secrets are provisioned from the Forge settings\n * panel over the transport bridge. Only handles `\"forge:\"` prefixed refs — returns\n * `undefined` for all others.\n * @docLink packages/connectors/api-reference#forge-secret-provider\n */\nexport class ForgeSecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"forge:\")) return this.store.get(ref.slice(6));\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `forge:${k}`);\n }\n}\n\n/**\n * Thrown when an OAuth-secured connector field requires user authorization before\n * it can be resolved. Contains the redirect URL to open in the user's browser.\n * @docLink packages/connectors/api-reference#o-auth-required-error\n */\nexport class OAuthRequiredError extends Error {\n readonly oauthRef: string;\n readonly authUrl: string;\n readonly state: string;\n\n /**\n * @param oauthRef - The 'oauth:<service>:<account>' ref that triggered the error\n * @param authUrl - Browser URL to open for OAuth authorization\n * @param state - OAuth state token for CSRF protection and callback correlation\n */\n constructor(oauthRef: string, authUrl: string, state: string) {\n super(`OAuth authorization required for ${oauthRef}`);\n this.name = \"OAuthRequiredError\";\n this.oauthRef = oauthRef;\n this.authUrl = authUrl;\n this.state = state;\n }\n}\n\n/**\n * Shape of an OAuth token bundle stored by `OAuthSecretProvider`.\n * @docLink packages/connectors/api-reference#o-auth-token-bundle\n */\nexport interface OAuthTokenBundle {\n accessToken: string;\n refreshToken?: string;\n /** Unix timestamp in ms */\n expiry?: number;\n}\n\n/**\n * Return value of `OAuthSecretProvider.initiateFlow()`. Contains the URL and CSRF state token.\n * @docLink packages/connectors/api-reference#o-auth-flow-request\n */\nexport interface OAuthFlowRequest {\n authUrl: string;\n state: string;\n}\n\n/**\n * OAuth token provider. Handles `\"oauth:<service>:<account>\"` refs.\n * Callers must call `chain.prepareRef()` before `chain.resolve()` for `oauth:` refs.\n * @docLink packages/connectors/api-reference#o-auth-secret-provider\n */\nexport interface OAuthSecretProvider extends SecretProvider {\n /**\n * Ensure the token for this ref is fresh.\n * Refreshes if expired.\n * Throws OAuthRequiredError if no token exists and user authorization is needed.\n */\n ensureFresh(ref: string): Promise<void>;\n\n /** Initiate the OAuth authorization flow. Returns URL to open in the user's browser. */\n initiateFlow(oauthService: string, account: string): Promise<OAuthFlowRequest>;\n\n /** Exchange authorization code for tokens and store the bundle. */\n completeFlow(state: string, code: string): Promise<void>;\n}\n\n/**\n * Abstract base for vault-backed secret providers (1Password, KeePass). Subclasses\n * implement `prefix` and `loadKeys()`. Locked until `unlock(credential)` is called.\n * @docLink packages/connectors/api-reference#locked-secret-provider\n */\nexport abstract class LockedSecretProvider implements SecretProvider {\n locked = true;\n protected readonly store = new Map<string, string>();\n abstract readonly prefix: string;\n\n async unlock(credential: string): Promise<void> {\n await this.loadKeys(credential);\n this.locked = false;\n }\n\n protected abstract loadKeys(credential: string): Promise<void>;\n\n resolve(ref: string): string | undefined {\n if (this.locked) return undefined;\n if (!ref.startsWith(this.prefix)) return undefined;\n return this.store.get(ref.slice(this.prefix.length));\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n if (this.locked) return [];\n return [...this.store.keys()].map((k) => `${this.prefix}${k}`);\n }\n}\n\n// ── Known provider prefixes ──────────────────────────────────────────────────\n\nconst KNOWN_PREFIXES = [\"env:\", \"forge:\", \"op:\", \"kp:\", \"oauth:\", \"mount:\", \"connector:\"] as const;\n\nfunction getPrefix(ref: string): string | undefined {\n return KNOWN_PREFIXES.find((p) => ref.startsWith(p));\n}\n\n/**\n * Chains multiple `SecretProvider` instances into a single resolver.\n * - Prefixed refs (`env:`, `forge:`, `op:`, `kp:`, `oauth:`) are routed to the first provider that can resolve them.\n * - Bare refs waterfall through all providers in order.\n * - Plain literals in `skaile.yaml` options are NOT passed to the chain; `ConnectorManager` handles them before calling `resolve()`.\n * @docLink packages/connectors/api-reference#secret-provider-chain\n */\nexport class SecretProviderChain implements SecretProvider {\n /**\n * @param providers - Ordered list of providers. For prefixed refs, the first\n * provider that can resolve wins. For bare refs, waterfall through all in order.\n */\n constructor(private readonly providers: SecretProvider[]) {}\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n const prefix = getPrefix(ref);\n log.debug(\"resolve secret\", { ref, prefix: prefix ?? \"(bare)\" });\n if (prefix) {\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n // Waterfall for bare refs\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n const all = this.providers.flatMap((p) => p.capabilities());\n return [...new Set(all)];\n }\n\n /** Returns the first provider that can resolve this ref. */\n providerFor(ref: string): SecretProvider | undefined {\n for (const p of this.providers) {\n if (p.resolve(ref) !== undefined) return p;\n }\n return undefined;\n }\n\n /**\n * Calls ensureFresh(ref) on the owning provider if it implements OAuthSecretProvider.\n * No-op for providers that don't have ensureFresh().\n *\n * @param ref - Must be an \"oauth:\" prefixed ref for this to have any effect.\n * Calls ensureFresh() on the owning OAuthSecretProvider.\n */\n async prepareRef(ref: string): Promise<void> {\n const owner = this.providerFor(ref);\n if (\n owner &&\n \"ensureFresh\" in owner &&\n typeof (owner as OAuthSecretProvider).ensureFresh === \"function\"\n ) {\n try {\n await (owner as OAuthSecretProvider).ensureFresh(ref);\n } catch (err) {\n log.error(\"secret provider ensureFresh failed\", err, { ref });\n throw err;\n }\n }\n }\n}\n","/**\n * Load connector declarations from skaile.yaml.\n *\n * The top-level `mounts:` key is no longer accepted (hard cut as of Task 11).\n * Filesystem-projected backends must be declared under `connectors:` with a\n * `mount:` sub-block. See `docs/migration-mounts-to-connectors.md`.\n */\n\nimport type { ConnectorDeclaration as WorkspaceConnector } from \"@skaile/workspaces/core\";\nimport { resolveSkWorkspaceConfig } from \"@skaile/workspaces/core\";\nimport type { ConnectorDeclaration } from \"./connector-types.js\";\n\n/**\n * Read `skaile.yaml` in `projectDir` and return all declared connectors as `ConnectorDeclaration[]`.\n *\n * Throws a migration error when the legacy top-level `mounts:` key is present.\n *\n * @param projectDir - Root of the workspace (directory containing `skaile.yaml`).\n * @returns Array of connector declarations, or an empty array if none are declared.\n * @docLink packages/connectors/api-reference#load-connector-declarations\n */\nexport function loadConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n const config = resolveSkWorkspaceConfig(projectDir);\n\n // Hard cut: reject legacy top-level `mounts:` key with an actionable message.\n if (config.mounts && config.mounts.length > 0) {\n throw new Error(\n \"'mounts:' is no longer supported — move entries under 'connectors:' with a 'mount:' sub-block. See docs/migration-mounts-to-connectors.md\",\n );\n }\n\n if (!config.connectors || config.connectors.length === 0) return [];\n return config.connectors.map(workspaceConnectorToDeclaration);\n}\n\nfunction workspaceConnectorToDeclaration(c: WorkspaceConnector): ConnectorDeclaration {\n const decl: ConnectorDeclaration = {\n id: c.id,\n driver: c.driver,\n access: c.access ?? \"read-only\",\n auth: c.auth,\n options: c.options,\n };\n\n // Map the optional mount sub-block when present.\n if (c.mount) {\n decl.mount = {\n source: c.mount.source,\n target: c.mount.target,\n watch: c.mount.watch,\n exposeAccessToken: c.mount.exposeAccessToken,\n accessTokenTTL: c.mount.accessTokenTTL,\n };\n }\n\n return decl;\n}\n\nimport type { ForgeSecretProvider, SecretProvider } from \"./secrets.js\";\nimport { EnvSecretProvider, InMemorySecretProvider, SecretProviderChain } from \"./secrets.js\";\n\n/**\n * Build a `SecretProviderChain` for Forge session context.\n * `OAuthSecretProvider` is not wired here — it must be provided externally\n * (the Forge session manager constructs it and passes it in).\n * @param forgeProvider - The Forge-provisioned secret store.\n * @param extraProviders - Additional providers prepended to the chain (e.g. an OAuth provider).\n * @returns A chain that routes `forge:` refs to the Forge store and `env:` refs to process.env.\n * @docLink packages/connectors/api-reference#create-forge-secret-provider-chain\n */\nexport function createForgeSecretProviderChain(\n forgeProvider: ForgeSecretProvider,\n extraProviders: SecretProvider[] = [],\n): SecretProviderChain {\n return new SecretProviderChain([...extraProviders, forgeProvider, new EnvSecretProvider()]);\n}\n\n/**\n * Build a `SecretProviderChain` for CLI/standalone context.\n * `EnvSecretProvider` takes priority; `extraSecrets` are loaded into an `InMemorySecretProvider`.\n * @param extraSecrets - Inline secrets injected into memory (e.g. tokens passed via CLI flags).\n * @returns A chain that resolves `env:` refs from process.env plus any inline extras.\n * @docLink packages/connectors/api-reference#create-cli-secret-provider-chain\n */\nexport function createCliSecretProviderChain(\n extraSecrets: Record<string, string> = {},\n): SecretProviderChain {\n const mem = new InMemorySecretProvider();\n if (Object.keys(extraSecrets).length > 0) {\n mem.provision(extraSecrets);\n }\n return new SecretProviderChain([new EnvSecretProvider(), mem]);\n}\n\n/**\n * Resolve a credential reference using a `SecretProvider`, or fall back to `env:NAME` lookup.\n * @param auth - Credential reference (e.g. `\"env:GIT_TOKEN\"`).\n * @param secrets - Optional provider; falls back to `process.env` if omitted.\n * @returns Resolved secret value or `undefined`.\n * @deprecated Use `SecretProviderChain.resolve()` instead.\n * @docLink packages/connectors/api-reference#resolve-auth\n */\n// @TODO: Code-Review: deprecated shim kept for backward compat — remove once all callers migrate to SecretProviderChain.resolve()\nexport function resolveAuth(\n auth: string | undefined,\n secrets?: import(\"./secrets.js\").SecretProvider,\n): string | undefined {\n if (!auth) return undefined;\n if (secrets) return secrets.resolve(auth);\n if (auth.startsWith(\"env:\")) {\n const envVar = auth.slice(4);\n return process.env[envVar];\n }\n return auth;\n}\n\n// ── Auth grammar (mount-side, Tier 2 credential tiers) ───────────────────────\n\n/**\n * Provider kind for a mount auth ref.\n *\n * Two values are accepted:\n * - `pat` — static personal access token resolved via the secrets chain\n * (standalone CLI / non-platform contexts).\n * - `backend` — token minted by the platform's credential mediator over the\n * transport (`request_access_token` round-trip). Provider\n * dispatch (OAuth, GitHub App, ...) lives backend-side; the\n * runner stays provider-agnostic.\n *\n * @docLink packages/connectors/api-reference#mount-auth-kind\n */\nexport type MountAuthKind = \"pat\" | \"backend\";\n\n/**\n * Parsed mount `auth:` field.\n *\n * - `pat` → `value` is the inner secret ref (e.g. `env:NAME`).\n * - `backend` → `value` is empty (sentinel only); the runner asks the\n * backend for tokens via `request_access_token`.\n *\n * @docLink packages/connectors/api-reference#mount-auth-ref\n */\nexport interface MountAuthRef {\n kind: MountAuthKind;\n /** Prefix-stripped payload — see kind for shape. Empty for `backend`. */\n value: string;\n /** Original auth string from the declaration, kept for diagnostics. */\n raw: string;\n}\n\n/**\n * Thrown when a mount declaration's `auth:` field uses the legacy bare `env:NAME` grammar\n * or any other unrecognized form. Migrate to `pat:env:NAME` (standalone) or `backend`\n * (platform-mediated).\n * @docLink packages/connectors/api-reference#legacy-auth-grammar-error\n */\nexport class LegacyAuthGrammarError extends Error {\n readonly auth: string;\n constructor(auth: string, mountId?: string) {\n const where = mountId ? ` on mount '${mountId}'` : \"\";\n super(\n `Legacy or unrecognized auth grammar${where} ('${auth}'). ` +\n `Replace with one of:\\n` +\n ` - backend (platform-mediated, recommended)\\n` +\n ` - pat:env:NAME (standalone CLI / static token)\\n` +\n `See _devlog/specs/2026-05-06-tier-2-credential-mediation.md.`,\n );\n this.name = \"LegacyAuthGrammarError\";\n this.auth = auth;\n }\n}\n\n/**\n * Resolve the `auth: backend` initial mint for a given mount or connector id\n * by querying the secrets chain with a `${kind}:${id}` ref. Returns the\n * resolved bearer token or `undefined` if no pre-minted credential is\n * available.\n *\n * Used by the runner when wiring `ConnectorManager` to\n * answer initial-mint requests from `PreMintedSecretProvider` without\n * round-tripping to the platform. Drivers continue to receive a\n * `tokenMediator` for refresh + retry-401 paths.\n *\n * @param kind Resource family (`mount` or `connector`).\n * @param id Resource declaration id.\n * @param chain Secrets chain. Pass `undefined` to return `undefined`.\n * @returns The pre-minted token, or `undefined` if not stored on the chain.\n * @docLink packages/connectors/api-reference#resolve-backend-auth-for\n */\nexport function resolveBackendAuthFor(\n kind: \"mount\" | \"connector\",\n id: string,\n chain: import(\"./secrets.js\").SecretProvider | undefined,\n): string | undefined {\n if (!chain) return undefined;\n return chain.resolve(`${kind}:${id}`);\n}\n\n/**\n * Parse a mount-side auth ref into a typed `MountAuthRef`.\n *\n * Accepted forms:\n * - `backend` — platform-mediated mint via `request_access_token`.\n * - `pat:env:NAME` — static PAT resolved from the secrets chain.\n *\n * Rejects bare `env:NAME` (legacy) and provider-prefixed grammars (`oauth:`,\n * `github-app:`) — those moved backend-side as part of Tier-2 mediation.\n * Returns `undefined` when `auth` is absent or empty.\n *\n * @param auth - Raw `auth:` value from the mount declaration.\n * @param mountId - Optional mount id included in error messages.\n * @returns Parsed `MountAuthRef` or `undefined`.\n * @throws {LegacyAuthGrammarError} for any unrecognized grammar.\n * @docLink packages/connectors/api-reference#resolve-auth-ref\n */\nexport function resolveAuthRef(\n auth: string | undefined,\n mountId?: string,\n): MountAuthRef | undefined {\n if (!auth) return undefined;\n\n if (auth === \"backend\") {\n return { kind: \"backend\", value: \"\", raw: auth };\n }\n if (auth.startsWith(\"pat:\")) {\n return { kind: \"pat\", value: auth.slice(\"pat:\".length), raw: auth };\n }\n\n // Legacy bare `env:NAME` and the deprecated provider-prefixed grammars\n // (`oauth:`, `github-app:`) all land here.\n throw new LegacyAuthGrammarError(auth, mountId);\n}\n"]}
1
+ {"version":3,"sources":["../connectors/src/secrets.ts","../connectors/src/config.ts"],"names":[],"mappings":";;;;AAUA,IAAM,MAAM,YAAA,CAAa,EAAE,MAAM,WAAA,EAAa,OAAA,EAAS,WAAW,CAAA;AAqD3D,IAAM,yBAAN,MAAoE;AAAA,EACxD,KAAA,uBAAY,GAAA,EAAoB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOjD,UAAU,OAAA,EAAuC;AAC/C,IAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,OAAO,CAAA,EAAG;AAClD,MAAA,IAAA,CAAK,KAAA,CAAM,GAAA,CAAI,GAAA,EAAK,KAAK,CAAA;AAAA,IAC3B;AAAA,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ACnD,IAAA,KAAA;AAAA,MACE,CAAA,mCAAA,EAAsC,KAAK,CAAA,GAAA,EAAM,IAAI,CAAA;AAAA;AAAA;AAAA,4DAAA;AAAA,KAKvD;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAmBO,SAAS,qBAAA,CACd,IAAA,EACA,EAAA,EACA,KAAA,EACoB;AACpB,EAAA,IAAI,CAAC,OAAO,OAAO,MAAA;AACnB,EAAA,OAAO,MAAM,OAAA,CAAQ,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,EAAE,CAAA,CAAE,CAAA;AACtC;AAmBO,SAAS,cAAA,CACd,MACA,OAAA,EAC0B;AAC1B,EAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAElB,EAAA,IAAI,SAAS,SAAA,EAAW;AACtB,IAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,EAAA,EAAI,KAAK,IAAA,EAAK;AAAA,EACjD;AACA,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,MAAM,CAAA,EAAG;AAC3B,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,IAAA,CAAK,MAAM,MAAA,CAAO,MAAM,CAAA,EAAG,GAAA,EAAK,IAAA,EAAK;AAAA,EACpE;AAIA,EAAA,MAAM,IAAI,sBAAA,CAAuB,IAAA,EAAM,OAAO,CAAA;AAChD","file":"chunk-VMUQAISH.js","sourcesContent":["/**\n * Secret provider abstraction.\n *\n * Decouples credential resolution from process.env so secrets can be\n * provisioned over the transport bridge instead of living in the\n * container's environment.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n\nconst log = createLogger({ kind: \"connector\", subkind: \"secrets\" });\n\n// ── Interfaces ──────────────────────────────────────────────────────────────\n\n/**\n * Read-only secret resolution. Adapters receive this interface.\n * @docLink packages/connectors/api-reference#secret-provider\n */\nexport interface SecretProvider {\n /**\n * Resolve a credential reference.\n *\n * @param ref - Credential reference such as \"env:GIT_TOKEN\",\n * \"oauth:google:user@example.com\", or an inline literal.\n * @returns The resolved secret value or undefined if not found.\n */\n resolve(ref: string): string | undefined;\n /**\n * Check whether a reference can be resolved.\n *\n * @param ref - Reference to check.\n * @returns True if resolve(ref) would return a non-undefined value.\n */\n has(ref: string): boolean;\n /**\n * Return all ref strings this provider can currently resolve.\n *\n * @returns All resolvable refs (used by forge UI and ConnectorFieldMissingError).\n */\n capabilities(): string[];\n}\n\n/**\n * Extends `SecretProvider` with the ability to load secrets at runtime via `provision()`.\n * @docLink packages/connectors/api-reference#provisionable-secret-provider\n */\nexport interface ProvisionableSecretProvider extends SecretProvider {\n /** Store a batch of key-value secrets. Keys are bare names (no prefix). */\n provision(secrets: Record<string, string>): void;\n}\n\n// ── Implementations ─────────────────────────────────────────────────────────\n\n/**\n * In-memory secret store. Secrets are provisioned over the transport bridge\n * and stored in a private Map — never touching the filesystem or process.env.\n *\n * Supports ref prefixes:\n * `\"env:KEY\"` — looks up KEY in the store\n * `\"vault:KEY\"` — looks up KEY in the store (future vault compat)\n * (no prefix) — returned as an inline value (backwards compat for non-chain usages)\n * @docLink packages/connectors/api-reference#in-memory-secret-provider\n */\nexport class InMemorySecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n /**\n * Store a batch of key-value secrets.\n *\n * @param secrets - Key-value map of secret names to values. Keys are bare names (no prefix).\n */\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return this.store.get(ref.slice(4));\n if (ref.startsWith(\"vault:\")) return this.store.get(ref.slice(6));\n // Bare key: check store first, then fall back to inline literal\n const stored = this.store.get(ref);\n if (stored !== undefined) return stored;\n return ref;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `env:${k}`);\n }\n}\n\n/**\n * Delegates to `process.env`. Used in CLI/standalone mode.\n * Does NOT pass through inline literals — returns `undefined` for any ref\n * that does not start with `\"env:\"`. Use `InMemorySecretProvider` for inline\n * literals in non-chain contexts.\n * @docLink packages/connectors/api-reference#env-secret-provider\n */\nexport class EnvSecretProvider implements SecretProvider {\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return process.env[ref.slice(4)];\n return undefined; // no inline passthrough\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return Object.keys(process.env).map((k) => `env:${k}`);\n }\n}\n\n/**\n * Pre-minted credential entry. Mirrors the discriminated `CredentialMint`\n * shape from `@skaile/workspaces/types` but redeclared here to keep this package\n * free of cross-package type dependencies.\n *\n * The failure branch carries the platform-side `code` + `message` so the\n * `ConnectorManager`'s wrapped mediator can surface the real reason instead of\n * a generic \"no pre-mint\" placeholder when a mint comes back as `ok: false`.\n */\nexport type PreMintedCredential =\n | { ok: true; token: string; expiresAt: string | null; mintedAt?: string }\n | {\n ok: false;\n code?: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\";\n message?: string;\n };\n\n/**\n * Pre-minted credential store. Holds short-lived tokens delivered upfront in\n * the v3 `session_init` envelope so the runner never has to call back to the\n * platform during mount setup.\n *\n * Resolves refs of the form `mount:<id>` and `connector:<id>`. Returns\n * `undefined` for any other ref so the chain falls through to the next\n * provider (`EnvSecretProvider` for `pat:env:NAME`, etc.).\n *\n * Tokens can be added/removed at runtime via {@link set} / {@link unset} so\n * `runner.add_mount` / `runner.add_connector` / `runner.update_credential`\n * capabilities stay strictly in-process — no round trip to the platform to\n * mint while the mount is hot-attached.\n *\n * For callers that need the full mint metadata (expiry timestamp, mintedAt\n * audit fields), use {@link mintFor} instead of the bare `resolve`. The\n * `ConnectorManager` consults this for the `auth: backend` initial-mint path so\n * the driver retains the original expiry semantics.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/connectors/api-reference#pre-minted-secret-provider\n */\nexport class PreMintedSecretProvider implements SecretProvider {\n private readonly mints = new Map<string, PreMintedCredential>();\n\n /**\n * Seed pre-minted credentials from the v3 `session_init.credentials` map.\n *\n * Failed mints (`ok: false`) are stored too so callers can distinguish\n * \"not pre-minted\" from \"pre-minted but failed\"; {@link resolve} treats\n * both as `undefined`.\n *\n * @param credentials Optional initial `{ mounts, connectors }` map.\n */\n constructor(credentials?: {\n mounts?: Record<string, PreMintedCredential>;\n connectors?: Record<string, PreMintedCredential>;\n }) {\n if (!credentials) return;\n for (const [id, mint] of Object.entries(credentials.mounts ?? {})) {\n this.mints.set(`mount:${id}`, mint);\n }\n for (const [id, mint] of Object.entries(credentials.connectors ?? {})) {\n this.mints.set(`connector:${id}`, mint);\n }\n }\n\n /**\n * Insert (or replace) a pre-minted credential. Used by\n * `runner.add_mount` / `runner.add_connector` / `runner.update_credential`\n * capability handlers when the platform delivers new credentials\n * mid-session.\n */\n set(kind: \"mount\" | \"connector\", id: string, mint: PreMintedCredential): void {\n this.mints.set(`${kind}:${id}`, mint);\n }\n\n /**\n * Remove a stored pre-minted credential. Used by the\n * `runner.remove_resource` capability handler.\n */\n unset(kind: \"mount\" | \"connector\", id: string): boolean {\n return this.mints.delete(`${kind}:${id}`);\n }\n\n /**\n * Look up the full {@link PreMintedCredential} for a `mount:` /\n * `connector:` keyed entry. Callers that only need the token use\n * {@link resolve} via the chain; callers that need expiry / audit\n * metadata (e.g. ConnectorManager) use this entry point.\n */\n mintFor(kind: \"mount\" | \"connector\", id: string): PreMintedCredential | undefined {\n return this.mints.get(`${kind}:${id}`);\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (!(ref.startsWith(\"mount:\") || ref.startsWith(\"connector:\"))) return undefined;\n const mint = this.mints.get(ref);\n return mint?.ok ? mint.token : undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.mints.entries()].filter(([, m]) => m.ok).map(([k]) => k);\n }\n}\n\n/**\n * Forge session secret provider. Secrets are provisioned from the Forge settings\n * panel over the transport bridge. Only handles `\"forge:\"` prefixed refs — returns\n * `undefined` for all others.\n * @docLink packages/connectors/api-reference#forge-secret-provider\n */\nexport class ForgeSecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"forge:\")) return this.store.get(ref.slice(6));\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `forge:${k}`);\n }\n}\n\n/**\n * Thrown when an OAuth-secured connector field requires user authorization before\n * it can be resolved. Contains the redirect URL to open in the user's browser.\n * @docLink packages/connectors/api-reference#o-auth-required-error\n */\nexport class OAuthRequiredError extends Error {\n readonly oauthRef: string;\n readonly authUrl: string;\n readonly state: string;\n\n /**\n * @param oauthRef - The 'oauth:<service>:<account>' ref that triggered the error\n * @param authUrl - Browser URL to open for OAuth authorization\n * @param state - OAuth state token for CSRF protection and callback correlation\n */\n constructor(oauthRef: string, authUrl: string, state: string) {\n super(`OAuth authorization required for ${oauthRef}`);\n this.name = \"OAuthRequiredError\";\n this.oauthRef = oauthRef;\n this.authUrl = authUrl;\n this.state = state;\n }\n}\n\n/**\n * Shape of an OAuth token bundle stored by `OAuthSecretProvider`.\n * @docLink packages/connectors/api-reference#o-auth-token-bundle\n */\nexport interface OAuthTokenBundle {\n accessToken: string;\n refreshToken?: string;\n /** Unix timestamp in ms */\n expiry?: number;\n}\n\n/**\n * Return value of `OAuthSecretProvider.initiateFlow()`. Contains the URL and CSRF state token.\n * @docLink packages/connectors/api-reference#o-auth-flow-request\n */\nexport interface OAuthFlowRequest {\n authUrl: string;\n state: string;\n}\n\n/**\n * OAuth token provider. Handles `\"oauth:<service>:<account>\"` refs.\n * Callers must call `chain.prepareRef()` before `chain.resolve()` for `oauth:` refs.\n * @docLink packages/connectors/api-reference#o-auth-secret-provider\n */\nexport interface OAuthSecretProvider extends SecretProvider {\n /**\n * Ensure the token for this ref is fresh.\n * Refreshes if expired.\n * Throws OAuthRequiredError if no token exists and user authorization is needed.\n */\n ensureFresh(ref: string): Promise<void>;\n\n /** Initiate the OAuth authorization flow. Returns URL to open in the user's browser. */\n initiateFlow(oauthService: string, account: string): Promise<OAuthFlowRequest>;\n\n /** Exchange authorization code for tokens and store the bundle. */\n completeFlow(state: string, code: string): Promise<void>;\n}\n\n/**\n * Abstract base for vault-backed secret providers (1Password, KeePass). Subclasses\n * implement `prefix` and `loadKeys()`. Locked until `unlock(credential)` is called.\n * @docLink packages/connectors/api-reference#locked-secret-provider\n */\nexport abstract class LockedSecretProvider implements SecretProvider {\n locked = true;\n protected readonly store = new Map<string, string>();\n abstract readonly prefix: string;\n\n async unlock(credential: string): Promise<void> {\n await this.loadKeys(credential);\n this.locked = false;\n }\n\n protected abstract loadKeys(credential: string): Promise<void>;\n\n resolve(ref: string): string | undefined {\n if (this.locked) return undefined;\n if (!ref.startsWith(this.prefix)) return undefined;\n return this.store.get(ref.slice(this.prefix.length));\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n if (this.locked) return [];\n return [...this.store.keys()].map((k) => `${this.prefix}${k}`);\n }\n}\n\n// ── Known provider prefixes ──────────────────────────────────────────────────\n\nconst KNOWN_PREFIXES = [\"env:\", \"forge:\", \"op:\", \"kp:\", \"oauth:\", \"mount:\", \"connector:\"] as const;\n\nfunction getPrefix(ref: string): string | undefined {\n return KNOWN_PREFIXES.find((p) => ref.startsWith(p));\n}\n\n/**\n * Chains multiple `SecretProvider` instances into a single resolver.\n * - Prefixed refs (`env:`, `forge:`, `op:`, `kp:`, `oauth:`) are routed to the first provider that can resolve them.\n * - Bare refs waterfall through all providers in order.\n * - Plain literals in `skaile.yaml` options are NOT passed to the chain; `ConnectorManager` handles them before calling `resolve()`.\n * @docLink packages/connectors/api-reference#secret-provider-chain\n */\nexport class SecretProviderChain implements SecretProvider {\n /**\n * @param providers - Ordered list of providers. For prefixed refs, the first\n * provider that can resolve wins. For bare refs, waterfall through all in order.\n */\n constructor(private readonly providers: SecretProvider[]) {}\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n const prefix = getPrefix(ref);\n log.debug(\"resolve secret\", { ref, prefix: prefix ?? \"(bare)\" });\n if (prefix) {\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n // Waterfall for bare refs\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n const all = this.providers.flatMap((p) => p.capabilities());\n return [...new Set(all)];\n }\n\n /** Returns the first provider that can resolve this ref. */\n providerFor(ref: string): SecretProvider | undefined {\n for (const p of this.providers) {\n if (p.resolve(ref) !== undefined) return p;\n }\n return undefined;\n }\n\n /**\n * Calls ensureFresh(ref) on the owning provider if it implements OAuthSecretProvider.\n * No-op for providers that don't have ensureFresh().\n *\n * @param ref - Must be an \"oauth:\" prefixed ref for this to have any effect.\n * Calls ensureFresh() on the owning OAuthSecretProvider.\n */\n async prepareRef(ref: string): Promise<void> {\n const owner = this.providerFor(ref);\n if (\n owner &&\n \"ensureFresh\" in owner &&\n typeof (owner as OAuthSecretProvider).ensureFresh === \"function\"\n ) {\n try {\n await (owner as OAuthSecretProvider).ensureFresh(ref);\n } catch (err) {\n log.error(\"secret provider ensureFresh failed\", err, { ref });\n throw err;\n }\n }\n }\n}\n","/**\n * Load connector declarations from skaile.yaml.\n *\n * The top-level `mounts:` key is no longer accepted (hard cut as of Task 11).\n * Filesystem-projected backends must be declared under `connectors:` with a\n * `mount:` sub-block. See `docs/migration-mounts-to-connectors.md`.\n */\n\nimport type { ConnectorDeclaration as WorkspaceConnector } from \"@skaile/workspaces/core\";\nimport { resolveSkWorkspaceConfig } from \"@skaile/workspaces/core\";\nimport type { ConnectorDeclaration } from \"./connector-types.js\";\n\n/**\n * Read `skaile.yaml` in `projectDir` and return all declared connectors as `ConnectorDeclaration[]`.\n *\n * Throws a migration error when the legacy top-level `mounts:` key is present.\n *\n * @param projectDir - Root of the workspace (directory containing `skaile.yaml`).\n * @returns Array of connector declarations, or an empty array if none are declared.\n * @docLink packages/connectors/api-reference#load-connector-declarations\n */\nexport function loadConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n const config = resolveSkWorkspaceConfig(projectDir);\n\n // Hard cut: reject legacy top-level `mounts:` key with an actionable message.\n if (config.mounts && config.mounts.length > 0) {\n throw new Error(\n \"'mounts:' is no longer supported — move entries under 'connectors:' with a 'mount:' sub-block. See docs/migration-mounts-to-connectors.md\",\n );\n }\n\n if (!config.connectors || config.connectors.length === 0) return [];\n return config.connectors.map(workspaceConnectorToDeclaration);\n}\n\nfunction workspaceConnectorToDeclaration(c: WorkspaceConnector): ConnectorDeclaration {\n const decl: ConnectorDeclaration = {\n id: c.id,\n driver: c.driver,\n access: c.access ?? \"read-only\",\n auth: c.auth,\n options: c.options,\n };\n\n // Map the optional mount sub-block when present.\n if (c.mount) {\n decl.mount = {\n source: c.mount.source,\n target: c.mount.target,\n watch: c.mount.watch,\n exposeAccessToken: c.mount.exposeAccessToken,\n accessTokenTTL: c.mount.accessTokenTTL,\n };\n }\n\n return decl;\n}\n\nimport type { ForgeSecretProvider, SecretProvider } from \"./secrets.js\";\nimport { EnvSecretProvider, InMemorySecretProvider, SecretProviderChain } from \"./secrets.js\";\n\n/**\n * Build a `SecretProviderChain` for Forge session context.\n * `OAuthSecretProvider` is not wired here — it must be provided externally\n * (the Forge session manager constructs it and passes it in).\n * @param forgeProvider - The Forge-provisioned secret store.\n * @param extraProviders - Additional providers prepended to the chain (e.g. an OAuth provider).\n * @returns A chain that routes `forge:` refs to the Forge store and `env:` refs to process.env.\n * @docLink packages/connectors/api-reference#create-forge-secret-provider-chain\n */\nexport function createForgeSecretProviderChain(\n forgeProvider: ForgeSecretProvider,\n extraProviders: SecretProvider[] = [],\n): SecretProviderChain {\n return new SecretProviderChain([...extraProviders, forgeProvider, new EnvSecretProvider()]);\n}\n\n/**\n * Build a `SecretProviderChain` for CLI/standalone context.\n * `EnvSecretProvider` takes priority; `extraSecrets` are loaded into an `InMemorySecretProvider`.\n * @param extraSecrets - Inline secrets injected into memory (e.g. tokens passed via CLI flags).\n * @returns A chain that resolves `env:` refs from process.env plus any inline extras.\n * @docLink packages/connectors/api-reference#create-cli-secret-provider-chain\n */\nexport function createCliSecretProviderChain(\n extraSecrets: Record<string, string> = {},\n): SecretProviderChain {\n const mem = new InMemorySecretProvider();\n if (Object.keys(extraSecrets).length > 0) {\n mem.provision(extraSecrets);\n }\n return new SecretProviderChain([new EnvSecretProvider(), mem]);\n}\n\n/**\n * Resolve a credential reference using a `SecretProvider`, or fall back to `env:NAME` lookup.\n * @param auth - Credential reference (e.g. `\"env:GIT_TOKEN\"`).\n * @param secrets - Optional provider; falls back to `process.env` if omitted.\n * @returns Resolved secret value or `undefined`.\n * @deprecated Use `SecretProviderChain.resolve()` instead.\n * @docLink packages/connectors/api-reference#resolve-auth\n */\n// @TODO: Code-Review: deprecated shim kept for backward compat — remove once all callers migrate to SecretProviderChain.resolve()\nexport function resolveAuth(\n auth: string | undefined,\n secrets?: import(\"./secrets.js\").SecretProvider,\n): string | undefined {\n if (!auth) return undefined;\n if (secrets) return secrets.resolve(auth);\n if (auth.startsWith(\"env:\")) {\n const envVar = auth.slice(4);\n return process.env[envVar];\n }\n return auth;\n}\n\n// ── Auth grammar (mount-side, Tier 2 credential tiers) ───────────────────────\n\n/**\n * Provider kind for a mount auth ref.\n *\n * Two values are accepted:\n * - `pat` — static personal access token resolved via the secrets chain\n * (standalone CLI / non-platform contexts).\n * - `backend` — token minted by the platform's credential mediator over the\n * transport (`request_access_token` round-trip). Provider\n * dispatch (OAuth, GitHub App, ...) lives backend-side; the\n * runner stays provider-agnostic.\n *\n * @docLink packages/connectors/api-reference#mount-auth-kind\n */\nexport type MountAuthKind = \"pat\" | \"backend\";\n\n/**\n * Parsed mount `auth:` field.\n *\n * - `pat` → `value` is the inner secret ref (e.g. `env:NAME`).\n * - `backend` → `value` is empty (sentinel only); the runner asks the\n * backend for tokens via `request_access_token`.\n *\n * @docLink packages/connectors/api-reference#mount-auth-ref\n */\nexport interface MountAuthRef {\n kind: MountAuthKind;\n /** Prefix-stripped payload — see kind for shape. Empty for `backend`. */\n value: string;\n /** Original auth string from the declaration, kept for diagnostics. */\n raw: string;\n}\n\n/**\n * Thrown when a mount declaration's `auth:` field uses the legacy bare `env:NAME` grammar\n * or any other unrecognized form. Migrate to `pat:env:NAME` (standalone) or `backend`\n * (platform-mediated).\n * @docLink packages/connectors/api-reference#legacy-auth-grammar-error\n */\nexport class LegacyAuthGrammarError extends Error {\n readonly auth: string;\n constructor(auth: string, mountId?: string) {\n const where = mountId ? ` on mount '${mountId}'` : \"\";\n super(\n `Legacy or unrecognized auth grammar${where} ('${auth}'). ` +\n `Replace with one of:\\n` +\n ` - backend (platform-mediated, recommended)\\n` +\n ` - pat:env:NAME (standalone CLI / static token)\\n` +\n `See _devlog/specs/2026-05-06-tier-2-credential-mediation.md.`,\n );\n this.name = \"LegacyAuthGrammarError\";\n this.auth = auth;\n }\n}\n\n/**\n * Resolve the `auth: backend` initial mint for a given mount or connector id\n * by querying the secrets chain with a `${kind}:${id}` ref. Returns the\n * resolved bearer token or `undefined` if no pre-minted credential is\n * available.\n *\n * Used by the runner when wiring `ConnectorManager` to\n * answer initial-mint requests from `PreMintedSecretProvider` without\n * round-tripping to the platform. Drivers continue to receive a\n * `tokenMediator` for refresh + retry-401 paths.\n *\n * @param kind Resource family (`mount` or `connector`).\n * @param id Resource declaration id.\n * @param chain Secrets chain. Pass `undefined` to return `undefined`.\n * @returns The pre-minted token, or `undefined` if not stored on the chain.\n * @docLink packages/connectors/api-reference#resolve-backend-auth-for\n */\nexport function resolveBackendAuthFor(\n kind: \"mount\" | \"connector\",\n id: string,\n chain: import(\"./secrets.js\").SecretProvider | undefined,\n): string | undefined {\n if (!chain) return undefined;\n return chain.resolve(`${kind}:${id}`);\n}\n\n/**\n * Parse a mount-side auth ref into a typed `MountAuthRef`.\n *\n * Accepted forms:\n * - `backend` — platform-mediated mint via `request_access_token`.\n * - `pat:env:NAME` — static PAT resolved from the secrets chain.\n *\n * Rejects bare `env:NAME` (legacy) and provider-prefixed grammars (`oauth:`,\n * `github-app:`) — those moved backend-side as part of Tier-2 mediation.\n * Returns `undefined` when `auth` is absent or empty.\n *\n * @param auth - Raw `auth:` value from the mount declaration.\n * @param mountId - Optional mount id included in error messages.\n * @returns Parsed `MountAuthRef` or `undefined`.\n * @throws {LegacyAuthGrammarError} for any unrecognized grammar.\n * @docLink packages/connectors/api-reference#resolve-auth-ref\n */\nexport function resolveAuthRef(\n auth: string | undefined,\n mountId?: string,\n): MountAuthRef | undefined {\n if (!auth) return undefined;\n\n if (auth === \"backend\") {\n return { kind: \"backend\", value: \"\", raw: auth };\n }\n if (auth.startsWith(\"pat:\")) {\n return { kind: \"pat\", value: auth.slice(\"pat:\".length), raw: auth };\n }\n\n // Legacy bare `env:NAME` and the deprecated provider-prefixed grammars\n // (`oauth:`, `github-app:`) all land here.\n throw new LegacyAuthGrammarError(auth, mountId);\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { resolveSkWorkspaceConfig, readLinks } from './chunk-SOQMVRQL.js';
2
- import { scanDirectory } from './chunk-ZHLRRT5D.js';
1
+ import { resolveSkWorkspaceConfig, readLinks } from './chunk-N2C3A5PS.js';
2
+ import { scanDirectory } from './chunk-FRPKLIEZ.js';
3
3
  import { existsSync, readFileSync, lstatSync } from 'fs';
4
4
  import { resolve, join, dirname } from 'path';
5
5
  import { fileURLToPath } from 'url';
@@ -165,5 +165,5 @@ function findCatalogEntry(entries, query) {
165
165
  }
166
166
 
167
167
  export { BASE_ASSETS_REPO_NAME, resolveBaseAssetsRoot, resolveRuntimeAssets };
168
- //# sourceMappingURL=chunk-3DS5VIQP.js.map
169
- //# sourceMappingURL=chunk-3DS5VIQP.js.map
168
+ //# sourceMappingURL=chunk-WGPT6FV6.js.map
169
+ //# sourceMappingURL=chunk-WGPT6FV6.js.map