@skaile/workspaces 1.10.0 → 1.10.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/bridge/drivers/claude-sdk.js +1 -1
  3. package/dist/bridge/drivers/codex.js +1 -1
  4. package/dist/bridge/drivers/continue.js +2 -2
  5. package/dist/bridge/drivers/echo.js +2 -2
  6. package/dist/bridge/drivers/echo.js.map +1 -1
  7. package/dist/bridge/drivers/gemini.js +3 -3
  8. package/dist/bridge/drivers/goose.js +2 -2
  9. package/dist/bridge/drivers/omp.js +1 -1
  10. package/dist/bridge/drivers/opencode.js +2 -2
  11. package/dist/bridge/drivers/qwen.js +3 -3
  12. package/dist/bridge/index.js +2 -2
  13. package/dist/bridge/src/drivers/echo.d.ts.map +1 -1
  14. package/dist/{chunk-DEBMR6MK.js → chunk-EAJWXVQL.js} +2 -2
  15. package/dist/{chunk-DEBMR6MK.js.map → chunk-EAJWXVQL.js.map} +1 -1
  16. package/dist/{chunk-YNEJXDCZ.js → chunk-JLJ3OMHR.js} +93 -18
  17. package/dist/chunk-JLJ3OMHR.js.map +1 -0
  18. package/dist/{chunk-APHTT5GE.js → chunk-KF3KDVKT.js} +2 -2
  19. package/dist/{chunk-APHTT5GE.js.map → chunk-KF3KDVKT.js.map} +1 -1
  20. package/dist/{chunk-6XQ5QG63.js → chunk-NQD7INSF.js} +4 -4
  21. package/dist/{chunk-6XQ5QG63.js.map → chunk-NQD7INSF.js.map} +1 -1
  22. package/dist/{chunk-LVQO4X4U.js → chunk-T5XXWWHT.js} +3 -3
  23. package/dist/{chunk-LVQO4X4U.js.map → chunk-T5XXWWHT.js.map} +1 -1
  24. package/dist/{chunk-FRD4NU3W.js → chunk-XVWK3VHH.js} +3 -3
  25. package/dist/{chunk-FRD4NU3W.js.map → chunk-XVWK3VHH.js.map} +1 -1
  26. package/dist/cli/index.js +5 -5
  27. package/dist/factory-assets/connectors/flow/run-flow.js +1 -1
  28. package/dist/runner/index.js +3 -3
  29. package/dist/runner/src/serve.d.ts +27 -0
  30. package/dist/runner/src/serve.d.ts.map +1 -1
  31. package/dist/sdk/bridge.js +2 -2
  32. package/dist/sdk/index.js +3 -3
  33. package/dist/sdk/runner.js +3 -3
  34. package/dist/{setup-H3WCLOEH.js → setup-M6QZBZSE.js} +4 -4
  35. package/dist/{setup-H3WCLOEH.js.map → setup-M6QZBZSE.js.map} +1 -1
  36. package/dist/tui/index.js +3 -3
  37. package/package.json +1 -1
  38. package/dist/chunk-YNEJXDCZ.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,42 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.10.2
