@kognitivedev/shared 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # @kognitivedev/shared
2
+
3
+ > Foundation utilities for the Kognitive AI framework — EventBus, Cache, Logger, Errors, Retry, and OpenTelemetry integration.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add @kognitivedev/shared
9
+ ```
10
+
11
+ ## Exports
12
+
13
+ ### Events
14
+ - `InMemoryEventBus` — typed pub/sub: `emit()`, `on()`, `once()`, `removeAll()`
15
+
16
+ ### Cache
17
+ - `InMemoryCacheAdapter` — TTL-based cache: `get()`, `set()`, `delete()`, `clear()`
18
+
19
+ ### Logger
20
+ - `ConsoleLogger` — structured logging with prefix
21
+ - `NoopLogger` — silent logger for testing
22
+
23
+ ### Errors
24
+ - `KognitiveError`, `RetryableError`, `ValidationError`, `TimeoutError`, `NotFoundError`, `ApprovalDeniedError`
25
+
26
+ ### Utilities
27
+ - `withRetry(fn, options)` — exponential backoff retry
28
+ - `generateId()` — UUID generation
29
+
30
+ ### Telemetry
31
+ - `withSpan(name, fn, attributes?)` — OpenTelemetry span wrapper (no-op if OTEL not installed)
32
+ - `createSpan()`, `endSpan()` — manual span control
33
+
34
+ ### Streaming
35
+ - `StreamMode` — `"values" | "updates" | "messages" | "custom" | "debug"`
36
+ - `StreamEvent` — `{ event: string; data: unknown }`
37
+ - `parseStreamModes(input)` — validate and parse comma-separated mode string
38
+ - `createSSEEncoder()` — `TransformStream<StreamEvent, Uint8Array>` for SSE wire format
39
+ - `sseHeaders()` — standard SSE response headers
40
+
41
+ ### Types
42
+ - `ResourceId` — `{ organizationId?, projectId, userId?, sessionId? }`
43
+ - `Result<T, E>` — discriminated union with `ok()` / `err()` helpers
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const vitest_1 = require("vitest");
4
+ const index_1 = require("../index");
5
+ // ─── EventBus ───
6
+ (0, vitest_1.describe)("InMemoryEventBus", () => {
7
+ let bus;
8
+ (0, vitest_1.beforeEach)(() => {
9
+ bus = new index_1.InMemoryEventBus();
10
+ });
11
+ (0, vitest_1.it)("emits events to registered handlers", () => {
12
+ const handler = vitest_1.vi.fn();
13
+ bus.on("test", handler);
14
+ bus.emit("test", { value: 42 });
15
+ (0, vitest_1.expect)(handler).toHaveBeenCalledWith({ value: 42 });
16
+ });
17
+ (0, vitest_1.it)("supports multiple handlers for same event", () => {
18
+ const h1 = vitest_1.vi.fn();
19
+ const h2 = vitest_1.vi.fn();
20
+ bus.on("evt", h1);
21
+ bus.on("evt", h2);
22
+ bus.emit("evt", "data");
23
+ (0, vitest_1.expect)(h1).toHaveBeenCalledWith("data");
24
+ (0, vitest_1.expect)(h2).toHaveBeenCalledWith("data");
25
+ });
26
+ (0, vitest_1.it)("unsubscribes via returned function", () => {
27
+ const handler = vitest_1.vi.fn();
28
+ const unsub = bus.on("evt", handler);
29
+ unsub();
30
+ bus.emit("evt", "data");
31
+ (0, vitest_1.expect)(handler).not.toHaveBeenCalled();
32
+ });
33
+ (0, vitest_1.it)("once fires handler only once", () => {
34
+ const handler = vitest_1.vi.fn();
35
+ bus.once("evt", handler);
36
+ bus.emit("evt", 1);
37
+ bus.emit("evt", 2);
38
+ (0, vitest_1.expect)(handler).toHaveBeenCalledTimes(1);
39
+ (0, vitest_1.expect)(handler).toHaveBeenCalledWith(1);
40
+ });
41
+ (0, vitest_1.it)("removeAll clears specific event", () => {
42
+ const h1 = vitest_1.vi.fn();
43
+ const h2 = vitest_1.vi.fn();
44
+ bus.on("a", h1);
45
+ bus.on("b", h2);
46
+ bus.removeAll("a");
47
+ bus.emit("a", 1);
48
+ bus.emit("b", 2);
49
+ (0, vitest_1.expect)(h1).not.toHaveBeenCalled();
50
+ (0, vitest_1.expect)(h2).toHaveBeenCalled();
51
+ });
52
+ (0, vitest_1.it)("removeAll with no arg clears all events", () => {
53
+ const h1 = vitest_1.vi.fn();
54
+ const h2 = vitest_1.vi.fn();
55
+ bus.on("a", h1);
56
+ bus.on("b", h2);
57
+ bus.removeAll();
58
+ bus.emit("a", 1);
59
+ bus.emit("b", 2);
60
+ (0, vitest_1.expect)(h1).not.toHaveBeenCalled();
61
+ (0, vitest_1.expect)(h2).not.toHaveBeenCalled();
62
+ });
63
+ (0, vitest_1.it)("does not throw on emit with no handlers", () => {
64
+ (0, vitest_1.expect)(() => bus.emit("nonexistent", {})).not.toThrow();
65
+ });
66
+ });
67
+ // ─── Cache ───
68
+ (0, vitest_1.describe)("InMemoryCacheAdapter", () => {
69
+ let cache;
70
+ (0, vitest_1.beforeEach)(() => {
71
+ cache = new index_1.InMemoryCacheAdapter();
72
+ });
73
+ (0, vitest_1.it)("get returns null for missing key", async () => {
74
+ (0, vitest_1.expect)(await cache.get("missing")).toBeNull();
75
+ });
76
+ (0, vitest_1.it)("set and get round-trips", async () => {
77
+ await cache.set("key", { value: 42 });
78
+ (0, vitest_1.expect)(await cache.get("key")).toEqual({ value: 42 });
79
+ });
80
+ (0, vitest_1.it)("delete removes entry", async () => {
81
+ await cache.set("key", "value");
82
+ await cache.delete("key");
83
+ (0, vitest_1.expect)(await cache.get("key")).toBeNull();
84
+ });
85
+ (0, vitest_1.it)("TTL expires entries", async () => {
86
+ vitest_1.vi.useFakeTimers();
87
+ await cache.set("key", "value", 1); // 1 second TTL
88
+ (0, vitest_1.expect)(await cache.get("key")).toBe("value");
89
+ vitest_1.vi.advanceTimersByTime(2000);
90
+ (0, vitest_1.expect)(await cache.get("key")).toBeNull();
91
+ vitest_1.vi.useRealTimers();
92
+ });
93
+ (0, vitest_1.it)("reports size", async () => {
94
+ await cache.set("a", 1);
95
+ await cache.set("b", 2);
96
+ (0, vitest_1.expect)(cache.size).toBe(2);
97
+ });
98
+ (0, vitest_1.it)("clear removes all entries", async () => {
99
+ await cache.set("a", 1);
100
+ await cache.set("b", 2);
101
+ cache.clear();
102
+ (0, vitest_1.expect)(cache.size).toBe(0);
103
+ });
104
+ });
105
+ // ─── withRetry ───
106
+ (0, vitest_1.describe)("withRetry", () => {
107
+ (0, vitest_1.it)("succeeds on first try", async () => {
108
+ const fn = vitest_1.vi.fn().mockResolvedValue("ok");
109
+ const result = await (0, index_1.withRetry)(fn, { maxRetries: 3 });
110
+ (0, vitest_1.expect)(result).toBe("ok");
111
+ (0, vitest_1.expect)(fn).toHaveBeenCalledTimes(1);
112
+ });
113
+ (0, vitest_1.it)("retries and succeeds on second attempt", async () => {
114
+ const fn = vitest_1.vi.fn()
115
+ .mockRejectedValueOnce(new Error("fail"))
116
+ .mockResolvedValue("ok");
117
+ const result = await (0, index_1.withRetry)(fn, { maxRetries: 3, baseDelayMs: 1 });
118
+ (0, vitest_1.expect)(result).toBe("ok");
119
+ (0, vitest_1.expect)(fn).toHaveBeenCalledTimes(2);
120
+ });
121
+ (0, vitest_1.it)("throws after max retries", async () => {
122
+ const fn = vitest_1.vi.fn().mockRejectedValue(new Error("always fails"));
123
+ await (0, vitest_1.expect)((0, index_1.withRetry)(fn, { maxRetries: 2, baseDelayMs: 1 })).rejects.toThrow("always fails");
124
+ (0, vitest_1.expect)(fn).toHaveBeenCalledTimes(2);
125
+ });
126
+ });
127
+ // ─── Utilities ───
128
+ (0, vitest_1.describe)("generateId", () => {
129
+ (0, vitest_1.it)("returns a UUID string", () => {
130
+ const id = (0, index_1.generateId)();
131
+ (0, vitest_1.expect)(id).toMatch(/^[0-9a-f-]{36}$/);
132
+ });
133
+ (0, vitest_1.it)("generates unique IDs", () => {
134
+ const ids = new Set(Array.from({ length: 100 }, () => (0, index_1.generateId)()));
135
+ (0, vitest_1.expect)(ids.size).toBe(100);
136
+ });
137
+ });
138
+ (0, vitest_1.describe)("Result helpers", () => {
139
+ (0, vitest_1.it)("ok creates success result", () => {
140
+ const result = (0, index_1.ok)(42);
141
+ (0, vitest_1.expect)(result.ok).toBe(true);
142
+ if (result.ok)
143
+ (0, vitest_1.expect)(result.value).toBe(42);
144
+ });
145
+ (0, vitest_1.it)("err creates failure result", () => {
146
+ const result = (0, index_1.err)(new Error("fail"));
147
+ (0, vitest_1.expect)(result.ok).toBe(false);
148
+ if (!result.ok)
149
+ (0, vitest_1.expect)(result.error.message).toBe("fail");
150
+ });
151
+ });
152
+ // ─── Error Types ───
153
+ (0, vitest_1.describe)("Error types", () => {
154
+ (0, vitest_1.it)("KognitiveError has code and name", () => {
155
+ const e = new index_1.KognitiveError("msg", "CODE");
156
+ (0, vitest_1.expect)(e.name).toBe("KognitiveError");
157
+ (0, vitest_1.expect)(e.code).toBe("CODE");
158
+ (0, vitest_1.expect)(e.message).toBe("msg");
159
+ });
160
+ (0, vitest_1.it)("ValidationError has field", () => {
161
+ const e = new index_1.ValidationError("bad input", "email");
162
+ (0, vitest_1.expect)(e.name).toBe("ValidationError");
163
+ (0, vitest_1.expect)(e.field).toBe("email");
164
+ (0, vitest_1.expect)(e.code).toBe("VALIDATION");
165
+ });
166
+ (0, vitest_1.it)("NotFoundError formats message", () => {
167
+ const e = new index_1.NotFoundError("User", "123");
168
+ (0, vitest_1.expect)(e.message).toBe("User not found: 123");
169
+ (0, vitest_1.expect)(e.code).toBe("NOT_FOUND");
170
+ });
171
+ (0, vitest_1.it)("TimeoutError has timeoutMs", () => {
172
+ const e = new index_1.TimeoutError("timed out", 5000);
173
+ (0, vitest_1.expect)(e.timeoutMs).toBe(5000);
174
+ (0, vitest_1.expect)(e.code).toBe("TIMEOUT");
175
+ });
176
+ (0, vitest_1.it)("ApprovalDeniedError has tool info", () => {
177
+ const e = new index_1.ApprovalDeniedError("search");
178
+ (0, vitest_1.expect)(e.message).toContain("search");
179
+ (0, vitest_1.expect)(e.code).toBe("APPROVAL_DENIED");
180
+ });
181
+ (0, vitest_1.it)("RetryableError is retryable", () => {
182
+ const e = new index_1.RetryableError("transient");
183
+ (0, vitest_1.expect)(e.code).toBe("RETRYABLE");
184
+ });
185
+ });
186
+ // ─── Logger ───
187
+ (0, vitest_1.describe)("Loggers", () => {
188
+ (0, vitest_1.it)("ConsoleLogger logs without throwing", () => {
189
+ const logger = new index_1.ConsoleLogger("[Test]");
190
+ (0, vitest_1.expect)(() => logger.debug("test")).not.toThrow();
191
+ (0, vitest_1.expect)(() => logger.info("test")).not.toThrow();
192
+ (0, vitest_1.expect)(() => logger.warn("test")).not.toThrow();
193
+ (0, vitest_1.expect)(() => logger.error("test", new Error("e"))).not.toThrow();
194
+ });
195
+ (0, vitest_1.it)("NoopLogger does nothing", () => {
196
+ const logger = new index_1.NoopLogger();
197
+ (0, vitest_1.expect)(() => logger.debug("test")).not.toThrow();
198
+ (0, vitest_1.expect)(() => logger.info("test")).not.toThrow();
199
+ });
200
+ });
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Cache interface for performance optimization.
3
+ * Extracted from @kognitivedev/core for shared use across all packages.
4
+ */
5
+ export interface CacheAdapter {
6
+ get<T>(key: string): Promise<T | null>;
7
+ set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>;
8
+ delete(key: string): Promise<void>;
9
+ }
10
+ /**
11
+ * In-memory cache implementation with TTL support.
12
+ */
13
+ export declare class InMemoryCacheAdapter implements CacheAdapter {
14
+ private store;
15
+ get<T>(key: string): Promise<T | null>;
16
+ set<T>(key: string, value: T, ttlSeconds?: number): Promise<void>;
17
+ delete(key: string): Promise<void>;
18
+ /**
19
+ * Clear all entries from the cache.
20
+ */
21
+ clear(): void;
22
+ /**
23
+ * Get the number of entries in the cache (including possibly expired).
24
+ */
25
+ get size(): number;
26
+ }
package/dist/cache.js ADDED
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InMemoryCacheAdapter = void 0;
4
+ /**
5
+ * In-memory cache implementation with TTL support.
6
+ */
7
+ class InMemoryCacheAdapter {
8
+ constructor() {
9
+ this.store = new Map();
10
+ }
11
+ async get(key) {
12
+ const entry = this.store.get(key);
13
+ if (!entry)
14
+ return null;
15
+ if (entry.expiresAt && Date.now() > entry.expiresAt) {
16
+ this.store.delete(key);
17
+ return null;
18
+ }
19
+ return entry.value;
20
+ }
21
+ async set(key, value, ttlSeconds) {
22
+ const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : null;
23
+ this.store.set(key, { value, expiresAt });
24
+ }
25
+ async delete(key) {
26
+ this.store.delete(key);
27
+ }
28
+ /**
29
+ * Clear all entries from the cache.
30
+ */
31
+ clear() {
32
+ this.store.clear();
33
+ }
34
+ /**
35
+ * Get the number of entries in the cache (including possibly expired).
36
+ */
37
+ get size() {
38
+ return this.store.size;
39
+ }
40
+ }
41
+ exports.InMemoryCacheAdapter = InMemoryCacheAdapter;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Base error class for all Kognitive errors.
3
+ */
4
+ export declare class KognitiveError extends Error {
5
+ readonly code: string;
6
+ readonly cause?: Error | undefined;
7
+ constructor(message: string, code: string, cause?: Error | undefined);
8
+ }
9
+ /**
10
+ * Error that can be retried (transient failures).
11
+ */
12
+ export declare class RetryableError extends KognitiveError {
13
+ constructor(message: string, cause?: Error);
14
+ }
15
+ /**
16
+ * Input validation error.
17
+ */
18
+ export declare class ValidationError extends KognitiveError {
19
+ readonly field?: string | undefined;
20
+ constructor(message: string, field?: string | undefined);
21
+ }
22
+ /**
23
+ * Operation timed out.
24
+ */
25
+ export declare class TimeoutError extends KognitiveError {
26
+ readonly timeoutMs: number;
27
+ constructor(message: string, timeoutMs: number);
28
+ }
29
+ /**
30
+ * Resource not found.
31
+ */
32
+ export declare class NotFoundError extends KognitiveError {
33
+ constructor(resource: string, id: string);
34
+ }
35
+ /**
36
+ * Tool approval was denied.
37
+ */
38
+ export declare class ApprovalDeniedError extends KognitiveError {
39
+ constructor(toolId: string);
40
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApprovalDeniedError = exports.NotFoundError = exports.TimeoutError = exports.ValidationError = exports.RetryableError = exports.KognitiveError = void 0;
4
+ /**
5
+ * Base error class for all Kognitive errors.
6
+ */
7
+ class KognitiveError extends Error {
8
+ constructor(message, code, cause) {
9
+ super(message);
10
+ this.code = code;
11
+ this.cause = cause;
12
+ this.name = "KognitiveError";
13
+ }
14
+ }
15
+ exports.KognitiveError = KognitiveError;
16
+ /**
17
+ * Error that can be retried (transient failures).
18
+ */
19
+ class RetryableError extends KognitiveError {
20
+ constructor(message, cause) {
21
+ super(message, "RETRYABLE", cause);
22
+ this.name = "RetryableError";
23
+ }
24
+ }
25
+ exports.RetryableError = RetryableError;
26
+ /**
27
+ * Input validation error.
28
+ */
29
+ class ValidationError extends KognitiveError {
30
+ constructor(message, field) {
31
+ super(message, "VALIDATION");
32
+ this.field = field;
33
+ this.name = "ValidationError";
34
+ }
35
+ }
36
+ exports.ValidationError = ValidationError;
37
+ /**
38
+ * Operation timed out.
39
+ */
40
+ class TimeoutError extends KognitiveError {
41
+ constructor(message, timeoutMs) {
42
+ super(message, "TIMEOUT");
43
+ this.timeoutMs = timeoutMs;
44
+ this.name = "TimeoutError";
45
+ }
46
+ }
47
+ exports.TimeoutError = TimeoutError;
48
+ /**
49
+ * Resource not found.
50
+ */
51
+ class NotFoundError extends KognitiveError {
52
+ constructor(resource, id) {
53
+ super(`${resource} not found: ${id}`, "NOT_FOUND");
54
+ this.name = "NotFoundError";
55
+ }
56
+ }
57
+ exports.NotFoundError = NotFoundError;
58
+ /**
59
+ * Tool approval was denied.
60
+ */
61
+ class ApprovalDeniedError extends KognitiveError {
62
+ constructor(toolId) {
63
+ super(`Approval denied for tool: ${toolId}`, "APPROVAL_DENIED");
64
+ this.name = "ApprovalDeniedError";
65
+ }
66
+ }
67
+ exports.ApprovalDeniedError = ApprovalDeniedError;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Typed event bus for decoupled communication between components.
3
+ * Used for agent lifecycle events, workflow step transitions, tool execution notifications, etc.
4
+ */
5
+ type EventHandler<T = unknown> = (data: T) => void;
6
+ export interface EventBus {
7
+ /**
8
+ * Emit an event with data to all registered handlers.
9
+ */
10
+ emit<T>(event: string, data: T): void;
11
+ /**
12
+ * Register a handler for an event. Returns an unsubscribe function.
13
+ */
14
+ on<T>(event: string, handler: EventHandler<T>): () => void;
15
+ /**
16
+ * Register a one-time handler for an event. Returns an unsubscribe function.
17
+ */
18
+ once<T>(event: string, handler: EventHandler<T>): () => void;
19
+ /**
20
+ * Remove all handlers for a specific event, or all events if no event is specified.
21
+ */
22
+ removeAll(event?: string): void;
23
+ }
24
+ /**
25
+ * In-memory event bus implementation.
26
+ */
27
+ export declare class InMemoryEventBus implements EventBus {
28
+ private handlers;
29
+ emit<T>(event: string, data: T): void;
30
+ on<T>(event: string, handler: EventHandler<T>): () => void;
31
+ once<T>(event: string, handler: EventHandler<T>): () => void;
32
+ removeAll(event?: string): void;
33
+ }
34
+ export {};
package/dist/events.js ADDED
@@ -0,0 +1,58 @@
1
+ "use strict";
2
+ /**
3
+ * Typed event bus for decoupled communication between components.
4
+ * Used for agent lifecycle events, workflow step transitions, tool execution notifications, etc.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.InMemoryEventBus = void 0;
8
+ /**
9
+ * In-memory event bus implementation.
10
+ */
11
+ class InMemoryEventBus {
12
+ constructor() {
13
+ this.handlers = new Map();
14
+ }
15
+ emit(event, data) {
16
+ const eventHandlers = this.handlers.get(event);
17
+ if (!eventHandlers)
18
+ return;
19
+ for (const handler of eventHandlers) {
20
+ try {
21
+ handler(data);
22
+ }
23
+ catch (_a) {
24
+ // Swallow handler errors to prevent breaking the event chain
25
+ }
26
+ }
27
+ }
28
+ on(event, handler) {
29
+ if (!this.handlers.has(event)) {
30
+ this.handlers.set(event, new Set());
31
+ }
32
+ const eventHandlers = this.handlers.get(event);
33
+ eventHandlers.add(handler);
34
+ return () => {
35
+ eventHandlers.delete(handler);
36
+ if (eventHandlers.size === 0) {
37
+ this.handlers.delete(event);
38
+ }
39
+ };
40
+ }
41
+ once(event, handler) {
42
+ const wrappedHandler = (data) => {
43
+ unsubscribe();
44
+ handler(data);
45
+ };
46
+ const unsubscribe = this.on(event, wrappedHandler);
47
+ return unsubscribe;
48
+ }
49
+ removeAll(event) {
50
+ if (event) {
51
+ this.handlers.delete(event);
52
+ }
53
+ else {
54
+ this.handlers.clear();
55
+ }
56
+ }
57
+ }
58
+ exports.InMemoryEventBus = InMemoryEventBus;
@@ -0,0 +1,17 @@
1
+ export type { ResourceId, Result, Metadata, Disposable } from "./types";
2
+ export { ok, err } from "./types";
3
+ export type { EventBus } from "./events";
4
+ export { InMemoryEventBus } from "./events";
5
+ export type { Logger } from "./logger";
6
+ export { ConsoleLogger, NoopLogger } from "./logger";
7
+ export type { CacheAdapter } from "./cache";
8
+ export { InMemoryCacheAdapter } from "./cache";
9
+ export { KognitiveError, RetryableError, ValidationError, TimeoutError, NotFoundError, ApprovalDeniedError, } from "./errors";
10
+ export { withRetry, type RetryOptions, type RetryAttempt, type RetryMetadata } from "./utils/retry";
11
+ export { generateId } from "./utils/id";
12
+ export type { SpanLike } from "./telemetry";
13
+ export { createSpan, endSpan, withSpan } from "./telemetry";
14
+ export type { StreamMode, StreamEvent } from "./streaming";
15
+ export { parseStreamModes, createSSEEncoder, sseHeaders } from "./streaming";
16
+ export type { TemplateVariables } from "./template";
17
+ export { renderTemplate } from "./template";
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.renderTemplate = exports.sseHeaders = exports.createSSEEncoder = exports.parseStreamModes = exports.withSpan = exports.endSpan = exports.createSpan = exports.generateId = exports.withRetry = exports.ApprovalDeniedError = exports.NotFoundError = exports.TimeoutError = exports.ValidationError = exports.RetryableError = exports.KognitiveError = exports.InMemoryCacheAdapter = exports.NoopLogger = exports.ConsoleLogger = exports.InMemoryEventBus = exports.err = exports.ok = void 0;
4
+ var types_1 = require("./types");
5
+ Object.defineProperty(exports, "ok", { enumerable: true, get: function () { return types_1.ok; } });
6
+ Object.defineProperty(exports, "err", { enumerable: true, get: function () { return types_1.err; } });
7
+ var events_1 = require("./events");
8
+ Object.defineProperty(exports, "InMemoryEventBus", { enumerable: true, get: function () { return events_1.InMemoryEventBus; } });
9
+ var logger_1 = require("./logger");
10
+ Object.defineProperty(exports, "ConsoleLogger", { enumerable: true, get: function () { return logger_1.ConsoleLogger; } });
11
+ Object.defineProperty(exports, "NoopLogger", { enumerable: true, get: function () { return logger_1.NoopLogger; } });
12
+ var cache_1 = require("./cache");
13
+ Object.defineProperty(exports, "InMemoryCacheAdapter", { enumerable: true, get: function () { return cache_1.InMemoryCacheAdapter; } });
14
+ // Errors
15
+ var errors_1 = require("./errors");
16
+ Object.defineProperty(exports, "KognitiveError", { enumerable: true, get: function () { return errors_1.KognitiveError; } });
17
+ Object.defineProperty(exports, "RetryableError", { enumerable: true, get: function () { return errors_1.RetryableError; } });
18
+ Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_1.ValidationError; } });
19
+ Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return errors_1.TimeoutError; } });
20
+ Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_1.NotFoundError; } });
21
+ Object.defineProperty(exports, "ApprovalDeniedError", { enumerable: true, get: function () { return errors_1.ApprovalDeniedError; } });
22
+ // Utilities
23
+ var retry_1 = require("./utils/retry");
24
+ Object.defineProperty(exports, "withRetry", { enumerable: true, get: function () { return retry_1.withRetry; } });
25
+ var id_1 = require("./utils/id");
26
+ Object.defineProperty(exports, "generateId", { enumerable: true, get: function () { return id_1.generateId; } });
27
+ var telemetry_1 = require("./telemetry");
28
+ Object.defineProperty(exports, "createSpan", { enumerable: true, get: function () { return telemetry_1.createSpan; } });
29
+ Object.defineProperty(exports, "endSpan", { enumerable: true, get: function () { return telemetry_1.endSpan; } });
30
+ Object.defineProperty(exports, "withSpan", { enumerable: true, get: function () { return telemetry_1.withSpan; } });
31
+ var streaming_1 = require("./streaming");
32
+ Object.defineProperty(exports, "parseStreamModes", { enumerable: true, get: function () { return streaming_1.parseStreamModes; } });
33
+ Object.defineProperty(exports, "createSSEEncoder", { enumerable: true, get: function () { return streaming_1.createSSEEncoder; } });
34
+ Object.defineProperty(exports, "sseHeaders", { enumerable: true, get: function () { return streaming_1.sseHeaders; } });
35
+ var template_1 = require("./template");
36
+ Object.defineProperty(exports, "renderTemplate", { enumerable: true, get: function () { return template_1.renderTemplate; } });
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Logger interface for structured logging and observability.
3
+ * Extracted from @kognitivedev/core for shared use across all packages.
4
+ */
5
+ export interface Logger {
6
+ debug(message: string, data?: Record<string, any>): void;
7
+ info(message: string, data?: Record<string, any>): void;
8
+ warn(message: string, data?: Record<string, any>): void;
9
+ error(message: string, error?: Error, data?: Record<string, any>): void;
10
+ }
11
+ /**
12
+ * Default console logger implementation.
13
+ */
14
+ export declare class ConsoleLogger implements Logger {
15
+ private prefix;
16
+ constructor(prefix?: string);
17
+ debug(message: string, data?: Record<string, any>): void;
18
+ info(message: string, data?: Record<string, any>): void;
19
+ warn(message: string, data?: Record<string, any>): void;
20
+ error(message: string, error?: Error, data?: Record<string, any>): void;
21
+ }
22
+ /**
23
+ * Silent logger that discards all output. Useful for testing.
24
+ */
25
+ export declare class NoopLogger implements Logger {
26
+ debug(_message: string, _data?: Record<string, any>): void;
27
+ info(_message: string, _data?: Record<string, any>): void;
28
+ warn(_message: string, _data?: Record<string, any>): void;
29
+ error(_message: string, _error?: Error, _data?: Record<string, any>): void;
30
+ }
package/dist/logger.js ADDED
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NoopLogger = exports.ConsoleLogger = void 0;
4
+ /**
5
+ * Default console logger implementation.
6
+ */
7
+ class ConsoleLogger {
8
+ constructor(prefix = "[Kognitive]") {
9
+ this.prefix = prefix;
10
+ }
11
+ debug(message, data) {
12
+ console.debug(`${this.prefix} DEBUG: ${message}`, data || "");
13
+ }
14
+ info(message, data) {
15
+ console.info(`${this.prefix} INFO: ${message}`, data || "");
16
+ }
17
+ warn(message, data) {
18
+ console.warn(`${this.prefix} WARN: ${message}`, data || "");
19
+ }
20
+ error(message, error, data) {
21
+ console.error(`${this.prefix} ERROR: ${message}`, error, data || "");
22
+ }
23
+ }
24
+ exports.ConsoleLogger = ConsoleLogger;
25
+ /**
26
+ * Silent logger that discards all output. Useful for testing.
27
+ */
28
+ class NoopLogger {
29
+ debug(_message, _data) { }
30
+ info(_message, _data) { }
31
+ warn(_message, _data) { }
32
+ error(_message, _error, _data) { }
33
+ }
34
+ exports.NoopLogger = NoopLogger;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Multi-mode streaming protocol for agents and workflows.
3
+ *
4
+ * Inspired by LangGraph's 5 streaming modes:
5
+ * - values: Full state snapshot after every step
6
+ * - updates: State deltas only (what changed)
7
+ * - messages: Token-by-token LLM output
8
+ * - custom: Application-specific events from user code (via emit())
9
+ * - debug: Full execution trace with node entry/exit, tool I/O
10
+ */
11
+ export type StreamMode = "values" | "updates" | "messages" | "custom" | "debug";
12
+ export interface StreamEvent {
13
+ /** SSE event name */
14
+ event: string;
15
+ /** JSON-serializable payload */
16
+ data: unknown;
17
+ }
18
+ /**
19
+ * Parse and validate stream modes from a comma-separated string or array.
20
+ * Returns ["messages"] if input is empty/undefined (default mode).
21
+ */
22
+ export declare function parseStreamModes(input: string | string[] | undefined): StreamMode[];
23
+ /**
24
+ * TransformStream that encodes StreamEvents into SSE wire format.
25
+ *
26
+ * Output format per event:
27
+ * event: <event>\n
28
+ * data: <JSON>\n
29
+ * \n
30
+ */
31
+ export declare function createSSEEncoder(): TransformStream<StreamEvent, Uint8Array>;
32
+ /**
33
+ * Create SSE Response headers.
34
+ */
35
+ export declare function sseHeaders(): Record<string, string>;