@harness-engineering/orchestrator 0.6.0 → 0.8.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/dist/index.d.ts CHANGED
@@ -1,9 +1,11 @@
1
- import { Issue, AgentEvent, WorkflowConfig, TokenUsage, ConcernSignal, ScopeTier, EscalationConfig, RoutingDecision, Result, WorkflowDefinition, WorkspaceConfig, HooksConfig, AgentBackend, SessionStartParams, AgentSession, AgentError, TurnParams, TurnResult, CheckScriptDefinition, OutputRetentionConfig, BackendDef, RoutingConfig, RoutingUseCase, ContainerConfig, SecretConfig, AgentConfig, CustomTaskDefinition, TokenScope, AuthToken, AuthTokenPublic, IndexedFileKind, SessionSearchResult, ReindexStats, SessionSummarizationConfig, SessionSummary, SessionSummaryMeta, SessionsConfig, GatewayEvent, NotificationEnvelope, NotificationDeliveryResult, NotificationSinkConfig, NotificationsConfig } from '@harness-engineering/types';
1
+ import * as _harness_engineering_types from '@harness-engineering/types';
2
+ import { Issue, AgentEvent, WorkflowConfig, TokenUsage, ConcernSignal, ScopeTier, EscalationConfig, IssueRoutingDecision, Result, WorkflowDefinition, BackendDef, RoutingConfig, WorkspaceConfig, HooksConfig, AgentBackend, SessionStartParams, AgentSession, AgentError, TurnParams, TurnResult, CheckScriptDefinition, OutputRetentionConfig, RoutingDecision, RoutingUseCase, ContainerConfig, SecretConfig, AgentConfig, LocalModelStatus, CustomTaskDefinition, TokenScope, AuthToken, AuthTokenPublic, IndexedFileKind, SessionSearchResult, ReindexStats, SessionSummarizationConfig, SessionSummary, SessionSummaryMeta, SessionsConfig, GatewayEvent, NotificationEnvelope, NotificationDeliveryResult, NotificationSinkConfig, NotificationsConfig } from '@harness-engineering/types';
2
3
  import { IssueTrackerClient, Issue as Issue$1, TrackerConfig, CacheMetricsRecorder, ArchiveHooks, SkillProposal, ProposalGateFinding } from '@harness-engineering/core';
3
4
  import { EnrichedSpec, ComplexityScore, SimulationResult, IntelligencePipeline, WeightedRecommendation, AnalysisProvider } from '@harness-engineering/intelligence';
4
5
  import { GraphStore } from '@harness-engineering/graph';
5
6
  import { execFile } from 'node:child_process';
6
7
  import { EventEmitter } from 'node:events';
8
+ import { z } from 'zod';
7
9
 
8
10
  /**
9
11
  * Run attempt lifecycle phases (internal to orchestrator).
@@ -366,6 +368,10 @@ interface TickEvent {
366
368
  simulationResults?: Map<string, SimulationResult>;
367
369
  /** Pre-computed persona recommendations from specialization scorer (issueId -> recommendations) */
368
370
  personaRecommendations?: Map<string, WeightedRecommendation[]>;
371
+ /** Identity of this orchestrator. Items assigned to a different value are
372
+ * filtered out of dispatch by `selectCandidates`. Omit for back-compat
373
+ * (preserves today's permissive behavior). */
374
+ selfAssignee?: string;
369
375
  }
