@skaile/workspaces 4.4.0 → 4.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/app-sdk/index.js +1 -1
- package/dist/{asset-feeds-OBOI2POB.js → asset-feeds-UQDXXKYK.js} +4 -4
- package/dist/{asset-feeds-OBOI2POB.js.map → asset-feeds-UQDXXKYK.js.map} +1 -1
- package/dist/asset-manager/index.js +1 -1
- package/dist/bridge/drivers/claude-sdk.js +42 -10
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +2 -2
- package/dist/bridge/drivers/continue.js +2 -2
- package/dist/bridge/drivers/echo.js +3 -3
- package/dist/bridge/drivers/gemini.js +4 -4
- package/dist/bridge/drivers/goose.js +2 -2
- package/dist/bridge/drivers/omp.js +1 -1
- package/dist/bridge/drivers/opencode.js +2 -2
- package/dist/bridge/drivers/qwen.js +4 -4
- package/dist/bridge/index.js +6 -6
- package/dist/bridge/src/cloud.d.ts.map +1 -1
- package/dist/bridge/src/drivers/claude-sdk.d.ts +14 -0
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/normalizer.d.ts.map +1 -1
- package/dist/bridge/src/types.d.ts +10 -0
- package/dist/bridge/src/types.d.ts.map +1 -1
- package/dist/channels/index.js +25 -1
- package/dist/channels/index.js.map +1 -1
- package/dist/channels/src/egress/output-mirror.d.ts +6 -0
- package/dist/channels/src/egress/output-mirror.d.ts.map +1 -1
- package/dist/channels/src/engine.d.ts.map +1 -1
- package/dist/{chunk-3UAE2BVU.js → chunk-3OLCTLTH.js} +9 -2
- package/dist/chunk-3OLCTLTH.js.map +1 -0
- package/dist/{chunk-62ETRVY3.js → chunk-7ZFC3E2C.js} +2 -2
- package/dist/{chunk-62ETRVY3.js.map → chunk-7ZFC3E2C.js.map} +1 -1
- package/dist/{chunk-JUAC5QL4.js → chunk-C2CYBRYJ.js} +2 -2
- package/dist/{chunk-JUAC5QL4.js.map → chunk-C2CYBRYJ.js.map} +1 -1
- package/dist/{chunk-JHBLSPAI.js → chunk-CNYIITSZ.js} +15 -3
- package/dist/chunk-CNYIITSZ.js.map +1 -0
- package/dist/{chunk-3IU5B3YX.js → chunk-F54V4XMH.js} +3 -3
- package/dist/{chunk-3IU5B3YX.js.map → chunk-F54V4XMH.js.map} +1 -1
- package/dist/{chunk-YDPT2X6G.js → chunk-GVOPQBGM.js} +7 -4
- package/dist/chunk-GVOPQBGM.js.map +1 -0
- package/dist/{chunk-FWDTBQCO.js → chunk-GWSVMX53.js} +3 -3
- package/dist/{chunk-FWDTBQCO.js.map → chunk-GWSVMX53.js.map} +1 -1
- package/dist/{chunk-HFS22LN2.js → chunk-JF77XKD7.js} +3 -3
- package/dist/{chunk-HFS22LN2.js.map → chunk-JF77XKD7.js.map} +1 -1
- package/dist/{chunk-A4UG5BWS.js → chunk-KIIH2T7W.js} +6 -6
- package/dist/{chunk-A4UG5BWS.js.map → chunk-KIIH2T7W.js.map} +1 -1
- package/dist/{chunk-O3XVKALH.js → chunk-KY5VVPM2.js} +11 -6
- package/dist/chunk-KY5VVPM2.js.map +1 -0
- package/dist/{chunk-52FI7RXZ.js → chunk-LKAWUFZA.js} +2 -2
- package/dist/{chunk-52FI7RXZ.js.map → chunk-LKAWUFZA.js.map} +1 -1
- package/dist/{chunk-TAZQ232B.js → chunk-NOH5UDO7.js} +3 -3
- package/dist/{chunk-TAZQ232B.js.map → chunk-NOH5UDO7.js.map} +1 -1
- package/dist/{chunk-WLFRA5RM.js → chunk-OUJVFZWJ.js} +8 -3
- package/dist/chunk-OUJVFZWJ.js.map +1 -0
- package/dist/{chunk-53MOGLIA.js → chunk-PJP2TOCB.js} +5 -5
- package/dist/{chunk-53MOGLIA.js.map → chunk-PJP2TOCB.js.map} +1 -1
- package/dist/{chunk-D7PYQMNK.js → chunk-QCXQXLS2.js} +3 -3
- package/dist/{chunk-D7PYQMNK.js.map → chunk-QCXQXLS2.js.map} +1 -1
- package/dist/{chunk-NXH7TTWK.js → chunk-RBQOLTC4.js} +6 -6
- package/dist/{chunk-NXH7TTWK.js.map → chunk-RBQOLTC4.js.map} +1 -1
- package/dist/{chunk-V2P4ECNY.js → chunk-U4AA7MOV.js} +4 -4
- package/dist/{chunk-V2P4ECNY.js.map → chunk-U4AA7MOV.js.map} +1 -1
- package/dist/{chunk-IFXO3KZT.js → chunk-UHKFMUM2.js} +35 -11
- package/dist/chunk-UHKFMUM2.js.map +1 -0
- package/dist/{chunk-BC7BBIDJ.js → chunk-VP2CACF2.js} +3 -3
- package/dist/{chunk-BC7BBIDJ.js.map → chunk-VP2CACF2.js.map} +1 -1
- package/dist/{chunk-FPV4E5DK.js → chunk-WIBL34ZS.js} +3 -3
- package/dist/{chunk-FPV4E5DK.js.map → chunk-WIBL34ZS.js.map} +1 -1
- package/dist/{chunk-VC4TWNOT.js → chunk-XHNK67X7.js} +4 -4
- package/dist/{chunk-VC4TWNOT.js.map → chunk-XHNK67X7.js.map} +1 -1
- package/dist/{chunk-EPQHIC6E.js → chunk-YVQZQGVW.js} +3 -3
- package/dist/{chunk-EPQHIC6E.js.map → chunk-YVQZQGVW.js.map} +1 -1
- package/dist/cli/index.js +38 -35
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/src/commands/connect.d.ts.map +1 -1
- package/dist/cli/src/commands/run.d.ts.map +1 -1
- package/dist/connectors/index.js +7 -7
- package/dist/{ensure-sources-XQ4WQAIB.js → ensure-sources-FDDMDIDJ.js} +4 -4
- package/dist/{ensure-sources-XQ4WQAIB.js.map → ensure-sources-FDDMDIDJ.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +7 -7
- package/dist/factory-assets/connectors/deploy.js +7 -7
- package/dist/factory-assets/connectors/devserver.js +7 -7
- package/dist/factory-assets/connectors/flow/adapter.js +7 -7
- package/dist/factory-assets/connectors/flow/run-flow.js +8 -8
- package/dist/factory-assets/connectors/flow.js +7 -7
- package/dist/factory-assets/connectors/git.js +7 -7
- package/dist/factory-assets/connectors/gmail.js +7 -7
- package/dist/factory-assets/connectors/googledrive.js +7 -7
- package/dist/factory-assets/connectors/local.js +7 -7
- package/dist/factory-assets/connectors/mattermost.js +7 -7
- package/dist/factory-assets/connectors/memory.js +7 -7
- package/dist/factory-assets/connectors/minio.js +7 -7
- package/dist/factory-assets/connectors/postgres.js +7 -7
- package/dist/factory-assets/connectors/s3.js +7 -7
- package/dist/factory-assets/connectors/sharepoint.js +7 -7
- package/dist/factory-assets/connectors/sqlite.js +7 -7
- package/dist/factory-assets/connectors/static-server.js +7 -7
- package/dist/factory-assets/connectors/tunnel.js +7 -7
- package/dist/factory-assets/connectors/webdav.js +7 -7
- package/dist/factory-assets/connectors/xstate-store.js +7 -7
- package/dist/factory-assets/connectors/xstate.js +7 -7
- package/dist/{helpers-AFXYIAYJ.js → helpers-QWMKOP52.js} +4 -4
- package/dist/{helpers-AFXYIAYJ.js.map → helpers-QWMKOP52.js.map} +1 -1
- package/dist/{library-publish-ZDLQ5PHJ.js → library-publish-GW7JXEPE.js} +6 -6
- package/dist/{library-publish-ZDLQ5PHJ.js.map → library-publish-GW7JXEPE.js.map} +1 -1
- package/dist/{open-library-Q44MES2N.js → open-library-QVBKKXX5.js} +5 -5
- package/dist/{open-library-Q44MES2N.js.map → open-library-QVBKKXX5.js.map} +1 -1
- package/dist/{project-2UJVJYPS.js → project-JEEMFZUN.js} +5 -5
- package/dist/{project-2UJVJYPS.js.map → project-JEEMFZUN.js.map} +1 -1
- package/dist/runner/index.js +11 -11
- package/dist/runner/src/agent.d.ts.map +1 -1
- package/dist/runner/src/compaction/orchestrator.d.ts.map +1 -1
- package/dist/runner/src/markdown-stream.d.ts +6 -0
- package/dist/runner/src/markdown-stream.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/bridge.js +6 -6
- package/dist/sdk/index.js +28 -11
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/runner.js +11 -11
- package/dist/sdk/session.js +2 -2
- package/dist/sdk/src/agent-session.d.ts +5 -0
- package/dist/sdk/src/agent-session.d.ts.map +1 -1
- package/dist/sdk/store.js +1 -1
- package/dist/sdk/types.js +1 -1
- package/dist/session/index.js +2 -2
- package/dist/session/src/dispatcher.d.ts.map +1 -1
- package/dist/{setup-LPTQRR6B.js → setup-5UZ4VPI4.js} +11 -11
- package/dist/{setup-LPTQRR6B.js.map → setup-5UZ4VPI4.js.map} +1 -1
- package/dist/{source-KSNC6ZYY.js → source-WZICRPYZ.js} +6 -6
- package/dist/{source-KSNC6ZYY.js.map → source-WZICRPYZ.js.map} +1 -1
- package/dist/{source-manifest-publish-QQYA6ZGP.js → source-manifest-publish-4Y47IQYN.js} +7 -7
- package/dist/{source-manifest-publish-QQYA6ZGP.js.map → source-manifest-publish-4Y47IQYN.js.map} +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/src/store.d.ts.map +1 -1
- package/dist/tui/index.js +19 -11
- package/dist/tui/index.js.map +1 -1
- package/dist/tui/src/repl-session.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/src/events.d.ts +22 -1
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/types/src/index.d.ts +1 -1
- package/dist/types/src/index.d.ts.map +1 -1
- package/dist/types/src/version.d.ts +8 -1
- package/dist/types/src/version.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +2 -2
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-3UAE2BVU.js.map +0 -1
- package/dist/chunk-IFXO3KZT.js.map +0 -1
- package/dist/chunk-JHBLSPAI.js.map +0 -1
- package/dist/chunk-O3XVKALH.js.map +0 -1
- package/dist/chunk-WLFRA5RM.js.map +0 -1
- package/dist/chunk-YDPT2X6G.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;;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,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-FWDTBQCO.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 isValidAssetName,\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, FlowPromptEvent } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport {\n findFlowFileInRoots,\n FLOW_FILE_EXTENSIONS,\n type FlowLookupMiss,\n flowLookupRoots,\n loadFlow,\n} from \"./engine/index.js\";\nimport { flowSkillVersionPins } from \"./engine/node-shape.js\";\nimport { SessionInlineSubFlowRunner } from \"./inline-sub-flow-host.js\";\nimport { SessionNodeExecutor } from \"./node-executor.js\";\nimport { driveOrchestratorTurn } from \"./orchestrator-turn.js\";\nimport { renderStimulusPrompt, type TurnStimulus } from \"./prompt-fragments.js\";\nimport { SessionSubpromptRunner } from \"./subprompt-runner.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\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. First-class\n * gate nodes remain mandatory human decisions in every mode.\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 */\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; first-class gate nodes are never bypassed. */\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. The\n * runner remains idle between turns; first-class gates always park for a human\n * decision, including in autonomous mode. Non-CLI hosts (Skaile platform,\n * Pichi) use the orchestrator directly via the serve command surface and drive\n * 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 bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\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 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 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 const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId }),\n };\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 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 capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });\n // Same endpoints and credentials the session driver used: the registry\n // and the credential env `createAgentSession` already resolved — not a\n // new resolution, not a new secret channel.\n const subpromptRunner = new SessionSubpromptRunner({\n driverType: agentSession.driverType,\n sessionModel: agentSession.model,\n workspaceDir: opts.projectDir,\n registry: agentSession.registry,\n credentialEnv: agentSession.credentialEnv,\n ...(agentSession.modelRef ? { modelRef: agentSession.modelRef } : {}),\n });\n let driverStarted = false;\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 hands the turn to\n // `driveOrchestratorTurn`, which rebuilds the five-section prompt so the\n // agent sees the same flow context the legacy orchestrator produced — and\n // announces it, so a CLI consumer's `onEvent` stream carries the prompt too.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n const ensureDriverStarted = async (): Promise<void> => {\n if (driverStarted) return;\n await driver.start();\n driverStarted = true;\n };\n\n // Same widening the `state_changed` forwarder below performs: `onEvent` is\n // typed against the bridge's driver-level union, which has no case for a\n // runtime-level event.\n const emitFlowPrompt = (event: FlowPromptEvent): void => {\n opts.onEvent?.(event as unknown as AgentEvent);\n };\n\n const inlineSubFlowRunner = new SessionInlineSubFlowRunner({\n resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),\n nodeExecutor,\n subpromptRunner,\n driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow: childFlow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\n },\n });\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. It is\n // discarded in favour of the structured stimulus, which\n // `driveOrchestratorTurn` rebuilds the full prompt from; that keeps the\n // prompt shape stable and the structured form already contains\n // everything the fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n await flowAdapterRef.drainRuntimeNodes(flowHandleRef);\n const execution = flowAdapterRef.getExecution(flowHandleRef);\n if (execution.done || execution.status === \"failed\" || execution.status === \"cancelled\") {\n return;\n }\n if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\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 nodeExecutor,\n subpromptRunner,\n inlineSubFlowRunner,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.json();\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\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 awaiting further stimulus\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not supply human approval/input decisions\",\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 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 = flowSkillVersionPins(flow);\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.skillId;\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 checks = validateFlowVersions(pinnedNodes, 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\n/**\n * Assert `found` sits inside one of `roots`.\n *\n * A backstop, not the primary control: `isValidAssetName` already rejects every\n * id containing a separator, and `findFlowFileInRoots` skips any candidate that\n * escapes its search dir. So on today's code this cannot fire — it is here to\n * fail loudly rather than silently if a future lookup stops enforcing\n * containment itself. Widening the accepted extensions must never widen which\n * paths are reachable, and this is the line that keeps that honest.\n */\nfunction assertContainedInAnyRoot(found: string, roots: string[], flowId: string): void {\n const resolved = path.resolve(found);\n const inside = roots.some((root) => {\n const relative = path.relative(path.resolve(root), resolved);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n });\n if (!inside) {\n throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);\n }\n}\n\n/** One line per near-miss: a file that is right there but was still rejected. */\nfunction describeMisses(misses: FlowLookupMiss[], heading: string): string {\n const seen = new Set<string>();\n const lines: string[] = [];\n for (const miss of misses) {\n if (seen.has(miss.path)) continue;\n seen.add(miss.path);\n lines.push(\n miss.reason === \"id-mismatch\"\n ? ` ${miss.path}: declares id ${JSON.stringify(miss.declaredId ?? \"\")}`\n : ` ${miss.path}: could not be parsed (${miss.error ?? \"unknown error\"})`,\n );\n }\n return lines.length > 0 ? `\\n${heading}\\n${lines.join(\"\\n\")}` : \"\";\n}\n\n/**\n * Resolve one flow identity through the CLI/serve host's normal lookup order —\n * the same roots and filenames `skaile run` and `flow list` use, via\n * {@link flowLookupRoots} / {@link findFlowFileInRoots}. Resolution is by the\n * **declared** `id`, not by filename.\n *\n * @throws {Error} When `flowId` is not a canonical asset name, when no file\n * declares it, or when a match somehow resolves outside every lookup root.\n */\nexport function resolveFlowPath(flowId: string, projectDir: string): string {\n // Sub-flow targets and resumed session records are the two callers, so an\n // identity that is not canonical is a bug in the caller, not a missing file.\n if (!isValidAssetName(flowId)) {\n throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);\n }\n\n const roots = flowLookupRoots(projectDir);\n const misses: FlowLookupMiss[] = [];\n const found = findFlowFileInRoots(flowId, roots, { onMiss: (m) => misses.push(m) });\n if (found) {\n assertContainedInAnyRoot(found, roots, flowId);\n return found;\n }\n\n // A file that is present but unparseable is a different problem from a missing\n // one, and \"not found\" is the wrong headline for it — that exact misdirection\n // is what this change exists to remove, so don't reintroduce it here.\n if (misses.length > 0 && misses.every((m) => m.reason === \"unparseable\")) {\n throw new Error(\n `Flow ${flowId} was found but could not be loaded.` + describeMisses(misses, \"Candidates:\"),\n );\n }\n\n const shown = roots.slice(0, 3).join(\", \");\n const more = roots.length > 3 ? \", …\" : \"\";\n // Spelled from FLOW_FILE_EXTENSIONS so the message cannot drift from the\n // candidate list the lookup actually probes.\n const accepted = FLOW_FILE_EXTENSIONS.map((ext) => `${flowId}${ext}`).join(\" | \");\n throw new Error(\n `Flow not found: ${flowId}. Searched ${roots.length} root(s) (${shown || \"none\"}${more}) ` +\n `for ${accepted} — flat, or inside a ${flowId}/ directory.` +\n describeMisses(misses, \"Near misses:\"),\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;;AAgEA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AAEjD,IAAM,0BAAA,uBAAiC,GAAA,CAAI;AAAA,EACzC,eAAA;AAAA,EACA,WA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Content":["/**\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 isValidAssetName,\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, FlowPromptEvent } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport {\n findFlowFileInRoots,\n FLOW_FILE_EXTENSIONS,\n type FlowLookupMiss,\n flowLookupRoots,\n loadFlow,\n} from \"./engine/index.js\";\nimport { flowSkillVersionPins } from \"./engine/node-shape.js\";\nimport { SessionInlineSubFlowRunner } from \"./inline-sub-flow-host.js\";\nimport { SessionNodeExecutor } from \"./node-executor.js\";\nimport { driveOrchestratorTurn } from \"./orchestrator-turn.js\";\nimport { renderStimulusPrompt, type TurnStimulus } from \"./prompt-fragments.js\";\nimport { SessionSubpromptRunner } from \"./subprompt-runner.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\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. First-class\n * gate nodes remain mandatory human decisions in every mode.\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 */\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; first-class gate nodes are never bypassed. */\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. The\n * runner remains idle between turns; first-class gates always park for a human\n * decision, including in autonomous mode. Non-CLI hosts (Skaile platform,\n * Pichi) use the orchestrator directly via the serve command surface and drive\n * 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 bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\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 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 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 const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId }),\n };\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 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 capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });\n // Same endpoints and credentials the session driver used: the registry\n // and the credential env `createAgentSession` already resolved — not a\n // new resolution, not a new secret channel.\n const subpromptRunner = new SessionSubpromptRunner({\n driverType: agentSession.driverType,\n sessionModel: agentSession.model,\n workspaceDir: opts.projectDir,\n registry: agentSession.registry,\n credentialEnv: agentSession.credentialEnv,\n ...(agentSession.modelRef ? { modelRef: agentSession.modelRef } : {}),\n });\n let driverStarted = false;\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 hands the turn to\n // `driveOrchestratorTurn`, which rebuilds the five-section prompt so the\n // agent sees the same flow context the legacy orchestrator produced — and\n // announces it, so a CLI consumer's `onEvent` stream carries the prompt too.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n const ensureDriverStarted = async (): Promise<void> => {\n if (driverStarted) return;\n await driver.start();\n driverStarted = true;\n };\n\n // Same widening the `state_changed` forwarder below performs: `onEvent` is\n // typed against the bridge's driver-level union, which has no case for a\n // runtime-level event.\n const emitFlowPrompt = (event: FlowPromptEvent): void => {\n opts.onEvent?.(event as unknown as AgentEvent);\n };\n\n const inlineSubFlowRunner = new SessionInlineSubFlowRunner({\n resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),\n nodeExecutor,\n subpromptRunner,\n driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow: childFlow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\n },\n });\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. It is\n // discarded in favour of the structured stimulus, which\n // `driveOrchestratorTurn` rebuilds the full prompt from; that keeps the\n // prompt shape stable and the structured form already contains\n // everything the fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n await flowAdapterRef.drainRuntimeNodes(flowHandleRef);\n const execution = flowAdapterRef.getExecution(flowHandleRef);\n if (execution.done || execution.status === \"failed\" || execution.status === \"cancelled\") {\n return;\n }\n if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;\n await ensureDriverStarted();\n await driveOrchestratorTurn({\n flow,\n execution,\n stimulus,\n emit: emitFlowPrompt,\n deliver: (prompt) => awaitAgentEnd(driver, prompt, opts.onEvent, turnTimeoutMs),\n });\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 nodeExecutor,\n subpromptRunner,\n inlineSubFlowRunner,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.json();\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\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 awaiting further stimulus\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not supply human approval/input decisions\",\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 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 = flowSkillVersionPins(flow);\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.skillId;\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 checks = validateFlowVersions(pinnedNodes, 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\n/**\n * Assert `found` sits inside one of `roots`.\n *\n * A backstop, not the primary control: `isValidAssetName` already rejects every\n * id containing a separator, and `findFlowFileInRoots` skips any candidate that\n * escapes its search dir. So on today's code this cannot fire — it is here to\n * fail loudly rather than silently if a future lookup stops enforcing\n * containment itself. Widening the accepted extensions must never widen which\n * paths are reachable, and this is the line that keeps that honest.\n */\nfunction assertContainedInAnyRoot(found: string, roots: string[], flowId: string): void {\n const resolved = path.resolve(found);\n const inside = roots.some((root) => {\n const relative = path.relative(path.resolve(root), resolved);\n return !relative.startsWith(\"..\") && !path.isAbsolute(relative);\n });\n if (!inside) {\n throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);\n }\n}\n\n/** One line per near-miss: a file that is right there but was still rejected. */\nfunction describeMisses(misses: FlowLookupMiss[], heading: string): string {\n const seen = new Set<string>();\n const lines: string[] = [];\n for (const miss of misses) {\n if (seen.has(miss.path)) continue;\n seen.add(miss.path);\n lines.push(\n miss.reason === \"id-mismatch\"\n ? ` ${miss.path}: declares id ${JSON.stringify(miss.declaredId ?? \"\")}`\n : ` ${miss.path}: could not be parsed (${miss.error ?? \"unknown error\"})`,\n );\n }\n return lines.length > 0 ? `\\n${heading}\\n${lines.join(\"\\n\")}` : \"\";\n}\n\n/**\n * Resolve one flow identity through the CLI/serve host's normal lookup order —\n * the same roots and filenames `skaile run` and `flow list` use, via\n * {@link flowLookupRoots} / {@link findFlowFileInRoots}. Resolution is by the\n * **declared** `id`, not by filename.\n *\n * @throws {Error} When `flowId` is not a canonical asset name, when no file\n * declares it, or when a match somehow resolves outside every lookup root.\n */\nexport function resolveFlowPath(flowId: string, projectDir: string): string {\n // Sub-flow targets and resumed session records are the two callers, so an\n // identity that is not canonical is a bug in the caller, not a missing file.\n if (!isValidAssetName(flowId)) {\n throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);\n }\n\n const roots = flowLookupRoots(projectDir);\n const misses: FlowLookupMiss[] = [];\n const found = findFlowFileInRoots(flowId, roots, { onMiss: (m) => misses.push(m) });\n if (found) {\n assertContainedInAnyRoot(found, roots, flowId);\n return found;\n }\n\n // A file that is present but unparseable is a different problem from a missing\n // one, and \"not found\" is the wrong headline for it — that exact misdirection\n // is what this change exists to remove, so don't reintroduce it here.\n if (misses.length > 0 && misses.every((m) => m.reason === \"unparseable\")) {\n throw new Error(\n `Flow ${flowId} was found but could not be loaded.` + describeMisses(misses, \"Candidates:\"),\n );\n }\n\n const shown = roots.slice(0, 3).join(\", \");\n const more = roots.length > 3 ? \", …\" : \"\";\n // Spelled from FLOW_FILE_EXTENSIONS so the message cannot drift from the\n // candidate list the lookup actually probes.\n const accepted = FLOW_FILE_EXTENSIONS.map((ext) => `${flowId}${ext}`).join(\" | \");\n throw new Error(\n `Flow not found: ${flowId}. Searched ${roots.length} root(s) (${shown || \"none\"}${more}) ` +\n `for ${accepted} — flat, or inside a ${flowId}/ directory.` +\n describeMisses(misses, \"Near misses:\"),\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { classifyGenericErrorMessage } from './chunk-GAH4YRCI.js';
|
|
2
|
-
import { getProviderPreset, registryCredentialEnv, providerCredentialEnvName, AgentDriver, BUILTIN_DRIVER_CATALOG } from './chunk-
|
|
2
|
+
import { getProviderPreset, registryCredentialEnv, providerCredentialEnvName, AgentDriver, BUILTIN_DRIVER_CATALOG } from './chunk-C2CYBRYJ.js';
|
|
3
3
|
import { mergeRegistries, resolveEntryBaseUrl, registryEntries, isEntryEnabled, parseModelRef } from './chunk-ILG4BXYE.js';
|
|
4
4
|
import { spawn } from 'child_process';
|
|
5
5
|
import { createInterface } from 'readline';
|
|
@@ -551,5 +551,5 @@ function extractCost(json) {
|
|
|
551
551
|
}
|
|
552
552
|
|
|
553
553
|
export { SubprocessCliDriver, backendModelSelector, backendProviderName, bindSingleProviderEntry, continueRoleBinding, credentialsForEveryProvider, entryBaseUrl, entryModelIds, entrySurface, extractCost, extractText, extractTokens, isStockCatalogEndpoint, registryModelEntries, resolveEnvDriverSession, resolveRegistryBinding, selectableEntries };
|
|
554
|
-
//# sourceMappingURL=chunk-
|
|
555
|
-
//# sourceMappingURL=chunk-
|
|
554
|
+
//# sourceMappingURL=chunk-JF77XKD7.js.map
|
|
555
|
+
//# sourceMappingURL=chunk-JF77XKD7.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/provider-materialize/env-drivers.ts","../bridge/src/drivers/_subprocess-cli.ts"],"names":[],"mappings":";;;;;;;AAwEO,SAAS,uBAAA,CACd,MAAA,EACA,UAAA,GAAiD,OAAA,CAAQ,GAAA,EACvC;AAClB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,MAAA,CAAO,QAAA,IAAY,eAAA,CAAgB,EAAE,CAAA;AAAA,IAC/C,WAAW,EAAE,GAAG,UAAA,EAAY,GAAG,OAAO,GAAA,EAAI;AAAA,IAC1C,GAAI,OAAO,QAAA,GAAW,EAAE,UAAU,MAAA,CAAO,QAAA,KAAa,EAAC;AAAA,IACvD,GAAI,OAAO,KAAA,GAAQ,EAAE,OAAO,MAAA,CAAO,KAAA,KAAU;AAAC,GAChD;AACF;AA2BO,SAAS,aAAa,KAAA,EAA0D;AACrF,EAAA,IAAI,KAAA,CAAM,OAAA,EAAS,OAAO,KAAA,CAAM,OAAA;AAChC,EAAA,OAAO,MAAM,MAAA,GAAS,iBAAA,CAAkB,KAAA,CAAM,MAAM,GAAG,OAAA,GAAU,MAAA;AACnE;AAQO,SAAS,aAAa,KAAA,EAA+C;AAC1E,EAAA,MAAM,QAAA,GAAW,oBAAoB,KAAK,CAAA;AAC1C,EAAA,IAAI,UAAU,OAAO,QAAA;AACrB,EAAA,OAAO,MAAM,MAAA,GAAS,iBAAA,CAAkB,KAAA,CAAM,MAAM,GAAG,QAAA,GAAW,MAAA;AACpE;AAaO,SAAS,uBAAuB,KAAA,EAAoC;AACzE,EAAA,MAAM,SAAS,KAAA,CAAM,MAAA,GAAS,iBAAA,CAAkB,KAAA,CAAM,MAAM,CAAA,GAAI,MAAA;AAChE,EAAA,OAAO,MAAA,KAAW,M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,SAAA;AAC5D,EAAA,OAAO,MAAA;AACT;AAGO,SAAS,YAAY,IAAA,EAA+B;AACzD,EAAA,MAAM,CAAA,GACJ,IAAA,EAAM,IAAA,IAAQ,IAAA,EAAM,OAAA,IAAW,IAAA,EAAM,cAAA,IAAkB,IAAA,EAAM,KAAA,EAAO,IAAA,IAAQ,IAAA,EAAM,KAAA,EAAO,IAAA;AAC3F,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC","file":"chunk-HFS22LN2.js","sourcesContent":["/**\n * Registry adapter for the **env-shaped CLI drivers** — Gemini, Qwen, OpenCode,\n * Goose and Continue (§2.3).\n *\n * These backends take their endpoint from the environment rather than from a\n * config file, so the adapter's job is three things: resolve which registry\n * entry the session's model selector names, refuse at start when that entry\n * speaks a wire surface the backend cannot, and hand the driver the\n * provider-side model id it must put on the command line.\n *\n * Two pluralities meet here (`BUILTIN_DRIVER_CATALOG.providerPlurality`):\n *\n * - `single` — Gemini and Qwen address exactly one endpoint. The bound entry\n * supplies the credential *and* the base URL, and a surface mismatch is\n * fatal: a Gemini CLI pointed at an `openai-completions` endpoint cannot\n * work, and failing at start names the surface instead of leaving the user\n * with an opaque error mid-turn.\n * - `credentials-n` — OpenCode, Goose and Continue accept every enabled\n * entry's credential at once and select one active model. The credential\n * fan-out is `registryCredentialEnv`; the active model is this module's\n * `<provider>/<model>` binding.\n *\n * Writing the per-endpoint config files those three need for *custom*\n * endpoints (`opencode.json`, Goose `custom_providers/*.json`, Continue\n * `config.yaml`) is the file half, and is deliberately not here.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3\n */\n\nimport {\n type AIProviderLlmEntry,\n type AIProviderSurface,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n mergeRegistries,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport type { ModelEntry } from \"../models.js\";\nimport { getProviderPreset } from \"../provider-catalog.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport type { AgentConfig } from \"../types.js\";\nimport { providerCredentialEnvName, registryCredentialEnv } from \"./credential-env.js\";\n\n/**\n * Everything a CLI driver needs to know about this session's AI providers,\n * resolved once from its {@link AgentConfig}.\n */\nexport interface EnvDriverSession {\n /** The merged registry this session may address. Empty when none was configured. */\n registry: MergedAIProviderRegistry;\n /**\n * Environment `credential.ref` lookups resolve against — the process\n * environment widened with `config.env`, which is where the session\n * boundary delivered every resolved `SKAILE_AIP_<ID>_KEY`.\n */\n lookupEnv: Record<string, string | undefined>;\n /** Model selector: `<providerId>/<modelId>`, a bare id, or `@role`. */\n modelRef?: string;\n /** Roles table an `@role` selector resolves through. */\n roles?: Record<string, string>;\n}\n\n/**\n * Resolve the session's providers once, from its {@link AgentConfig}.\n *\n * `config.env` is folded into `lookupEnv` rather than kept apart: it is part\n * of the session's environment, not an extra, and a credential or\n * `*_BASE_URL` delivered there must be visible exactly as the child will see\n * it.\n */\nexport function resolveEnvDriverSession(\n config: AgentConfig,\n processEnv: Record<string, string | undefined> = process.env,\n): EnvDriverSession {\n return {\n registry: config.registry ?? mergeRegistries([]),\n lookupEnv: { ...processEnv, ...config.env },\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n };\n}\n\n/** One resolved endpoint + model — everything a driver needs to spawn. */\nexport interface RegistryModelBinding {\n /** Registry id of the selected entry. */\n providerId: string;\n /** The selected entry itself. */\n entry: AIProviderLlmEntry;\n /** Logical model id, after `@role` expansion and before `model_map`. */\n modelId?: string;\n /** Provider-side model id — what goes on the wire / command line. */\n providerModelId?: string;\n /** Wire protocol, from the entry or its preset. */\n surface?: AIProviderSurface;\n /** Resolved endpoint, from the entry, its transport params, or its preset. */\n baseUrl?: string;\n /**\n * The provider name the *backend* knows this endpoint by — a catalog preset\n * id for a stock endpoint, the registry id for anything custom. See\n * {@link backendProviderName}.\n */\n backendProviderId: string;\n /** Non-fatal notes from `parseModelRef` (dangling role, disabled provider). */\n warnings: string[];\n}\n\n/** The entry's wire surface: its own, else its preset's. */\nexport function entrySurface(entry: AIProviderLlmEntry): AIProviderSurface | undefined {\n if (entry.surface) return entry.surface;\n return entry.preset ? getProviderPreset(entry.preset)?.surface : undefined;\n}\n\n/**\n * The entry's endpoint: its literal or transport-derived URL, else its\n * preset's literal. Transport templates that still carry `{param}`\n * placeholders never come back — `resolveEntryBaseUrl` withholds those, and a\n * preset's template is not a URL.\n */\nexport function entryBaseUrl(entry: AIProviderLlmEntry): string | undefined {\n const resolved = resolveEntryBaseUrl(entry);\n if (resolved) return resolved;\n return entry.preset ? getProviderPreset(entry.preset)?.base_url : undefined;\n}\n\n/**\n * True when a `credentials-n` backend already knows this endpoint under its\n * own catalog name — the entry names a preset and did not move it somewhere\n * else.\n *\n * The one rule both halves of §2.3 read: it decides the name the env half\n * puts on the command line ({@link backendProviderName}) *and* whether the\n * file half has to describe the endpoint at all. Reading it twice is what\n * keeps `-m <name>/<model>` and the generated provider file talking about the\n * same thing.\n */\nexport function isStockCatalogEndpoint(entry: AIProviderLlmEntry): boolean {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n return preset !== undefined && entryBaseUrl(entry) === preset.base_url;\n}\n\n/**\n * The provider name to give a `credentials-n` backend (`-m <name>/<model>`,\n * `GOOSE_PROVIDER`).\n *\n * A stock catalog endpoint is named by its preset, because that is the name\n * OpenCode's models.dev list and Goose's built-in provider table already use —\n * `prod-claude: {preset: anthropic}` is still Anthropic to them. An entry with\n * an endpoint of its own is named by its registry id: no built-in table knows\n * it, so the id is what its generated provider file is keyed by (the file half\n * of §2.3).\n */\nexport function backendProviderName(providerId: string, entry: AIProviderLlmEntry): string {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n if (!preset || !isStockCatalogEndpoint(entry)) return providerId;\n return preset.id;\n}\n\n/**\n * Enabled `llm`/`embed` entries, in registry order. Also the set the file\n * adapters render (`opencode-config.ts`, `goose-custom-providers.ts`,\n * `continue-config-yaml.ts`): the env half and the file half must agree on\n * which entries exist before they can agree on what to call them.\n */\nexport function selectableEntries(\n registry: MergedAIProviderRegistry,\n): Array<[string, AIProviderLlmEntry]> {\n return registryEntries(registry).filter(\n (pair): pair is [string, AIProviderLlmEntry] =>\n (pair[1].kind === \"llm\" || pair[1].kind === \"embed\") && isEntryEnabled(pair[1]),\n );\n}\n\n/**\n * The provider-side model ids an entry declares, as `[logicalId, providerId]`\n * pairs in declaration order: every `model_map` entry, plus every\n * `capabilities` key the map does not rename.\n */\nexport function entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logicalIds = [\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}).filter((id) => !(id in (entry.model_map ?? {}))),\n ];\n return logicalIds.map((id) => [id, entry.model_map?.[id] ?? id]);\n}\n\nfunction describeBinding(\n providerId: string,\n entry: AIProviderLlmEntry,\n modelId: string | undefined,\n providerModelId: string | undefined,\n warnings: string[],\n): RegistryModelBinding {\n const surface = entrySurface(entry);\n const baseUrl = entryBaseUrl(entry);\n return {\n providerId,\n entry,\n ...(modelId === undefined ? {} : { modelId }),\n ...(providerModelId === undefined ? {} : { providerModelId }),\n ...(surface ? { surface } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n backendProviderId: backendProviderName(providerId, entry),\n warnings,\n };\n}\n\n/**\n * Resolve the session's endpoint + model.\n *\n * With no selector the first entry in registry order wins and the backend\n * keeps its own default model — exactly what an absent `model` meant before\n * the registry existed. Returns `undefined` when no entry can serve a model\n * (an empty, fully-disabled or voice-only registry).\n */\nexport function resolveRegistryBinding(\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const entries = selectableEntries(session.registry);\n if (entries.length === 0) return undefined;\n\n const selector = session.modelRef?.trim();\n if (!selector) {\n const [providerId, entry] = entries[0];\n return describeBinding(providerId, entry, undefined, undefined, []);\n }\n\n // A selector that is exactly an entry id names the endpoint and nothing\n // else: the backend keeps its own default model. `parseModelRef` would read\n // it as a bare *model* id and fall back to registry order.\n const named = entries.find(([id]) => id === selector);\n if (named) return describeBinding(named[0], named[1], undefined, undefined, []);\n\n const resolved = parseModelRef(selector, session.registry, session.roles);\n if (!resolved) return undefined;\n const match = entries.find(([id]) => id === resolved.providerId);\n if (!match) return undefined;\n return describeBinding(\n match[0],\n match[1],\n resolved.modelId,\n resolved.providerModelId,\n resolved.warnings,\n );\n}\n\n/**\n * Every credential a `credentials-n` backend may use: one variable per\n * enabled registry entry. OpenCode, Goose and Continue have always received\n * *all* of them, not just the selected endpoint's, because they route across\n * providers inside a single session.\n */\nexport function credentialsForEveryProvider(session: EnvDriverSession): Record<string, string> {\n return registryCredentialEnv(session.registry, { env: session.lookupEnv });\n}\n\n/**\n * Throw when the bound entry speaks a wire surface this driver cannot.\n *\n * The message names the offending surface and lists the ones the backend does\n * speak (`BUILTIN_DRIVER_CATALOG[driverId].surfaces`). An entry that declares\n * no surface and names no preset is not judged — there is nothing to compare.\n */\nexport function assertDriverSpeaksSurface(\n driverId: string,\n productName: string,\n binding: RegistryModelBinding,\n): void {\n const supported = BUILTIN_DRIVER_CATALOG[driverId]?.surfaces;\n if (!supported || supported.length === 0) return;\n const surface = binding.surface;\n if (!surface || supported.includes(surface)) return;\n throw new Error(\n `${productName} cannot speak the '${surface}' surface of AI provider entry ` +\n `'${binding.providerId}'. ${productName} speaks: ${supported.join(\", \")}. ` +\n `Point this session's model at an entry with one of those surfaces, ` +\n `or run it on a driver that speaks '${surface}'.`,\n );\n}\n\n/**\n * The models a `credentials-n` backend can be pointed at, straight from the\n * registry: every enabled entry's mapped ids, namespaced the way the backend\n * takes them (`-m <provider>/<model>`).\n *\n * These backends have no model-list endpoint of their own — OpenCode reads\n * models.dev, Goose and Continue read their config — so the registry is the\n * only list that describes *this* session's reachable models, and it needs no\n * network call to produce.\n */\nexport function registryModelEntries(session: EnvDriverSession): ModelEntry[] {\n const out: ModelEntry[] = [];\n const seen = new Set<string>();\n for (const [providerId, entry] of selectableEntries(session.registry)) {\n const backendId = backendProviderName(providerId, entry);\n const label = entry.label ?? providerId;\n for (const [logicalId, providerModelId] of entryModelIds(entry)) {\n const id = `${backendId}/${providerModelId}`;\n if (seen.has(id)) continue;\n seen.add(id);\n out.push({ id, name: `${label} ${logicalId}` });\n }\n }\n return out;\n}\n\n/**\n * Resolve the binding and enforce the surface — what a `single`-plurality\n * driver does at start.\n *\n * The registry is authoritative: pointing the driver at an entry it cannot\n * speak throws rather than silently running somewhere else. `undefined` when\n * the session configured no endpoint at all, which leaves the driver on its\n * own native auth.\n */\nexport function bindSingleProviderEntry(\n driverId: string,\n productName: string,\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n assertDriverSpeaksSurface(driverId, productName, binding);\n return binding;\n}\n\n/**\n * The `<provider>/<model>` selector a `credentials-n` backend takes on its\n * command line (`opencode -m`). `undefined` when no model was selected — the\n * backend then uses its own default rather than being handed a bare provider.\n */\nexport function backendModelSelector(binding: RegistryModelBinding): string | undefined {\n if (!binding.providerModelId) return undefined;\n return `${binding.backendProviderId}/${binding.providerModelId}`;\n}\n\n/**\n * Continue's model selection is a **role binding**, not a flag: `cn` has no\n * `--model` option (only `--config <slug>`), and its `config.yaml` binds each\n * model to roles (`chat`, `edit`, `apply`, …). This is the binding for the\n * role a headless `cn -p` turn runs as, and the shape its generated\n * `config.yaml` is rendered from.\n *\n * `apiKeyEnv` is a variable *name*: the secret travels in the child\n * environment, never in a rendered config.\n */\nexport interface ContinueRoleBinding {\n /** Continue role this model serves. A headless prompt is a `chat` turn. */\n role: \"chat\";\n /** Registry id of the entry. */\n providerId: string;\n /** Provider name Continue knows the endpoint by. */\n provider: string;\n /** Provider-side model id. */\n model?: string;\n /** Endpoint, when the entry states one. */\n apiBase?: string;\n /** Env var holding the credential — the name, never the value. */\n apiKeyEnv: string;\n}\n\n/**\n * Map the session's chosen endpoint onto the Continue role a headless turn\n * runs as. `undefined` when the session configured no endpoint — `cn` then\n * runs against whatever its own `config.yaml` / Hub login provides.\n */\nexport function continueRoleBinding(session: EnvDriverSession): ContinueRoleBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n return {\n role: \"chat\",\n providerId: binding.providerId,\n provider: binding.backendProviderId,\n ...(binding.providerModelId ? { model: binding.providerModelId } : {}),\n ...(binding.baseUrl ? { apiBase: binding.baseUrl } : {}),\n apiKeyEnv: providerCredentialEnvName(binding.providerId),\n };\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport type { EventEmitter } from \"node:events\";\nimport { createInterface, type Interface } from \"node:readline\";\nimport type { Logger, TokenUsage } from \"@skaile/workspaces/types\";\nimport { classifyGenericErrorMessage } from \"../error-classifier.js\";\nimport {\n type AgentConfig,\n AgentDriver,\n type AgentError,\n type AgentEvent,\n type AgentMessage,\n} from \"../types.js\";\n\n/**\n * Shared base for one-shot **subprocess CLI** agent backends (Gemini, Qwen,\n * OpenCode, Goose, Continue).\n *\n * These backends are neither persistent JSON-RPC subprocesses (`omp`) nor\n * in-process SDKs (`claude-sdk`, `codex`). In headless mode each is invoked\n * **once per turn** — `prompt()` spawns the CLI fresh, a `readline` loop maps\n * newline-delimited JSON on stdout to the unified {@link AgentEvent} stream, and\n * **process exit marks the end of the turn**. Multi-turn continuity comes from\n * capturing a backend session id (emitted as `session_info`) and replaying it\n * via a resume flag on the next spawn.\n *\n * Subclasses implement {@link buildArgs}, {@link buildEnv}, and either\n * {@link handleJson} (streaming JSONL, the default) or {@link handleBuffered}\n * (`mode = \"buffered\"`, for CLIs that print a single JSON blob at the end).\n *\n * **Terminal-sequence invariant.** Subclasses MUST NOT emit `agent_end`. The\n * base emits exactly one `result` (synthesizing a success result when the\n * stream produced none) followed by a single `agent_end` on clean exit, or an\n * `error` + `agent_end` on crash. This keeps the turn-completion contract\n * (`prompt()` resolves after `agent_end`) identical across every CLI driver.\n *\n * @docLink packages/bridge/drivers#subprocess-cli\n */\nexport abstract class SubprocessCliDriver extends AgentDriver {\n /** Per-driver logger, constructed once by the subclass. */\n protected abstract readonly log: Logger;\n /** Default binary name spawned in production (e.g. `\"gemini\"`). */\n protected abstract readonly defaultBin: string;\n /** Human product name used in error messages / hints (e.g. `\"Gemini CLI\"`). */\n protected abstract readonly productName: string;\n /**\n * Test-seam env prefix. `<PREFIX>_BRIDGE_BIN` overrides the spawn binary and\n * `<PREFIX>_BRIDGE_PREARGS` (space-delimited) supplies leading argv — used by\n * the fake-CLI harness to redirect spawn without monkey-patching\n * `child_process`. Both are ignored in production.\n */\n protected abstract readonly envPrefix: string;\n /** `\"jsonl\"` streams events line-by-line; `\"buffered\"` parses all stdout once on exit. */\n protected readonly mode: \"jsonl\" | \"buffered\" = \"jsonl\";\n\n protected config: AgentConfig;\n\n private proc: ChildProcess | null = null;\n private rl: Interface | null = null;\n private stderrBuffer: string[] = [];\n private stdoutBuffer = \"\";\n private started = false;\n\n // ── Per-turn state ──────────────────────────────────────────────────────\n private prevText = \"\";\n private activeAssistant = false;\n private pendingToolResults: AgentMessage[] = [];\n private sawResult = false;\n private aborting = false;\n private turnResolve: (() => void) | null = null;\n private turnReject: ((err: Error) => void) | null = null;\n\n protected _sessionId?: string;\n protected _lastTokens: TokenUsage | null = null;\n\n constructor(config: AgentConfig) {\n super();\n this.config = config;\n }\n\n override get runtimeSessionId(): string | undefined {\n return this._sessionId;\n }\n\n override getModel(): string | undefined {\n return this.config.model;\n }\n\n override getTokenUsage(): TokenUsage | null {\n return this._lastTokens;\n }\n\n override reconfigure(patch: Partial<Pick<AgentConfig, \"model\" | \"thinking\" | \"effort\">>): void {\n if (patch.model !== undefined) this.config.model = patch.model;\n if (patch.thinking !== undefined) this.config.thinking = patch.thinking;\n if (patch.effort !== undefined) this.config.effort = patch.effort;\n }\n\n /**\n * No-op for one-shot CLIs — there is no long-lived process to spawn until the\n * first prompt. Kept so the runner's `start()` → `prompt()` ordering works\n * uniformly; binary-presence failures surface as a `config` error on the\n * first spawn (see {@link classifyProcessError}).\n */\n async start(): Promise<void> {\n this.started = true;\n }\n\n get isRunning(): boolean {\n return this.proc !== null && !this.proc.killed;\n }\n\n /**\n * Sends a user message to the CLI and resolves after the turn completes\n * (`agent_end`). Spawns a fresh child per call; rejects if the child exits\n * non-zero before emitting a result, so the caller never hangs.\n */\n async prompt(message: string): Promise<void> {\n if (this.proc) throw new Error(`${this.productName} turn already in progress`);\n if (!this.started) await this.start();\n\n this.prevText = \"\";\n this.activeAssistant = false;\n this.pendingToolResults = [];\n this.sawResult = false;\n this.aborting = false;\n this.stderrBuffer = [];\n this.stdoutBuffer = \"\";\n this._lastTokens = null;\n\n const composed = this.composePrompt(message);\n const overrideBin = process.env[`${this.envPrefix}_BRIDGE_BIN`];\n const preArgs = process.env[`${this.envPrefix}_BRIDGE_PREARGS`]\n ? (process.env[`${this.envPrefix}_BRIDGE_PREARGS`] as string).split(/\\s+/).filter(Boolean)\n : [];\n const bin = overrideBin || this.defaultBin;\n const args = [...preArgs, ...this.buildArgs(composed, this._sessionId)];\n const env = this.buildEnv();\n\n return new Promise<void>((resolve, reject) => {\n this.turnResolve = resolve;\n this.turnReject = reject;\n this.log.info(\"spawning CLI\", {\n bin,\n cwd: this.config.cwd,\n resume: Boolean(this._sessionId),\n });\n\n const proc = spawn(bin, args, {\n cwd: this.config.cwd,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n }) as ChildProcess;\n this.proc = proc;\n const procEmitter = proc as unknown as EventEmitter;\n\n procEmitter.on(\"error\", (err: Error) => {\n const detail = this.classifyProcessError(err as NodeJS.ErrnoException);\n this.log.error(\"spawn error\", err, { detail });\n this.pushError(detail);\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleReject(Object.assign(new Error(detail.message), { detail }));\n });\n\n if (proc.stdout) {\n if (this.mode === \"jsonl\") {\n const rl = createInterface({ input: proc.stdout });\n this.rl = rl;\n (rl as unknown as EventEmitter).on(\"line\", (line: string) => this.onStdoutLine(line));\n } else {\n proc.stdout.setEncoding(\"utf8\");\n proc.stdout.on(\"data\", (chunk: string) => {\n this.stdoutBuffer += chunk;\n });\n }\n }\n\n if (proc.stderr) {\n const stderrRl = createInterface({ input: proc.stderr });\n (stderrRl as unknown as EventEmitter).on(\"line\", (line: string) => {\n this.log.debug(\"stderr\", { line });\n this.stderrBuffer.push(line);\n if (this.stderrBuffer.length > 20) this.stderrBuffer.shift();\n });\n }\n\n procEmitter.on(\"exit\", (code: number | null, signal: NodeJS.Signals | null) => {\n this.log.info(\"CLI exited\", { code, signal });\n this.onExit(code, signal);\n });\n });\n }\n\n /** Out-of-band abort: terminates the current child. Driver stays usable for the next prompt. */\n async abort(): Promise<void> {\n this.aborting = true;\n this.proc?.kill(\"SIGTERM\");\n }\n\n kill(): void {\n this.aborting = true;\n this.proc?.kill(\"SIGTERM\");\n this.cleanup();\n }\n\n async resetSession(): Promise<void> {\n this.kill();\n this._sessionId = undefined;\n this._lastTokens = null;\n }\n\n // ── Subclass hooks ────────────────────────────────────────────────────────\n\n /** Build the CLI argv (binary excluded) for one turn. `resumeId` is the captured session id, if any. */\n protected abstract buildArgs(message: string, resumeId: string | undefined): string[];\n\n /** Build the child-process env (explicit allowlist — see {@link baseEnv}). */\n protected abstract buildEnv(): Record<string, string>;\n\n /** Map one parsed stdout JSON object to events via the `push*` helpers. Streaming (`jsonl`) mode only. */\n protected handleJson(_json: unknown): void {}\n\n /** Parse the full stdout blob once on clean exit. `buffered` mode only. */\n protected handleBuffered(_raw: string): void {}\n\n /** Install-failure hint surfaced when the binary is missing. */\n protected abstract installHint(): string;\n\n /**\n * Classify a non-zero exit into an {@link AgentError}, or `null` to treat the\n * exit as success (e.g. a turn-limit code where a result was already\n * emitted). Default: code `0` / clean signal → success; otherwise `process`.\n */\n protected classifyExit(code: number | null, signal: NodeJS.Signals | null): AgentError | null {\n if (code === 0 || (code === null && signal === null)) return null;\n const tail = this.stderrBuffer.slice(-10).join(\"\\n\");\n return {\n message: `${this.productName} exited with code ${code ?? \"null\"}${tail ? `: ${tail}` : \"\"}`,\n category: \"process\",\n retryable: true,\n hint: tail || `The ${this.productName} process exited unexpectedly. Try the prompt again.`,\n };\n }\n\n // ── Protected emit helpers (used by handleJson / handleBuffered) ────────────\n\n /** Prepend `systemPrompt` to the user message — uniform across CLIs lacking a reliable system flag. */\n protected composePrompt(message: string): string {\n return this.config.systemPrompt ? `${this.config.systemPrompt}\\n\\n---\\n\\n${message}` : message;\n }\n\n protected pushAssistantDelta(fullText: string): void {\n if (!this.activeAssistant) {\n this.activeAssistant = true;\n this.prevText = \"\";\n this.emit(\"agent-event\", {\n type: \"message_start\",\n message: asstMessage(\"\"),\n } satisfies AgentEvent);\n }\n const delta = fullText.startsWith(this.prevText)\n ? fullText.slice(this.prevText.length)\n : fullText;\n this.prevText = fullText;\n if (delta) {\n this.emit(\"agent-event\", {\n type: \"message_update\",\n message: asstMessage(fullText),\n _textDelta: delta,\n } satisfies AgentEvent);\n }\n }\n\n protected pushAssistantEnd(fullText?: string): void {\n if (!this.activeAssistant) return;\n const text = fullText ?? this.prevText;\n this.emit(\"agent-event\", {\n type: \"message_end\",\n message: asstMessage(text),\n } satisfies AgentEvent);\n this.activeAssistant = false;\n this.prevText = \"\";\n }\n\n protected pushToolCall(name: string, input: unknown): void {\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name,\n tool: { name },\n input,\n } satisfies AgentEvent);\n }\n\n protected pushToolResult(name: string, data: unknown, isError = false): void {\n this.pendingToolResults.push({ role: \"tool\", toolName: name, content: \"\", data, isError });\n this.emit(\"agent-event\", {\n type: \"tool_execution_end\",\n toolName: name,\n } satisfies AgentEvent);\n }\n\n private flushToolResults(): void {\n if (this.pendingToolResults.length === 0) return;\n this.emit(\"agent-event\", {\n type: \"turn_end\",\n toolResults: [...this.pendingToolResults],\n } satisfies AgentEvent);\n this.pendingToolResults = [];\n }\n\n protected pushResult(opts: {\n tokens?: TokenUsage | null;\n costUsd?: number;\n summary?: string;\n subtype?: string;\n }): void {\n this.pushAssistantEnd();\n this.flushToolResults();\n if (opts.tokens) this._lastTokens = opts.tokens;\n this.sawResult = true;\n this.emit(\"agent-event\", {\n type: \"result\",\n subtype: opts.subtype ?? \"success\",\n summary: opts.summary,\n costUsd: opts.costUsd ?? 0,\n ...(opts.tokens ? { tokens: opts.tokens } : {}),\n } satisfies AgentEvent);\n }\n\n protected pushError(detail: AgentError, fatal = false): void {\n this.emit(\"agent-event\", {\n type: \"error\",\n error: detail.message,\n detail,\n fatal,\n } satisfies AgentEvent);\n }\n\n protected captureSession(id?: string, file?: string): void {\n if (!id || id === this._sessionId) return;\n this._sessionId = id;\n this.emit(\"agent-event\", {\n type: \"session_info\",\n driverSessionId: id,\n ...(file ? { sessionFile: file } : {}),\n } satisfies AgentEvent);\n }\n\n /** Shared keyword classification + per-driver hint copy (mirrors omp/codex). */\n protected classifyMessage(message: string): AgentError {\n const generic = classifyGenericErrorMessage(message);\n if (!generic) {\n return {\n message,\n category: \"unknown\",\n retryable: true,\n hint: `An unexpected ${this.productName} error occurred. Try the prompt again.`,\n };\n }\n const hint =\n generic.category === \"auth\"\n ? `Check the API key / login configured for ${this.productName}.`\n : generic.category === \"rate_limit\"\n ? `${this.productName} hit a provider rate limit. Wait a moment and try again.`\n : generic.category === \"model\"\n ? \"The selected model is unavailable or the context is too long. Change the model or start a new session.\"\n : `A network error occurred while talking to ${this.productName}.`;\n return { message, category: generic.category, retryable: generic.retryable, hint };\n }\n\n // ── Env allowlist ──────────────────────────────────────────────────────────\n\n /**\n * Explicit env whitelist forwarded to the child. Omits anything provisioned\n * by `provision_secrets` so user credentials stay out of the subprocess\n * environment. Always passes through the driver's test-seam vars and\n * `FAKE_CLI_*`.\n *\n * `config.env` is merged **over** the whitelist, not in place of it. It used\n * to replace it wholesale, which meant any caller that set a single variable\n * silently dropped `PATH` and `HOME` and the spawn failed with ENOENT —\n * unusable as the delivery channel for registry-derived endpoint variables\n * (plan §2.3, \"Delivery rule\"). Widening keeps both: the caller's variables\n * win per key, the process still has a `PATH`.\n */\n protected baseEnv(extraKeys: string[] = []): Record<string, string> {\n const out: Record<string, string> = {};\n const explicit = [\"PATH\", \"HOME\", \"USER\", \"HOSTNAME\", \"SKAILE_SESSION_ID\", ...extraKeys];\n for (const key of explicit) {\n const v = process.env[key];\n if (v !== undefined) out[key] = v;\n }\n for (const [key, value] of Object.entries(process.env)) {\n if (typeof value !== \"string\") continue;\n if (key.startsWith(`${this.envPrefix}_BRIDGE_`) || key.startsWith(\"FAKE_CLI_\")) {\n out[key] = value;\n }\n }\n if (this.config.sshKeyPath) {\n out.GIT_SSH_COMMAND = `ssh -i \"${this.config.sshKeyPath}\" -o StrictHostKeyChecking=accept-new`;\n }\n if (this.config.env) Object.assign(out, this.config.env);\n return out;\n }\n\n // ── Internals ────────────────────────────────────────────────────────────\n\n private onStdoutLine(line: string): void {\n if (!line.trim()) return;\n let json: unknown;\n try {\n json = JSON.parse(line);\n } catch {\n this.log.debug(\"non-JSON stdout line\", { line });\n return;\n }\n try {\n this.handleJson(json);\n } catch (err) {\n this.log.warn(\"handleJson threw\", { error: String(err) });\n }\n }\n\n private onExit(code: number | null, signal: NodeJS.Signals | null): void {\n this.cleanup();\n\n if (this.aborting) {\n this.pushAssistantEnd();\n this.flushToolResults();\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleResolve();\n return;\n }\n\n if (this.mode === \"buffered\" && (code === 0 || code === null)) {\n try {\n this.handleBuffered(this.stdoutBuffer);\n } catch (err) {\n this.log.warn(\"handleBuffered threw\", { error: String(err) });\n }\n }\n\n const exitErr = this.classifyExit(code, signal);\n if (exitErr && !this.sawResult) {\n this.pushAssistantEnd();\n this.flushToolResults();\n this.pushError(exitErr);\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleReject(Object.assign(new Error(exitErr.message), { detail: exitErr }));\n return;\n }\n\n // Clean exit (or non-zero exit after a result already streamed): close any\n // open assistant message, synthesize a success result if none arrived, end.\n if (!this.sawResult) this.pushResult({ summary: \"Task completed\" });\n else {\n this.pushAssistantEnd();\n this.flushToolResults();\n }\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleResolve();\n }\n\n private settleResolve(): void {\n const resolve = this.turnResolve;\n this.turnResolve = null;\n this.turnReject = null;\n resolve?.();\n }\n\n private settleReject(err: Error): void {\n const reject = this.turnReject;\n this.turnResolve = null;\n this.turnReject = null;\n reject?.(err);\n }\n\n private cleanup(): void {\n this.rl?.close();\n this.rl = null;\n this.proc = null;\n }\n\n private classifyProcessError(err: NodeJS.ErrnoException): AgentError {\n if (err.code === \"ENOENT\") {\n return {\n message: `${this.defaultBin} command not found`,\n category: \"config\",\n retryable: false,\n hint: this.installHint(),\n };\n }\n if (err.code === \"EACCES\") {\n return {\n message: `Permission denied running ${this.defaultBin}`,\n category: \"config\",\n retryable: false,\n hint: `Check file permissions for the ${this.defaultBin} binary.`,\n };\n }\n return {\n message: err.message,\n category: \"process\",\n retryable: true,\n hint: `An unexpected process error occurred running ${this.productName}. Try again.`,\n };\n }\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// Tolerant JSON extractors — shared because the upstream stream-json schemas\n// are not fully pinned; read the common field-name variants defensively.\n// ───────────────────────────────────────────────────────────────────────────\n\nfunction asstMessage(text: string): AgentMessage {\n return { role: \"assistant\", content: [{ type: \"text\", text }] };\n}\n\n/** Pull assistant text out of a CLI event, trying the common field names. */\nexport function extractText(json: any): string {\n if (typeof json?.text === \"string\") return json.text;\n if (typeof json?.delta === \"string\") return json.delta;\n if (typeof json?.content === \"string\") return json.content;\n if (typeof json?.response === \"string\") return json.response;\n const msg = json?.message;\n if (typeof msg?.content === \"string\") return msg.content;\n if (Array.isArray(msg?.content)) {\n return msg.content\n .filter(\n (b: any) => (b?.type === \"text\" || b?.type === undefined) && typeof b?.text === \"string\",\n )\n .map((b: any) => b.text)\n .join(\"\");\n }\n if (Array.isArray(json?.parts)) {\n return json.parts\n .filter((p: any) => typeof p?.text === \"string\")\n .map((p: any) => p.text)\n .join(\"\");\n }\n return \"\";\n}\n\n/** Map a CLI usage/stats object onto {@link TokenUsage}, trying common field names. */\nexport function extractTokens(json: any): TokenUsage | null {\n const u = json?.usage ?? json?.stats?.usage ?? json?.stats ?? json?.tokens ?? json;\n if (!u || typeof u !== \"object\") return null;\n const input = u.input_tokens ?? u.inputTokens ?? u.prompt_tokens ?? u.promptTokenCount ?? u.input;\n const output =\n u.output_tokens ?? u.outputTokens ?? u.completion_tokens ?? u.candidatesTokenCount ?? u.output;\n const cacheRead = u.cached_input_tokens ?? u.cacheReadTokens ?? u.cachedContentTokenCount;\n if (input === undefined && output === undefined) return null;\n const tokens: TokenUsage = {};\n if (typeof input === \"number\") tokens.inputTokens = input;\n if (typeof output === \"number\") tokens.outputTokens = output;\n if (typeof cacheRead === \"number\") tokens.cacheReadTokens = cacheRead;\n return tokens;\n}\n\n/** Pull a per-turn USD cost from a CLI result object, or `undefined`. */\nexport function extractCost(json: any): number | undefined {\n const c =\n json?.cost ?? json?.costUsd ?? json?.total_cost_usd ?? json?.stats?.cost ?? json?.usage?.cost;\n return typeof c === \"number\" ? c : undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../bridge/src/provider-materialize/env-drivers.ts","../bridge/src/drivers/_subprocess-cli.ts"],"names":[],"mappings":";;;;;;;AAwEO,SAAS,uBAAA,CACd,MAAA,EACA,UAAA,GAAiD,OAAA,CAAQ,GAAA,EACvC;AAClB,EAAA,OAAO;AAAA,IACL,QAAA,EAAU,MAAA,CAAO,QAAA,IAAY,eAAA,CAAgB,EAAE,CAAA;AAAA,IAC/C,WAAW,EAAE,GAAG,UAAA,EAAY,GAAG,OAAO,GAAA,EAAI;AAAA,IAC1C,GAAI,OAAO,QAAA,GAAW,EAAE,UAAU,MAAA,CAAO,QAAA,KAAa,EAAC;AAAA,IACvD,GAAI,OAAO,KAAA,GAAQ,EAAE,OAAO,MAAA,CAAO,KA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A,IAAoB,CAAA,CAAE,KAAA;AAC5F,EAAA,MAAM,MAAA,GACJ,EAAE,aAAA,IAAiB,CAAA,CAAE,gBAAgB,CAAA,CAAE,iBAAA,IAAqB,CAAA,CAAE,oBAAA,IAAwB,CAAA,CAAE,MAAA;AAC1F,EAAA,MAAM,SAAA,GAAY,CAAA,CAAE,mBAAA,IAAuB,CAAA,CAAE,mBAAmB,CAAA,CAAE,uBAAA;AAClE,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,MAAA,KAAW,MAAA,EAAW,OAAO,IAAA;AACxD,EAAA,MAAM,SAAqB,EAAC;AAC5B,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,MAAA,CAAO,WAAA,GAAc,KAAA;AACpD,EAAA,IAAI,OAAO,MAAA,KAAW,QAAA,EAAU,MAAA,CAAO,YAAA,GAAe,MAAA;AACtD,EAAA,IAAI,OAAO,SAAA,KAAc,QAAA,EAAU,MAAA,CAAO,eAAA,GAAkB,SAAA;AAC5D,EAAA,OAAO,MAAA;AACT;AAGO,SAAS,YAAY,IAAA,EAA+B;AACzD,EAAA,MAAM,CAAA,GACJ,IAAA,EAAM,IAAA,IAAQ,IAAA,EAAM,OAAA,IAAW,IAAA,EAAM,cAAA,IAAkB,IAAA,EAAM,KAAA,EAAO,IAAA,IAAQ,IAAA,EAAM,KAAA,EAAO,IAAA;AAC3F,EAAA,OAAO,OAAO,CAAA,KAAM,QAAA,GAAW,CAAA,GAAI,MAAA;AACrC","file":"chunk-JF77XKD7.js","sourcesContent":["/**\n * Registry adapter for the **env-shaped CLI drivers** — Gemini, Qwen, OpenCode,\n * Goose and Continue (§2.3).\n *\n * These backends take their endpoint from the environment rather than from a\n * config file, so the adapter's job is three things: resolve which registry\n * entry the session's model selector names, refuse at start when that entry\n * speaks a wire surface the backend cannot, and hand the driver the\n * provider-side model id it must put on the command line.\n *\n * Two pluralities meet here (`BUILTIN_DRIVER_CATALOG.providerPlurality`):\n *\n * - `single` — Gemini and Qwen address exactly one endpoint. The bound entry\n * supplies the credential *and* the base URL, and a surface mismatch is\n * fatal: a Gemini CLI pointed at an `openai-completions` endpoint cannot\n * work, and failing at start names the surface instead of leaving the user\n * with an opaque error mid-turn.\n * - `credentials-n` — OpenCode, Goose and Continue accept every enabled\n * entry's credential at once and select one active model. The credential\n * fan-out is `registryCredentialEnv`; the active model is this module's\n * `<provider>/<model>` binding.\n *\n * Writing the per-endpoint config files those three need for *custom*\n * endpoints (`opencode.json`, Goose `custom_providers/*.json`, Continue\n * `config.yaml`) is the file half, and is deliberately not here.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3\n */\n\nimport {\n type AIProviderLlmEntry,\n type AIProviderSurface,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n mergeRegistries,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport type { ModelEntry } from \"../models.js\";\nimport { getProviderPreset } from \"../provider-catalog.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport type { AgentConfig } from \"../types.js\";\nimport { providerCredentialEnvName, registryCredentialEnv } from \"./credential-env.js\";\n\n/**\n * Everything a CLI driver needs to know about this session's AI providers,\n * resolved once from its {@link AgentConfig}.\n */\nexport interface EnvDriverSession {\n /** The merged registry this session may address. Empty when none was configured. */\n registry: MergedAIProviderRegistry;\n /**\n * Environment `credential.ref` lookups resolve against — the process\n * environment widened with `config.env`, which is where the session\n * boundary delivered every resolved `SKAILE_AIP_<ID>_KEY`.\n */\n lookupEnv: Record<string, string | undefined>;\n /** Model selector: `<providerId>/<modelId>`, a bare id, or `@role`. */\n modelRef?: string;\n /** Roles table an `@role` selector resolves through. */\n roles?: Record<string, string>;\n}\n\n/**\n * Resolve the session's providers once, from its {@link AgentConfig}.\n *\n * `config.env` is folded into `lookupEnv` rather than kept apart: it is part\n * of the session's environment, not an extra, and a credential or\n * `*_BASE_URL` delivered there must be visible exactly as the child will see\n * it.\n */\nexport function resolveEnvDriverSession(\n config: AgentConfig,\n processEnv: Record<string, string | undefined> = process.env,\n): EnvDriverSession {\n return {\n registry: config.registry ?? mergeRegistries([]),\n lookupEnv: { ...processEnv, ...config.env },\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n };\n}\n\n/** One resolved endpoint + model — everything a driver needs to spawn. */\nexport interface RegistryModelBinding {\n /** Registry id of the selected entry. */\n providerId: string;\n /** The selected entry itself. */\n entry: AIProviderLlmEntry;\n /** Logical model id, after `@role` expansion and before `model_map`. */\n modelId?: string;\n /** Provider-side model id — what goes on the wire / command line. */\n providerModelId?: string;\n /** Wire protocol, from the entry or its preset. */\n surface?: AIProviderSurface;\n /** Resolved endpoint, from the entry, its transport params, or its preset. */\n baseUrl?: string;\n /**\n * The provider name the *backend* knows this endpoint by — a catalog preset\n * id for a stock endpoint, the registry id for anything custom. See\n * {@link backendProviderName}.\n */\n backendProviderId: string;\n /** Non-fatal notes from `parseModelRef` (dangling role, disabled provider). */\n warnings: string[];\n}\n\n/** The entry's wire surface: its own, else its preset's. */\nexport function entrySurface(entry: AIProviderLlmEntry): AIProviderSurface | undefined {\n if (entry.surface) return entry.surface;\n return entry.preset ? getProviderPreset(entry.preset)?.surface : undefined;\n}\n\n/**\n * The entry's endpoint: its literal or transport-derived URL, else its\n * preset's literal. Transport templates that still carry `{param}`\n * placeholders never come back — `resolveEntryBaseUrl` withholds those, and a\n * preset's template is not a URL.\n */\nexport function entryBaseUrl(entry: AIProviderLlmEntry): string | undefined {\n const resolved = resolveEntryBaseUrl(entry);\n if (resolved) return resolved;\n return entry.preset ? getProviderPreset(entry.preset)?.base_url : undefined;\n}\n\n/**\n * True when a `credentials-n` backend already knows this endpoint under its\n * own catalog name — the entry names a preset and did not move it somewhere\n * else.\n *\n * The one rule both halves of §2.3 read: it decides the name the env half\n * puts on the command line ({@link backendProviderName}) *and* whether the\n * file half has to describe the endpoint at all. Reading it twice is what\n * keeps `-m <name>/<model>` and the generated provider file talking about the\n * same thing.\n */\nexport function isStockCatalogEndpoint(entry: AIProviderLlmEntry): boolean {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n return preset !== undefined && entryBaseUrl(entry) === preset.base_url;\n}\n\n/**\n * The provider name to give a `credentials-n` backend (`-m <name>/<model>`,\n * `GOOSE_PROVIDER`).\n *\n * A stock catalog endpoint is named by its preset, because that is the name\n * OpenCode's models.dev list and Goose's built-in provider table already use —\n * `prod-claude: {preset: anthropic}` is still Anthropic to them. An entry with\n * an endpoint of its own is named by its registry id: no built-in table knows\n * it, so the id is what its generated provider file is keyed by (the file half\n * of §2.3).\n */\nexport function backendProviderName(providerId: string, entry: AIProviderLlmEntry): string {\n const preset = entry.preset ? getProviderPreset(entry.preset) : undefined;\n if (!preset || !isStockCatalogEndpoint(entry)) return providerId;\n return preset.id;\n}\n\n/**\n * Enabled `llm`/`embed` entries, in registry order. Also the set the file\n * adapters render (`opencode-config.ts`, `goose-custom-providers.ts`,\n * `continue-config-yaml.ts`): the env half and the file half must agree on\n * which entries exist before they can agree on what to call them.\n */\nexport function selectableEntries(\n registry: MergedAIProviderRegistry,\n): Array<[string, AIProviderLlmEntry]> {\n return registryEntries(registry).filter(\n (pair): pair is [string, AIProviderLlmEntry] =>\n (pair[1].kind === \"llm\" || pair[1].kind === \"embed\") && isEntryEnabled(pair[1]),\n );\n}\n\n/**\n * The provider-side model ids an entry declares, as `[logicalId, providerId]`\n * pairs in declaration order: every `model_map` entry, plus every\n * `capabilities` key the map does not rename.\n */\nexport function entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logicalIds = [\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}).filter((id) => !(id in (entry.model_map ?? {}))),\n ];\n return logicalIds.map((id) => [id, entry.model_map?.[id] ?? id]);\n}\n\nfunction describeBinding(\n providerId: string,\n entry: AIProviderLlmEntry,\n modelId: string | undefined,\n providerModelId: string | undefined,\n warnings: string[],\n): RegistryModelBinding {\n const surface = entrySurface(entry);\n const baseUrl = entryBaseUrl(entry);\n return {\n providerId,\n entry,\n ...(modelId === undefined ? {} : { modelId }),\n ...(providerModelId === undefined ? {} : { providerModelId }),\n ...(surface ? { surface } : {}),\n ...(baseUrl ? { baseUrl } : {}),\n backendProviderId: backendProviderName(providerId, entry),\n warnings,\n };\n}\n\n/**\n * Resolve the session's endpoint + model.\n *\n * With no selector the first entry in registry order wins and the backend\n * keeps its own default model — exactly what an absent `model` meant before\n * the registry existed. Returns `undefined` when no entry can serve a model\n * (an empty, fully-disabled or voice-only registry).\n */\nexport function resolveRegistryBinding(\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const entries = selectableEntries(session.registry);\n if (entries.length === 0) return undefined;\n\n const selector = session.modelRef?.trim();\n if (!selector) {\n const [providerId, entry] = entries[0];\n return describeBinding(providerId, entry, undefined, undefined, []);\n }\n\n // A selector that is exactly an entry id names the endpoint and nothing\n // else: the backend keeps its own default model. `parseModelRef` would read\n // it as a bare *model* id and fall back to registry order.\n const named = entries.find(([id]) => id === selector);\n if (named) return describeBinding(named[0], named[1], undefined, undefined, []);\n\n const resolved = parseModelRef(selector, session.registry, session.roles);\n if (!resolved) return undefined;\n const match = entries.find(([id]) => id === resolved.providerId);\n if (!match) return undefined;\n return describeBinding(\n match[0],\n match[1],\n resolved.modelId,\n resolved.providerModelId,\n resolved.warnings,\n );\n}\n\n/**\n * Every credential a `credentials-n` backend may use: one variable per\n * enabled registry entry. OpenCode, Goose and Continue have always received\n * *all* of them, not just the selected endpoint's, because they route across\n * providers inside a single session.\n */\nexport function credentialsForEveryProvider(session: EnvDriverSession): Record<string, string> {\n return registryCredentialEnv(session.registry, { env: session.lookupEnv });\n}\n\n/**\n * Throw when the bound entry speaks a wire surface this driver cannot.\n *\n * The message names the offending surface and lists the ones the backend does\n * speak (`BUILTIN_DRIVER_CATALOG[driverId].surfaces`). An entry that declares\n * no surface and names no preset is not judged — there is nothing to compare.\n */\nexport function assertDriverSpeaksSurface(\n driverId: string,\n productName: string,\n binding: RegistryModelBinding,\n): void {\n const supported = BUILTIN_DRIVER_CATALOG[driverId]?.surfaces;\n if (!supported || supported.length === 0) return;\n const surface = binding.surface;\n if (!surface || supported.includes(surface)) return;\n throw new Error(\n `${productName} cannot speak the '${surface}' surface of AI provider entry ` +\n `'${binding.providerId}'. ${productName} speaks: ${supported.join(\", \")}. ` +\n `Point this session's model at an entry with one of those surfaces, ` +\n `or run it on a driver that speaks '${surface}'.`,\n );\n}\n\n/**\n * The models a `credentials-n` backend can be pointed at, straight from the\n * registry: every enabled entry's mapped ids, namespaced the way the backend\n * takes them (`-m <provider>/<model>`).\n *\n * These backends have no model-list endpoint of their own — OpenCode reads\n * models.dev, Goose and Continue read their config — so the registry is the\n * only list that describes *this* session's reachable models, and it needs no\n * network call to produce.\n */\nexport function registryModelEntries(session: EnvDriverSession): ModelEntry[] {\n const out: ModelEntry[] = [];\n const seen = new Set<string>();\n for (const [providerId, entry] of selectableEntries(session.registry)) {\n const backendId = backendProviderName(providerId, entry);\n const label = entry.label ?? providerId;\n for (const [logicalId, providerModelId] of entryModelIds(entry)) {\n const id = `${backendId}/${providerModelId}`;\n if (seen.has(id)) continue;\n seen.add(id);\n out.push({ id, name: `${label} ${logicalId}` });\n }\n }\n return out;\n}\n\n/**\n * Resolve the binding and enforce the surface — what a `single`-plurality\n * driver does at start.\n *\n * The registry is authoritative: pointing the driver at an entry it cannot\n * speak throws rather than silently running somewhere else. `undefined` when\n * the session configured no endpoint at all, which leaves the driver on its\n * own native auth.\n */\nexport function bindSingleProviderEntry(\n driverId: string,\n productName: string,\n session: EnvDriverSession,\n): RegistryModelBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n assertDriverSpeaksSurface(driverId, productName, binding);\n return binding;\n}\n\n/**\n * The `<provider>/<model>` selector a `credentials-n` backend takes on its\n * command line (`opencode -m`). `undefined` when no model was selected — the\n * backend then uses its own default rather than being handed a bare provider.\n */\nexport function backendModelSelector(binding: RegistryModelBinding): string | undefined {\n if (!binding.providerModelId) return undefined;\n return `${binding.backendProviderId}/${binding.providerModelId}`;\n}\n\n/**\n * Continue's model selection is a **role binding**, not a flag: `cn` has no\n * `--model` option (only `--config <slug>`), and its `config.yaml` binds each\n * model to roles (`chat`, `edit`, `apply`, …). This is the binding for the\n * role a headless `cn -p` turn runs as, and the shape its generated\n * `config.yaml` is rendered from.\n *\n * `apiKeyEnv` is a variable *name*: the secret travels in the child\n * environment, never in a rendered config.\n */\nexport interface ContinueRoleBinding {\n /** Continue role this model serves. A headless prompt is a `chat` turn. */\n role: \"chat\";\n /** Registry id of the entry. */\n providerId: string;\n /** Provider name Continue knows the endpoint by. */\n provider: string;\n /** Provider-side model id. */\n model?: string;\n /** Endpoint, when the entry states one. */\n apiBase?: string;\n /** Env var holding the credential — the name, never the value. */\n apiKeyEnv: string;\n}\n\n/**\n * Map the session's chosen endpoint onto the Continue role a headless turn\n * runs as. `undefined` when the session configured no endpoint — `cn` then\n * runs against whatever its own `config.yaml` / Hub login provides.\n */\nexport function continueRoleBinding(session: EnvDriverSession): ContinueRoleBinding | undefined {\n const binding = resolveRegistryBinding(session);\n if (!binding) return undefined;\n return {\n role: \"chat\",\n providerId: binding.providerId,\n provider: binding.backendProviderId,\n ...(binding.providerModelId ? { model: binding.providerModelId } : {}),\n ...(binding.baseUrl ? { apiBase: binding.baseUrl } : {}),\n apiKeyEnv: providerCredentialEnvName(binding.providerId),\n };\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport type { EventEmitter } from \"node:events\";\nimport { createInterface, type Interface } from \"node:readline\";\nimport type { Logger, TokenUsage } from \"@skaile/workspaces/types\";\nimport { classifyGenericErrorMessage } from \"../error-classifier.js\";\nimport {\n type AgentConfig,\n AgentDriver,\n type AgentError,\n type AgentEvent,\n type AgentMessage,\n} from \"../types.js\";\n\n/**\n * Shared base for one-shot **subprocess CLI** agent backends (Gemini, Qwen,\n * OpenCode, Goose, Continue).\n *\n * These backends are neither persistent JSON-RPC subprocesses (`omp`) nor\n * in-process SDKs (`claude-sdk`, `codex`). In headless mode each is invoked\n * **once per turn** — `prompt()` spawns the CLI fresh, a `readline` loop maps\n * newline-delimited JSON on stdout to the unified {@link AgentEvent} stream, and\n * **process exit marks the end of the turn**. Multi-turn continuity comes from\n * capturing a backend session id (emitted as `session_info`) and replaying it\n * via a resume flag on the next spawn.\n *\n * Subclasses implement {@link buildArgs}, {@link buildEnv}, and either\n * {@link handleJson} (streaming JSONL, the default) or {@link handleBuffered}\n * (`mode = \"buffered\"`, for CLIs that print a single JSON blob at the end).\n *\n * **Terminal-sequence invariant.** Subclasses MUST NOT emit `agent_end`. The\n * base emits exactly one `result` (synthesizing a success result when the\n * stream produced none) followed by a single `agent_end` on clean exit, or an\n * `error` + `agent_end` on crash. This keeps the turn-completion contract\n * (`prompt()` resolves after `agent_end`) identical across every CLI driver.\n *\n * @docLink packages/bridge/drivers#subprocess-cli\n */\nexport abstract class SubprocessCliDriver extends AgentDriver {\n /** Per-driver logger, constructed once by the subclass. */\n protected abstract readonly log: Logger;\n /** Default binary name spawned in production (e.g. `\"gemini\"`). */\n protected abstract readonly defaultBin: string;\n /** Human product name used in error messages / hints (e.g. `\"Gemini CLI\"`). */\n protected abstract readonly productName: string;\n /**\n * Test-seam env prefix. `<PREFIX>_BRIDGE_BIN` overrides the spawn binary and\n * `<PREFIX>_BRIDGE_PREARGS` (space-delimited) supplies leading argv — used by\n * the fake-CLI harness to redirect spawn without monkey-patching\n * `child_process`. Both are ignored in production.\n */\n protected abstract readonly envPrefix: string;\n /** `\"jsonl\"` streams events line-by-line; `\"buffered\"` parses all stdout once on exit. */\n protected readonly mode: \"jsonl\" | \"buffered\" = \"jsonl\";\n\n protected config: AgentConfig;\n\n private proc: ChildProcess | null = null;\n private rl: Interface | null = null;\n private stderrBuffer: string[] = [];\n private stdoutBuffer = \"\";\n private started = false;\n\n // ── Per-turn state ──────────────────────────────────────────────────────\n private prevText = \"\";\n private activeAssistant = false;\n private pendingToolResults: AgentMessage[] = [];\n private sawResult = false;\n private aborting = false;\n private turnResolve: (() => void) | null = null;\n private turnReject: ((err: Error) => void) | null = null;\n\n protected _sessionId?: string;\n protected _lastTokens: TokenUsage | null = null;\n\n constructor(config: AgentConfig) {\n super();\n this.config = config;\n }\n\n override get runtimeSessionId(): string | undefined {\n return this._sessionId;\n }\n\n override getModel(): string | undefined {\n return this.config.model;\n }\n\n override getTokenUsage(): TokenUsage | null {\n return this._lastTokens;\n }\n\n override reconfigure(patch: Partial<Pick<AgentConfig, \"model\" | \"thinking\" | \"effort\">>): void {\n if (patch.model !== undefined) this.config.model = patch.model;\n if (patch.thinking !== undefined) this.config.thinking = patch.thinking;\n if (patch.effort !== undefined) this.config.effort = patch.effort;\n }\n\n /**\n * No-op for one-shot CLIs — there is no long-lived process to spawn until the\n * first prompt. Kept so the runner's `start()` → `prompt()` ordering works\n * uniformly; binary-presence failures surface as a `config` error on the\n * first spawn (see {@link classifyProcessError}).\n */\n async start(): Promise<void> {\n this.started = true;\n }\n\n get isRunning(): boolean {\n return this.proc !== null && !this.proc.killed;\n }\n\n /**\n * Sends a user message to the CLI and resolves after the turn completes\n * (`agent_end`). Spawns a fresh child per call; rejects if the child exits\n * non-zero before emitting a result, so the caller never hangs.\n */\n async prompt(message: string): Promise<void> {\n if (this.proc) throw new Error(`${this.productName} turn already in progress`);\n if (!this.started) await this.start();\n\n this.prevText = \"\";\n this.activeAssistant = false;\n this.pendingToolResults = [];\n this.sawResult = false;\n this.aborting = false;\n this.stderrBuffer = [];\n this.stdoutBuffer = \"\";\n this._lastTokens = null;\n\n const composed = this.composePrompt(message);\n const overrideBin = process.env[`${this.envPrefix}_BRIDGE_BIN`];\n const preArgs = process.env[`${this.envPrefix}_BRIDGE_PREARGS`]\n ? (process.env[`${this.envPrefix}_BRIDGE_PREARGS`] as string).split(/\\s+/).filter(Boolean)\n : [];\n const bin = overrideBin || this.defaultBin;\n const args = [...preArgs, ...this.buildArgs(composed, this._sessionId)];\n const env = this.buildEnv();\n\n return new Promise<void>((resolve, reject) => {\n this.turnResolve = resolve;\n this.turnReject = reject;\n this.log.info(\"spawning CLI\", {\n bin,\n cwd: this.config.cwd,\n resume: Boolean(this._sessionId),\n });\n\n const proc = spawn(bin, args, {\n cwd: this.config.cwd,\n env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n }) as ChildProcess;\n this.proc = proc;\n const procEmitter = proc as unknown as EventEmitter;\n\n procEmitter.on(\"error\", (err: Error) => {\n const detail = this.classifyProcessError(err as NodeJS.ErrnoException);\n this.log.error(\"spawn error\", err, { detail });\n this.pushError(detail);\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleReject(Object.assign(new Error(detail.message), { detail }));\n });\n\n if (proc.stdout) {\n if (this.mode === \"jsonl\") {\n const rl = createInterface({ input: proc.stdout });\n this.rl = rl;\n (rl as unknown as EventEmitter).on(\"line\", (line: string) => this.onStdoutLine(line));\n } else {\n proc.stdout.setEncoding(\"utf8\");\n proc.stdout.on(\"data\", (chunk: string) => {\n this.stdoutBuffer += chunk;\n });\n }\n }\n\n if (proc.stderr) {\n const stderrRl = createInterface({ input: proc.stderr });\n (stderrRl as unknown as EventEmitter).on(\"line\", (line: string) => {\n this.log.debug(\"stderr\", { line });\n this.stderrBuffer.push(line);\n if (this.stderrBuffer.length > 20) this.stderrBuffer.shift();\n });\n }\n\n procEmitter.on(\"exit\", (code: number | null, signal: NodeJS.Signals | null) => {\n this.log.info(\"CLI exited\", { code, signal });\n this.onExit(code, signal);\n });\n });\n }\n\n /** Out-of-band abort: terminates the current child. Driver stays usable for the next prompt. */\n async abort(): Promise<void> {\n this.aborting = true;\n this.proc?.kill(\"SIGTERM\");\n }\n\n kill(): void {\n this.aborting = true;\n this.proc?.kill(\"SIGTERM\");\n this.cleanup();\n }\n\n async resetSession(): Promise<void> {\n this.kill();\n this._sessionId = undefined;\n this._lastTokens = null;\n }\n\n // ── Subclass hooks ────────────────────────────────────────────────────────\n\n /** Build the CLI argv (binary excluded) for one turn. `resumeId` is the captured session id, if any. */\n protected abstract buildArgs(message: string, resumeId: string | undefined): string[];\n\n /** Build the child-process env (explicit allowlist — see {@link baseEnv}). */\n protected abstract buildEnv(): Record<string, string>;\n\n /** Map one parsed stdout JSON object to events via the `push*` helpers. Streaming (`jsonl`) mode only. */\n protected handleJson(_json: unknown): void {}\n\n /** Parse the full stdout blob once on clean exit. `buffered` mode only. */\n protected handleBuffered(_raw: string): void {}\n\n /** Install-failure hint surfaced when the binary is missing. */\n protected abstract installHint(): string;\n\n /**\n * Classify a non-zero exit into an {@link AgentError}, or `null` to treat the\n * exit as success (e.g. a turn-limit code where a result was already\n * emitted). Default: code `0` / clean signal → success; otherwise `process`.\n */\n protected classifyExit(code: number | null, signal: NodeJS.Signals | null): AgentError | null {\n if (code === 0 || (code === null && signal === null)) return null;\n const tail = this.stderrBuffer.slice(-10).join(\"\\n\");\n return {\n message: `${this.productName} exited with code ${code ?? \"null\"}${tail ? `: ${tail}` : \"\"}`,\n category: \"process\",\n retryable: true,\n hint: tail || `The ${this.productName} process exited unexpectedly. Try the prompt again.`,\n };\n }\n\n // ── Protected emit helpers (used by handleJson / handleBuffered) ────────────\n\n /** Prepend `systemPrompt` to the user message — uniform across CLIs lacking a reliable system flag. */\n protected composePrompt(message: string): string {\n return this.config.systemPrompt ? `${this.config.systemPrompt}\\n\\n---\\n\\n${message}` : message;\n }\n\n protected pushAssistantDelta(fullText: string): void {\n if (!this.activeAssistant) {\n this.activeAssistant = true;\n this.prevText = \"\";\n this.emit(\"agent-event\", {\n type: \"message_start\",\n message: asstMessage(\"\"),\n } satisfies AgentEvent);\n }\n const delta = fullText.startsWith(this.prevText)\n ? fullText.slice(this.prevText.length)\n : fullText;\n this.prevText = fullText;\n if (delta) {\n this.emit(\"agent-event\", {\n type: \"message_update\",\n message: asstMessage(fullText),\n _textDelta: delta,\n } satisfies AgentEvent);\n }\n }\n\n protected pushAssistantEnd(fullText?: string): void {\n if (!this.activeAssistant) return;\n const text = fullText ?? this.prevText;\n this.emit(\"agent-event\", {\n type: \"message_end\",\n message: asstMessage(text),\n } satisfies AgentEvent);\n this.activeAssistant = false;\n this.prevText = \"\";\n }\n\n protected pushToolCall(name: string, input: unknown): void {\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name,\n tool: { name },\n input,\n } satisfies AgentEvent);\n }\n\n protected pushToolResult(name: string, data: unknown, isError = false): void {\n this.pendingToolResults.push({ role: \"tool\", toolName: name, content: \"\", data, isError });\n this.emit(\"agent-event\", {\n type: \"tool_execution_end\",\n toolName: name,\n } satisfies AgentEvent);\n }\n\n private flushToolResults(): void {\n if (this.pendingToolResults.length === 0) return;\n this.emit(\"agent-event\", {\n type: \"turn_end\",\n toolResults: [...this.pendingToolResults],\n } satisfies AgentEvent);\n this.pendingToolResults = [];\n }\n\n protected pushResult(opts: {\n tokens?: TokenUsage | null;\n costUsd?: number;\n summary?: string;\n subtype?: string;\n }): void {\n this.pushAssistantEnd();\n this.flushToolResults();\n if (opts.tokens) this._lastTokens = opts.tokens;\n this.sawResult = true;\n this.emit(\"agent-event\", {\n type: \"result\",\n subtype: opts.subtype ?? \"success\",\n summary: opts.summary,\n costUsd: opts.costUsd ?? 0,\n ...(opts.tokens ? { tokens: opts.tokens } : {}),\n } satisfies AgentEvent);\n }\n\n protected pushError(detail: AgentError, fatal = false): void {\n this.emit(\"agent-event\", {\n type: \"error\",\n error: detail.message,\n detail,\n fatal,\n } satisfies AgentEvent);\n }\n\n protected captureSession(id?: string, file?: string): void {\n if (!id || id === this._sessionId) return;\n this._sessionId = id;\n this.emit(\"agent-event\", {\n type: \"session_info\",\n driverSessionId: id,\n ...(file ? { sessionFile: file } : {}),\n } satisfies AgentEvent);\n }\n\n /** Shared keyword classification + per-driver hint copy (mirrors omp/codex). */\n protected classifyMessage(message: string): AgentError {\n const generic = classifyGenericErrorMessage(message);\n if (!generic) {\n return {\n message,\n category: \"unknown\",\n retryable: true,\n hint: `An unexpected ${this.productName} error occurred. Try the prompt again.`,\n };\n }\n const hint =\n generic.category === \"auth\"\n ? `Check the API key / login configured for ${this.productName}.`\n : generic.category === \"rate_limit\"\n ? `${this.productName} hit a provider rate limit. Wait a moment and try again.`\n : generic.category === \"model\"\n ? \"The selected model is unavailable or the context is too long. Change the model or start a new session.\"\n : `A network error occurred while talking to ${this.productName}.`;\n return { message, category: generic.category, retryable: generic.retryable, hint };\n }\n\n // ── Env allowlist ──────────────────────────────────────────────────────────\n\n /**\n * Explicit env whitelist forwarded to the child. Omits anything provisioned\n * by `provision_secrets` so user credentials stay out of the subprocess\n * environment. Always passes through the driver's test-seam vars and\n * `FAKE_CLI_*`.\n *\n * `config.env` is merged **over** the whitelist, not in place of it. It used\n * to replace it wholesale, which meant any caller that set a single variable\n * silently dropped `PATH` and `HOME` and the spawn failed with ENOENT —\n * unusable as the delivery channel for registry-derived endpoint variables\n * (plan §2.3, \"Delivery rule\"). Widening keeps both: the caller's variables\n * win per key, the process still has a `PATH`.\n */\n protected baseEnv(extraKeys: string[] = []): Record<string, string> {\n const out: Record<string, string> = {};\n const explicit = [\"PATH\", \"HOME\", \"USER\", \"HOSTNAME\", \"SKAILE_SESSION_ID\", ...extraKeys];\n for (const key of explicit) {\n const v = process.env[key];\n if (v !== undefined) out[key] = v;\n }\n for (const [key, value] of Object.entries(process.env)) {\n if (typeof value !== \"string\") continue;\n if (key.startsWith(`${this.envPrefix}_BRIDGE_`) || key.startsWith(\"FAKE_CLI_\")) {\n out[key] = value;\n }\n }\n if (this.config.sshKeyPath) {\n out.GIT_SSH_COMMAND = `ssh -i \"${this.config.sshKeyPath}\" -o StrictHostKeyChecking=accept-new`;\n }\n if (this.config.env) Object.assign(out, this.config.env);\n return out;\n }\n\n // ── Internals ────────────────────────────────────────────────────────────\n\n private onStdoutLine(line: string): void {\n if (!line.trim()) return;\n let json: unknown;\n try {\n json = JSON.parse(line);\n } catch {\n this.log.debug(\"non-JSON stdout line\", { line });\n return;\n }\n try {\n this.handleJson(json);\n } catch (err) {\n this.log.warn(\"handleJson threw\", { error: String(err) });\n }\n }\n\n private onExit(code: number | null, signal: NodeJS.Signals | null): void {\n this.cleanup();\n\n if (this.aborting) {\n this.pushAssistantEnd();\n this.flushToolResults();\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleResolve();\n return;\n }\n\n if (this.mode === \"buffered\" && (code === 0 || code === null)) {\n try {\n this.handleBuffered(this.stdoutBuffer);\n } catch (err) {\n this.log.warn(\"handleBuffered threw\", { error: String(err) });\n }\n }\n\n const exitErr = this.classifyExit(code, signal);\n if (exitErr && !this.sawResult) {\n this.pushAssistantEnd();\n this.flushToolResults();\n this.pushError(exitErr);\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleReject(Object.assign(new Error(exitErr.message), { detail: exitErr }));\n return;\n }\n\n // Clean exit (or non-zero exit after a result already streamed): close any\n // open assistant message, synthesize a success result if none arrived, end.\n if (!this.sawResult) this.pushResult({ summary: \"Task completed\" });\n else {\n this.pushAssistantEnd();\n this.flushToolResults();\n }\n this.emit(\"agent-event\", { type: \"agent_end\" } satisfies AgentEvent);\n this.settleResolve();\n }\n\n private settleResolve(): void {\n const resolve = this.turnResolve;\n this.turnResolve = null;\n this.turnReject = null;\n resolve?.();\n }\n\n private settleReject(err: Error): void {\n const reject = this.turnReject;\n this.turnResolve = null;\n this.turnReject = null;\n reject?.(err);\n }\n\n private cleanup(): void {\n this.rl?.close();\n this.rl = null;\n this.proc = null;\n }\n\n private classifyProcessError(err: NodeJS.ErrnoException): AgentError {\n if (err.code === \"ENOENT\") {\n return {\n message: `${this.defaultBin} command not found`,\n category: \"config\",\n retryable: false,\n hint: this.installHint(),\n };\n }\n if (err.code === \"EACCES\") {\n return {\n message: `Permission denied running ${this.defaultBin}`,\n category: \"config\",\n retryable: false,\n hint: `Check file permissions for the ${this.defaultBin} binary.`,\n };\n }\n return {\n message: err.message,\n category: \"process\",\n retryable: true,\n hint: `An unexpected process error occurred running ${this.productName}. Try again.`,\n };\n }\n}\n\n// ───────────────────────────────────────────────────────────────────────────\n// Tolerant JSON extractors — shared because the upstream stream-json schemas\n// are not fully pinned; read the common field-name variants defensively.\n// ───────────────────────────────────────────────────────────────────────────\n\nfunction asstMessage(text: string): AgentMessage {\n return { role: \"assistant\", content: [{ type: \"text\", text }] };\n}\n\n/** Pull assistant text out of a CLI event, trying the common field names. */\nexport function extractText(json: any): string {\n if (typeof json?.text === \"string\") return json.text;\n if (typeof json?.delta === \"string\") return json.delta;\n if (typeof json?.content === \"string\") return json.content;\n if (typeof json?.response === \"string\") return json.response;\n const msg = json?.message;\n if (typeof msg?.content === \"string\") return msg.content;\n if (Array.isArray(msg?.content)) {\n return msg.content\n .filter(\n (b: any) => (b?.type === \"text\" || b?.type === undefined) && typeof b?.text === \"string\",\n )\n .map((b: any) => b.text)\n .join(\"\");\n }\n if (Array.isArray(json?.parts)) {\n return json.parts\n .filter((p: any) => typeof p?.text === \"string\")\n .map((p: any) => p.text)\n .join(\"\");\n }\n return \"\";\n}\n\n/** Map a CLI usage/stats object onto {@link TokenUsage}, trying common field names. */\nexport function extractTokens(json: any): TokenUsage | null {\n const u = json?.usage ?? json?.stats?.usage ?? json?.stats ?? json?.tokens ?? json;\n if (!u || typeof u !== \"object\") return null;\n const input = u.input_tokens ?? u.inputTokens ?? u.prompt_tokens ?? u.promptTokenCount ?? u.input;\n const output =\n u.output_tokens ?? u.outputTokens ?? u.completion_tokens ?? u.candidatesTokenCount ?? u.output;\n const cacheRead = u.cached_input_tokens ?? u.cacheReadTokens ?? u.cachedContentTokenCount;\n if (input === undefined && output === undefined) return null;\n const tokens: TokenUsage = {};\n if (typeof input === \"number\") tokens.inputTokens = input;\n if (typeof output === \"number\") tokens.outputTokens = output;\n if (typeof cacheRead === \"number\") tokens.cacheReadTokens = cacheRead;\n return tokens;\n}\n\n/** Pull a per-turn USD cost from a CLI result object, or `undefined`. */\nexport function extractCost(json: any): number | undefined {\n const c =\n json?.cost ?? json?.costUsd ?? json?.total_cost_usd ?? json?.stats?.cost ?? json?.usage?.cost;\n return typeof c === \"number\" ? c : undefined;\n}\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { openLibraryManager, createFullRegistry } from './chunk-
|
|
2
|
-
import { logErr, logInfo, logWarn, logOk, S } from './chunk-
|
|
1
|
+
import { openLibraryManager, createFullRegistry } from './chunk-QCXQXLS2.js';
|
|
2
|
+
import { logErr, logInfo, logWarn, logOk, S } from './chunk-F54V4XMH.js';
|
|
3
3
|
import { getStoreManifestsDir, LocalCatalogSource, writeCuratedManifest } from './chunk-COK4WPU4.js';
|
|
4
4
|
import { computeDeterministicHash, discoverAssetsInTree } from './chunk-M5H4DWIA.js';
|
|
5
5
|
import { WorkspaceYamlEditor } from './chunk-UJPVUN6H.js';
|
|
@@ -313,12 +313,12 @@ function addSourceManifestCommands(src) {
|
|
|
313
313
|
).option("-C, --project-dir <dir>", "Project directory", process.cwd()).option("--publisher <name>", "Override the publisher (--overwrite only)").option("--dev", "Include assets under the source's dev_paths", false).option("--overwrite", "Discard curation and re-scan the full inventory", false).action((arg, opts) => runRebuild(arg, opts));
|
|
314
314
|
manifest.command("verify <src>").description("Verify hashes, deps, and schema (read-only)").option("-C, --project-dir <dir>", "Project directory", process.cwd()).option("--strict", "Fail on advisory checks (warnings force a nonzero exit)", false).action((arg, opts) => runVerify(arg, opts));
|
|
315
315
|
manifest.command("publish <src>").description("Push the curated sidecar manifest and publish it to the store").option("-C, --project-dir <dir>", "Project directory", process.cwd()).option("--as <namespace>", "Publisher namespace (default: your store username)").option("--sidecar-repo <url>", "Public GitHub repo you own to hold the curated manifest").option("--ref <gitref>", "Foreign source ref to ingest (branch/sha; default: main)").option("--dry-run", "Print the publish plan without pushing or calling the store", false).action(async (arg, opts) => {
|
|
316
|
-
const { runPublish } = await import('./source-manifest-publish-
|
|
316
|
+
const { runPublish } = await import('./source-manifest-publish-4Y47IQYN.js');
|
|
317
317
|
await runPublish(arg, opts);
|
|
318
318
|
});
|
|
319
319
|
manifest.command("propose <src>").description("Open a PR to upstream with the sidecar manifest").action(() => notWired("propose"));
|
|
320
320
|
manifest.command("yank <src>").description("Retract the source's published assets from the store").option("-C, --project-dir <dir>", "Project directory", process.cwd()).option("--asset <ref>", "Yank only the asset matching this ref/name").action(async (arg, opts) => {
|
|
321
|
-
const { runYank } = await import('./source-manifest-publish-
|
|
321
|
+
const { runYank } = await import('./source-manifest-publish-4Y47IQYN.js');
|
|
322
322
|
await runYank(arg, opts);
|
|
323
323
|
});
|
|
324
324
|
}
|
|
@@ -684,5 +684,5 @@ function makeSourceCommand() {
|
|
|
684
684
|
}
|
|
685
685
|
|
|
686
686
|
export { autoSyncForSearch, ensureClone, findCacheKeyCollision, indexingHadFailures, legacySourceConfigHint, makeSourceCommand, normalizeSourceUrl, readProjectSources, resolveSourceArg, sourceClonePath, sourceMatchesKey, syncProjectSources };
|
|
687
|
-
//# sourceMappingURL=chunk-
|
|
688
|
-
//# sourceMappingURL=chunk-
|
|
687
|
+
//# sourceMappingURL=chunk-KIIH2T7W.js.map
|
|
688
|
+
//# sourceMappingURL=chunk-KIIH2T7W.js.map
|