@skaile/workspaces 2.5.0 → 2.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +26 -11
- package/dist/{asset-feeds-4AWAT5PW.js → asset-feeds-23CP6YUY.js} +4 -4
- package/dist/{asset-feeds-4AWAT5PW.js.map → asset-feeds-23CP6YUY.js.map} +1 -1
- package/dist/asset-manager/index.js +1 -1
- package/dist/{chunk-WSARNOPP.js → chunk-6AYGXPPF.js} +2 -2
- package/dist/{chunk-WSARNOPP.js.map → chunk-6AYGXPPF.js.map} +1 -1
- package/dist/{chunk-ENBTXMPL.js → chunk-AZ44F3AT.js} +6 -6
- package/dist/{chunk-ENBTXMPL.js.map → chunk-AZ44F3AT.js.map} +1 -1
- package/dist/{chunk-4O2RAXKJ.js → chunk-E4AVJMOJ.js} +316 -6
- package/dist/chunk-E4AVJMOJ.js.map +1 -0
- package/dist/{chunk-JAFEMG7W.js → chunk-FW2C6JJP.js} +3 -3
- package/dist/{chunk-JAFEMG7W.js.map → chunk-FW2C6JJP.js.map} +1 -1
- package/dist/{chunk-EEHOMCRU.js → chunk-HVQWLYZB.js} +129 -11
- package/dist/chunk-HVQWLYZB.js.map +1 -0
- package/dist/{chunk-V4ZLZJFN.js → chunk-IWUIXNMF.js} +6 -3
- package/dist/chunk-IWUIXNMF.js.map +1 -0
- package/dist/{chunk-IHX2SN35.js → chunk-JIA2S3T2.js} +6 -6
- package/dist/{chunk-IHX2SN35.js.map → chunk-JIA2S3T2.js.map} +1 -1
- package/dist/{chunk-RK3HU3H3.js → chunk-KSHCQ777.js} +8 -6
- package/dist/chunk-KSHCQ777.js.map +1 -0
- package/dist/{chunk-YWPEDILM.js → chunk-OAUKA7VT.js} +8 -8
- package/dist/{chunk-YWPEDILM.js.map → chunk-OAUKA7VT.js.map} +1 -1
- package/dist/{chunk-MADO7PH5.js → chunk-ONUDDQGS.js} +2 -2
- package/dist/{chunk-MADO7PH5.js.map → chunk-ONUDDQGS.js.map} +1 -1
- package/dist/{chunk-EUWN4EK4.js → chunk-P3DUVOAW.js} +6 -6
- package/dist/{chunk-EUWN4EK4.js.map → chunk-P3DUVOAW.js.map} +1 -1
- package/dist/{chunk-FKBQRV4J.js → chunk-SCR3WGW7.js} +3 -3
- package/dist/{chunk-FKBQRV4J.js.map → chunk-SCR3WGW7.js.map} +1 -1
- package/dist/{chunk-4QROZZ5Z.js → chunk-TUYN2HDT.js} +7 -4
- package/dist/chunk-TUYN2HDT.js.map +1 -0
- package/dist/{chunk-OEGHKO5N.js → chunk-XJ74XFIZ.js} +20 -9
- package/dist/chunk-XJ74XFIZ.js.map +1 -0
- package/dist/{chunk-PJ6INYDD.js → chunk-XTFZOYNY.js} +3 -3
- package/dist/{chunk-PJ6INYDD.js.map → chunk-XTFZOYNY.js.map} +1 -1
- package/dist/{chunk-UZYTSIX6.js → chunk-ZJ7MRR2R.js} +4 -4
- package/dist/{chunk-UZYTSIX6.js.map → chunk-ZJ7MRR2R.js.map} +1 -1
- package/dist/{chunk-AKVAZ5CB.js → chunk-ZJOEU5GP.js} +2 -2
- package/dist/{chunk-AKVAZ5CB.js.map → chunk-ZJOEU5GP.js.map} +1 -1
- package/dist/cli/index.js +31 -31
- package/dist/connectors/index.js +5 -5
- package/dist/{ensure-sources-QF72HVUM.js → ensure-sources-N7B7657V.js} +4 -4
- package/dist/{ensure-sources-QF72HVUM.js.map → ensure-sources-N7B7657V.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +5 -5
- package/dist/factory-assets/connectors/deploy.js +5 -5
- package/dist/factory-assets/connectors/devserver.js +5 -5
- package/dist/factory-assets/connectors/flow/CONNECTOR.md +36 -8
- package/dist/factory-assets/connectors/flow/adapter.d.ts +4 -1
- package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/adapter.js +5 -5
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts +3 -0
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/flow.v2.schema.json +5 -1
- package/dist/factory-assets/connectors/flow/contract/hash.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -1
- package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/schema.d.ts +21 -2
- package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract.js +2 -2
- package/dist/factory-assets/connectors/flow/engine/engine.d.ts +30 -0
- package/dist/factory-assets/connectors/flow/engine/engine.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts +6 -0
- package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts +48 -0
- package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow/engine/types.d.ts +13 -24
- package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine.js +3 -3
- package/dist/factory-assets/connectors/flow/prompt-fragments.js +2 -2
- package/dist/factory-assets/connectors/flow/run-flow.js +6 -6
- package/dist/factory-assets/connectors/flow.js +5 -5
- package/dist/factory-assets/connectors/git.js +5 -5
- package/dist/factory-assets/connectors/gmail.js +5 -5
- package/dist/factory-assets/connectors/googledrive.js +5 -5
- package/dist/factory-assets/connectors/local.js +5 -5
- package/dist/factory-assets/connectors/mattermost.js +5 -5
- package/dist/factory-assets/connectors/memory.js +5 -5
- package/dist/factory-assets/connectors/minio.js +5 -5
- package/dist/factory-assets/connectors/postgres.js +5 -5
- package/dist/factory-assets/connectors/s3.js +5 -5
- package/dist/factory-assets/connectors/sharepoint.js +5 -5
- package/dist/factory-assets/connectors/sqlite.js +5 -5
- package/dist/factory-assets/connectors/static-server.js +5 -5
- package/dist/factory-assets/connectors/tunnel.js +5 -5
- package/dist/factory-assets/connectors/webdav.js +5 -5
- package/dist/factory-assets/connectors/xstate-store.js +5 -5
- package/dist/factory-assets/connectors/xstate.js +5 -5
- package/dist/{flows-YIW4HL3L.js → flows-K7B253U6.js} +3 -3
- package/dist/{flows-YIW4HL3L.js.map → flows-K7B253U6.js.map} +1 -1
- package/dist/{helpers-LURCZHA4.js → helpers-PXEHIKF7.js} +4 -4
- package/dist/{helpers-LURCZHA4.js.map → helpers-PXEHIKF7.js.map} +1 -1
- package/dist/{library-publish-2GMJM3NZ.js → library-publish-3Z33J2ZY.js} +9 -9
- package/dist/{library-publish-2GMJM3NZ.js.map → library-publish-3Z33J2ZY.js.map} +1 -1
- package/dist/{open-library-POFOXZWH.js → open-library-Y5SKFAMK.js} +8 -8
- package/dist/{open-library-POFOXZWH.js.map → open-library-Y5SKFAMK.js.map} +1 -1
- package/dist/{project-GVOPZEJZ.js → project-DQRC6J6M.js} +5 -5
- package/dist/{project-GVOPZEJZ.js.map → project-DQRC6J6M.js.map} +1 -1
- package/dist/runner/index.js +9 -9
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/flow.js +3 -3
- package/dist/sdk/index.js +9 -9
- package/dist/sdk/runner.js +9 -9
- package/dist/sdk/store.js +1 -1
- package/dist/{source-FB3T4IHP.js → source-XBJ5KTAV.js} +9 -9
- package/dist/{source-FB3T4IHP.js.map → source-XBJ5KTAV.js.map} +1 -1
- package/dist/{source-manifest-publish-XTRDVPSC.js → source-manifest-publish-Q7TXBMCW.js} +10 -10
- package/dist/{source-manifest-publish-XTRDVPSC.js.map → source-manifest-publish-Q7TXBMCW.js.map} +1 -1
- package/dist/store/index.js +1 -1
- package/dist/store/src/store.d.ts +3 -2
- package/dist/store/src/store.d.ts.map +1 -1
- package/dist/tui/index.js +9 -9
- package/dist/types/src/events.d.ts +5 -1
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +1 -1
- package/dist/workspace-plugin/adapters/omp.js +3 -3
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4O2RAXKJ.js.map +0 -1
- package/dist/chunk-4QROZZ5Z.js.map +0 -1
- package/dist/chunk-EEHOMCRU.js.map +0 -1
- package/dist/chunk-OEGHKO5N.js.map +0 -1
- package/dist/chunk-RK3HU3H3.js.map +0 -1
- package/dist/chunk-V4ZLZJFN.js.map +0 -1
|
@@ -68,5 +68,5 @@ async function flowFindFlowForSession(projectDir, runId) {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
export { flowFindFlowForSession, flowGetSession, flowList, flowListSessions, flowShow };
|
|
71
|
-
//# sourceMappingURL=chunk-
|
|
72
|
-
//# sourceMappingURL=chunk-
|
|
71
|
+
//# sourceMappingURL=chunk-ONUDDQGS.js.map
|
|
72
|
+
//# sourceMappingURL=chunk-ONUDDQGS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../workspace-plugin/src/tools/flows.ts"],"names":[],"mappings":";;;;;AAmBA,eAAsB,SAAS,UAAA,EAAyC;AACtE,EAAA,IAAI;AACF,IAAA,MAAM,UAAA,GAAa,MAAM,gBAAA,CAAiB,UAAU,CAAA;AACpD,IAAA,IAAI,CAAC,UAAA,EAAY,OAAO,MAAA,CAAO,EAAE,CAAA;AACjC,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,MAAM,OAC7B,4CACF,CAAA;AACA,IAAA,MAAM,KAAA,GAAQ,aAAa,UAAU,CAAA;AACrC,IAAA,MAAM,OAAA,GAAU,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,MAAY;AAAA,MACrC,IAAI,CAAA,CAAE,EAAA;AAAA,MACN,IAAA,EAAM,CAAA,CAAE,IAAA,IAAQ,CAAA,CAAE,EAAA;AAAA,MAClB,SAAA,EAAW,CAAA,CAAE,KAAA,EAAO,MAAA,IAAU;AAAA,KAChC,CAAE,CAAA;AACF,IAAA,OAAO,OAAO,OAA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GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACF;AAaA,eAAsB,sBAAA,CACpB,YACA,KAAA,EACqB;AACrB,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,GAAW,MAAM,eAAA,CAAgB,UAAU,CAAA;AACjD,IAAA,MAAM,UAAU,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,UAAU,KAAK,CAAA;AACtD,IAAA,IAAI,CAAC,OAAA,EAAS,OAAO,GAAA,CAAI,CAAA,mBAAA,EAAsB,KAAK,CAAA,CAAE,CAAA;AAEtD,IAAA,MAAM,UAAA,GAAa,MAAM,gBAAA,CAAiB,UAAU,CAAA;AACpD,IAAA,IAAI,CAAC,UAAA,EAAY,OAAO,GAAA,CAAI,CAAA,4BAAA,EAA+B,KAAK,CAAA,oBAAA,CAAsB,CAAA;AAEtF,IAAA,MAAM,EAAE,YAAA,EAAa,GAAI,MAAM,OAC7B,4CACF,CAAA;AACA,IAAA,MAAM,KAAA,GAAQ,aAAa,UAAU,CAAA;AACrC,IAAA,MAAM,IAAA,GAAO,MAAM,IAAA,CAAK,CAAC,MAAW,CAAA,CAAE,EAAA,KAAO,QAAQ,MAAM,CAAA;AAC3D,IAAA,IAAI,CAAC,IAAA,EAAM,OAAO,IAAI,CAAA,gBAAA,EAAmB,OAAA,CAAQ,MAAM,CAAA,CAAE,CAAA;AACzD,IAAA,OAAO,OAAO,IAAI,CAAA;AAAA,EACpB,SAAS,CAAA,EAAY;AACnB,IAAA,OAAO,IAAI,CAAA,YAAa,KAAA,GAAQ,EAAE,OAAA,GAAU,MAAA,CAAO,CAAC,CAAC,CAAA;AAAA,EACvD;AACF","file":"chunk-ONUDDQGS.js","sourcesContent":["// src/tools/flows.ts\n\nimport type { ToolResult } from \"../types.js\";\nimport { err, okJson } from \"../types.js\";\nimport { findAiAssetsRoot } from \"../utils/ai-assets.js\";\nimport { readAllSessions } from \"./sessions.js\";\n\n// ── Flow tools ────────────────────────────────────────────────────────────────\n\n/**\n * List all flow definitions available in the project's `ai-assets` directory.\n *\n * Returns a JSON array of summary objects `{ id, name, nodeCount }`.\n * Returns an empty array when no `ai-assets` root is found.\n *\n * @param projectDir - Absolute path to the skaile project root.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function flowList(projectDir: string): Promise<ToolResult> {\n try {\n const assetsRoot = await findAiAssetsRoot(projectDir);\n if (!assetsRoot) return okJson([]);\n const { loadAllFlows } = await import(\n \"@skaile/workspaces/factory-assets/connectors/flow/engine\"\n );\n const flows = loadAllFlows(assetsRoot);\n const summary = flows.map((f: any) => ({\n id: f.id,\n name: f.name ?? f.id,\n nodeCount: f.nodes?.length ?? 0,\n }));\n return okJson(summary);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Show the full flow definition (nodes, edges, metadata) for a specific flow.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param flowId - Flow ID as returned by {@link flowList}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function flowShow(projectDir: string, flowId: string): Promise<ToolResult> {\n try {\n const assetsRoot = await findAiAssetsRoot(projectDir);\n if (!assetsRoot) return err(`Flow not found: ${flowId}`);\n const { loadAllFlows } = await import(\n \"@skaile/workspaces/factory-assets/connectors/flow/engine\"\n );\n const flows = loadAllFlows(assetsRoot);\n const flow = flows.find((f: any) => f.id === flowId);\n if (!flow) return err(`Flow not found: ${flowId}`);\n return okJson(flow);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * List all past and active flow run sessions for the workspace.\n *\n * Delegates to {@link readAllSessions} (reads `.skaile/sessions/*.json`),\n * sorted newest-first by `updatedAt`.\n *\n * @param projectDir - Absolute path to the skaile project root.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function flowListSessions(projectDir: string): Promise<ToolResult> {\n try {\n const sessions = await readAllSessions(projectDir);\n return okJson(sessions);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Get driver metadata for a specific flow run session.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param runId - Run ID from {@link flowListSessions}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function flowGetSession(projectDir: string, runId: string): Promise<ToolResult> {\n try {\n const sessions = await readAllSessions(projectDir);\n const session = sessions.find((s) => s.runId === runId);\n if (!session) return err(`Session not found: ${runId}`);\n return okJson(session);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n\n/**\n * Resolve and return the flow definition that was used in a past session.\n *\n * Looks up the session by `runId`, reads its `flowId`, then returns the full\n * flow definition from `ai-assets`.\n *\n * @param projectDir - Absolute path to the skaile project root.\n * @param runId - Run ID from {@link flowListSessions}.\n *\n * @docLink packages/workspace-plugin/concepts#tool-delivery\n */\nexport async function flowFindFlowForSession(\n projectDir: string,\n runId: string,\n): Promise<ToolResult> {\n try {\n const sessions = await readAllSessions(projectDir);\n const session = sessions.find((s) => s.runId === runId);\n if (!session) return err(`Session not found: ${runId}`);\n\n const assetsRoot = await findAiAssetsRoot(projectDir);\n if (!assetsRoot) return err(`Flow not found for session: ${runId} (no ai-assets root)`);\n\n const { loadAllFlows } = await import(\n \"@skaile/workspaces/factory-assets/connectors/flow/engine\"\n );\n const flows = loadAllFlows(assetsRoot);\n const flow = flows.find((f: any) => f.id === session.flowId);\n if (!flow) return err(`Flow not found: ${session.flowId}`);\n return okJson(flow);\n } catch (e: unknown) {\n return err(e instanceof Error ? e.message : String(e));\n }\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { initTelemetry } from './chunk-4R6DROGN.js';
|
|
2
2
|
import { parseSkillFrontmatter, validateFlowVersions } from './chunk-CZZRDYT4.js';
|
|
3
|
-
import { FlowAdapter, SessionNodeExecutor, SessionInlineSubFlowRunner } from './chunk-
|
|
4
|
-
import { loadFlow } from './chunk-
|
|
5
|
-
import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-
|
|
6
|
-
import { nodeAssets } from './chunk-
|
|
3
|
+
import { FlowAdapter, SessionNodeExecutor, SessionInlineSubFlowRunner } from './chunk-HVQWLYZB.js';
|
|
4
|
+
import { loadFlow } from './chunk-E4AVJMOJ.js';
|
|
5
|
+
import { buildOrchestratorPrompt, renderStimulusPrompt } from './chunk-SCR3WGW7.js';
|
|
6
|
+
import { nodeAssets } from './chunk-TUYN2HDT.js';
|
|
7
7
|
import { resolveSettings } from './chunk-P43HBWKK.js';
|
|
8
8
|
import { resolveAgentDir, resolveSkWorkspaceConfig } from './chunk-Q26C5GLO.js';
|
|
9
9
|
import { isValidAssetName } from './chunk-GEEW6SY2.js';
|
|
@@ -517,5 +517,5 @@ function walkForSkill(dir, skillId) {
|
|
|
517
517
|
}
|
|
518
518
|
|
|
519
519
|
export { resolveFlowPath, resumeFlow, runFlow };
|
|
520
|
-
//# sourceMappingURL=chunk-
|
|
521
|
-
//# sourceMappingURL=chunk-
|
|
520
|
+
//# sourceMappingURL=chunk-P3DUVOAW.js.map
|
|
521
|
+
//# sourceMappingURL=chunk-P3DUVOAW.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;;AA4DA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AAEjD,IAAM,0BAAA,uBAAiC,GAAA,CAAI;AAAA,EACzC,eAAA;AAAA,EACA,WAAA;AAAA,EACA,aAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,kBA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AA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-EUWN4EK4.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n isValidAssetName,\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport { nodeAssets } from \"./engine/node-shape.js\";\nimport { SessionInlineSubFlowRunner } from \"./inline-sub-flow-host.js\";\nimport { SessionNodeExecutor } from \"./node-executor.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\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. First-class\n * gate nodes remain mandatory human decisions in every mode.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * 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; first-class gate nodes are never bypassed. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. The\n * runner remains idle between turns; first-class gates always park for a human\n * decision, including in autonomous mode. Non-CLI hosts (Skaile platform,\n * Pichi) use the orchestrator directly via the serve command surface and drive\n * gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n 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 const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId }),\n };\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n 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 capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });\n let driverStarted = false;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It 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 const ensureDriverStarted = async (): Promise<void> => {\n if (driverStarted) return;\n await driver.start();\n driverStarted = true;\n };\n\n const inlineSubFlowRunner = new SessionInlineSubFlowRunner({\n resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),\n nodeExecutor,\n driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {\n await ensureDriverStarted();\n await awaitAgentEnd(\n driver,\n buildOrchestratorPrompt(childFlow, execution, stimulus),\n opts.onEvent,\n turnTimeoutMs,\n );\n },\n });\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\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 await flowAdapterRef.drainRuntimeNodes(flowHandleRef);\n const execution = flowAdapterRef.getExecution(flowHandleRef);\n if (execution.done || execution.status === \"failed\" || execution.status === \"cancelled\") {\n return;\n }\n if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;\n const fullPrompt = buildOrchestratorPrompt(flow, execution, stimulus);\n await ensureDriverStarted();\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 nodeExecutor,\n inlineSubFlowRunner,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.json();\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused awaiting further stimulus\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not supply human approval/input decisions\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n 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.flatMap((node) => {\n const fromAssets = nodeAssets(node).flatMap((asset) => {\n if (!asset.startsWith(\"skill:\")) return [];\n const hashIndex = asset.lastIndexOf(\"#\");\n if (hashIndex <= \"skill:\".length || hashIndex === asset.length - 1) return [];\n const identity = asset.slice(\"skill:\".length, hashIndex);\n const skillId = identity.slice(identity.lastIndexOf(\"/\") + 1);\n return [\n {\n nodeId: node.id,\n skillId,\n requestedVersion: asset.slice(hashIndex + 1),\n },\n ];\n });\n if (fromAssets.length > 0) return fromAssets;\n if (node.type !== \"skill\" || !node.data?.version) return [];\n return [\n {\n nodeId: node.id,\n skillId: node.data.skill ?? node.id,\n requestedVersion: node.data.version,\n },\n ];\n });\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.skillId;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const checks = validateFlowVersions(pinnedNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\n/** Resolve one flow identity through the CLI/serve host's normal lookup order. */\nexport function resolveFlowPath(flowId: string, projectDir: string): string {\n if (!isValidAssetName(flowId)) {\n throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);\n }\n\n const contained = (root: string, ...segments: string[]): string => {\n const resolvedRoot = path.resolve(root);\n const candidate = path.resolve(resolvedRoot, ...segments);\n const relative = path.relative(resolvedRoot, candidate);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);\n }\n return candidate;\n };\n const flowRoot = path.resolve(projectDir, \".skaile\", \"flows\");\n const armInstalled = contained(flowRoot, flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = contained(flowRoot, `${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 = contained(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = contained(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":";;;;;;;;;;;;;;AA4DA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;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AAA,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-P3DUVOAW.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n isValidAssetName,\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport { nodeAssets } from \"./engine/node-shape.js\";\nimport { SessionInlineSubFlowRunner } from \"./inline-sub-flow-host.js\";\nimport { SessionNodeExecutor } from \"./node-executor.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\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. First-class\n * gate nodes remain mandatory human decisions in every mode.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * 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; first-class gate nodes are never bypassed. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default. The\n * runner remains idle between turns; first-class gates always park for a human\n * decision, including in autonomous mode. Non-CLI hosts (Skaile platform,\n * Pichi) use the orchestrator directly via the serve command surface and drive\n * gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n 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 const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId }),\n };\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n 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 capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const nodeExecutor = new SessionNodeExecutor({ workspaceDir: opts.projectDir });\n let driverStarted = false;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It 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 const ensureDriverStarted = async (): Promise<void> => {\n if (driverStarted) return;\n await driver.start();\n driverStarted = true;\n };\n\n const inlineSubFlowRunner = new SessionInlineSubFlowRunner({\n resolveFlow: (flowId) => loadFlow(resolveFlowPath(flowId, opts.projectDir)),\n nodeExecutor,\n driveAgentTurn: async ({ flow: childFlow, execution, stimulus }) => {\n await ensureDriverStarted();\n await awaitAgentEnd(\n driver,\n buildOrchestratorPrompt(childFlow, execution, stimulus),\n opts.onEvent,\n turnTimeoutMs,\n );\n },\n });\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\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 await flowAdapterRef.drainRuntimeNodes(flowHandleRef);\n const execution = flowAdapterRef.getExecution(flowHandleRef);\n if (execution.done || execution.status === \"failed\" || execution.status === \"cancelled\") {\n return;\n }\n if (!flowAdapterRef.shouldDriveAgentTurn(flowHandleRef, stimulus)) return;\n const fullPrompt = buildOrchestratorPrompt(flow, execution, stimulus);\n await ensureDriverStarted();\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 nodeExecutor,\n inlineSubFlowRunner,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.json();\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused awaiting further stimulus\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not supply human approval/input decisions\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n 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.flatMap((node) => {\n const fromAssets = nodeAssets(node).flatMap((asset) => {\n if (!asset.startsWith(\"skill:\")) return [];\n const hashIndex = asset.lastIndexOf(\"#\");\n if (hashIndex <= \"skill:\".length || hashIndex === asset.length - 1) return [];\n const identity = asset.slice(\"skill:\".length, hashIndex);\n const skillId = identity.slice(identity.lastIndexOf(\"/\") + 1);\n return [\n {\n nodeId: node.id,\n skillId,\n requestedVersion: asset.slice(hashIndex + 1),\n },\n ];\n });\n if (fromAssets.length > 0) return fromAssets;\n if (node.type !== \"skill\" || !node.data?.version) return [];\n return [\n {\n nodeId: node.id,\n skillId: node.data.skill ?? node.id,\n requestedVersion: node.data.version,\n },\n ];\n });\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.skillId;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const checks = validateFlowVersions(pinnedNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\n/** Resolve one flow identity through the CLI/serve host's normal lookup order. */\nexport function resolveFlowPath(flowId: string, projectDir: string): string {\n if (!isValidAssetName(flowId)) {\n throw new Error(`Invalid canonical flow identity: ${JSON.stringify(flowId)}`);\n }\n\n const contained = (root: string, ...segments: string[]): string => {\n const resolvedRoot = path.resolve(root);\n const candidate = path.resolve(resolvedRoot, ...segments);\n const relative = path.relative(resolvedRoot, candidate);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n throw new Error(`Flow path escapes its lookup root: ${JSON.stringify(flowId)}`);\n }\n return candidate;\n };\n const flowRoot = path.resolve(projectDir, \".skaile\", \"flows\");\n const armInstalled = contained(flowRoot, flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = contained(flowRoot, `${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 = contained(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = contained(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isAgentNode, isGateNode, nodeIsOptional, nodeRequiresApproval, nodeLabel, flowDefaults } from './chunk-
|
|
1
|
+
import { isAgentNode, isGateNode, nodeIsOptional, nodeRequiresApproval, nodeLabel, flowDefaults } from './chunk-TUYN2HDT.js';
|
|
2
2
|
|
|
3
3
|
// factory-assets/connectors/flow/prompt-fragments.ts
|
|
4
4
|
function renderStimulusPrompt(stimulus) {
|
|
@@ -176,5 +176,5 @@ function describeStimulus(stimulus) {
|
|
|
176
176
|
}
|
|
177
177
|
|
|
178
178
|
export { buildOrchestratorPrompt, describeStimulus, renderStimulusPrompt };
|
|
179
|
-
//# sourceMappingURL=chunk-
|
|
180
|
-
//# sourceMappingURL=chunk-
|
|
179
|
+
//# sourceMappingURL=chunk-SCR3WGW7.js.map
|
|
180
|
+
//# sourceMappingURL=chunk-SCR3WGW7.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../factory-assets/connectors/flow/prompt-fragments.ts"],"names":[],"mappings":";;;AA0DO,SAAS,qBAAqB,QAAA,EAAgC;AACnE,EAAA,QAAQ,SAAS,IAAA;AAAM,IACrB,KAAK,cAAA;AACH,MAAA,OAAO,iKAAA;AAAA,IACT,KAAK,mBAAA,EAAqB;AACxB,MAAA,MAAM,EAAE,MAAA,EAAQ,QAAA,EAAU,SAAA,EAAW,UAAS,GAAI,QAAA;AAClD,MAAA,IAAI,aAAa,UAAA,EAAY;AAC3B,QAAA,OAAO,CAAA,OAAA,EAAU,MAAM,CAAA,uBAAA,EAA0B,SAAS,CAAA,yGAAA,CAAA;AAAA,MAC5D;AACA,MAAA,MAAM,EAAA,GAAK,QAAA,GAAW,CAAA,YAAA,EAAe,QAAQ,CAAA,EAAA,CAAA,GAAO,EAAA;AACpD,MAAA,OAAO,CAAA,OAAA,EAAU,MAAM,CAAA,uBAAA,EAA0B,SAAS,IAAI,EAAE,CAAA,kNAAA,CAAA;AAAA,IAClE;AAAA,IACA,KAAK,gBAAA;AACH,MAAA,OAAO,CAAA,wCAAA,EAA2C,QAAA,CAAS,MAAM,CAAA,gBAAA,EAAmB,SAAS,UAAU,CAAA,0FAAA,CAAA;AAAA,IACzG,KAAK,iBAAA;AACH,M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AO,CAAA;;AAAA;;AAAA;AAAA;AAAA,EAMlF,QAAQ;;AAAA;AAAA;;AAAA;;AAAA,EAOR,YAAY;;AAAA,EAEZ,cAAc,CAAA,EAAG,iBAAiB,CAAA,EAAG,mBAAmB,CAAA;;AAAA,EAExD,iBAAiB;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA2BnB;AAUO,SAAS,iBAAiB,QAAA,EAAgC;AAC/D,EAAA,QAAQ,SAAS,IAAA;AAAM,IACrB,KAAK,cAAA;AACH,MAAA,OAAO,cAAA;AAAA,IACT,KAAK,mBAAA;AACH,MAAA,OAAO,CAAA,kBAAA,EAAqB,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI,SAAS,QAAQ,CAAA,CAAA;AAAA,IAClE,KAAK,gBAAA;AACH,MAAA,OAAO,CAAA,eAAA,EAAkB,SAAS,MAAM,CAAA,CAAA;AAAA,IAC1C,KAAK,iBAAA;AACH,MAAA,OAAO,CAAA,gBAAA,EAAmB,SAAS,MAAM,CAAA,CAAA;AAAA,IAC3C,KAAK,cAAA;AACH,MAAA,OAAO,CAAA,aAAA,EAAgB,SAAS,QAAQ,CAAA,CAAA;AAAA,IAC1C,KAAK,2BAAA;AACH,MAAA,OAAO,2BAAA;AAAA,IACT,KAAK,WAAA;AACH,MAAA,OAAO,WAAA;AAAA,IACT,KAAK,eAAA;AACH,MAAA,OAAO,eAAA;AAAA;AAEb","file":"chunk-FKBQRV4J.js","sourcesContent":["/**\n * Prompt fragments for the flow connector.\n *\n * Pure functions that translate a {@link TurnStimulus} into the strings the\n * runner's flow orchestrator splices into the per-turn agent prompt.\n * Extracted from `runner/src/flow-orchestrator.ts` in Phase 3 of the\n * flow-connector extraction (2026-05-08) so the connector owns its\n * prompt-rendering surface without a runtime dep on the orchestrator.\n *\n * The contract is byte-identical to the previous inline implementation —\n * any divergence is a regression.\n *\n * @docLink packages/factory-assets/flow#prompt-fragments\n */\n\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport type { FlowDefinition } from \"./engine/types.js\";\nimport {\n flowDefaults,\n isAgentNode,\n isGateNode,\n nodeIsOptional,\n nodeLabel,\n nodeRequiresApproval,\n} from \"./engine/node-shape.js\";\n\n/**\n * Reasons why a new turn is starting. The flow orchestrator's prompt template\n * renders a stimulus-specific paragraph (via {@link renderStimulusPrompt}) so\n * the agent knows exactly why it has been invoked.\n *\n * @docLink packages/factory-assets/flow#turn-stimulus\n */\nexport type TurnStimulus =\n | { kind: \"flow_started\" }\n | {\n kind: \"approval_received\";\n nodeId: string;\n decision: \"approved\" | \"rejected\";\n feedback?: string;\n decidedBy: string;\n }\n | { kind: \"input_received\"; nodeId: string; response: unknown; providedBy: string }\n | { kind: \"retry_requested\"; nodeId: string; requestedBy: string }\n | { kind: \"user_message\"; text: string; senderId: string }\n | { kind: \"resumed_after_hibernation\" }\n | { kind: \"cancelled\" }\n | { kind: \"state_changed\" };\n\n/**\n * Render the stimulus paragraph the agent sees at turn start.\n *\n * The output is a single paragraph (one or more sentences, no surrounding\n * whitespace) describing why the runner has woken the agent. Spliced into\n * the orchestrator prompt under the `## Why this turn is happening` heading.\n *\n * @docLink packages/factory-assets/flow#render-stimulus-prompt\n */\nexport function renderStimulusPrompt(stimulus: TurnStimulus): string {\n switch (stimulus.kind) {\n case \"flow_started\":\n return \"The user just started this flow. Begin with the first available node — call `get_available`, then `build_handoff` for your chosen node, then `start_node`.\";\n case \"approval_received\": {\n const { nodeId, decision, decidedBy, feedback } = stimulus;\n if (decision === \"approved\") {\n return `Node \\`${nodeId}\\` was **approved** by ${decidedBy}. Call \\`complete_node\\` for this node with the approved output, then advance to the next available node.`;\n }\n const fb = feedback ? ` Feedback: \"${feedback}\".` : \"\";\n return `Node \\`${nodeId}\\` was **rejected** by ${decidedBy}.${fb} Decide how to proceed: retry the node (the engine returned it to \\`available\\`), ask clarifying questions via \\`request_input\\`, or call \\`fail_node(..., recoverable: false)\\` if the issue cannot be addressed.`;\n }\n case \"input_received\":\n return `The user just provided input for node \\`${stimulus.nodeId}\\` (provided by ${stimulus.providedBy}). The node has returned to its prior status. Continue executing the node with this input.`;\n case \"retry_requested\":\n return `A user requested a retry of node \\`${stimulus.nodeId}\\` (requested by ${stimulus.requestedBy}). The node has been returned to \\`available\\` with its prior error preserved in history. Start a fresh attempt — review the error context if relevant and try a different approach.`;\n case \"user_message\":\n return `A user sent a message: \"${stimulus.text}\" (from ${stimulus.senderId}). You can respond directly without touching the flow, continue flow work, or both. If the message is a question about the flow, answer it; if it signals a new direction, consider whether to pause.`;\n case \"resumed_after_hibernation\":\n return \"This session was hibernated and has just resumed. Review the current state above and continue where you left off. No state was lost.\";\n case \"cancelled\":\n return \"The user has cancelled this flow. Wrap up cleanly: do not start any new nodes. You may record a short summary if relevant, then stop.\";\n case \"state_changed\":\n return \"The flow state changed. Review the current state above and continue work accordingly.\";\n }\n}\n\n/**\n * Build the full agent-orchestrator prompt for a flow turn.\n *\n * Reassembles the five-section prompt from the current FlowExecution snapshot\n * and the supplied stimulus:\n *\n * 1. Flow definition (markdown table of nodes)\n * 2. Current state (progress, available/blocked, interaction pointers)\n * 3. Why this turn is happening (stimulus-specific paragraph)\n * 4. Flow tools available (static documentation)\n * 5. Rules\n *\n * Originally a byte-identical lift of the (since-deleted)\n * `FlowOrchestrator.buildOrchestratorPrompt`; the contract now is simply\n * this function's own output. When strict v2 defaults or legacy globals are\n * non-empty, a `## Flow globals` section exposes those run-scoped values. The\n * flow-wide active-node table stays bounded to selection metadata; `build_handoff`\n * supplies a selected agent node's execution payload. First-class gates appear\n * as runtime-owned state but never as agent-executable work.\n * Pure — depends only on its inputs.\n *\n * @docLink packages/factory-assets/flow#build-orchestrator-prompt\n * @since 2.2.0\n */\nexport function buildOrchestratorPrompt(\n flowDef: FlowDefinition,\n state: FlowExecution,\n stimulus: TurnStimulus,\n): string {\n const agentNodes = flowDef.nodes.filter(isAgentNode);\n const gateNodes = flowDef.nodes.filter(isGateNode);\n const promptNodes = flowDef.nodes.filter((node) => isAgentNode(node) || isGateNode(node));\n const agentNodeIds = new Set(agentNodes.map((node) => node.id));\n const promptNodeIds = new Set(promptNodes.map((node) => node.id));\n\n // ── Section 1: definition table ──\n const nodeRows = promptNodes\n .map((n) => {\n const deps =\n flowDef.edges\n .filter((e) => e.target === n.id && e.type === \"flow\")\n .map((e) => e.source)\n .join(\", \") || \"—\";\n const required = nodeIsOptional(n) ? \"optional\" : \"required\";\n const gate = isGateNode(n) ? \"first-class\" : nodeRequiresApproval(n) ? \"mandatory\" : \"—\";\n const nodeState = state.nodes[n.id];\n const status = nodeState?.status ?? \"not_started\";\n const description = (n.description ?? n.data?.description ?? \"—\")\n .replace(/\\s+/g, \" \")\n .replaceAll(\"|\", \"\\\\|\");\n return `| ${n.id} | ${nodeLabel(n)} | ${description} | ${required} | ${gate} | ${status} | ${deps} |`;\n })\n .join(\"\\n\");\n\n // ── Section 2: current state summary ──\n const nodesByStatus = (s: string) =>\n Object.values(state.nodes)\n .filter((n) => promptNodeIds.has(n.id) && n.status === s)\n .map((n) => n.id);\n const available = nodesByStatus(\"available\");\n const awaitingApproval = nodesByStatus(\"awaiting_approval\");\n const awaitingInput = nodesByStatus(\"awaiting_input\");\n const running = nodesByStatus(\"running\");\n const failed = nodesByStatus(\"failed\");\n const completed = nodesByStatus(\"complete\");\n const totalRequired = promptNodes.filter((n) => !nodeIsOptional(n)).length;\n\n const stateSummary = [\n `- Run ID: ${state.runId}`,\n `- Status: ${state.status}`,\n `- Autonomous mode: ${state.autonomousMode}`,\n `- Progress: ${completed.length} / ${totalRequired} required nodes complete`,\n `- Available now: ${available.join(\", \") || \"(none)\"}`,\n `- Currently running: ${running.join(\", \") || \"(none)\"}`,\n `- Awaiting approval: ${awaitingApproval.join(\", \") || \"(none)\"}`,\n `- Awaiting input: ${awaitingInput.join(\", \") || \"(none)\"}`,\n `- Failed: ${failed.join(\", \") || \"(none)\"}`,\n ].join(\"\\n\");\n\n const outputCorrections = Object.values(state.nodes)\n .filter(\n (node) =>\n agentNodeIds.has(node.id) &&\n node.outputCorrection &&\n node.status !== \"complete\" &&\n node.status !== \"failed\",\n )\n .map(\n (node) =>\n `- Node \\`${node.id}\\`: ${node.outputCorrection?.issues.join(\"; \") ?? \"unknown issue\"}`,\n );\n const correctionSection =\n outputCorrections.length > 0\n ? `## Output correction required\n\nThe following node has already used its single corrective reprompt. Submit one corrected \\`complete_node\\` call that fixes every issue; a second mismatch fails the node.\n\n${outputCorrections.join(\"\\n\")}\n\n`\n : \"\";\n\n const rejectedGates = gateNodes.flatMap((node) => {\n const approval = state.nodes[node.id]?.approval;\n if (approval?.decision !== \"rejected\") return [];\n return [\n `- \\`${node.id}\\` — rejected by ${approval.decidedBy ?? \"unknown reviewer\"}: ${\n approval.feedback ?? \"(no feedback provided)\"\n }`,\n ];\n });\n const rejectedGateSection =\n rejectedGates.length > 0\n ? `## Rejected first-class gates requiring revision\n\n${rejectedGates.join(\"\\n\")}\n\nRevise the surrounding work in conversation, then re-request each gate with \\`request_approval(nodeId, summary, artifacts)\\`. Every gate remains parked until its new human decision; do not start, complete, skip, or fail a first-class gate.\n\n`\n : \"\";\n\n // ── Section 2b: flow globals (additive — omitted entirely when empty so\n // flows without globals keep the byte-identical Phase 3 prompt) ──\n const globals = flowDefaults(flowDef);\n const globalsSection =\n Object.keys(globals).length > 0\n ? `## Flow globals\n\nRun-scoped parameters set by the flow author or by the host that started this run. When \\`run_input\\` is present it carries the payload this run was started with (e.g. a scheduled or webhook-triggered run) — treat it as the run's initial input instead of asking the user for it.\n\n\\`\\`\\`json\n${JSON.stringify(globals, null, 2)}\n\\`\\`\\`\n\n`\n : \"\";\n\n // ── Section 3: stimulus paragraph ──\n const stimulusNode =\n stimulus.kind === \"approval_received\"\n ? flowDef.nodes.find((node) => node.id === stimulus.nodeId)\n : undefined;\n let stimulusParagraph = renderStimulusPrompt(stimulus);\n if (stimulus.kind === \"approval_received\" && stimulusNode && isGateNode(stimulusNode)) {\n if (stimulus.decision === \"approved\") {\n const availableSuccessors = agentNodes\n .filter((node) => state.nodes[node.id]?.status === \"available\")\n .map((node) => `\\`${node.id}\\``);\n stimulusParagraph = `Gate node \\`${stimulus.nodeId}\\` is already \\`complete\\` after approval by ${stimulus.decidedBy}. Do not call \\`complete_node\\` for the gate. Advance to successor work${\n availableSuccessors.length > 0\n ? `; available agent nodes: ${availableSuccessors.join(\", \")}`\n : \"\"\n } — call \\`get_available\\`, then \\`build_handoff\\` and \\`start_node\\` for the chosen agent node.`;\n } else {\n stimulusParagraph = `Gate node \\`${stimulus.nodeId}\\` was **rejected** by ${stimulus.decidedBy}.${\n stimulus.feedback ? ` Feedback: \"${stimulus.feedback}\".` : \"\"\n } Revise the work in conversation and follow the rejected-gate instructions above.`;\n }\n }\n\n // ── Section 4+5: static tool surface and rules ──\n return `# Flow Execution Context\n\nYou are orchestrating the flow **${flowDef.name}** (${flowDef.id} v${flowDef.version}). This is a governed flow execution: your job is to run nodes through the flow tools, summarize their outputs for human review, and yield control at approval gates.\n\n## Flow definition\n\n| ID | Label | Description | Required | Gate | Status | Depends on |\n|----|-------|-------------|----------|------|--------|------------|\n${nodeRows}\n\nNodes with **Gate = mandatory** are hard approval gates: they always require \\`request_approval\\` and a human decision, even when autonomous mode is on. They cannot be skipped — \\`request_approval\\` → approval is their only completion path.\nNodes with **Gate = first-class** are runtime-owned human decisions. The runtime parks them automatically and completes them directly on approval; the agent never executes them.\n\n## Current state\n\n${stateSummary}\n\n${globalsSection}${correctionSection}${rejectedGateSection}## Why this turn is happening\n\n${stimulusParagraph}\n\n## Flow tools available\n\nAll tools are exposed by the \\`flow\\` connector:\n\n- \\`get_available()\\` — list node IDs that are ready to start\n- \\`get_state()\\` — full current state including approvals, inputs, outputs\n- \\`get_globals()\\` — the flow's run-scoped globals (e.g. the \\`run_input\\` payload for scheduled/params-bound runs)\n- \\`build_handoff(nodeId)\\` — selected node instruction, supplied bindings, required assets, and upstream context\n- \\`start_node(nodeId)\\` — transition an agent node from \\`available\\` → \\`running\\`; call before executing it. Never start a first-class gate.\n- \\`request_approval(nodeId, summary, artifacts)\\` — transition a running agent node to \\`awaiting_approval\\`, or replace a rejected first-class gate's decision with a fresh pending request. **This ends your turn.**\n- \\`request_input(nodeId, prompt, schema)\\` — transition to \\`awaiting_input\\`. **This ends your turn.** Legal from \\`available\\`, \\`running\\`, or \\`awaiting_approval\\`.\n- \\`complete_node(nodeId, summary, fields?, artifacts?, concerns?)\\` — complete an agent node. When downstream nodes consume declared output fields, include a conforming JSON object. The first mismatch gets one corrective call; the second fails the node. Valid only if the agent node was approved, OR autonomousMode is true and it does not require mandatory approval. First-class gates are completed by the runtime on approval; never call this tool for them.\n- \\`fail_node(nodeId, message, recoverable)\\` — transition to \\`failed\\`. \\`recoverable=true\\` returns the node to \\`available\\`.\n- \\`skip_node(nodeId)\\` — transition to \\`skipped\\`. Only valid for optional nodes.\n\n## Rules\n\n1. Before executing an agent node, call \\`build_handoff(nodeId)\\` and follow its instruction with the supplied bindings, assets, and upstream context; then call \\`start_node(nodeId)\\`.\n2. After executing the node, call \\`request_approval\\` unless \\`autonomousMode\\` is true — in which case call \\`complete_node\\` directly. Exception: nodes marked **Gate = mandatory** always require \\`request_approval\\` and a human decision, even in autonomous mode.\n3. First-class nodes marked **Gate = first-class** are runtime-owned. Never start, complete, skip, fail, or request input for them. After rejection, revise in conversation and only call \\`request_approval\\` to create the next attempt.\n4. If you need information from the user before or during agent execution, call \\`request_input\\`. This ends your turn until the user responds.\n5. On unrecoverable agent failure, call \\`fail_node(..., recoverable: false)\\`. On recoverable failure, call \\`fail_node(..., recoverable: true)\\` and the engine returns the node to \\`available\\`.\n6. When all required nodes are \\`complete\\` or \\`skipped\\`, stop. The runner marks the flow done automatically.\n7. Free-chat user messages do not require flow action. Respond directly, continue flow work, or both — your call.\n`;\n}\n\n/**\n * Single-line tag suitable for telemetry / logging. Derives a short, stable\n * summary of a stimulus that's safe to attach to spans, log entries, and\n * trace events. The kind is always included; node-specific stimuli also\n * include their `nodeId` so log queries can pivot on it.\n *\n * @docLink packages/factory-assets/flow#describe-stimulus\n */\nexport function describeStimulus(stimulus: TurnStimulus): string {\n switch (stimulus.kind) {\n case \"flow_started\":\n return \"flow_started\";\n case \"approval_received\":\n return `approval_received:${stimulus.nodeId}:${stimulus.decision}`;\n case \"input_received\":\n return `input_received:${stimulus.nodeId}`;\n case \"retry_requested\":\n return `retry_requested:${stimulus.nodeId}`;\n case \"user_message\":\n return `user_message:${stimulus.senderId}`;\n case \"resumed_after_hibernation\":\n return \"resumed_after_hibernation\";\n case \"cancelled\":\n return \"cancelled\";\n case \"state_changed\":\n return \"state_changed\";\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../factory-assets/connectors/flow/prompt-fragments.ts"],"names":[],"mappings":";;;AA0DO,SAAS,qBAAqB,QAAA,EAAgC;AACnE,EAAA,QAAQ,SAAS,IAAA;AAAM,IACrB,KAAK,cAAA;AACH,MAAA,OAAO,iKAAA;AAAA,IACT,KAAK,mBAAA,EAAqB;AACxB,MAAA,MAAM,EAAE,MAAA,EAAQ,QAAA,EAAU,SAAA,EAAW,UAAS,GAAI,QAAA;AAClD,MAAA,IAAI,aAAa,UAAA,EAAY;AAC3B,QAAA,OAAO,CAAA,OAAA,EAAU,MAAM,CAAA,uBAAA,EAA0B,SAAS,CAAA,yGAAA,CAAA;AAAA,MAC5D;AACA,MAAA,MAAM,EAAA,GAAK,QAAA,GAAW,CAAA,YAAA,EAAe,QAAQ,CAAA,EAAA,CAAA,GAAO,EAAA;AACpD,MAAA,OAAO,CAAA,OAAA,EAAU,MAAM,CAAA,uBAAA,EAA0B,SAAS,IAAI,EAAE,CAAA,kNAAA,CAAA;AAAA,IAClE;AAAA,IACA,KAAK,gBAAA;AACH,MAAA,OAAO,CAAA,wCAAA,EAA2C,QAAA,CAAS,MAAM,CAAA,gBAAA,EAAm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IAAI,CAAA,IAAA,EAAO,QAAQ,EAAE,CAAA,EAAA,EAAK,QAAQ,OAAO,CAAA;;AAAA;;AAAA;AAAA;AAAA,EAMlF,QAAQ;;AAAA;AAAA;;AAAA;;AAAA,EAOR,YAAY;;AAAA,EAEZ,cAAc,CAAA,EAAG,iBAAiB,CAAA,EAAG,mBAAmB,CAAA;;AAAA,EAExD,iBAAiB;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA2BnB;AAUO,SAAS,iBAAiB,QAAA,EAAgC;AAC/D,EAAA,QAAQ,SAAS,IAAA;AAAM,IACrB,KAAK,cAAA;AACH,MAAA,OAAO,cAAA;AAAA,IACT,KAAK,mBAAA;AACH,MAAA,OAAO,CAAA,kBAAA,EAAqB,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI,SAAS,QAAQ,CAAA,CAAA;AAAA,IAClE,KAAK,gBAAA;AACH,MAAA,OAAO,CAAA,eAAA,EAAkB,SAAS,MAAM,CAAA,CAAA;AAAA,IAC1C,KAAK,iBAAA;AACH,MAAA,OAAO,CAAA,gBAAA,EAAmB,SAAS,MAAM,CAAA,CAAA;AAAA,IAC3C,KAAK,cAAA;AACH,MAAA,OAAO,CAAA,aAAA,EAAgB,SAAS,QAAQ,CAAA,CAAA;AAAA,IAC1C,KAAK,2BAAA;AACH,MAAA,OAAO,2BAAA;AAAA,IACT,KAAK,WAAA;AACH,MAAA,OAAO,WAAA;AAAA,IACT,KAAK,eAAA;AACH,MAAA,OAAO,eAAA;AAAA;AAEb","file":"chunk-SCR3WGW7.js","sourcesContent":["/**\n * Prompt fragments for the flow connector.\n *\n * Pure functions that translate a {@link TurnStimulus} into the strings the\n * runner's flow orchestrator splices into the per-turn agent prompt.\n * Extracted from `runner/src/flow-orchestrator.ts` in Phase 3 of the\n * flow-connector extraction (2026-05-08) so the connector owns its\n * prompt-rendering surface without a runtime dep on the orchestrator.\n *\n * The contract is byte-identical to the previous inline implementation —\n * any divergence is a regression.\n *\n * @docLink packages/factory-assets/flow#prompt-fragments\n */\n\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport type { FlowDefinition } from \"./engine/types.js\";\nimport {\n flowDefaults,\n isAgentNode,\n isGateNode,\n nodeIsOptional,\n nodeLabel,\n nodeRequiresApproval,\n} from \"./engine/node-shape.js\";\n\n/**\n * Reasons why a new turn is starting. The flow orchestrator's prompt template\n * renders a stimulus-specific paragraph (via {@link renderStimulusPrompt}) so\n * the agent knows exactly why it has been invoked.\n *\n * @docLink packages/factory-assets/flow#turn-stimulus\n */\nexport type TurnStimulus =\n | { kind: \"flow_started\" }\n | {\n kind: \"approval_received\";\n nodeId: string;\n decision: \"approved\" | \"rejected\";\n feedback?: string;\n decidedBy: string;\n }\n | { kind: \"input_received\"; nodeId: string; response: unknown; providedBy: string }\n | { kind: \"retry_requested\"; nodeId: string; requestedBy: string }\n | { kind: \"user_message\"; text: string; senderId: string }\n | { kind: \"resumed_after_hibernation\" }\n | { kind: \"cancelled\" }\n | { kind: \"state_changed\" };\n\n/**\n * Render the stimulus paragraph the agent sees at turn start.\n *\n * The output is a single paragraph (one or more sentences, no surrounding\n * whitespace) describing why the runner has woken the agent. Spliced into\n * the orchestrator prompt under the `## Why this turn is happening` heading.\n *\n * @docLink packages/factory-assets/flow#render-stimulus-prompt\n */\nexport function renderStimulusPrompt(stimulus: TurnStimulus): string {\n switch (stimulus.kind) {\n case \"flow_started\":\n return \"The user just started this flow. Begin with the first available node — call `get_available`, then `build_handoff` for your chosen node, then `start_node`.\";\n case \"approval_received\": {\n const { nodeId, decision, decidedBy, feedback } = stimulus;\n if (decision === \"approved\") {\n return `Node \\`${nodeId}\\` was **approved** by ${decidedBy}. Call \\`complete_node\\` for this node with the approved output, then advance to the next available node.`;\n }\n const fb = feedback ? ` Feedback: \"${feedback}\".` : \"\";\n return `Node \\`${nodeId}\\` was **rejected** by ${decidedBy}.${fb} Decide how to proceed: retry the node (the engine returned it to \\`available\\`), ask clarifying questions via \\`request_input\\`, or call \\`fail_node(..., recoverable: false)\\` if the issue cannot be addressed.`;\n }\n case \"input_received\":\n return `The user just provided input for node \\`${stimulus.nodeId}\\` (provided by ${stimulus.providedBy}). The node has returned to its prior status. Continue executing the node with this input.`;\n case \"retry_requested\":\n return `A user requested a retry of node \\`${stimulus.nodeId}\\` (requested by ${stimulus.requestedBy}). The node has been returned to \\`available\\` with its prior error preserved in history. Start a fresh attempt — review the error context if relevant and try a different approach.`;\n case \"user_message\":\n return `A user sent a message: \"${stimulus.text}\" (from ${stimulus.senderId}). You can respond directly without touching the flow, continue flow work, or both. If the message is a question about the flow, answer it; if it signals a new direction, consider whether to pause.`;\n case \"resumed_after_hibernation\":\n return \"This session was hibernated and has just resumed. Review the current state above and continue where you left off. No state was lost.\";\n case \"cancelled\":\n return \"The user has cancelled this flow. Wrap up cleanly: do not start any new nodes. You may record a short summary if relevant, then stop.\";\n case \"state_changed\":\n return \"The flow state changed. Review the current state above and continue work accordingly.\";\n }\n}\n\n/**\n * Build the full agent-orchestrator prompt for a flow turn.\n *\n * Reassembles the five-section prompt from the current FlowExecution snapshot\n * and the supplied stimulus:\n *\n * 1. Flow definition (markdown table of nodes)\n * 2. Current state (progress, available/blocked, interaction pointers)\n * 3. Why this turn is happening (stimulus-specific paragraph)\n * 4. Flow tools available (static documentation)\n * 5. Rules\n *\n * Originally a byte-identical lift of the (since-deleted)\n * `FlowOrchestrator.buildOrchestratorPrompt`; the contract now is simply\n * this function's own output. When strict v2 defaults or legacy globals are\n * non-empty, a `## Flow globals` section exposes those run-scoped values. The\n * flow-wide active-node table stays bounded to selection metadata; `build_handoff`\n * supplies a selected agent node's execution payload. First-class gates appear\n * as runtime-owned state but never as agent-executable work.\n * Pure — depends only on its inputs.\n *\n * @docLink packages/factory-assets/flow#build-orchestrator-prompt\n * @since 2.2.0\n */\nexport function buildOrchestratorPrompt(\n flowDef: FlowDefinition,\n state: FlowExecution,\n stimulus: TurnStimulus,\n): string {\n const agentNodes = flowDef.nodes.filter(isAgentNode);\n const gateNodes = flowDef.nodes.filter(isGateNode);\n const promptNodes = flowDef.nodes.filter((node) => isAgentNode(node) || isGateNode(node));\n const agentNodeIds = new Set(agentNodes.map((node) => node.id));\n const promptNodeIds = new Set(promptNodes.map((node) => node.id));\n\n // ── Section 1: definition table ──\n const nodeRows = promptNodes\n .map((n) => {\n const deps =\n flowDef.edges\n .filter((e) => e.target === n.id && e.type === \"flow\")\n .map((e) => e.source)\n .join(\", \") || \"—\";\n const required = nodeIsOptional(n) ? \"optional\" : \"required\";\n const gate = isGateNode(n) ? \"first-class\" : nodeRequiresApproval(n) ? \"mandatory\" : \"—\";\n const nodeState = state.nodes[n.id];\n const status = nodeState?.status ?? \"not_started\";\n const description = (n.description ?? n.data?.description ?? \"—\")\n .replace(/\\s+/g, \" \")\n .replaceAll(\"|\", \"\\\\|\");\n return `| ${n.id} | ${nodeLabel(n)} | ${description} | ${required} | ${gate} | ${status} | ${deps} |`;\n })\n .join(\"\\n\");\n\n // ── Section 2: current state summary ──\n const nodesByStatus = (s: string) =>\n Object.values(state.nodes)\n .filter((n) => promptNodeIds.has(n.id) && n.status === s)\n .map((n) => n.id);\n const available = nodesByStatus(\"available\");\n const awaitingApproval = nodesByStatus(\"awaiting_approval\");\n const awaitingInput = nodesByStatus(\"awaiting_input\");\n const running = nodesByStatus(\"running\");\n const failed = nodesByStatus(\"failed\");\n const completed = nodesByStatus(\"complete\");\n const totalRequired = promptNodes.filter((n) => !nodeIsOptional(n)).length;\n\n const stateSummary = [\n `- Run ID: ${state.runId}`,\n `- Status: ${state.status}`,\n `- Autonomous mode: ${state.autonomousMode}`,\n `- Progress: ${completed.length} / ${totalRequired} required nodes complete`,\n `- Available now: ${available.join(\", \") || \"(none)\"}`,\n `- Currently running: ${running.join(\", \") || \"(none)\"}`,\n `- Awaiting approval: ${awaitingApproval.join(\", \") || \"(none)\"}`,\n `- Awaiting input: ${awaitingInput.join(\", \") || \"(none)\"}`,\n `- Failed: ${failed.join(\", \") || \"(none)\"}`,\n ].join(\"\\n\");\n\n const outputCorrections = Object.values(state.nodes)\n .filter(\n (node) =>\n agentNodeIds.has(node.id) &&\n node.outputCorrection &&\n node.status !== \"complete\" &&\n node.status !== \"failed\",\n )\n .map(\n (node) =>\n `- Node \\`${node.id}\\`: ${node.outputCorrection?.issues.join(\"; \") ?? \"unknown issue\"}`,\n );\n const correctionSection =\n outputCorrections.length > 0\n ? `## Output correction required\n\nThe following node has already used its single corrective reprompt. Submit one corrected \\`complete_node\\` call that fixes every issue; a second mismatch fails the node.\n\n${outputCorrections.join(\"\\n\")}\n\n`\n : \"\";\n\n const rejectedGates = gateNodes.flatMap((node) => {\n const approval = state.nodes[node.id]?.approval;\n if (approval?.decision !== \"rejected\") return [];\n return [\n `- \\`${node.id}\\` — rejected by ${approval.decidedBy ?? \"unknown reviewer\"}: ${\n approval.feedback ?? \"(no feedback provided)\"\n }`,\n ];\n });\n const rejectedGateSection =\n rejectedGates.length > 0\n ? `## Rejected first-class gates requiring revision\n\n${rejectedGates.join(\"\\n\")}\n\nRevise the surrounding work in conversation, then re-request each gate with \\`request_approval(nodeId, summary, artifacts)\\`. Every gate remains parked until its new human decision; do not start, complete, skip, or fail a first-class gate.\n\n`\n : \"\";\n\n // ── Section 2b: flow globals (additive — omitted entirely when empty so\n // flows without globals keep the byte-identical Phase 3 prompt) ──\n const globals = flowDefaults(flowDef);\n const globalsSection =\n Object.keys(globals).length > 0\n ? `## Flow globals\n\nRun-scoped parameters set by the flow author or by the host that started this run. When \\`run_input\\` is present it carries the payload this run was started with (e.g. a scheduled or webhook-triggered run) — treat it as the run's initial input instead of asking the user for it.\n\n\\`\\`\\`json\n${JSON.stringify(globals, null, 2)}\n\\`\\`\\`\n\n`\n : \"\";\n\n // ── Section 3: stimulus paragraph ──\n const stimulusNode =\n stimulus.kind === \"approval_received\"\n ? flowDef.nodes.find((node) => node.id === stimulus.nodeId)\n : undefined;\n let stimulusParagraph = renderStimulusPrompt(stimulus);\n if (stimulus.kind === \"approval_received\" && stimulusNode && isGateNode(stimulusNode)) {\n if (stimulus.decision === \"approved\") {\n const availableSuccessors = agentNodes\n .filter((node) => state.nodes[node.id]?.status === \"available\")\n .map((node) => `\\`${node.id}\\``);\n stimulusParagraph = `Gate node \\`${stimulus.nodeId}\\` is already \\`complete\\` after approval by ${stimulus.decidedBy}. Do not call \\`complete_node\\` for the gate. Advance to successor work${\n availableSuccessors.length > 0\n ? `; available agent nodes: ${availableSuccessors.join(\", \")}`\n : \"\"\n } — call \\`get_available\\`, then \\`build_handoff\\` and \\`start_node\\` for the chosen agent node.`;\n } else {\n stimulusParagraph = `Gate node \\`${stimulus.nodeId}\\` was **rejected** by ${stimulus.decidedBy}.${\n stimulus.feedback ? ` Feedback: \"${stimulus.feedback}\".` : \"\"\n } Revise the work in conversation and follow the rejected-gate instructions above.`;\n }\n }\n\n // ── Section 4+5: static tool surface and rules ──\n return `# Flow Execution Context\n\nYou are orchestrating the flow **${flowDef.name}** (${flowDef.id} v${flowDef.version}). This is a governed flow execution: your job is to run nodes through the flow tools, summarize their outputs for human review, and yield control at approval gates.\n\n## Flow definition\n\n| ID | Label | Description | Required | Gate | Status | Depends on |\n|----|-------|-------------|----------|------|--------|------------|\n${nodeRows}\n\nNodes with **Gate = mandatory** are hard approval gates: they always require \\`request_approval\\` and a human decision, even when autonomous mode is on. They cannot be skipped — \\`request_approval\\` → approval is their only completion path.\nNodes with **Gate = first-class** are runtime-owned human decisions. The runtime parks them automatically and completes them directly on approval; the agent never executes them.\n\n## Current state\n\n${stateSummary}\n\n${globalsSection}${correctionSection}${rejectedGateSection}## Why this turn is happening\n\n${stimulusParagraph}\n\n## Flow tools available\n\nAll tools are exposed by the \\`flow\\` connector:\n\n- \\`get_available()\\` — list node IDs that are ready to start\n- \\`get_state()\\` — full current state including approvals, inputs, outputs\n- \\`get_globals()\\` — the flow's run-scoped globals (e.g. the \\`run_input\\` payload for scheduled/params-bound runs)\n- \\`build_handoff(nodeId)\\` — selected node instruction, supplied bindings, required assets, and upstream context\n- \\`start_node(nodeId)\\` — transition an agent node from \\`available\\` → \\`running\\`; call before executing it. Never start a first-class gate.\n- \\`request_approval(nodeId, summary, artifacts)\\` — transition a running agent node to \\`awaiting_approval\\`, or replace a rejected first-class gate's decision with a fresh pending request. **This ends your turn.**\n- \\`request_input(nodeId, prompt, schema)\\` — transition to \\`awaiting_input\\`. **This ends your turn.** Legal from \\`available\\`, \\`running\\`, or \\`awaiting_approval\\`.\n- \\`complete_node(nodeId, summary, fields?, artifacts?, concerns?)\\` — complete an agent node. When downstream nodes consume declared output fields, include a conforming JSON object. The first mismatch gets one corrective call; the second fails the node. Valid only if the agent node was approved, OR autonomousMode is true and it does not require mandatory approval. First-class gates are completed by the runtime on approval; never call this tool for them.\n- \\`fail_node(nodeId, message, recoverable)\\` — transition to \\`failed\\`. \\`recoverable=true\\` returns the node to \\`available\\`.\n- \\`skip_node(nodeId)\\` — transition to \\`skipped\\`. Only valid for optional nodes.\n\n## Rules\n\n1. Before executing an agent node, call \\`build_handoff(nodeId)\\` and follow its instruction with the supplied bindings, assets, and upstream context; then call \\`start_node(nodeId)\\`.\n2. After executing the node, call \\`request_approval\\` unless \\`autonomousMode\\` is true — in which case call \\`complete_node\\` directly. Exception: nodes marked **Gate = mandatory** always require \\`request_approval\\` and a human decision, even in autonomous mode.\n3. First-class nodes marked **Gate = first-class** are runtime-owned. Never start, complete, skip, fail, or request input for them. After rejection, revise in conversation and only call \\`request_approval\\` to create the next attempt.\n4. If you need information from the user before or during agent execution, call \\`request_input\\`. This ends your turn until the user responds.\n5. On unrecoverable agent failure, call \\`fail_node(..., recoverable: false)\\`. On recoverable failure, call \\`fail_node(..., recoverable: true)\\` and the engine returns the node to \\`available\\`.\n6. When all required nodes are \\`complete\\` or \\`skipped\\`, stop. The runner marks the flow done automatically.\n7. Free-chat user messages do not require flow action. Respond directly, continue flow work, or both — your call.\n`;\n}\n\n/**\n * Single-line tag suitable for telemetry / logging. Derives a short, stable\n * summary of a stimulus that's safe to attach to spans, log entries, and\n * trace events. The kind is always included; node-specific stimuli also\n * include their `nodeId` so log queries can pivot on it.\n *\n * @docLink packages/factory-assets/flow#describe-stimulus\n */\nexport function describeStimulus(stimulus: TurnStimulus): string {\n switch (stimulus.kind) {\n case \"flow_started\":\n return \"flow_started\";\n case \"approval_received\":\n return `approval_received:${stimulus.nodeId}:${stimulus.decision}`;\n case \"input_received\":\n return `input_received:${stimulus.nodeId}`;\n case \"retry_requested\":\n return `retry_requested:${stimulus.nodeId}`;\n case \"user_message\":\n return `user_message:${stimulus.senderId}`;\n case \"resumed_after_hibernation\":\n return \"resumed_after_hibernation\";\n case \"cancelled\":\n return \"cancelled\";\n case \"state_changed\":\n return \"state_changed\";\n }\n}\n"]}
|
|
@@ -8,11 +8,14 @@ function isFunctionNode(node) {
|
|
|
8
8
|
function isGateNode(node) {
|
|
9
9
|
return node.run?.kind === "gate";
|
|
10
10
|
}
|
|
11
|
+
function isRouterNode(node) {
|
|
12
|
+
return node.run?.kind === "router";
|
|
13
|
+
}
|
|
11
14
|
function isSubFlowNode(node) {
|
|
12
15
|
return node.run?.kind === "sub-flow";
|
|
13
16
|
}
|
|
14
17
|
function isActiveRuntimeNode(node) {
|
|
15
|
-
return isAgentNode(node) || isFunctionNode(node) || isGateNode(node) || isSubFlowNode(node);
|
|
18
|
+
return isAgentNode(node) || isFunctionNode(node) || isGateNode(node) || isRouterNode(node) || isSubFlowNode(node);
|
|
16
19
|
}
|
|
17
20
|
function nodeIsOptional(node) {
|
|
18
21
|
return node.control?.optional ?? node.data?.optional ?? false;
|
|
@@ -45,6 +48,6 @@ function flowDefaults(flow) {
|
|
|
45
48
|
return flow.defaults ?? flow.globals ?? {};
|
|
46
49
|
}
|
|
47
50
|
|
|
48
|
-
export { flowDefaults, isActiveRuntimeNode, isAgentNode, isFunctionNode, isGateNode, isSubFlowNode, nodeAssets, nodeBindings, nodeInstruction, nodeIsOptional, nodeLabel, nodeRequiresApproval, nodeSkillId };
|
|
49
|
-
//# sourceMappingURL=chunk-
|
|
50
|
-
//# sourceMappingURL=chunk-
|
|
51
|
+
export { flowDefaults, isActiveRuntimeNode, isAgentNode, isFunctionNode, isGateNode, isRouterNode, isSubFlowNode, nodeAssets, nodeBindings, nodeInstruction, nodeIsOptional, nodeLabel, nodeRequiresApproval, nodeSkillId };
|
|
52
|
+
//# sourceMappingURL=chunk-TUYN2HDT.js.map
|
|
53
|
+
//# sourceMappingURL=chunk-TUYN2HDT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../factory-assets/connectors/flow/engine/node-shape.ts"],"names":[],"mappings":";AAGO,SAAS,YAAY,IAAA,EAAyB;AACnD,EAAA,OAAO,IAAA,CAAK,IAAA,KAAS,OAAA,IAAW,IAAA,CAAK,KAAK,IAAA,KAAS,OAAA;AACrD;AAGO,SAAS,eACd,IAAA,EACyF;AACzF,EAAA,OAAO,IAAA,CAAK,KAAK,IAAA,KAAS,UAAA;AAC5B;AAGO,SAAS,WACd,IAAA,EACqF;AACrF,EAAA,OAAO,IAAA,CAAK,KAAK,IAAA,KAAS,MAAA;AAC5B;AAGO,SAAS,aACd,IAAA,EACuF;AACvF,EAAA,OAAO,IAAA,CAAK,KAAK,IAAA,KAAS,QAAA;AAC5B;AAGO,SAAS,cACd,IAAA,EACyF;AACzF,EAAA,OAAO,IAAA,CAAK,KAAK,IAAA,KAAS,UAAA;AAC5B;AAGO,SAAS,oBAAoB,IAAA,EAAyB;AAC3D,EAAA,OACE,WAAA,CAAY,IAAI,CAAA,IAChB,cAAA,CAAe,IAAI,CAAA,IACnB,UAAA,CAAW,IAAI,CAAA,IACf,YAAA,CAAa,IAAI,CAAA,IACjB,cAAc,IAAI,CAAA;AAEtB;AAMO,SAAS,eAAe,IAAA,EAAyB;AACtD,EAAA,OAAO,IAAA,CAAK,OA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,OAAO,KAAA,GAAQ,CAAC,KAAA,EAAO,GAAG,YAAY,CAAA,GAAI,YAAA;AAC5C;AAGO,SAAS,aAAa,IAAA,EAAyC;AACpE,EAAA,IAAI,IAAA,CAAK,QAAA,EAAU,KAAA,EAAO,OAAO,KAAK,QAAA,CAAS,KAAA;AAC/C,EAAA,OAAO,IAAA,CAAK,IAAA,EAAM,UAAA,IAAc,EAAC;AACnC;AAGO,SAAS,gBAAgB,IAAA,EAAoC;AAClE,EAAA,OAAO,KAAK,GAAA,EAAK,IAAA,KAAS,OAAA,GAAU,IAAA,CAAK,IAAI,WAAA,GAAc,MAAA;AAC7D;AAGO,SAAS,aAAa,IAAA,EAA+C;AAC1E,EAAA,OAAO,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,OAAA,IAAW,EAAC;AAC3C","file":"chunk-TUYN2HDT.js","sourcesContent":["import type { FlowDefinition, FlowNode } from \"./types.js\";\n\n/** Returns whether a node is executable by the currently active agent-turn runtime. */\nexport function isAgentNode(node: FlowNode): boolean {\n return node.type === \"skill\" || node.run?.kind === \"agent\";\n}\n\n/** Returns whether a node executes deterministically through NodeExecutor. */\nexport function isFunctionNode(\n node: FlowNode,\n): node is FlowNode & { run: Extract<NonNullable<FlowNode[\"run\"]>, { kind: \"function\" }> } {\n return node.run?.kind === \"function\";\n}\n\n/** Returns whether a node is a runtime-owned human decision point. */\nexport function isGateNode(\n node: FlowNode,\n): node is FlowNode & { run: Extract<NonNullable<FlowNode[\"run\"]>, { kind: \"gate\" }> } {\n return node.run?.kind === \"gate\";\n}\n\n/** Returns whether a node deterministically selects one declared branch in the engine. */\nexport function isRouterNode(\n node: FlowNode,\n): node is FlowNode & { run: Extract<NonNullable<FlowNode[\"run\"]>, { kind: \"router\" }> } {\n return node.run?.kind === \"router\";\n}\n\n/** Returns whether a node delegates once to an inline child flow. */\nexport function isSubFlowNode(\n node: FlowNode,\n): node is FlowNode & { run: Extract<NonNullable<FlowNode[\"run\"]>, { kind: \"sub-flow\" }> } {\n return node.run?.kind === \"sub-flow\";\n}\n\n/** Returns whether the current runtime owns the node's execution state. */\nexport function isActiveRuntimeNode(node: FlowNode): boolean {\n return (\n isAgentNode(node) ||\n isFunctionNode(node) ||\n isGateNode(node) ||\n isRouterNode(node) ||\n isSubFlowNode(node)\n );\n}\n\n/** @deprecated Use {@link isActiveRuntimeNode}; gates are active but nobody executes them. */\nexport const isExecutableNode = isActiveRuntimeNode;\n\n/** Returns the node's optional policy across strict v2 and legacy definitions. */\nexport function nodeIsOptional(node: FlowNode): boolean {\n return node.control?.optional ?? node.data?.optional ?? false;\n}\n\n/** Returns the node's mandatory approval policy across strict v2 and legacy definitions. */\nexport function nodeRequiresApproval(node: FlowNode): boolean {\n return node.gate?.approval === \"mandatory\" || node.data?.approval?.mandatory === true;\n}\n\n/** Returns the first declared skill requirement without making it the node identity. */\nexport function nodeSkillId(node: FlowNode): string {\n if (node.type === \"skill\") return node.data?.skill ?? node.id;\n const skillAsset = node.run?.assets?.find((asset) => asset.startsWith(\"skill:\"));\n return skillAsset?.slice(\"skill:\".length).replace(/#.*$/, \"\") ?? node.id;\n}\n\n/** Returns the user-facing node label across strict v2 and legacy definitions. */\nexport function nodeLabel(node: FlowNode): string {\n return node.label ?? node.data?.label ?? nodeSkillId(node);\n}\n\n/** Returns strict v2 run assets or the equivalent legacy declarations. */\nexport function nodeAssets(node: FlowNode): string[] {\n if (node.run?.assets) return node.run.assets;\n const legacyAssets = Array.isArray(node.data?.assets)\n ? node.data.assets.filter((asset): asset is string => typeof asset === \"string\")\n : [];\n const skill = node.type === \"skill\" && node.data?.skill ? `skill:${node.data.skill}` : undefined;\n return skill ? [skill, ...legacyAssets] : legacyAssets;\n}\n\n/** Returns the binding values already supplied at the node boundary. */\nexport function nodeBindings(node: FlowNode): Record<string, unknown> {\n if (node.contract?.input) return node.contract.input;\n return node.data?.parameters ?? {};\n}\n\n/** Returns the first-class instruction for a strict v2 agent node. */\nexport function nodeInstruction(node: FlowNode): string | undefined {\n return node.run?.kind === \"agent\" ? node.run.instruction : undefined;\n}\n\n/** Returns run-scoped defaults across strict v2 and legacy definitions. */\nexport function flowDefaults(flow: FlowDefinition): Record<string, unknown> {\n return flow.defaults ?? flow.globals ?? {};\n}\n"]}
|
|
@@ -20,10 +20,17 @@ function collectFlowBindingExpressions(value) {
|
|
|
20
20
|
var FlowExpressionError = class extends Error {
|
|
21
21
|
/** Stable error name for callers that classify evaluator failures. */
|
|
22
22
|
name = "FlowExpressionError";
|
|
23
|
+
/** Runtime path that was grammar-valid but absent from the supplied context. */
|
|
24
|
+
missingPath;
|
|
25
|
+
constructor(message, missingPath) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.missingPath = missingPath;
|
|
28
|
+
}
|
|
23
29
|
};
|
|
24
|
-
function expressionError(message, position) {
|
|
30
|
+
function expressionError(message, position, missingPath) {
|
|
25
31
|
return new FlowExpressionError(
|
|
26
|
-
position === void 0 ? `Flow expression ${message}` : `Flow expression ${message} at ${position}
|
|
32
|
+
position === void 0 ? `Flow expression ${message}` : `Flow expression ${message} at ${position}`,
|
|
33
|
+
missingPath
|
|
27
34
|
);
|
|
28
35
|
}
|
|
29
36
|
function parseString(source, start) {
|
|
@@ -128,11 +135,13 @@ function tokenize(source) {
|
|
|
128
135
|
return tokens;
|
|
129
136
|
}
|
|
130
137
|
var FORBIDDEN_PATH_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
|
|
131
|
-
function ownValue(value, segment, position) {
|
|
138
|
+
function ownValue(value, segment, position, path) {
|
|
132
139
|
if (typeof value !== "object" && typeof value !== "function" || value === null) {
|
|
133
|
-
throw expressionError("path does not exist", position);
|
|
140
|
+
throw expressionError("path does not exist", position, path);
|
|
141
|
+
}
|
|
142
|
+
if (!Object.hasOwn(value, segment)) {
|
|
143
|
+
throw expressionError("path does not exist", position, path);
|
|
134
144
|
}
|
|
135
|
-
if (!Object.hasOwn(value, segment)) throw expressionError("path does not exist", position);
|
|
136
145
|
return value[segment];
|
|
137
146
|
}
|
|
138
147
|
function resolvePath(raw, context, position, traverse) {
|
|
@@ -172,7 +181,7 @@ function resolvePath(raw, context, position, traverse) {
|
|
|
172
181
|
throw expressionError(`contains unsupported path ${raw}`, position);
|
|
173
182
|
}
|
|
174
183
|
if (!traverse) return void 0;
|
|
175
|
-
for (const segment of remaining) value = ownValue(value, segment, position);
|
|
184
|
+
for (const segment of remaining) value = ownValue(value, segment, position, raw);
|
|
176
185
|
return value;
|
|
177
186
|
}
|
|
178
187
|
function compare(operator, left, right, position) {
|
|
@@ -595,15 +604,17 @@ var NodeControlSchema = z.strictObject({
|
|
|
595
604
|
subagent: z.boolean().optional()
|
|
596
605
|
});
|
|
597
606
|
var runAssets = { assets: z.array(nonEmptyString).optional() };
|
|
607
|
+
var modelTier = z.enum(["small", "default", "deep"]);
|
|
598
608
|
var AgentRunSchema = z.strictObject({
|
|
599
609
|
kind: z.literal("agent"),
|
|
600
610
|
instruction: nonEmptyString,
|
|
611
|
+
model: modelTier.optional(),
|
|
601
612
|
...runAssets
|
|
602
613
|
});
|
|
603
614
|
var SubpromptRunSchema = z.strictObject({
|
|
604
615
|
kind: z.literal("subprompt"),
|
|
605
616
|
instruction: nonEmptyString,
|
|
606
|
-
model:
|
|
617
|
+
model: modelTier.optional(),
|
|
607
618
|
...runAssets
|
|
608
619
|
});
|
|
609
620
|
var deterministicRun = {
|
|
@@ -1232,5 +1243,5 @@ function parseFlowDefinition(data) {
|
|
|
1232
1243
|
}
|
|
1233
1244
|
|
|
1234
1245
|
export { FLOW_EXPRESSION_LIMITS, FlowDefinitionSchema, FlowExpressionError, collectFlowBindingExpressions, evaluate, evaluateFlowExpression, inspectFlowExpression, normalizeV1, parseFlowDefinition, resolveFlowBindings, stableFlowJson };
|
|
1235
|
-
//# sourceMappingURL=chunk-
|
|
1236
|
-
//# sourceMappingURL=chunk-
|
|
1246
|
+
//# sourceMappingURL=chunk-XJ74XFIZ.js.map
|
|
1247
|
+
//# sourceMappingURL=chunk-XJ74XFIZ.js.map
|