370
376
  interface WorkerExitEvent {
371
377
  type: 'worker_exit';
@@ -485,11 +491,11 @@ declare function sortCandidates(issues: readonly Issue[]): Issue[];
485
491
  * Check if a single issue is dispatch-eligible.
486
492
  * State comparisons are case-insensitive.
487
493
  */
488
- declare function isEligible(issue: Issue, state: OrchestratorState, activeStates: string[], terminalStates: string[]): boolean;
494
+ declare function isEligible(issue: Issue, state: OrchestratorState, activeStates: string[], terminalStates: string[], selfAssignee?: string | null): boolean;
489
495
  /**
490
496
  * Select and sort eligible candidates from a list of issues.
491
497
  */
492
- declare function selectCandidates(issues: readonly Issue[], state: OrchestratorState, activeStates: string[], terminalStates: string[]): Issue[];
498
+ declare function selectCandidates(issues: readonly Issue[], state: OrchestratorState, activeStates: string[], terminalStates: string[], selfAssignee?: string | null): Issue[];
493
499
 
494
500
  /**
495
501
  * Get the number of available global concurrency slots.
@@ -549,7 +555,7 @@ declare function detectScopeTier(issue: Issue, artifacts: ArtifactPresence): Sco
549
555
  * 4. If tier is in signalGated -> check concern signals
550
556
  * 5. Otherwise -> dispatch-local (safe default)
551
557
  */
552
- declare function routeIssue(scopeTier: ScopeTier, concernSignals: ConcernSignal[], config: EscalationConfig): RoutingDecision;
558
+ declare function routeIssue(scopeTier: ScopeTier, concernSignals: ConcernSignal[], config: EscalationConfig): IssueRoutingDecision;
553
559
 
554
560
  /**
555
561
  * Candidate skills the orchestrator may dispatch to. Keep this set
@@ -864,9 +870,107 @@ declare class WorkflowLoader {
864
870
  loadWorkflow(filePath: string): Promise<Result<WorkflowDefinition, Error>>;
865
871
  }
866
872
 
867
- declare function validateWorkflowConfig(config: unknown): Result<WorkflowConfig, Error>;
873
+ /**
874
+ * Cross-field check: every value in `routing` must reference a key in
875
+ * `backends`. Mirrors the Phase 1 standalone helper but returns a flat
876
+ * array of issues for synchronous consumption inside
877
+ * `validateWorkflowConfig` (which is hand-rolled, not a Zod parse).
878
+ *
879
+ * Exported for unit testing. Production callers should prefer
880
+ * `validateWorkflowConfig` (which wraps this helper with the surrounding
881
+ * legacy-vs-modern branching).
882
+ */
883
+ declare function crossFieldRoutingIssues(backends: Record<string, BackendDef>, routing: RoutingConfig): Array<{
884
+ path: string[];
885
+ message: string;
886
+ }>;
887
+ /**
888
+ * Spec B Phase 2 / S3: produce non-blocking warnings for misconfigured
889
+ * routing entries that are SYNTACTICALLY valid (the cross-field check
890
+ * has passed) but SEMANTICALLY suspicious:
891
+ *
892
+ * - `routing.skills.<name>` where `<name>` is not in the local skill
893
+ * catalog. Likely a typo or a skill that was renamed / removed.
894
+ *
895
+ * - `routing.modes.<mode>` where `<mode>` is not in the
896
+ * STANDARD_COGNITIVE_MODES tuple. Since `CognitiveMode` allows the
897
+ * `(string & {})` escape hatch, the type system accepts custom modes
898
+ * — but operators are far more likely to typo a standard mode than
899
+ * introduce a custom one, so we warn.
900
+ *
901
+ * Returns an empty array when `knownSkillNames` is empty (i.e., the
902
+ * catalog could not be discovered — most likely because `agents/skills/`
903
+ * is absent). Skipping is preferable to flooding the operator with
904
+ * false positives when the catalog itself is missing.
905
+ *
906
+ * Warnings are advisory; the loader continues to return `Ok` and the
907
+ * orchestrator starts normally.
908
+ */
909
+ declare function routingWarnings(routing: RoutingConfig, knownSkillNames: readonly string[]): string[];
910
+ interface ValidateWorkflowConfigOptions {
911
+ /**
912
+ * Known skill names from the local catalog. When non-empty, used to
913
+ * warn (S3) on `routing.skills.<name>` references that are not in
914
+ * the catalog. When empty, skill-name warnings are suppressed — the
915
+ * caller is presumed to be running without a discoverable catalog
916
+ * (e.g., tests, or orchestrator outside a harness project root).
917
+ */
918
+ knownSkillNames?: readonly string[];
919
+ }
920
+ interface ValidatedWorkflowConfig {
921
+ config: WorkflowConfig;
922
+ /**
923
+ * Non-blocking warnings produced during validation. Currently
924
+ * includes (Spec B Phase 2 / S3):
925
+ * - `routing.skills.<name>` not in the local catalog
926
+ * - `routing.modes.<mode>` not in `STANDARD_COGNITIVE_MODES`
927
+ */
928
+ warnings: readonly string[];
929
+ }
930
+ declare function validateWorkflowConfig(config: unknown, options?: ValidateWorkflowConfigOptions): Result<ValidatedWorkflowConfig, Error>;
868
931
  declare function getDefaultConfig(): WorkflowConfig;
869
932
 
933
+ /**
934
+ * Spec B Phase 3: an entry in the local skill catalog.
935
+ *
936
+ * Carries the skill's catalog `name` AND optional `cognitive_mode`
937
+ * declaration from `skill.yaml`. Consumed by the orchestrator dispatch
938
+ * site to construct `{ kind: 'skill', skillName, cognitiveMode }`
939
+ * RoutingUseCases so per-skill / per-mode routing fires at dispatch.
940
+ */
941
+ interface SkillCatalogEntry {
942
+ readonly name: string;
943
+ readonly cognitiveMode?: string;
944
+ }
945
+ /**
946
+ * Spec B Phase 3: read the local skill catalog at orchestrator startup,
947
+ * returning each declared skill's `name` AND optional `cognitive_mode`.
948
+ *
949
+ * Reads from EVERY host subdirectory under `agents/skills/` (claude-code,
950
+ * cursor, gemini, etc.). Names are deduplicated across hosts — first
951
+ * occurrence wins (matches Phase 2 behavior for `discoverSkillCatalogNames`).
952
+ *
953
+ * Returns an empty array when `agents/skills/` is absent (orchestrator
954
+ * running outside a harness project root). In that case dispatch-site
955
+ * routing falls through to per-tier resolution, preserving today's
956
+ * behavior (F11/N2).
957
+ *
958
+ * Errors reading individual skill.yaml files (malformed YAML, missing
959
+ * `name` field, IO errors) are swallowed silently. The catalog is
960
+ * advisory; a single broken skill.yaml should not block dispatch.
961
+ */
962
+ declare function discoverSkillCatalog(projectRoot: string): SkillCatalogEntry[];
963
+ /**
964
+ * Spec B Phase 2: read the local skill catalog at orchestrator startup
965
+ * for warning-level routing validation (`routing.skills.<name>` where
966
+ * `<name>` is not in the catalog).
967
+ *
968
+ * Spec B Phase 3: thin alias over {@link discoverSkillCatalog} — name
969
+ * extraction preserved for the Phase 2 WorkflowLoader → validation
970
+ * pipeline (no behavioral change for Phase 2 callers).
971
+ */
972
+ declare function discoverSkillCatalogNames(projectRoot: string): string[];
973
+
870
974
  /**
871
975
  * Adapter for using a markdown roadmap file as an issue tracker.
872
976
  *
@@ -1254,6 +1358,144 @@ interface MaintenanceStatus {
1254
1358
  history: RunResult[];
1255
1359
  }
1256
1360
 
1361
+ interface RoutingDecisionBusFilter {
1362
+ skillName?: string;
1363
+ mode?: string;
1364
+ backendName?: string;
1365
+ limit?: number;
1366
+ }
1367
+ interface RoutingDecisionBusOptions {
1368
+ /** Default 500. Bound on the in-memory ring buffer. */
1369
+ capacity?: number;
1370
+ /**
1371
+ * Logger for the structured `routing-decision` line (O1) and for
1372
+ * one-off warn() when a subscriber throws (S6). When omitted, the
1373
+ * bus silently swallows subscriber errors (test-mode default).
1374
+ */
1375
+ logger?: StructuredLogger;
1376
+ }
1377
+ /**
1378
+ * Spec B Phase 4 (D8): in-process bus + ring buffer for
1379
+ * {@link RoutingDecision} events. One emit() per
1380
+ * {@link BackendRouter.resolve} call; subscribers receive the
1381
+ * decision synchronously after the ring buffer is updated.
1382
+ *
1383
+ * Subscriber errors are isolated (caught + logged, never thrown
1384
+ * back to the emitter) so a misbehaving subscriber cannot block a
1385
+ * dispatch. (S6)
1386
+ *
1387
+ * Capacity-bound (default 500) via Array.shift() — acceptable for
1388
+ * v1 (see plan C4); switch to circular indexing if 24h dispatch
1389
+ * volume ever pushes 10K+ records/min.
1390
+ */
1391
+ declare class RoutingDecisionBus {
1392
+ private readonly ringBuffer;
1393
+ private readonly listeners;
1394
+ private readonly capacity;
1395
+ private readonly logger;
1396
+ constructor(opts?: RoutingDecisionBusOptions);
1397
+ emit(decision: RoutingDecision): void;
1398
+ recent(filter?: RoutingDecisionBusFilter): RoutingDecision[];
1399
+ subscribe(listener: (d: RoutingDecision) => void): () => void;
1400
+ /**
1401
+ * Spec B Phase 5 (review-S2 fix): release all subscriber references so
1402
+ * teardown can complete without anchoring closures. Called from
1403
+ * `Orchestrator.stop()` before nulling the bus reference. The bus
1404
+ * remains usable after clear — `subscribe()` works as normal.
1405
+ */
1406
+ clearListeners(): void;
1407
+ }
1408
+
1409
+ interface BackendRouterOptions {
1410
+ backends: Record<string, BackendDef>;
1411
+ routing: RoutingConfig;
1412
+ /**
1413
+ * Spec B Phase 4 (D8): when present, every resolve() emits its
1414
+ * decision onto the bus. The bus owns the structured log line + ring
1415
+ * buffer; the router stays a pure resolution function.
1416
+ */
1417
+ decisionBus?: RoutingDecisionBus;
1418
+ }
1419
+ /**
1420
+ * BackendRouter (Spec B Phase 1)
1421
+ *
1422
+ * Owns the lookup from a {@link RoutingUseCase} (a discriminated query
1423
+ * — tier, intelligence layer, maintenance, chat, isolation, **skill**,
1424
+ * **mode**) to a {@link RoutingDecision} naming a chosen backend and
1425
+ * the full resolution path that produced it.
1426
+ *
1427
+ * Resolution order (D2): invocation override -> per-skill -> per-mode
1428
+ * -> existing per-tier/intelligence/isolation/maintenance/chat ->
1429
+ * `routing.default`. Within each source, fallback chain entries are
1430
+ * tried in declared order; first existing backend wins. Unknown
1431
+ * entries are recorded with `outcome: 'unknown-backend'` and the walk
1432
+ * continues.
1433
+ *
1434
+ * Construction-time validation guarantees every name referenced by
1435
+ * `routing` is present in `backends` so the static-config case can
1436
+ * never produce a runtime exhaustion throw. The runtime throw at the
1437
+ * end of `resolve()` is a safety net for future dynamic-backends
1438
+ * scenarios where a chain entry can become unknown post-construction.
1439
+ */
1440
+ declare class BackendRouter {
1441
+ private readonly backends;
1442
+ private readonly routing;
1443
+ private readonly decisionBus;
1444
+ constructor(opts: BackendRouterOptions);
1445
+ /**
1446
+ * Resolve a {@link RoutingUseCase} to a {@link RoutingDecision}.
1447
+ *
1448
+ * @param useCase the routing query
1449
+ * @param opts.invocationOverride if set and the named backend exists,
1450
+ * beats all other sources (D7 — the `--backend <name>` escape hatch)
1451
+ */
1452
+ resolve(useCase: RoutingUseCase, opts?: {
1453
+ invocationOverride?: string;
1454
+ }): RoutingDecision;
1455
+ /**
1456
+ * Returns the {@link BackendDef} reference for the resolved name.
1457
+ * Identity-equal to the entry in `backends` (no copy) so callers
1458
+ * relying on reference equality (SC21) continue to work.
1459
+ */
1460
+ resolveDefinition(useCase: RoutingUseCase, opts?: {
1461
+ invocationOverride?: string;
1462
+ }): BackendDef;
1463
+ /**
1464
+ * Spec B Phase 4 (closes P1-IMP-2): a single resolve() + def lookup
1465
+ * for callers that need both. Replaces the previous pattern of
1466
+ * `resolveDefinition(useCase) + resolve(useCase)` which produced two
1467
+ * RoutingDecision emissions per dispatch — doubling routing-decision
1468
+ * log volume now that Phase 4 emits.
1469
+ *
1470
+ * Identity-equal `BackendDef` (no copy) so callers relying on
1471
+ * reference equality (SC21) continue to work.
1472
+ */
1473
+ resolveDecisionAndDef(useCase: RoutingUseCase, opts?: {
1474
+ invocationOverride?: string;
1475
+ }): {
1476
+ decision: RoutingDecision;
1477
+ def: BackendDef;
1478
+ };
1479
+ /**
1480
+ * The pre-Spec-B resolution helper: returns the configured
1481
+ * {@link RoutingValue} for tier/intelligence/isolation/maintenance/chat
1482
+ * use cases (or `undefined` for skill/mode use cases, which are owned
1483
+ * by the per-skill / per-mode steps in {@link resolve}). Returning
1484
+ * `undefined` lets the caller fall through to `routing.default`.
1485
+ */
1486
+ private resolveExistingUseCase;
1487
+ private validateReferences;
1488
+ }
1489
+
1490
+ /**
1491
+ * The central orchestrator that manages the lifecycle of coding agents.
1492
+ *
1493
+ * It polls an issue tracker for candidate tasks, manages ephemeral workspaces,
1494
+ * runs agents to resolve issues, and updates the tracker with progress.
1495
+ *
1496
+ * @fires Orchestrator#state_change Emitted when the internal state machine transitions
1497
+ * @fires Orchestrator#agent_event Emitted when an agent produces an output or thought
1498
+ */
1257
1499
  declare class Orchestrator extends EventEmitter {
1258
1500
  private state;
1259
1501
  private config;
@@ -1278,6 +1520,14 @@ declare class Orchestrator extends EventEmitter {
1278
1520
  * construction time. Eliminating this fallback is autopilot Phase 4+.
1279
1521
  */
1280
1522
  private backendFactory;
1523
+ /**
1524
+ * Spec B Phase 4 (D8): per-orchestrator in-process bus for
1525
+ * `RoutingDecision` events. Constructed alongside backendFactory when
1526
+ * agent.backends synthesis succeeds; null when legacy single-backend
1527
+ * config bypassed backends. Phase 5+ consumers (HTTP, WS, dashboard)
1528
+ * subscribe via `getRoutingDecisionBus()`.
1529
+ */
1530
+ private routingDecisionBus;
1281
1531
  /**
1282
1532
  * Test-only: when overrides.backend is provided, dispatch uses this
1283
1533
  * instance directly (bypassing the factory). Mirrors Phase 1
@@ -1300,6 +1550,15 @@ declare class Orchestrator extends EventEmitter {
1300
1550
  * so this map is the single source of truth post-migration.
1301
1551
  */
1302
1552
  private localResolvers;
1553
+ /**
1554
+ * Spec B Phase 3: skill catalog (name + cognitiveMode) read once at
1555
+ * construction from `projectRoot/agents/skills/`. Consulted by
1556
+ * `buildRoutingUseCase` at dispatch start to construct
1557
+ * `{ kind: 'skill', skillName, cognitiveMode }` RoutingUseCases.
1558
+ * Empty when the orchestrator runs outside a harness project root
1559
+ * (then dispatch falls through to per-tier, preserving F11/N2).
1560
+ */
1561
+ private readonly skillCatalog;
1303
1562
  /**
1304
1563
  * Per-resolver `onStatusChange` unsubscribe callbacks. Spec 2 Phase 5
1305
1564
  * (SC39): each local/pi resolver gets its own listener emitting a
@@ -1482,6 +1741,34 @@ declare class Orchestrator extends EventEmitter {
1482
1741
  * Returns a point-in-time snapshot of the orchestrator's internal state.
1483
1742
  */
1484
1743
  getSnapshot(): Record<string, unknown>;
1744
+ /**
1745
+ * Spec B Phase 4 (D8): expose the bus for Phase 5 (HTTP routes) and
1746
+ * Phase 7 (dashboard WS broadcast). Returns null when the legacy
1747
+ * single-backend config bypassed agent.backends synthesis.
1748
+ */
1749
+ getRoutingDecisionBus(): RoutingDecisionBus | null;
1750
+ /**
1751
+ * Spec B Phase 5: live BackendRouter for HTTP routes. The orchestrator
1752
+ * dispatch path uses the factory-owned router directly; observability
1753
+ * routes (config / decisions) reach it through this accessor. Returns
1754
+ * null when the legacy single-backend config bypassed agent.backends
1755
+ * synthesis (no backendFactory built).
1756
+ */
1757
+ getBackendRouter(): BackendRouter | null;
1758
+ /**
1759
+ * Spec B Phase 5: snapshot of the active RoutingConfig for the config
1760
+ * route and the trace route's bus-less router construction. Returns
1761
+ * null when the operator's harness.config.json carries no
1762
+ * `agent.routing` block.
1763
+ */
1764
+ getRoutingConfig(): _harness_engineering_types.RoutingConfig | null;
1765
+ /**
1766
+ * Spec B Phase 5: snapshot of `agent.backends` for the config route
1767
+ * (existence annotations) and the trace route (bus-less router
1768
+ * construction). Returns null when no synthesized backends map exists
1769
+ * (legacy single-backend configs).
1770
+ */
1771
+ getBackends(): Record<string, _harness_engineering_types.BackendDef> | null;
1485
1772
  /** Returns the maintenance scheduler status, or null if maintenance is not enabled. */
1486
1773
  getMaintenanceStatus(): MaintenanceStatus | null;
1487
1774
  }
@@ -1497,47 +1784,6 @@ declare function launchTUI(orchestrator: Orchestrator): {
1497
1784
  waitUntilExit: () => Promise<void>;
1498
1785
  };
1499
1786
 
1500
- interface BackendRouterOptions {
1501
- backends: Record<string, BackendDef>;
1502
- routing: RoutingConfig;
1503
- }
1504
- /**
1505
- * BackendRouter
1506
- *
1507
- * Owns the lookup from a `RoutingUseCase` (a discriminated query — tier,
1508
- * intelligence layer, maintenance, chat) to a named backend.
1509
- * Construction-time validation guarantees every name referenced by
1510
- * `routing` is present in `backends` so runtime lookups are total and
1511
- * never throw on unknown-name references (D6/D7).
1512
- *
1513
- * Lookups for tier/intelligence use cases that fall through to undefined
1514
- * mappings return `routing.default` without throwing — this matches the
1515
- * spec's "every use case inherits default unless explicitly routed"
1516
- * semantics. The `maintenance` and `chat` kinds always resolve to
1517
- * `routing.default` (SC19, SC20).
1518
- */
1519
- declare class BackendRouter {
1520
- private readonly backends;
1521
- private readonly routing;
1522
- constructor(opts: BackendRouterOptions);
1523
- /**
1524
- * Returns the backend name for a given use case.
1525
- *
1526
- * - `tier`: per-tier override, falling back to `routing.default`.
1527
- * - `intelligence`: per-layer override under `routing.intelligence`,
1528
- * falling back to `routing.default`.
1529
- * - `maintenance` / `chat`: always `routing.default`.
1530
- */
1531
- resolve(useCase: RoutingUseCase): string;
1532
- /**
1533
- * Returns the BackendDef reference for the resolved name. Returns the
1534
- * exact reference held in `backends` (no copy) so identity comparisons
1535
- * succeed (SC21).
1536
- */
1537
- resolveDefinition(useCase: RoutingUseCase): BackendDef;
1538
- private validateReferences;
1539
- }
1540
-
1541
1787
  /**
1542
1788
  * Options for `OrchestratorBackendFactory`.
1543
1789
  *
@@ -1572,6 +1818,11 @@ interface OrchestratorBackendFactoryOptions {
1572
1818
  * `/api/v1/telemetry/cache/stats` endpoint sees the full rolling window.
1573
1819
  */
1574
1820
  cacheMetrics?: CacheMetricsRecorder;
1821
+ /**
1822
+ * Spec B Phase 4 (D8): forwarded to the underlying BackendRouter so
1823
+ * every resolve() during forUseCase / resolveName emits.
1824
+ */
1825
+ decisionBus?: RoutingDecisionBus;
1575
1826
  }