4
+
5
+ ### Patch Changes
6
+
7
+ - [#406](https://github.com/skaile-ai/workspaces/pull/406) [`975dc26`](https://github.com/skaile-ai/workspaces/commit/975dc263aa581e9189e540afcb4afa6b15bbed48) Thanks [@peteralbert](https://github.com/peteralbert)! - Fix the HITL approve path: `applyApproval` / `applyInput` / `retryNode` now kick
8
+ a resume turn with the correct typed stimulus (workspaces#404). Previously an
9
+ approved gate could hang forever — the approved branch records the decision but
10
+ leaves `status = awaiting_approval` and relied on the generic
11
+ `mutate() -> computeStimulus() -> bus.signal()` path, which flattens everything
12
+ to `state_changed` and (for approvals, which leave `status`/`focus`/`done`
13
+ unchanged) can drop the signal entirely, so no turn was kicked.
14
+
15
+ The runner's `connector_mutate` dispatch now emits an explicit typed stimulus
16
+ (`approval_received` / `input_received` / `retry_requested`) after applying the
17
+ op, fire-and-forget — mirroring the op:start `flow_started` kick ([#399](https://github.com/skaile-ai/workspaces/issues/399)). This
18
+ also gives the agent the correct resume guidance instead of a bare
19
+ `state_changed`. `driveTurn` reconstructs those kinds and, when signals coalesce,
20
+ prefers the most-specific stimulus in the batch so a trailing `state_changed`
21
+ can't mask the resume stimulus. Reject/input/retry paths are unchanged. No
22
+ protocol/envelope/flow-contract change. (The underlying shared-reference quirk in
23
+ `FlowAdapter.mutate()` is tracked separately in [#405](https://github.com/skaile-ai/workspaces/issues/405); this fix is correct
24
+ independent of it.)
25
+
26
+ ## 1.10.1
27
+
28
+ ### Patch Changes
29
+
30
+ - [#402](https://github.com/skaile-ai/workspaces/pull/402) [`f717cf3`](https://github.com/skaile-ai/workspaces/commit/f717cf39cdbf02f2878723f18f4592bbee4f8602) Thanks [@peteralbert](https://github.com/peteralbert)! - Make `[test-flow]` scripted-driver arming robust to host message decoration
31
+ (workspaces#401). Hosts decorate user messages (e.g. the platform prepends a
32
+ `<SESSION_MEMBERS>` block and a wake-restoration preamble), so the previous
33
+ message-anchored match (`/^\s*\[test-flow\]/`) never fired and the scripted
34
+ driver silently failed to arm. Detection is now line-anchored: the echo driver
35
+ arms when a line **begins** with the exact `[test-flow]` token (leading
36
+ whitespace allowed) anywhere in the composed prompt, with the optional JSON
37
+ script on that same line. This is decoration-independent yet still impossible to
38
+ arm from ordinary prose (a line must start with the token). No contract change.
39
+
3
40
  ## 1.10.0
4
41
 
5
42
  ### Minor Changes
@@ -2,7 +2,7 @@ import { SUPPORTED_CLOUDS, buildClaudeCloudEnv } from '../../chunk-ISQWMBKD.js';
2
2
  import { dispatchCapability } from '../../chunk-RRVQAE5D.js';
3
3
  import { fetchProviderModels } from '../../chunk-BMQKMOQY.js';
4
4
  import { AuthError, classifyClaudeSdkError, reclassifyAuthAsAccountUnavailable, AccountUnavailableError } from '../../chunk-GAH4YRCI.js';
5
- import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-APHTT5GE.js';
5
+ import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
6
6
  import '../../chunk-6E6PKKAD.js';
7
7
  import '../../chunk-JB35MVBN.js';
8
8
  import '../../chunk-NSBPE2FW.js';
@@ -1,6 +1,6 @@
1
1
  import { fetchProviderModels } from '../../chunk-BMQKMOQY.js';
2
2
  import { classifyGenericErrorMessage } from '../../chunk-GAH4YRCI.js';
3
- import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-APHTT5GE.js';
3
+ import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
4
4
  import '../../chunk-6E6PKKAD.js';
5
5
  import '../../chunk-JB35MVBN.js';
6
6
  import '../../chunk-NSBPE2FW.js';
@@ -1,6 +1,6 @@
1
- import { SubprocessCliDriver, mapApiKeysToEnv, extractText, extractCost, extractTokens } from '../../chunk-FRD4NU3W.js';
1
+ import { SubprocessCliDriver, mapApiKeysToEnv, extractText, extractCost, extractTokens } from '../../chunk-XVWK3VHH.js';
2
2
  import '../../chunk-GAH4YRCI.js';
3
- import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-APHTT5GE.js';
3
+ import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
4
4
  import '../../chunk-6E6PKKAD.js';
5
5
  import '../../chunk-JB35MVBN.js';
6
6
  import '../../chunk-NSBPE2FW.js';
@@ -1,5 +1,5 @@
1
1
  import { dispatchCapability } from '../../chunk-RRVQAE5D.js';
2
- import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-APHTT5GE.js';
2
+ import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
3
3
  import '../../chunk-6E6PKKAD.js';
4
4
  import '../../chunk-JB35MVBN.js';
5
5
  import '../../chunk-NSBPE2FW.js';
@@ -186,7 +186,7 @@ var EchoDriver = class extends AgentDriver {
186
186
  const content = message.toLowerCase();
187
187
  this.log.info("received prompt", { preview: message.slice(0, 80), length: message.length });
188
188
  await new Promise((resolve) => setTimeout(resolve, 200));
189
- const flowMatch = /^\s*\[test-flow\]\s*(.*)$/s.exec(message);
189
+ const flowMatch = /^[ \t]*\[test-flow\][ \t]*(.*)$/m.exec(message);
190
190
  if (flowMatch) {
191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O;AAEL,IAAA,MAAM,OAAA,GACJ,6BAA6B,cAAc,CAAA,2GAAA,CAAA;AAE7C,IAAA,MAAA,CAAO,IAAA,CAAK,GAAG,aAAA,CAAc,OAAO,CAAC,CAAA;AAAA,EACvC;AAEA,EAAA,OAAO,MAAA;AACT;AAMO,IAAM,gBAAA,GAA8C;AAAA,EACzD,EAAA,EAAI,MAAA;AAAA,EACJ,WAAA,EAAa,sBAAA,CAAuB,IAAA,EAAM,IAAA,IAAQ,iBAAA;AAAA,EAClD,UAAA,EAAY,CAAA;AAAA;AAAA,EAEZ,YAAA,EAAgB,CAAA,CAAA,MAAA,CAAoB,MAAM,IAAI,CAAA;AAAA,EAC9C,QAAQ,OAAO,MAAA,EAAQ,IAAA,KAAS,IAAI,WAAW,MAAM,CAAA;AAAA,EACrD,UAAA,EAAY,OAAO,OAAA,KACjB,IAAI,WAAW,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,IAAO,SAAA,EAAW,YAAA,EAAc,OAAA,EAAS,EAAE,UAAA;AAC7E","file":"echo.js","sourcesContent":["/**\n * Scripted-flow decision logic for the echo driver.\n *\n * Pure, deterministic policy that maps a live {@link FlowExecution} snapshot\n * (plus an optional per-node script) to the single next flow-adapter mutation\n * the driver should emit this iteration. The echo driver calls this in a loop\n * per turn (see `echo.ts`), executing each returned action against the\n * runner-injected {@link FlowTestDriverHook} until it yields (`null`) or emits\n * a turn-ending action.\n *\n * The policy mirrors what a real LLM orchestrator would do, but without an\n * LLM: it reacts to state each turn, so a host can drive a flow to `complete`,\n * park it at an approval/input gate, and exercise the reject/recover path\n * simply by applying host mutations (`applyApproval`, `applyInput`, …) between\n * turns. No new protocol, no flow-contract change — it only calls the existing\n * FlowAdapter agent-tool operations.\n *\n * @docLink packages/bridge/drivers#scripted-flow\n * @since 3.6.0\n */\n\nimport type { FlowExecution, NodeExecution } from \"@skaile/workspaces/types\";\n\n/**\n * What the scripted driver should do when a node reaches its decision point.\n *\n * - `auto` (default): follow the flow's `autonomousMode` — `complete_node`\n * when autonomous, else `request_approval`.\n * - `complete`: always `complete_node` (autonomous-style, even if the flow's\n * autonomousMode is false — the adapter allows it only when autonomous, so\n * use with autonomous flows).\n * - `approve`: always `request_approval` (park at an approval gate).\n * - `input`: `request_input` once; after the host applies input, fall back to\n * `auto` behaviour.\n * - `skip`: `skip_node` (optional nodes only).\n * - `fail`: `fail_node`. With `recoverable: false` (default) this is terminal.\n * With `recoverable: true` the node returns to `available`; the driver\n * re-emits the recoverable failure `failCount` times (default 1) and then\n * proceeds as `auto` — it never deadlocks on a recoverable fail.\n */\nexport type OnRun = \"auto\" | \"complete\" | \"approve\" | \"input\" | \"skip\" | \"fail\";\n\n/**\n * What to do when a node returns to `available` after a rejection.\n *\n * - `retry` (default): re-drive it — `start_node` again, then its `onRun`.\n * - `fail`: `fail_node(recoverable: false)` — exercises the terminal path.\n */\nexport type OnReject = \"retry\" | \"fail\";\n\n/** Per-node scripting directive. All fields optional. */\nexport interface FlowNodeDirective {\n onRun?: OnRun;\n onReject?: OnReject;\n /** For `onRun: \"input\"` — the input request shown to the host. */\n input?: { prompt?: string; schema?: unknown };\n /** For `onRun: \"fail\"` — whether the failure is recoverable. Default false. */\n recoverable?: boolean;\n /**\n * For `onRun: \"fail\"` with `recoverable: true` — how many recoverable\n * failures to emit before the node proceeds as `auto`. Default 1. Counted\n * from the node's own `errorHistory`, so the policy stays a pure function of\n * state (no driver-instance bookkeeping) and never deadlocks.\n */\n failCount?: number;\n /** Summary text used for `complete_node` / `request_approval` / failures. */\n summary?: string;\n}\n\n/**\n * A scripted-flow program. Empty (`{}`) means \"canonical policy\": start each\n * available node, then complete (autonomous) or request approval (interactive)\n * — enough to drive the autonomous-complete, approval-gate, and reject/recover\n * scenarios with no per-node scripting at all.\n */\nexport interface FlowScript {\n /** Per-node overrides, keyed by node id. */\n nodes?: Record<string, FlowNodeDirective>;\n /** Fallback directive for any node without its own entry. */\n default?: FlowNodeDirective;\n}\n\n/** A single flow-adapter mutation the driver will execute. */\nexport type FlowAction =\n | { op: \"start_node\"; nodeId: string }\n | { op: \"complete_node\"; nodeId: string; summary: string }\n | { op: \"request_approval\"; nodeId: string; summary: string }\n | { op: \"request_input\"; nodeId: string; prompt: string; schema: string }\n | { op: \"skip_node\"; nodeId: string }\n | { op: \"fail_node\"; nodeId: string; message: string; recoverable: boolean };\n\n/** Ops that end the agent turn (the runner yields until the host acts). */\nconst TURN_ENDING: ReadonlySet<FlowAction[\"op\"]> = new Set([\n \"request_approval\",\n \"request_input\",\n \"fail_node\",\n]);\n\n/** Whether an action ends the turn (driver stops looping after emitting it). */\nexport function isTurnEnding(action: FlowAction): boolean {\n return TURN_ENDING.has(action.op);\n}\n\n/** Map a {@link FlowAction} to the `executeOp` argument bag the adapter expects. */\nexport function actionArgs(action: FlowAction): Record<string, unknown> {\n switch (action.op) {\n case \"start_node\":\n case \"skip_node\":\n return { nodeId: action.nodeId };\n case \"complete_node\":\n return { nodeId: action.nodeId, summary: action.summary };\n case \"request_approval\":\n return { nodeId: action.nodeId, summary: action.summary };\n case \"request_input\":\n return { nodeId: action.nodeId, prompt: action.prompt, schema: action.schema };\n case \"fail_node\":\n return {\n nodeId: action.nodeId,\n message: action.message,\n recoverable: String(action.recoverable),\n };\n }\n}\n\nfunction summaryFor(d: FlowNodeDirective, n: NodeExecution): string {\n return d.summary ?? `Scripted output for ${n.id}`;\n}\n\n/**\n * Decide the single next flow action for the current state, or `null` to yield\n * (nothing to do this iteration — wait for a host mutation).\n *\n * Priority order: resolve approved gates → advance running nodes → start (or\n * skip / terminally-fail) available nodes. Terminal flow states and gates with\n * no decision / input yet yield.\n *\n * Pure — the fail bookkeeping (how many recoverable failures a node has already\n * emitted) is read from the node's own `errorHistory`, so no external counter is\n * needed and a recoverable `fail` directive can never deadlock.\n */\nexport function decideFlowAction(state: FlowExecution, script: FlowScript): FlowAction | null {\n // Terminal flow — never fight a completed/failed/cancelled run.\n if (state.status === \"complete\" || state.status === \"failed\" || state.status === \"cancelled\") {\n return null;\n }\n\n const dir = (id: string): FlowNodeDirective => script.nodes?.[id] ?? script.default ?? {};\n const nodes = Object.values(state.nodes);\n\n // 1. Approved gate → complete.\n for (const n of nodes) {\n if (n.status === \"awaiting_approval\" && n.approval?.decision === \"approved\") {\n return { op: \"complete_node\", nodeId: n.id, summary: summaryFor(dir(n.id), n) };\n }\n }\n\n // 2. Running node → per directive.\n for (const n of nodes) {\n if (n.status !== \"running\") continue;\n const d = dir(n.id);\n const onRun: OnRun = d.onRun ?? \"auto\";\n const resolved: OnRun =\n onRun === \"auto\" ? (state.autonomousMode ? \"complete\" : \"approve\") : onRun;\n\n if (resolved === \"complete\") {\n return { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n if (resolved === \"approve\") {\n return { op: \"request_approval\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n if (resolved === \"input\") {\n const lastInput = n.inputHistory[n.inputHistory.length - 1];\n if (lastInput && lastInput.response !== undefined) {\n // Input already provided — proceed as if `auto`.\n return state.autonomousMode\n ? { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) }\n : { op: \"request_approval\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n return {\n op: \"request_input\",\n nodeId: n.id,\n prompt: d.input?.prompt ?? `Provide input for ${n.id}`,\n schema: JSON.stringify(d.input?.schema ?? { kind: \"text\" }),\n };\n }\n if (resolved === \"fail\") {\n const recoverable = d.recoverable ?? false;\n if (!recoverable) {\n // Terminal fail — the adapter marks node + flow `failed`, so the\n // terminal-status guard above stops any re-fire on later turns.\n return {\n op: \"fail_node\",\n nodeId: n.id,\n message: d.summary ?? `Scripted failure for ${n.id}`,\n recoverable: false,\n };\n }\n // Recoverable fail — emit up to `failCount` times (counting the node's\n // own recorded recoverable errors), then proceed as `auto` so the node\n // is not stranded in a re-drive loop.\n const emitted = n.errorHistory.filter((e) => e.recoverable).length;\n const failCount = Math.max(1, d.failCount ?? 1);\n if (emitted < failCount) {\n return {\n op: \"fail_node\",\n nodeId: n.id,\n message: d.summary ?? `Scripted recoverable failure for ${n.id}`,\n recoverable: true,\n };\n }\n return state.autonomousMode\n ? { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) }\n : { op: \"request_approval\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n // `skip` while running is illegal; complete instead to avoid a deadlock.\n return { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n\n // 3. Available node → terminally-fail (post-reject), skip, or start.\n for (const n of nodes) {\n if (n.status !== \"available\") continue;\n const d = dir(n.id);\n const lastApproval = n.approvalHistory[n.approvalHistory.length - 1];\n if (lastApproval?.decision === \"rejected\" && d.onReject === \"fail\") {\n return {\n op: \"fail_node\",\n nodeId: n.id,\n message: d.summary ?? `Rejected and not recoverable: ${n.id}`,\n recoverable: false,\n };\n }\n if (d.onRun === \"skip\") {\n return { op: \"skip_node\", nodeId: n.id };\n }\n return { op: \"start_node\", nodeId: n.id };\n }\n\n // 4. Nothing actionable — awaiting_approval (no decision), awaiting_input\n // (no response), or fully drained. Yield.\n return null;\n}\n\n/**\n * Parse a `[test-flow]` sentinel body into a {@link FlowScript}. An empty body\n * yields the canonical (empty) script. Malformed JSON is a hard error so tests\n * fail loudly rather than silently running the wrong policy.\n */\nexport function parseFlowScript(body: string): FlowScript {\n const trimmed = body.trim();\n if (trimmed.length === 0) return {};\n const parsed: unknown = JSON.parse(trimmed);\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"flow script must be a JSON object\");\n }\n return parsed as FlowScript;\n}\n","import type { DriverTarget } from \"@skaile/workspaces/plugin-registry\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { dispatchCapability } from \"../capability-dispatch.js\";\nimport { getBridgeLogger } from \"../logger.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport {\n type AgentConfig,\n AgentDriver,\n type AgentEvent,\n type BridgeCapabilityTool,\n type DriverInfo,\n} from \"../types.js\";\nimport {\n actionArgs,\n type FlowScript,\n decideFlowAction,\n isTurnEnding,\n parseFlowScript,\n} from \"./flow-script.js\";\n\n/**\n * Echo/mock driver for E2E testing in docker mode.\n *\n * Runs inside a real Docker container with real WebSocket transport and\n * session lifecycle, but generates deterministic keyword-triggered responses\n * instead of calling the Anthropic API. This lets E2E tests exercise the\n * full infrastructure (containers, WebSocket, session management, message\n * persistence) without needing real AI credentials.\n *\n * Keyword triggers match the MockAgentClient in\n * `platform/backend/libs/agent-gateway/src/mock-agent-client.ts` — the\n * same test messages (\"test toolcall\", \"test question\", etc.) produce\n * the same events.\n *\n * Enable by setting `SKAILE_AGENT_DRIVER=echo` in the container env,\n * or by passing `{ driver: 'echo' }` in the runner config.\n *\n * @docLink packages/bridge/drivers#echo-driver\n */\nexport class EchoDriver extends AgentDriver {\n readonly driverInfo: DriverInfo = {\n id: \"echo\",\n name: \"Echo (E2E mock)\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n };\n\n private readonly log: Logger = getBridgeLogger(\"echo\");\n private running = false;\n private readonly config: AgentConfig;\n\n /**\n * Scripted-flow mode state (workspaces#396). Enabled by a `[test-flow]`\n * sentinel chat message; once on, orchestrator-prompt turns are driven\n * deterministically against `config.flowTestDriver`. `null` script ⇒ mode\n * off (default echo behaviour, unchanged).\n */\n private flowScript: FlowScript | null = null;\n\n constructor(config: AgentConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Test surface: returns the tool list the LLM would see for this turn.\n * Composition: the registry hooks (Protocol v2) take precedence; legacy\n * `mcpServers` is not enumerated here (the echo driver never exposed MCP\n * tools to the LLM by name).\n */\n listCapabilityTools(): BridgeCapabilityTool[] {\n return this.config.capabilities?.composeTools() ?? [];\n }\n\n /**\n * Test surface: invoke a registered capability through the dispatch\n * helper. Mirrors what a real driver would do when the LLM produced a\n * tool_use for the given name — applies fire-and-forget, render emission,\n * and fallback text. Returns the structured dispatch result so tests can\n * assert immediate-vs-background resolution.\n */\n async invokeCapabilityForTest(\n name: string,\n input: unknown,\n ): Promise<{ result: unknown; background: boolean }> {\n const hooks = this.config.capabilities;\n if (!hooks) throw new Error(\"EchoDriver: no capability hooks configured\");\n const callId = `echo-cap-${Date.now()}`;\n const out = await dispatchCapability(hooks, callId, name, input, (err) =>\n this.log.warn(\"background capability handler failed\", {\n name,\n error: String(err),\n }),\n );\n return out;\n }\n\n async start(): Promise<void> {\n this.running = true;\n this.log.info(\"driver started\");\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.running) return;\n const content = message.toLowerCase();\n this.log.info(\"received prompt\", { preview: message.slice(0, 80), length: message.length });\n\n // Small delay to simulate real agent processing\n await new Promise((resolve) => setTimeout(resolve, 200));\n\n // Scripted-flow test seam (workspaces#396) — a `[test-flow]` sentinel\n // arms deterministic flow driving for this session and (optionally)\n // carries a JSON script. Format: `[test-flow] {json}`; empty body ⇒\n // canonical policy. Must be handled before the flow-turn branch below.\n const flowMatch = /^\\s*\\[test-flow\\]\\s*(.*)$/s.exec(message);\n if (flowMatch) {\n let summary: string;\n try {\n this.flowScript = parseFlowScript(flowMatch[1] ?? \"\");\n summary = \"echo[test-flow]: scripted-flow mode armed\";\n } catch (err) {\n this.flowScript = null;\n summary = `echo[test-flow]: invalid script — ${err instanceof Error ? err.message : String(err)}`;\n this.emit(\"agent-event\", { type: \"error\", error: summary, fatal: false });\n }\n for (const event of textAndResult(summary)) this.emit(\"agent-event\", event);\n this.emit(\"agent-event\", { type: \"agent_end\" });\n return;\n }\n\n // Scripted-flow turn — the runner reassembles the orchestrator prompt on\n // every flow turn; when scripted-flow mode is armed and a flow driver hook\n // is present, drive nodes deterministically instead of echoing text.\n if (this.flowScript && this.config.flowTestDriver && isFlowTurn(message)) {\n await this.runScriptedFlowTurn();\n return;\n }\n\n // Phase 7B test seam — explicit capability invocation keyword. Lets E2E\n // tests drive `dispatchCapability` from a chat prompt without a real LLM.\n // Format: `[test-cap:<name>] {json}`. Anything after the closing bracket\n // is parsed as JSON input; on parse error we fall back to `{}`.\n const capMatch = /^\\s*\\[test-cap:([\\w.\\-_]+)\\]\\s*(.*)$/s.exec(message);\n if (capMatch) {\n const name = capMatch[1] ?? \"\";\n const rawInput = (capMatch[2] ?? \"\").trim();\n let input: unknown = {};\n if (rawInput.length > 0) {\n try {\n input = JSON.parse(rawInput);\n } catch (err) {\n this.log.warn(\"test-cap input was not valid JSON; defaulting to {}\", {\n error: String(err),\n preview: rawInput.slice(0, 80),\n });\n }\n }\n const events = await this.runCapabilityKeyword(name, input);\n for (const event of events) {\n this.emit(\"agent-event\", event);\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n this.emit(\"agent-event\", { type: \"agent_end\" });\n return;\n }\n\n const events = buildEchoEvents(content, message);\n for (const event of events) {\n this.emit(\"agent-event\", event);\n // Small gap between events to let the transport process each one\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n // Signal turn completion — the runner waits for this before accepting\n // the next prompt. Without it, the runner stays stuck after the first message.\n this.emit(\"agent-event\", { type: \"agent_end\" });\n }\n\n /**\n * Phase 7B helper — drive a single capability through the dispatcher and\n * surface the structured outcome as a result event the LLM-side test code\n * can assert against. Used exclusively by the `[test-cap:<name>]` prompt\n * keyword above; never wired into normal chat flow.\n */\n private async runCapabilityKeyword(name: string, input: unknown): Promise<AgentEvent[]> {\n const events: AgentEvent[] = [];\n if (!this.config.capabilities) {\n return textAndResult(`echo[test-cap]: no capability hooks configured (skipping ${name})`);\n }\n try {\n const out = await this.invokeCapabilityForTest(name, input);\n const summary = `echo[test-cap]: invoked ${name} background=${String(out.background)} result=${safeStringify(out.result)}`;\n events.push(...textAndResult(summary));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n events.push({\n type: \"error\",\n error: `echo[test-cap]: ${name} failed: ${msg}`,\n fatal: false,\n });\n events.push(...textAndResult(`echo[test-cap]: ${name} errored (${msg})`));\n }\n return events;\n }\n\n /**\n * Scripted-flow turn (workspaces#396). Reads the live flow state via the\n * runner-injected `flowTestDriver` hook and executes the scripted next\n * action(s) until the policy yields or emits a turn-ending action. Each\n * mutation fires the adapter's `onChange` (→ host `state_changed`) and, when\n * the runner wires the stimulus bus, queues the follow-up turn — so the\n * driver advances one step at a time exactly like a real LLM orchestrator.\n */\n private async runScriptedFlowTurn(): Promise<void> {\n const hook = this.config.flowTestDriver;\n const script = this.flowScript;\n if (!hook || !script) {\n this.emit(\"agent-event\", { type: \"agent_end\" });\n return;\n }\n\n const executed: string[] = [];\n // Hard cap — the policy is monotonic, but never let a bug spin forever.\n const MAX_STEPS = 200;\n for (let i = 0; i < MAX_STEPS; i++) {\n const state = hook.getState();\n if (!state) break;\n const action = decideFlowAction(state, script);\n if (!action) break;\n\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name: action.op,\n tool: { name: action.op },\n input: action.nodeId,\n });\n try {\n await hook.execute(action.op, actionArgs(action));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log.warn(\"scripted flow op failed\", {\n op: action.op,\n nodeId: action.nodeId,\n error: msg,\n });\n this.emit(\"agent-event\", {\n type: \"error\",\n error: `echo[test-flow]: ${action.op}(${action.nodeId}) failed: ${msg}`,\n fatal: false,\n });\n break;\n }\n this.emit(\"agent-event\", { type: \"tool_execution_end\", toolName: action.op });\n executed.push(`${action.op}(${action.nodeId})`);\n if (isTurnEnding(action)) break;\n }\n\n const summary =\n executed.length > 0\n ? `echo[test-flow]: ${executed.join(\" → \")}`\n : \"echo[test-flow]: no action (yielding to host)\";\n for (const event of textAndResult(summary)) this.emit(\"agent-event\", event);\n this.emit(\"agent-event\", { type: \"agent_end\" });\n }\n\n async abort(): Promise<void> {\n this.log.info(\"abort requested\");\n }\n\n kill(): void {\n this.running = false;\n this.log.info(\"killed\");\n }\n\n async resetSession(): Promise<void> {\n this.log.info(\"session reset\");\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Echo response generation — mirrors MockAgentClient.buildMockEvents\n// ---------------------------------------------------------------------------\n\n/**\n * A flow turn is recognised by the orchestrator prompt's stable header\n * (`buildOrchestratorPrompt` in the flow connector). Detection is header-only —\n * the driver reads live state through the injected hook, never by parsing the\n * prompt body.\n */\nfunction isFlowTurn(message: string): boolean {\n return message.startsWith(\"# Flow Execution Context\");\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\nfunction textAndResult(summary: string): AgentEvent[] {\n return [\n {\n type: \"message_start\",\n message: { role: \"assistant\", content: summary },\n },\n {\n type: \"message_end\",\n message: { role: \"assistant\", content: summary },\n },\n {\n type: \"result\",\n subtype: \"success\",\n summary,\n costUsd: 0,\n },\n ];\n}\n\nfunction buildEchoEvents(content: string, originalPrompt: string): AgentEvent[] {\n const events: AgentEvent[] = [];\n\n if (content.includes(\"test all\")) {\n events.push(\n { type: \"tool_call\", name: \"Read\", tool: { name: \"Read\" }, input: \"prisma/schema.prisma\" },\n { type: \"tool_execution_end\", toolName: \"Read\" },\n {\n type: \"tool_call\",\n name: \"Write\",\n tool: { name: \"Write\" },\n input: \"src/modules/sprint/sprint.service.ts\",\n },\n { type: \"tool_execution_end\", toolName: \"Write\" },\n );\n events.push(\n ...textAndResult(\n \"All operations completed successfully. Created sprint service, updated schema, started dev server, and ran E2E tests.\",\n ),\n );\n } else if (content.includes(\"test toolcall\")) {\n events.push(\n {\n type: \"tool_call\",\n name: \"Read\",\n tool: { name: \"Read\" },\n input: \"platform/prisma/schema.prisma\",\n },\n { type: \"tool_execution_end\", toolName: \"Read\" },\n );\n events.push(\n ...textAndResult(\n \"I've read the schema and found 42 models. The data model looks well-structured.\",\n ),\n );\n } else if (content.includes(\"test question\")) {\n // Emit a message that asks the user a question (the runner normalizer\n // converts this to a `question` AgentEvent for the transport layer)\n events.push(\n ...textAndResult(\n \"The blueprint calls for a relational database. Which engine should I target? \" +\n \"This will affect the Prisma provider, Docker Compose setup, and the connection string.\\n\\n\" +\n \"Options: PostgreSQL, MySQL, SQLite\",\n ),\n );\n } else if (content.includes(\"test error\")) {\n events.push({\n type: \"error\",\n error:\n \"AI provider returned HTTP 429 — rate limit exceeded. The request will be retried automatically in 35 seconds.\",\n fatal: false,\n });\n } else if (content.includes(\"test fatal\")) {\n events.push({\n type: \"error\",\n error:\n \"Session agent was killed by the container runtime (OOM — memory limit 2 GB exceeded). The session cannot continue.\",\n fatal: true,\n });\n } else {\n // Default echo response\n const summary =\n `I received your message: \"${originalPrompt}\". I'm the Skaile AI assistant running in echo mode. ` +\n `This is a deterministic mock response for E2E testing.`;\n events.push(...textAndResult(summary));\n }\n\n return events;\n}\n\n/**\n * `DriverTarget` wrapper for the echo driver. Registered into the plugin\n * registry by `registerBuiltinDrivers()`.\n */\nexport const echoDriverTarget: DriverTarget<AgentConfig> = {\n id: \"echo\",\n displayName: BUILTIN_DRIVER_CATALOG.echo?.name ?? \"Echo (E2E mock)\",\n apiVersion: 1,\n // Drivers take AgentConfig; passthrough — full schema validation is out of scope.\n configSchema: z.custom<AgentConfig>(() => true),\n create: async (config, _ctx) => new EchoDriver(config),\n listModels: async (apiKeys) =>\n new EchoDriver({ cwd: process.cwd(), sessionId: \"model-list\", apiKeys }).listModels(),\n};\n"]}
1
+ {"version":3,"sources":["../../../bridge/src/drivers/flow-script.ts","../../../bridge/src/drivers/echo.ts"],"names":["events"],"mappings":";;;;;;;;AA4FA,IAAM,WAAA,uBAAiD,GAAA,CAAI;AAAA,EACzD,kBAAA;AAAA,EACA,eAAA;AAAA,EACA;AACF,CAAC,CAAA;AAGM,SAAS,aAAa,MAAA,EAA6B;AACxD,EAAA,OAAO,WAAA,CAAY,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA;AAClC;AAGO,SAAS,WAAW,MAAA,EAA6C;AACtE,EAAA,QAAQ,OAAO,EAAA;AAAI,IACjB,KAAK,YAAA;AAAA,IACL,KAAK,WAAA;AACH,MAAA,OAAO,EAAE,MAAA,EAAQ,MAAA,CAAO,MAAA,EAAO;AAAA,IACjC,KAAK,eAA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,KACjB,IAAI,WAAW,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,IAAO,SAAA,EAAW,YAAA,EAAc,OAAA,EAAS,EAAE,UAAA;AAC7E","file":"echo.js","sourcesContent":["/**\n * Scripted-flow decision logic for the echo driver.\n *\n * Pure, deterministic policy that maps a live {@link FlowExecution} snapshot\n * (plus an optional per-node script) to the single next flow-adapter mutation\n * the driver should emit this iteration. The echo driver calls this in a loop\n * per turn (see `echo.ts`), executing each returned action against the\n * runner-injected {@link FlowTestDriverHook} until it yields (`null`) or emits\n * a turn-ending action.\n *\n * The policy mirrors what a real LLM orchestrator would do, but without an\n * LLM: it reacts to state each turn, so a host can drive a flow to `complete`,\n * park it at an approval/input gate, and exercise the reject/recover path\n * simply by applying host mutations (`applyApproval`, `applyInput`, …) between\n * turns. No new protocol, no flow-contract change — it only calls the existing\n * FlowAdapter agent-tool operations.\n *\n * @docLink packages/bridge/drivers#scripted-flow\n * @since 3.6.0\n */\n\nimport type { FlowExecution, NodeExecution } from \"@skaile/workspaces/types\";\n\n/**\n * What the scripted driver should do when a node reaches its decision point.\n *\n * - `auto` (default): follow the flow's `autonomousMode` — `complete_node`\n * when autonomous, else `request_approval`.\n * - `complete`: always `complete_node` (autonomous-style, even if the flow's\n * autonomousMode is false — the adapter allows it only when autonomous, so\n * use with autonomous flows).\n * - `approve`: always `request_approval` (park at an approval gate).\n * - `input`: `request_input` once; after the host applies input, fall back to\n * `auto` behaviour.\n * - `skip`: `skip_node` (optional nodes only).\n * - `fail`: `fail_node`. With `recoverable: false` (default) this is terminal.\n * With `recoverable: true` the node returns to `available`; the driver\n * re-emits the recoverable failure `failCount` times (default 1) and then\n * proceeds as `auto` — it never deadlocks on a recoverable fail.\n */\nexport type OnRun = \"auto\" | \"complete\" | \"approve\" | \"input\" | \"skip\" | \"fail\";\n\n/**\n * What to do when a node returns to `available` after a rejection.\n *\n * - `retry` (default): re-drive it — `start_node` again, then its `onRun`.\n * - `fail`: `fail_node(recoverable: false)` — exercises the terminal path.\n */\nexport type OnReject = \"retry\" | \"fail\";\n\n/** Per-node scripting directive. All fields optional. */\nexport interface FlowNodeDirective {\n onRun?: OnRun;\n onReject?: OnReject;\n /** For `onRun: \"input\"` — the input request shown to the host. */\n input?: { prompt?: string; schema?: unknown };\n /** For `onRun: \"fail\"` — whether the failure is recoverable. Default false. */\n recoverable?: boolean;\n /**\n * For `onRun: \"fail\"` with `recoverable: true` — how many recoverable\n * failures to emit before the node proceeds as `auto`. Default 1. Counted\n * from the node's own `errorHistory`, so the policy stays a pure function of\n * state (no driver-instance bookkeeping) and never deadlocks.\n */\n failCount?: number;\n /** Summary text used for `complete_node` / `request_approval` / failures. */\n summary?: string;\n}\n\n/**\n * A scripted-flow program. Empty (`{}`) means \"canonical policy\": start each\n * available node, then complete (autonomous) or request approval (interactive)\n * — enough to drive the autonomous-complete, approval-gate, and reject/recover\n * scenarios with no per-node scripting at all.\n */\nexport interface FlowScript {\n /** Per-node overrides, keyed by node id. */\n nodes?: Record<string, FlowNodeDirective>;\n /** Fallback directive for any node without its own entry. */\n default?: FlowNodeDirective;\n}\n\n/** A single flow-adapter mutation the driver will execute. */\nexport type FlowAction =\n | { op: \"start_node\"; nodeId: string }\n | { op: \"complete_node\"; nodeId: string; summary: string }\n | { op: \"request_approval\"; nodeId: string; summary: string }\n | { op: \"request_input\"; nodeId: string; prompt: string; schema: string }\n | { op: \"skip_node\"; nodeId: string }\n | { op: \"fail_node\"; nodeId: string; message: string; recoverable: boolean };\n\n/** Ops that end the agent turn (the runner yields until the host acts). */\nconst TURN_ENDING: ReadonlySet<FlowAction[\"op\"]> = new Set([\n \"request_approval\",\n \"request_input\",\n \"fail_node\",\n]);\n\n/** Whether an action ends the turn (driver stops looping after emitting it). */\nexport function isTurnEnding(action: FlowAction): boolean {\n return TURN_ENDING.has(action.op);\n}\n\n/** Map a {@link FlowAction} to the `executeOp` argument bag the adapter expects. */\nexport function actionArgs(action: FlowAction): Record<string, unknown> {\n switch (action.op) {\n case \"start_node\":\n case \"skip_node\":\n return { nodeId: action.nodeId };\n case \"complete_node\":\n return { nodeId: action.nodeId, summary: action.summary };\n case \"request_approval\":\n return { nodeId: action.nodeId, summary: action.summary };\n case \"request_input\":\n return { nodeId: action.nodeId, prompt: action.prompt, schema: action.schema };\n case \"fail_node\":\n return {\n nodeId: action.nodeId,\n message: action.message,\n recoverable: String(action.recoverable),\n };\n }\n}\n\nfunction summaryFor(d: FlowNodeDirective, n: NodeExecution): string {\n return d.summary ?? `Scripted output for ${n.id}`;\n}\n\n/**\n * Decide the single next flow action for the current state, or `null` to yield\n * (nothing to do this iteration — wait for a host mutation).\n *\n * Priority order: resolve approved gates → advance running nodes → start (or\n * skip / terminally-fail) available nodes. Terminal flow states and gates with\n * no decision / input yet yield.\n *\n * Pure — the fail bookkeeping (how many recoverable failures a node has already\n * emitted) is read from the node's own `errorHistory`, so no external counter is\n * needed and a recoverable `fail` directive can never deadlock.\n */\nexport function decideFlowAction(state: FlowExecution, script: FlowScript): FlowAction | null {\n // Terminal flow — never fight a completed/failed/cancelled run.\n if (state.status === \"complete\" || state.status === \"failed\" || state.status === \"cancelled\") {\n return null;\n }\n\n const dir = (id: string): FlowNodeDirective => script.nodes?.[id] ?? script.default ?? {};\n const nodes = Object.values(state.nodes);\n\n // 1. Approved gate → complete.\n for (const n of nodes) {\n if (n.status === \"awaiting_approval\" && n.approval?.decision === \"approved\") {\n return { op: \"complete_node\", nodeId: n.id, summary: summaryFor(dir(n.id), n) };\n }\n }\n\n // 2. Running node → per directive.\n for (const n of nodes) {\n if (n.status !== \"running\") continue;\n const d = dir(n.id);\n const onRun: OnRun = d.onRun ?? \"auto\";\n const resolved: OnRun =\n onRun === \"auto\" ? (state.autonomousMode ? \"complete\" : \"approve\") : onRun;\n\n if (resolved === \"complete\") {\n return { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n if (resolved === \"approve\") {\n return { op: \"request_approval\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n if (resolved === \"input\") {\n const lastInput = n.inputHistory[n.inputHistory.length - 1];\n if (lastInput && lastInput.response !== undefined) {\n // Input already provided — proceed as if `auto`.\n return state.autonomousMode\n ? { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) }\n : { op: \"request_approval\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n return {\n op: \"request_input\",\n nodeId: n.id,\n prompt: d.input?.prompt ?? `Provide input for ${n.id}`,\n schema: JSON.stringify(d.input?.schema ?? { kind: \"text\" }),\n };\n }\n if (resolved === \"fail\") {\n const recoverable = d.recoverable ?? false;\n if (!recoverable) {\n // Terminal fail — the adapter marks node + flow `failed`, so the\n // terminal-status guard above stops any re-fire on later turns.\n return {\n op: \"fail_node\",\n nodeId: n.id,\n message: d.summary ?? `Scripted failure for ${n.id}`,\n recoverable: false,\n };\n }\n // Recoverable fail — emit up to `failCount` times (counting the node's\n // own recorded recoverable errors), then proceed as `auto` so the node\n // is not stranded in a re-drive loop.\n const emitted = n.errorHistory.filter((e) => e.recoverable).length;\n const failCount = Math.max(1, d.failCount ?? 1);\n if (emitted < failCount) {\n return {\n op: \"fail_node\",\n nodeId: n.id,\n message: d.summary ?? `Scripted recoverable failure for ${n.id}`,\n recoverable: true,\n };\n }\n return state.autonomousMode\n ? { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) }\n : { op: \"request_approval\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n // `skip` while running is illegal; complete instead to avoid a deadlock.\n return { op: \"complete_node\", nodeId: n.id, summary: summaryFor(d, n) };\n }\n\n // 3. Available node → terminally-fail (post-reject), skip, or start.\n for (const n of nodes) {\n if (n.status !== \"available\") continue;\n const d = dir(n.id);\n const lastApproval = n.approvalHistory[n.approvalHistory.length - 1];\n if (lastApproval?.decision === \"rejected\" && d.onReject === \"fail\") {\n return {\n op: \"fail_node\",\n nodeId: n.id,\n message: d.summary ?? `Rejected and not recoverable: ${n.id}`,\n recoverable: false,\n };\n }\n if (d.onRun === \"skip\") {\n return { op: \"skip_node\", nodeId: n.id };\n }\n return { op: \"start_node\", nodeId: n.id };\n }\n\n // 4. Nothing actionable — awaiting_approval (no decision), awaiting_input\n // (no response), or fully drained. Yield.\n return null;\n}\n\n/**\n * Parse a `[test-flow]` sentinel body into a {@link FlowScript}. An empty body\n * yields the canonical (empty) script. Malformed JSON is a hard error so tests\n * fail loudly rather than silently running the wrong policy.\n */\nexport function parseFlowScript(body: string): FlowScript {\n const trimmed = body.trim();\n if (trimmed.length === 0) return {};\n const parsed: unknown = JSON.parse(trimmed);\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"flow script must be a JSON object\");\n }\n return parsed as FlowScript;\n}\n","import type { DriverTarget } from \"@skaile/workspaces/plugin-registry\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { dispatchCapability } from \"../capability-dispatch.js\";\nimport { getBridgeLogger } from \"../logger.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport {\n type AgentConfig,\n AgentDriver,\n type AgentEvent,\n type BridgeCapabilityTool,\n type DriverInfo,\n} from \"../types.js\";\nimport {\n actionArgs,\n type FlowScript,\n decideFlowAction,\n isTurnEnding,\n parseFlowScript,\n} from \"./flow-script.js\";\n\n/**\n * Echo/mock driver for E2E testing in docker mode.\n *\n * Runs inside a real Docker container with real WebSocket transport and\n * session lifecycle, but generates deterministic keyword-triggered responses\n * instead of calling the Anthropic API. This lets E2E tests exercise the\n * full infrastructure (containers, WebSocket, session management, message\n * persistence) without needing real AI credentials.\n *\n * Keyword triggers match the MockAgentClient in\n * `platform/backend/libs/agent-gateway/src/mock-agent-client.ts` — the\n * same test messages (\"test toolcall\", \"test question\", etc.) produce\n * the same events.\n *\n * Enable by setting `SKAILE_AGENT_DRIVER=echo` in the container env,\n * or by passing `{ driver: 'echo' }` in the runner config.\n *\n * @docLink packages/bridge/drivers#echo-driver\n */\nexport class EchoDriver extends AgentDriver {\n readonly driverInfo: DriverInfo = {\n id: \"echo\",\n name: \"Echo (E2E mock)\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n };\n\n private readonly log: Logger = getBridgeLogger(\"echo\");\n private running = false;\n private readonly config: AgentConfig;\n\n /**\n * Scripted-flow mode state (workspaces#396). Enabled by a `[test-flow]`\n * sentinel chat message; once on, orchestrator-prompt turns are driven\n * deterministically against `config.flowTestDriver`. `null` script ⇒ mode\n * off (default echo behaviour, unchanged).\n */\n private flowScript: FlowScript | null = null;\n\n constructor(config: AgentConfig) {\n super();\n this.config = config;\n }\n\n /**\n * Test surface: returns the tool list the LLM would see for this turn.\n * Composition: the registry hooks (Protocol v2) take precedence; legacy\n * `mcpServers` is not enumerated here (the echo driver never exposed MCP\n * tools to the LLM by name).\n */\n listCapabilityTools(): BridgeCapabilityTool[] {\n return this.config.capabilities?.composeTools() ?? [];\n }\n\n /**\n * Test surface: invoke a registered capability through the dispatch\n * helper. Mirrors what a real driver would do when the LLM produced a\n * tool_use for the given name — applies fire-and-forget, render emission,\n * and fallback text. Returns the structured dispatch result so tests can\n * assert immediate-vs-background resolution.\n */\n async invokeCapabilityForTest(\n name: string,\n input: unknown,\n ): Promise<{ result: unknown; background: boolean }> {\n const hooks = this.config.capabilities;\n if (!hooks) throw new Error(\"EchoDriver: no capability hooks configured\");\n const callId = `echo-cap-${Date.now()}`;\n const out = await dispatchCapability(hooks, callId, name, input, (err) =>\n this.log.warn(\"background capability handler failed\", {\n name,\n error: String(err),\n }),\n );\n return out;\n }\n\n async start(): Promise<void> {\n this.running = true;\n this.log.info(\"driver started\");\n }\n\n async prompt(message: string): Promise<void> {\n if (!this.running) return;\n const content = message.toLowerCase();\n this.log.info(\"received prompt\", { preview: message.slice(0, 80), length: message.length });\n\n // Small delay to simulate real agent processing\n await new Promise((resolve) => setTimeout(resolve, 200));\n\n // Scripted-flow test seam (workspaces#396) — a `[test-flow]` sentinel\n // arms deterministic flow driving for this session and (optionally)\n // carries a JSON script. Format: `[test-flow] {json}`; empty body ⇒\n // canonical policy. Must be handled before the flow-turn branch below.\n //\n // Detection is LINE-anchored, not message-anchored (workspaces#401): hosts\n // decorate user messages (e.g. a prepended `<SESSION_MEMBERS>` block and a\n // wake-restoration preamble), so the sentinel is rarely at the start of the\n // composed prompt. We match `[test-flow]` at the start of ANY line (only\n // leading whitespace allowed), which is decoration-independent yet still\n // impossible to arm from ordinary prose — a line must BEGIN with the exact\n // token. The optional JSON script must sit on that same line.\n const flowMatch = /^[ \\t]*\\[test-flow\\][ \\t]*(.*)$/m.exec(message);\n if (flowMatch) {\n let summary: string;\n try {\n this.flowScript = parseFlowScript(flowMatch[1] ?? \"\");\n summary = \"echo[test-flow]: scripted-flow mode armed\";\n } catch (err) {\n this.flowScript = null;\n summary = `echo[test-flow]: invalid script — ${err instanceof Error ? err.message : String(err)}`;\n this.emit(\"agent-event\", { type: \"error\", error: summary, fatal: false });\n }\n for (const event of textAndResult(summary)) this.emit(\"agent-event\", event);\n this.emit(\"agent-event\", { type: \"agent_end\" });\n return;\n }\n\n // Scripted-flow turn — the runner reassembles the orchestrator prompt on\n // every flow turn; when scripted-flow mode is armed and a flow driver hook\n // is present, drive nodes deterministically instead of echoing text.\n if (this.flowScript && this.config.flowTestDriver && isFlowTurn(message)) {\n await this.runScriptedFlowTurn();\n return;\n }\n\n // Phase 7B test seam — explicit capability invocation keyword. Lets E2E\n // tests drive `dispatchCapability` from a chat prompt without a real LLM.\n // Format: `[test-cap:<name>] {json}`. Anything after the closing bracket\n // is parsed as JSON input; on parse error we fall back to `{}`.\n const capMatch = /^\\s*\\[test-cap:([\\w.\\-_]+)\\]\\s*(.*)$/s.exec(message);\n if (capMatch) {\n const name = capMatch[1] ?? \"\";\n const rawInput = (capMatch[2] ?? \"\").trim();\n let input: unknown = {};\n if (rawInput.length > 0) {\n try {\n input = JSON.parse(rawInput);\n } catch (err) {\n this.log.warn(\"test-cap input was not valid JSON; defaulting to {}\", {\n error: String(err),\n preview: rawInput.slice(0, 80),\n });\n }\n }\n const events = await this.runCapabilityKeyword(name, input);\n for (const event of events) {\n this.emit(\"agent-event\", event);\n await new Promise((resolve) => setTimeout(resolve, 20));\n }\n this.emit(\"agent-event\", { type: \"agent_end\" });\n return;\n }\n\n const events = buildEchoEvents(content, message);\n for (const event of events) {\n this.emit(\"agent-event\", event);\n // Small gap between events to let the transport process each one\n await new Promise((resolve) => setTimeout(resolve, 50));\n }\n // Signal turn completion — the runner waits for this before accepting\n // the next prompt. Without it, the runner stays stuck after the first message.\n this.emit(\"agent-event\", { type: \"agent_end\" });\n }\n\n /**\n * Phase 7B helper — drive a single capability through the dispatcher and\n * surface the structured outcome as a result event the LLM-side test code\n * can assert against. Used exclusively by the `[test-cap:<name>]` prompt\n * keyword above; never wired into normal chat flow.\n */\n private async runCapabilityKeyword(name: string, input: unknown): Promise<AgentEvent[]> {\n const events: AgentEvent[] = [];\n if (!this.config.capabilities) {\n return textAndResult(`echo[test-cap]: no capability hooks configured (skipping ${name})`);\n }\n try {\n const out = await this.invokeCapabilityForTest(name, input);\n const summary = `echo[test-cap]: invoked ${name} background=${String(out.background)} result=${safeStringify(out.result)}`;\n events.push(...textAndResult(summary));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n events.push({\n type: \"error\",\n error: `echo[test-cap]: ${name} failed: ${msg}`,\n fatal: false,\n });\n events.push(...textAndResult(`echo[test-cap]: ${name} errored (${msg})`));\n }\n return events;\n }\n\n /**\n * Scripted-flow turn (workspaces#396). Reads the live flow state via the\n * runner-injected `flowTestDriver` hook and executes the scripted next\n * action(s) until the policy yields or emits a turn-ending action. Each\n * mutation fires the adapter's `onChange` (→ host `state_changed`) and, when\n * the runner wires the stimulus bus, queues the follow-up turn — so the\n * driver advances one step at a time exactly like a real LLM orchestrator.\n */\n private async runScriptedFlowTurn(): Promise<void> {\n const hook = this.config.flowTestDriver;\n const script = this.flowScript;\n if (!hook || !script) {\n this.emit(\"agent-event\", { type: \"agent_end\" });\n return;\n }\n\n const executed: string[] = [];\n // Hard cap — the policy is monotonic, but never let a bug spin forever.\n const MAX_STEPS = 200;\n for (let i = 0; i < MAX_STEPS; i++) {\n const state = hook.getState();\n if (!state) break;\n const action = decideFlowAction(state, script);\n if (!action) break;\n\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name: action.op,\n tool: { name: action.op },\n input: action.nodeId,\n });\n try {\n await hook.execute(action.op, actionArgs(action));\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n this.log.warn(\"scripted flow op failed\", {\n op: action.op,\n nodeId: action.nodeId,\n error: msg,\n });\n this.emit(\"agent-event\", {\n type: \"error\",\n error: `echo[test-flow]: ${action.op}(${action.nodeId}) failed: ${msg}`,\n fatal: false,\n });\n break;\n }\n this.emit(\"agent-event\", { type: \"tool_execution_end\", toolName: action.op });\n executed.push(`${action.op}(${action.nodeId})`);\n if (isTurnEnding(action)) break;\n }\n\n const summary =\n executed.length > 0\n ? `echo[test-flow]: ${executed.join(\" → \")}`\n : \"echo[test-flow]: no action (yielding to host)\";\n for (const event of textAndResult(summary)) this.emit(\"agent-event\", event);\n this.emit(\"agent-event\", { type: \"agent_end\" });\n }\n\n async abort(): Promise<void> {\n this.log.info(\"abort requested\");\n }\n\n kill(): void {\n this.running = false;\n this.log.info(\"killed\");\n }\n\n async resetSession(): Promise<void> {\n this.log.info(\"session reset\");\n }\n\n get isRunning(): boolean {\n return this.running;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Echo response generation — mirrors MockAgentClient.buildMockEvents\n// ---------------------------------------------------------------------------\n\n/**\n * A flow turn is recognised by the orchestrator prompt's stable header\n * (`buildOrchestratorPrompt` in the flow connector). Detection is header-only —\n * the driver reads live state through the injected hook, never by parsing the\n * prompt body.\n */\nfunction isFlowTurn(message: string): boolean {\n return message.startsWith(\"# Flow Execution Context\");\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\nfunction textAndResult(summary: string): AgentEvent[] {\n return [\n {\n type: \"message_start\",\n message: { role: \"assistant\", content: summary },\n },\n {\n type: \"message_end\",\n message: { role: \"assistant\", content: summary },\n },\n {\n type: \"result\",\n subtype: \"success\",\n summary,\n costUsd: 0,\n },\n ];\n}\n\nfunction buildEchoEvents(content: string, originalPrompt: string): AgentEvent[] {\n const events: AgentEvent[] = [];\n\n if (content.includes(\"test all\")) {\n events.push(\n { type: \"tool_call\", name: \"Read\", tool: { name: \"Read\" }, input: \"prisma/schema.prisma\" },\n { type: \"tool_execution_end\", toolName: \"Read\" },\n {\n type: \"tool_call\",\n name: \"Write\",\n tool: { name: \"Write\" },\n input: \"src/modules/sprint/sprint.service.ts\",\n },\n { type: \"tool_execution_end\", toolName: \"Write\" },\n );\n events.push(\n ...textAndResult(\n \"All operations completed successfully. Created sprint service, updated schema, started dev server, and ran E2E tests.\",\n ),\n );\n } else if (content.includes(\"test toolcall\")) {\n events.push(\n {\n type: \"tool_call\",\n name: \"Read\",\n tool: { name: \"Read\" },\n input: \"platform/prisma/schema.prisma\",\n },\n { type: \"tool_execution_end\", toolName: \"Read\" },\n );\n events.push(\n ...textAndResult(\n \"I've read the schema and found 42 models. The data model looks well-structured.\",\n ),\n );\n } else if (content.includes(\"test question\")) {\n // Emit a message that asks the user a question (the runner normalizer\n // converts this to a `question` AgentEvent for the transport layer)\n events.push(\n ...textAndResult(\n \"The blueprint calls for a relational database. Which engine should I target? \" +\n \"This will affect the Prisma provider, Docker Compose setup, and the connection string.\\n\\n\" +\n \"Options: PostgreSQL, MySQL, SQLite\",\n ),\n );\n } else if (content.includes(\"test error\")) {\n events.push({\n type: \"error\",\n error:\n \"AI provider returned HTTP 429 — rate limit exceeded. The request will be retried automatically in 35 seconds.\",\n fatal: false,\n });\n } else if (content.includes(\"test fatal\")) {\n events.push({\n type: \"error\",\n error:\n \"Session agent was killed by the container runtime (OOM — memory limit 2 GB exceeded). The session cannot continue.\",\n fatal: true,\n });\n } else {\n // Default echo response\n const summary =\n `I received your message: \"${originalPrompt}\". I'm the Skaile AI assistant running in echo mode. ` +\n `This is a deterministic mock response for E2E testing.`;\n events.push(...textAndResult(summary));\n }\n\n return events;\n}\n\n/**\n * `DriverTarget` wrapper for the echo driver. Registered into the plugin\n * registry by `registerBuiltinDrivers()`.\n */\nexport const echoDriverTarget: DriverTarget<AgentConfig> = {\n id: \"echo\",\n displayName: BUILTIN_DRIVER_CATALOG.echo?.name ?? \"Echo (E2E mock)\",\n apiVersion: 1,\n // Drivers take AgentConfig; passthrough — full schema validation is out of scope.\n configSchema: z.custom<AgentConfig>(() => true),\n create: async (config, _ctx) => new EchoDriver(config),\n listModels: async (apiKeys) =>\n new EchoDriver({ cwd: process.cwd(), sessionId: \"model-list\", apiKeys }).listModels(),\n};\n"]}
@@ -1,8 +1,8 @@
1
- export { GeminiDriver, GeminiFamilyDriver, geminiDriverTarget } from '../../chunk-6XQ5QG63.js';
2
- import '../../chunk-FRD4NU3W.js';
1
+ export { GeminiDriver, GeminiFamilyDriver, geminiDriverTarget } from '../../chunk-NQD7INSF.js';
2
+ import '../../chunk-XVWK3VHH.js';
3
3
  import '../../chunk-BMQKMOQY.js';
4
4
  import '../../chunk-GAH4YRCI.js';
5
- import '../../chunk-APHTT5GE.js';
5
+ import '../../chunk-KF3KDVKT.js';
6
6
  import '../../chunk-6E6PKKAD.js';
7
7
  import '../../chunk-JB35MVBN.js';
8
8
  import '../../chunk-NSBPE2FW.js';
@@ -1,6 +1,6 @@
1
- import { SubprocessCliDriver, mapApiKeysToEnv, extractText, extractCost, extractTokens } from '../../chunk-FRD4NU3W.js';
1
+ import { SubprocessCliDriver, mapApiKeysToEnv, extractText, extractCost, extractTokens } from '../../chunk-XVWK3VHH.js';
2
2
  import '../../chunk-GAH4YRCI.js';
3
- import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-APHTT5GE.js';
3
+ import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
4
4
  import '../../chunk-6E6PKKAD.js';
5
5
  import '../../chunk-JB35MVBN.js';
6
6
  import '../../chunk-NSBPE2FW.js';
@@ -1,5 +1,5 @@
1
1
  import { classifyGenericErrorMessage } from '../../chunk-GAH4YRCI.js';
2
- import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-APHTT5GE.js';
2
+ import { BUILTIN_DRIVER_CATALOG, AgentDriver, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
3
3
  import '../../chunk-6E6PKKAD.js';
4
4
  import '../../chunk-JB35MVBN.js';
5
5
  import '../../chunk-NSBPE2FW.js';
@@ -1,6 +1,6 @@
1
- import { SubprocessCliDriver, mapApiKeysToEnv, extractText, extractCost, extractTokens } from '../../chunk-FRD4NU3W.js';
1
+ import { SubprocessCliDriver, mapApiKeysToEnv, extractText, extractCost, extractTokens } from '../../chunk-XVWK3VHH.js';
2
2
  import '../../chunk-GAH4YRCI.js';
3
- import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-APHTT5GE.js';
3
+ import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
4
4
  import '../../chunk-6E6PKKAD.js';
5
5
  import '../../chunk-JB35MVBN.js';
6
6
  import '../../chunk-NSBPE2FW.js';
@@ -1,8 +1,8 @@
1
- import { GeminiFamilyDriver } from '../../chunk-6XQ5QG63.js';
2
- import '../../chunk-FRD4NU3W.js';
1
+ import { GeminiFamilyDriver } from '../../chunk-NQD7INSF.js';
2
+ import '../../chunk-XVWK3VHH.js';
3
3
  import { fetchProviderModels } from '../../chunk-BMQKMOQY.js';
4
4
  import '../../chunk-GAH4YRCI.js';
5
- import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-APHTT5GE.js';
5
+ import { BUILTIN_DRIVER_CATALOG, getBridgeLogger } from '../../chunk-KF3KDVKT.js';
6
6
  import '../../chunk-6E6PKKAD.js';
7
7
  import '../../chunk-JB35MVBN.js';
8
8
  import '../../chunk-NSBPE2FW.js';
@@ -1,9 +1,9 @@
1
- export { BridgeRuntime, EventNormalizer, createRuntime, detectFileChange, detectFileChanges, summarizeToolCall, summarizeToolResult, validateApiKey } from '../chunk-LVQO4X4U.js';
1
+ export { BridgeRuntime, EventNormalizer, createRuntime, detectFileChange, detectFileChanges, summarizeToolCall, summarizeToolResult, validateApiKey } from '../chunk-T5XXWWHT.js';
2
2
  export { CLOUD_SECRET_ENV_KEYS, SUPPORTED_CLOUDS, buildClaudeCloudEnv } from '../chunk-ISQWMBKD.js';
3
3
  export { dispatchCapability, filterRenderCapabilities, renderFallback } from '../chunk-RRVQAE5D.js';
4
4
  export { STATIC_MODELS, fetchProviderModels, getModels, getStaticModels } from '../chunk-BMQKMOQY.js';
5
5
  export { AccountUnavailableError, AuthError, classifyClaudeSdkError, reclassifyAuthAsAccountUnavailable } from '../chunk-GAH4YRCI.js';
6
- export { AgentDriver, BUILTIN_DRIVER_CATALOG, DRIVER_CATALOG, createDriver, getBridgeLogger, listDrivers, listModelsForDriver, registerBuiltinDrivers } from '../chunk-APHTT5GE.js';
6
+ export { AgentDriver, BUILTIN_DRIVER_CATALOG, DRIVER_CATALOG, createDriver, getBridgeLogger, listDrivers, listModelsForDriver, registerBuiltinDrivers } from '../chunk-KF3KDVKT.js';
7
7
  import '../chunk-6E6PKKAD.js';
8
8
  import '../chunk-JB35MVBN.js';
9
9
  import '../chunk-NSBPE2FW.js';
@@ -1 +1 @@
1
- {"version":3,"file":"echo.d.ts","sourceRoot":"","sources":["../../../../bridge/src/drivers/echo.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAMvE,OAAO,EACL,KAAK,WAAW,EAChB,WAAW,EAEX,KAAK,oBAAoB,EACzB,KAAK,UAAU,EAChB,MAAM,aAAa,CAAC;AASrB;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,UAAW,SAAQ,WAAW;IACzC,QAAQ,CAAC,UAAU,EAAE,UAAU,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D,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAc;IAErC;;;;;OAKG;IACH,OAAO,CAAC,UAAU,CAA2B;gBAEjC,MAAM,EAAE,WAAW;IAK/B;;;;;OAKG;IACH,mBAAmB,IAAI,oBAAoB,EAAE;IAI7C;;;;;;OAMG;IACG,uBAAuB,CAC3B,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,OAAO,GACb,OAAO,CAAC;QAAE,MAAM,EAAE,OAAO,CAAC;QAAC,UAAU,EAAE,OAAO,CAAA;KAAE,CAAC;IAa9C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAKtB,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAmF5C;;;;;OAKG;YACW,oBAAoB;IAqBlC;;;;;;;OAOG;YACW,mBAAmB;IAoD3B,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,IAAI,IAAI;IAKN,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAInC,IAAI,SAAS,IAAI,OAAO,CAEvB;CACF;AAiHD;;;GAGG;AACH,eAAO,MAAM,gBAAgB,EAAE,YAAY,CAAC,WAAW,CAStD,CAAC"}
@@ -389,5 +389,5 @@ function walkForSkill(dir, skillId) {
389
389
  }
390
390
 
391
391
  export { resumeFlow, runFlow };
392
- //# sourceMappingURL=chunk-DEBMR6MK.js.map
393
- //# sourceMappingURL=chunk-DEBMR6MK.js.map
392
+ //# sourceMappingURL=chunk-EAJWXVQL.js.map
393
+ //# sourceMappingURL=chunk-EAJWXVQL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;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,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-DEBMR6MK.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
1
+ {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI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;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-EAJWXVQL.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}