@skaile/workspaces 0.11.1 → 0.12.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 +38 -0
- package/dist/base-assets/connectors/flow/run-flow.js +1 -1
- package/dist/bridge/drivers/claude-sdk.js +31 -28
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +1 -1
- package/dist/bridge/drivers/echo.js +1 -1
- package/dist/bridge/drivers/omp.js +1 -1
- package/dist/bridge/index.js +3 -3
- package/dist/bridge/src/drivers/claude-sdk.d.ts +33 -17
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/error-classifier.d.ts.map +1 -1
- package/dist/{chunk-YOFKTALB.js → chunk-4ACWI5YT.js} +2 -2
- package/dist/{chunk-YOFKTALB.js.map → chunk-4ACWI5YT.js.map} +1 -1
- package/dist/{chunk-XYEFV7XN.js → chunk-DDVKNST3.js} +2 -2
- package/dist/{chunk-XYEFV7XN.js.map → chunk-DDVKNST3.js.map} +1 -1
- package/dist/{chunk-EWP5HZBV.js → chunk-DQWREFRQ.js} +11 -2
- package/dist/chunk-DQWREFRQ.js.map +1 -0
- package/dist/{chunk-VMU2WEN7.js → chunk-S2OVTCAL.js} +4 -4
- package/dist/{chunk-VMU2WEN7.js.map → chunk-S2OVTCAL.js.map} +1 -1
- package/dist/{chunk-34333Z5H.js → chunk-UTKGPNLV.js} +5 -5
- package/dist/{chunk-34333Z5H.js.map → chunk-UTKGPNLV.js.map} +1 -1
- package/dist/cli/index.js +6 -6
- package/dist/runner/index.js +4 -4
- package/dist/sdk/bridge.js +3 -3
- package/dist/sdk/index.js +4 -4
- package/dist/sdk/runner.js +4 -4
- package/dist/{setup-QAOUBECX.js → setup-WZFCLQ2J.js} +5 -5
- package/dist/{setup-QAOUBECX.js.map → setup-WZFCLQ2J.js.map} +1 -1
- package/dist/tui/index.js +4 -4
- package/package.json +14 -15
- package/dist/chunk-EWP5HZBV.js.map +0 -1
|
@@ -34,6 +34,22 @@ import { type AgentConfig, AgentDriver, type DriverInfo, type SlashCommandInfo }
|
|
|
34
34
|
*
|
|
35
35
|
* @docLink packages/bridge/drivers#claude-sdk-driver
|
|
36
36
|
*/
|
|
37
|
+
/**
|
|
38
|
+
* One-shot recovery budgets for a single logical {@link ClaudeSdkDriver.prompt}
|
|
39
|
+
* turn. Each recovery path owns an independent budget so an earlier recovery of
|
|
40
|
+
* one kind never starves a later recovery of a different kind — most
|
|
41
|
+
* importantly, a stale-resume retry must not consume the auth self-heal budget,
|
|
42
|
+
* because the fresh session it starts can still hit an expired credential.
|
|
43
|
+
* Total retries stay bounded (at most one per kind).
|
|
44
|
+
*/
|
|
45
|
+
interface RetryBudget {
|
|
46
|
+
/** A stale-resume ("No conversation found") retry has been spent. */
|
|
47
|
+
staleResume: boolean;
|
|
48
|
+
/** A poisoned-transcript scrub retry has been spent. */
|
|
49
|
+
poison: boolean;
|
|
50
|
+
/** An auth self-heal (`onAuthError`) retry has been spent. */
|
|
51
|
+
auth: boolean;
|
|
52
|
+
}
|
|
37
53
|
export declare class ClaudeSdkDriver extends AgentDriver {
|
|
38
54
|
readonly driverInfo: DriverInfo;
|
|
39
55
|
private readonly log;
|
|
@@ -52,16 +68,15 @@ export declare class ClaudeSdkDriver extends AgentDriver {
|
|
|
52
68
|
/** Guards against duplicate agent_end emissions per turn. */
|
|
53
69
|
private turnCompleted;
|
|
54
70
|
/**
|
|
55
|
-
* Mirror of the
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* `onAuthError` self-heal branch.
|
|
71
|
+
* Mirror of the in-flight {@link prompt} call's auth retry budget: `false`
|
|
72
|
+
* while the `onAuthError` self-heal is still available, `true` once it has
|
|
73
|
+
* been spent. Read by {@link failTurn} to decide whether to defer the
|
|
74
|
+
* `agent-event: error` emission for a self-healable auth error.
|
|
60
75
|
*
|
|
61
76
|
* Set unconditionally at the top of every {@link prompt} invocation; never
|
|
62
77
|
* reset elsewhere — the next call's set is the only legitimate transition.
|
|
63
78
|
*/
|
|
64
|
-
private
|
|
79
|
+
private authSelfHealUsed;
|
|
65
80
|
/** Tracks whether a session has been started (for continue: true). */
|
|
66
81
|
private hasSession;
|
|
67
82
|
/** Session ID from the SDK — used for streamInput messages. */
|
|
@@ -117,7 +132,7 @@ export declare class ClaudeSdkDriver extends AgentDriver {
|
|
|
117
132
|
* "No conversation found with session ID …" — a recoverable stale-resume error that
|
|
118
133
|
* occurs after a container crash that prevented the SDK from flushing its session file.
|
|
119
134
|
*/
|
|
120
|
-
prompt(message: string,
|
|
135
|
+
prompt(message: string, _budget?: RetryBudget): Promise<void>;
|
|
121
136
|
/**
|
|
122
137
|
* Resolve the Claude Code config directory — the parent of `projects/` — from
|
|
123
138
|
* the driver config, the process environment, or the `~/.claude` default.
|
|
@@ -196,16 +211,16 @@ export declare class ClaudeSdkDriver extends AgentDriver {
|
|
|
196
211
|
* caller transitions even if the listener chain misbehaves; the emit is
|
|
197
212
|
* wrapped in try/catch so a listener failure cannot leak out.
|
|
198
213
|
*
|
|
199
|
-
* Self-heal deferral: when the failure is an {@link AuthError}
|
|
200
|
-
*
|
|
201
|
-
* `onAuthError` callback, the downstream `agent-event: error`
|
|
202
|
-
* is deferred. The rejected turn promise still travels to
|
|
203
|
-
* catch block where the self-heal runs; if the retry
|
|
204
|
-
* never sees a 401, if the retry fails the second
|
|
205
|
-
* with `
|
|
206
|
-
* the historical "401 flashes in the UI even though
|
|
207
|
-
* misbehaviour where the bridge emitted the error event
|
|
208
|
-
* retry decision was known.
|
|
214
|
+
* Self-heal deferral: when the failure is an {@link AuthError} and the auth
|
|
215
|
+
* self-heal budget is still available (`!authSelfHealUsed`) AND the caller
|
|
216
|
+
* wired an `onAuthError` callback, the downstream `agent-event: error`
|
|
217
|
+
* emission is deferred. The rejected turn promise still travels to
|
|
218
|
+
* {@link prompt}'s catch block where the self-heal runs; if the retry
|
|
219
|
+
* succeeds the user never sees a 401, if the retry fails the second
|
|
220
|
+
* `failTurn` call (now with `authSelfHealUsed === true`) emits the error
|
|
221
|
+
* normally. This stops the historical "401 flashes in the UI even though
|
|
222
|
+
* self-heal worked" misbehaviour where the bridge emitted the error event
|
|
223
|
+
* before the retry decision was known.
|
|
209
224
|
*
|
|
210
225
|
* Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`
|
|
211
226
|
* § "Runner-side handling on 401" (the AI 401 mediation path that
|
|
@@ -266,4 +281,5 @@ export declare class ClaudeSdkDriver extends AgentDriver {
|
|
|
266
281
|
*/
|
|
267
282
|
private findClaudeBinary;
|
|
268
283
|
}
|
|
284
|
+
export {};
|
|
269
285
|
//# sourceMappingURL=claude-sdk.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"claude-sdk.d.ts","sourceRoot":"","sources":["../../../../bridge/src/drivers/claude-sdk.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAU,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAanE,OAAO,EAAuB,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AAEpE,OAAO,EACL,KAAK,WAAW,EAChB,WAAW,EAIX,KAAK,UAAU,EACf,KAAK,gBAAgB,EAEtB,MAAM,aAAa,CAAC;AAiErB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,qBAAa,eAAgB,SAAQ,WAAW;IAC9C,QAAQ,CAAC,UAAU,EAAE,UAAU,CAK7B;IAEF,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAyC;IAC7D,OAAO,CAAC,MAAM,CAAc;IAC5B,OAAO,CAAC,eAAe,CAAgC;IACvD,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,GAAG,CAA6C;IACxD,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,QAAQ,CAAM;IAEtB,wEAAwE;IACxE,OAAO,CAAC,KAAK,CAAyB;IACtC,gDAAgD;IACh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BAAmB;IA+B3B,OAAO,CAAC,cAAc;IAqBtB;;;;;;OAMG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAanC,+DAA+D;IAC/D,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED;;;;;OAKG;IACI,IAAI,IAAI,IAAI;IAeJ,UAAU,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;IAUzC,aAAa,IAAI,UAAU,GAAG,IAAI;IAIlC,gBAAgB,IAAI,MAAM,GAAG,IAAI;IAIpC,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAgBnC;;;;;;OAMG;IACH,OAAO,CAAC,qBAAqB;IAuB7B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAazB;;;;;;;;;;OAUG;IACH,OAAO,CAAC,gBAAgB;CAQzB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error-classifier.d.ts","sourceRoot":"","sources":["../../../bridge/src/error-classifier.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;gBAChB,MAAM,EAAE,UAAU;CAK/B;AAcD;;;;;;;GAOG;AACH,MAAM,WAAW,yBAAyB;IACxC,qEAAqE;IACrE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,yBAAyB,GAAG,UAAU,
|
|
1
|
+
{"version":3,"file":"error-classifier.d.ts","sourceRoot":"","sources":["../../../bridge/src/error-classifier.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;gBAChB,MAAM,EAAE,UAAU;CAK/B;AAcD;;;;;;;GAOG;AACH,MAAM,WAAW,yBAAyB;IACxC,qEAAqE;IACrE,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,+DAA+D;IAC/D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,yBAAyB,GAAG,UAAU,CA4O5F"}
|
|
@@ -197,5 +197,5 @@ async function listModelsForDriver(driverId, apiKeys) {
|
|
|
197
197
|
}
|
|
198
198
|
|
|
199
199
|
export { AgentDriver, DRIVER_CATALOG, createDriver, getBridgeLogger, listDrivers, listModelsForDriver, loadDriver, registerDriver };
|
|
200
|
-
//# sourceMappingURL=chunk-
|
|
201
|
-
//# sourceMappingURL=chunk-
|
|
200
|
+
//# sourceMappingURL=chunk-4ACWI5YT.js.map
|
|
201
|
+
//# sourceMappingURL=chunk-4ACWI5YT.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/logger.ts","../bridge/src/types.ts","../bridge/src/registry.ts"],"names":[],"mappings":";;;;AAuBO,SAAS,gBAAgB,OAAA,EAAyB;AACvD,EAAA,OAAO,YAAA,CAAa,EAAE,IAAA,EAAM,QAAA,EAAU,SAAS,CAAA;AACjD;AC4ZO,IAAe,WAAA,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AAA,MAAM,KAAA,GAAQ,cAAA,CAAe,GAAA,CAAI,QAAQ,CAAA;AACzC,EAAA,IAAI,CAAC,KAAA,EAAO,OAAO,EAAC;AAGpB,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,OAAA,CAAQ,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAI,EAAG,SAAA,EAAW,YAAA,EAAc,OAAA,EAAS,CAAA;AACrF,EAAA,OAAO,OAAO,UAAA,EAAW;AAC3B","file":"chunk-YOFKTALB.js","sourcesContent":["/**\n * Bridge-layer logger factory.\n *\n * Each driver creates its own Logger via `getBridgeLogger(subkind)` at\n * construction time. Falls back to an off-mode Logger (stdout only) when\n * no LogStore is registered — see @skaile/workspaces/core/logging for details.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * Construct a bridge-scoped Logger for a given driver subkind.\n *\n * Creates a `Logger` with `kind: \"bridge\"` and the specified `subkind`. Falls back to\n * an off-mode Logger (stdout only) when no `LogStore` is registered — see\n * `@skaile/workspaces/core/logging` for details. Each driver calls this once at construction\n * time; never re-construct per call.\n *\n * @param subkind - Driver id, e.g. `\"claude-sdk\"`, `\"omp\"`, `\"echo\"`, `\"codex\"`.\n * @returns A `Logger` scoped to `bridge:<subkind>`.\n * @docLink packages/bridge/api-reference#logger\n */\nexport function getBridgeLogger(subkind: string): Logger {\n return createLogger({ kind: \"bridge\", subkind });\n}\n","import { EventEmitter } from \"node:events\";\nimport type { Span, TelemetryProvider, Trace } from \"@skaile/workspaces/telemetry\";\nimport type {\n Capability,\n CredentialMint,\n RenderInvokedEvent,\n TokenUsage,\n} from \"@skaile/workspaces/types\";\nimport type { ModelEntry } from \"./models.js\";\n\n/**\n * Minimal LLM tool descriptor used by the capability dispatch path. Mirrors\n * the runner's `LLMTool` shape so drivers can consume registry output without\n * importing `@skaile/workspaces/runner` (which would create a circular dep).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-tool\n */\nexport interface BridgeCapabilityTool {\n /** Capability name; used as the LLM-visible tool name. */\n name: string;\n /** Human/LLM-readable description. */\n description: string;\n /** JSON Schema for the tool's input parameters. */\n parameters: Record<string, unknown>;\n}\n\n/**\n * Render-cap event emission callback used by the bridge when the LLM invokes\n * a capability that carries a `render` spec. The runner provides the actual\n * sink (transport.send / sendEvent); the bridge only emits.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-render-emit\n */\nexport type BridgeRenderEmit = (event: RenderInvokedEvent) => void;\n\n/**\n * Text-event emission callback for render-capability fallbacks. When a\n * `RenderCapability` carries `render.fallback` and the LLM invokes it, the\n * bridge substitutes `{{prop}}` placeholders (top-level keys of `props`,\n * optional dotted-path traversal `{{user.name}}`) and pushes the rendered\n * string through this callback so clients without a render layer still see\n * a textual representation. No-op when `fallback` is absent.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-text-emit\n */\nexport type BridgeTextEmit = (text: string) => void;\n\n/**\n * Bundle of capability dispatch hooks. Registered into the driver via\n * `AgentConfig.capabilities`; the driver routes registered LLM tool calls\n * back into `invoke()` instead of using its native dispatch path.\n *\n * The runner constructs this from a `CapabilityRegistry` instance and threads\n * it through `createAgentSession()`. Drivers that don't yet implement\n * capability dispatch ignore the field — legacy v1 paths stay intact.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-hooks\n */\nexport interface BridgeCapabilityHooks {\n /** Build the LLM tool descriptor list from the registry. Called per turn so registration changes take effect. */\n composeTools(): BridgeCapabilityTool[];\n /** Resolve a wire-format Capability descriptor by name. Used by the bridge to inspect `fireAndForget` / `render`. */\n resolve(name: string): Capability | null;\n /** Validate input + dispatch through the registry. Logging is wired by the registry. */\n invoke(name: string, input: unknown): Promise<unknown>;\n /** Emit a render-invoked event. The runner forwards via the WebSocket transport. */\n emitRender?: BridgeRenderEmit;\n /** Emit a text fallback for render capabilities with `render.fallback`. */\n emitText?: BridgeTextEmit;\n /** Session id passed through to the runner's per-handler logger. */\n sessionId: string;\n}\n\n/**\n * Static metadata for a registered agent driver backend.\n *\n * Returned by {@link listDrivers} and exposed on every {@link AgentDriver} instance\n * via `driverInfo`.\n *\n * @docLink packages/bridge/concepts#driver-info\n */\nexport interface DriverInfo {\n /** Stable machine identifier used to look up the driver in the registry (e.g. `\"omp\"`, `\"claude-sdk\"`). */\n id: string;\n /** Human-readable display name shown in UIs and logs. */\n name: string;\n /** `true` when the driver can target any LLM provider; `false` for Anthropic-only drivers. */\n modelAgnostic: boolean;\n /**\n * `true` when the driver supports mid-stream abort via `abort()` without killing the process.\n * Drivers that return `false` can only be stopped via `kill()`.\n */\n supportsInBandAbort: boolean;\n}\n\n/**\n * Codex-specific tuning options passed through `DriverOptions.codex`.\n *\n * @remarks These are forwarded verbatim to the Codex driver and have no effect on other drivers.\n * @docLink packages/bridge/concepts#codex-driver-options\n */\nexport interface CodexDriverOptions {\n /** Controls whether Codex may auto-apply edits without user approval. */\n approvalPolicy?: \"never\" | \"on-request\" | \"on-failure\" | \"untrusted\";\n /** Filesystem sandbox level for the Codex process. */\n sandboxMode?: \"read-only\" | \"workspace-write\" | \"danger-full-access\";\n /** Reasoning budget passed to the model. */\n reasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** When `true`, the Codex sandbox is allowed to make outbound network requests. */\n networkAccessEnabled?: boolean;\n /** Extra directories made accessible to the Codex sandbox in addition to `cwd`. */\n additionalDirectories?: string[];\n}\n\n/**\n * Driver-specific configuration bag.\n *\n * Fields are keyed by driver ID so that callers can pass driver-specific options\n * through the common {@link AgentConfig} without breaking other drivers.\n *\n * @docLink packages/bridge/concepts#driver-options\n */\nexport interface DriverOptions {\n /** Codex-specific options. Ignored by all other drivers. */\n codex?: CodexDriverOptions;\n}\n\n/**\n * Configuration passed to a driver when it is created via {@link createDriver}.\n *\n * All fields are shared across drivers; driver-specific behaviour is documented\n * per field. Fields that are silently ignored by a driver are marked accordingly.\n *\n * @docLink packages/bridge/concepts#agent-config\n */\nexport interface AgentConfig {\n /** Absolute path to the working directory the agent operates in. */\n cwd: string;\n /**\n * LLM provider name (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * Combined with `model` as `provider/model` for omp's `--model` flag.\n * Ignored by claude-sdk (always Anthropic).\n */\n provider?: string;\n /**\n * LLM model identifier (e.g. `\"claude-sonnet-4-5\"`, `\"gpt-4o\"`).\n * For omp: passed as `--model [provider/]model`.\n * For claude-sdk: passed as the `model` query option.\n */\n model?: string;\n /**\n * Provider API keys keyed by provider name (e.g. `{ anthropic: \"sk-...\" }`).\n * Drivers inject the relevant key into the environment or SDK options.\n */\n apiKeys?: Record<string, string>;\n /**\n * Additional environment variables merged into the child process environment.\n * For omp: merged with `process.env` before spawn. For claude-sdk: accessed\n * via `env.ANTHROPIC_API_KEY` as an alternative to `apiKeys.anthropic`.\n */\n env?: Record<string, string>;\n /** Inline system prompt — written to .omp/system.md and passed via --append-system-prompt (omp driver) */\n systemPrompt?: string;\n /** Path to project .omp/ directory (PI_CODING_AGENT_DIR for omp driver) */\n agentDir?: string;\n /** SSH key path — injected as GIT_SSH_COMMAND */\n sshKeyPath?: string;\n /** Pre-assign a UUID as the session ID for a new session (claude-sdk: passed as sessionId option) */\n sessionId?: string;\n /** Resume this specific past session by UUID instead of starting fresh (claude-sdk: passed as resume option) */\n resumeSessionId?: string;\n /** Maximum agentic turns per query (claude-sdk: passed as maxTurns option) */\n maxTurns?: number;\n /** Agent name — selects a deployed sub-agent definition as the main agent identity.\n * claude-sdk: passed as `agent` option to query() → reads .claude/agents/<name>.md natively.\n * omp: ignored (omp uses agentDir/PI_CODING_AGENT_DIR instead). */\n agentName?: string;\n /** In-process SDK MCP servers for custom tool injection (Claude SDK only, ignored by other drivers) */\n mcpServers?: Record<string, unknown>;\n /** Tool restrictions from agent.yaml — applied to the main agent session */\n tools?: {\n /** Tool names that the agent is allowed to invoke. An empty array means no restriction. */\n allowed?: string[];\n /** Tool names that the agent is explicitly forbidden from invoking. */\n denied?: string[];\n };\n /** Thinking mode for Claude models: adaptive (Claude decides), enabled (always think), disabled (no thinking). */\n thinking?: \"adaptive\" | \"enabled\" | \"disabled\";\n /** Reasoning effort level for Claude models. */\n effort?: \"low\" | \"medium\" | \"high\" | \"max\";\n /** Driver-specific configuration bag. */\n driverOptions?: DriverOptions;\n /**\n * Protocol v2 capability dispatch hooks. When present, the driver uses the\n * registry as the source of LLM tool definitions and routes invocations\n * through `capabilities.invoke()`. Absent → legacy v1 path (existing\n * mcpServers / native dispatch).\n *\n * @since 2.0.0\n */\n capabilities?: BridgeCapabilityHooks;\n /**\n * The platform's `AIProviderConfig.id` for the AI credential currently\n * provisioned into this driver. The runner reads this off `AgentConfig`\n * during 401 mediation and passes it as `configId` in\n * `request_access_token { kind: 'ai-credentials' }`. The driver itself\n * does not consume this field — only the runner uses it.\n *\n * Set by the platform agent-gateway in `ConfigureCommandV2` for mediated\n * sessions. Standalone runners (CLI / forge / Claude plugin) leave it\n * undefined; the runner falls back to surfacing the auth error to the\n * user without mediating.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Wire `aiProviderConfigId` end-to-end\".\n *\n * @since 3.3.0\n */\n aiProviderConfigId?: string;\n /**\n * Optional callback invoked by the driver when the underlying agent\n * surfaces an `authentication_error`. In Protocol v3 the runner mediates\n * the refresh via the `host.refresh_credential` capability and returns a\n * typed {@link CredentialMint}. The driver inspects the discriminator:\n *\n * - `mint.ok === true`: a fresh credential is now provisioned. The\n * driver re-attempts the in-flight prompt once.\n * - `mint.ok === false`: refresh failed (`code` carries a stable reason\n * such as `revoked`, `not-configured`, `provider-error`,\n * `backend-error`). The driver surfaces the original `AuthError` to\n * the caller.\n *\n * `args.configId` carries the platform `AIProviderConfig.id` the driver\n * was provisioned with (mirrors {@link AgentConfig.aiProviderConfigId}).\n * The runner uses it to scope the refresh to the correct AI credential.\n *\n * When omitted, the driver throws `AuthError` immediately as before\n * (standalone CLI / forge mode — there is no platform mediator to ask).\n *\n * Centralising auth-retry inside the driver means every consumer of\n * `driver.prompt(...)` (serve handler, compaction orchestrator, flow\n * orchestrator, …) gets self-healing for free — there is no per-call-site\n * wrapping.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"host.refresh_credential capability\".\n *\n * @since 3.4.0\n */\n onAuthError?: (args: { configId: string }) => Promise<CredentialMint>;\n}\n\n/**\n * A single message in an agent conversation.\n *\n * Emitted as part of {@link AgentEvent} variants (`message_start`, `message_update`, `message_end`).\n *\n * @docLink packages/bridge/concepts#agent-message\n */\nexport interface AgentMessage {\n /** Originator of the message. */\n role: \"user\" | \"assistant\" | \"tool\";\n /** Message body — either a plain string or a list of typed content blocks. */\n content: string | ContentBlock[];\n /** Tool invocations made by the assistant in this message. */\n toolCalls?: ToolCall[];\n /** For `role === \"tool\"`: the name of the tool whose result this message carries. */\n toolName?: string;\n /** For `role === \"tool\"`: `true` when the tool returned an error. */\n isError?: boolean;\n /** Optional structured payload for tool results. */\n data?: unknown;\n}\n\n/**\n * A typed block within an {@link AgentMessage}'s content array.\n *\n * Mirrors the Anthropic content block schema but is driver-agnostic.\n *\n * @docLink packages/bridge/concepts#content-block\n */\nexport interface ContentBlock {\n /** Block discriminant. */\n type: \"text\" | \"tool_use\" | \"tool_result\" | \"thinking\";\n /** Present for `text` and `thinking` blocks. */\n text?: string;\n /** Tool use / tool result correlation ID. */\n id?: string;\n /** Tool name (present on `tool_use` blocks). */\n name?: string;\n /** Tool input arguments (present on `tool_use` blocks). */\n input?: any;\n /** Serialised tool result content (present on `tool_result` blocks). */\n content?: string;\n}\n\n/**\n * A single tool invocation made by the agent within a message.\n *\n * @docLink packages/bridge/concepts#tool-call\n */\nexport interface ToolCall {\n /** Correlation ID used to match the call with its result. */\n id: string;\n /** Name of the tool being invoked. */\n name: string;\n /** Arguments passed to the tool. */\n input: any;\n}\n\n/**\n * Error classification for agent failures.\n *\n * Used to determine whether a failure is retryable and to surface actionable\n * hints to the user. See `bridge/CLAUDE.md` for the full category-to-behaviour matrix.\n *\n * @see AgentError\n * @docLink packages/bridge/concepts#error-category\n */\nexport type ErrorCategory =\n | \"auth\"\n | \"rate_limit\"\n | \"model\"\n | \"network\"\n | \"config\"\n | \"process\"\n | \"validation\"\n | \"unknown\";\n\n/**\n * Structured error payload emitted inside the `error` {@link AgentEvent}.\n *\n * Consumers should inspect `retryable` before deciding to surface a retry button,\n * and `hint` to provide an actionable message to the user.\n *\n * @docLink packages/bridge/concepts#agent-error\n */\nexport interface AgentError {\n /** Human-readable error description. */\n message: string;\n /** Coarse failure classification used for retry logic and telemetry. */\n category: ErrorCategory;\n /** HTTP status code if the error originated from an API response. */\n statusCode?: number;\n /** `true` when the caller may safely retry the same operation. */\n retryable: boolean;\n /** Short actionable advice suitable for display in the UI. */\n hint?: string;\n}\n\n/**\n * Metadata for a slash command exposed by the active agent runtime.\n *\n * @docLink packages/bridge/concepts#slash-command-info\n */\nexport interface SlashCommandInfo {\n /** Command name without the leading slash (e.g. `\"compact\"`). */\n name: string;\n /** One-line description shown in command pickers. */\n description: string;\n /** Placeholder text describing what argument the command expects. */\n argumentHint?: string;\n}\n\n/**\n * Discriminated union of all events emitted by a driver on the `'agent-event'` channel.\n *\n * @remarks\n * Consumers listen via `driver.on('agent-event', (event: AgentEvent) => ...)`.\n * The `[k: string]: any` index signature on most variants allows drivers to attach\n * driver-specific fields (e.g. `_textDelta`) without breaking the union.\n *\n * @docLink packages/bridge/concepts#agent-event\n */\nexport type AgentEvent =\n | { type: \"message_start\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_update\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_end\"; message: AgentMessage; [k: string]: any }\n | { type: \"turn_end\"; toolResults?: AgentMessage[]; [k: string]: any }\n | { type: \"agent_end\"; [k: string]: any }\n | {\n type: \"result\";\n subtype: string;\n summary?: string;\n costUsd?: number;\n /** Per-turn token usage when the driver tracks it. Added in 3.1.0. */\n tokens?: TokenUsage;\n errors?: string[];\n [k: string]: any;\n }\n | { type: \"error\"; error: string; detail?: AgentError; fatal?: boolean; [k: string]: any }\n | { type: \"tool_call\"; name?: string; tool?: { name: string }; [k: string]: any }\n | { type: \"tool_execution_end\"; toolName?: string; [k: string]: any }\n | { type: \"commands_available\"; commands: SlashCommandInfo[] }\n | { type: \"session_info\"; driverSessionId: string; sessionFile?: string }\n | { type: \"ui_render\"; [k: string]: any }\n | { type: \"ui_render_update\"; [k: string]: any }\n | { type: \"ui_clear\"; [k: string]: any }\n // Phase 3 (resume cascade) — driver-emitted resume outcome.\n | {\n type: \"resume_failed\";\n resumeSessionId: string;\n reason: \"signature_mismatch\" | \"model_mismatch\" | \"jsonl_lost\" | \"jsonl_poisoned\";\n [k: string]: any;\n };\n\n/**\n * Abstract base class for agent driver backends.\n *\n * Wraps an LLM coding agent behind a single `prompt()` interface.\n * All drivers emit `'agent-event'` with {@link AgentEvent} payloads.\n *\n * @remarks\n * Subclasses must implement `start`, `prompt`, `abort`, `kill`, and `isRunning`.\n * Implementations should never emit an event name other than `'agent-event'` as\n * the public streaming channel — internal events (`'ready'`, `'exit'`, etc.) are\n * driver-private.\n *\n * @example\n * ```ts\n * const driver = createDriver('omp', config);\n * driver.on('agent-event', (event) => console.log(event.type));\n * await driver.start();\n * await driver.prompt('Refactor the auth module');\n * driver.kill();\n * ```\n *\n * @docLink packages/bridge/concepts#agent-driver\n */\nexport abstract class AgentDriver extends EventEmitter {\n /** Static metadata describing this driver's capabilities. */\n abstract readonly driverInfo: DriverInfo;\n\n /**\n * Initialises the driver backend — spawns the child process (omp) or loads\n * the SDK module (claude-sdk). Resolves when the backend is ready to accept\n * prompts. Idempotent: calling `start()` on an already-running driver is a no-op.\n *\n * @throws {Error} When the backend binary is missing or the SDK cannot be loaded.\n */\n abstract start(): Promise<void>;\n\n /**\n * Sends a user message to the agent and resolves when the agent's turn completes\n * (i.e. after the `agent_end` event has been emitted).\n *\n * @param message - Plain-text user prompt to send to the agent.\n * @throws {Error} When the driver is not running or the underlying backend reports a fatal error.\n */\n abstract prompt(message: string): Promise<void>;\n\n /**\n * Sends an in-band abort signal to the agent, requesting it to stop the current\n * turn without terminating the process. The driver remains usable after `abort()`.\n *\n * @remarks Only meaningful when `driverInfo.supportsInBandAbort` is `true`.\n * For other drivers, prefer `kill()` followed by creating a new driver instance.\n */\n abstract abort(): Promise<void>;\n\n /**\n * Terminates the agent backend immediately (SIGTERM for subprocess drivers,\n * `close()` for in-process drivers). The driver instance must not be reused\n * after `kill()`.\n */\n abstract kill(): void;\n\n /** `true` when the backend is alive and able to accept new prompts. */\n abstract get isRunning(): boolean;\n\n /** Optional provider-native session/thread identifier for resume support. */\n get runtimeSessionId(): string | undefined {\n return undefined;\n }\n\n /** Slash commands discovered from the agent runtime. Override in drivers that support introspection. */\n getSlashCommands(): SlashCommandInfo[] {\n return [];\n }\n\n // ── Live reconfiguration ────────────────────────────────────────────────\n\n /**\n * Live-update driver configuration. The new values take effect on the next\n * prompt() call. Only model/thinking/effort are reconfigurable mid-session.\n *\n * Subclasses that store config locally should override this to apply the\n * patch to their own config field. The base implementation is a no-op.\n */\n reconfigure(patch: Partial<Pick<AgentConfig, \"model\" | \"thinking\" | \"effort\">>): void {\n // No-op — subclasses override to apply to their own config.\n void patch;\n }\n\n /**\n * Returns the model identifier currently configured on this driver.\n * Subclasses that store config locally should override this.\n */\n getModel(): string | undefined {\n return undefined;\n }\n\n // ── Compaction support ──────────────────────────────────────────────────\n\n /**\n * Returns the token usage from the most recent completed turn.\n * Returns `null` if usage data is unavailable (e.g. driver doesn't track it).\n *\n * Widened in 3.1.0 to return the full `TokenUsage` shape (input / output /\n * cache-read / cache-creation / reasoning). All fields are optional so\n * drivers can populate just what their provider reports. Existing callers\n * that read only `inputTokens` / `outputTokens` keep working — those fields\n * are still present and carry the same semantics as before.\n */\n getTokenUsage(): TokenUsage | null {\n return null;\n }\n\n /**\n * Returns the model's context window size in tokens.\n * Returns `null` if unknown.\n */\n getContextWindow(): number | null {\n return null;\n }\n\n /**\n * Returns the list of models available to this driver without starting a session.\n * Drivers that can enumerate their own models override this method.\n * Returns an empty array by default.\n */\n async listModels(): Promise<ModelEntry[]> {\n return [];\n }\n\n /**\n * Closes the current conversation session and prepares for a fresh start.\n * The next `prompt()` call will begin a new session without prior history.\n * The driver remains usable after `resetSession()`.\n */\n abstract resetSession(): Promise<void>;\n\n // ── Telemetry ─────────────────────────────────────────────────────────────\n\n protected _telemetry?: TelemetryProvider;\n protected _activeTrace?: Trace;\n protected _activeTurnSpan?: Span;\n private _turnStartTime?: number;\n\n /**\n * Attach a telemetry provider and active trace to this driver.\n * Called by the runner after creating the driver but before start().\n */\n setTelemetry(provider: TelemetryProvider, trace: Trace): void {\n this._telemetry = provider;\n this._activeTrace = trace;\n }\n\n /**\n * Begin a turn span. Called by the runner before prompt().\n * Pass a parent span (e.g. the turn span from the orchestrator) for nesting.\n * Returns the span so the runner can annotate it further.\n */\n beginTurnSpan(\n parent?: Trace | Span,\n attrs?: Record<string, string | number | boolean>,\n ): Span | undefined {\n if (!this._telemetry || !this._activeTrace) return undefined;\n this._turnStartTime = Date.now();\n this._activeTurnSpan = this._telemetry.startSpan(parent ?? this._activeTrace, {\n name: \"llm_generation\",\n kind: \"llm_generation\",\n attributes: attrs,\n });\n return this._activeTurnSpan;\n }\n\n /**\n * End the current turn span with generation data.\n * Called by the runner after agent_end. Model and provider are passed\n * explicitly — the driver base class does not access config directly.\n */\n endTurnSpan(result?: {\n model?: string;\n provider?: string;\n inputTokens?: number;\n outputTokens?: number;\n stopReason?: string;\n error?: string;\n }): void {\n if (!this._telemetry || !this._activeTurnSpan) return;\n const durationMs = this._turnStartTime ? Date.now() - this._turnStartTime : 0;\n\n if (result?.inputTokens !== undefined || result?.outputTokens !== undefined) {\n this._telemetry.logGeneration(this._activeTurnSpan, {\n model: result?.model ?? \"unknown\",\n provider: result?.provider ?? \"unknown\",\n inputTokens: result.inputTokens,\n outputTokens: result.outputTokens,\n durationMs,\n stopReason: result.stopReason,\n });\n }\n\n this._telemetry.endSpan(this._activeTurnSpan, {\n status: result?.error ? \"error\" : \"ok\",\n error: result?.error,\n attributes: { \"skaile.turn.duration_ms\": durationMs },\n });\n\n this._activeTurnSpan = undefined;\n this._turnStartTime = undefined;\n }\n}\n\n/**\n * Factory function signature registered in the driver registry.\n *\n * @param config - Configuration for the new driver instance.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @docLink packages/bridge/concepts#driver-factory\n */\nexport type DriverFactory = (config: AgentConfig) => AgentDriver;\n","import type { ModelEntry } from \"./models.js\";\nimport type { AgentConfig, AgentDriver, DriverFactory, DriverInfo } from \"./types.js\";\n\n// Build-time backend gating. `bun build --compile --define:__INCLUDE_*__=...`\n// folds these to literal booleans so an excluded backend's driver module and\n// its SDK are dead-code-stripped from the binary. Under tsup / vitest / bun\n// run-on-source no `--define` runs and the `typeof` guard defaults to `true` —\n// every backend is available (the SDKs stay optional peers).\ndeclare const __INCLUDE_CLAUDE_SDK__: boolean;\ndeclare const __INCLUDE_CODEX__: boolean;\nconst INCLUDE_CLAUDE_SDK =\n typeof __INCLUDE_CLAUDE_SDK__ === \"undefined\" ? true : __INCLUDE_CLAUDE_SDK__;\nconst INCLUDE_CODEX = typeof __INCLUDE_CODEX__ === \"undefined\" ? true : __INCLUDE_CODEX__;\n\nconst driverRegistry = new Map<string, { factory: DriverFactory; info: DriverInfo }>();\n\n/**\n * Static capability metadata for every built-in backend.\n *\n * Pure data — this object imports no driver module and references no backend\n * SDK. {@link listDrivers} returns it (merged with any third-party drivers)\n * so selection UIs can enumerate every backend without loading a single\n * driver module. The matching driver module self-registers its factory via\n * {@link registerDriver} when {@link loadDriver} imports it.\n *\n * @docLink packages/bridge/api-reference#registry\n */\nexport const DRIVER_CATALOG: Record<string, DriverInfo> = {\n omp: {\n id: \"omp\",\n name: \"omp (oh-my-pi)\",\n modelAgnostic: true,\n supportsInBandAbort: true,\n },\n \"claude-sdk\": {\n id: \"claude-sdk\",\n name: \"Claude Agent SDK\",\n modelAgnostic: false,\n supportsInBandAbort: true,\n },\n codex: {\n id: \"codex\",\n name: \"OpenAI Codex\",\n modelAgnostic: false,\n supportsInBandAbort: true,\n },\n echo: {\n id: \"echo\",\n name: \"Echo (E2E mock)\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n};\n\n/**\n * Registers a driver factory under a stable string identifier.\n *\n * Built-in drivers (`omp`, `claude-sdk`, `codex`, `echo`) self-register when\n * their driver module is imported by {@link loadDriver} — `createDriver` and\n * `listModelsForDriver` trigger that load for the requested id. Third-party\n * drivers can call `registerDriver` directly at any time before the first\n * `createDriver` call that uses their id.\n *\n * @param id - Stable identifier used to look up the driver (e.g. `\"omp\"`).\n * @param factory - Function that constructs a new driver instance for the given config.\n * @param info - Static capability metadata returned by {@link listDrivers}.\n * @docLink packages/bridge/api-reference#registry\n */\nexport function registerDriver(id: string, factory: DriverFactory, info: DriverInfo): void {\n driverRegistry.set(id, { factory, info });\n}\n\n/**\n * Imports the driver module for the given built-in backend id, which\n * self-registers its factory via {@link registerDriver} on import.\n *\n * This is the single id → module map in bridge core. Every specifier is a\n * literal string so `bun --compile` can statically bundle the driver module\n * (and, transitively, its SDK). The in-process-SDK backends (`claude-sdk`,\n * `codex`) are wrapped in build-constant guards so an excluded backend's\n * `await import` folds to dead code in the compiled binary. `omp` and `echo`\n * carry no SDK weight and are always available.\n *\n * Unknown ids are a no-op — {@link createDriver} surfaces the clear error.\n * Idempotent: a second call re-imports an already-cached module.\n *\n * @param id - Built-in driver identifier (e.g. `\"omp\"`, `\"claude-sdk\"`).\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function loadDriver(id: string): Promise<void> {\n switch (id) {\n case \"omp\":\n await import(\"@skaile/workspaces/drivers/omp\");\n break;\n case \"echo\":\n await import(\"@skaile/workspaces/drivers/echo\");\n break;\n case \"claude-sdk\":\n if (INCLUDE_CLAUDE_SDK) await import(\"@skaile/workspaces/drivers/claude-sdk\");\n break;\n case \"codex\":\n if (INCLUDE_CODEX) await import(\"@skaile/workspaces/drivers/codex\");\n break;\n // unknown id: no-op — createDriver throws its existing clear error\n }\n}\n\n/**\n * Creates a new driver instance for the given backend id.\n *\n * Lazily loads the driver module via {@link loadDriver} first, so callers\n * never have to register built-ins themselves. The returned driver has not\n * been started yet — call `driver.start()` before sending prompts.\n *\n * @param id - Registered driver identifier (e.g. `\"omp\"`, `\"claude-sdk\"`).\n * @param config - Configuration forwarded to the driver constructor.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @throws {Error} When `id` is a known backend excluded from this build, or\n * when `id` does not match any registered driver at all.\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function createDriver(id: string, config: AgentConfig): Promise<AgentDriver> {\n await loadDriver(id);\n const entry = driverRegistry.get(id);\n if (!entry) {\n if (id in DRIVER_CATALOG) {\n throw new Error(`Agent driver \"${id}\" is not bundled in this build.`);\n }\n throw new Error(\n `Unknown agent driver: \"${id}\". Available: ${listDrivers()\n .map((d) => d.id)\n .join(\", \")}`,\n );\n }\n return entry.factory(config);\n}\n\n/**\n * Returns the capability metadata for every available driver.\n *\n * Enumerates every built-in backend from {@link DRIVER_CATALOG} without\n * loading a single driver module or backend SDK, then merges in any\n * third-party drivers registered via {@link registerDriver} that are not\n * already in the catalog. Use this to populate driver selection UIs.\n *\n * @returns Array of {@link DriverInfo} objects, one per available driver.\n * @docLink packages/bridge/api-reference#registry\n */\nexport function listDrivers(): DriverInfo[] {\n const merged = new Map<string, DriverInfo>();\n for (const info of Object.values(DRIVER_CATALOG)) {\n merged.set(info.id, info);\n }\n for (const { info } of driverRegistry.values()) {\n if (!merged.has(info.id)) merged.set(info.id, info);\n }\n return [...merged.values()];\n}\n\n/**\n * List models available to a specific driver without starting a full agent session.\n *\n * Lazily loads the driver module via {@link loadDriver}, creates a minimal\n * driver instance (no subprocess spawned, no `start()` call), delegates to\n * its `listModels()` method, and returns the result. API keys are forwarded\n * so drivers can authenticate against provider REST APIs if needed. Returns\n * `[]` when `driverId` is not registered.\n *\n * @param driverId - Registered driver id (e.g. `\"omp\"`, `\"claude-sdk\"`, `\"codex\"`).\n * @param apiKeys - Provider API keys keyed by provider name (e.g. `{ anthropic: \"sk-...\" }`).\n * Pass `settings.apiKeys ?? {}` from forge-assistant's resolved settings.\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function listModelsForDriver(\n driverId: string,\n apiKeys: Record<string, string>,\n): Promise<ModelEntry[]> {\n await loadDriver(driverId);\n const entry = driverRegistry.get(driverId);\n if (!entry) return [];\n // cwd and sessionId are required by AgentConfig but none of the listModels()\n // implementations use them — they only need apiKeys / env for authentication.\n const driver = entry.factory({ cwd: process.cwd(), sessionId: \"model-list\", apiKeys });\n return driver.listModels();\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../bridge/src/logger.ts","../bridge/src/types.ts","../bridge/src/registry.ts"],"names":[],"mappings":";;;;AAuBO,SAAS,gBAAgB,OAAA,EAAyB;AACvD,EAAA,OAAO,YAAA,CAAa,EAAE,IAAA,EAAM,QAAA,EAAU,SAAS,CAAA;AACjD;AC4ZO,IAAe,WAAA,GAAf,cAAmC,YAAA,CAAa;AAAA;AAAA,EA0CrD,IAAI,gBAAA,GAAuC;AACzC,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,gBAAA,GAAuC;AACrC,IAAA,OAAO,EAAC;AAAA,EACV;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,YAAY,KAAA,EAA0E;AAE/E,EACP;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,QAAA,GAA+B;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,aAAA,GAAmC;AACjC,IAAA,OAAO,IAAA;AAAA,EACT;AAAA;A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,KAAM,CAAA,CAAE,EAAE,CAAA,CACf,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,KACf;AAAA,EACF;AACA,EAAA,OAAO,KAAA,CAAM,QAAQ,MAAM,CAAA;AAC7B;AAaO,SAAS,WAAA,GAA4B;AAC1C,EAAA,MAAM,MAAA,uBAAa,GAAA,EAAwB;AAC3C,EAAA,KAAA,MAAW,IAAA,IAAQ,MAAA,CAAO,MAAA,CAAO,cAAc,CAAA,EAAG;AAChD,IAAA,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,EAAA,EAAI,IAAI,CAAA;AAAA,EAC1B;AACA,EAAA,KAAA,MAAW,EAAE,IAAA,EAAK,IAAK,cAAA,CAAe,QAAO,EAAG;AAC9C,IAAA,IAAI,CAAC,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,EAAE,GAAG,MAAA,CAAO,GAAA,CAAI,IAAA,CAAK,EAAA,EAAI,IAAI,CAAA;AAAA,EACpD;AACA,EAAA,OAAO,CAAC,GAAG,MAAA,CAAO,MAAA,EAAQ,CAAA;AAC5B;AAgBA,eAAsB,mBAAA,CACpB,UACA,OAAA,EACuB;AACvB,EAAA,MAAM,WAAW,QAAQ,CAAA;AACzB,EAAA,MAAM,KAAA,GAAQ,cAAA,CAAe,GAAA,CAAI,QAAQ,CAAA;AACzC,EAAA,IAAI,CAAC,KAAA,EAAO,OAAO,EAAC;AAGpB,EAAA,MAAM,MAAA,GAAS,KAAA,CAAM,OAAA,CAAQ,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAI,EAAG,SAAA,EAAW,YAAA,EAAc,OAAA,EAAS,CAAA;AACrF,EAAA,OAAO,OAAO,UAAA,EAAW;AAC3B","file":"chunk-4ACWI5YT.js","sourcesContent":["/**\n * Bridge-layer logger factory.\n *\n * Each driver creates its own Logger via `getBridgeLogger(subkind)` at\n * construction time. Falls back to an off-mode Logger (stdout only) when\n * no LogStore is registered — see @skaile/workspaces/core/logging for details.\n */\n\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * Construct a bridge-scoped Logger for a given driver subkind.\n *\n * Creates a `Logger` with `kind: \"bridge\"` and the specified `subkind`. Falls back to\n * an off-mode Logger (stdout only) when no `LogStore` is registered — see\n * `@skaile/workspaces/core/logging` for details. Each driver calls this once at construction\n * time; never re-construct per call.\n *\n * @param subkind - Driver id, e.g. `\"claude-sdk\"`, `\"omp\"`, `\"echo\"`, `\"codex\"`.\n * @returns A `Logger` scoped to `bridge:<subkind>`.\n * @docLink packages/bridge/api-reference#logger\n */\nexport function getBridgeLogger(subkind: string): Logger {\n return createLogger({ kind: \"bridge\", subkind });\n}\n","import { EventEmitter } from \"node:events\";\nimport type { Span, TelemetryProvider, Trace } from \"@skaile/workspaces/telemetry\";\nimport type {\n Capability,\n CredentialMint,\n RenderInvokedEvent,\n TokenUsage,\n} from \"@skaile/workspaces/types\";\nimport type { ModelEntry } from \"./models.js\";\n\n/**\n * Minimal LLM tool descriptor used by the capability dispatch path. Mirrors\n * the runner's `LLMTool` shape so drivers can consume registry output without\n * importing `@skaile/workspaces/runner` (which would create a circular dep).\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-tool\n */\nexport interface BridgeCapabilityTool {\n /** Capability name; used as the LLM-visible tool name. */\n name: string;\n /** Human/LLM-readable description. */\n description: string;\n /** JSON Schema for the tool's input parameters. */\n parameters: Record<string, unknown>;\n}\n\n/**\n * Render-cap event emission callback used by the bridge when the LLM invokes\n * a capability that carries a `render` spec. The runner provides the actual\n * sink (transport.send / sendEvent); the bridge only emits.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-render-emit\n */\nexport type BridgeRenderEmit = (event: RenderInvokedEvent) => void;\n\n/**\n * Text-event emission callback for render-capability fallbacks. When a\n * `RenderCapability` carries `render.fallback` and the LLM invokes it, the\n * bridge substitutes `{{prop}}` placeholders (top-level keys of `props`,\n * optional dotted-path traversal `{{user.name}}`) and pushes the rendered\n * string through this callback so clients without a render layer still see\n * a textual representation. No-op when `fallback` is absent.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-text-emit\n */\nexport type BridgeTextEmit = (text: string) => void;\n\n/**\n * Bundle of capability dispatch hooks. Registered into the driver via\n * `AgentConfig.capabilities`; the driver routes registered LLM tool calls\n * back into `invoke()` instead of using its native dispatch path.\n *\n * The runner constructs this from a `CapabilityRegistry` instance and threads\n * it through `createAgentSession()`. Drivers that don't yet implement\n * capability dispatch ignore the field — legacy v1 paths stay intact.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/bridge/concepts#bridge-capability-hooks\n */\nexport interface BridgeCapabilityHooks {\n /** Build the LLM tool descriptor list from the registry. Called per turn so registration changes take effect. */\n composeTools(): BridgeCapabilityTool[];\n /** Resolve a wire-format Capability descriptor by name. Used by the bridge to inspect `fireAndForget` / `render`. */\n resolve(name: string): Capability | null;\n /** Validate input + dispatch through the registry. Logging is wired by the registry. */\n invoke(name: string, input: unknown): Promise<unknown>;\n /** Emit a render-invoked event. The runner forwards via the WebSocket transport. */\n emitRender?: BridgeRenderEmit;\n /** Emit a text fallback for render capabilities with `render.fallback`. */\n emitText?: BridgeTextEmit;\n /** Session id passed through to the runner's per-handler logger. */\n sessionId: string;\n}\n\n/**\n * Static metadata for a registered agent driver backend.\n *\n * Returned by {@link listDrivers} and exposed on every {@link AgentDriver} instance\n * via `driverInfo`.\n *\n * @docLink packages/bridge/concepts#driver-info\n */\nexport interface DriverInfo {\n /** Stable machine identifier used to look up the driver in the registry (e.g. `\"omp\"`, `\"claude-sdk\"`). */\n id: string;\n /** Human-readable display name shown in UIs and logs. */\n name: string;\n /** `true` when the driver can target any LLM provider; `false` for Anthropic-only drivers. */\n modelAgnostic: boolean;\n /**\n * `true` when the driver supports mid-stream abort via `abort()` without killing the process.\n * Drivers that return `false` can only be stopped via `kill()`.\n */\n supportsInBandAbort: boolean;\n}\n\n/**\n * Codex-specific tuning options passed through `DriverOptions.codex`.\n *\n * @remarks These are forwarded verbatim to the Codex driver and have no effect on other drivers.\n * @docLink packages/bridge/concepts#codex-driver-options\n */\nexport interface CodexDriverOptions {\n /** Controls whether Codex may auto-apply edits without user approval. */\n approvalPolicy?: \"never\" | \"on-request\" | \"on-failure\" | \"untrusted\";\n /** Filesystem sandbox level for the Codex process. */\n sandboxMode?: \"read-only\" | \"workspace-write\" | \"danger-full-access\";\n /** Reasoning budget passed to the model. */\n reasoningEffort?: \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\";\n /** When `true`, the Codex sandbox is allowed to make outbound network requests. */\n networkAccessEnabled?: boolean;\n /** Extra directories made accessible to the Codex sandbox in addition to `cwd`. */\n additionalDirectories?: string[];\n}\n\n/**\n * Driver-specific configuration bag.\n *\n * Fields are keyed by driver ID so that callers can pass driver-specific options\n * through the common {@link AgentConfig} without breaking other drivers.\n *\n * @docLink packages/bridge/concepts#driver-options\n */\nexport interface DriverOptions {\n /** Codex-specific options. Ignored by all other drivers. */\n codex?: CodexDriverOptions;\n}\n\n/**\n * Configuration passed to a driver when it is created via {@link createDriver}.\n *\n * All fields are shared across drivers; driver-specific behaviour is documented\n * per field. Fields that are silently ignored by a driver are marked accordingly.\n *\n * @docLink packages/bridge/concepts#agent-config\n */\nexport interface AgentConfig {\n /** Absolute path to the working directory the agent operates in. */\n cwd: string;\n /**\n * LLM provider name (e.g. `\"anthropic\"`, `\"openai\"`, `\"google\"`).\n * Combined with `model` as `provider/model` for omp's `--model` flag.\n * Ignored by claude-sdk (always Anthropic).\n */\n provider?: string;\n /**\n * LLM model identifier (e.g. `\"claude-sonnet-4-5\"`, `\"gpt-4o\"`).\n * For omp: passed as `--model [provider/]model`.\n * For claude-sdk: passed as the `model` query option.\n */\n model?: string;\n /**\n * Provider API keys keyed by provider name (e.g. `{ anthropic: \"sk-...\" }`).\n * Drivers inject the relevant key into the environment or SDK options.\n */\n apiKeys?: Record<string, string>;\n /**\n * Additional environment variables merged into the child process environment.\n * For omp: merged with `process.env` before spawn. For claude-sdk: accessed\n * via `env.ANTHROPIC_API_KEY` as an alternative to `apiKeys.anthropic`.\n */\n env?: Record<string, string>;\n /** Inline system prompt — written to .omp/system.md and passed via --append-system-prompt (omp driver) */\n systemPrompt?: string;\n /** Path to project .omp/ directory (PI_CODING_AGENT_DIR for omp driver) */\n agentDir?: string;\n /** SSH key path — injected as GIT_SSH_COMMAND */\n sshKeyPath?: string;\n /** Pre-assign a UUID as the session ID for a new session (claude-sdk: passed as sessionId option) */\n sessionId?: string;\n /** Resume this specific past session by UUID instead of starting fresh (claude-sdk: passed as resume option) */\n resumeSessionId?: string;\n /** Maximum agentic turns per query (claude-sdk: passed as maxTurns option) */\n maxTurns?: number;\n /** Agent name — selects a deployed sub-agent definition as the main agent identity.\n * claude-sdk: passed as `agent` option to query() → reads .claude/agents/<name>.md natively.\n * omp: ignored (omp uses agentDir/PI_CODING_AGENT_DIR instead). */\n agentName?: string;\n /** In-process SDK MCP servers for custom tool injection (Claude SDK only, ignored by other drivers) */\n mcpServers?: Record<string, unknown>;\n /** Tool restrictions from agent.yaml — applied to the main agent session */\n tools?: {\n /** Tool names that the agent is allowed to invoke. An empty array means no restriction. */\n allowed?: string[];\n /** Tool names that the agent is explicitly forbidden from invoking. */\n denied?: string[];\n };\n /** Thinking mode for Claude models: adaptive (Claude decides), enabled (always think), disabled (no thinking). */\n thinking?: \"adaptive\" | \"enabled\" | \"disabled\";\n /** Reasoning effort level for Claude models. */\n effort?: \"low\" | \"medium\" | \"high\" | \"max\";\n /** Driver-specific configuration bag. */\n driverOptions?: DriverOptions;\n /**\n * Protocol v2 capability dispatch hooks. When present, the driver uses the\n * registry as the source of LLM tool definitions and routes invocations\n * through `capabilities.invoke()`. Absent → legacy v1 path (existing\n * mcpServers / native dispatch).\n *\n * @since 2.0.0\n */\n capabilities?: BridgeCapabilityHooks;\n /**\n * The platform's `AIProviderConfig.id` for the AI credential currently\n * provisioned into this driver. The runner reads this off `AgentConfig`\n * during 401 mediation and passes it as `configId` in\n * `request_access_token { kind: 'ai-credentials' }`. The driver itself\n * does not consume this field — only the runner uses it.\n *\n * Set by the platform agent-gateway in `ConfigureCommandV2` for mediated\n * sessions. Standalone runners (CLI / forge / Claude plugin) leave it\n * undefined; the runner falls back to surfacing the auth error to the\n * user without mediating.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Wire `aiProviderConfigId` end-to-end\".\n *\n * @since 3.3.0\n */\n aiProviderConfigId?: string;\n /**\n * Optional callback invoked by the driver when the underlying agent\n * surfaces an `authentication_error`. In Protocol v3 the runner mediates\n * the refresh via the `host.refresh_credential` capability and returns a\n * typed {@link CredentialMint}. The driver inspects the discriminator:\n *\n * - `mint.ok === true`: a fresh credential is now provisioned. The\n * driver re-attempts the in-flight prompt once.\n * - `mint.ok === false`: refresh failed (`code` carries a stable reason\n * such as `revoked`, `not-configured`, `provider-error`,\n * `backend-error`). The driver surfaces the original `AuthError` to\n * the caller.\n *\n * `args.configId` carries the platform `AIProviderConfig.id` the driver\n * was provisioned with (mirrors {@link AgentConfig.aiProviderConfigId}).\n * The runner uses it to scope the refresh to the correct AI credential.\n *\n * When omitted, the driver throws `AuthError` immediately as before\n * (standalone CLI / forge mode — there is no platform mediator to ask).\n *\n * Centralising auth-retry inside the driver means every consumer of\n * `driver.prompt(...)` (serve handler, compaction orchestrator, flow\n * orchestrator, …) gets self-healing for free — there is no per-call-site\n * wrapping.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"host.refresh_credential capability\".\n *\n * @since 3.4.0\n */\n onAuthError?: (args: { configId: string }) => Promise<CredentialMint>;\n}\n\n/**\n * A single message in an agent conversation.\n *\n * Emitted as part of {@link AgentEvent} variants (`message_start`, `message_update`, `message_end`).\n *\n * @docLink packages/bridge/concepts#agent-message\n */\nexport interface AgentMessage {\n /** Originator of the message. */\n role: \"user\" | \"assistant\" | \"tool\";\n /** Message body — either a plain string or a list of typed content blocks. */\n content: string | ContentBlock[];\n /** Tool invocations made by the assistant in this message. */\n toolCalls?: ToolCall[];\n /** For `role === \"tool\"`: the name of the tool whose result this message carries. */\n toolName?: string;\n /** For `role === \"tool\"`: `true` when the tool returned an error. */\n isError?: boolean;\n /** Optional structured payload for tool results. */\n data?: unknown;\n}\n\n/**\n * A typed block within an {@link AgentMessage}'s content array.\n *\n * Mirrors the Anthropic content block schema but is driver-agnostic.\n *\n * @docLink packages/bridge/concepts#content-block\n */\nexport interface ContentBlock {\n /** Block discriminant. */\n type: \"text\" | \"tool_use\" | \"tool_result\" | \"thinking\";\n /** Present for `text` and `thinking` blocks. */\n text?: string;\n /** Tool use / tool result correlation ID. */\n id?: string;\n /** Tool name (present on `tool_use` blocks). */\n name?: string;\n /** Tool input arguments (present on `tool_use` blocks). */\n input?: any;\n /** Serialised tool result content (present on `tool_result` blocks). */\n content?: string;\n}\n\n/**\n * A single tool invocation made by the agent within a message.\n *\n * @docLink packages/bridge/concepts#tool-call\n */\nexport interface ToolCall {\n /** Correlation ID used to match the call with its result. */\n id: string;\n /** Name of the tool being invoked. */\n name: string;\n /** Arguments passed to the tool. */\n input: any;\n}\n\n/**\n * Error classification for agent failures.\n *\n * Used to determine whether a failure is retryable and to surface actionable\n * hints to the user. See `bridge/CLAUDE.md` for the full category-to-behaviour matrix.\n *\n * @see AgentError\n * @docLink packages/bridge/concepts#error-category\n */\nexport type ErrorCategory =\n | \"auth\"\n | \"rate_limit\"\n | \"model\"\n | \"network\"\n | \"config\"\n | \"process\"\n | \"validation\"\n | \"unknown\";\n\n/**\n * Structured error payload emitted inside the `error` {@link AgentEvent}.\n *\n * Consumers should inspect `retryable` before deciding to surface a retry button,\n * and `hint` to provide an actionable message to the user.\n *\n * @docLink packages/bridge/concepts#agent-error\n */\nexport interface AgentError {\n /** Human-readable error description. */\n message: string;\n /** Coarse failure classification used for retry logic and telemetry. */\n category: ErrorCategory;\n /** HTTP status code if the error originated from an API response. */\n statusCode?: number;\n /** `true` when the caller may safely retry the same operation. */\n retryable: boolean;\n /** Short actionable advice suitable for display in the UI. */\n hint?: string;\n}\n\n/**\n * Metadata for a slash command exposed by the active agent runtime.\n *\n * @docLink packages/bridge/concepts#slash-command-info\n */\nexport interface SlashCommandInfo {\n /** Command name without the leading slash (e.g. `\"compact\"`). */\n name: string;\n /** One-line description shown in command pickers. */\n description: string;\n /** Placeholder text describing what argument the command expects. */\n argumentHint?: string;\n}\n\n/**\n * Discriminated union of all events emitted by a driver on the `'agent-event'` channel.\n *\n * @remarks\n * Consumers listen via `driver.on('agent-event', (event: AgentEvent) => ...)`.\n * The `[k: string]: any` index signature on most variants allows drivers to attach\n * driver-specific fields (e.g. `_textDelta`) without breaking the union.\n *\n * @docLink packages/bridge/concepts#agent-event\n */\nexport type AgentEvent =\n | { type: \"message_start\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_update\"; message: AgentMessage; [k: string]: any }\n | { type: \"message_end\"; message: AgentMessage; [k: string]: any }\n | { type: \"turn_end\"; toolResults?: AgentMessage[]; [k: string]: any }\n | { type: \"agent_end\"; [k: string]: any }\n | {\n type: \"result\";\n subtype: string;\n summary?: string;\n costUsd?: number;\n /** Per-turn token usage when the driver tracks it. Added in 3.1.0. */\n tokens?: TokenUsage;\n errors?: string[];\n [k: string]: any;\n }\n | { type: \"error\"; error: string; detail?: AgentError; fatal?: boolean; [k: string]: any }\n | { type: \"tool_call\"; name?: string; tool?: { name: string }; [k: string]: any }\n | { type: \"tool_execution_end\"; toolName?: string; [k: string]: any }\n | { type: \"commands_available\"; commands: SlashCommandInfo[] }\n | { type: \"session_info\"; driverSessionId: string; sessionFile?: string }\n | { type: \"ui_render\"; [k: string]: any }\n | { type: \"ui_render_update\"; [k: string]: any }\n | { type: \"ui_clear\"; [k: string]: any }\n // Phase 3 (resume cascade) — driver-emitted resume outcome.\n | {\n type: \"resume_failed\";\n resumeSessionId: string;\n reason: \"signature_mismatch\" | \"model_mismatch\" | \"jsonl_lost\" | \"jsonl_poisoned\";\n [k: string]: any;\n };\n\n/**\n * Abstract base class for agent driver backends.\n *\n * Wraps an LLM coding agent behind a single `prompt()` interface.\n * All drivers emit `'agent-event'` with {@link AgentEvent} payloads.\n *\n * @remarks\n * Subclasses must implement `start`, `prompt`, `abort`, `kill`, and `isRunning`.\n * Implementations should never emit an event name other than `'agent-event'` as\n * the public streaming channel — internal events (`'ready'`, `'exit'`, etc.) are\n * driver-private.\n *\n * @example\n * ```ts\n * const driver = createDriver('omp', config);\n * driver.on('agent-event', (event) => console.log(event.type));\n * await driver.start();\n * await driver.prompt('Refactor the auth module');\n * driver.kill();\n * ```\n *\n * @docLink packages/bridge/concepts#agent-driver\n */\nexport abstract class AgentDriver extends EventEmitter {\n /** Static metadata describing this driver's capabilities. */\n abstract readonly driverInfo: DriverInfo;\n\n /**\n * Initialises the driver backend — spawns the child process (omp) or loads\n * the SDK module (claude-sdk). Resolves when the backend is ready to accept\n * prompts. Idempotent: calling `start()` on an already-running driver is a no-op.\n *\n * @throws {Error} When the backend binary is missing or the SDK cannot be loaded.\n */\n abstract start(): Promise<void>;\n\n /**\n * Sends a user message to the agent and resolves when the agent's turn completes\n * (i.e. after the `agent_end` event has been emitted).\n *\n * @param message - Plain-text user prompt to send to the agent.\n * @throws {Error} When the driver is not running or the underlying backend reports a fatal error.\n */\n abstract prompt(message: string): Promise<void>;\n\n /**\n * Sends an in-band abort signal to the agent, requesting it to stop the current\n * turn without terminating the process. The driver remains usable after `abort()`.\n *\n * @remarks Only meaningful when `driverInfo.supportsInBandAbort` is `true`.\n * For other drivers, prefer `kill()` followed by creating a new driver instance.\n */\n abstract abort(): Promise<void>;\n\n /**\n * Terminates the agent backend immediately (SIGTERM for subprocess drivers,\n * `close()` for in-process drivers). The driver instance must not be reused\n * after `kill()`.\n */\n abstract kill(): void;\n\n /** `true` when the backend is alive and able to accept new prompts. */\n abstract get isRunning(): boolean;\n\n /** Optional provider-native session/thread identifier for resume support. */\n get runtimeSessionId(): string | undefined {\n return undefined;\n }\n\n /** Slash commands discovered from the agent runtime. Override in drivers that support introspection. */\n getSlashCommands(): SlashCommandInfo[] {\n return [];\n }\n\n // ── Live reconfiguration ────────────────────────────────────────────────\n\n /**\n * Live-update driver configuration. The new values take effect on the next\n * prompt() call. Only model/thinking/effort are reconfigurable mid-session.\n *\n * Subclasses that store config locally should override this to apply the\n * patch to their own config field. The base implementation is a no-op.\n */\n reconfigure(patch: Partial<Pick<AgentConfig, \"model\" | \"thinking\" | \"effort\">>): void {\n // No-op — subclasses override to apply to their own config.\n void patch;\n }\n\n /**\n * Returns the model identifier currently configured on this driver.\n * Subclasses that store config locally should override this.\n */\n getModel(): string | undefined {\n return undefined;\n }\n\n // ── Compaction support ──────────────────────────────────────────────────\n\n /**\n * Returns the token usage from the most recent completed turn.\n * Returns `null` if usage data is unavailable (e.g. driver doesn't track it).\n *\n * Widened in 3.1.0 to return the full `TokenUsage` shape (input / output /\n * cache-read / cache-creation / reasoning). All fields are optional so\n * drivers can populate just what their provider reports. Existing callers\n * that read only `inputTokens` / `outputTokens` keep working — those fields\n * are still present and carry the same semantics as before.\n */\n getTokenUsage(): TokenUsage | null {\n return null;\n }\n\n /**\n * Returns the model's context window size in tokens.\n * Returns `null` if unknown.\n */\n getContextWindow(): number | null {\n return null;\n }\n\n /**\n * Returns the list of models available to this driver without starting a session.\n * Drivers that can enumerate their own models override this method.\n * Returns an empty array by default.\n */\n async listModels(): Promise<ModelEntry[]> {\n return [];\n }\n\n /**\n * Closes the current conversation session and prepares for a fresh start.\n * The next `prompt()` call will begin a new session without prior history.\n * The driver remains usable after `resetSession()`.\n */\n abstract resetSession(): Promise<void>;\n\n // ── Telemetry ─────────────────────────────────────────────────────────────\n\n protected _telemetry?: TelemetryProvider;\n protected _activeTrace?: Trace;\n protected _activeTurnSpan?: Span;\n private _turnStartTime?: number;\n\n /**\n * Attach a telemetry provider and active trace to this driver.\n * Called by the runner after creating the driver but before start().\n */\n setTelemetry(provider: TelemetryProvider, trace: Trace): void {\n this._telemetry = provider;\n this._activeTrace = trace;\n }\n\n /**\n * Begin a turn span. Called by the runner before prompt().\n * Pass a parent span (e.g. the turn span from the orchestrator) for nesting.\n * Returns the span so the runner can annotate it further.\n */\n beginTurnSpan(\n parent?: Trace | Span,\n attrs?: Record<string, string | number | boolean>,\n ): Span | undefined {\n if (!this._telemetry || !this._activeTrace) return undefined;\n this._turnStartTime = Date.now();\n this._activeTurnSpan = this._telemetry.startSpan(parent ?? this._activeTrace, {\n name: \"llm_generation\",\n kind: \"llm_generation\",\n attributes: attrs,\n });\n return this._activeTurnSpan;\n }\n\n /**\n * End the current turn span with generation data.\n * Called by the runner after agent_end. Model and provider are passed\n * explicitly — the driver base class does not access config directly.\n */\n endTurnSpan(result?: {\n model?: string;\n provider?: string;\n inputTokens?: number;\n outputTokens?: number;\n stopReason?: string;\n error?: string;\n }): void {\n if (!this._telemetry || !this._activeTurnSpan) return;\n const durationMs = this._turnStartTime ? Date.now() - this._turnStartTime : 0;\n\n if (result?.inputTokens !== undefined || result?.outputTokens !== undefined) {\n this._telemetry.logGeneration(this._activeTurnSpan, {\n model: result?.model ?? \"unknown\",\n provider: result?.provider ?? \"unknown\",\n inputTokens: result.inputTokens,\n outputTokens: result.outputTokens,\n durationMs,\n stopReason: result.stopReason,\n });\n }\n\n this._telemetry.endSpan(this._activeTurnSpan, {\n status: result?.error ? \"error\" : \"ok\",\n error: result?.error,\n attributes: { \"skaile.turn.duration_ms\": durationMs },\n });\n\n this._activeTurnSpan = undefined;\n this._turnStartTime = undefined;\n }\n}\n\n/**\n * Factory function signature registered in the driver registry.\n *\n * @param config - Configuration for the new driver instance.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @docLink packages/bridge/concepts#driver-factory\n */\nexport type DriverFactory = (config: AgentConfig) => AgentDriver;\n","import type { ModelEntry } from \"./models.js\";\nimport type { AgentConfig, AgentDriver, DriverFactory, DriverInfo } from \"./types.js\";\n\n// Build-time backend gating. `bun build --compile --define:__INCLUDE_*__=...`\n// folds these to literal booleans so an excluded backend's driver module and\n// its SDK are dead-code-stripped from the binary. Under tsup / vitest / bun\n// run-on-source no `--define` runs and the `typeof` guard defaults to `true` —\n// every backend is available (the SDKs stay optional peers).\ndeclare const __INCLUDE_CLAUDE_SDK__: boolean;\ndeclare const __INCLUDE_CODEX__: boolean;\nconst INCLUDE_CLAUDE_SDK =\n typeof __INCLUDE_CLAUDE_SDK__ === \"undefined\" ? true : __INCLUDE_CLAUDE_SDK__;\nconst INCLUDE_CODEX = typeof __INCLUDE_CODEX__ === \"undefined\" ? true : __INCLUDE_CODEX__;\n\nconst driverRegistry = new Map<string, { factory: DriverFactory; info: DriverInfo }>();\n\n/**\n * Static capability metadata for every built-in backend.\n *\n * Pure data — this object imports no driver module and references no backend\n * SDK. {@link listDrivers} returns it (merged with any third-party drivers)\n * so selection UIs can enumerate every backend without loading a single\n * driver module. The matching driver module self-registers its factory via\n * {@link registerDriver} when {@link loadDriver} imports it.\n *\n * @docLink packages/bridge/api-reference#registry\n */\nexport const DRIVER_CATALOG: Record<string, DriverInfo> = {\n omp: {\n id: \"omp\",\n name: \"omp (oh-my-pi)\",\n modelAgnostic: true,\n supportsInBandAbort: true,\n },\n \"claude-sdk\": {\n id: \"claude-sdk\",\n name: \"Claude Agent SDK\",\n modelAgnostic: false,\n supportsInBandAbort: true,\n },\n codex: {\n id: \"codex\",\n name: \"OpenAI Codex\",\n modelAgnostic: false,\n supportsInBandAbort: true,\n },\n echo: {\n id: \"echo\",\n name: \"Echo (E2E mock)\",\n modelAgnostic: true,\n supportsInBandAbort: false,\n },\n};\n\n/**\n * Registers a driver factory under a stable string identifier.\n *\n * Built-in drivers (`omp`, `claude-sdk`, `codex`, `echo`) self-register when\n * their driver module is imported by {@link loadDriver} — `createDriver` and\n * `listModelsForDriver` trigger that load for the requested id. Third-party\n * drivers can call `registerDriver` directly at any time before the first\n * `createDriver` call that uses their id.\n *\n * @param id - Stable identifier used to look up the driver (e.g. `\"omp\"`).\n * @param factory - Function that constructs a new driver instance for the given config.\n * @param info - Static capability metadata returned by {@link listDrivers}.\n * @docLink packages/bridge/api-reference#registry\n */\nexport function registerDriver(id: string, factory: DriverFactory, info: DriverInfo): void {\n driverRegistry.set(id, { factory, info });\n}\n\n/**\n * Imports the driver module for the given built-in backend id, which\n * self-registers its factory via {@link registerDriver} on import.\n *\n * This is the single id → module map in bridge core. Every specifier is a\n * literal string so `bun --compile` can statically bundle the driver module\n * (and, transitively, its SDK). The in-process-SDK backends (`claude-sdk`,\n * `codex`) are wrapped in build-constant guards so an excluded backend's\n * `await import` folds to dead code in the compiled binary. `omp` and `echo`\n * carry no SDK weight and are always available.\n *\n * Unknown ids are a no-op — {@link createDriver} surfaces the clear error.\n * Idempotent: a second call re-imports an already-cached module.\n *\n * @param id - Built-in driver identifier (e.g. `\"omp\"`, `\"claude-sdk\"`).\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function loadDriver(id: string): Promise<void> {\n switch (id) {\n case \"omp\":\n await import(\"@skaile/workspaces/drivers/omp\");\n break;\n case \"echo\":\n await import(\"@skaile/workspaces/drivers/echo\");\n break;\n case \"claude-sdk\":\n if (INCLUDE_CLAUDE_SDK) await import(\"@skaile/workspaces/drivers/claude-sdk\");\n break;\n case \"codex\":\n if (INCLUDE_CODEX) await import(\"@skaile/workspaces/drivers/codex\");\n break;\n // unknown id: no-op — createDriver throws its existing clear error\n }\n}\n\n/**\n * Creates a new driver instance for the given backend id.\n *\n * Lazily loads the driver module via {@link loadDriver} first, so callers\n * never have to register built-ins themselves. The returned driver has not\n * been started yet — call `driver.start()` before sending prompts.\n *\n * @param id - Registered driver identifier (e.g. `\"omp\"`, `\"claude-sdk\"`).\n * @param config - Configuration forwarded to the driver constructor.\n * @returns A freshly constructed (not yet started) {@link AgentDriver}.\n * @throws {Error} When `id` is a known backend excluded from this build, or\n * when `id` does not match any registered driver at all.\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function createDriver(id: string, config: AgentConfig): Promise<AgentDriver> {\n await loadDriver(id);\n const entry = driverRegistry.get(id);\n if (!entry) {\n if (id in DRIVER_CATALOG) {\n throw new Error(`Agent driver \"${id}\" is not bundled in this build.`);\n }\n throw new Error(\n `Unknown agent driver: \"${id}\". Available: ${listDrivers()\n .map((d) => d.id)\n .join(\", \")}`,\n );\n }\n return entry.factory(config);\n}\n\n/**\n * Returns the capability metadata for every available driver.\n *\n * Enumerates every built-in backend from {@link DRIVER_CATALOG} without\n * loading a single driver module or backend SDK, then merges in any\n * third-party drivers registered via {@link registerDriver} that are not\n * already in the catalog. Use this to populate driver selection UIs.\n *\n * @returns Array of {@link DriverInfo} objects, one per available driver.\n * @docLink packages/bridge/api-reference#registry\n */\nexport function listDrivers(): DriverInfo[] {\n const merged = new Map<string, DriverInfo>();\n for (const info of Object.values(DRIVER_CATALOG)) {\n merged.set(info.id, info);\n }\n for (const { info } of driverRegistry.values()) {\n if (!merged.has(info.id)) merged.set(info.id, info);\n }\n return [...merged.values()];\n}\n\n/**\n * List models available to a specific driver without starting a full agent session.\n *\n * Lazily loads the driver module via {@link loadDriver}, creates a minimal\n * driver instance (no subprocess spawned, no `start()` call), delegates to\n * its `listModels()` method, and returns the result. API keys are forwarded\n * so drivers can authenticate against provider REST APIs if needed. Returns\n * `[]` when `driverId` is not registered.\n *\n * @param driverId - Registered driver id (e.g. `\"omp\"`, `\"claude-sdk\"`, `\"codex\"`).\n * @param apiKeys - Provider API keys keyed by provider name (e.g. `{ anthropic: \"sk-...\" }`).\n * Pass `settings.apiKeys ?? {}` from forge-assistant's resolved settings.\n * @docLink packages/bridge/api-reference#registry\n */\nexport async function listModelsForDriver(\n driverId: string,\n apiKeys: Record<string, string>,\n): Promise<ModelEntry[]> {\n await loadDriver(driverId);\n const entry = driverRegistry.get(driverId);\n if (!entry) return [];\n // cwd and sessionId are required by AgentConfig but none of the listModels()\n // implementations use them — they only need apiKeys / env for authentication.\n const driver = entry.factory({ cwd: process.cwd(), sessionId: \"model-list\", apiKeys });\n return driver.listModels();\n}\n"]}
|
|
@@ -389,5 +389,5 @@ function walkForSkill(dir, skillId) {
|
|
|
389
389
|
}
|
|
390
390
|
|
|
391
391
|
export { resumeFlow, runFlow };
|
|
392
|
-
//# sourceMappingURL=chunk-
|
|
393
|
-
//# sourceMappingURL=chunk-
|
|
392
|
+
//# sourceMappingURL=chunk-DDVKNST3.js.map
|
|
393
|
+
//# sourceMappingURL=chunk-DDVKNST3.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../base-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ,uBAAA;AAAA,IACA,kBAAA;AAAA,IACA,wBAAA;AAAA,IACA,kBAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,IAAA,CAAK,QAAQ,CAAA;AACnC,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,IAAY,eAAA,CAAgB,KAAK,UAAU,CAAA;AACjE,EAAA,MAAM,QAAA,GAAW,MAAM,eAAA,CAAgB,IAAA,CAAK,UAAA,EAAY;AAAA,IACtD,QAAQ,IAAA,CAAK,MAAA;AAAA,IACb,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,OAAO,IAAA,CAAK;AAAA,GACb,CA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,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,KAAa,OAAA,EAAgC;AACjE,EAAA,KAAA,MAAW,KAAA,IAAS,GAAG,WAAA,CAAY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-XYEFV7XN.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `base-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/base-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → base-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * base-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { loadFlow } from \"./engine/index.js\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/base-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/base-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/base-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/base-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../base-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;AAuDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAAA;AACxD,EAAA,OAAO,aAAA;AACT;AAMA,IAAM,0BAAA,GAA6B,CAAA,GAAI,EAAA,GAAK,EAAA,GAAK,GAAA;AA2HjD,eAAsB,QAAQ,IAAA,EAAiC;AAC7D,EAAA,MAAM,MAAA,GAAS,MAAM,gBAAA,EAAiB;AACtC,EAAA,MAAM;AAAA,IACJ,uBAAA;AAAA,IACA,kBAAA;AAAA,IACA,wBAAA;AAAA,IACA,kBAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF,GAAI,MAAA;AAEJ,EAAA,MAAM,IAAA,GAAO,QAAA,CAAS,IAAA,CAAK,QAAQ,CAAA;AACnC,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,QAAA,IAAY,eAAA,CAAgB,KAAK,UAAU,CAAA;AACjE,EAAA,MAAM,QAAA,GAAW,MAAM,eAAA,CAAgB,IAAA,CAAK,UAAA,EAAY;AAAA,IACtD,QAAQ,IAAA,CAAK,MAAA;AAAA,IAC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,CAA+C,KAAA,IAC/C,KAAA,CAA+B,OAAA,IAChC,aAAA;AACF,QAAA,IAAA,CAAK,IAAI,KAAA,CAAM,GAAG,CAAC,CAAA;AAAA,MACrB;AAAA,IACF,CAAC,CAAA;AAED,IAAA,MAAA,CAAO,MAAA,CAAO,MAAM,CAAA,CAAE,KAAA,CAAM,IAAI,CAAA;AAAA,EAClC,CAAC,CAAA;AACH;AAEA,SAAS,YAAA,CAAa,KAAa,OAAA,EAAgC;AACjE,EAAA,KAAA,MAAW,KAAA,IAAS,GAAG,WAAA,CAAY,GAAA,EAAK,EAAE,aAAA,EAAe,IAAA,EAAM,CAAA,EAAG;AAChE,IAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,EAAG;AAC1B,IAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,GAAA,EAAK,MAAM,IAAI,CAAA;AACtC,IAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,UAAU,CAAA;AAC1C,IAAA,IAAI,EAAA,CAAG,UAAA,CAAW,OAAO,CAAA,EAAG;AAC1B,MAAA,IAAI,KAAA,CAAM,IAAA,KAAS,OAAA,EAAS,OAAO,OAAA;AAAA,IACrC,CAAA,MAAO;AACL,MAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,IAAA,EAAM,OAAO,CAAA;AACxC,MAAA,IAAI,OAAO,OAAO,KAAA;AAAA,IACpB;AAAA,EACF;AACA,EAAA,OAAO,IAAA;AACT","file":"chunk-DDVKNST3.js","sourcesContent":["/**\n * runFlow / resumeFlow — CLI entry helpers for the flow connector.\n *\n * Moved from `runner/src/runner.ts` to `base-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/base-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → base-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * base-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { loadFlow } from \"./engine/index.js\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/base-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/base-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/base-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n createAgentSession,\n createSessionStimulusBus,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n });\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/base-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.filter((n) => n.type === \"skill\" && n.data?.version);\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.data?.skill ?? node.id;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const versionNodes = pinnedNodes.map((n) => ({\n nodeId: n.id,\n skillId: n.data?.skill ?? n.id,\n requestedVersion: n.data?.version,\n }));\n\n const checks = validateFlowVersions(versionNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}
|
|
@@ -110,6 +110,15 @@ function classifyClaudeSdkError(input) {
|
|
|
110
110
|
hint: "The Claude Code CLI did not send the OAuth beta header. The bundled CLI in this image is too old \u2014 rebuild the agent image."
|
|
111
111
|
};
|
|
112
112
|
}
|
|
113
|
+
if (lower.includes("not logged in") || lower.includes("please run /login")) {
|
|
114
|
+
return {
|
|
115
|
+
message,
|
|
116
|
+
category: "auth",
|
|
117
|
+
statusCode: 401,
|
|
118
|
+
retryable: false,
|
|
119
|
+
hint: opts.oauthCredential ? "The Claude Code OAuth credential expired and could not be auto-refreshed in-container. The runner will re-mint it \u2014 retry the prompt. If it persists, re-export `~/.claude/.credentials.json` from a working Claude Code install." : "No Anthropic credential is configured for this provider. Add one in Settings -> AI Providers."
|
|
120
|
+
};
|
|
121
|
+
}
|
|
113
122
|
if (lower.includes("api key") || lower.includes("authentication") || lower.includes("invalid authentication") || lower.includes("unauthorized") || lower.includes("401") || lower.includes("403")) {
|
|
114
123
|
return {
|
|
115
124
|
message,
|
|
@@ -222,5 +231,5 @@ function tryParseEmbeddedAnthropicError(text) {
|
|
|
222
231
|
}
|
|
223
232
|
|
|
224
233
|
export { AuthError, classifyClaudeSdkError };
|
|
225
|
-
//# sourceMappingURL=chunk-
|
|
226
|
-
//# sourceMappingURL=chunk-
|
|
234
|
+
//# sourceMappingURL=chunk-DQWREFRQ.js.map
|
|
235
|
+
//# sourceMappingURL=chunk-DQWREFRQ.js.map
|