1576
1827
  /**
1577
1828
  * High-level factory wrapping `BackendRouter` + `createBackend` plus
@@ -1604,8 +1855,19 @@ declare class OrchestratorBackendFactory {
1604
1855
  * is `undefined` for pure-modern configs. Threading the routed name
1605
1856
  * through dispatch eliminates that gap.
1606
1857
  */
1607
- resolveName(useCase: RoutingUseCase): string;
1608
- forUseCase(useCase: RoutingUseCase): AgentBackend;
1858
+ resolveName(useCase: RoutingUseCase, opts?: {
1859
+ invocationOverride?: string;
1860
+ }): string;
1861
+ /**
1862
+ * Spec B Phase 1: expose the underlying router for callers that need
1863
+ * it directly (e.g., {@link buildIntelligencePipeline} for the
1864
+ * I1 SEL/PESL comparison fix). Read-only access; consumers must not
1865
+ * mutate router state.
1866
+ */
1867
+ getRouter(): BackendRouter;
1868
+ forUseCase(useCase: RoutingUseCase, opts?: {
1869
+ invocationOverride?: string;
1870
+ }): AgentBackend;
1609
1871
  /**
1610
1872
  * Rebuild a `local`/`pi` backend with a resolver-bound `getModel`,
1611
1873
  * mirroring `createBackend`'s local/pi branches but substituting the
@@ -1660,6 +1922,270 @@ interface CreateBackendOptions {
1660
1922
  */
