@kb-labs/core-platform 1.0.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.
Files changed (56) hide show
  1. package/README.md +108 -0
  2. package/dist/adapters/index.cjs +26 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +125 -0
  5. package/dist/adapters/index.d.ts +125 -0
  6. package/dist/adapters/index.js +21 -0
  7. package/dist/adapters/index.js.map +1 -0
  8. package/dist/artifacts-BUghvkUU.d.cts +273 -0
  9. package/dist/artifacts-Bd-1UVTw.d.ts +273 -0
  10. package/dist/artifacts-DrVnkLzu.d.cts +1374 -0
  11. package/dist/artifacts-DrVnkLzu.d.ts +1374 -0
  12. package/dist/core/index.cjs +4 -0
  13. package/dist/core/index.cjs.map +1 -0
  14. package/dist/core/index.d.cts +2 -0
  15. package/dist/core/index.d.ts +2 -0
  16. package/dist/core/index.js +3 -0
  17. package/dist/core/index.js.map +1 -0
  18. package/dist/database-DGV6a1nj.d.cts +427 -0
  19. package/dist/database-DGV6a1nj.d.ts +427 -0
  20. package/dist/index.cjs +1405 -0
  21. package/dist/index.cjs.map +1 -0
  22. package/dist/index.d.cts +579 -0
  23. package/dist/index.d.ts +579 -0
  24. package/dist/index.js +1381 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/log-reader-BVohbSMB.d.cts +314 -0
  27. package/dist/log-reader-uOHBLBax.d.ts +314 -0
  28. package/dist/noop/adapters/index.cjs +656 -0
  29. package/dist/noop/adapters/index.cjs.map +1 -0
  30. package/dist/noop/adapters/index.d.cts +71 -0
  31. package/dist/noop/adapters/index.d.ts +71 -0
  32. package/dist/noop/adapters/index.js +637 -0
  33. package/dist/noop/adapters/index.js.map +1 -0
  34. package/dist/noop/core/index.cjs +217 -0
  35. package/dist/noop/core/index.cjs.map +1 -0
  36. package/dist/noop/core/index.d.cts +94 -0
  37. package/dist/noop/core/index.d.ts +94 -0
  38. package/dist/noop/core/index.js +212 -0
  39. package/dist/noop/core/index.js.map +1 -0
  40. package/dist/noop/index.cjs +806 -0
  41. package/dist/noop/index.cjs.map +1 -0
  42. package/dist/noop/index.d.cts +36 -0
  43. package/dist/noop/index.d.ts +36 -0
  44. package/dist/noop/index.js +787 -0
  45. package/dist/noop/index.js.map +1 -0
  46. package/dist/resources-DaufJFad.d.cts +419 -0
  47. package/dist/resources-DaufJFad.d.ts +419 -0
  48. package/dist/serializable/index.cjs +162 -0
  49. package/dist/serializable/index.cjs.map +1 -0
  50. package/dist/serializable/index.d.cts +352 -0
  51. package/dist/serializable/index.d.ts +352 -0
  52. package/dist/serializable/index.js +152 -0
  53. package/dist/serializable/index.js.map +1 -0
  54. package/dist/snapshot-provider--COac4P-.d.ts +923 -0
  55. package/dist/snapshot-provider-nE9wuc1C.d.cts +923 -0
  56. package/package.json +92 -0
