@skaile/workspaces 0.39.0 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/dist/{asset-feeds-W6JNAGNQ.js → asset-feeds-NOHUJ4XZ.js} +24 -6
- package/dist/asset-feeds-NOHUJ4XZ.js.map +1 -0
- package/dist/asset-manager/index.js +1 -1
- package/dist/{chunk-LJIE3PGF.js → chunk-22Q5R7SM.js} +2 -2
- package/dist/{chunk-LJIE3PGF.js.map → chunk-22Q5R7SM.js.map} +1 -1
- package/dist/{chunk-CMZWYMGD.js → chunk-3P7HBSSD.js} +3 -3
- package/dist/{chunk-CMZWYMGD.js.map → chunk-3P7HBSSD.js.map} +1 -1
- package/dist/{chunk-6LW7Q53Z.js → chunk-6BEGKO2Q.js} +3 -3
- package/dist/{chunk-6LW7Q53Z.js.map → chunk-6BEGKO2Q.js.map} +1 -1
- package/dist/{chunk-WVWX76IB.js → chunk-B5LHVPE2.js} +2 -2
- package/dist/{chunk-WVWX76IB.js.map → chunk-B5LHVPE2.js.map} +1 -1
- package/dist/{chunk-FZL6QOM7.js → chunk-BGVQKQCP.js} +3 -3
- package/dist/{chunk-FZL6QOM7.js.map → chunk-BGVQKQCP.js.map} +1 -1
- package/dist/{chunk-P7CIT445.js → chunk-C5UK3JK7.js} +21 -14
- package/dist/chunk-C5UK3JK7.js.map +1 -0
- package/dist/{chunk-ZDKJHQY2.js → chunk-JXT46QFC.js} +2 -2
- package/dist/{chunk-ZDKJHQY2.js.map → chunk-JXT46QFC.js.map} +1 -1
- package/dist/{chunk-UAYAK7N4.js → chunk-O66LT7UI.js} +49 -3
- package/dist/chunk-O66LT7UI.js.map +1 -0
- package/dist/{chunk-W23HDR6W.js → chunk-RM2KAMGD.js} +210 -59
- package/dist/chunk-RM2KAMGD.js.map +1 -0
- package/dist/{chunk-O4PANZI2.js → chunk-XNMABEHH.js} +3 -3
- package/dist/{chunk-O4PANZI2.js.map → chunk-XNMABEHH.js.map} +1 -1
- package/dist/{chunk-6KKNROBU.js → chunk-XZNPKJXU.js} +4 -4
- package/dist/{chunk-6KKNROBU.js.map → chunk-XZNPKJXU.js.map} +1 -1
- package/dist/cli/index.js +30 -26
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/src/asset-feeds.d.ts +8 -5
- package/dist/cli/src/asset-feeds.d.ts.map +1 -1
- package/dist/cli/src/commands/manage.d.ts +6 -5
- package/dist/cli/src/commands/manage.d.ts.map +1 -1
- package/dist/cli/src/commands/source.d.ts +8 -0
- package/dist/cli/src/commands/source.d.ts.map +1 -1
- package/dist/connectors/index.js +2 -2
- package/dist/connectors/rclone.js +1 -1
- package/dist/connectors/src/rclone-process-manager.d.ts +9 -0
- package/dist/connectors/src/rclone-process-manager.d.ts.map +1 -1
- package/dist/discovery/index.js +2 -2
- package/dist/{ensure-sources-AGORTKJC.js → ensure-sources-XITKRBLU.js} +5 -5
- package/dist/{ensure-sources-AGORTKJC.js.map → ensure-sources-XITKRBLU.js.map} +1 -1
- package/dist/factory-assets/connectors/deploy.js +2 -2
- package/dist/factory-assets/connectors/devserver.js +2 -2
- package/dist/factory-assets/connectors/flow/adapter.js +2 -2
- package/dist/factory-assets/connectors/flow/run-flow.js +3 -3
- package/dist/factory-assets/connectors/flow.js +2 -2
- package/dist/factory-assets/connectors/git.js +2 -2
- package/dist/factory-assets/connectors/gmail.js +2 -2
- package/dist/factory-assets/connectors/googledrive.js +2 -2
- package/dist/factory-assets/connectors/local.js +2 -2
- package/dist/factory-assets/connectors/mattermost.js +2 -2
- package/dist/factory-assets/connectors/memory.js +2 -2
- package/dist/factory-assets/connectors/minio.js +2 -2
- package/dist/factory-assets/connectors/postgres.js +2 -2
- package/dist/factory-assets/connectors/s3.js +2 -2
- package/dist/factory-assets/connectors/sharepoint.js +2 -2
- package/dist/factory-assets/connectors/sqlite.js +2 -2
- package/dist/factory-assets/connectors/static-server.js +2 -2
- package/dist/factory-assets/connectors/tunnel.js +2 -2
- package/dist/factory-assets/connectors/webdav.js +2 -2
- package/dist/factory-assets/connectors/xstate-store.js +2 -2
- package/dist/factory-assets/connectors/xstate.js +2 -2
- package/dist/library/index.js +3 -3
- package/dist/library/src/remote/remote-catalog-source.d.ts +11 -1
- package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
- package/dist/{open-library-WTN7QLN7.js → open-library-5KJOZHG7.js} +6 -6
- package/dist/{open-library-WTN7QLN7.js.map → open-library-5KJOZHG7.js.map} +1 -1
- package/dist/plugins/index.js +1 -1
- package/dist/plugins/src/catalog-source.d.ts +52 -0
- package/dist/plugins/src/catalog-source.d.ts.map +1 -1
- package/dist/plugins/src/index.d.ts +1 -1
- package/dist/plugins/src/index.d.ts.map +1 -1
- package/dist/runner/index.js +4 -4
- package/dist/runner/src/ai-credential-refresh.d.ts +55 -23
- package/dist/runner/src/ai-credential-refresh.d.ts.map +1 -1
- package/dist/runner/src/ai-credential-retry.d.ts +79 -0
- package/dist/runner/src/ai-credential-retry.d.ts.map +1 -0
- package/dist/runner/src/credential-rotated.d.ts +33 -0
- package/dist/runner/src/credential-rotated.d.ts.map +1 -0
- package/dist/runner/src/resource-handler.d.ts.map +1 -1
- package/dist/runner/src/serve-credentials.d.ts +14 -0
- package/dist/runner/src/serve-credentials.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/index.js +4 -4
- package/dist/sdk/runner.js +4 -4
- package/dist/secrets/index.js +2 -2
- package/dist/tui/index.js +4 -4
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/asset-feeds-W6JNAGNQ.js.map +0 -1
- package/dist/chunk-P7CIT445.js.map +0 -1
- package/dist/chunk-UAYAK7N4.js.map +0 -1
- package/dist/chunk-W23HDR6W.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"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AC1B,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-FZL6QOM7.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }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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-BGVQKQCP.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
@@ -563,7 +563,10 @@ function _buildRcloneArgs(config, io) {
|
|
|
563
563
|
"--log-level",
|
|
564
564
|
"INFO",
|
|
565
565
|
"--use-json-log",
|
|
566
|
-
"--allow-other"
|
|
566
|
+
"--allow-other",
|
|
567
|
+
// The ro-tmpfs deferred-mount barrier is already mounted here; without this
|
|
568
|
+
// rclone aborts with "directory already mounted". See mount-placeholder.ts.
|
|
569
|
+
"--allow-non-empty"
|
|
567
570
|
];
|
|
568
571
|
if (config.ignoreSizeCheck) {
|
|
569
572
|
args.push("--ignore-size", "--ignore-checksum");
|
|
@@ -609,19 +612,23 @@ async function newestMtimeMs(dir) {
|
|
|
609
612
|
}
|
|
610
613
|
return newest;
|
|
611
614
|
}
|
|
615
|
+
function _fuseMountPresent(procMountsText, mountPoint) {
|
|
616
|
+
const resolved = path.resolve(mountPoint);
|
|
617
|
+
for (const raw of procMountsText.split("\n")) {
|
|
618
|
+
if (raw.length === 0) continue;
|
|
619
|
+
const fields = raw.split(/\s+/);
|
|
620
|
+
const mp = fields[1];
|
|
621
|
+
const fstype = fields[2];
|
|
622
|
+
if (!mp || !fstype) continue;
|
|
623
|
+
const decoded = mp.replace(/\\040/g, " ");
|
|
624
|
+
if (decoded === resolved && (fstype === "fuse" || fstype.startsWith("fuse."))) return true;
|
|
625
|
+
}
|
|
626
|
+
return false;
|
|
627
|
+
}
|
|
612
628
|
async function isMountpoint(mountPoint) {
|
|
613
629
|
try {
|
|
614
|
-
const resolved = path.resolve(mountPoint);
|
|
615
630
|
const text = await readFile("/proc/self/mounts", "utf8");
|
|
616
|
-
|
|
617
|
-
if (raw.length === 0) continue;
|
|
618
|
-
const fields = raw.split(/\s+/);
|
|
619
|
-
const mp = fields[1];
|
|
620
|
-
if (!mp) continue;
|
|
621
|
-
const decoded = mp.replace(/\\040/g, " ");
|
|
622
|
-
if (decoded === resolved) return true;
|
|
623
|
-
}
|
|
624
|
-
return false;
|
|
631
|
+
return _fuseMountPresent(text, mountPoint);
|
|
625
632
|
} catch {
|
|
626
633
|
return false;
|
|
627
634
|
}
|
|
@@ -681,6 +688,6 @@ async function dirSize(dir) {
|
|
|
681
688
|
return total;
|
|
682
689
|
}
|
|
683
690
|
|
|
684
|
-
export { DEFAULT_UPLOAD_STUCK_THRESHOLD, DEFAULT_VFS_WRITE_BACK, PortPool, RcloneProcessManager, _buildRcloneArgs, _routeRcloneLogLine, awaitQuiescent, createFsWatcher, ensureDirMode };
|
|
685
|
-
//# sourceMappingURL=chunk-
|
|
686
|
-
//# sourceMappingURL=chunk-
|
|
691
|
+
export { DEFAULT_UPLOAD_STUCK_THRESHOLD, DEFAULT_VFS_WRITE_BACK, PortPool, RcloneProcessManager, _buildRcloneArgs, _fuseMountPresent, _routeRcloneLogLine, awaitQuiescent, createFsWatcher, ensureDirMode };
|
|
692
|
+
//# sourceMappingURL=chunk-C5UK3JK7.js.map
|
|
693
|
+
//# sourceMappingURL=chunk-C5UK3JK7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../connectors/src/fs-utils.ts","../connectors/src/port-pool.ts","../connectors/src/watcher.ts","../connectors/src/rclone-process-manager.ts"],"names":[],"mappings":";;;;;;;;;;AAkCA,eAAsB,aAAA,CAAc,KAAa,GAAA,EAA6B;AAC5E,EAAA,MAAM,KAAA,CAAM,GAAA,EAAK,EAAE,SAAA,EAAW,MAAM,CAAA;AACpC,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,CAAM,KAAK,GAAK,CAAA;AAAA,EACxB,SAAS,GAAA,EAAK;AACZ,IAAA,GAAA,EAAK,MAAM,4DAAA,EAAyD;AAAA,MAClE,IAAA,EAAM,GAAA;AAAA,MACN,OAAO,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG;AAAA,KACvD,CAAA;AAAA,EACH;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AAA,CAAE,MAAA,EAAO,EAAG;AACrB,QAAA,IAAI;AACF,UAAA,MAAM,CAAA,GAAI,MAAM,IAAA,CAAK,IAAI,CAAA;AACzB,UAAA,KAAA,IAAS,CAAA,CAAE,IAAA;AAAA,QACb,CAAA,CAAA,MAAQ;AAAA,QAER;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,CAAA;AAAA,EACT;AACA,EAAA,OAAO,KAAA;AACT","file":"chunk-C5UK3JK7.js","sourcesContent":["/**\n * Shared filesystem helpers for connector infrastructure.\n *\n * @docLink packages/connectors/api-reference#fs-utils\n */\n\nimport { chmod, mkdir } from \"node:fs/promises\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * mkdir(recursive) + chmod 0o770 in one call. The post-mkdir `chmod` is the\n * load-bearing piece: `mkdir(mode:)` is ANDed with the process umask\n * (typically 022 → effective mode 0o750), which strips the group-write bit\n * that `fusermount3` requires on the rclone mountpoint and rclone needs on\n * its vfs cache directory. Explicit `chmod` is umask-immune.\n *\n * EPERM on `chmod` is swallowed: when a foreign uid pre-created the\n * directory (a stray uid-1000 process inside the container or a host-side\n * platform process writing through the project bind-mount), the runner\n * cannot chmod it. The platform's agent container entrypoint runs as root\n * and heals the subtree on the next restart — see\n * `platform/docker/agent/entrypoint.sh` `_skaile_heal_ownership`. A debug\n * line is emitted when a logger is supplied so the rare-but-real heal\n * trigger is observable in session logs without adding noise on the happy\n * path.\n *\n * The chmod is *idempotent* (the syscall always fires, but a no-op when\n * the mode is already 0o770), not a no-op — kernel behaviour for chmod is\n * \"set\", not \"set-if-different\".\n *\n * @param dir Absolute or relative path to ensure exists at mode 0o770.\n * @param log Optional logger. When provided, EPERM-on-chmod emits a\n * `debug`-level entry under whatever taxonomy the caller's logger uses.\n */\nexport async function ensureDirMode(dir: string, log?: Logger): Promise<void> {\n await mkdir(dir, { recursive: true });\n try {\n await chmod(dir, 0o770);\n } catch (err) {\n log?.debug(\"chmod 0770 skipped (EPERM — entrypoint heal expected)\", {\n path: dir,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","/**\n * PortPool — allocates ports from a [min, max] range, checks OS for collisions.\n */\n\nimport { createConnection } from \"node:net\";\n\n/**\n * Allocates TCP ports from a `[min, max]` range with OS-level collision detection.\n * Used by service connector adapters (devserver, static-server) to assign local ports.\n * @docLink packages/connectors/api-reference#port-pool\n */\nexport class PortPool {\n private readonly min: number;\n private readonly max: number;\n private readonly inUse = new Set<number>();\n\n constructor(range: [number, number]) {\n this.min = range[0];\n this.max = range[1];\n }\n\n /** Allocate the next free port from the range. Checks OS for collisions. */\n async allocate(): Promise<number> {\n for (let port = this.min; port <= this.max; port++) {\n if (this.inUse.has(port)) continue;\n if (!(await PortPool.isPortFree(port))) {\n this.inUse.add(port);\n continue;\n }\n this.inUse.add(port);\n return port;\n }\n throw new Error(`No free port in range ${this.min}-${this.max}`);\n }\n\n /** Mark a port as in-use (for explicit port args or registered instances). */\n reserve(port: number): void {\n this.inUse.add(port);\n }\n\n /** Return a port to the pool. */\n release(port: number): void {\n this.inUse.delete(port);\n }\n\n /** Check if a port is currently tracked as in-use. */\n isInUse(port: number): boolean {\n return this.inUse.has(port);\n }\n\n /** Quick TCP connect test — returns true if nothing is listening. */\n static isPortFree(port: number, host = \"127.0.0.1\"): Promise<boolean> {\n return new Promise((resolve) => {\n const socket = createConnection({ port, host });\n socket.once(\"connect\", () => {\n socket.destroy();\n resolve(false);\n });\n socket.once(\"error\", () => {\n socket.destroy();\n resolve(true);\n });\n socket.setTimeout(500, () => {\n socket.destroy();\n resolve(true);\n });\n });\n }\n}\n","/**\n * Shared filesystem watcher factory for mountable adapters.\n *\n * Uses chokidar for cross-platform, debounced file watching.\n *\n * Automatically reads .gitignore from the watched directory and merges\n * those patterns into chokidar's ignore list. This prevents scanning\n * large generated directories (node_modules, dist, .next, etc.) that\n * most projects already declare as ignored.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n// Static import so bun --compile bundles chokidar into the binary. A dynamic\n// `await import(\"chokidar\")` is not seen by the compiler's static analyzer\n// and fails at runtime inside the /$bunfs/ virtual filesystem.\nimport chokidar from \"chokidar\";\nimport type { ConnectorChangeEvent } from \"./connector-types.js\";\nimport type { WatchHandle, WatchOptions } from \"./shared-types.js\";\n\n/**\n * Convert a glob pattern to a matcher function.\n *\n * Chokidar 5 changed string matchers to exact equality (`===`) instead of\n * glob matching. We convert our patterns to functions so chokidar can still\n * filter correctly.\n */\nfunction globToMatcher(pattern: string): (path: string) => boolean {\n // Simple segment-name patterns: **/NAME/** or **/NAME\n // Match any path that contains /NAME/ or ends with /NAME\n const segmentMatch = pattern.match(/^\\*\\*\\/([^*/?]+)\\/\\*\\*$/);\n if (segmentMatch) {\n const name = segmentMatch[1];\n return (p: string) => p.includes(`/${name}/`) || p.endsWith(`/${name}`) || p === name;\n }\n\n // Dot-prefixed segment: **/.NAME or **/.NAME/**\n const dotSegment = pattern.match(/^\\*\\*\\/(\\.[\\w#]+)(?:\\/\\*\\*)?$/);\n if (dotSegment) {\n const name = dotSegment[1];\n return (p: string) => p.includes(`/${name}/`) || p.endsWith(`/${name}`) || p === name;\n }\n\n // Extension wildcard: **/*.EXT.* or **/*.EXT\n const extMatch = pattern.match(/^\\*\\*\\/\\*(\\.\\w+(?:\\.\\*)?)/);\n if (extMatch) {\n const suffix = extMatch[1];\n if (suffix.endsWith(\".*\")) {\n // e.g. **/*.tmp.* -> match any file with .tmp. in it\n const base = suffix.slice(0, -2);\n return (p: string) => p.includes(base);\n }\n return (p: string) => p.endsWith(suffix);\n }\n\n // Suffix wildcard: **/*SUFFIX (e.g. **/*~)\n const suffixMatch = pattern.match(/^\\*\\*\\/\\*(.+)$/);\n if (suffixMatch) {\n const sfx = suffixMatch[1];\n return (p: string) => p.endsWith(sfx);\n }\n\n // Fallback: convert simple globs to regex\n const escaped = pattern\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \".*\");\n const re = new RegExp(`^${escaped}$`);\n return (p: string) => re.test(p);\n}\n\nconst DEFAULT_IGNORED: Array<string | ((path: string) => boolean)> = [\n (p: string) => p.includes(\"/.git/\") || p.endsWith(\"/.git\"),\n (p: string) => p.includes(\"/node_modules/\") || p.endsWith(\"/node_modules\"),\n (p: string) => p.includes(\"/.connectors/\") || p.endsWith(\"/.connectors\"),\n // Atomic-write tempfiles (Bun.write creates `<name>.tmp.<pid>.<ts>` then renames).\n // These vanish between readdir and fs.watch, causing EINVAL that crashes the process.\n (p: string) => /\\.tmp\\.\\d/.test(p),\n // Editor swap/backup files that also race with save operations.\n (p: string) => p.endsWith(\".swp\"),\n (p: string) => p.endsWith(\".swx\"),\n (p: string) => p.includes(\"/.#\"),\n (p: string) => p.endsWith(\"~\"),\n];\n/**\n * Default chokidar `awaitWriteFinish` stability threshold (ms). Exported so the\n * rclone process manager can reuse the same write-stabilization concept when\n * gating a flush on a quiescent mount.\n */\nexport const DEFAULT_DEBOUNCE_MS = 150;\n\n/**\n * Parse a .gitignore file into glob patterns suitable for chokidar's `ignored` option.\n * Handles comments, blank lines, directory patterns, and root-relative patterns.\n * Negation patterns (!) are skipped - chokidar cannot un-ignore.\n */\nfunction parseGitignore(rootDir: string): Array<(path: string) => boolean> {\n const gitignorePath = join(rootDir, \".gitignore\");\n if (!existsSync(gitignorePath)) return [];\n\n try {\n const content = readFileSync(gitignorePath, \"utf-8\");\n const matchers: Array<(path: string) => boolean> = [];\n\n for (const raw of content.split(\"\\n\")) {\n const line = raw.trim();\n if (!line || line.startsWith(\"#\") || line.startsWith(\"!\")) continue;\n\n let pattern = line;\n\n // Strip leading / (root-relative -> convert to rootDir-relative)\n if (pattern.startsWith(\"/\")) {\n pattern = pattern.slice(1);\n } else if (!pattern.includes(\"/\")) {\n // Bare name like \"node_modules\" or \"*.log\" -> match anywhere\n pattern = `**/${pattern}`;\n }\n\n // Directory pattern (trailing /) -> ensure it matches contents too\n if (pattern.endsWith(\"/\")) {\n matchers.push(globToMatcher(`${pattern}**`));\n } else {\n matchers.push(globToMatcher(pattern));\n // Also match as directory (e.g. \"dist\" should match \"dist/\" and \"dist/**\")\n if (!pattern.includes(\"*\") && !pattern.includes(\".\")) {\n matchers.push(globToMatcher(`${pattern}/**`));\n }\n }\n }\n\n return matchers;\n } catch {\n return [];\n }\n}\n\ntype ChokidarAction = \"create\" | \"edit\" | \"delete\";\n\nconst CHOKIDAR_EVENT_MAP: Record<string, ChokidarAction> = {\n add: \"create\",\n change: \"edit\",\n unlink: \"delete\",\n addDir: \"create\",\n unlinkDir: \"delete\",\n};\n\n/**\n * Create a cross-platform filesystem watcher on `rootDir` using chokidar.\n * Auto-reads `.gitignore` from `rootDir` and merges those patterns into the ignore list.\n * @param rootDir - Absolute path to the directory to watch.\n * @param callback - Called with each `ConnectorChangeEvent` (create / edit / delete).\n * @param options - Debounce interval and additional ignore patterns.\n * @returns A `WatchHandle` — call `.close()` to stop watching.\n * @docLink packages/connectors/api-reference#create-fs-watcher\n */\nexport async function createFsWatcher(\n rootDir: string,\n callback: (event: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n): Promise<WatchHandle> {\n const log = createLogger({ kind: \"connector\", subkind: \"watcher\", instance: rootDir });\n const gitignorePatterns = parseGitignore(rootDir);\n // Convert any remaining string patterns from options to matcher functions\n // (chokidar 5 treats strings as exact equality, not globs)\n const optionsIgnored = (options?.ignored ?? []).map((entry) =>\n typeof entry === \"string\" ? globToMatcher(entry) : entry,\n );\n const ignored = [...DEFAULT_IGNORED, ...gitignorePatterns, ...optionsIgnored];\n const debounceMs = options?.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n\n const watcher = chokidar.watch(rootDir, {\n ignoreInitial: true,\n ignored,\n awaitWriteFinish: { stabilityThreshold: debounceMs, pollInterval: 50 },\n usePolling: false,\n });\n\n // Swallow transient watch errors (EINVAL/ENOENT when a file vanishes between\n // readdir and fs.watch). Without this handler, chokidar rethrows and the\n // agent process dies.\n watcher.on(\"error\", (err) => {\n const message = err instanceof Error ? err.message : String(err);\n log.warn(\"watcher error (non-fatal)\", { message });\n });\n\n for (const [chokidarEvent, action] of Object.entries(CHOKIDAR_EVENT_MAP)) {\n (watcher as { on(event: string, fn: (fullPath: string) => void): void }).on(\n chokidarEvent,\n (fullPath: string) => {\n const rel = relative(rootDir, fullPath);\n if (!rel || rel.startsWith(\"..\")) return;\n // Normalize to forward slashes\n const normalizedPath = rel.split(\"\\\\\").join(\"/\");\n callback({ path: normalizedPath, action, source: \"filesystem\" });\n },\n );\n }\n\n return {\n close: () => watcher.close(),\n };\n}\n","/**\n * RcloneProcessManager — supervises an rclone FUSE subprocess per mount.\n *\n * Responsibilities:\n * - Spawn rclone with a per-mount config + cache dir, wait for the FUSE\n * mountpoint to appear, then return a handle.\n * - Pipe rclone's JSON-formatted log lines into the parent driver's\n * {@link Logger} via a child source `${driverName}+rclone`.\n * - Coordinate graceful stop (flush → SIGTERM → fusermount fallback).\n * - Expose `flush` (POST /vfs/refresh + poll /vfs/stats) and `status`\n * (process liveness + cache-dir size).\n *\n * Cross-link: see `workspaces/core/CLAUDE.md` § Logging for the\n * `createLogger` / `LogStore` contract, and\n * `_devlog/specs/2026-05-01-debug-logging-design.md` for the source taxonomy.\n */\n\nimport { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomBytes } from \"node:crypto\";\nimport { readdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport { ensureDirMode } from \"./fs-utils.js\";\nimport { PortPool } from \"./port-pool.js\";\nimport { DEFAULT_DEBOUNCE_MS } from \"./watcher.js\";\n\n/** Module-level pool for rclone remote-control (rc) ports. */\nconst RCLONE_RC_PORTS = new PortPool([55000, 56000]);\n\n/** Default rclone `--vfs-write-back` delay; raised from 5s so a rapidly-rewritten file settles before upload (avoids mid-write \"sizes differ\" aborts). */\nexport const DEFAULT_VFS_WRITE_BACK = \"30s\";\n\n/** Consecutive failed upload retries for one object before a stuck-upload error is surfaced. */\nexport const DEFAULT_UPLOAD_STUCK_THRESHOLD = 3;\n\n/**\n * Stabilization gate defaults for {@link RcloneProcessManager.flush}. Before\n * forcing an upload we wait until the vfs cache dir has had no write for\n * `thresholdMs`, bounded by `timeoutMs` so close/hibernate never blocks\n * forever. `pollMs` reuses the watcher's write-stabilization debounce.\n */\nconst STABILIZE_THRESHOLD_MS = 1_500;\nconst STABILIZE_TIMEOUT_MS = 30_000;\nconst STABILIZE_POLL_MS = DEFAULT_DEBOUNCE_MS;\n\n/**\n * Spawn-time configuration for a single rclone FUSE mount.\n * @docLink packages/connectors/api-reference#rclone-spawn-config\n */\nexport interface RcloneSpawnConfig {\n /** Logical mount id; used as `instance` and as part of the rclone config filename. */\n mountId: string;\n /**\n * Driver name (e.g. \"sharepoint\", \"webdav\"); used to derive the rclone\n * subprocess child logger subkind: `${driverName}+rclone`.\n */\n driverName: string;\n /** Absolute path inside the container where rclone will FUSE-mount. Created if missing. */\n mountPoint: string;\n /** Absolute path inside the container for the vfs cache. Created if missing. */\n cacheDir: string;\n /** Full INI text for rclone.conf (one [remote] section, named `skaile-<mountId>`). */\n rcloneConfig: string;\n /** Remote spec, e.g. `skaile-foo:/Clients/KADK`. */\n remote: string;\n /** rclone --vfs-cache-mode value. */\n vfsCacheMode: \"minimal\" | \"writes\" | \"full\";\n /** Per-mount cache size cap. Default: '5G'. */\n cacheMaxSize?: string;\n /** Per-mount cache age cap. Default: '168h'. */\n cacheMaxAge?: string;\n /**\n * Skip rclone's post-transfer size + checksum verification by appending\n * `--ignore-size --ignore-checksum`. Default: false (verification on).\n *\n * Escape hatch for remotes that mutate uploaded bytes server-side (notably\n * SharePoint Online normalising LF→CRLF on text/html), which makes the\n * remote object a different size/hash than the local source. rclone reads\n * that as `corrupted on transfer`, deletes the upload, and retries forever,\n * so the file never durably lands. Enabling this trades integrity\n * verification for sync-ability and must only be set by drivers that have\n * confirmed the mutation is benign. Off-by-default; wired per-driver, never\n * globally.\n */\n ignoreSizeCheck?: boolean;\n /**\n * rclone `--vfs-write-back` delay (e.g. '30s', '1m'). Controls how long a\n * dirty file sits before rclone starts uploading it. Default:\n * {@link DEFAULT_VFS_WRITE_BACK}. Raise it when the agent rewrites files\n * faster than they upload, to avoid mid-write \"sizes differ\" aborts.\n */\n vfsWriteBack?: string;\n /**\n * Consecutive upload retries for one object before {@link onUploadStuck}\n * fires. Default: {@link DEFAULT_UPLOAD_STUCK_THRESHOLD}.\n */\n uploadStuckThreshold?: number;\n /**\n * Optional hook invoked once per object when its upload has failed\n * `uploadStuckThreshold` times in a row. spawn() always also logs an\n * error-level entry through the `${driverName}+rclone` child logger; this\n * hook lets callers surface the stranded file elsewhere (e.g. a sync event).\n */\n onUploadStuck?: (object: string, tries: number) => void;\n /**\n * Optional hook invoked when rclone reports an OAuth auth failure (notably\n * `invalid_client` / `couldn't fetch token`, the symptom of an expired\n * access token that rclone cannot self-refresh). Wired by the mount driver\n * to the reactive arm of its token-refresh controller. Fires per matching\n * log line; the controller dedupes via its in-flight guard + cooldown.\n */\n onAuthError?: () => void;\n /**\n * Parent driver Logger — already tagged\n * `{kind:\"mount\", subkind:<driver>, instance:<mountId>}` by ConnectorManager.\n * Used for manager-level events; rclone subprocess events go through the\n * derived `child({subkind: \\`${driverName}+rclone\\`})` logger.\n */\n log: Logger;\n}\n\n/**\n * Handle returned by `RcloneProcessManager.spawn()` once the FUSE mountpoint is confirmed.\n * @docLink packages/connectors/api-reference#rclone-handle\n */\nexport interface RcloneHandle {\n /** OS process id of the rclone subprocess. */\n pid: number;\n /** Confirmed FUSE mountpoint (echo of input). */\n mountPoint: string;\n /** Cache directory (echo of input). */\n cacheDir: string;\n /** The local rc API address rclone is bound to, e.g. '127.0.0.1:54321'. */\n rcAddr: string;\n}\n\ninterface InternalEntry {\n proc: ChildProcess;\n configPath: string;\n port: number;\n mountPoint: string;\n cacheDir: string;\n /** The full spawn config, retained so `reconfigure` can recycle the process. */\n spawnConfig: RcloneSpawnConfig;\n log: Logger;\n rcloneLog: Logger;\n /**\n * Last few stderr lines for diagnostic purposes (used in spawn-failure\n * messages).\n */\n recentStderr: string[];\n}\n\nconst HANDLES = new Map<number, InternalEntry>();\n\n/**\n * Manages rclone FUSE subprocesses for mount drivers. Stateless across instances —\n * the internal handle registry is module-scoped so a fresh `RcloneProcessManager`\n * can still find handles created by a previous instance.\n * @docLink packages/connectors/api-reference#rclone-process-manager\n */\nexport class RcloneProcessManager {\n /**\n * Spawn an rclone FUSE mount. Resolves once the mountpoint is confirmed\n * present in `/proc/self/mounts`. Throws on timeout, on early exit, or\n * if invariants are violated.\n */\n async spawn(config: RcloneSpawnConfig): Promise<RcloneHandle> {\n if (!path.isAbsolute(config.mountPoint)) {\n throw new Error(`mountPoint must be absolute: ${config.mountPoint}`);\n }\n if (!path.isAbsolute(config.cacheDir)) {\n throw new Error(`cacheDir must be absolute: ${config.cacheDir}`);\n }\n\n // Defence-in-depth: the per-connector driver already chmods these via\n // ensureDirMode, but direct callers that bypass the driver still need\n // mountPoint and cacheDir to be group-writable for fusermount3 / vfs.\n await ensureDirMode(config.mountPoint, config.log);\n await ensureDirMode(config.cacheDir, config.log);\n\n const configPath = path.join(\n tmpdir(),\n `rclone-${config.mountId}-${randomBytes(6).toString(\"hex\")}.conf`,\n );\n await writeFile(configPath, config.rcloneConfig, { mode: 0o600 });\n\n const port = await RCLONE_RC_PORTS.allocate();\n const rcAddr = `127.0.0.1:${port}`;\n const rcloneLog = config.log.child({ subkind: `${config.driverName}+rclone` });\n\n config.log.info(\"rclone spawn starting\", {\n mountPoint: config.mountPoint,\n remote: config.remote,\n vfsCacheMode: config.vfsCacheMode,\n });\n\n const args = _buildRcloneArgs(config, { configPath, rcAddr });\n\n const proc = spawn(\"rclone\", args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\n // Per-process tracker for the upload-stuck observability gate. When an\n // object's upload retry count crosses the threshold we log once at error\n // level (the stream otherwise stays at INFO and the failure is silent).\n const routeCtx: RcloneLogRouteContext = {\n stuckThreshold: config.uploadStuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD,\n alertedObjects: new Set<string>(),\n onUploadStuck: (object, tries) => {\n rcloneLog.error(\n \"rclone upload repeatedly failing — file may be stranded in this session's cache\",\n undefined,\n { object, tries, event: \"sync_status\", phase: \"error\" },\n );\n config.onUploadStuck?.(object, tries);\n },\n onAuthError: config.onAuthError,\n };\n\n const recentStderr: string[] = [];\n const stderrTail = (line: string) => {\n recentStderr.push(line);\n if (recentStderr.length > 20) recentStderr.shift();\n };\n\n const stdoutHandler = (line: string) => {\n _routeRcloneLogLine(line, rcloneLog, routeCtx);\n };\n const stderrHandler = (line: string) => {\n stderrTail(line);\n _routeRcloneLogLine(line, rcloneLog, routeCtx);\n };\n\n if (proc.stdout) attachLineSplitter(proc.stdout, stdoutHandler);\n if (proc.stderr) attachLineSplitter(proc.stderr, stderrHandler);\n\n let earlyExitCode: number | null = null;\n let earlyExitSignal: NodeJS.Signals | null = null;\n const earlyExit = new Promise<void>((resolve) => {\n proc.once(\"exit\", (code, signal) => {\n earlyExitCode = code;\n earlyExitSignal = signal;\n resolve();\n });\n });\n\n const mountReady = waitFor(\n async () => {\n if (earlyExitCode !== null || earlyExitSignal !== null) return false;\n return await isMountpoint(config.mountPoint);\n },\n { timeoutMs: 15_000, intervalMs: 100 },\n );\n\n const ready = await Promise.race([mountReady, earlyExit.then(() => false)]);\n\n if (!ready) {\n try {\n if (proc.exitCode === null && proc.signalCode === null) {\n proc.kill(\"SIGKILL\");\n }\n } catch {\n // ignore\n }\n await unlink(configPath).catch(() => {});\n RCLONE_RC_PORTS.release(port);\n const tail =\n recentStderr.length > 0 ? `\\nstderr tail:\\n${recentStderr.slice(-5).join(\"\\n\")}` : \"\";\n throw new Error(`rclone failed to mount ${config.remote} at ${config.mountPoint}${tail}`);\n }\n\n const pid = proc.pid;\n if (pid === undefined) {\n // Should never happen if mountReady resolved true, but defend anyway.\n proc.kill(\"SIGKILL\");\n await unlink(configPath).catch(() => {});\n RCLONE_RC_PORTS.release(port);\n throw new Error(\"rclone process has no pid after successful mount\");\n }\n\n const entry: InternalEntry = {\n proc,\n configPath,\n port,\n mountPoint: config.mountPoint,\n cacheDir: config.cacheDir,\n spawnConfig: config,\n log: config.log,\n rcloneLog,\n recentStderr,\n };\n HANDLES.set(pid, entry);\n\n proc.on(\"exit\", (code) => {\n // If the entry is still in the registry, this was unplanned.\n if (HANDLES.has(pid)) {\n config.log.warn(\"rclone exited unexpectedly\", { code, pid });\n }\n });\n\n config.log.info(\"rclone mountpoint confirmed\", { pid });\n\n return { pid, mountPoint: config.mountPoint, cacheDir: config.cacheDir, rcAddr };\n }\n\n /**\n * Stop an rclone subprocess. Attempts a flush first, then SIGTERM, then\n * SIGKILL + fusermount3 if `graceMs` elapses without the mountpoint\n * disappearing.\n *\n * `graceMs` bounds both the flush stabilization gate and the SIGTERM→SIGKILL\n * window — it is *not* a single total wall-clock cap: the flush also waits on\n * rclone's `/vfs/stats` drain (its own 60s ceiling) between the two.\n */\n async stop(handle: RcloneHandle, opts?: { graceMs?: number }): Promise<void> {\n const graceMs = opts?.graceMs ?? 30_000;\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n return;\n }\n\n try {\n // Bound the stabilization gate by graceMs so stop() doesn't silently add\n // the full default stabilize timeout on top of the caller's budget.\n await this.flush(handle, { stabilizeTimeoutMs: graceMs });\n } catch (err) {\n entry.log.warn(\"rclone flush before stop failed\", {\n pid: handle.pid,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n entry.log.info(\"rclone stop initiated\", { pid: handle.pid });\n\n // Remove FIRST so the exit handler doesn't fire the unplanned-exit warning.\n HANDLES.delete(handle.pid);\n\n try {\n entry.proc.kill(\"SIGTERM\");\n } catch {\n // ignore — process may already be gone\n }\n\n const unmounted = await waitFor(async () => !(await isMountpoint(entry.mountPoint)), {\n timeoutMs: graceMs,\n intervalMs: 200,\n });\n\n if (!unmounted) {\n try {\n entry.proc.kill(\"SIGKILL\");\n } catch {\n // ignore\n }\n await new Promise<void>((resolve) => {\n const fuse = spawn(\"fusermount3\", [\"-u\", entry.mountPoint], { stdio: \"ignore\" });\n fuse.once(\"exit\", () => resolve());\n fuse.once(\"error\", () => resolve());\n });\n entry.log.warn(\"rclone hard-killed\", { pid: handle.pid });\n }\n\n RCLONE_RC_PORTS.release(entry.port);\n await unlink(entry.configPath).catch(() => {});\n }\n\n /**\n * Apply a freshly-rendered rclone INI to a running mount by recycling the\n * process: flush + stop the current rclone, then re-spawn at the same\n * mountpoint/cacheDir with the new config. Returns the new handle.\n *\n * rclone holds the OAuth token in memory (baked into the config at spawn);\n * there is no rc command to swap it on a live `onedrive` backend, so a\n * recycle is the reliable way to apply a refreshed token. The vfs cache dir\n * is reused, so the remount revalidates rather than re-downloads. During the\n * brief unmount window the read-only mount-placeholder barrier underneath is\n * exposed (writes fail with EROFS, not EIO) — see ConnectorManager's\n * read-only-until-ready guarantee.\n */\n async reconfigure(handle: RcloneHandle, rcloneConfig: string): Promise<RcloneHandle> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n throw new Error(`rclone handle not found (pid=${handle.pid})`);\n }\n const nextConfig: RcloneSpawnConfig = { ...entry.spawnConfig, rcloneConfig };\n entry.log.info(\"rclone reconfigure — recycling process to apply refreshed credential\", {\n pid: handle.pid,\n });\n await this.stop(handle, { graceMs: 30_000 });\n return this.spawn(nextConfig);\n }\n\n /**\n * Force rclone to upload pending writes, then wait until the in-use\n * counter reaches zero.\n *\n * Before issuing the refresh it waits for the vfs cache dir to go quiescent\n * (no write for `stabilityThresholdMs`, bounded by `stabilizeTimeoutMs`) so a\n * close/hibernate-triggered flush doesn't snapshot a half-written file and\n * trigger rclone's mid-write \"sizes differ\" abort. Pass `stabilize: false`\n * to skip the gate.\n */\n async flush(\n handle: RcloneHandle,\n opts?: { stabilize?: boolean; stabilityThresholdMs?: number; stabilizeTimeoutMs?: number },\n ): Promise<void> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n throw new Error(`rclone handle not found (pid=${handle.pid})`);\n }\n\n if (opts?.stabilize !== false) {\n const thresholdMs = opts?.stabilityThresholdMs ?? STABILIZE_THRESHOLD_MS;\n const timeoutMs = opts?.stabilizeTimeoutMs ?? STABILIZE_TIMEOUT_MS;\n // Scan only the vfs content subtree (agent writes land here). The sibling\n // `vfsMeta/` tree is rclone housekeeping whose churn would never settle.\n const scanDir = await vfsContentDir(entry.cacheDir);\n const quiescent = await awaitQuiescent(scanDir, {\n thresholdMs,\n timeoutMs,\n pollMs: STABILIZE_POLL_MS,\n });\n if (!quiescent) {\n entry.log.warn(\"rclone cache did not stabilize before flush — proceeding anyway\", {\n pid: handle.pid,\n thresholdMs,\n timeoutMs,\n });\n }\n }\n\n const refreshRes = await fetch(`http://${handle.rcAddr}/vfs/refresh?recursive=true`, {\n method: \"POST\",\n });\n if (!refreshRes.ok) {\n const body = await refreshRes.text().catch(() => \"\");\n throw new Error(`rclone /vfs/refresh failed: ${refreshRes.status} ${body}`);\n }\n\n const ok = await waitFor(\n async () => {\n const r = await fetch(`http://${handle.rcAddr}/vfs/stats`, { method: \"GET\" });\n if (!r.ok) return false;\n const body = (await r.json()) as { inUse?: number; [k: string]: unknown };\n return body.inUse === 0;\n },\n { timeoutMs: 60_000, intervalMs: 500 },\n );\n if (!ok) {\n throw new Error(`rclone flush did not drain within 60s (pid=${handle.pid})`);\n }\n }\n\n /** Liveness + cache-dir size. */\n async status(handle: RcloneHandle): Promise<{ alive: boolean; cacheBytes: number }> {\n const entry = HANDLES.get(handle.pid);\n if (!entry) {\n return { alive: false, cacheBytes: 0 };\n }\n const alive = entry.proc.exitCode === null && entry.proc.signalCode === null;\n const cacheBytes = await dirSize(entry.cacheDir);\n return { alive, cacheBytes };\n }\n}\n\ninterface RcloneJsonLine {\n level?: string;\n msg?: string;\n source?: string;\n time?: string;\n object?: string;\n error?: unknown;\n}\n\n/**\n * Per-process state threaded through {@link _routeRcloneLogLine} so it can\n * detect a sustained upload failure (the same object failing to upload K times\n * in a row) and surface it exactly once, instead of letting rclone retry\n * silently at INFO level forever.\n */\nexport interface RcloneLogRouteContext {\n /** Consecutive retries for one object before {@link onUploadStuck} fires. */\n stuckThreshold?: number;\n /** Objects already alerted on, to fire once and not on every later retry. */\n alertedObjects?: Set<string>;\n /** Called the first time an object crosses {@link stuckThreshold}. */\n onUploadStuck?: (object: string, tries: number) => void;\n /** Called when a line matches an OAuth auth-failure pattern. */\n onAuthError?: () => void;\n}\n\n/** rclone's vfs write-back failure line: \"... failed to upload try #3, will retry ...\". */\nconst UPLOAD_FAIL_RE = /failed to upload.*?try #(\\d+)/i;\n/** rclone's vfs write-back success line, used to reset the per-object alert. */\nconst UPLOAD_OK_RE = /upload succeeded/i;\n/**\n * OAuth token-level failures rclone emits when the access token is expired and\n * it cannot self-refresh (the Skaile-managed-Entra `client_secret`-stripped\n * case). `invalid_client` / `couldn't fetch token` is the confirmed prod\n * symptom; the rest cover the equivalent MSAL/refresh-grant token failures.\n * Bare HTTP `401` is intentionally excluded — rclone retries many transient\n * 401s internally without needing a token refresh; only these token-level\n * failures mean rclone is stuck.\n */\nconst AUTH_FAIL_RE =\n /invalid_client|couldn'?t fetch token|invalid_grant|InvalidAuthenticationToken/i;\n/**\n * Non-retryable upload failure: the remote target (or its parent folder) no\n * longer exists, so the write-back upload can never land — retrying just spins\n * forever and poisons the vfs cache. `itemNotFound` is the OneDrive/SharePoint\n * Graph error code for this; surface it immediately rather than after the retry\n * threshold so the stranded file is visible the first time it fails.\n */\nconst ITEM_NOT_FOUND_RE = /itemNotFound/i;\n\n/**\n * @internal\n * Route a single rclone log line (JSON or raw) to the appropriate Logger\n * call. Exported for tests; not part of the public API. When `ctx` is\n * supplied, also tracks consecutive upload failures per object and invokes\n * `ctx.onUploadStuck` once the retry count for an object reaches the threshold.\n */\nexport function _routeRcloneLogLine(line: string, log: Logger, ctx?: RcloneLogRouteContext): void {\n const trimmed = line.trim();\n if (trimmed.length === 0) return;\n\n let parsed: RcloneJsonLine | null = null;\n try {\n const candidate = JSON.parse(trimmed);\n if (candidate && typeof candidate === \"object\") parsed = candidate as RcloneJsonLine;\n } catch {\n parsed = null;\n }\n\n if (!parsed) {\n if (ctx) {\n _trackUploadFailure(trimmed, undefined, ctx);\n if (AUTH_FAIL_RE.test(trimmed)) ctx.onAuthError?.();\n if (ITEM_NOT_FOUND_RE.test(trimmed)) _trackNonRetryableUpload(undefined, trimmed, ctx);\n }\n log.info(trimmed);\n return;\n }\n\n const level = (parsed.level ?? \"INFO\").toUpperCase();\n const msg = parsed.msg ?? \"\";\n const data: Record<string, unknown> = {};\n if (parsed.object !== undefined) data.object = parsed.object;\n if (parsed.source !== undefined) data.source = parsed.source;\n\n if (ctx) {\n _trackUploadFailure(msg, parsed.object, ctx);\n const errText = typeof parsed.error === \"string\" ? parsed.error : \"\";\n if (AUTH_FAIL_RE.test(msg) || (errText && AUTH_FAIL_RE.test(errText))) ctx.onAuthError?.();\n if (ITEM_NOT_FOUND_RE.test(msg) || (errText && ITEM_NOT_FOUND_RE.test(errText))) {\n _trackNonRetryableUpload(parsed.object, msg, ctx);\n }\n }\n\n switch (level) {\n case \"DEBUG\":\n log.debug(msg, data);\n break;\n case \"INFO\":\n case \"NOTICE\":\n log.info(msg, data);\n break;\n case \"WARNING\":\n log.warn(msg, data);\n break;\n case \"ERROR\":\n case \"CRITICAL\":\n case \"EMERGENCY\":\n case \"ALERT\":\n log.error(msg, parsed.error, data);\n break;\n default:\n log.info(msg, data);\n break;\n }\n}\n\n/**\n * @internal\n * Inspect one rclone message for an upload retry / success and update the\n * per-object alert state in `ctx`. Fires `onUploadStuck` once when an object's\n * retry count first reaches the threshold; a later success clears the alert so\n * a fresh failure run can re-trigger.\n */\nfunction _trackUploadFailure(\n msg: string,\n object: string | undefined,\n ctx: RcloneLogRouteContext,\n): void {\n const failMatch = UPLOAD_FAIL_RE.exec(msg);\n if (failMatch) {\n const tries = Number(failMatch[1]);\n const key = object ?? extractObjectFromMsg(msg) ?? \"(unknown)\";\n const threshold = ctx.stuckThreshold ?? DEFAULT_UPLOAD_STUCK_THRESHOLD;\n if (!ctx.alertedObjects) ctx.alertedObjects = new Set<string>();\n const alerted = ctx.alertedObjects;\n if (tries >= threshold && !alerted.has(key)) {\n alerted.add(key);\n ctx.onUploadStuck?.(key, tries);\n }\n return;\n }\n if (UPLOAD_OK_RE.test(msg)) {\n const key = object ?? extractObjectFromMsg(msg);\n if (key) ctx.alertedObjects?.delete(key);\n }\n}\n\n/**\n * @internal\n * Surface a non-retryable upload failure (itemNotFound — remote target gone)\n * exactly once per object via the same `onUploadStuck` signal the retry-threshold\n * path uses. Fired on the FIRST occurrence (no threshold) because retrying a\n * vanished remote can never succeed; the object is shared with the retry tracker\n * so the two paths can't double-fire for the same object.\n */\nfunction _trackNonRetryableUpload(\n object: string | undefined,\n msg: string,\n ctx: RcloneLogRouteContext,\n): void {\n const key = object ?? extractObjectFromMsg(msg) ?? \"(unknown)\";\n if (!ctx.alertedObjects) ctx.alertedObjects = new Set<string>();\n if (ctx.alertedObjects.has(key)) return;\n ctx.alertedObjects.add(key);\n // tries=1: a non-retryable failure is surfaced on its FIRST occurrence, not\n // after the retry threshold — reporting the threshold here would mislead.\n ctx.onUploadStuck?.(key, 1);\n}\n\n/** Best-effort path extraction from a free-text rclone message. */\nfunction extractObjectFromMsg(msg: string): string | undefined {\n const m = /(?:^|\\s)([^\\s:]+\\/[^\\s:]+):/.exec(msg);\n return m?.[1];\n}\n\n/**\n * @internal\n * Build the `rclone mount` argv from a spawn config. Extracted from spawn() so\n * the flag wiring (notably `--vfs-write-back` and the conditional\n * `--ignore-size --ignore-checksum`) is unit-testable without actually\n * launching rclone. Exported for tests; not part of the public API.\n */\nexport function _buildRcloneArgs(\n config: RcloneSpawnConfig,\n io: { configPath: string; rcAddr: string },\n): string[] {\n const args = [\n \"mount\",\n config.remote,\n config.mountPoint,\n \"--config\",\n io.configPath,\n \"--cache-dir\",\n config.cacheDir,\n \"--vfs-cache-mode\",\n config.vfsCacheMode,\n \"--vfs-cache-max-size\",\n config.cacheMaxSize ?? \"5G\",\n \"--vfs-cache-max-age\",\n config.cacheMaxAge ?? \"168h\",\n \"--vfs-write-back\",\n config.vfsWriteBack ?? DEFAULT_VFS_WRITE_BACK,\n \"--vfs-cache-poll-interval\",\n \"60s\",\n \"--rc\",\n \"--rc-addr\",\n io.rcAddr,\n // loopback-only rc server — without no-auth, flush's POST /vfs/refresh 403s,\n // graceful stop fails, and the write-back cache is left dirty. Safe: nothing\n // external can reach 127.0.0.1:<port>.\n \"--rc-no-auth\",\n \"--log-level\",\n \"INFO\",\n \"--use-json-log\",\n \"--allow-other\",\n // The ro-tmpfs deferred-mount barrier is already mounted here; without this\n // rclone aborts with \"directory already mounted\". See mount-placeholder.ts.\n \"--allow-non-empty\",\n ];\n\n // Remotes that rewrite bytes on upload (SharePoint LF→CRLF) make the\n // post-transfer size/hash check fail and rclone rolls the upload back\n // forever. Both flags are needed: a byte change shifts size AND checksum.\n if (config.ignoreSizeCheck) {\n args.push(\"--ignore-size\", \"--ignore-checksum\");\n }\n\n return args;\n}\n\n/**\n * Poll `dir` until its newest file mtime is at least `thresholdMs` in the past\n * (no write for that long), or `timeoutMs` elapses. Returns true if it went\n * quiescent, false on timeout. An empty/missing dir counts as quiescent.\n */\nexport async function awaitQuiescent(\n dir: string,\n opts: { thresholdMs: number; timeoutMs: number; pollMs: number },\n): Promise<boolean> {\n const deadline = Date.now() + opts.timeoutMs;\n for (;;) {\n const newest = await newestMtimeMs(dir);\n if (newest === null || Date.now() - newest >= opts.thresholdMs) return true;\n if (Date.now() >= deadline) return false;\n await sleep(opts.pollMs);\n }\n}\n\n/**\n * Resolve the rclone vfs content subtree (`<cacheDir>/vfs`) where cached file\n * data — and therefore agent writes — land, falling back to `cacheDir` itself\n * if that subtree doesn't exist yet. Keeps the stabilization gate off rclone's\n * `vfsMeta/` housekeeping tree.\n */\nasync function vfsContentDir(cacheDir: string): Promise<string> {\n const vfs = path.join(cacheDir, \"vfs\");\n try {\n return (await stat(vfs)).isDirectory() ? vfs : cacheDir;\n } catch {\n return cacheDir;\n }\n}\n\n/**\n * Recursively find the most recent file mtime (ms) under `dir`. Returns null if\n * the dir is missing or contains no files. Symlinks are skipped — rclone's\n * cache holds only regular files and dirs.\n */\nasync function newestMtimeMs(dir: string): Promise<number | null> {\n let newest: number | null = null;\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const full = path.join(dir, String(e.name));\n if (e.isDirectory()) {\n const sub = await newestMtimeMs(full);\n if (sub !== null && (newest === null || sub > newest)) newest = sub;\n } else if (e.isFile()) {\n try {\n const s = await stat(full);\n if (newest === null || s.mtimeMs > newest) newest = s.mtimeMs;\n } catch {\n // ignore — file vanished between readdir and stat\n }\n }\n }\n } catch {\n return null;\n }\n return newest;\n}\n\n/**\n * @internal\n * Returns true if a FUSE mount is present at `mountPoint` in the given\n * /proc/self/mounts text. The fstype check (field 3, `fuse.*`) is essential:\n * the deferred-mount barrier leaves a `tmpfs` mounted at the same path, so a\n * path-only match would report the *barrier* as the confirmed mount and mask a\n * dead rclone process. Exported for tests; not part of the public API.\n */\nexport function _fuseMountPresent(procMountsText: string, mountPoint: string): boolean {\n const resolved = path.resolve(mountPoint);\n for (const raw of procMountsText.split(\"\\n\")) {\n if (raw.length === 0) continue;\n const fields = raw.split(/\\s+/);\n const mp = fields[1];\n const fstype = fields[2];\n if (!mp || !fstype) continue;\n // /proc/self/mounts encodes spaces as \\040; cheap decode.\n const decoded = mp.replace(/\\\\040/g, \" \");\n // User-space FUSE only (`fuse` or `fuse.<subtype>`); excludes the `fusectl`\n // kernel control fs. rclone mounts as `fuse.rclone`.\n if (decoded === resolved && (fstype === \"fuse\" || fstype.startsWith(\"fuse.\"))) return true;\n }\n return false;\n}\n\n/** Returns true if a FUSE mount (rclone) is live at `mountPoint`. */\nasync function isMountpoint(mountPoint: string): Promise<boolean> {\n try {\n const text = await readFile(\"/proc/self/mounts\", \"utf8\");\n return _fuseMountPresent(text, mountPoint);\n } catch {\n return false;\n }\n}\n\n/**\n * Poll `check` every `intervalMs` until it returns true or `timeoutMs`\n * elapses. Returns true on success, false on timeout.\n */\nasync function waitFor(\n check: () => Promise<boolean>,\n opts: { timeoutMs: number; intervalMs: number },\n): Promise<boolean> {\n const deadline = Date.now() + opts.timeoutMs;\n while (Date.now() < deadline) {\n if (await check()) return true;\n await sleep(opts.intervalMs);\n }\n return await check();\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n\n/** Wire a Readable to a per-line callback, buffering partial chunks. */\nfunction attachLineSplitter(stream: Readable, onLine: (line: string) => void): void {\n let buffer = \"\";\n stream.setEncoding(\"utf8\");\n stream.on(\"data\", (chunk: string) => {\n buffer += chunk;\n let idx = buffer.indexOf(\"\\n\");\n while (idx >= 0) {\n const line = buffer.slice(0, idx);\n buffer = buffer.slice(idx + 1);\n if (line.length > 0) onLine(line);\n idx = buffer.indexOf(\"\\n\");\n }\n });\n stream.on(\"end\", () => {\n if (buffer.length > 0) {\n onLine(buffer);\n buffer = \"\";\n }\n });\n}\n\n/** Recursively sum file sizes under `dir`. Returns 0 if dir does not exist. */\nasync function dirSize(dir: string): Promise<number> {\n let total = 0;\n try {\n const entries = await readdir(dir, { withFileTypes: true });\n for (const e of entries) {\n const full = path.join(dir, String(e.name));\n if (e.isDirectory()) {\n total += await dirSize(full);\n } else if (e.isFile()) {\n try {\n const s = await stat(full);\n total += s.size;\n } catch {\n // ignore\n }\n }\n }\n } catch {\n return 0;\n }\n return total;\n}\n"]}
|
|
@@ -83,5 +83,5 @@ var ProviderUnavailableError = class extends SecretsError {
|
|
|
83
83
|
var VERSION = "0.0.0";
|
|
84
84
|
|
|
85
85
|
export { AssetKindConflictError, AssetKindPathAmbiguityError, AssetKindPatternConflictError, AssetKindRegistryFrozenError, ProviderUnavailableError, SecretAccessDeniedError, SecretExpiredError, SecretNotFoundError, SecretsError, VERSION };
|
|
86
|
-
//# sourceMappingURL=chunk-
|
|
87
|
-
//# sourceMappingURL=chunk-
|
|
86
|
+
//# sourceMappingURL=chunk-JXT46QFC.js.map
|
|
87
|
+
//# sourceMappingURL=chunk-JXT46QFC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../plugins/src/asset-kind-registry.ts","../plugins/src/secrets-provider.ts","../plugins/src/index.ts"],"names":[],"mappings":";AA8BO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EACvC,IAAA;AAAA,EAET,YAAY,IAAA,EAAc;AACxB,IAAA,KAAA,CAAM,CAAA,YAAA,EAAe,IAAI,CAAA,kEAAA,CAAoE,CAAA;AAC7F,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAMO,IAAM,6BAAA,GAAN,cAA4C,KAAA,CAAM;AAAA,EAC9C,OAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,YAAA,EAAsB,kBAAA,EAA4B;AAC7E,IAAA,KAAA;AAAA,MACE,CAAA,mBAAA,EAAsB,kBAAkB,CAAA,aAAA,EAAgB,OAAO,0BAA0B,YAAY,CAAA,8CAAA;AAAA,KACvG;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,+BAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,YAAA,GAAe,YAAA;AACpB,IAAA,IAAA,CAAK,kBAAA,GAAqB,kBAAA;AAAA,EA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A,GAAN,cAAiC,YAAA,CAAa;AAAA,EACnD,YAAY,GAAA,EAAa;AACvB,IAAA,KAAA,CAAM,CAAA,gBAAA,EAAmB,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA;AAChD,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,YAAA,CAAa;AAAA,EACzD,WAAA,CAAY,YAAoB,KAAA,EAAgB;AAC9C,IAAA,KAAA;AAAA,MACE,yBAAyB,UAAU,CAAA,EAAG,QAAQ,CAAA,EAAA,EAAK,KAAK,MAAM,EAAE,CAAA,CAAA;AAAA,MAChE;AAAA,KACF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,0BAAA;AAAA,EACd;AACF;;;AChJO,IAAM,OAAA,GAAU","file":"chunk-ZDKJHQY2.js","sourcesContent":["/**\n * IAssetKindRegistry — contract for the frozen-state asset kind registry.\n *\n * Library-bound, not process-global. Follows a frozen-state machine:\n * - register() is valid only in the \"open\" state\n * - First read operation auto-freezes the registry\n * - freeze() is idempotent\n *\n * Conflicts on registration are hard errors (A4):\n * - Same kind registered twice → AssetKindConflictError\n * - Overlapping glob patterns → AssetKindPatternConflictError\n * - Multiple providers match a path → AssetKindPathAmbiguityError\n *\n * Design decisions A3, A4: locked in Phase 1.7 planning.\n */\n\nimport type { ManifestValidationResult } from \"@skaile/workspaces/types/manifests\";\nimport type {\n AssetKindFileFilter,\n AssetKindRequiresEdge,\n IAssetKindProvider,\n} from \"./asset-kind-provider.js\";\n\n// ---------------------------------------------------------------------------\n// Error classes (A4)\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a kind is registered that already exists in the registry.\n */\nexport class AssetKindConflictError extends Error {\n readonly kind: string;\n\n constructor(kind: string) {\n super(`Asset kind \"${kind}\" is already registered. Each kind must have exactly one provider.`);\n this.name = \"AssetKindConflictError\";\n this.kind = kind;\n }\n}\n\n/**\n * Thrown when a provider's discovery patterns overlap with an\n * already-registered provider's patterns.\n */\nexport class AssetKindPatternConflictError extends Error {\n readonly newKind: string;\n readonly existingKind: string;\n readonly conflictingPattern: string;\n\n constructor(newKind: string, existingKind: string, conflictingPattern: string) {\n super(\n `Discovery pattern \"${conflictingPattern}\" from kind \"${newKind}\" conflicts with kind \"${existingKind}\". Patterns must not overlap across providers.`,\n );\n this.name = \"AssetKindPatternConflictError\";\n this.newKind = newKind;\n this.existingKind = existingKind;\n this.conflictingPattern = conflictingPattern;\n }\n}\n\n/**\n * Thrown at discovery time when multiple providers claim the same path.\n * This indicates a bug in matchesPath implementations — should be caught\n * earlier by pattern conflict detection, but serves as a runtime safety net.\n */\nexport class AssetKindPathAmbiguityError extends Error {\n readonly path: string;\n readonly matchingKinds: string[];\n\n constructor(path: string, matchingKinds: string[]) {\n super(\n `Path \"${path}\" matches multiple providers: [${matchingKinds.join(\", \")}]. Only one provider may claim a path.`,\n );\n this.name = \"AssetKindPathAmbiguityError\";\n this.path = path;\n this.matchingKinds = matchingKinds;\n }\n}\n\n/**\n * Thrown when register() is called on a frozen registry.\n */\nexport class AssetKindRegistryFrozenError extends Error {\n constructor() {\n super(\n \"Cannot register providers after the registry is frozen. All providers must be registered before the first read operation.\",\n );\n this.name = \"AssetKindRegistryFrozenError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen-state asset kind registry.\n *\n * Lifecycle:\n * 1. Created in \"open\" state\n * 2. Providers registered via register()\n * 3. First read operation (getProvider, getAllProviders, resolveKind,\n * validateManifest, defaultFileFilter, extractRequires) auto-freezes\n * 4. No further registrations allowed\n *\n * Implementations: AssetKindRegistry in @skaile/discovery.\n */\nexport interface IAssetKindRegistry {\n /** Whether the registry is frozen (no further registrations allowed). */\n readonly frozen: boolean;\n\n /**\n * Register a provider. Must be called before the registry is frozen.\n * @throws AssetKindConflictError if kind already registered\n * @throws AssetKindPatternConflictError if patterns overlap\n * @throws AssetKindRegistryFrozenError if registry is frozen\n */\n register(provider: IAssetKindProvider): void;\n\n /**\n * Explicitly freeze the registry. Idempotent — calling on an already-frozen\n * registry is a no-op.\n */\n freeze(): void;\n\n // -- Read operations (auto-freeze on first call) --\n\n /** Get a provider by kind name. Returns undefined for unregistered kinds. */\n getProvider(kind: string): IAssetKindProvider | undefined;\n\n /** Get all registered providers (snapshot, not live). */\n getAllProviders(): IAssetKindProvider[];\n\n /** Get all registered kind names. */\n getAllKinds(): string[];\n\n /**\n * Resolve a relative path to an asset kind.\n * @throws AssetKindPathAmbiguityError if multiple providers match\n * @returns The kind string, or undefined if no provider matches\n */\n resolveKind(relativePath: string): string | undefined;\n\n // -- Convenience delegates (auto-freeze on first call) --\n\n /**\n * Validate a manifest for a given kind.\n * @returns Validation result, or a failure if the kind is unregistered\n */\n validateManifest(kind: string, data: unknown): ManifestValidationResult<unknown>;\n\n /**\n * Compute the default file filter for an asset.\n * @returns The file filter, or undefined if the kind is unregistered\n */\n defaultFileFilter(kind: string, manifestPath: string): AssetKindFileFilter | undefined;\n\n /**\n * Extract requires edges from a manifest.\n * @returns The edges, or an empty array if the kind has no extractRequires\n */\n extractRequires(\n kind: string,\n assetRef: string,\n manifest: Record<string, unknown>,\n ): AssetKindRequiresEdge[];\n}\n","/**\n * ISecretsProvider — pluggable secret storage/retrieval interface.\n *\n * Lives in workspaces/plugins (all pluggable interface contracts centralized here).\n * Built-in implementations live in workspaces/secrets.\n *\n * Signature locked per Phase 1 plan decision E5.\n */\n\n// ---------------------------------------------------------------------------\n// Helper types\n// ---------------------------------------------------------------------------\n\n/**\n * Metadata record returned by {@link ISecretsProvider.getMetadata}.\n *\n * Carries audit timestamps and optional ownership information without\n * exposing the secret value itself.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface SecretMetadata {\n ref: string;\n createdAt: Date;\n updatedAt: Date;\n lastAccessedAt?: Date;\n owner?: string;\n scopeSummary?: string;\n}\n\n/**\n * Feature flags advertised by a secrets provider via\n * {@link ISecretsProvider.getCapabilities}.\n *\n * Consumers use this to determine whether rotation, TTL, or batch operations\n * are available before calling the corresponding methods.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface ProviderCapabilities {\n supportsRotation: boolean;\n supportsExpiry: boolean;\n supportsBatch: boolean;\n scopeModel: \"flat\" | \"hierarchical\";\n}\n\n/**\n * Options accepted by {@link ISecretsProvider.setSecret}.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface SetSecretOptions {\n ttlSeconds?: number;\n metadata?: Record<string, string>;\n}\n\n/**\n * Filter parameters accepted by {@link ISecretsProvider.listSecrets}.\n *\n * All fields are optional — an empty filter returns all accessible secrets.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface ListFilter {\n prefix?: string;\n owner?: string;\n limit?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Error hierarchy\n// ---------------------------------------------------------------------------\n\n/**\n * Base error class for all secrets-layer failures.\n *\n * Carries a machine-readable `code` string alongside the human-readable\n * message so callers can switch on error type without instanceof chains.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretsError extends Error {\n code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = \"SecretsError\";\n this.code = code;\n }\n}\n\n/**\n * Thrown by {@link ISecretsProvider.getSecret} when the requested `ref` does\n * not exist in the provider's backing store.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretNotFoundError extends SecretsError {\n constructor(ref: string) {\n super(`Secret not found: ${ref}`, \"SECRET_NOT_FOUND\");\n this.name = \"SecretNotFoundError\";\n }\n}\n\n/**\n * Thrown when the caller does not have permission to access a secret.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretAccessDeniedError extends SecretsError {\n constructor(message = \"Access denied\") {\n super(message, \"SECRET_ACCESS_DENIED\");\n this.name = \"SecretAccessDeniedError\";\n }\n}\n\n/**\n * Thrown by {@link ISecretsProvider.getSecret} when the secret exists but its\n * TTL has elapsed.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretExpiredError extends SecretsError {\n constructor(ref: string) {\n super(`Secret expired: ${ref}`, \"SECRET_EXPIRED\");\n this.name = \"SecretExpiredError\";\n }\n}\n\n/**\n * Thrown when the backing secrets provider cannot be reached.\n *\n * Carries an optional `cause` string with provider-specific diagnostics.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class ProviderUnavailableError extends SecretsError {\n constructor(providerId: string, cause?: string) {\n super(\n `Provider unavailable: ${providerId}${cause ? ` (${cause})` : \"\"}`,\n \"PROVIDER_UNAVAILABLE\",\n );\n this.name = \"ProviderUnavailableError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/**\n * Pluggable interface for secret storage and retrieval.\n *\n * Built-in implementations (Phase 1): `LocalSecretsProvider`, `EnvSecretsProvider`\n * (in `workspaces/secrets`). Future implementations include Vault, AWS SM,\n * GCP SM, Azure Key Vault, Infisical, Doppler, and Bitwarden Secrets.\n *\n * Registration is explicit and programmatic: `pluginRegistry.register(impl)`.\n * Third-party providers are loaded via dynamic import driven by config.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface ISecretsProvider {\n /** Unique provider identifier used for registration and diagnostics. */\n readonly id: string;\n /** Retrieve a secret by ref, returning the raw bytes. */\n getSecret(ref: string): Promise<Uint8Array>;\n /** Store or update a secret. Optional TTL and metadata can be attached. */\n setSecret(ref: string, value: Uint8Array, opts?: SetSecretOptions): Promise<void>;\n /** Permanently remove a secret. */\n deleteSecret(ref: string): Promise<void>;\n /** List secret refs accessible to the caller, with optional filtering. */\n listSecrets(filter?: ListFilter): Promise<string[]>;\n /** Verify the provider is reachable and measure round-trip latency. */\n testConnection(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;\n /** Return audit metadata for a secret without revealing its value. */\n getMetadata(ref: string): Promise<SecretMetadata>;\n /** Advertise which optional capabilities this provider supports. */\n getCapabilities(): ProviderCapabilities;\n}\n","export const VERSION = \"0.0.0\";\n\n// Pluggable interface contracts — Asset Kind Provider\nexport type {\n AssetKindFileFilter,\n AssetKindRequiresEdge,\n IAssetKindProvider,\n} from \"./asset-kind-provider.js\";\nexport type { IAssetKindRegistry } from \"./asset-kind-registry.js\";\n// Pluggable interface contracts — Asset Kind Registry\nexport {\n AssetKindConflictError,\n AssetKindPathAmbiguityError,\n AssetKindPatternConflictError,\n AssetKindRegistryFrozenError,\n} from \"./asset-kind-registry.js\";\n// Pluggable interface contracts — Catalog Source\nexport type {\n CatalogAsset,\n CatalogAssetFilter,\n CatalogSourceInfo,\n ICatalogSource,\n} from \"./catalog-source.js\";\n\nexport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"./secrets-provider.js\";\n// Pluggable interface contracts — Secrets\nexport {\n ProviderUnavailableError,\n SecretAccessDeniedError,\n SecretExpiredError,\n SecretNotFoundError,\n SecretsError,\n} from \"./secrets-provider.js\";\n"]}
|
|
1
|
+
{"version":3,"sources":["../plugins/src/asset-kind-registry.ts","../plugins/src/secrets-provider.ts","../plugins/src/index.ts"],"names":[],"mappings":";AA8BO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EACvC,IAAA;AAAA,EAET,YAAY,IAAA,EAAc;AACxB,IAAA,KAAA,CAAM,CAAA,YAAA,EAAe,IAAI,CAAA,kEAAA,CAAoE,CAAA;AAC7F,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;AAMO,IAAM,6BAAA,GAAN,cAA4C,KAAA,CAAM;AAAA,EAC9C,OAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,YAAA,EAAsB,kBAAA,EAA4B;AAC7E,IAAA,KAAA;AAAA,MACE,CAAA,mBAA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,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAOO,IAAM,uBAAA,GAAN,cAAsC,YAAA,CAAa;AAAA,EACxD,WAAA,CAAY,UAAU,eAAA,EAAiB;AACrC,IAAA,KAAA,CAAM,SAAS,sBAAsB,CAAA;AACrC,IAAA,IAAA,CAAK,IAAA,GAAO,yBAAA;AAAA,EACd;AACF;AAQO,IAAM,kBAAA,GAAN,cAAiC,YAAA,CAAa;AAAA,EACnD,YAAY,GAAA,EAAa;AACvB,IAAA,KAAA,CAAM,CAAA,gBAAA,EAAmB,GAAG,CAAA,CAAA,EAAI,gBAAgB,CAAA;AAChD,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AAAA,EACd;AACF;AASO,IAAM,wBAAA,GAAN,cAAuC,YAAA,CAAa;AAAA,EACzD,WAAA,CAAY,YAAoB,KAAA,EAAgB;AAC9C,IAAA,KAAA;AAAA,MACE,yBAAyB,UAAU,CAAA,EAAG,QAAQ,CAAA,EAAA,EAAK,KAAK,MAAM,EAAE,CAAA,CAAA;AAAA,MAChE;AAAA,KACF;AACA,IAAA,IAAA,CAAK,IAAA,GAAO,0BAAA;AAAA,EACd;AACF;;;AChJO,IAAM,OAAA,GAAU","file":"chunk-JXT46QFC.js","sourcesContent":["/**\n * IAssetKindRegistry — contract for the frozen-state asset kind registry.\n *\n * Library-bound, not process-global. Follows a frozen-state machine:\n * - register() is valid only in the \"open\" state\n * - First read operation auto-freezes the registry\n * - freeze() is idempotent\n *\n * Conflicts on registration are hard errors (A4):\n * - Same kind registered twice → AssetKindConflictError\n * - Overlapping glob patterns → AssetKindPatternConflictError\n * - Multiple providers match a path → AssetKindPathAmbiguityError\n *\n * Design decisions A3, A4: locked in Phase 1.7 planning.\n */\n\nimport type { ManifestValidationResult } from \"@skaile/workspaces/types/manifests\";\nimport type {\n AssetKindFileFilter,\n AssetKindRequiresEdge,\n IAssetKindProvider,\n} from \"./asset-kind-provider.js\";\n\n// ---------------------------------------------------------------------------\n// Error classes (A4)\n// ---------------------------------------------------------------------------\n\n/**\n * Thrown when a kind is registered that already exists in the registry.\n */\nexport class AssetKindConflictError extends Error {\n readonly kind: string;\n\n constructor(kind: string) {\n super(`Asset kind \"${kind}\" is already registered. Each kind must have exactly one provider.`);\n this.name = \"AssetKindConflictError\";\n this.kind = kind;\n }\n}\n\n/**\n * Thrown when a provider's discovery patterns overlap with an\n * already-registered provider's patterns.\n */\nexport class AssetKindPatternConflictError extends Error {\n readonly newKind: string;\n readonly existingKind: string;\n readonly conflictingPattern: string;\n\n constructor(newKind: string, existingKind: string, conflictingPattern: string) {\n super(\n `Discovery pattern \"${conflictingPattern}\" from kind \"${newKind}\" conflicts with kind \"${existingKind}\". Patterns must not overlap across providers.`,\n );\n this.name = \"AssetKindPatternConflictError\";\n this.newKind = newKind;\n this.existingKind = existingKind;\n this.conflictingPattern = conflictingPattern;\n }\n}\n\n/**\n * Thrown at discovery time when multiple providers claim the same path.\n * This indicates a bug in matchesPath implementations — should be caught\n * earlier by pattern conflict detection, but serves as a runtime safety net.\n */\nexport class AssetKindPathAmbiguityError extends Error {\n readonly path: string;\n readonly matchingKinds: string[];\n\n constructor(path: string, matchingKinds: string[]) {\n super(\n `Path \"${path}\" matches multiple providers: [${matchingKinds.join(\", \")}]. Only one provider may claim a path.`,\n );\n this.name = \"AssetKindPathAmbiguityError\";\n this.path = path;\n this.matchingKinds = matchingKinds;\n }\n}\n\n/**\n * Thrown when register() is called on a frozen registry.\n */\nexport class AssetKindRegistryFrozenError extends Error {\n constructor() {\n super(\n \"Cannot register providers after the registry is frozen. All providers must be registered before the first read operation.\",\n );\n this.name = \"AssetKindRegistryFrozenError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/**\n * Frozen-state asset kind registry.\n *\n * Lifecycle:\n * 1. Created in \"open\" state\n * 2. Providers registered via register()\n * 3. First read operation (getProvider, getAllProviders, resolveKind,\n * validateManifest, defaultFileFilter, extractRequires) auto-freezes\n * 4. No further registrations allowed\n *\n * Implementations: AssetKindRegistry in @skaile/discovery.\n */\nexport interface IAssetKindRegistry {\n /** Whether the registry is frozen (no further registrations allowed). */\n readonly frozen: boolean;\n\n /**\n * Register a provider. Must be called before the registry is frozen.\n * @throws AssetKindConflictError if kind already registered\n * @throws AssetKindPatternConflictError if patterns overlap\n * @throws AssetKindRegistryFrozenError if registry is frozen\n */\n register(provider: IAssetKindProvider): void;\n\n /**\n * Explicitly freeze the registry. Idempotent — calling on an already-frozen\n * registry is a no-op.\n */\n freeze(): void;\n\n // -- Read operations (auto-freeze on first call) --\n\n /** Get a provider by kind name. Returns undefined for unregistered kinds. */\n getProvider(kind: string): IAssetKindProvider | undefined;\n\n /** Get all registered providers (snapshot, not live). */\n getAllProviders(): IAssetKindProvider[];\n\n /** Get all registered kind names. */\n getAllKinds(): string[];\n\n /**\n * Resolve a relative path to an asset kind.\n * @throws AssetKindPathAmbiguityError if multiple providers match\n * @returns The kind string, or undefined if no provider matches\n */\n resolveKind(relativePath: string): string | undefined;\n\n // -- Convenience delegates (auto-freeze on first call) --\n\n /**\n * Validate a manifest for a given kind.\n * @returns Validation result, or a failure if the kind is unregistered\n */\n validateManifest(kind: string, data: unknown): ManifestValidationResult<unknown>;\n\n /**\n * Compute the default file filter for an asset.\n * @returns The file filter, or undefined if the kind is unregistered\n */\n defaultFileFilter(kind: string, manifestPath: string): AssetKindFileFilter | undefined;\n\n /**\n * Extract requires edges from a manifest.\n * @returns The edges, or an empty array if the kind has no extractRequires\n */\n extractRequires(\n kind: string,\n assetRef: string,\n manifest: Record<string, unknown>,\n ): AssetKindRequiresEdge[];\n}\n","/**\n * ISecretsProvider — pluggable secret storage/retrieval interface.\n *\n * Lives in workspaces/plugins (all pluggable interface contracts centralized here).\n * Built-in implementations live in workspaces/secrets.\n *\n * Signature locked per Phase 1 plan decision E5.\n */\n\n// ---------------------------------------------------------------------------\n// Helper types\n// ---------------------------------------------------------------------------\n\n/**\n * Metadata record returned by {@link ISecretsProvider.getMetadata}.\n *\n * Carries audit timestamps and optional ownership information without\n * exposing the secret value itself.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface SecretMetadata {\n ref: string;\n createdAt: Date;\n updatedAt: Date;\n lastAccessedAt?: Date;\n owner?: string;\n scopeSummary?: string;\n}\n\n/**\n * Feature flags advertised by a secrets provider via\n * {@link ISecretsProvider.getCapabilities}.\n *\n * Consumers use this to determine whether rotation, TTL, or batch operations\n * are available before calling the corresponding methods.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface ProviderCapabilities {\n supportsRotation: boolean;\n supportsExpiry: boolean;\n supportsBatch: boolean;\n scopeModel: \"flat\" | \"hierarchical\";\n}\n\n/**\n * Options accepted by {@link ISecretsProvider.setSecret}.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface SetSecretOptions {\n ttlSeconds?: number;\n metadata?: Record<string, string>;\n}\n\n/**\n * Filter parameters accepted by {@link ISecretsProvider.listSecrets}.\n *\n * All fields are optional — an empty filter returns all accessible secrets.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface ListFilter {\n prefix?: string;\n owner?: string;\n limit?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Error hierarchy\n// ---------------------------------------------------------------------------\n\n/**\n * Base error class for all secrets-layer failures.\n *\n * Carries a machine-readable `code` string alongside the human-readable\n * message so callers can switch on error type without instanceof chains.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretsError extends Error {\n code: string;\n\n constructor(message: string, code: string) {\n super(message);\n this.name = \"SecretsError\";\n this.code = code;\n }\n}\n\n/**\n * Thrown by {@link ISecretsProvider.getSecret} when the requested `ref` does\n * not exist in the provider's backing store.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretNotFoundError extends SecretsError {\n constructor(ref: string) {\n super(`Secret not found: ${ref}`, \"SECRET_NOT_FOUND\");\n this.name = \"SecretNotFoundError\";\n }\n}\n\n/**\n * Thrown when the caller does not have permission to access a secret.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretAccessDeniedError extends SecretsError {\n constructor(message = \"Access denied\") {\n super(message, \"SECRET_ACCESS_DENIED\");\n this.name = \"SecretAccessDeniedError\";\n }\n}\n\n/**\n * Thrown by {@link ISecretsProvider.getSecret} when the secret exists but its\n * TTL has elapsed.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class SecretExpiredError extends SecretsError {\n constructor(ref: string) {\n super(`Secret expired: ${ref}`, \"SECRET_EXPIRED\");\n this.name = \"SecretExpiredError\";\n }\n}\n\n/**\n * Thrown when the backing secrets provider cannot be reached.\n *\n * Carries an optional `cause` string with provider-specific diagnostics.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport class ProviderUnavailableError extends SecretsError {\n constructor(providerId: string, cause?: string) {\n super(\n `Provider unavailable: ${providerId}${cause ? ` (${cause})` : \"\"}`,\n \"PROVIDER_UNAVAILABLE\",\n );\n this.name = \"ProviderUnavailableError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// Interface\n// ---------------------------------------------------------------------------\n\n/**\n * Pluggable interface for secret storage and retrieval.\n *\n * Built-in implementations (Phase 1): `LocalSecretsProvider`, `EnvSecretsProvider`\n * (in `workspaces/secrets`). Future implementations include Vault, AWS SM,\n * GCP SM, Azure Key Vault, Infisical, Doppler, and Bitwarden Secrets.\n *\n * Registration is explicit and programmatic: `pluginRegistry.register(impl)`.\n * Third-party providers are loaded via dynamic import driven by config.\n *\n * @docLink packages/workspace-plugin/index#plugin-interfaces\n */\nexport interface ISecretsProvider {\n /** Unique provider identifier used for registration and diagnostics. */\n readonly id: string;\n /** Retrieve a secret by ref, returning the raw bytes. */\n getSecret(ref: string): Promise<Uint8Array>;\n /** Store or update a secret. Optional TTL and metadata can be attached. */\n setSecret(ref: string, value: Uint8Array, opts?: SetSecretOptions): Promise<void>;\n /** Permanently remove a secret. */\n deleteSecret(ref: string): Promise<void>;\n /** List secret refs accessible to the caller, with optional filtering. */\n listSecrets(filter?: ListFilter): Promise<string[]>;\n /** Verify the provider is reachable and measure round-trip latency. */\n testConnection(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;\n /** Return audit metadata for a secret without revealing its value. */\n getMetadata(ref: string): Promise<SecretMetadata>;\n /** Advertise which optional capabilities this provider supports. */\n getCapabilities(): ProviderCapabilities;\n}\n","export const VERSION = \"0.0.0\";\n\n// Pluggable interface contracts — Asset Kind Provider\nexport type {\n AssetKindFileFilter,\n AssetKindRequiresEdge,\n IAssetKindProvider,\n} from \"./asset-kind-provider.js\";\nexport type { IAssetKindRegistry } from \"./asset-kind-registry.js\";\n// Pluggable interface contracts — Asset Kind Registry\nexport {\n AssetKindConflictError,\n AssetKindPathAmbiguityError,\n AssetKindPatternConflictError,\n AssetKindRegistryFrozenError,\n} from \"./asset-kind-registry.js\";\n// Pluggable interface contracts — Catalog Source\nexport type {\n CatalogAsset,\n CatalogAssetFilter,\n CatalogDomain,\n CatalogDomainFilter,\n CatalogSourceInfo,\n DomainRelation,\n ICatalogSource,\n} from \"./catalog-source.js\";\n\nexport type {\n ISecretsProvider,\n ListFilter,\n ProviderCapabilities,\n SecretMetadata,\n SetSecretOptions,\n} from \"./secrets-provider.js\";\n// Pluggable interface contracts — Secrets\nexport {\n ProviderUnavailableError,\n SecretAccessDeniedError,\n SecretExpiredError,\n SecretNotFoundError,\n SecretsError,\n} from \"./secrets-provider.js\";\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { readManifestSourceConfig, discoverAssetsInTree } from './chunk-
|
|
1
|
+
import { readManifestSourceConfig, discoverAssetsInTree } from './chunk-XNMABEHH.js';
|
|
2
2
|
import { installFromManifest } from './chunk-KYC6JH75.js';
|
|
3
3
|
import { parseAssetRef } from './chunk-BM7XANVN.js';
|
|
4
4
|
import { PresetManifestSchema } from './chunk-HRKB2ATT.js';
|
|
@@ -2857,6 +2857,32 @@ var RemoteCatalogSource = class {
|
|
|
2857
2857
|
async listSources() {
|
|
2858
2858
|
return [{ id: this.id, type: "remote-catalog", url: this.baseUrl }];
|
|
2859
2859
|
}
|
|
2860
|
+
/**
|
|
2861
|
+
* List navigational domains via `GET /trpc/catalog.listDomains`. Display-only,
|
|
2862
|
+
* so this **never throws**: a missing endpoint (older store → 404), a transport
|
|
2863
|
+
* error, or a malformed payload all degrade to `[]` rather than jeopardize the
|
|
2864
|
+
* asset feed this call accompanies. Air-gapped mode returns `[]` (domains are
|
|
2865
|
+
* not part of the offline cache in v1).
|
|
2866
|
+
*
|
|
2867
|
+
* Not cached — domains are read once per `skaile manage` open and are cheap.
|
|
2868
|
+
*/
|
|
2869
|
+
async listDomains(filter) {
|
|
2870
|
+
if (this.cache.airGapped) return [];
|
|
2871
|
+
try {
|
|
2872
|
+
const input = filter && (filter.publisher || filter.source) ? filter : {};
|
|
2873
|
+
const url = trpcGetUrl(this.baseUrl, "catalog.listDomains", input);
|
|
2874
|
+
const res = await this.httpClient(url, {
|
|
2875
|
+
method: "GET",
|
|
2876
|
+
headers: { Accept: "application/json" }
|
|
2877
|
+
});
|
|
2878
|
+
if (!res.ok) return [];
|
|
2879
|
+
const data = await parseTrpcGet(res);
|
|
2880
|
+
if (!Array.isArray(data)) return [];
|
|
2881
|
+
return data.map(normalizeCatalogDomain).filter((d) => d !== null);
|
|
2882
|
+
} catch {
|
|
2883
|
+
return [];
|
|
2884
|
+
}
|
|
2885
|
+
}
|
|
2860
2886
|
// ── extension API ───────────────────────────────────────────────────────
|
|
2861
2887
|
/**
|
|
2862
2888
|
* Force a metadata-cache refresh. Wipes all resolve/list entries and
|
|
@@ -3116,6 +3142,26 @@ function pickString(r, key) {
|
|
|
3116
3142
|
const v = r[key];
|
|
3117
3143
|
return typeof v === "string" ? v : void 0;
|
|
3118
3144
|
}
|
|
3145
|
+
function normalizeCatalogDomain(raw) {
|
|
3146
|
+
if (!raw || typeof raw !== "object") return null;
|
|
3147
|
+
const r = raw;
|
|
3148
|
+
const slug = pickString(r, "slug");
|
|
3149
|
+
const title = pickString(r, "title");
|
|
3150
|
+
if (!slug || !title) return null;
|
|
3151
|
+
const domain = { slug, title };
|
|
3152
|
+
const description = pickString(r, "description");
|
|
3153
|
+
if (description) domain.description = description;
|
|
3154
|
+
const relation = pickString(r, "relation");
|
|
3155
|
+
if (relation === "additions" || relation === "alternatives" || relation === "sequence") {
|
|
3156
|
+
domain.relation = relation;
|
|
3157
|
+
}
|
|
3158
|
+
if (typeof r.order === "number") domain.order = r.order;
|
|
3159
|
+
const recommendedRef = pickString(r, "recommendedRef");
|
|
3160
|
+
if (recommendedRef) domain.recommendedRef = recommendedRef;
|
|
3161
|
+
const sidecarSource = pickString(r, "sidecarSource");
|
|
3162
|
+
if (sidecarSource) domain.sidecarSource = sidecarSource;
|
|
3163
|
+
return domain;
|
|
3164
|
+
}
|
|
3119
3165
|
var CATALOG_REQUEST_TIMEOUT_MS = 1e4;
|
|
3120
3166
|
var defaultFetch = async (url, init) => {
|
|
3121
3167
|
if (typeof fetch === "undefined") {
|
|
@@ -3623,5 +3669,5 @@ function detectWorkspaceVersion(dir, filename = "skaile.yaml") {
|
|
|
3623
3669
|
}
|
|
3624
3670
|
|
|
3625
3671
|
export { AssignmentNotFoundError, CatalogCache, CatalogConfigSchema, CatalogHttpError, DuplicateAssignmentError, DuplicateLibraryNameError, GitSyncDriver, InstanceHasConsumersError, InstanceNotFoundError, InterpolationError, KNOWN_ASSET_KINDS, KnowledgeManifestSchema, LIBRARY_BACKENDS, LIBRARY_OWNERSHIPS, LIBRARY_STRUCTURES, LOCAL_CATALOG_URL, LibraryConfigSchema, LibraryError, LibraryInstanceRefSchema, LibraryManager, LibrarySectionSchema, LibrarySyncError, LocalCatalogSource, LocalIndex, LocalSyncDriver, LockAssignmentSchema, LockFileSchema, OfflineError, OperationNotPermittedError, PIN_POLICIES, PinPolicySchema, PresetAppliedSchema, PresetExpandedSchema, RemoteCatalogSource, RequiresEdgeSchema, RestCatalogSource, SidecarGit, SkaileConfigSchema, SourceNotFoundError, TarballHashMismatchError, UserLibraryNotFoundError, WorkspaceConfigV2Schema, applyNonStructuralUpgrade, applyPreset, applyPresetFromData, classifyRef, createEmptyLockFile, deriveSlug, detectChanges, detectNestedPresetRefs, detectWorkspaceVersion, evaluateUpgrade, extractLibraryInstanceId, extractReferencedKeys, filterKey, getConfigDefaults, getDefaultValue, getSidecarRoot, getStoreManifestsDir, getStoreRoot, hasInterpolationTokens, interpolate, isLocalCatalogUrl, isSecretPlaceholder, knowledgeKindProvider, listSidecarSlugsOnDisk, loadLockFile, loadWorkspaceV2, migrateSidecarsToStoreIfNeeded, migrateWorkspaceConfig, parsePreset, parsePresetYaml, parseWorkspaceV2, projectConfigPath, queryInstancePickerChoices, resolveAllItems, resolveConfig, resolveIndexPath, resolveItem, resolveLibraryDir, resolvePin, resolveSidecarPaths, saveConfig, saveLockFile, saveWorkspaceV2, sha256Hex, skaileHomeDir, storeSecrets, trpcGetUrl, userConfigPath, validateAllPlaceholders, validateKnowledge, validateNestingDepth, validatePlaceholder, writeManifestIfMissing };
|
|
3626
|
-
//# sourceMappingURL=chunk-
|
|
3627
|
-
//# sourceMappingURL=chunk-
|
|
3672
|
+
//# sourceMappingURL=chunk-O66LT7UI.js.map
|
|
3673
|
+
//# sourceMappingURL=chunk-O66LT7UI.js.map
|