1661
1923
  declare function createBackend(def: BackendDef, options?: CreateBackendOptions): AgentBackend;
1662
1924
 
1925
+ /**
1926
+ * Zod schema for `BackendDef` (Spec 2 — multi-backend routing).
1927
+ *
1928
+ * Discriminated union on `type`. Per-variant validation surfaces shape
1929
+ * mismatches (missing `model`, missing `endpoint`, etc.) at config-load
1930
+ * time rather than at orchestrator runtime.
1931
+ *
1932
+ * Used in Phase 3 by `validateWorkflowConfig`; in Phase 1 it is exported
1933
+ * for standalone unit testing.
1934
+ */
1935
+ declare const BackendDefSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
1936
+ type: z.ZodLiteral<"mock">;
1937
+ }, "strict", z.ZodTypeAny, {
1938
+ type: "mock";
1939
+ }, {
1940
+ type: "mock";
1941
+ }>, z.ZodObject<{
1942
+ type: z.ZodLiteral<"claude">;
1943
+ command: z.ZodOptional<z.ZodString>;
1944
+ }, "strict", z.ZodTypeAny, {
1945
+ type: "claude";
1946
+ command?: string | undefined;
1947
+ }, {
1948
+ type: "claude";
1949
+ command?: string | undefined;
1950
+ }>, z.ZodObject<{
1951
+ type: z.ZodLiteral<"anthropic">;
1952
+ model: z.ZodString;
1953
+ apiKey: z.ZodOptional<z.ZodString>;
1954
+ }, "strict", z.ZodTypeAny, {
1955
+ type: "anthropic";
1956
+ model: string;
1957
+ apiKey?: string | undefined;
1958
+ }, {
1959
+ type: "anthropic";
1960
+ model: string;
1961
+ apiKey?: string | undefined;
1962
+ }>, z.ZodObject<{
1963
+ type: z.ZodLiteral<"openai">;
1964
+ model: z.ZodString;
1965
+ apiKey: z.ZodOptional<z.ZodString>;
1966
+ }, "strict", z.ZodTypeAny, {
1967
+ type: "openai";
1968
+ model: string;
1969
+ apiKey?: string | undefined;
1970
+ }, {
1971
+ type: "openai";
1972
+ model: string;
1973
+ apiKey?: string | undefined;
1974
+ }>, z.ZodObject<{
1975
+ type: z.ZodLiteral<"gemini">;
1976
+ model: z.ZodString;
1977
+ apiKey: z.ZodOptional<z.ZodString>;
1978
+ }, "strict", z.ZodTypeAny, {
1979
+ type: "gemini";
1980
+ model: string;
1981
+ apiKey?: string | undefined;
1982
+ }, {
1983
+ type: "gemini";
1984
+ model: string;
1985
+ apiKey?: string | undefined;
1986
+ }>, z.ZodObject<{
1987
+ type: z.ZodLiteral<"local">;
1988
+ endpoint: z.ZodString;
1989
+ model: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "atleastone">]>;
1990
+ apiKey: z.ZodOptional<z.ZodString>;
1991
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
1992
+ probeIntervalMs: z.ZodOptional<z.ZodNumber>;
1993
+ }, "strict", z.ZodTypeAny, {
1994
+ type: "local";
1995
+ model: string | [string, ...string[]];
1996
+ endpoint: string;
1997
+ apiKey?: string | undefined;
1998
+ timeoutMs?: number | undefined;
1999
+ probeIntervalMs?: number | undefined;
2000
+ }, {
2001
+ type: "local";
2002
+ model: string | [string, ...string[]];
2003
+ endpoint: string;
2004
+ apiKey?: string | undefined;
2005
+ timeoutMs?: number | undefined;
2006
+ probeIntervalMs?: number | undefined;
2007
+ }>, z.ZodObject<{
2008
+ type: z.ZodLiteral<"pi">;
2009
+ endpoint: z.ZodString;
2010
+ model: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "atleastone">]>;
2011
+ apiKey: z.ZodOptional<z.ZodString>;
2012
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
2013
+ probeIntervalMs: z.ZodOptional<z.ZodNumber>;
2014
+ }, "strict", z.ZodTypeAny, {
2015
+ type: "pi";
2016
+ model: string | [string, ...string[]];
2017
+ endpoint: string;
2018
+ apiKey?: string | undefined;
2019
+ timeoutMs?: number | undefined;
2020
+ probeIntervalMs?: number | undefined;
2021
+ }, {
2022
+ type: "pi";
2023
+ model: string | [string, ...string[]];
2024
+ endpoint: string;
2025
+ apiKey?: string | undefined;
2026
+ timeoutMs?: number | undefined;
2027
+ probeIntervalMs?: number | undefined;
2028
+ }>]>;
2029
+ /**
2030
+ * Spec B Phase 0: a routing target is either a backend name (scalar
2031
+ * string) or a non-empty ordered fallback chain (string tuple). The
2032
+ * scalar form is byte-compatible with pre-Spec-B configs.
2033
+ */
2034
+ declare const RoutingValueSchema: z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>;
2035
+ /**
2036
+ * Zod schema for `RoutingConfig`. `.strict()` rejects unknown keys at
2037
+ * every level (per Spec 2 D7: typos in routing keys are validation
2038
+ * errors, not silent default-fallthroughs).
2039
+ *
2040
+ * Spec B Phase 0: all scalar routing fields accept `RoutingValueSchema`
2041
+ * (scalar or non-empty chain). New optional `skills` and `modes` maps
2042
+ * accept the same.
2043
+ *
2044
+ * Spec B Phase 2: the `isolation` block (added to the TS interface in
2045
+ * Hermes Phase 5 but not previously in this Zod schema) is now included
2046
+ * here with each tier widened to `RoutingValueSchema`. This closes the
2047
+ * Phase 0 I2 review finding (TS-vs-Zod drift) and ensures isolation
2048
+ * chain entries are validated by the same cross-field check that
2049
+ * covers `skills` / `modes`.
2050
+ */
2051
+ declare const RoutingConfigSchema: z.ZodObject<{
2052
+ default: z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>;
2053
+ 'quick-fix': z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2054
+ 'guided-change': z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2055
+ 'full-exploration': z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2056
+ diagnostic: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2057
+ intelligence: z.ZodOptional<z.ZodObject<{
2058
+ sel: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2059
+ pesl: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2060
+ }, "strict", z.ZodTypeAny, {
2061
+ sel?: string | readonly [string, ...string[]] | undefined;
2062
+ pesl?: string | readonly [string, ...string[]] | undefined;
2063
+ }, {
2064
+ sel?: string | readonly [string, ...string[]] | undefined;
2065
+ pesl?: string | readonly [string, ...string[]] | undefined;
2066
+ }>>;
2067
+ isolation: z.ZodOptional<z.ZodObject<{
2068
+ none: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2069
+ container: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2070
+ 'remote-sandbox': z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>;
2071
+ }, "strict", z.ZodTypeAny, {
2072
+ none?: string | readonly [string, ...string[]] | undefined;
2073
+ container?: string | readonly [string, ...string[]] | undefined;
2074
+ 'remote-sandbox'?: string | readonly [string, ...string[]] | undefined;
2075
+ }, {
2076
+ none?: string | readonly [string, ...string[]] | undefined;
2077
+ container?: string | readonly [string, ...string[]] | undefined;
2078
+ 'remote-sandbox'?: string | readonly [string, ...string[]] | undefined;
2079
+ }>>;
2080
+ skills: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>>;
2081
+ modes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnion<[z.ZodString, z.ZodReadonly<z.ZodArray<z.ZodString, "atleastone">>]>>>;
2082
+ }, "strict", z.ZodTypeAny, {
2083
+ default: string | readonly [string, ...string[]];
2084
+ 'quick-fix'?: string | readonly [string, ...string[]] | undefined;
2085
+ 'guided-change'?: string | readonly [string, ...string[]] | undefined;
2086
+ 'full-exploration'?: string | readonly [string, ...string[]] | undefined;
2087
+ diagnostic?: string | readonly [string, ...string[]] | undefined;
2088
+ intelligence?: {
2089
+ sel?: string | readonly [string, ...string[]] | undefined;
2090
+ pesl?: string | readonly [string, ...string[]] | undefined;
2091
+ } | undefined;
2092
+ isolation?: {
2093
+ none?: string | readonly [string, ...string[]] | undefined;
2094
+ container?: string | readonly [string, ...string[]] | undefined;
2095
+ 'remote-sandbox'?: string | readonly [string, ...string[]] | undefined;
2096
+ } | undefined;
2097
+ skills?: Record<string, string | readonly [string, ...string[]]> | undefined;
2098
+ modes?: Record<string, string | readonly [string, ...string[]]> | undefined;
2099
+ }, {
2100
+ default: string | readonly [string, ...string[]];
2101
+ 'quick-fix'?: string | readonly [string, ...string[]] | undefined;
2102
+ 'guided-change'?: string | readonly [string, ...string[]] | undefined;
2103
+ 'full-exploration'?: string | readonly [string, ...string[]] | undefined;
2104
+ diagnostic?: string | readonly [string, ...string[]] | undefined;
2105
+ intelligence?: {
2106
+ sel?: string | readonly [string, ...string[]] | undefined;
2107
+ pesl?: string | readonly [string, ...string[]] | undefined;
2108
+ } | undefined;
2109
+ isolation?: {
2110
+ none?: string | readonly [string, ...string[]] | undefined;
2111
+ container?: string | readonly [string, ...string[]] | undefined;
2112
+ 'remote-sandbox'?: string | readonly [string, ...string[]] | undefined;
2113
+ } | undefined;
2114
+ skills?: Record<string, string | readonly [string, ...string[]]> | undefined;
2115
+ modes?: Record<string, string | readonly [string, ...string[]]> | undefined;
2116
+ }>;
2117
+
2118
+ interface ResolverLogger {
2119
+ info(message: string, context?: Record<string, unknown>): void;
2120
+ warn(message: string, context?: Record<string, unknown>): void;
2121
+ }
2122
+ interface LocalModelResolverOptions {
2123
+ endpoint: string;
2124
+ apiKey?: string;
2125
+ /** Normalized candidate list (already turned from string|string[] into string[]). */
2126
+ configured: string[];
2127
+ /** Probe cadence in ms; default 30_000, minimum 1_000. */
2128
+ probeIntervalMs?: number;
2129
+ /**
2130
+ * Per-request timeout for the default fetch implementation, in ms.
2131
+ * Default: 5_000. Ignored when a custom `fetchModels` is provided
2132
+ * (custom impls own their own timeout policy). Spec §3.1 line 136
2133
+ * enumerates timeout as a supported failure mode.
2134
+ */
2135
+ timeoutMs?: number;
2136
+ /**
2137
+ * Injectable for tests. Default: GET `${endpoint}/models` with bearer apiKey.
2138
+ * Resolves to detected model IDs. Rejects on network/timeout/non-2xx/malformed.
2139
+ */
2140
+ fetchModels?: (endpoint: string, apiKey?: string) => Promise<string[]>;
2141
+ logger?: ResolverLogger;
2142
+ }
2143
+ declare function normalizeLocalModel(input: string | string[] | undefined): string[];
2144
+ /**
2145
+ * Default `fetchModels` — GET `${endpoint}/models` with bearer apiKey.
2146
+ * Throws on network failure, non-2xx, malformed body, or timeout.
2147
+ *
2148
+ * `timeoutMs` defaults to 5_000. A timeout aborts the in-flight request and
2149
+ * surfaces as `Error('request timeout (Nms)')` so callers can distinguish it
2150
+ * from generic network errors.
2151
+ */
2152
+ declare function defaultFetchModels(endpoint: string, apiKey?: string, timeoutMs?: number): Promise<string[]>;
2153
+ declare class LocalModelResolver {
2154
+ private readonly endpoint;
2155
+ private readonly apiKey?;
2156
+ private readonly configured;
2157
+ private readonly probeIntervalMs;
2158
+ private readonly fetchModels;
2159
+ private readonly logger;
2160
+ private timer;
2161
+ private listeners;
2162
+ /**
2163
+ * Tracks an in-flight probe so concurrent invocations (interval tick while a
2164
+ * slow probe is running, or a manual `probe()` call mid-flight) share the
2165
+ * existing promise instead of racing to mutate `detected/resolved/lastError/
2166
+ * warnings` non-atomically across `await` points. Applies to both the timer
2167
+ * callback and direct `probe()` calls — any caller that arrives during an
2168
+ * in-flight probe gets the same promise back. Cleared in `finally` so the
2169
+ * next tick can start a fresh probe.
2170
+ */
2171
+ private probeInFlight;
2172
+ private resolved;
2173
+ private detected;
2174
+ private lastProbeAt;
2175
+ private lastError;
2176
+ private warnings;
2177
+ private available;
2178
+ constructor(opts: LocalModelResolverOptions);
2179
+ resolveModel(): string | null;
2180
+ getStatus(): LocalModelStatus;
2181
+ onStatusChange(handler: (status: LocalModelStatus) => void): () => void;
2182
+ probe(): Promise<LocalModelStatus>;
2183
+ private runProbe;
2184
+ start(): Promise<void>;
2185
+ stop(): void;
2186
+ private snapshotForDiff;
2187
+ }
2188
+
1663
2189
  /**
1664
2190
  * Function signature compatible with Node's `child_process.execFile`.
1665
2191
  * Allows injection for testing.
@@ -2291,4 +2817,4 @@ declare function emitProposalCreated(bus: EventEmitter, proposal: SkillProposal)
2291
2817
  declare function emitProposalApproved(bus: EventEmitter, proposal: SkillProposal): void;
2292
2818
  declare function emitProposalRejected(bus: EventEmitter, proposal: SkillProposal): void;
2293
2819
 
2294
- export { type AgentUpdateEvent, AnalysisArchive, type AnalysisRecord, type ApplyEventResult, type ArtifactPresence, type AttemptStats, BUILT_IN_TASKS, BackendRouter, type BackendRouterOptions, type BaseRefFallbackEvent, type BuildArchiveHooksOptions, ClaimManager, type ClaimManagerConfig, type CleanWorkspaceEffect, type CreateTokenInput, type CreateTokenResult, type CustomTaskValidationError, type DispatchEffect, type EmitLogEffect, type EscalateEffect, type ExecFileFn$1 as ExecFileFn, type FromConfigOptions, GateNotReadyError, type GateResult, GateRunError, type Highlight, type HighlightsInfo, type IndexedDoc, InteractionQueue, type LinearGraphQLExtension, LinearGraphQLStub, type LiveSession, MAX_ATTEMPTS, type MigrationResult, MockBackend, type NotificationSink, type NotificationSinkDeliverInput, ORCHESTRATOR_IDENTITY_FILE, Orchestrator, OrchestratorBackendFactory, type OrchestratorBackendFactoryOptions, type OrchestratorContext, type OrchestratorEvent, type OrchestratorState, PRDetector, type PRDetectorLogger, type PendingInteraction, type PersistedOutputEntry, PromotionError, type PromotionResult, PromptRenderer, type ProposalApprovedData, type ProposalCreatedData, type ProposalRejectedData, type PublishedIndex, type QueueInsertInput, type QueueRow, type QueueStats, RETRY_DELAYS_MS, type RateLimitSnapshot as RateLimitComputeSnapshot, type RateLimitConfig, type RateLimitSnapshot$1 as RateLimitSnapshot, type RegistryEntry, type ReleaseClaimEffect, type RetryEntry, type RetryFiredEvent, RoadmapTrackerAdapter, type RunAttemptPhase, type RunOrigin, type RunningEntry, type ScheduleRetryEffect, type SearchOptions, type SideEffect, SinkConfigError, SinkRegistry, SlackSink, type SlackSinkOptions, SqliteSearchIndex, type StallDetectedEvent, type StopEffect, type StreamManifest, StreamRecorder, type SummarizeContext, type SummarizeResult, type SyncMainOptions, type SyncMainResult, type SyncSkipReason, type TaskDefinition, TaskOutputStore, type TaskType, type TickEvent, TokenStore, type TokenTotals, type TriageConfig, type TriageDecision, type TriageSignals, type TriageSkill, type UpdateTokensEffect, WebhookQueue, type WorkerExitEvent, WorkflowLoader, WorkspaceHooks, WorkspaceManager, type WorkspaceManagerOptions, applyEvent, artifactPresenceFromIssue, buildArchiveHooks, calculateRetryDelay, canDispatch, computeRateLimitDelay, createBackend, createEmptyState, detectScopeTier, emitProposalApproved, emitProposalCreated, emitProposalRejected, extractHighlights, extractTitlePrefix, getAvailableSlots, getDefaultConfig, getPerStateCount, indexSessionDirectory, isEligible, isSummaryEnabled, launchTUI, loadPublishedIndex, migrateAgentConfig, normalizeFts5Query, openSearchIndex, promote, reconcile, reindexFromArchive, renderAnalysisComment, renderLlmSummaryMarkdown, renderPRComment, resolveEscalationConfig, resolveOrchestratorId, routeIssue, runGate, savePublishedIndex, searchIndexPath, selectCandidates, sortCandidates, summarizeArchivedSession, syncMain, triageIssue, truncateForBudget, validateCustomTasks, validateWorkflowConfig, wireNotificationSinks, wrapAsEnvelope };
2820
+ export { type AgentUpdateEvent, AnalysisArchive, type AnalysisRecord, type ApplyEventResult, type ArtifactPresence, type AttemptStats, BUILT_IN_TASKS, BackendDefSchema, BackendRouter, type BackendRouterOptions, type BaseRefFallbackEvent, type BuildArchiveHooksOptions, ClaimManager, type ClaimManagerConfig, type CleanWorkspaceEffect, type CreateTokenInput, type CreateTokenResult, type CustomTaskValidationError, type DispatchEffect, type EmitLogEffect, type EscalateEffect, type ExecFileFn$1 as ExecFileFn, type FromConfigOptions, GateNotReadyError, type GateResult, GateRunError, type Highlight, type HighlightsInfo, type IndexedDoc, InteractionQueue, type LinearGraphQLExtension, LinearGraphQLStub, type LiveSession, LocalModelResolver, type LocalModelResolverOptions, MAX_ATTEMPTS, type MigrationResult, MockBackend, type NotificationSink, type NotificationSinkDeliverInput, ORCHESTRATOR_IDENTITY_FILE, Orchestrator, OrchestratorBackendFactory, type OrchestratorBackendFactoryOptions, type OrchestratorContext, type OrchestratorEvent, type OrchestratorState, PRDetector, type PRDetectorLogger, type PendingInteraction, type PersistedOutputEntry, PromotionError, type PromotionResult, PromptRenderer, type ProposalApprovedData, type ProposalCreatedData, type ProposalRejectedData, type PublishedIndex, type QueueInsertInput, type QueueRow, type QueueStats, RETRY_DELAYS_MS, type RateLimitSnapshot as RateLimitComputeSnapshot, type RateLimitConfig, type RateLimitSnapshot$1 as RateLimitSnapshot, type RegistryEntry, type ReleaseClaimEffect, type ResolverLogger, type RetryEntry, type RetryFiredEvent, RoadmapTrackerAdapter, RoutingConfigSchema, RoutingValueSchema, type RunAttemptPhase, type RunOrigin, type RunningEntry, type ScheduleRetryEffect, type SearchOptions, type SideEffect, SinkConfigError, SinkRegistry, type SkillCatalogEntry, SlackSink, type SlackSinkOptions, SqliteSearchIndex, type StallDetectedEvent, type StopEffect, type StreamManifest, StreamRecorder, type SummarizeContext, type SummarizeResult, type SyncMainOptions, type SyncMainResult, type SyncSkipReason, type TaskDefinition, TaskOutputStore, type TaskType, type TickEvent, TokenStore, type TokenTotals, type TriageConfig, type TriageDecision, type TriageSignals, type TriageSkill, type UpdateTokensEffect, type ValidateWorkflowConfigOptions, type ValidatedWorkflowConfig, WebhookQueue, type WorkerExitEvent, WorkflowLoader, WorkspaceHooks, WorkspaceManager, type WorkspaceManagerOptions, applyEvent, artifactPresenceFromIssue, buildArchiveHooks, calculateRetryDelay, canDispatch, computeRateLimitDelay, createBackend, createEmptyState, crossFieldRoutingIssues, defaultFetchModels, detectScopeTier, discoverSkillCatalog, discoverSkillCatalogNames, emitProposalApproved, emitProposalCreated, emitProposalRejected, extractHighlights, extractTitlePrefix, getAvailableSlots, getDefaultConfig, getPerStateCount, indexSessionDirectory, isEligible, isSummaryEnabled, launchTUI, loadPublishedIndex, migrateAgentConfig, normalizeFts5Query, normalizeLocalModel, openSearchIndex, promote, reconcile, reindexFromArchive, renderAnalysisComment, renderLlmSummaryMarkdown, renderPRComment, resolveEscalationConfig, resolveOrchestratorId, routeIssue, routingWarnings, runGate, savePublishedIndex, searchIndexPath, selectCandidates, sortCandidates, summarizeArchivedSession, syncMain, triageIssue, truncateForBudget, validateCustomTasks, validateWorkflowConfig, wireNotificationSinks, wrapAsEnvelope };