@kb-labs/agent-contracts 2.118.2 → 2.119.0-canary.0b4b21a55
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 +74 -10
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -715,8 +715,47 @@ interface Turn {
|
|
|
715
715
|
runId?: string;
|
|
716
716
|
/** Summary of files changed during this turn (populated on run completion) */
|
|
717
717
|
fileChanges?: FileChangeSummary[];
|
|
718
|
+
/**
|
|
719
|
+
* Client-generated id echoed back on user turns, so the frontend can
|
|
720
|
+
* reconcile its optimistic message by id instead of fuzzy text-matching.
|
|
721
|
+
*/
|
|
722
|
+
clientId?: string;
|
|
718
723
|
};
|
|
719
724
|
}
|
|
725
|
+
/**
|
|
726
|
+
* Incremental change to a Turn, addressed by the session's monotonic `seq`.
|
|
727
|
+
* The server emits these instead of resending the full Turn on every event —
|
|
728
|
+
* the client applies them as ordered patches against its local turn map.
|
|
729
|
+
* `turn:created` carries the turn WITHOUT steps; steps arrive via their own
|
|
730
|
+
* `turn:step:appended` deltas (including any present at creation time).
|
|
731
|
+
*/
|
|
732
|
+
type TurnDelta = {
|
|
733
|
+
kind: 'turn:created';
|
|
734
|
+
seq: number;
|
|
735
|
+
turn: Turn;
|
|
736
|
+
} | {
|
|
737
|
+
kind: 'turn:step:appended';
|
|
738
|
+
seq: number;
|
|
739
|
+
turnId: string;
|
|
740
|
+
step: TurnStep;
|
|
741
|
+
} | {
|
|
742
|
+
kind: 'turn:step:updated';
|
|
743
|
+
seq: number;
|
|
744
|
+
turnId: string;
|
|
745
|
+
step: TurnStep;
|
|
746
|
+
} | {
|
|
747
|
+
kind: 'turn:status';
|
|
748
|
+
seq: number;
|
|
749
|
+
turnId: string;
|
|
750
|
+
status: Turn['status'];
|
|
751
|
+
completedAt: string | null;
|
|
752
|
+
error?: Turn['error'];
|
|
753
|
+
} | {
|
|
754
|
+
kind: 'turn:metadata';
|
|
755
|
+
seq: number;
|
|
756
|
+
turnId: string;
|
|
757
|
+
patch: Partial<Turn['metadata']>;
|
|
758
|
+
};
|
|
720
759
|
/**
|
|
721
760
|
* A step is a single action within a turn.
|
|
722
761
|
* Maps to event types from the event stream.
|
|
@@ -2435,6 +2474,14 @@ interface RunCompletedMessage {
|
|
|
2435
2474
|
success: boolean;
|
|
2436
2475
|
summary: string;
|
|
2437
2476
|
durationMs: number;
|
|
2477
|
+
/** Session-wide cursor value for this event, for gap detection. */
|
|
2478
|
+
seq: number;
|
|
2479
|
+
/**
|
|
2480
|
+
* Final state of the assistant turn this run produced, if any. Carried
|
|
2481
|
+
* here so the client has a guaranteed-fresh terminal state without
|
|
2482
|
+
* depending on the ordering of a separate delta message arriving first.
|
|
2483
|
+
*/
|
|
2484
|
+
turn?: Turn;
|
|
2438
2485
|
};
|
|
2439
2486
|
timestamp: number;
|
|
2440
2487
|
}
|
|
@@ -2463,32 +2510,37 @@ interface CorrectionAckMessage {
|
|
|
2463
2510
|
timestamp: number;
|
|
2464
2511
|
}
|
|
2465
2512
|
/**
|
|
2466
|
-
* Turn
|
|
2467
|
-
* Sent
|
|
2513
|
+
* Turn delta message (server → client)
|
|
2514
|
+
* Sent for every incremental change to a turn's projection. This is the
|
|
2515
|
+
* SOLE live-update channel — the client applies deltas as ordered patches
|
|
2516
|
+
* against its local turn map, gated by `delta.seq`. Replaces the previous
|
|
2517
|
+
* full-Turn-per-event `turn:snapshot` message.
|
|
2468
2518
|
*/
|
|
2469
|
-
interface
|
|
2470
|
-
type: 'turn:
|
|
2519
|
+
interface TurnDeltaMessage {
|
|
2520
|
+
type: 'turn:delta';
|
|
2471
2521
|
payload: {
|
|
2472
2522
|
sessionId: string;
|
|
2473
|
-
|
|
2474
|
-
sequenceNumber: number;
|
|
2523
|
+
delta: TurnDelta;
|
|
2475
2524
|
};
|
|
2476
2525
|
timestamp: number;
|
|
2477
2526
|
}
|
|
2478
2527
|
/**
|
|
2479
2528
|
* Conversation snapshot message (server → client)
|
|
2480
|
-
* Sent on initial WebSocket connection
|
|
2529
|
+
* Sent on initial WebSocket connection (or reconnect without a resume
|
|
2530
|
+
* cursor) to provide the full current projection as a cold-start baseline.
|
|
2481
2531
|
*/
|
|
2482
2532
|
interface ConversationSnapshotMessage {
|
|
2483
2533
|
type: 'conversation:snapshot';
|
|
2484
2534
|
payload: {
|
|
2485
2535
|
sessionId: string;
|
|
2486
|
-
/** Recent completed turns
|
|
2536
|
+
/** Recent completed turns */
|
|
2487
2537
|
completedTurns: Turn[];
|
|
2488
2538
|
/** Currently streaming turns */
|
|
2489
2539
|
activeTurns: Turn[];
|
|
2490
2540
|
/** Total turns in session */
|
|
2491
2541
|
totalTurns: number;
|
|
2542
|
+
/** Session-wide cursor value this snapshot was taken at. */
|
|
2543
|
+
seq: number;
|
|
2492
2544
|
/** Snapshot timestamp */
|
|
2493
2545
|
timestamp: string;
|
|
2494
2546
|
};
|
|
@@ -2497,7 +2549,7 @@ interface ConversationSnapshotMessage {
|
|
|
2497
2549
|
/**
|
|
2498
2550
|
* Union of all server → client messages
|
|
2499
2551
|
*/
|
|
2500
|
-
type ServerMessage = ConnectionReadyMessage | RunCompletedMessage | ErrorMessage | CorrectionAckMessage |
|
|
2552
|
+
type ServerMessage = ConnectionReadyMessage | RunCompletedMessage | ErrorMessage | CorrectionAckMessage | TurnDeltaMessage | ConversationSnapshotMessage;
|
|
2501
2553
|
/**
|
|
2502
2554
|
* User correction message (client → server)
|
|
2503
2555
|
* User sends a correction/feedback to the orchestrator
|
|
@@ -2558,6 +2610,12 @@ interface RunRequest {
|
|
|
2558
2610
|
smartTiering?: AgentSmartTieringConfig;
|
|
2559
2611
|
/** Answer style depth (auto/brief/deep) */
|
|
2560
2612
|
responseMode?: AgentResponseMode;
|
|
2613
|
+
/**
|
|
2614
|
+
* Client-generated id for the optimistic user message this run represents.
|
|
2615
|
+
* Echoed back on `RunResponse.userTurn.metadata.clientId` so the frontend
|
|
2616
|
+
* can reconcile its optimistic turn by id instead of text-matching.
|
|
2617
|
+
*/
|
|
2618
|
+
clientId?: string;
|
|
2561
2619
|
}
|
|
2562
2620
|
/**
|
|
2563
2621
|
* Response for POST /run
|
|
@@ -2576,6 +2634,12 @@ interface RunResponse {
|
|
|
2576
2634
|
status: 'started' | 'queued';
|
|
2577
2635
|
/** Timestamp */
|
|
2578
2636
|
startedAt: string;
|
|
2637
|
+
/**
|
|
2638
|
+
* The persisted user turn this run created, returned synchronously so the
|
|
2639
|
+
* frontend can reconcile its optimistic message immediately by id/clientId
|
|
2640
|
+
* without waiting on a WS round-trip.
|
|
2641
|
+
*/
|
|
2642
|
+
userTurn: Turn;
|
|
2579
2643
|
}
|
|
2580
2644
|
/**
|
|
2581
2645
|
* Request body for POST /run/:runId/correct
|
|
@@ -3652,4 +3716,4 @@ interface SpawnAgentResult {
|
|
|
3652
3716
|
preset: SubAgentPreset;
|
|
3653
3717
|
}
|
|
3654
3718
|
|
|
3655
|
-
export { AGENTS_BASE_PATH, AGENTS_ROUTES, AGENTS_WS_BASE_PATH, AGENTS_WS_CHANNELS, AGENT_ANALYTICS_EVENTS, AGENT_MODES, type AgentAnalyticsEvent, type AgentConfig, type AgentEndEvent, type AgentErrorEvent, type AgentEvent, type AgentEventBase, type AgentEventCallback, type AgentEventEmitter, type AgentEventType, type AgentMemory, type AgentMode, type AgentResponseMode, type AgentSession, type AgentSessionInfo, type AgentSmartTieringConfig, type AgentSpecBudgetConfig, type AgentSpecification, type AgentStartEvent, type AgentTokenBudgetConfig, type AgentsPluginConfig, type AnalyzeResponse, type ApproveSessionPlanRequest, type ApproveSessionPlanResponse, type ArchiveEntry, type ArchiveStoreEvent, type AssumptionRecord, type AsyncTask, type AsyncTaskStatus, type BaseTraceEntry, type ClaimVerificationResult, type ClientMessage, type CompareResponse, type ConflictInfo, type ConflictResolutionConfig, type ConnectionReadyMessage, type ContextSnapshotEvent, type ContextTrimEvent, type ControlAction, type ConversationSnapshotMessage, type CorrectionAckMessage, type CorrectionRecord, type CorrectionRequest, type CorrectionResponse, type CreateSessionRequest, type CreateSessionResponse, DEFAULT_AGENT_TOKEN_BUDGET_CONFIG, DEFAULT_FEATURE_FLAGS, DEFAULT_FILE_HISTORY_CONFIG, DEFAULT_VERIFICATION_THRESHOLDS, type DebugContext, type DecisionPointEvent, type DecisionRecord, type DecompositionDecision, type DecompositionTaskType, type DetailedTraceEntry, type EditContext, type ErrorCapturedEvent, type ErrorMessage, type ErrorStep, type EscalationLevelConfig, type EscalationPolicy, type EvidenceRecord, type EvidenceRequirements, type ExecuteContext, type ExecuteSessionPlanRequest, type ExecuteSessionPlanResponse, type ExecutionMode, type ExecutionPlan, type ExportResponse, type FactAddedEvent, type FactCategory, type FactSheetEntry, type FeatureFlags, type FileChangeSummary, type FileHistoryConfig, type FileHistoryStorageConfig, type FilterResponse, type GenerateSpecRequest, type GenerateSpecResponse, type GetSessionPlanResponse, type GetSessionRequest, type GetSessionResponse, type GetSpecResponse, type HumanEscalationConfig, type IterationDetailEvent, type IterationEndEvent, type IterationResponse, type IterationSnapshot, type IterationStartEvent, type KernelEntryKind, type KernelMemoryState, type KernelState, type LLMCallEvent, type LLMChunkEvent, type LLMDebugEvent, type LLMEndEvent, type LLMStartEvent, type LLMStreamEvent, type LLMTier, type LLMValidationEvent, type ListAgentsResponse, type ListSessionsRequest, type ListSessionsResponse, type LoopResult, type MemoryCategory, type MemoryConfig, type MemoryEntry, type MemoryReadEvent, type MemoryRollup, type MemorySnapshotEvent, type MemorySummary, type MemoryWriteEvent, type MiddlewareConfig, type MiddlewareDecisionEvent, type MiddlewareFailPolicy, type ModeConfig, type ModeContext, type OpenQuestionRecord, type PackedTool, type PendingActionRecord, type PersistentMemory, type Phase, type PingMessage, type PlanContext, type PlanUpdate, type PlanUpdateAction, type ProgressUpdateEvent, type ProjectContext, type PromptContextSelection, type PromptDiffEvent, type QualityMetrics, type ReflectionResult, type ReplayResponse, type RepositoryConventions, type RepositoryFingerprints, type RepositoryModel, type RepositorySignal, type RepositoryStack, type RepositoryTopology, type RepositoryWorkspaceLayout, type ResolvedTool, type ResultProcessor, type RollbackResult, type RoutingHints, type RunCompletedMessage, type RunEvaluation, type RunEvaluationRecommendation, type RunHandoff, type RunRequest, type RunResponse, type RunStatusResponse, type RuntimeTurnRecord, type ServerMessage, type SessionEntry, type SessionProgress, type SessionSnapshot, type SnapshotResponse, type SpawnAgentRequest, type SpawnAgentResult, type SpecChange, type SpecSection, type StatsResponse, type StatusChangeEvent, type Step, type StopConditionResult, StopPriority, type StopRequest, type StopRequestMessage, type StopResponse, type StoppingAnalysisEvent, type SubAgentPreset, type SubAgentStep, type Subtask, type SubtaskEndEvent, type SubtaskStartEvent, type SummarizationLLMCallEvent, type SummarizationResultEvent, type SynthesisCompleteEvent, type SynthesisForcedEvent, type SynthesisForcedTraceEvent, type SynthesisStartEvent, TASK_STATUSES, TODO_PRIORITIES, TODO_STATUSES, type TailResponse, type TaskEndEvent, type TaskPlan, type TaskResult, type TaskSpec, type TaskStartEvent, type TaskStatus, type TextStep, type ThinkingChunkEvent, type ThinkingEndEvent, type ThinkingStartEvent, type ThinkingStep, type TodoItem, type TodoList, type TodoPriority, type TodoStatus, type ToolCall, type ToolCallRecord, type ToolCapability, type ToolConflictPolicy, type ToolDefinition, type ToolEndEvent, type ToolErrorEvent, type ToolEventMetadata, type ToolExecutionEvent, type ToolFilter, type ToolFilterEvent, type ToolPack, type ToolPermissions, type ToolResult, type ToolResultArtifact, type ToolResultRecord, type ToolResultStep, type ToolResultsSummary, type ToolStartEvent, type ToolUseStep, type TraceCommandResponse, type TraceEntry, type TraceErrorCode, TraceErrorCodes, type TraceEventType, type Tracer, type Turn, type
|
|
3719
|
+
export { AGENTS_BASE_PATH, AGENTS_ROUTES, AGENTS_WS_BASE_PATH, AGENTS_WS_CHANNELS, AGENT_ANALYTICS_EVENTS, AGENT_MODES, type AgentAnalyticsEvent, type AgentConfig, type AgentEndEvent, type AgentErrorEvent, type AgentEvent, type AgentEventBase, type AgentEventCallback, type AgentEventEmitter, type AgentEventType, type AgentMemory, type AgentMode, type AgentResponseMode, type AgentSession, type AgentSessionInfo, type AgentSmartTieringConfig, type AgentSpecBudgetConfig, type AgentSpecification, type AgentStartEvent, type AgentTokenBudgetConfig, type AgentsPluginConfig, type AnalyzeResponse, type ApproveSessionPlanRequest, type ApproveSessionPlanResponse, type ArchiveEntry, type ArchiveStoreEvent, type AssumptionRecord, type AsyncTask, type AsyncTaskStatus, type BaseTraceEntry, type ClaimVerificationResult, type ClientMessage, type CompareResponse, type ConflictInfo, type ConflictResolutionConfig, type ConnectionReadyMessage, type ContextSnapshotEvent, type ContextTrimEvent, type ControlAction, type ConversationSnapshotMessage, type CorrectionAckMessage, type CorrectionRecord, type CorrectionRequest, type CorrectionResponse, type CreateSessionRequest, type CreateSessionResponse, DEFAULT_AGENT_TOKEN_BUDGET_CONFIG, DEFAULT_FEATURE_FLAGS, DEFAULT_FILE_HISTORY_CONFIG, DEFAULT_VERIFICATION_THRESHOLDS, type DebugContext, type DecisionPointEvent, type DecisionRecord, type DecompositionDecision, type DecompositionTaskType, type DetailedTraceEntry, type EditContext, type ErrorCapturedEvent, type ErrorMessage, type ErrorStep, type EscalationLevelConfig, type EscalationPolicy, type EvidenceRecord, type EvidenceRequirements, type ExecuteContext, type ExecuteSessionPlanRequest, type ExecuteSessionPlanResponse, type ExecutionMode, type ExecutionPlan, type ExportResponse, type FactAddedEvent, type FactCategory, type FactSheetEntry, type FeatureFlags, type FileChangeSummary, type FileHistoryConfig, type FileHistoryStorageConfig, type FilterResponse, type GenerateSpecRequest, type GenerateSpecResponse, type GetSessionPlanResponse, type GetSessionRequest, type GetSessionResponse, type GetSpecResponse, type HumanEscalationConfig, type IterationDetailEvent, type IterationEndEvent, type IterationResponse, type IterationSnapshot, type IterationStartEvent, type KernelEntryKind, type KernelMemoryState, type KernelState, type LLMCallEvent, type LLMChunkEvent, type LLMDebugEvent, type LLMEndEvent, type LLMStartEvent, type LLMStreamEvent, type LLMTier, type LLMValidationEvent, type ListAgentsResponse, type ListSessionsRequest, type ListSessionsResponse, type LoopResult, type MemoryCategory, type MemoryConfig, type MemoryEntry, type MemoryReadEvent, type MemoryRollup, type MemorySnapshotEvent, type MemorySummary, type MemoryWriteEvent, type MiddlewareConfig, type MiddlewareDecisionEvent, type MiddlewareFailPolicy, type ModeConfig, type ModeContext, type OpenQuestionRecord, type PackedTool, type PendingActionRecord, type PersistentMemory, type Phase, type PingMessage, type PlanContext, type PlanUpdate, type PlanUpdateAction, type ProgressUpdateEvent, type ProjectContext, type PromptContextSelection, type PromptDiffEvent, type QualityMetrics, type ReflectionResult, type ReplayResponse, type RepositoryConventions, type RepositoryFingerprints, type RepositoryModel, type RepositorySignal, type RepositoryStack, type RepositoryTopology, type RepositoryWorkspaceLayout, type ResolvedTool, type ResultProcessor, type RollbackResult, type RoutingHints, type RunCompletedMessage, type RunEvaluation, type RunEvaluationRecommendation, type RunHandoff, type RunRequest, type RunResponse, type RunStatusResponse, type RuntimeTurnRecord, type ServerMessage, type SessionEntry, type SessionProgress, type SessionSnapshot, type SnapshotResponse, type SpawnAgentRequest, type SpawnAgentResult, type SpecChange, type SpecSection, type StatsResponse, type StatusChangeEvent, type Step, type StopConditionResult, StopPriority, type StopRequest, type StopRequestMessage, type StopResponse, type StoppingAnalysisEvent, type SubAgentPreset, type SubAgentStep, type Subtask, type SubtaskEndEvent, type SubtaskStartEvent, type SummarizationLLMCallEvent, type SummarizationResultEvent, type SynthesisCompleteEvent, type SynthesisForcedEvent, type SynthesisForcedTraceEvent, type SynthesisStartEvent, TASK_STATUSES, TODO_PRIORITIES, TODO_STATUSES, type TailResponse, type TaskEndEvent, type TaskPlan, type TaskResult, type TaskSpec, type TaskStartEvent, type TaskStatus, type TextStep, type ThinkingChunkEvent, type ThinkingEndEvent, type ThinkingStartEvent, type ThinkingStep, type TodoItem, type TodoList, type TodoPriority, type TodoStatus, type ToolCall, type ToolCallRecord, type ToolCapability, type ToolConflictPolicy, type ToolDefinition, type ToolEndEvent, type ToolErrorEvent, type ToolEventMetadata, type ToolExecutionEvent, type ToolFilter, type ToolFilterEvent, type ToolPack, type ToolPermissions, type ToolResult, type ToolResultArtifact, type ToolResultRecord, type ToolResultStep, type ToolResultsSummary, type ToolStartEvent, type ToolUseStep, type TraceCommandResponse, type TraceEntry, type TraceErrorCode, TraceErrorCodes, type TraceEventType, type Tracer, type Turn, type TurnDelta, type TurnDeltaMessage, type TurnInterpretation, type TurnKind, type TurnStep, type TwoTierMemoryConfig, type UserCorrectionMessage, type VerificationCompleteEvent, type VerificationEventData, type VerificationInput, type VerificationOutput, type VerificationResult, type VerificationStartEvent, type VerificationThresholds, type VerificationWarning, type VerificationWarningCode, buildRestRoute, buildWsChannel, schemas };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas.ts","../src/routes.ts","../src/analytics.ts","../src/verification.ts","../src/control.ts","../src/config-types.ts"],"names":["StopPriority"],"mappings":";AAKO,IAAM,UAAU;;;ACEhB,IAAM,gBAAA,GAAmB;AAKzB,IAAM,mBAAA,GAAsB;AAK5B,IAAM,aAAA,GAAgB;AAAA;AAAA,EAE3B,IAAA,EAAM,EAAA;AAAA;AAAA,EAGN,GAAA,EAAK,MAAA;AAAA;AAAA,EAGL,UAAA,EAAY,aAAA;AAAA;AAAA,EAGZ,OAAA,EAAS,qBAAA;AAAA;AAAA,EAGT,IAAA,EAAM,kBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAON,aAAA,EAAe,WAAA;AAAA;AAAA,EAGf,WAAA,EAAa,sBAAA;AAAA;AAAA,EAGb,cAAA,EAAgB,WAAA;AAAA;AAAA,EAGhB,aAAA,EAAe,4BAAA;AAAA;AAAA,EAGf,eAAA,EAAiB,8BAAA;AAAA;AAAA,EAGjB,mBAAA,EAAqB,6CAAA;AAAA;AAAA,EAGrB,gBAAA,EAAkB,+BAAA;AAAA;AAAA,EAGlB,eAA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,IACb,aAAA,EAAe,IAAA;AAAA,IACf,qBAAA,EAAuB,GAAA;AAAA,IACvB,gBAAA,EAAkB;AAAA;AAEtB","file":"index.js","sourcesContent":["/**\n * Zod schemas for validation (future use)\n */\n\n// Placeholder for Zod schemas when needed\nexport const schemas = {};\n","/**\n * REST API & WebSocket route constants for agents plugin\n */\n\n/**\n * Base path for agents REST API routes\n */\nexport const AGENTS_BASE_PATH = '/v1/plugins/agents' as const;\n\n/**\n * Base path for agents WebSocket channels\n */\nexport const AGENTS_WS_BASE_PATH = '/v1/ws/plugins/agents' as const;\n\n/**\n * REST API route paths (relative to basePath)\n */\nexport const AGENTS_ROUTES = {\n /** GET - List all available agents */\n LIST: '',\n\n /** POST /run - Start a new agent run */\n RUN: '/run',\n\n /** GET /run/:runId - Get run status */\n RUN_STATUS: '/run/:runId',\n\n /** POST /run/:runId/correct - Send user correction to running agent */\n CORRECT: '/run/:runId/correct',\n\n /** POST /run/:runId/stop - Stop running agent */\n STOP: '/run/:runId/stop',\n\n // ═══════════════════════════════════════════════════════════════════════\n // Session Management Routes\n // ═══════════════════════════════════════════════════════════════════════\n\n /** GET /sessions - List all sessions */\n SESSIONS_LIST: '/sessions',\n\n /** GET /sessions/:sessionId - Get session details */\n SESSION_GET: '/sessions/:sessionId',\n\n /** POST /sessions - Create new session */\n SESSION_CREATE: '/sessions',\n\n /** GET /sessions/:sessionId/turns - Get session turns (turn-based UI) */\n SESSION_TURNS: '/sessions/:sessionId/turns',\n\n /** GET /sessions/:sessionId/changes - List file changes for session */\n SESSION_CHANGES: '/sessions/:sessionId/changes',\n\n /** GET /sessions/:sessionId/changes/:changeId/diff - Get unified diff for a specific file change */\n SESSION_CHANGE_DIFF: '/sessions/:sessionId/changes/:changeId/diff',\n\n /** POST /sessions/:sessionId/rollback - Rollback file changes */\n SESSION_ROLLBACK: '/sessions/:sessionId/rollback',\n\n /** POST /sessions/:sessionId/approve - Approve file changes */\n SESSION_APPROVE: '/sessions/:sessionId/approve',\n\n /** GET /sessions/:sessionId/plan - Get current session plan */\n SESSION_PLAN_GET: '/sessions/:sessionId/plan',\n\n /** POST /sessions/:sessionId/plan/approve - Approve current session plan */\n SESSION_PLAN_APPROVE: '/sessions/:sessionId/plan/approve',\n\n /** POST /sessions/:sessionId/plan/execute - Execute approved session plan */\n SESSION_PLAN_EXECUTE: '/sessions/:sessionId/plan/execute',\n\n /** POST /sessions/:sessionId/plan/spec - Generate detailed spec from approved plan */\n SESSION_PLAN_SPEC: '/sessions/:sessionId/plan/spec',\n\n /** GET /sessions/:sessionId/plan/spec - Get generated spec */\n SESSION_PLAN_SPEC_GET: '/sessions/:sessionId/spec',\n} as const;\n\n/**\n * WebSocket channel paths (relative to wsBasePath)\n */\nexport const AGENTS_WS_CHANNELS = {\n /** WS /session/:sessionId - Persistent session stream (all runs in session) */\n SESSION_STREAM: '/session/:sessionId',\n} as const;\n\n/**\n * Build full REST route path\n */\nexport function buildRestRoute(route: keyof typeof AGENTS_ROUTES, params?: Record<string, string>): string {\n let path = `${AGENTS_BASE_PATH}${AGENTS_ROUTES[route]}`;\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, value);\n }\n }\n return path;\n}\n\n/**\n * Build full WebSocket channel path\n */\nexport function buildWsChannel(channel: keyof typeof AGENTS_WS_CHANNELS, params?: Record<string, string>): string {\n let path = `${AGENTS_WS_BASE_PATH}${AGENTS_WS_CHANNELS[channel]}`;\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, value);\n }\n }\n return path;\n}\n","/**\n * Analytics event constants for agent system\n */\n\n/**\n * Analytics event IDs\n */\nexport const AGENT_ANALYTICS_EVENTS = {\n // Run lifecycle\n RUN_STARTED: 'agent.run.started',\n RUN_COMPLETED: 'agent.run.completed',\n RUN_FAILED: 'agent.run.failed',\n RUN_STOPPED: 'agent.run.stopped',\n\n // Corrections\n CORRECTION_SENT: 'agent.correction.sent',\n CORRECTION_APPLIED: 'agent.correction.applied',\n CORRECTION_REJECTED: 'agent.correction.rejected',\n\n // WebSocket\n WS_CONNECTED: 'agent.ws.connected',\n WS_DISCONNECTED: 'agent.ws.disconnected',\n\n // Agent execution\n AGENT_SPAWNED: 'agent.spawned',\n AGENT_COMPLETED: 'agent.completed',\n TOOL_CALLED: 'agent.tool.called',\n TIER_ESCALATED: 'agent.tier.escalated',\n} as const;\n\nexport type AgentAnalyticsEvent = typeof AGENT_ANALYTICS_EVENTS[keyof typeof AGENT_ANALYTICS_EVENTS];\n","/**\n * Verification types for agent responses\n *\n * Cross-tier verification system to detect hallucinations\n * and assess response quality.\n */\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Results\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Warning codes for verification issues\n */\nexport type VerificationWarningCode =\n | 'UNVERIFIED_FILE'\n | 'UNVERIFIED_PACKAGE'\n | 'UNVERIFIED_CLASS'\n | 'UNVERIFIED_FUNCTION'\n | 'LOW_CONFIDENCE'\n | 'INCOMPLETE_ANSWER'\n | 'CONTRADICTION'\n | 'VERIFICATION_FAILED';\n\n/**\n * Warning about potential issues in agent response\n */\nexport interface VerificationWarning {\n code: VerificationWarningCode;\n message: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Result of cross-tier verification\n */\nexport interface VerificationResult {\n /** Entities mentioned in answer (files, packages, classes) */\n mentions: string[];\n /** Mentions that were verified against tool results */\n verifiedMentions: string[];\n /** Mentions that could NOT be verified (potential hallucinations) */\n unverifiedMentions: string[];\n /** Overall confidence in answer correctness (0-1) */\n confidence: number;\n /** How complete is the answer (0-1) */\n completeness: number;\n /** Aspects of the question that weren't addressed */\n gaps: string[];\n /** Warnings about potential issues */\n warnings: VerificationWarning[];\n /** Brief reasoning for the assessment */\n reasoning: string;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Quality Metrics\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Quality metrics for agent response\n */\nexport interface QualityMetrics {\n /** Overall confidence in answer (0-1) */\n confidence: number;\n /** How complete relative to question (0-1) */\n completeness: number;\n /** Unanswered aspects */\n gaps: string[];\n /** Verifier's reasoning */\n reasoning: string;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Input/Output (for cross-tier verifier)\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Input for cross-tier verification\n */\nexport interface VerificationInput {\n /** Original task/question */\n task: string;\n /** Agent's final answer */\n answer: string;\n /** Summary of tool results (files read, commands run, etc.) */\n toolResultsSummary: string;\n /** List of files that were actually read */\n filesRead?: string[];\n /** Executor tier (to determine verifier tier) */\n executorTier?: 'small' | 'medium' | 'large';\n}\n\n/**\n * Raw output from verifier LLM (via tool call)\n */\nexport interface VerificationOutput {\n /** Entities mentioned in answer (files, packages, classes) */\n mentions: string[];\n /** Which mentions appear in tool results */\n verified: string[];\n /** Which mentions could NOT be verified */\n unverified: string[];\n /** Overall confidence in answer (0-1) */\n confidence: number;\n /** How complete is the answer (0-1) */\n completeness: number;\n /** What aspects of the question weren't addressed */\n gaps: string[];\n /** Potential issues found */\n warnings: string[];\n /** Brief reasoning for the assessment */\n reasoning: string;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Tool Results Summary (for verifier context)\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Record of a single tool call and its result\n */\nexport interface ToolResultRecord {\n /** Tool name (e.g., 'fs:read', 'mind:rag-query') */\n tool: string;\n /** Input parameters */\n input: Record<string, unknown>;\n /** Tool output */\n output: string;\n /** When the tool was called */\n timestamp?: string;\n}\n\n/**\n * Summary of tool results for verifier\n */\nexport interface ToolResultsSummary {\n /** Human-readable summary for verifier */\n text: string;\n /** Files that were read */\n filesRead: string[];\n /** Files that were created/modified */\n filesWritten: string[];\n /** Commands that were executed */\n commandsRun: string[];\n /** Searches that were performed */\n searchQueries: string[];\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Thresholds\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Thresholds for verification-based decisions\n */\nexport interface VerificationThresholds {\n /** Max unverified mentions before retry */\n maxUnverifiedMentions: number;\n /** Min confidence before reformulation */\n minConfidence: number;\n /** Min confidence to mark as uncertain */\n uncertainConfidence: number;\n /** Min completeness before follow-up tasks */\n minCompleteness: number;\n /** Max retries per subtask */\n maxRetries: number;\n}\n\n/**\n * Default verification thresholds\n */\nexport const DEFAULT_VERIFICATION_THRESHOLDS: VerificationThresholds = {\n maxUnverifiedMentions: 3,\n minConfidence: 0.4,\n uncertainConfidence: 0.6,\n minCompleteness: 0.6,\n maxRetries: 2,\n};\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Events\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Verification event data (for agent events)\n */\nexport interface VerificationEventData {\n /** Verification result */\n verification: VerificationResult;\n /** Which subtask/task was verified */\n taskId?: string;\n /** Executor tier used */\n executorTier?: 'small' | 'medium' | 'large';\n /** Verifier tier used */\n verifierTier?: 'small' | 'medium' | 'large';\n /** Duration of verification in ms */\n durationMs?: number;\n}\n","/**\n * Control flow types for Agent v2 middleware pipeline and execution loop.\n *\n * ControlAction is the unified return type for middleware hooks and execution decisions.\n * StopPriority defines deterministic ordering when multiple stop conditions fire simultaneously.\n */\n\n// ═══════════════════════════════════════════════════════════════════════\n// Control Actions\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Unified control action for middleware pipeline and execution loop.\n *\n * - 'continue' — proceed with current iteration\n * - 'stop' — stop the execution loop gracefully\n * - 'escalate' — request tier escalation (small → medium → large)\n * - 'handoff' — hand off to a different agent (sub-agent orchestration)\n */\nexport type ControlAction = 'continue' | 'stop' | 'escalate' | 'handoff';\n\n// ═══════════════════════════════════════════════════════════════════════\n// Stop Conditions\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Stop condition priorities (lower number = higher priority).\n *\n * When multiple conditions fire in the same iteration, the evaluator checks ALL\n * and returns the one with the highest priority (lowest numeric value).\n * Tie-break is impossible because enum values are unique.\n *\n * Example collision: report + hard_budget → REPORT_COMPLETE (1 < 2).\n */\nexport enum StopPriority {\n /** User cancelled via AbortController */\n ABORT_SIGNAL = 0,\n /** Agent called the `report` tool — task is done */\n REPORT_COMPLETE = 1,\n /** Token hard limit reached */\n HARD_BUDGET = 2,\n /** Maximum iterations reached */\n MAX_ITERATIONS = 3,\n /** Same tool calls repeated 3+ times in a row */\n LOOP_DETECTED = 4,\n /** Agent produced no tool calls — implicit completion */\n NO_TOOL_CALLS = 5,\n}\n\n/**\n * A fired stop condition with its priority and metadata.\n */\nexport interface StopConditionResult {\n /** Which condition fired */\n priority: StopPriority;\n /** Human-readable reason */\n reason: string;\n /** Machine-readable code for analytics */\n reasonCode: string;\n /** Additional metadata (e.g., report answer, loop count) */\n metadata?: Record<string, unknown>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Middleware Configuration\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Failure policy for a middleware.\n *\n * - 'fail-open' — if the middleware throws, log and continue the pipeline\n * - 'fail-closed' — if the middleware throws, stop the entire execution\n */\nexport type MiddlewareFailPolicy = 'fail-open' | 'fail-closed';\n\n/**\n * Per-middleware configuration for pipeline behavior.\n */\nexport interface MiddlewareConfig {\n /** What happens when this middleware throws (default: 'fail-open') */\n failPolicy: MiddlewareFailPolicy;\n /** Maximum time for any single hook invocation in ms (default: 5000) */\n timeoutMs?: number;\n /** Whether the middleware is safe to retry on failure */\n idempotent?: boolean;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Feature Flags\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Feature flags controlling which experimental middlewares are active.\n * All default to false unless explicitly enabled.\n */\nexport interface FeatureFlags {\n /** Two-tier memory: FactSheet (hot) + ArchiveMemory (cold) */\n twoTierMemory: boolean;\n /** TODO sync coordinator — nudges agent toward todo discipline */\n todoSync: boolean;\n /** Search signal tracker — discovery vs action classification */\n searchSignal: boolean;\n /** Reflection engine — adaptive LLM-driven behavior */\n reflection: boolean;\n /** Task classifier — intent inference (action/discovery/analysis) */\n taskClassifier: boolean;\n /** Smart summarizer — progressive conversation compression */\n smartSummarizer: boolean;\n /** Tier escalation — auto-escalate small → medium → large */\n tierEscalation: boolean;\n}\n\n/**\n * Default feature flags — conservative, all experimental features off.\n */\nexport const DEFAULT_FEATURE_FLAGS: FeatureFlags = {\n twoTierMemory: false,\n todoSync: false,\n searchSignal: false,\n reflection: false,\n taskClassifier: false,\n smartSummarizer: false,\n tierEscalation: false,\n};\n\n// ═══════════════════════════════════════════════════════════════════════\n// Execution Loop Result\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Result of a single ExecutionLoop run.\n * Uses discriminated union on `outcome` instead of thrown exceptions.\n */\nexport type LoopResult<T = unknown> =\n | { outcome: 'complete'; result: T }\n | { outcome: 'escalate'; reason: string }\n | { outcome: 'handoff'; targetAgentId: string; context: Record<string, unknown> };\n","/**\n * Agent configuration types for kb.config.json\n */\nimport type { AgentSmartTieringConfig, AgentTokenBudgetConfig } from './types.js';\n\n/**\n * Storage configuration for file history snapshots\n */\nexport interface FileHistoryStorageConfig {\n /** Base path for session storage (default: .kb/agents/sessions) */\n basePath?: string;\n /** Maximum number of sessions to keep (default: 30) */\n maxSessions?: number;\n /** Maximum age of sessions in days (default: 30) */\n maxAgeDays?: number;\n /** Maximum total storage size in MB (default: 500) */\n maxTotalSizeMb?: number;\n /** Enable compression for old snapshots (default: true) */\n compressOldSnapshots?: boolean;\n}\n\n/**\n * Escalation level configuration\n */\nexport interface EscalationLevelConfig {\n /** Enable this escalation level */\n enabled: boolean;\n /** Confidence threshold for this level (0-1) */\n confidenceThreshold: number;\n /** Maximum duration in milliseconds */\n maxDurationMs: number;\n}\n\n/**\n * Human escalation configuration\n */\nexport interface HumanEscalationConfig {\n /** Enable human escalation */\n enabled: boolean;\n /** Auto-escalate to human after this many milliseconds */\n autoEscalateAfterMs?: number;\n}\n\n/**\n * Escalation policy for adaptive conflict resolution\n */\nexport interface EscalationPolicy {\n /** Level 1: Auto-resolve (disjoint changes, 60%, <10ms) */\n level1AutoResolve: EscalationLevelConfig;\n /** Level 2: LLM-merge (overlapping changes, 30%, 2-5s) */\n level2LLMMerge: EscalationLevelConfig;\n /** Level 3: Agent coordination (conflicting intent, 8%, 10-30s) */\n level3AgentCoordination: EscalationLevelConfig;\n /** Level 4: Human escalation (unresolvable, 2%) */\n level4HumanEscalation: HumanEscalationConfig;\n}\n\n/**\n * Conflict resolution configuration\n */\nexport interface ConflictResolutionConfig {\n /** Default strategy: 'adaptive' | 'skip-conflicts' | 'force-overwrite' */\n defaultStrategy: 'adaptive' | 'skip-conflicts' | 'force-overwrite';\n /** Escalation policy for adaptive resolution */\n escalationPolicy: EscalationPolicy;\n}\n\n/**\n * File history configuration\n */\nexport interface FileHistoryConfig {\n /** Enable file history tracking */\n enabled: boolean;\n /** Storage configuration */\n storage: FileHistoryStorageConfig;\n /** Conflict resolution configuration */\n conflictResolution: ConflictResolutionConfig;\n}\n\n/**\n * Agents plugin configuration\n */\nexport interface AgentsPluginConfig {\n /** Enable agents plugin */\n enabled: boolean;\n /** Adaptive helper-node elevation policy (small -> medium on risk) */\n smartTiering?: AgentSmartTieringConfig;\n /** Token budget policy for long-running tasks */\n tokenBudget?: AgentTokenBudgetConfig;\n /** File history tracking configuration */\n fileHistory: FileHistoryConfig;\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_FILE_HISTORY_CONFIG: Required<FileHistoryConfig> = {\n enabled: true,\n storage: {\n basePath: '.kb/agents/sessions',\n maxSessions: 30,\n maxAgeDays: 30,\n maxTotalSizeMb: 500,\n compressOldSnapshots: true,\n },\n conflictResolution: {\n defaultStrategy: 'adaptive',\n escalationPolicy: {\n level1AutoResolve: {\n enabled: true,\n confidenceThreshold: 1.0,\n maxDurationMs: 10,\n },\n level2LLMMerge: {\n enabled: true,\n confidenceThreshold: 0.8,\n maxDurationMs: 5000,\n },\n level3AgentCoordination: {\n enabled: true,\n confidenceThreshold: 0.6,\n maxDurationMs: 30000,\n },\n level4HumanEscalation: {\n enabled: true,\n autoEscalateAfterMs: 60000,\n },\n },\n },\n};\n\nexport const DEFAULT_AGENT_TOKEN_BUDGET_CONFIG: Required<\n Omit<AgentTokenBudgetConfig, 'maxTokens'>\n> = {\n enabled: false,\n softLimitRatio: 0.7,\n hardLimitRatio: 1.0,\n hardStop: false,\n forceSynthesisOnHardLimit: true,\n restrictBroadExplorationAtSoftLimit: true,\n allowIterationBudgetExtension: true,\n spec: {\n enabled: true,\n multiplier: 4.0,\n floorTokens: 100_000,\n ceilingTokens: 250_000,\n synthesisReserveRatio: 0.2,\n partialOnFailure: true,\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../home/runner/work/kb-labs/kb-labs/plugins/agents/contracts/src/schemas.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/contracts/src/routes.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/contracts/src/analytics.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/contracts/src/verification.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/contracts/src/control.ts","../../home/runner/work/kb-labs/kb-labs/plugins/agents/contracts/src/config-types.ts"],"names":["StopPriority"],"mappings":";AAKO,IAAM,UAAU;;;ACEhB,IAAM,gBAAA,GAAmB;AAKzB,IAAM,mBAAA,GAAsB;AAK5B,IAAM,aAAA,GAAgB;AAAA;AAAA,EAE3B,IAAA,EAAM,EAAA;AAAA;AAAA,EAGN,GAAA,EAAK,MAAA;AAAA;AAAA,EAGL,UAAA,EAAY,aAAA;AAAA;AAAA,EAGZ,OAAA,EAAS,qBAAA;AAAA;AAAA,EAGT,IAAA,EAAM,kBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAON,aAAA,EAAe,WAAA;AAAA;AAAA,EAGf,WAAA,EAAa,sBAAA;AAAA;AAAA,EAGb,cAAA,EAAgB,WAAA;AAAA;AAAA,EAGhB,aAAA,EAAe,4BAAA;AAAA;AAAA,EAGf,eAAA,EAAiB,8BAAA;AAAA;AA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M;AAAA,IACJ,OAAA,EAAS,IAAA;AAAA,IACT,UAAA,EAAY,CAAA;AAAA,IACZ,WAAA,EAAa,GAAA;AAAA,IACb,aAAA,EAAe,IAAA;AAAA,IACf,qBAAA,EAAuB,GAAA;AAAA,IACvB,gBAAA,EAAkB;AAAA;AAEtB","file":"index.js","sourcesContent":["/**\n * Zod schemas for validation (future use)\n */\n\n// Placeholder for Zod schemas when needed\nexport const schemas = {};\n","/**\n * REST API & WebSocket route constants for agents plugin\n */\n\n/**\n * Base path for agents REST API routes\n */\nexport const AGENTS_BASE_PATH = '/v1/plugins/agents' as const;\n\n/**\n * Base path for agents WebSocket channels\n */\nexport const AGENTS_WS_BASE_PATH = '/v1/ws/plugins/agents' as const;\n\n/**\n * REST API route paths (relative to basePath)\n */\nexport const AGENTS_ROUTES = {\n /** GET - List all available agents */\n LIST: '',\n\n /** POST /run - Start a new agent run */\n RUN: '/run',\n\n /** GET /run/:runId - Get run status */\n RUN_STATUS: '/run/:runId',\n\n /** POST /run/:runId/correct - Send user correction to running agent */\n CORRECT: '/run/:runId/correct',\n\n /** POST /run/:runId/stop - Stop running agent */\n STOP: '/run/:runId/stop',\n\n // ═══════════════════════════════════════════════════════════════════════\n // Session Management Routes\n // ═══════════════════════════════════════════════════════════════════════\n\n /** GET /sessions - List all sessions */\n SESSIONS_LIST: '/sessions',\n\n /** GET /sessions/:sessionId - Get session details */\n SESSION_GET: '/sessions/:sessionId',\n\n /** POST /sessions - Create new session */\n SESSION_CREATE: '/sessions',\n\n /** GET /sessions/:sessionId/turns - Get session turns (turn-based UI) */\n SESSION_TURNS: '/sessions/:sessionId/turns',\n\n /** GET /sessions/:sessionId/changes - List file changes for session */\n SESSION_CHANGES: '/sessions/:sessionId/changes',\n\n /** GET /sessions/:sessionId/changes/:changeId/diff - Get unified diff for a specific file change */\n SESSION_CHANGE_DIFF: '/sessions/:sessionId/changes/:changeId/diff',\n\n /** POST /sessions/:sessionId/rollback - Rollback file changes */\n SESSION_ROLLBACK: '/sessions/:sessionId/rollback',\n\n /** POST /sessions/:sessionId/approve - Approve file changes */\n SESSION_APPROVE: '/sessions/:sessionId/approve',\n\n /** GET /sessions/:sessionId/plan - Get current session plan */\n SESSION_PLAN_GET: '/sessions/:sessionId/plan',\n\n /** POST /sessions/:sessionId/plan/approve - Approve current session plan */\n SESSION_PLAN_APPROVE: '/sessions/:sessionId/plan/approve',\n\n /** POST /sessions/:sessionId/plan/execute - Execute approved session plan */\n SESSION_PLAN_EXECUTE: '/sessions/:sessionId/plan/execute',\n\n /** POST /sessions/:sessionId/plan/spec - Generate detailed spec from approved plan */\n SESSION_PLAN_SPEC: '/sessions/:sessionId/plan/spec',\n\n /** GET /sessions/:sessionId/plan/spec - Get generated spec */\n SESSION_PLAN_SPEC_GET: '/sessions/:sessionId/spec',\n} as const;\n\n/**\n * WebSocket channel paths (relative to wsBasePath)\n */\nexport const AGENTS_WS_CHANNELS = {\n /** WS /session/:sessionId - Persistent session stream (all runs in session) */\n SESSION_STREAM: '/session/:sessionId',\n} as const;\n\n/**\n * Build full REST route path\n */\nexport function buildRestRoute(route: keyof typeof AGENTS_ROUTES, params?: Record<string, string>): string {\n let path = `${AGENTS_BASE_PATH}${AGENTS_ROUTES[route]}`;\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, value);\n }\n }\n return path;\n}\n\n/**\n * Build full WebSocket channel path\n */\nexport function buildWsChannel(channel: keyof typeof AGENTS_WS_CHANNELS, params?: Record<string, string>): string {\n let path = `${AGENTS_WS_BASE_PATH}${AGENTS_WS_CHANNELS[channel]}`;\n if (params) {\n for (const [key, value] of Object.entries(params)) {\n path = path.replace(`:${key}`, value);\n }\n }\n return path;\n}\n","/**\n * Analytics event constants for agent system\n */\n\n/**\n * Analytics event IDs\n */\nexport const AGENT_ANALYTICS_EVENTS = {\n // Run lifecycle\n RUN_STARTED: 'agent.run.started',\n RUN_COMPLETED: 'agent.run.completed',\n RUN_FAILED: 'agent.run.failed',\n RUN_STOPPED: 'agent.run.stopped',\n\n // Corrections\n CORRECTION_SENT: 'agent.correction.sent',\n CORRECTION_APPLIED: 'agent.correction.applied',\n CORRECTION_REJECTED: 'agent.correction.rejected',\n\n // WebSocket\n WS_CONNECTED: 'agent.ws.connected',\n WS_DISCONNECTED: 'agent.ws.disconnected',\n\n // Agent execution\n AGENT_SPAWNED: 'agent.spawned',\n AGENT_COMPLETED: 'agent.completed',\n TOOL_CALLED: 'agent.tool.called',\n TIER_ESCALATED: 'agent.tier.escalated',\n} as const;\n\nexport type AgentAnalyticsEvent = typeof AGENT_ANALYTICS_EVENTS[keyof typeof AGENT_ANALYTICS_EVENTS];\n","/**\n * Verification types for agent responses\n *\n * Cross-tier verification system to detect hallucinations\n * and assess response quality.\n */\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Results\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Warning codes for verification issues\n */\nexport type VerificationWarningCode =\n | 'UNVERIFIED_FILE'\n | 'UNVERIFIED_PACKAGE'\n | 'UNVERIFIED_CLASS'\n | 'UNVERIFIED_FUNCTION'\n | 'LOW_CONFIDENCE'\n | 'INCOMPLETE_ANSWER'\n | 'CONTRADICTION'\n | 'VERIFICATION_FAILED';\n\n/**\n * Warning about potential issues in agent response\n */\nexport interface VerificationWarning {\n code: VerificationWarningCode;\n message: string;\n details?: Record<string, unknown>;\n}\n\n/**\n * Result of cross-tier verification\n */\nexport interface VerificationResult {\n /** Entities mentioned in answer (files, packages, classes) */\n mentions: string[];\n /** Mentions that were verified against tool results */\n verifiedMentions: string[];\n /** Mentions that could NOT be verified (potential hallucinations) */\n unverifiedMentions: string[];\n /** Overall confidence in answer correctness (0-1) */\n confidence: number;\n /** How complete is the answer (0-1) */\n completeness: number;\n /** Aspects of the question that weren't addressed */\n gaps: string[];\n /** Warnings about potential issues */\n warnings: VerificationWarning[];\n /** Brief reasoning for the assessment */\n reasoning: string;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Quality Metrics\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Quality metrics for agent response\n */\nexport interface QualityMetrics {\n /** Overall confidence in answer (0-1) */\n confidence: number;\n /** How complete relative to question (0-1) */\n completeness: number;\n /** Unanswered aspects */\n gaps: string[];\n /** Verifier's reasoning */\n reasoning: string;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Input/Output (for cross-tier verifier)\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Input for cross-tier verification\n */\nexport interface VerificationInput {\n /** Original task/question */\n task: string;\n /** Agent's final answer */\n answer: string;\n /** Summary of tool results (files read, commands run, etc.) */\n toolResultsSummary: string;\n /** List of files that were actually read */\n filesRead?: string[];\n /** Executor tier (to determine verifier tier) */\n executorTier?: 'small' | 'medium' | 'large';\n}\n\n/**\n * Raw output from verifier LLM (via tool call)\n */\nexport interface VerificationOutput {\n /** Entities mentioned in answer (files, packages, classes) */\n mentions: string[];\n /** Which mentions appear in tool results */\n verified: string[];\n /** Which mentions could NOT be verified */\n unverified: string[];\n /** Overall confidence in answer (0-1) */\n confidence: number;\n /** How complete is the answer (0-1) */\n completeness: number;\n /** What aspects of the question weren't addressed */\n gaps: string[];\n /** Potential issues found */\n warnings: string[];\n /** Brief reasoning for the assessment */\n reasoning: string;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Tool Results Summary (for verifier context)\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Record of a single tool call and its result\n */\nexport interface ToolResultRecord {\n /** Tool name (e.g., 'fs:read', 'mind:rag-query') */\n tool: string;\n /** Input parameters */\n input: Record<string, unknown>;\n /** Tool output */\n output: string;\n /** When the tool was called */\n timestamp?: string;\n}\n\n/**\n * Summary of tool results for verifier\n */\nexport interface ToolResultsSummary {\n /** Human-readable summary for verifier */\n text: string;\n /** Files that were read */\n filesRead: string[];\n /** Files that were created/modified */\n filesWritten: string[];\n /** Commands that were executed */\n commandsRun: string[];\n /** Searches that were performed */\n searchQueries: string[];\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Thresholds\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Thresholds for verification-based decisions\n */\nexport interface VerificationThresholds {\n /** Max unverified mentions before retry */\n maxUnverifiedMentions: number;\n /** Min confidence before reformulation */\n minConfidence: number;\n /** Min confidence to mark as uncertain */\n uncertainConfidence: number;\n /** Min completeness before follow-up tasks */\n minCompleteness: number;\n /** Max retries per subtask */\n maxRetries: number;\n}\n\n/**\n * Default verification thresholds\n */\nexport const DEFAULT_VERIFICATION_THRESHOLDS: VerificationThresholds = {\n maxUnverifiedMentions: 3,\n minConfidence: 0.4,\n uncertainConfidence: 0.6,\n minCompleteness: 0.6,\n maxRetries: 2,\n};\n\n// ═══════════════════════════════════════════════════════════════════════\n// Verification Events\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Verification event data (for agent events)\n */\nexport interface VerificationEventData {\n /** Verification result */\n verification: VerificationResult;\n /** Which subtask/task was verified */\n taskId?: string;\n /** Executor tier used */\n executorTier?: 'small' | 'medium' | 'large';\n /** Verifier tier used */\n verifierTier?: 'small' | 'medium' | 'large';\n /** Duration of verification in ms */\n durationMs?: number;\n}\n","/**\n * Control flow types for Agent v2 middleware pipeline and execution loop.\n *\n * ControlAction is the unified return type for middleware hooks and execution decisions.\n * StopPriority defines deterministic ordering when multiple stop conditions fire simultaneously.\n */\n\n// ═══════════════════════════════════════════════════════════════════════\n// Control Actions\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Unified control action for middleware pipeline and execution loop.\n *\n * - 'continue' — proceed with current iteration\n * - 'stop' — stop the execution loop gracefully\n * - 'escalate' — request tier escalation (small → medium → large)\n * - 'handoff' — hand off to a different agent (sub-agent orchestration)\n */\nexport type ControlAction = 'continue' | 'stop' | 'escalate' | 'handoff';\n\n// ═══════════════════════════════════════════════════════════════════════\n// Stop Conditions\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Stop condition priorities (lower number = higher priority).\n *\n * When multiple conditions fire in the same iteration, the evaluator checks ALL\n * and returns the one with the highest priority (lowest numeric value).\n * Tie-break is impossible because enum values are unique.\n *\n * Example collision: report + hard_budget → REPORT_COMPLETE (1 < 2).\n */\nexport enum StopPriority {\n /** User cancelled via AbortController */\n ABORT_SIGNAL = 0,\n /** Agent called the `report` tool — task is done */\n REPORT_COMPLETE = 1,\n /** Token hard limit reached */\n HARD_BUDGET = 2,\n /** Maximum iterations reached */\n MAX_ITERATIONS = 3,\n /** Same tool calls repeated 3+ times in a row */\n LOOP_DETECTED = 4,\n /** Agent produced no tool calls — implicit completion */\n NO_TOOL_CALLS = 5,\n}\n\n/**\n * A fired stop condition with its priority and metadata.\n */\nexport interface StopConditionResult {\n /** Which condition fired */\n priority: StopPriority;\n /** Human-readable reason */\n reason: string;\n /** Machine-readable code for analytics */\n reasonCode: string;\n /** Additional metadata (e.g., report answer, loop count) */\n metadata?: Record<string, unknown>;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Middleware Configuration\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Failure policy for a middleware.\n *\n * - 'fail-open' — if the middleware throws, log and continue the pipeline\n * - 'fail-closed' — if the middleware throws, stop the entire execution\n */\nexport type MiddlewareFailPolicy = 'fail-open' | 'fail-closed';\n\n/**\n * Per-middleware configuration for pipeline behavior.\n */\nexport interface MiddlewareConfig {\n /** What happens when this middleware throws (default: 'fail-open') */\n failPolicy: MiddlewareFailPolicy;\n /** Maximum time for any single hook invocation in ms (default: 5000) */\n timeoutMs?: number;\n /** Whether the middleware is safe to retry on failure */\n idempotent?: boolean;\n}\n\n// ═══════════════════════════════════════════════════════════════════════\n// Feature Flags\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Feature flags controlling which experimental middlewares are active.\n * All default to false unless explicitly enabled.\n */\nexport interface FeatureFlags {\n /** Two-tier memory: FactSheet (hot) + ArchiveMemory (cold) */\n twoTierMemory: boolean;\n /** TODO sync coordinator — nudges agent toward todo discipline */\n todoSync: boolean;\n /** Search signal tracker — discovery vs action classification */\n searchSignal: boolean;\n /** Reflection engine — adaptive LLM-driven behavior */\n reflection: boolean;\n /** Task classifier — intent inference (action/discovery/analysis) */\n taskClassifier: boolean;\n /** Smart summarizer — progressive conversation compression */\n smartSummarizer: boolean;\n /** Tier escalation — auto-escalate small → medium → large */\n tierEscalation: boolean;\n}\n\n/**\n * Default feature flags — conservative, all experimental features off.\n */\nexport const DEFAULT_FEATURE_FLAGS: FeatureFlags = {\n twoTierMemory: false,\n todoSync: false,\n searchSignal: false,\n reflection: false,\n taskClassifier: false,\n smartSummarizer: false,\n tierEscalation: false,\n};\n\n// ═══════════════════════════════════════════════════════════════════════\n// Execution Loop Result\n// ═══════════════════════════════════════════════════════════════════════\n\n/**\n * Result of a single ExecutionLoop run.\n * Uses discriminated union on `outcome` instead of thrown exceptions.\n */\nexport type LoopResult<T = unknown> =\n | { outcome: 'complete'; result: T }\n | { outcome: 'escalate'; reason: string }\n | { outcome: 'handoff'; targetAgentId: string; context: Record<string, unknown> };\n","/**\n * Agent configuration types for kb.config.json\n */\nimport type { AgentSmartTieringConfig, AgentTokenBudgetConfig } from './types.js';\n\n/**\n * Storage configuration for file history snapshots\n */\nexport interface FileHistoryStorageConfig {\n /** Base path for session storage (default: .kb/agents/sessions) */\n basePath?: string;\n /** Maximum number of sessions to keep (default: 30) */\n maxSessions?: number;\n /** Maximum age of sessions in days (default: 30) */\n maxAgeDays?: number;\n /** Maximum total storage size in MB (default: 500) */\n maxTotalSizeMb?: number;\n /** Enable compression for old snapshots (default: true) */\n compressOldSnapshots?: boolean;\n}\n\n/**\n * Escalation level configuration\n */\nexport interface EscalationLevelConfig {\n /** Enable this escalation level */\n enabled: boolean;\n /** Confidence threshold for this level (0-1) */\n confidenceThreshold: number;\n /** Maximum duration in milliseconds */\n maxDurationMs: number;\n}\n\n/**\n * Human escalation configuration\n */\nexport interface HumanEscalationConfig {\n /** Enable human escalation */\n enabled: boolean;\n /** Auto-escalate to human after this many milliseconds */\n autoEscalateAfterMs?: number;\n}\n\n/**\n * Escalation policy for adaptive conflict resolution\n */\nexport interface EscalationPolicy {\n /** Level 1: Auto-resolve (disjoint changes, 60%, <10ms) */\n level1AutoResolve: EscalationLevelConfig;\n /** Level 2: LLM-merge (overlapping changes, 30%, 2-5s) */\n level2LLMMerge: EscalationLevelConfig;\n /** Level 3: Agent coordination (conflicting intent, 8%, 10-30s) */\n level3AgentCoordination: EscalationLevelConfig;\n /** Level 4: Human escalation (unresolvable, 2%) */\n level4HumanEscalation: HumanEscalationConfig;\n}\n\n/**\n * Conflict resolution configuration\n */\nexport interface ConflictResolutionConfig {\n /** Default strategy: 'adaptive' | 'skip-conflicts' | 'force-overwrite' */\n defaultStrategy: 'adaptive' | 'skip-conflicts' | 'force-overwrite';\n /** Escalation policy for adaptive resolution */\n escalationPolicy: EscalationPolicy;\n}\n\n/**\n * File history configuration\n */\nexport interface FileHistoryConfig {\n /** Enable file history tracking */\n enabled: boolean;\n /** Storage configuration */\n storage: FileHistoryStorageConfig;\n /** Conflict resolution configuration */\n conflictResolution: ConflictResolutionConfig;\n}\n\n/**\n * Agents plugin configuration\n */\nexport interface AgentsPluginConfig {\n /** Enable agents plugin */\n enabled: boolean;\n /** Adaptive helper-node elevation policy (small -> medium on risk) */\n smartTiering?: AgentSmartTieringConfig;\n /** Token budget policy for long-running tasks */\n tokenBudget?: AgentTokenBudgetConfig;\n /** File history tracking configuration */\n fileHistory: FileHistoryConfig;\n}\n\n/**\n * Default configuration values\n */\nexport const DEFAULT_FILE_HISTORY_CONFIG: Required<FileHistoryConfig> = {\n enabled: true,\n storage: {\n basePath: '.kb/agents/sessions',\n maxSessions: 30,\n maxAgeDays: 30,\n maxTotalSizeMb: 500,\n compressOldSnapshots: true,\n },\n conflictResolution: {\n defaultStrategy: 'adaptive',\n escalationPolicy: {\n level1AutoResolve: {\n enabled: true,\n confidenceThreshold: 1.0,\n maxDurationMs: 10,\n },\n level2LLMMerge: {\n enabled: true,\n confidenceThreshold: 0.8,\n maxDurationMs: 5000,\n },\n level3AgentCoordination: {\n enabled: true,\n confidenceThreshold: 0.6,\n maxDurationMs: 30000,\n },\n level4HumanEscalation: {\n enabled: true,\n autoEscalateAfterMs: 60000,\n },\n },\n },\n};\n\nexport const DEFAULT_AGENT_TOKEN_BUDGET_CONFIG: Required<\n Omit<AgentTokenBudgetConfig, 'maxTokens'>\n> = {\n enabled: false,\n softLimitRatio: 0.7,\n hardLimitRatio: 1.0,\n hardStop: false,\n forceSynthesisOnHardLimit: true,\n restrictBroadExplorationAtSoftLimit: true,\n allowIterationBudgetExtension: true,\n spec: {\n enabled: true,\n multiplier: 4.0,\n floorTokens: 100_000,\n ceilingTokens: 250_000,\n synthesisReserveRatio: 0.2,\n partialOnFailure: true,\n },\n};\n"]}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kb-labs/agent-contracts",
|
|
3
3
|
"description": "Type definitions and contracts for KB Labs Agents. IDs, Session, Specification, Gates, Multi-Agent types.",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.119.0-canary.0b4b21a55",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"tsup": "^8.5.0",
|
|
28
28
|
"typescript": "^5.6.3",
|
|
29
29
|
"vitest": "^3.2.6",
|
|
30
|
-
"@kb-labs/devkit": "2.
|
|
30
|
+
"@kb-labs/devkit": "2.119.0-canary.0b4b21a55"
|
|
31
31
|
},
|
|
32
32
|
"engines": {
|
|
33
33
|
"node": ">=22.0.0",
|