@@ -0,0 +1,152 @@
1
+ // src/serializable/types.ts
2
+ var IPC_PROTOCOL_VERSION = 2;
3
+ function isAdapterCall(msg) {
4
+ if (typeof msg !== "object" || msg === null || msg.type !== "adapter:call" || typeof msg.requestId !== "string" || typeof msg.adapter !== "string" || typeof msg.method !== "string" || !Array.isArray(msg.args)) {
5
+ return false;
6
+ }
7
+ if ("version" in msg && typeof msg.version !== "number") {
8
+ return false;
9
+ }
10
+ if (!("version" in msg)) {
11
+ msg.version = 1;
12
+ }
13
+ return true;
14
+ }
15
+ function isAdapterResponse(msg) {
16
+ return typeof msg === "object" && msg !== null && msg.type === "adapter:response" && typeof msg.requestId === "string";
17
+ }
18
+ var SerializationError = class extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = "SerializationError";
22
+ }
23
+ };
24
+ var DeserializationError = class extends Error {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "DeserializationError";
28
+ }
29
+ };
30
+
31
+ // src/serializable/serializer.ts
32
+ function serialize(value) {
33
+ const seen = /* @__PURE__ */ new WeakSet();
34
+ return serializeValue(value, seen);
35
+ }
36
+ function serializeValue(value, seen) {
37
+ if (value === null || value === void 0) {
38
+ return null;
39
+ }
40
+ if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
41
+ return value;
42
+ }
43
+ if (typeof value === "object") {
44
+ if (seen.has(value)) {
45
+ throw new SerializationError("Circular reference detected");
46
+ }
47
+ seen.add(value);
48
+ }
49
+ if (Buffer.isBuffer(value)) {
50
+ return {
51
+ __type: "Buffer",
52
+ data: value.toString("base64")
53
+ };
54
+ }
55
+ if (value instanceof Date) {
56
+ if (isNaN(value.getTime())) {
57
+ throw new SerializationError("Cannot serialize invalid Date");
58
+ }
59
+ return {
60
+ __type: "Date",
61
+ iso: value.toISOString()
62
+ };
63
+ }
64
+ if (value instanceof Error) {
65
+ return {
66
+ __type: "Error",
67
+ name: value.name,
68
+ message: value.message,
69
+ stack: value.stack,
70
+ code: value.code
71
+ };
72
+ }
73
+ if (Array.isArray(value)) {
74
+ return value.map((item) => serializeValue(item, seen));
75
+ }
76
+ if (typeof value === "object" && value.constructor === Object) {
77
+ const result = {};
78
+ for (const [key, val] of Object.entries(value)) {
79
+ result[key] = serializeValue(val, seen);
80
+ }
81
+ return result;
82
+ }
83
+ throw new SerializationError(
84
+ `Cannot serialize type: ${typeof value} (constructor: ${value.constructor?.name || "unknown"})`
85
+ );
86
+ }
87
+ function deserialize(value) {
88
+ if (value === null) {
89
+ return null;
90
+ }
91
+ if (typeof value === "boolean" || typeof value === "number" || typeof value === "string") {
92
+ return value;
93
+ }
94
+ if (typeof value !== "object") {
95
+ throw new DeserializationError(`Invalid serialized value type: ${typeof value}`);
96
+ }
97
+ const obj = value;
98
+ if (obj.__type === "Buffer") {
99
+ if (typeof obj.data !== "string") {
100
+ throw new DeserializationError("Invalid SerializableBuffer: missing or invalid data field");
101
+ }
102
+ try {
103
+ return Buffer.from(obj.data, "base64");
104
+ } catch (error) {
105
+ throw new DeserializationError(`Failed to decode Buffer: ${error}`);
106
+ }
107
+ }
108
+ if (obj.__type === "Date") {
109
+ if (typeof obj.iso !== "string") {
110
+ throw new DeserializationError("Invalid SerializableDate: missing or invalid iso field");
111
+ }
112
+ const date = new Date(obj.iso);
113
+ if (isNaN(date.getTime())) {
114
+ throw new DeserializationError(`Invalid ISO date string: ${obj.iso}`);
115
+ }
116
+ return date;
117
+ }
118
+ if (obj.__type === "Error") {
119
+ if (typeof obj.message !== "string") {
120
+ throw new DeserializationError("Invalid SerializableError: missing or invalid message field");
121
+ }
122
+ const error = new Error(obj.message);
123
+ if (typeof obj.name === "string") {
124
+ error.name = obj.name;
125
+ }
126
+ if (typeof obj.stack === "string") {
127
+ error.stack = obj.stack;
128
+ }
129
+ if (obj.code !== void 0) {
130
+ error.code = obj.code;
131
+ }
132
+ return error;
133
+ }
134
+ if (Array.isArray(value)) {
135
+ return value.map((item) => deserialize(item));
136
+ }
137
+ const result = {};
138
+ for (const [key, val] of Object.entries(value)) {
139
+ result[key] = deserialize(val);
140
+ }
141
+ return result;
142
+ }
143
+ function serializeArgs(args) {
144
+ return args.map((arg) => serialize(arg));
145
+ }
146
+ function deserializeArgs(args) {
147
+ return args.map((arg) => deserialize(arg));
148
+ }
149
+
150
+ export { DeserializationError, IPC_PROTOCOL_VERSION, SerializationError, deserialize, deserializeArgs, isAdapterCall, isAdapterResponse, serialize, serializeArgs };
151
+ //# sourceMappingURL=index.js.map
152
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/serializable/types.ts","../../src/serializable/serializer.ts"],"names":[],"mappings":";AA6JO,IAAM,oBAAA,GAAuB;AAmG7B,SAAS,cAAc,GAAA,EAAkC;AAC9D,EAAA,IACE,OAAO,GAAA,KAAQ,QAAA,IACf,GAAA,KAAQ,IAAA,IACP,IAAY,IAAA,KAAS,cAAA,IACtB,OAAQ,GAAA,CAAY,SAAA,KAAc,QAAA,IAClC,OAAQ,GAAA,CAAY,OAAA,KAAY,QAAA,IAChC,OAAQ,GAAA,CAAY,MAAA,KAAW,QAAA,IAC/B,CAAC,KAAA,CAAM,O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,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAK,CAAA,EAAG;AAC9C,IAAA,MAAA,CAAO,GAAG,CAAA,GAAI,WAAA,CAAY,GAAG,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,MAAA;AACT;AAcO,SAAS,cAAc,IAAA,EAAsC;AAClE,EAAA,OAAO,KAAK,GAAA,CAAI,CAAC,GAAA,KAAQ,SAAA,CAAU,GAAG,CAAC,CAAA;AACzC;AAcO,SAAS,gBAAgB,IAAA,EAAsC;AACpE,EAAA,OAAO,KAAK,GAAA,CAAI,CAAC,GAAA,KAAQ,WAAA,CAAY,GAAG,CAAC,CAAA;AAC3C","file":"index.js","sourcesContent":["/**\n * @module @kb-labs/core-platform/serializable\n * IPC serialization types for cross-process adapter communication.\n *\n * This module defines the protocol for serializing adapter method calls\n * and responses across process boundaries using IPC (Inter-Process Communication).\n *\n * @example\n * ```typescript\n * import { AdapterCall, AdapterResponse } from '@kb-labs/core-platform/serializable';\n *\n * const call: AdapterCall = {\n * type: 'adapter:call',\n * requestId: 'uuid-123',\n * adapter: 'vectorStore',\n * method: 'search',\n * args: [[0.1, 0.2, 0.3], 10],\n * timeout: 30000,\n * };\n * ```\n */\n\n/**\n * Special type for serialized Buffer instances.\n * Buffers are converted to base64 strings for transmission.\n */\nexport interface SerializableBuffer {\n __type: 'Buffer';\n data: string; // base64 encoded\n}\n\n/**\n * Special type for serialized Date instances.\n * Dates are converted to ISO 8601 strings for transmission.\n */\nexport interface SerializableDate {\n __type: 'Date';\n iso: string; // ISO 8601 format\n}\n\n/**\n * Special type for serialized Error instances.\n * Errors are converted to structured objects with name, message, stack, and optional code.\n */\nexport interface SerializableError {\n __type: 'Error';\n name: string;\n message: string;\n stack?: string;\n code?: string;\n}\n\n/**\n * Values that can be safely serialized over IPC/network.\n *\n * Supports:\n * - Primitives: null, boolean, number, string\n * - Special types: Buffer, Date, Error\n * - Collections: Array, Object\n *\n * Does NOT support:\n * - Functions\n * - Symbols (except as object keys after serialization)\n * - WeakMap/WeakSet\n * - Circular references (will be detected and throw error)\n */\nexport type SerializableValue =\n | null\n | boolean\n | number\n | string\n | SerializableBuffer\n | SerializableDate\n | SerializableError\n | SerializableArray\n | SerializableObject;\n\n/**\n * Serializable array - all elements must be SerializableValue\n */\nexport type SerializableArray = SerializableValue[];\n\n/**\n * Serializable object - all values must be SerializableValue\n */\nexport type SerializableObject = { [key: string]: SerializableValue };\n\n/**\n * Adapter types supported by the IPC protocol.\n *\n * These correspond to the adapters available in PlatformContainer:\n * - vectorStore: IVectorStore\n * - cache: ICache\n * - llm: ILLM\n * - embeddings: IEmbeddings\n * - storage: IStorage\n * - logger: ILogger\n * - analytics: IAnalytics\n * - eventBus: IEventBus\n * - invoke: IInvoke\n * - artifacts: IArtifacts\n */\nexport type AdapterType =\n | 'vectorStore'\n | 'cache'\n | 'config'\n | 'llm'\n | 'embeddings'\n | 'storage'\n | 'logger'\n | 'analytics'\n | 'eventBus'\n | 'invoke'\n | 'artifacts'\n | 'database.document'\n | 'database.sql';\n\n/**\n * Execution context for adapter calls.\n *\n * Used for tracing, debugging, security validation, and metrics.\n * All fields are optional to maintain backward compatibility.\n */\nexport interface AdapterCallContext {\n /** Trace ID for distributed tracing (spans entire CLI → Worker → Adapter → Service flow) */\n traceId?: string;\n /** Session ID for user session tracking */\n sessionId?: string;\n /** Plugin ID making the adapter call */\n pluginId?: string;\n /** Workspace ID for multi-tenant scenarios */\n workspaceId?: string;\n /** Tenant ID for multi-tenant quota enforcement */\n tenantId?: string;\n /** Plugin permissions snapshot (for adapter-level validation) */\n permissions?: {\n /** Allowed adapter access (e.g., ['vectorStore', 'cache']) */\n adapters?: string[];\n /** Allowed storage paths (e.g., ['.kb/**', 'docs/**']) */\n storagePaths?: string[];\n /** Allowed network hosts (e.g., ['api.openai.com']) */\n networkHosts?: string[];\n };\n}\n\n/**\n * IPC protocol version.\n *\n * Version history:\n * - v1: Initial implementation (requestId, adapter, method, args, timeout)\n * - v2: Added context (traceId, pluginId, sessionId, tenantId, permissions)\n *\n * When making breaking changes:\n * 1. Increment version\n * 2. Update IPCServer to handle both old and new versions\n * 3. Update ADR-0038 with migration guide\n */\nexport const IPC_PROTOCOL_VERSION = 2;\n\n/**\n * Adapter method call that can be sent over IPC.\n *\n * Represents a request from child process to parent process\n * to execute a method on an adapter.\n *\n * @example\n * ```typescript\n * const call: AdapterCall = {\n * version: 2,\n * type: 'adapter:call',\n * requestId: 'uuid-123',\n * adapter: 'vectorStore',\n * method: 'search',\n * args: [[0.1, 0.2, 0.3], 10, { collectionId: 'docs' }],\n * timeout: 30000,\n * context: {\n * traceId: 'trace-abc',\n * pluginId: '@kb-labs/mind',\n * sessionId: 'session-xyz',\n * },\n * };\n * ```\n */\nexport interface AdapterCall {\n /** Protocol version for backward compatibility */\n version: number;\n type: 'adapter:call';\n /** Unique request ID to match with response */\n requestId: string;\n /** Adapter to call */\n adapter: AdapterType;\n /** Method name to call on adapter */\n method: string;\n /** Serialized method arguments */\n args: SerializableValue[];\n /** Optional timeout in milliseconds (default: 30000) */\n timeout?: number;\n /** Optional execution context for tracing, debugging, security (v2+) */\n context?: AdapterCallContext;\n}\n\n/**\n * Response from adapter method call.\n *\n * Represents a response from parent process back to child process\n * after executing an adapter method.\n *\n * Either `result` or `error` will be present, never both.\n *\n * @example Success:\n * ```typescript\n * const response: AdapterResponse = {\n * type: 'adapter:response',\n * requestId: 'uuid-123',\n * result: [{ id: '1', score: 0.95, metadata: {} }],\n * };\n * ```\n *\n * @example Error:\n * ```typescript\n * const response: AdapterResponse = {\n * type: 'adapter:response',\n * requestId: 'uuid-123',\n * error: {\n * __type: 'Error',\n * name: 'VectorStoreError',\n * message: 'Collection not found',\n * stack: '...',\n * },\n * };\n * ```\n */\nexport interface AdapterResponse {\n type: 'adapter:response';\n /** Request ID this response corresponds to */\n requestId: string;\n /** Serialized result (if successful) */\n result?: SerializableValue;\n /** Serialized error (if failed) */\n error?: SerializableError;\n}\n\n/**\n * All possible IPC messages.\n *\n * Child → Parent: AdapterCall\n * Parent → Child: AdapterResponse\n */\nexport type IPCMessage = AdapterCall | AdapterResponse;\n\n/**\n * Type guard to check if message is an AdapterCall.\n *\n * Supports both v1 (no version field) and v2+ (with version field)\n * for backward compatibility.\n */\nexport function isAdapterCall(msg: unknown): msg is AdapterCall {\n if (\n typeof msg !== 'object' ||\n msg === null ||\n (msg as any).type !== 'adapter:call' ||\n typeof (msg as any).requestId !== 'string' ||\n typeof (msg as any).adapter !== 'string' ||\n typeof (msg as any).method !== 'string' ||\n !Array.isArray((msg as any).args)\n ) {\n return false;\n }\n\n // If version field is present, it must be a number\n if ('version' in (msg as any) && typeof (msg as any).version !== 'number') {\n return false;\n }\n\n // v1 messages (no version field) are auto-upgraded to v2 by adding version: 1\n if (!('version' in (msg as any))) {\n (msg as any).version = 1; // Auto-upgrade legacy messages\n }\n\n return true;\n}\n\n/**\n * Type guard to check if message is an AdapterResponse.\n */\nexport function isAdapterResponse(msg: unknown): msg is AdapterResponse {\n return (\n typeof msg === 'object' &&\n msg !== null &&\n (msg as any).type === 'adapter:response' &&\n typeof (msg as any).requestId === 'string'\n );\n}\n\n/**\n * Error thrown when serialization fails.\n */\nexport class SerializationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'SerializationError';\n }\n}\n\n/**\n * Error thrown when deserialization fails.\n */\nexport class DeserializationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'DeserializationError';\n }\n}\n","/**\n * @module @kb-labs/core-platform/serializable\n * Serializer for cross-process communication.\n *\n * Handles serialization/deserialization of complex types:\n * - Buffer (to/from base64)\n * - Date (to/from ISO 8601)\n * - Error (with stack traces)\n * - Circular reference detection\n *\n * @example\n * ```typescript\n * import { serialize, deserialize } from '@kb-labs/core-platform/serializable';\n *\n * const data = {\n * buffer: Buffer.from('hello'),\n * date: new Date(),\n * error: new Error('test'),\n * nested: { values: [1, 2, 3] },\n * };\n *\n * const serialized = serialize(data);\n * const deserialized = deserialize(serialized);\n * ```\n */\n\nimport type {\n SerializableValue,\n SerializableBuffer,\n SerializableDate,\n SerializableError,\n SerializableArray,\n SerializableObject} from './types';\nimport {\n SerializationError,\n DeserializationError,\n} from './types';\n\n/**\n * Serialize value for IPC transmission.\n *\n * Handles special types:\n * - Buffer → base64 string\n * - Date → ISO 8601 string\n * - Error → structured object with stack\n * - Detects and throws on circular references\n *\n * @param value - Value to serialize\n * @returns Serialized value safe for JSON transmission\n * @throws SerializationError if value contains unsupported types or circular refs\n *\n * @example\n * ```typescript\n * const result = serialize({\n * buf: Buffer.from('hello'),\n * date: new Date('2025-01-01'),\n * error: new Error('test'),\n * });\n * // result = {\n * // buf: { __type: 'Buffer', data: 'aGVsbG8=' },\n * // date: { __type: 'Date', iso: '2025-01-01T00:00:00.000Z' },\n * // error: { __type: 'Error', name: 'Error', message: 'test', stack: '...' },\n * // }\n * ```\n */\nexport function serialize(value: unknown): SerializableValue {\n const seen = new WeakSet<object>();\n return serializeValue(value, seen);\n}\n\n/**\n * Internal serialization with circular reference tracking.\n */\nfunction serializeValue(value: unknown, seen: WeakSet<object>): SerializableValue {\n // Primitives\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {\n return value;\n }\n\n // Check for circular references\n if (typeof value === 'object') {\n if (seen.has(value)) {\n throw new SerializationError('Circular reference detected');\n }\n seen.add(value);\n }\n\n // Buffer → base64\n if (Buffer.isBuffer(value)) {\n return {\n __type: 'Buffer',\n data: value.toString('base64'),\n } as SerializableBuffer;\n }\n\n // Date → ISO string\n if (value instanceof Date) {\n if (isNaN(value.getTime())) {\n throw new SerializationError('Cannot serialize invalid Date');\n }\n return {\n __type: 'Date',\n iso: value.toISOString(),\n } as SerializableDate;\n }\n\n // Error → structured\n if (value instanceof Error) {\n return {\n __type: 'Error',\n name: value.name,\n message: value.message,\n stack: value.stack,\n code: (value as any).code,\n } as SerializableError;\n }\n\n // Array\n if (Array.isArray(value)) {\n return value.map((item) => serializeValue(item, seen)) as SerializableArray;\n }\n\n // Plain object\n if (typeof value === 'object' && value.constructor === Object) {\n const result: SerializableObject = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = serializeValue(val, seen);\n }\n return result;\n }\n\n // Unsupported type\n throw new SerializationError(\n `Cannot serialize type: ${typeof value} (constructor: ${value.constructor?.name || 'unknown'})`\n );\n}\n\n/**\n * Deserialize value from IPC transmission.\n *\n * Reconstructs special types:\n * - base64 string → Buffer\n * - ISO 8601 string → Date\n * - structured object → Error (with stack)\n *\n * @param value - Serialized value\n * @returns Original value reconstructed from serialization\n * @throws DeserializationError if value format is invalid\n *\n * @example\n * ```typescript\n * const serialized = {\n * buf: { __type: 'Buffer', data: 'aGVsbG8=' },\n * date: { __type: 'Date', iso: '2025-01-01T00:00:00.000Z' },\n * error: { __type: 'Error', name: 'Error', message: 'test' },\n * };\n *\n * const result = deserialize(serialized);\n * // result = {\n * // buf: Buffer.from('hello'),\n * // date: new Date('2025-01-01'),\n * // error: Error('test'),\n * // }\n * ```\n */\nexport function deserialize(value: SerializableValue): unknown {\n // Primitives\n if (value === null) {\n return null;\n }\n\n if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {\n return value;\n }\n\n // Must be object/array at this point\n if (typeof value !== 'object') {\n throw new DeserializationError(`Invalid serialized value type: ${typeof value}`);\n }\n\n // Check for special types\n const obj = value as any;\n\n // Buffer\n if (obj.__type === 'Buffer') {\n if (typeof obj.data !== 'string') {\n throw new DeserializationError('Invalid SerializableBuffer: missing or invalid data field');\n }\n try {\n return Buffer.from(obj.data, 'base64');\n } catch (error) {\n throw new DeserializationError(`Failed to decode Buffer: ${error}`);\n }\n }\n\n // Date\n if (obj.__type === 'Date') {\n if (typeof obj.iso !== 'string') {\n throw new DeserializationError('Invalid SerializableDate: missing or invalid iso field');\n }\n const date = new Date(obj.iso);\n if (isNaN(date.getTime())) {\n throw new DeserializationError(`Invalid ISO date string: ${obj.iso}`);\n }\n return date;\n }\n\n // Error\n if (obj.__type === 'Error') {\n if (typeof obj.message !== 'string') {\n throw new DeserializationError('Invalid SerializableError: missing or invalid message field');\n }\n const error = new Error(obj.message);\n if (typeof obj.name === 'string') {\n error.name = obj.name;\n }\n if (typeof obj.stack === 'string') {\n error.stack = obj.stack;\n }\n if (obj.code !== undefined) {\n (error as any).code = obj.code;\n }\n return error;\n }\n\n // Array\n if (Array.isArray(value)) {\n return value.map((item) => deserialize(item));\n }\n\n // Plain object\n const result: any = {};\n for (const [key, val] of Object.entries(value)) {\n result[key] = deserialize(val);\n }\n return result;\n}\n\n/**\n * Serialize multiple values (convenience for adapter method args).\n *\n * @example\n * ```typescript\n * const args = serializeArgs([\n * Buffer.from('hello'),\n * new Date(),\n * { nested: { value: 42 } },\n * ]);\n * ```\n */\nexport function serializeArgs(args: unknown[]): SerializableValue[] {\n return args.map((arg) => serialize(arg));\n}\n\n/**\n * Deserialize multiple values (convenience for adapter method args).\n *\n * @example\n * ```typescript\n * const args = deserializeArgs([\n * { __type: 'Buffer', data: 'aGVsbG8=' },\n * { __type: 'Date', iso: '2025-01-01T00:00:00.000Z' },\n * { nested: { value: 42 } },\n * ]);\n * ```\n */\nexport function deserializeArgs(args: SerializableValue[]): unknown[] {\n return args.map((arg) => deserialize(arg));\n}\n"]}