@quilltap/plugin-types 2.13.0 → 2.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.14.0] - 2026-11-30
9
+
10
+ ### Added
11
+
12
+ - **Host services** — the one definition of what the Quilltap host provides to the plugins it loads. Until now the contract existed only as two `globalThis` keys, with their names and value types written out separately in `@quilltap/plugin-utils` and in the host.
13
+ - `QuilltapHostServices` (`createLogger`, `appVersion`), `PluginLoggerFactory`, and `PluginLoggerWithChild` (moved here from `@quilltap/plugin-utils`, which still exports it).
14
+ - `readHostServices()` — the services currently available. Each is optional: outside Quilltap, or under a host older than a service, it is simply missing.
15
+ - `provideHostServices(services)` and `withdrawHostServices()` — the host's side. Not for plugin use.
16
+ - The two existing keys are unchanged, so every plugin already built keeps working, and a plugin built against this version works under an older host.
17
+
18
+ ### Changed
19
+
20
+ - `PLUGIN_TYPES_VERSION` re-synced to the package version.
21
+
22
+ ## [2.13.1] - 2026-11-26
23
+
24
+ Dependency update only; no code changes.
25
+
26
+ ### Changed
27
+
28
+ - Dev dependency `@types/node` raised to `^24.19.4`.
29
+
8
30
  ## [2.13.0] - 2026-11-20
9
31
 
10
32
  ### Added
package/README.md CHANGED
@@ -115,6 +115,26 @@ logger.warn('Deprecated feature used');
115
115
  logger.error('Failed to connect', { endpoint: 'api.example.com' }, error);
116
116
  ```
117
117
 
118
+ ### Host Services
119
+
120
+ When Quilltap loads a plugin it provides a few services: a logger that writes
121
+ into the application's own log, and the application's version. This package
122
+ holds the one definition of that contract, `QuilltapHostServices`.
123
+
124
+ Plugin authors do not normally read it directly. `createPluginLogger`,
125
+ `getQuilltapVersion` and `getQuilltapUserAgent` in `@quilltap/plugin-utils` do,
126
+ and each falls back sensibly when a service is missing:
127
+
128
+ ```typescript
129
+ import { readHostServices } from '@quilltap/plugin-types';
130
+
131
+ const { createLogger, appVersion } = readHostServices();
132
+ // Either may be undefined: outside Quilltap, or under a host older than the service.
133
+ ```
134
+
135
+ `provideHostServices` and `withdrawHostServices` are the host's side of the
136
+ same contract and are not for plugin use.
137
+
118
138
  ## Type Reference
119
139
 
120
140
  ### LLM Types
@@ -151,6 +171,8 @@ logger.error('Failed to connect', { endpoint: 'api.example.com' }, error);
151
171
  | Type | Description |
152
172
  |------|-------------|
153
173
  | `PluginLogger` | Logger interface |
174
+ | `PluginLoggerWithChild` | A `PluginLogger` that can derive child loggers with extra context |
175
+ | `QuilltapHostServices` | What the host provides to plugins: `createLogger`, `appVersion` |
154
176
  | `LogLevel` | Log level type |
155
177
  | `PluginError` | Base error class |
156
178
  | `ApiKeyError` | API key validation error |
@@ -1 +1 @@
1
- export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, P as PluginError, d as PluginLogger, e as ProviderApiError, R as RateLimitError, T as ToolExecutionError, f as createConsoleLogger, g as createNoopLogger } from '../index-DZbctGgg.mjs';
1
+ export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, P as PluginError, d as PluginLogger, e as PluginLoggerFactory, f as PluginLoggerWithChild, g as ProviderApiError, Q as QuilltapHostServices, R as RateLimitError, T as ToolExecutionError, h as createConsoleLogger, i as createNoopLogger, p as provideHostServices, r as readHostServices, w as withdrawHostServices } from '../index-D3B03G_D.mjs';
@@ -1 +1 @@
1
- export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, P as PluginError, d as PluginLogger, e as ProviderApiError, R as RateLimitError, T as ToolExecutionError, f as createConsoleLogger, g as createNoopLogger } from '../index-DZbctGgg.js';
1
+ export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, P as PluginError, d as PluginLogger, e as PluginLoggerFactory, f as PluginLoggerWithChild, g as ProviderApiError, Q as QuilltapHostServices, R as RateLimitError, T as ToolExecutionError, h as createConsoleLogger, i as createNoopLogger, p as provideHostServices, r as readHostServices, w as withdrawHostServices } from '../index-D3B03G_D.js';
@@ -106,6 +106,43 @@ function createNoopLogger() {
106
106
  };
107
107
  }
108
108
 
109
+ // src/common/host-services.ts
110
+ var HOST_SERVICE_GLOBALS = {
111
+ createLogger: "__quilltap_logger_factory",
112
+ appVersion: "__quilltap_app_version"
113
+ };
114
+ var SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS);
115
+ function hostGlobals() {
116
+ return globalThis;
117
+ }
118
+ function provideHostServices(services) {
119
+ const globals = hostGlobals();
120
+ for (const name of SERVICE_NAMES) {
121
+ if (name in services) {
122
+ globals[HOST_SERVICE_GLOBALS[name]] = services[name];
123
+ }
124
+ }
125
+ }
126
+ function withdrawHostServices() {
127
+ const globals = hostGlobals();
128
+ for (const name of SERVICE_NAMES) {
129
+ globals[HOST_SERVICE_GLOBALS[name]] = void 0;
130
+ }
131
+ }
132
+ function readHostServices() {
133
+ const globals = hostGlobals();
134
+ const services = {};
135
+ const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];
136
+ if (typeof createLogger === "function") {
137
+ services.createLogger = createLogger;
138
+ }
139
+ const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];
140
+ if (typeof appVersion === "string") {
141
+ services.appVersion = appVersion;
142
+ }
143
+ return services;
144
+ }
145
+
109
146
  exports.ApiKeyError = ApiKeyError;
110
147
  exports.AttachmentError = AttachmentError;
111
148
  exports.ConfigurationError = ConfigurationError;
@@ -116,5 +153,8 @@ exports.RateLimitError = RateLimitError;
116
153
  exports.ToolExecutionError = ToolExecutionError;
117
154
  exports.createConsoleLogger = createConsoleLogger;
118
155
  exports.createNoopLogger = createNoopLogger;
156
+ exports.provideHostServices = provideHostServices;
157
+ exports.readHostServices = readHostServices;
158
+ exports.withdrawHostServices = withdrawHostServices;
119
159
  //# sourceMappingURL=index.js.map
120
160
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/common/errors.ts","../../src/common/logger.ts"],"names":[],"mappings":";;;AAWO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,WAAA,GAAN,cAA0B,WAAA,CAAY;AAAA,EAC3C,WAAA,CAAY,SAAiB,UAAA,EAAqB;AAChD,IAAA,KAAA,CAAM,OAAA,EAAS,iBAAiB,UAAU,CAAA;AAC1C,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,gBAAA,GAAN,cAA+B,WAAA,CAAY;AAAA,EAChD,WAAA,CACE,OAAA,EACgB,UAAA,EACA,QAAA,EAChB,UAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,sBAAsB,UAAU,CAAA;AAJ/B,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AAIhB,IAAA,IAAA,CAAK,IAAA,GAAO,kBAAA;AAAA,EACd;AACF;AAoCO,IAAM,cAAA,GAAN,cAA6B,gBAAA,CAAiB;AAAA,EAGnD,WAAA,CACE,OAAA,EACgB,UAAA,EAChB,UAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,GAAA,EAAK,MAAA,EAAW,UAAU,CAAA;AAHzB,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAJlB,IAAA,IAA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A,IAAI,SAAA,CAAU,MAAM,CAAA,EAAG;AACrB,QAAA,OAAA,CAAQ,IAAA,CAAK,IAAI,MAAM,CAAA,EAAA,EAAK,OAAO,CAAA,EAAG,aAAA,CAAc,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,MAChE;AAAA,IACF,CAAA;AAAA,IAEA,KAAA,EAAO,CAAC,OAAA,EAAiB,OAAA,EAAsB,KAAA,KAAwB;AACrE,MAAA,IAAI,SAAA,CAAU,OAAO,CAAA,EAAG;AACtB,QAAA,OAAA,CAAQ,KAAA;AAAA,UACN,IAAI,MAAM,CAAA,EAAA,EAAK,OAAO,CAAA,EAAG,aAAA,CAAc,OAAO,CAAC,CAAA,CAAA;AAAA,UAC/C,KAAA,GAAQ;AAAA,EAAK,KAAA,CAAM,KAAA,IAAS,KAAA,CAAM,OAAO,CAAA,CAAA,GAAK;AAAA,SAChD;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF;AAOO,SAAS,gBAAA,GAAiC;AAC/C,EAAA,MAAM,OAAO,MAAY;AAAA,EAAC,CAAA;AAC1B,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,IAAA,EAAM,IAAA;AAAA,IACN,IAAA,EAAM,IAAA;AAAA,IACN,KAAA,EAAO;AAAA,GACT;AACF","file":"index.js","sourcesContent":["/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/common/errors.ts","../../src/common/logger.ts","../../src/common/host-services.ts"],"names":[],"mappings":";;;AAWO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,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Y;AACtC,IAAA,QAAA,CAAS,YAAA,GAAe,YAAA;AAAA,EAC1B;AAEA,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,oBAAA,CAAqB,UAAU,CAAA;AAC1D,EAAA,IAAI,OAAO,eAAe,QAAA,EAAU;AAClC,IAAA,QAAA,CAAS,UAAA,GAAa,UAAA;AAAA,EACxB;AAEA,EAAA,OAAO,QAAA;AACT","file":"index.js","sourcesContent":["/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n","/**\n * Host services: what the Quilltap host provides to every plugin it loads.\n *\n * This module is the one definition of that contract — the shape of each\n * service, the name it travels under, and the two functions that write and\n * read it. The host calls {@link provideHostServices}; plugin code (through\n * `@quilltap/plugin-utils`) calls {@link readHostServices}. Nothing else\n * should touch the names below.\n *\n * **Why globals.** A plugin is bundled with its own copy of this package and\n * of `@quilltap/plugin-utils`, so the host and a plugin never share a module\n * instance: a value the host stores in a module variable is invisible to the\n * plugin's copy of that module. `globalThis` is the only object both sides\n * have in common, so that is where the services are handed over.\n *\n * **The names are a wire format.** Every plugin already built reads these\n * exact keys through the copy of plugin-utils it was bundled with, and an\n * older host writes them. Renaming one, or folding them into a single object,\n * would silently cut those plugins off from the host's log and version. Add a\n * service by adding a field and a key; never change an existing one.\n *\n * **Every service is optional to the reader.** A plugin may be running outside\n * Quilltap (a test, a script) or under a host older than the service it wants,\n * so {@link readHostServices} returns only what is actually there and a plugin\n * must have a fallback for each.\n *\n * @module @quilltap/plugin-types/common/host-services\n */\n\nimport type { LogContext, PluginLogger } from './logger';\n\n/**\n * A plugin logger that can derive child loggers carrying extra context.\n */\nexport interface PluginLoggerWithChild extends PluginLogger {\n /**\n * Create a child logger with additional context\n * @param additionalContext Context to merge with the parent's context\n * @returns A new logger with the combined context\n */\n child(additionalContext: LogContext): PluginLoggerWithChild;\n}\n\n/**\n * Creates the logger a named plugin writes through.\n *\n * @param pluginName The plugin's identifier (e.g. `qtap-plugin-openai`)\n */\nexport type PluginLoggerFactory = (pluginName: string) => PluginLoggerWithChild;\n\n/**\n * The services the Quilltap host provides to the plugins it loads.\n */\nexport interface QuilltapHostServices {\n /**\n * Creates a logger that writes into the host's own log, tagged with the\n * plugin's name.\n */\n createLogger: PluginLoggerFactory;\n\n /**\n * The host application's version (e.g. `4.15.0`), so a plugin can identify\n * the application in the requests it makes.\n */\n appVersion: string;\n}\n\n/**\n * The `globalThis` key each service travels under. A wire format — see the\n * module notes before changing anything here.\n */\nconst HOST_SERVICE_GLOBALS: { readonly [Name in keyof QuilltapHostServices]: string } = {\n createLogger: '__quilltap_logger_factory',\n appVersion: '__quilltap_app_version',\n};\n\nconst SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS) as Array<keyof QuilltapHostServices>;\n\nfunction hostGlobals(): Record<string, unknown> {\n return globalThis as unknown as Record<string, unknown>;\n}\n\n/**\n * Provide host services to plugins.\n *\n * Called by the Quilltap host before it loads any plugin. Only the services\n * named in the argument are touched, so they can be provided one at a time; a\n * service passed as `undefined` is withdrawn.\n *\n * **Host API — not for plugin use.**\n *\n * @param services The services to provide\n */\nexport function provideHostServices(services: Partial<QuilltapHostServices>): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n if (name in services) {\n globals[HOST_SERVICE_GLOBALS[name]] = services[name];\n }\n }\n}\n\n/**\n * Withdraw every host service.\n *\n * Called by the host when it unloads the plugin system, and by tests.\n *\n * **Host API — not for plugin use.**\n */\nexport function withdrawHostServices(): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n globals[HOST_SERVICE_GLOBALS[name]] = undefined;\n }\n}\n\n/**\n * Read the services the host has provided.\n *\n * Returns only the services that are present and well-formed. Outside\n * Quilltap the result is empty, and under an older host a newer service is\n * simply missing — check each one before using it.\n *\n * @returns The services currently available\n */\nexport function readHostServices(): Partial<QuilltapHostServices> {\n const globals = hostGlobals();\n const services: Partial<QuilltapHostServices> = {};\n\n const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];\n if (typeof createLogger === 'function') {\n services.createLogger = createLogger as PluginLoggerFactory;\n }\n\n const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];\n if (typeof appVersion === 'string') {\n services.appVersion = appVersion;\n }\n\n return services;\n}\n"]}
@@ -104,6 +104,43 @@ function createNoopLogger() {
104
104
  };
105
105
  }
106
106
 
107
- export { ApiKeyError, AttachmentError, ConfigurationError, ModelNotFoundError, PluginError, ProviderApiError, RateLimitError, ToolExecutionError, createConsoleLogger, createNoopLogger };
107
+ // src/common/host-services.ts
108
+ var HOST_SERVICE_GLOBALS = {
109
+ createLogger: "__quilltap_logger_factory",
110
+ appVersion: "__quilltap_app_version"
111
+ };
112
+ var SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS);
113
+ function hostGlobals() {
114
+ return globalThis;
115
+ }
116
+ function provideHostServices(services) {
117
+ const globals = hostGlobals();
118
+ for (const name of SERVICE_NAMES) {
119
+ if (name in services) {
120
+ globals[HOST_SERVICE_GLOBALS[name]] = services[name];
121
+ }
122
+ }
123
+ }
124
+ function withdrawHostServices() {
125
+ const globals = hostGlobals();
126
+ for (const name of SERVICE_NAMES) {
127
+ globals[HOST_SERVICE_GLOBALS[name]] = void 0;
128
+ }
129
+ }
130
+ function readHostServices() {
131
+ const globals = hostGlobals();
132
+ const services = {};
133
+ const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];
134
+ if (typeof createLogger === "function") {
135
+ services.createLogger = createLogger;
136
+ }
137
+ const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];
138
+ if (typeof appVersion === "string") {
139
+ services.appVersion = appVersion;
140
+ }
141
+ return services;
142
+ }
143
+
144
+ export { ApiKeyError, AttachmentError, ConfigurationError, ModelNotFoundError, PluginError, ProviderApiError, RateLimitError, ToolExecutionError, createConsoleLogger, createNoopLogger, provideHostServices, readHostServices, withdrawHostServices };
108
145
  //# sourceMappingURL=index.mjs.map
109
146
  //# sourceMappingURL=index.mjs.map
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aAAA,CAAc,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,MAChE;AAAA,IACF,CAAA;AAAA,IAEA,KAAA,EAAO,CAAC,OAAA,EAAiB,OAAA,EAAsB,KAAA,KAAwB;AACrE,MAAA,IAAI,SAAA,CAAU,OAAO,CAAA,EAAG;AACtB,QAAA,OAAA,CAAQ,KAAA;AAAA,UACN,IAAI,MAAM,CAAA,EAAA,EAAK,OAAO,CAAA,EAAG,aAAA,CAAc,OAAO,CAAC,CAAA,CAAA;AAAA,UAC/C,KAAA,GAAQ;AAAA,EAAK,KAAA,CAAM,KAAA,IAAS,KAAA,CAAM,OAAO,CAAA,CAAA,GAAK;AAAA,SAChD;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF;AAOO,SAAS,gBAAA,GAAiC;AAC/C,EAAA,MAAM,OAAO,MAAY;AAAA,EAAC,CAAA;AAC1B,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,IAAA,EAAM,IAAA;AAAA,IACN,IAAA,EAAM,IAAA;AAAA,IACN,KAAA,EAAO;AAAA,GACT;AACF","file":"index.mjs","sourcesContent":["/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n"]}
1
+ {"version":3,"sources":["../../src/common/errors.ts","../../src/common/logger.ts","../../src/common/host-services.ts"],"names":[],"mappings":";AAWO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,WAAA,GAAN,cAA0B,WAAA,CAAY;AAAA,EAC3C,WAAA,CAAY,SAAiB,UAAA,EAAqB;AAChD,IAAA,K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AA;AAC1D,EAAA,IAAI,OAAO,eAAe,QAAA,EAAU;AAClC,IAAA,QAAA,CAAS,UAAA,GAAa,UAAA;AAAA,EACxB;AAEA,EAAA,OAAO,QAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n","/**\n * Host services: what the Quilltap host provides to every plugin it loads.\n *\n * This module is the one definition of that contract — the shape of each\n * service, the name it travels under, and the two functions that write and\n * read it. The host calls {@link provideHostServices}; plugin code (through\n * `@quilltap/plugin-utils`) calls {@link readHostServices}. Nothing else\n * should touch the names below.\n *\n * **Why globals.** A plugin is bundled with its own copy of this package and\n * of `@quilltap/plugin-utils`, so the host and a plugin never share a module\n * instance: a value the host stores in a module variable is invisible to the\n * plugin's copy of that module. `globalThis` is the only object both sides\n * have in common, so that is where the services are handed over.\n *\n * **The names are a wire format.** Every plugin already built reads these\n * exact keys through the copy of plugin-utils it was bundled with, and an\n * older host writes them. Renaming one, or folding them into a single object,\n * would silently cut those plugins off from the host's log and version. Add a\n * service by adding a field and a key; never change an existing one.\n *\n * **Every service is optional to the reader.** A plugin may be running outside\n * Quilltap (a test, a script) or under a host older than the service it wants,\n * so {@link readHostServices} returns only what is actually there and a plugin\n * must have a fallback for each.\n *\n * @module @quilltap/plugin-types/common/host-services\n */\n\nimport type { LogContext, PluginLogger } from './logger';\n\n/**\n * A plugin logger that can derive child loggers carrying extra context.\n */\nexport interface PluginLoggerWithChild extends PluginLogger {\n /**\n * Create a child logger with additional context\n * @param additionalContext Context to merge with the parent's context\n * @returns A new logger with the combined context\n */\n child(additionalContext: LogContext): PluginLoggerWithChild;\n}\n\n/**\n * Creates the logger a named plugin writes through.\n *\n * @param pluginName The plugin's identifier (e.g. `qtap-plugin-openai`)\n */\nexport type PluginLoggerFactory = (pluginName: string) => PluginLoggerWithChild;\n\n/**\n * The services the Quilltap host provides to the plugins it loads.\n */\nexport interface QuilltapHostServices {\n /**\n * Creates a logger that writes into the host's own log, tagged with the\n * plugin's name.\n */\n createLogger: PluginLoggerFactory;\n\n /**\n * The host application's version (e.g. `4.15.0`), so a plugin can identify\n * the application in the requests it makes.\n */\n appVersion: string;\n}\n\n/**\n * The `globalThis` key each service travels under. A wire format — see the\n * module notes before changing anything here.\n */\nconst HOST_SERVICE_GLOBALS: { readonly [Name in keyof QuilltapHostServices]: string } = {\n createLogger: '__quilltap_logger_factory',\n appVersion: '__quilltap_app_version',\n};\n\nconst SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS) as Array<keyof QuilltapHostServices>;\n\nfunction hostGlobals(): Record<string, unknown> {\n return globalThis as unknown as Record<string, unknown>;\n}\n\n/**\n * Provide host services to plugins.\n *\n * Called by the Quilltap host before it loads any plugin. Only the services\n * named in the argument are touched, so they can be provided one at a time; a\n * service passed as `undefined` is withdrawn.\n *\n * **Host API — not for plugin use.**\n *\n * @param services The services to provide\n */\nexport function provideHostServices(services: Partial<QuilltapHostServices>): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n if (name in services) {\n globals[HOST_SERVICE_GLOBALS[name]] = services[name];\n }\n }\n}\n\n/**\n * Withdraw every host service.\n *\n * Called by the host when it unloads the plugin system, and by tests.\n *\n * **Host API — not for plugin use.**\n */\nexport function withdrawHostServices(): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n globals[HOST_SERVICE_GLOBALS[name]] = undefined;\n }\n}\n\n/**\n * Read the services the host has provided.\n *\n * Returns only the services that are present and well-formed. Outside\n * Quilltap the result is empty, and under an older host a newer service is\n * simply missing — check each one before using it.\n *\n * @returns The services currently available\n */\nexport function readHostServices(): Partial<QuilltapHostServices> {\n const globals = hostGlobals();\n const services: Partial<QuilltapHostServices> = {};\n\n const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];\n if (typeof createLogger === 'function') {\n services.createLogger = createLogger as PluginLoggerFactory;\n }\n\n const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];\n if (typeof appVersion === 'string') {\n services.appVersion = appVersion;\n }\n\n return services;\n}\n"]}
@@ -177,5 +177,97 @@ declare function createConsoleLogger(prefix: string, minLevel?: LogLevel): Plugi
177
177
  */
178
178
  declare function createNoopLogger(): PluginLogger;
179
179
 
180
- export { ApiKeyError as A, ConfigurationError as C, ModelNotFoundError as M, PluginError as P, RateLimitError as R, ToolExecutionError as T, AttachmentError as a, ModerationRejectionError as c, ProviderApiError as e, createConsoleLogger as f, createNoopLogger as g };
181
- export type { LogContext as L, LogLevel as b, PluginLogger as d };
180
+ /**
181
+ * Host services: what the Quilltap host provides to every plugin it loads.
182
+ *
183
+ * This module is the one definition of that contract — the shape of each
184
+ * service, the name it travels under, and the two functions that write and
185
+ * read it. The host calls {@link provideHostServices}; plugin code (through
186
+ * `@quilltap/plugin-utils`) calls {@link readHostServices}. Nothing else
187
+ * should touch the names below.
188
+ *
189
+ * **Why globals.** A plugin is bundled with its own copy of this package and
190
+ * of `@quilltap/plugin-utils`, so the host and a plugin never share a module
191
+ * instance: a value the host stores in a module variable is invisible to the
192
+ * plugin's copy of that module. `globalThis` is the only object both sides
193
+ * have in common, so that is where the services are handed over.
194
+ *
195
+ * **The names are a wire format.** Every plugin already built reads these
196
+ * exact keys through the copy of plugin-utils it was bundled with, and an
197
+ * older host writes them. Renaming one, or folding them into a single object,
198
+ * would silently cut those plugins off from the host's log and version. Add a
199
+ * service by adding a field and a key; never change an existing one.
200
+ *
201
+ * **Every service is optional to the reader.** A plugin may be running outside
202
+ * Quilltap (a test, a script) or under a host older than the service it wants,
203
+ * so {@link readHostServices} returns only what is actually there and a plugin
204
+ * must have a fallback for each.
205
+ *
206
+ * @module @quilltap/plugin-types/common/host-services
207
+ */
208
+
209
+ /**
210
+ * A plugin logger that can derive child loggers carrying extra context.
211
+ */
212
+ interface PluginLoggerWithChild extends PluginLogger {
213
+ /**
214
+ * Create a child logger with additional context
215
+ * @param additionalContext Context to merge with the parent's context
216
+ * @returns A new logger with the combined context
217
+ */
218
+ child(additionalContext: LogContext): PluginLoggerWithChild;
219
+ }
220
+ /**
221
+ * Creates the logger a named plugin writes through.
222
+ *
223
+ * @param pluginName The plugin's identifier (e.g. `qtap-plugin-openai`)
224
+ */
225
+ type PluginLoggerFactory = (pluginName: string) => PluginLoggerWithChild;
226
+ /**
227
+ * The services the Quilltap host provides to the plugins it loads.
228
+ */
229
+ interface QuilltapHostServices {
230
+ /**
231
+ * Creates a logger that writes into the host's own log, tagged with the
232
+ * plugin's name.
233
+ */
234
+ createLogger: PluginLoggerFactory;
235
+ /**
236
+ * The host application's version (e.g. `4.15.0`), so a plugin can identify
237
+ * the application in the requests it makes.
238
+ */
239
+ appVersion: string;
240
+ }
241
+ /**
242
+ * Provide host services to plugins.
243
+ *
244
+ * Called by the Quilltap host before it loads any plugin. Only the services
245
+ * named in the argument are touched, so they can be provided one at a time; a
246
+ * service passed as `undefined` is withdrawn.
247
+ *
248
+ * **Host API — not for plugin use.**
249
+ *
250
+ * @param services The services to provide
251
+ */
252
+ declare function provideHostServices(services: Partial<QuilltapHostServices>): void;
253
+ /**
254
+ * Withdraw every host service.
255
+ *
256
+ * Called by the host when it unloads the plugin system, and by tests.
257
+ *
258
+ * **Host API — not for plugin use.**
259
+ */
260
+ declare function withdrawHostServices(): void;
261
+ /**
262
+ * Read the services the host has provided.
263
+ *
264
+ * Returns only the services that are present and well-formed. Outside
265
+ * Quilltap the result is empty, and under an older host a newer service is
266
+ * simply missing — check each one before using it.
267
+ *
268
+ * @returns The services currently available
269
+ */
270
+ declare function readHostServices(): Partial<QuilltapHostServices>;
271
+
272
+ export { ApiKeyError as A, ConfigurationError as C, ModelNotFoundError as M, PluginError as P, RateLimitError as R, ToolExecutionError as T, AttachmentError as a, ModerationRejectionError as c, ProviderApiError as g, createConsoleLogger as h, createNoopLogger as i, provideHostServices as p, readHostServices as r, withdrawHostServices as w };
273
+ export type { LogContext as L, QuilltapHostServices as Q, LogLevel as b, PluginLogger as d, PluginLoggerFactory as e, PluginLoggerWithChild as f };
@@ -177,5 +177,97 @@ declare function createConsoleLogger(prefix: string, minLevel?: LogLevel): Plugi
177
177
  */
178
178
  declare function createNoopLogger(): PluginLogger;
179
179
 
180
- export { ApiKeyError as A, ConfigurationError as C, ModelNotFoundError as M, PluginError as P, RateLimitError as R, ToolExecutionError as T, AttachmentError as a, ModerationRejectionError as c, ProviderApiError as e, createConsoleLogger as f, createNoopLogger as g };
181
- export type { LogContext as L, LogLevel as b, PluginLogger as d };
180
+ /**
181
+ * Host services: what the Quilltap host provides to every plugin it loads.
182
+ *
183
+ * This module is the one definition of that contract — the shape of each
184
+ * service, the name it travels under, and the two functions that write and
185
+ * read it. The host calls {@link provideHostServices}; plugin code (through
186
+ * `@quilltap/plugin-utils`) calls {@link readHostServices}. Nothing else
187
+ * should touch the names below.
188
+ *
189
+ * **Why globals.** A plugin is bundled with its own copy of this package and
190
+ * of `@quilltap/plugin-utils`, so the host and a plugin never share a module
191
+ * instance: a value the host stores in a module variable is invisible to the
192
+ * plugin's copy of that module. `globalThis` is the only object both sides
193
+ * have in common, so that is where the services are handed over.
194
+ *
195
+ * **The names are a wire format.** Every plugin already built reads these
196
+ * exact keys through the copy of plugin-utils it was bundled with, and an
197
+ * older host writes them. Renaming one, or folding them into a single object,
198
+ * would silently cut those plugins off from the host's log and version. Add a
199
+ * service by adding a field and a key; never change an existing one.
200
+ *
201
+ * **Every service is optional to the reader.** A plugin may be running outside
202
+ * Quilltap (a test, a script) or under a host older than the service it wants,
203
+ * so {@link readHostServices} returns only what is actually there and a plugin
204
+ * must have a fallback for each.
205
+ *
206
+ * @module @quilltap/plugin-types/common/host-services
207
+ */
208
+
209
+ /**
210
+ * A plugin logger that can derive child loggers carrying extra context.
211
+ */
212
+ interface PluginLoggerWithChild extends PluginLogger {
213
+ /**
214
+ * Create a child logger with additional context
215
+ * @param additionalContext Context to merge with the parent's context
216
+ * @returns A new logger with the combined context
217
+ */
218
+ child(additionalContext: LogContext): PluginLoggerWithChild;
219
+ }
220
+ /**
221
+ * Creates the logger a named plugin writes through.
222
+ *
223
+ * @param pluginName The plugin's identifier (e.g. `qtap-plugin-openai`)
224
+ */
225
+ type PluginLoggerFactory = (pluginName: string) => PluginLoggerWithChild;
226
+ /**
227
+ * The services the Quilltap host provides to the plugins it loads.
228
+ */
229
+ interface QuilltapHostServices {
230
+ /**
231
+ * Creates a logger that writes into the host's own log, tagged with the
232
+ * plugin's name.
233
+ */
234
+ createLogger: PluginLoggerFactory;
235
+ /**
236
+ * The host application's version (e.g. `4.15.0`), so a plugin can identify
237
+ * the application in the requests it makes.
238
+ */
239
+ appVersion: string;
240
+ }
241
+ /**
242
+ * Provide host services to plugins.
243
+ *
244
+ * Called by the Quilltap host before it loads any plugin. Only the services
245
+ * named in the argument are touched, so they can be provided one at a time; a
246
+ * service passed as `undefined` is withdrawn.
247
+ *
248
+ * **Host API — not for plugin use.**
249
+ *
250
+ * @param services The services to provide
251
+ */
252
+ declare function provideHostServices(services: Partial<QuilltapHostServices>): void;
253
+ /**
254
+ * Withdraw every host service.
255
+ *
256
+ * Called by the host when it unloads the plugin system, and by tests.
257
+ *
258
+ * **Host API — not for plugin use.**
259
+ */
260
+ declare function withdrawHostServices(): void;
261
+ /**
262
+ * Read the services the host has provided.
263
+ *
264
+ * Returns only the services that are present and well-formed. Outside
265
+ * Quilltap the result is empty, and under an older host a newer service is
266
+ * simply missing — check each one before using it.
267
+ *
268
+ * @returns The services currently available
269
+ */
270
+ declare function readHostServices(): Partial<QuilltapHostServices>;
271
+
272
+ export { ApiKeyError as A, ConfigurationError as C, ModelNotFoundError as M, PluginError as P, RateLimitError as R, ToolExecutionError as T, AttachmentError as a, ModerationRejectionError as c, ProviderApiError as g, createConsoleLogger as h, createNoopLogger as i, provideHostServices as p, readHostServices as r, withdrawHostServices as w };
273
+ export type { LogContext as L, QuilltapHostServices as Q, LogLevel as b, PluginLogger as d, PluginLoggerFactory as e, PluginLoggerWithChild as f };
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ import { U as UniversalTool } from './index-Y_myuqS4.mjs';
2
2
  export { A as AnthropicToolDefinition, a as AttachmentResults, C as CacheUsage, E as EmbeddingOptions, b as EmbeddingProvider, c as EmbeddingResult, F as FileAttachment, G as GeneratedImage, d as GoogleToolDefinition, I as ImageGenParams, e as ImageGenProvider, f as ImageGenResponse, g as ImageLoraSpec, h as ImageOrientation, e as ImageProvider, J as JSONSchemaDefinition, L as LLMMessage, i as LLMParams, T as LLMProvider, j as LLMResponse, k as LocalEmbeddingProvider, l as LocalEmbeddingProviderState, M as ModelMetadata, m as ModelWarning, n as ModelWarningLevel, O as OpenAIToolDefinition, R as ResponseFormat, S as StreamChunk, T as TextProvider, o as TokenUsage, p as ToolCall, q as ToolCallRequest, r as ToolFormatOptions, s as ToolResult, t as isLocalEmbeddingProvider } from './index-Y_myuqS4.mjs';
3
3
  export { CategoryScore, ScoringInput, ScoringProvider, ScoringResult, ScoringTask } from './providers/index.mjs';
4
4
  export { A as AttachmentSupport, C as CheapModelConfig, a as ColorPalette, E as Effects, b as EmbeddedFont, c as EmbeddingModelInfo, F as FontDefinition, I as IconProps, d as ImageGenerationModelInfo, e as ImageLoraSupport, f as ImageOrientationSupport, g as ImageProviderConstraints, h as ImageStyleInfo, i as InstalledPluginInfo, L as LLMProviderPlugin, M as MessageFormatSupport, j as ModelInfo, k as ModerationCategoryResult, l as ModerationProviderConfigRequirements, m as ModerationProviderMetadata, n as ModerationProviderPlugin, o as ModerationProviderPluginExport, p as ModerationResult, O as OrientationMapping, q as OrientationStrategy, P as PluginAuthor, r as PluginCapability, s as PluginCategory, t as PluginCompatibility, u as PluginIconData, v as PluginManifest, w as PluginPermissions, x as PluginStatus, y as ProviderCapabilities, z as ProviderConfig, B as ProviderConfigRequirements, D as ProviderMetadata, G as ProviderOptionDirective, H as ProviderOptionEnumValue, J as ProviderOptionField, K as ProviderOptionFieldType, N as ProviderOptionGroup, Q as ProviderOptionShowIf, R as ProviderOptionsSchema, S as ProviderOptionsSchemaContext, T as ProviderPluginExport, U as ScoringProviderConfigRequirements, V as ScoringProviderMetadata, W as ScoringProviderPlugin, X as ScoringProviderPluginExport, Y as SearchOutput, Z as SearchProviderConfig, _ as SearchProviderConfigRequirements, $ as SearchProviderMetadata, a0 as SearchProviderPlugin, a1 as SearchProviderPluginExport, a2 as SearchResult, a3 as Spacing, a4 as SubsystemOverrides, a5 as TextProviderPlugin, a6 as ThemeMetadata, a7 as ThemePlugin, a8 as ThemePluginExport, a9 as ThemeTokens, aa as ThinkingTurnRule, ab as ToolFormatType, ac as Typography } from './index-GCLLSju8.mjs';
5
- export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, c as ModerationRejectionError, P as PluginError, d as PluginLogger, e as ProviderApiError, R as RateLimitError, T as ToolExecutionError, f as createConsoleLogger, g as createNoopLogger } from './index-DZbctGgg.mjs';
5
+ export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, c as ModerationRejectionError, P as PluginError, d as PluginLogger, e as PluginLoggerFactory, f as PluginLoggerWithChild, g as ProviderApiError, Q as QuilltapHostServices, R as RateLimitError, T as ToolExecutionError, h as createConsoleLogger, i as createNoopLogger, p as provideHostServices, r as readHostServices, w as withdrawHostServices } from './index-D3B03G_D.mjs';
6
6
 
7
7
  /**
8
8
  * Roleplay Template Plugin Interface types for Quilltap plugin development
@@ -752,7 +752,7 @@ type CharacterPluginDataMap = Record<string, unknown>;
752
752
  * Version of the plugin-types package.
753
753
  * Can be used at runtime to check compatibility.
754
754
  */
755
- declare const PLUGIN_TYPES_VERSION = "2.13.0";
755
+ declare const PLUGIN_TYPES_VERSION = "2.14.0";
756
756
 
757
757
  export { PLUGIN_TYPES_VERSION, UniversalTool };
758
758
  export type { CharacterPluginDataEntry, CharacterPluginDataMap, NarrationDelimiters, RoleplayTemplateConfig, RoleplayTemplateMetadata, RoleplayTemplatePlugin, RoleplayTemplatePluginExport, SystemPromptData, SystemPromptMetadata, SystemPromptPlugin, SystemPromptPluginExport, ToolCallEffect, ToolEffect, ToolExecutionContext, ToolExecutionResult, ToolHierarchyInfo, ToolMetadata, ToolPlugin, ToolPluginExport };
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ import { U as UniversalTool } from './index-Y_myuqS4.js';
2
2
  export { A as AnthropicToolDefinition, a as AttachmentResults, C as CacheUsage, E as EmbeddingOptions, b as EmbeddingProvider, c as EmbeddingResult, F as FileAttachment, G as GeneratedImage, d as GoogleToolDefinition, I as ImageGenParams, e as ImageGenProvider, f as ImageGenResponse, g as ImageLoraSpec, h as ImageOrientation, e as ImageProvider, J as JSONSchemaDefinition, L as LLMMessage, i as LLMParams, T as LLMProvider, j as LLMResponse, k as LocalEmbeddingProvider, l as LocalEmbeddingProviderState, M as ModelMetadata, m as ModelWarning, n as ModelWarningLevel, O as OpenAIToolDefinition, R as ResponseFormat, S as StreamChunk, T as TextProvider, o as TokenUsage, p as ToolCall, q as ToolCallRequest, r as ToolFormatOptions, s as ToolResult, t as isLocalEmbeddingProvider } from './index-Y_myuqS4.js';
3
3
  export { CategoryScore, ScoringInput, ScoringProvider, ScoringResult, ScoringTask } from './providers/index.js';
4
4
  export { A as AttachmentSupport, C as CheapModelConfig, a as ColorPalette, E as Effects, b as EmbeddedFont, c as EmbeddingModelInfo, F as FontDefinition, I as IconProps, d as ImageGenerationModelInfo, e as ImageLoraSupport, f as ImageOrientationSupport, g as ImageProviderConstraints, h as ImageStyleInfo, i as InstalledPluginInfo, L as LLMProviderPlugin, M as MessageFormatSupport, j as ModelInfo, k as ModerationCategoryResult, l as ModerationProviderConfigRequirements, m as ModerationProviderMetadata, n as ModerationProviderPlugin, o as ModerationProviderPluginExport, p as ModerationResult, O as OrientationMapping, q as OrientationStrategy, P as PluginAuthor, r as PluginCapability, s as PluginCategory, t as PluginCompatibility, u as PluginIconData, v as PluginManifest, w as PluginPermissions, x as PluginStatus, y as ProviderCapabilities, z as ProviderConfig, B as ProviderConfigRequirements, D as ProviderMetadata, G as ProviderOptionDirective, H as ProviderOptionEnumValue, J as ProviderOptionField, K as ProviderOptionFieldType, N as ProviderOptionGroup, Q as ProviderOptionShowIf, R as ProviderOptionsSchema, S as ProviderOptionsSchemaContext, T as ProviderPluginExport, U as ScoringProviderConfigRequirements, V as ScoringProviderMetadata, W as ScoringProviderPlugin, X as ScoringProviderPluginExport, Y as SearchOutput, Z as SearchProviderConfig, _ as SearchProviderConfigRequirements, $ as SearchProviderMetadata, a0 as SearchProviderPlugin, a1 as SearchProviderPluginExport, a2 as SearchResult, a3 as Spacing, a4 as SubsystemOverrides, a5 as TextProviderPlugin, a6 as ThemeMetadata, a7 as ThemePlugin, a8 as ThemePluginExport, a9 as ThemeTokens, aa as ThinkingTurnRule, ab as ToolFormatType, ac as Typography } from './index-B4OofyaX.js';
5
- export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, c as ModerationRejectionError, P as PluginError, d as PluginLogger, e as ProviderApiError, R as RateLimitError, T as ToolExecutionError, f as createConsoleLogger, g as createNoopLogger } from './index-DZbctGgg.js';
5
+ export { A as ApiKeyError, a as AttachmentError, C as ConfigurationError, L as LogContext, b as LogLevel, M as ModelNotFoundError, c as ModerationRejectionError, P as PluginError, d as PluginLogger, e as PluginLoggerFactory, f as PluginLoggerWithChild, g as ProviderApiError, Q as QuilltapHostServices, R as RateLimitError, T as ToolExecutionError, h as createConsoleLogger, i as createNoopLogger, p as provideHostServices, r as readHostServices, w as withdrawHostServices } from './index-D3B03G_D.js';
6
6
 
7
7
  /**
8
8
  * Roleplay Template Plugin Interface types for Quilltap plugin development
@@ -752,7 +752,7 @@ type CharacterPluginDataMap = Record<string, unknown>;
752
752
  * Version of the plugin-types package.
753
753
  * Can be used at runtime to check compatibility.
754
754
  */
755
- declare const PLUGIN_TYPES_VERSION = "2.13.0";
755
+ declare const PLUGIN_TYPES_VERSION = "2.14.0";
756
756
 
757
757
  export { PLUGIN_TYPES_VERSION, UniversalTool };
758
758
  export type { CharacterPluginDataEntry, CharacterPluginDataMap, NarrationDelimiters, RoleplayTemplateConfig, RoleplayTemplateMetadata, RoleplayTemplatePlugin, RoleplayTemplatePluginExport, SystemPromptData, SystemPromptMetadata, SystemPromptPlugin, SystemPromptPluginExport, ToolCallEffect, ToolEffect, ToolExecutionContext, ToolExecutionResult, ToolHierarchyInfo, ToolMetadata, ToolPlugin, ToolPluginExport };
package/dist/index.js CHANGED
@@ -119,8 +119,45 @@ function createNoopLogger() {
119
119
  };
120
120
  }
121
121
 
122
+ // src/common/host-services.ts
123
+ var HOST_SERVICE_GLOBALS = {
124
+ createLogger: "__quilltap_logger_factory",
125
+ appVersion: "__quilltap_app_version"
126
+ };
127
+ var SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS);
128
+ function hostGlobals() {
129
+ return globalThis;
130
+ }
131
+ function provideHostServices(services) {
132
+ const globals = hostGlobals();
133
+ for (const name of SERVICE_NAMES) {
134
+ if (name in services) {
135
+ globals[HOST_SERVICE_GLOBALS[name]] = services[name];
136
+ }
137
+ }
138
+ }
139
+ function withdrawHostServices() {
140
+ const globals = hostGlobals();
141
+ for (const name of SERVICE_NAMES) {
142
+ globals[HOST_SERVICE_GLOBALS[name]] = void 0;
143
+ }
144
+ }
145
+ function readHostServices() {
146
+ const globals = hostGlobals();
147
+ const services = {};
148
+ const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];
149
+ if (typeof createLogger === "function") {
150
+ services.createLogger = createLogger;
151
+ }
152
+ const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];
153
+ if (typeof appVersion === "string") {
154
+ services.appVersion = appVersion;
155
+ }
156
+ return services;
157
+ }
158
+
122
159
  // src/index.ts
123
- var PLUGIN_TYPES_VERSION = "2.13.0";
160
+ var PLUGIN_TYPES_VERSION = "2.14.0";
124
161
 
125
162
  exports.ApiKeyError = ApiKeyError;
126
163
  exports.AttachmentError = AttachmentError;
@@ -135,5 +172,8 @@ exports.ToolExecutionError = ToolExecutionError;
135
172
  exports.createConsoleLogger = createConsoleLogger;
136
173
  exports.createNoopLogger = createNoopLogger;
137
174
  exports.isLocalEmbeddingProvider = isLocalEmbeddingProvider;
175
+ exports.provideHostServices = provideHostServices;
176
+ exports.readHostServices = readHostServices;
177
+ exports.withdrawHostServices = withdrawHostServices;
138
178
  //# sourceMappingURL=index.js.map
139
179
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/providers/embedding.ts","../src/common/errors.ts","../src/common/logger.ts","../src/index.ts"],"names":[],"mappings":";;;AAyLO,SAAS,yBACd,QAAA,EACoC;AACpC,EAAA,OAAO,WAAA,IAAe,QAAA,IAAY,WAAA,IAAe,QAAA,IAAY,UAAA,IAAc,QAAA;AAC7E;;;AClLO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,WAAA,GAAN,cAA0B,WAAA,CAAY;AAAA,EAC3C,WAAA,CAAY,SAAiB,UAAA,EAAqB;AAChD,IAAA,KAAA,CAAM,OAAA,EAAS,iBAAiB,UAAU,CAAA;AAC1C,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,gBAAA,GAAN,cAA+B,WAAA,CAAY;AAAA,EAChD,WAAA,CACE,OAAA,EACgB,UAAA,EACA,QAAA,EAChB,UAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,sBAAsB,UAAU,CAAA;AAJ/B,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AACA,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AAA,IACF;AAAA,GACF;AACF;AAOO,SAAS,gBAAA,GAAiC;AAC/C,EAAA,MAAM,OAAO,MAAY;AAAA,EAAC,CAAA;AAC1B,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,IAAA,EAAM,IAAA;AAAA,IACN,IAAA,EAAM,IAAA;AAAA,IACN,KAAA,EAAO;AAAA,GACT;AACF;;;AC4HO,IAAM,oBAAA,GAAuB","file":"index.js","sourcesContent":["/**\n * Embedding Provider — Shape 3: Text -> Vector\n *\n * Send text to an embedding model, receive a numeric vector representation.\n * Used for semantic search, RAG, and similarity matching.\n *\n * @module @quilltap/plugin-types/providers/embedding\n */\n\n/**\n * Result of an embedding operation\n */\nexport interface EmbeddingResult {\n /** The embedding vector (array of floating point numbers) */\n embedding: number[];\n /** The model used to generate the embedding */\n model: string;\n /** Number of dimensions in the embedding vector */\n dimensions: number;\n /** Token usage information (if available) */\n usage?: {\n promptTokens: number;\n totalTokens: number;\n cost?: number;\n };\n}\n\n/**\n * Options for embedding generation\n */\nexport interface EmbeddingOptions {\n /** Desired dimensions for the embedding (if model supports variable dimensions) */\n dimensions?: number;\n}\n\n/**\n * Embedding provider interface — Shape 3: Text -> Vector\n *\n * Sends text to an embedding model and receives a numeric vector\n * representation for use in semantic search, RAG, and similarity matching.\n */\nexport interface EmbeddingProvider {\n /**\n * Generate an embedding for a single text\n *\n * @param text The text to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns The embedding result\n */\n generateEmbedding(\n text: string,\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult>;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns Array of embedding results\n */\n generateBatchEmbeddings?(\n texts: string[],\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult[]>;\n\n /**\n * Get available embedding models\n *\n * @param apiKey The API key for authentication\n * @returns Array of model IDs\n */\n getAvailableModels?(apiKey: string): Promise<string[]>;\n\n /**\n * Check if the provider is available and properly configured\n *\n * @param apiKey Optional API key to validate\n * @returns True if the provider is ready to use\n */\n isAvailable?(apiKey?: string): Promise<boolean>;\n}\n\n/**\n * Serializable state for local embedding providers\n *\n * Used by providers like TF-IDF that maintain vocabulary state\n */\nexport interface LocalEmbeddingProviderState {\n /** The vocabulary as an array of [term, index] pairs */\n vocabulary: [string, number][];\n /** The IDF (Inverse Document Frequency) weights */\n idf: number[];\n /** Average document length across the corpus */\n avgDocLength: number;\n /** Size of the vocabulary */\n vocabularySize: number;\n /** Whether bigrams are included in the vocabulary */\n includeBigrams: boolean;\n /** Timestamp when the vocabulary was fitted */\n fittedAt: string;\n}\n\n/**\n * Local embedding provider interface\n *\n * Extended interface for local/offline embedding providers that\n * maintain vocabulary state (like TF-IDF). These providers don't\n * require API keys and can work entirely offline.\n */\nexport interface LocalEmbeddingProvider extends Omit<EmbeddingProvider, 'generateEmbedding' | 'generateBatchEmbeddings'> {\n /**\n * Generate an embedding for a single text\n * Local providers don't need apiKey parameter\n *\n * @param text The text to embed\n * @returns The embedding result\n */\n generateEmbedding(text: string): EmbeddingResult;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @returns Array of embedding results\n */\n generateBatchEmbeddings(texts: string[]): EmbeddingResult[];\n\n /**\n * Fit the vocabulary on a corpus of documents\n *\n * This method analyzes the corpus to build vocabulary, calculate IDF weights,\n * and other statistics needed for embedding generation.\n *\n * @param documents Array of text documents to analyze\n */\n fitCorpus(documents: string[]): void;\n\n /**\n * Check if the vocabulary has been fitted\n *\n * @returns True if fitCorpus has been called with documents\n */\n isFitted(): boolean;\n\n /**\n * Load state from a serialized representation\n *\n * @param state The serialized provider state\n */\n loadState(state: LocalEmbeddingProviderState): void;\n\n /**\n * Get the current state for serialization\n *\n * @returns The provider state, or null if not fitted\n */\n getState(): LocalEmbeddingProviderState | null;\n\n /**\n * Get the vocabulary size\n *\n * @returns Number of terms in the vocabulary\n */\n getVocabularySize(): number;\n\n /**\n * Get the embedding dimensions\n *\n * @returns Number of dimensions in generated embeddings\n */\n getDimensions(): number;\n}\n\n/**\n * Type guard to check if a provider is a local embedding provider\n */\nexport function isLocalEmbeddingProvider(\n provider: EmbeddingProvider | LocalEmbeddingProvider\n): provider is LocalEmbeddingProvider {\n return 'fitCorpus' in provider && 'loadState' in provider && 'getState' in provider;\n}\n","/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n","/**\n * @quilltap/plugin-types\n *\n * Type definitions for Quilltap plugin development.\n *\n * This package provides TypeScript types and interfaces for building\n * Quilltap plugins, including LLM providers, authentication providers,\n * and utility plugins.\n *\n * @packageDocumentation\n * @module @quilltap/plugin-types\n */\n\n// ============================================================================\n// Provider Interfaces — The Four Canonical Shapes\n// ============================================================================\n\nexport type {\n // Shape 1: Text -> Text\n TextProvider,\n LLMMessage,\n JSONSchemaDefinition,\n ResponseFormat,\n LLMParams,\n LLMResponse,\n StreamChunk,\n\n // Shape 2: Text -> Image\n ImageProvider,\n ImageOrientation,\n ImageGenParams,\n ImageLoraSpec,\n GeneratedImage,\n ImageGenResponse,\n\n // Shape 3: Text -> Vector\n EmbeddingProvider,\n EmbeddingResult,\n EmbeddingOptions,\n LocalEmbeddingProviderState,\n LocalEmbeddingProvider,\n\n // Shape 4: Text + Candidates -> Scores\n ScoringProvider,\n ScoringTask,\n ScoringInput,\n CategoryScore,\n ScoringResult,\n\n // Common types shared across shapes\n FileAttachment,\n TokenUsage,\n CacheUsage,\n AttachmentResults,\n ModelWarningLevel,\n ModelWarning,\n ModelMetadata,\n} from './providers';\n\nexport { isLocalEmbeddingProvider } from './providers';\n\n// ============================================================================\n// Deprecated Provider Aliases (backward compatibility)\n// ============================================================================\n\n/**\n * @deprecated Use `TextProvider` instead\n */\nexport type { TextProvider as LLMProvider } from './providers';\n\n/**\n * @deprecated Use `ImageProvider` instead\n */\nexport type { ImageProvider as ImageGenProvider } from './providers';\n\n// ============================================================================\n// LLM Tool Types\n// ============================================================================\n\nexport type {\n // Tool definitions\n OpenAIToolDefinition,\n UniversalTool,\n AnthropicToolDefinition,\n GoogleToolDefinition,\n\n // Tool calls\n ToolCall,\n ToolCallRequest,\n ToolResult,\n ToolFormatOptions,\n} from './llm/tools';\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\nexport type {\n // Text provider plugin types (primary)\n TextProviderPlugin,\n ProviderMetadata,\n ProviderConfigRequirements,\n ProviderCapabilities,\n AttachmentSupport,\n ModelInfo,\n ThinkingTurnRule,\n EmbeddingModelInfo,\n ImageGenerationModelInfo,\n ImageStyleInfo,\n ImageLoraSupport,\n ImageProviderConstraints,\n OrientationStrategy,\n OrientationMapping,\n ImageOrientationSupport,\n IconProps,\n PluginIconData,\n ProviderPluginExport,\n // Runtime configuration types\n MessageFormatSupport,\n CheapModelConfig,\n ToolFormatType,\n // Deprecated alias\n LLMProviderPlugin,\n} from './plugins/provider';\n\nexport type {\n // Provider options schema (rendered by the connection-profile editor)\n ProviderOptionFieldType,\n ProviderOptionEnumValue,\n ProviderOptionDirective,\n ProviderOptionShowIf,\n ProviderOptionField,\n ProviderOptionGroup,\n ProviderOptionsSchema,\n ProviderOptionsSchemaContext,\n} from './plugins/provider-options';\n\nexport type {\n // Scoring provider plugin types (primary)\n ScoringProviderMetadata,\n ScoringProviderConfigRequirements,\n ScoringProviderPlugin,\n ScoringProviderPluginExport,\n} from './plugins/scoring-provider';\n\nexport type {\n // Manifest types\n PluginCapability,\n PluginCategory,\n PluginStatus,\n PluginAuthor,\n PluginCompatibility,\n ProviderConfig,\n SearchProviderConfig,\n PluginPermissions,\n PluginManifest,\n InstalledPluginInfo,\n} from './plugins/manifest';\n\nexport type {\n // Theme plugin types\n ColorPalette,\n Typography,\n Spacing,\n Effects,\n ThemeTokens,\n FontDefinition,\n EmbeddedFont,\n ThemeMetadata,\n SubsystemOverrides,\n ThemePlugin,\n ThemePluginExport,\n} from './plugins/theme';\n\nexport type {\n // Roleplay template plugin types\n NarrationDelimiters,\n RoleplayTemplateConfig,\n RoleplayTemplateMetadata,\n RoleplayTemplatePlugin,\n RoleplayTemplatePluginExport,\n} from './plugins/roleplay-template';\n\nexport type {\n // System prompt plugin types\n SystemPromptData,\n SystemPromptMetadata,\n SystemPromptPlugin,\n SystemPromptPluginExport,\n} from './plugins/system-prompt';\n\nexport type {\n // Tool plugin types\n ToolMetadata,\n ToolHierarchyInfo,\n ToolEffect,\n ToolCallEffect,\n ToolExecutionContext,\n ToolExecutionResult,\n ToolPlugin,\n ToolPluginExport,\n} from './plugins/tool';\n\nexport type {\n // Search provider plugin types\n SearchProviderMetadata,\n SearchProviderConfigRequirements,\n SearchResult,\n SearchOutput,\n SearchProviderPlugin,\n SearchProviderPluginExport,\n} from './plugins/search-provider';\n\nexport type {\n // Moderation provider plugin types (deprecated, use scoring)\n ModerationProviderMetadata,\n ModerationProviderConfigRequirements,\n ModerationCategoryResult,\n ModerationResult,\n ModerationProviderPlugin,\n ModerationProviderPluginExport,\n} from './plugins/moderation-provider';\n\n// ============================================================================\n// Common Types\n// ============================================================================\n\nexport type { LogLevel, LogContext, PluginLogger } from './common/logger';\n\nexport type {\n CharacterPluginDataEntry,\n CharacterPluginDataMap,\n} from './common/character-plugin-data';\n\n// Error classes (these are values, not just types)\nexport {\n PluginError,\n ApiKeyError,\n ProviderApiError,\n RateLimitError,\n ModerationRejectionError,\n ConfigurationError,\n ModelNotFoundError,\n AttachmentError,\n ToolExecutionError,\n} from './common/errors';\n\n// Logger factories\nexport { createConsoleLogger, createNoopLogger } from './common/logger';\n\n// ============================================================================\n// Version\n// ============================================================================\n\n/**\n * Version of the plugin-types package.\n * Can be used at runtime to check compatibility.\n */\nexport const PLUGIN_TYPES_VERSION = '2.13.0';\n"]}
1
+ {"version":3,"sources":["../src/providers/embedding.ts","../src/common/errors.ts","../src/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A,GAAgB,MAAA,CAAO,IAAA,CAAK,oBAAoB,CAAA;AAEtD,SAAS,WAAA,GAAuC;AAC9C,EAAA,OAAO,UAAA;AACT;AAaO,SAAS,oBAAoB,QAAA,EAA+C;AACjF,EAAA,MAAM,UAAU,WAAA,EAAY;AAC5B,EAAA,KAAA,MAAW,QAAQ,aAAA,EAAe;AAChC,IAAA,IAAI,QAAQ,QAAA,EAAU;AACpB,MAAA,OAAA,CAAQ,oBAAA,CAAqB,IAAI,CAAC,CAAA,GAAI,SAAS,IAAI,CAAA;AAAA,IACrD;AAAA,EACF;AACF;AASO,SAAS,oBAAA,GAA6B;AAC3C,EAAA,MAAM,UAAU,WAAA,EAAY;AAC5B,EAAA,KAAA,MAAW,QAAQ,aAAA,EAAe;AAChC,IAAA,OAAA,CAAQ,oBAAA,CAAqB,IAAI,CAAC,CAAA,GAAI,MAAA;AAAA,EACxC;AACF;AAWO,SAAS,gBAAA,GAAkD;AAChE,EAAA,MAAM,UAAU,WAAA,EAAY;AAC5B,EAAA,MAAM,WAA0C,EAAC;AAEjD,EAAA,MAAM,YAAA,GAAe,OAAA,CAAQ,oBAAA,CAAqB,YAAY,CAAA;AAC9D,EAAA,IAAI,OAAO,iBAAiB,UAAA,EAAY;AACtC,IAAA,QAAA,CAAS,YAAA,GAAe,YAAA;AAAA,EAC1B;AAEA,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,oBAAA,CAAqB,UAAU,CAAA;AAC1D,EAAA,IAAI,OAAO,eAAe,QAAA,EAAU;AAClC,IAAA,QAAA,CAAS,UAAA,GAAa,UAAA;AAAA,EACxB;AAEA,EAAA,OAAO,QAAA;AACT;;;ACoIO,IAAM,oBAAA,GAAuB","file":"index.js","sourcesContent":["/**\n * Embedding Provider — Shape 3: Text -> Vector\n *\n * Send text to an embedding model, receive a numeric vector representation.\n * Used for semantic search, RAG, and similarity matching.\n *\n * @module @quilltap/plugin-types/providers/embedding\n */\n\n/**\n * Result of an embedding operation\n */\nexport interface EmbeddingResult {\n /** The embedding vector (array of floating point numbers) */\n embedding: number[];\n /** The model used to generate the embedding */\n model: string;\n /** Number of dimensions in the embedding vector */\n dimensions: number;\n /** Token usage information (if available) */\n usage?: {\n promptTokens: number;\n totalTokens: number;\n cost?: number;\n };\n}\n\n/**\n * Options for embedding generation\n */\nexport interface EmbeddingOptions {\n /** Desired dimensions for the embedding (if model supports variable dimensions) */\n dimensions?: number;\n}\n\n/**\n * Embedding provider interface — Shape 3: Text -> Vector\n *\n * Sends text to an embedding model and receives a numeric vector\n * representation for use in semantic search, RAG, and similarity matching.\n */\nexport interface EmbeddingProvider {\n /**\n * Generate an embedding for a single text\n *\n * @param text The text to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns The embedding result\n */\n generateEmbedding(\n text: string,\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult>;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns Array of embedding results\n */\n generateBatchEmbeddings?(\n texts: string[],\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult[]>;\n\n /**\n * Get available embedding models\n *\n * @param apiKey The API key for authentication\n * @returns Array of model IDs\n */\n getAvailableModels?(apiKey: string): Promise<string[]>;\n\n /**\n * Check if the provider is available and properly configured\n *\n * @param apiKey Optional API key to validate\n * @returns True if the provider is ready to use\n */\n isAvailable?(apiKey?: string): Promise<boolean>;\n}\n\n/**\n * Serializable state for local embedding providers\n *\n * Used by providers like TF-IDF that maintain vocabulary state\n */\nexport interface LocalEmbeddingProviderState {\n /** The vocabulary as an array of [term, index] pairs */\n vocabulary: [string, number][];\n /** The IDF (Inverse Document Frequency) weights */\n idf: number[];\n /** Average document length across the corpus */\n avgDocLength: number;\n /** Size of the vocabulary */\n vocabularySize: number;\n /** Whether bigrams are included in the vocabulary */\n includeBigrams: boolean;\n /** Timestamp when the vocabulary was fitted */\n fittedAt: string;\n}\n\n/**\n * Local embedding provider interface\n *\n * Extended interface for local/offline embedding providers that\n * maintain vocabulary state (like TF-IDF). These providers don't\n * require API keys and can work entirely offline.\n */\nexport interface LocalEmbeddingProvider extends Omit<EmbeddingProvider, 'generateEmbedding' | 'generateBatchEmbeddings'> {\n /**\n * Generate an embedding for a single text\n * Local providers don't need apiKey parameter\n *\n * @param text The text to embed\n * @returns The embedding result\n */\n generateEmbedding(text: string): EmbeddingResult;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @returns Array of embedding results\n */\n generateBatchEmbeddings(texts: string[]): EmbeddingResult[];\n\n /**\n * Fit the vocabulary on a corpus of documents\n *\n * This method analyzes the corpus to build vocabulary, calculate IDF weights,\n * and other statistics needed for embedding generation.\n *\n * @param documents Array of text documents to analyze\n */\n fitCorpus(documents: string[]): void;\n\n /**\n * Check if the vocabulary has been fitted\n *\n * @returns True if fitCorpus has been called with documents\n */\n isFitted(): boolean;\n\n /**\n * Load state from a serialized representation\n *\n * @param state The serialized provider state\n */\n loadState(state: LocalEmbeddingProviderState): void;\n\n /**\n * Get the current state for serialization\n *\n * @returns The provider state, or null if not fitted\n */\n getState(): LocalEmbeddingProviderState | null;\n\n /**\n * Get the vocabulary size\n *\n * @returns Number of terms in the vocabulary\n */\n getVocabularySize(): number;\n\n /**\n * Get the embedding dimensions\n *\n * @returns Number of dimensions in generated embeddings\n */\n getDimensions(): number;\n}\n\n/**\n * Type guard to check if a provider is a local embedding provider\n */\nexport function isLocalEmbeddingProvider(\n provider: EmbeddingProvider | LocalEmbeddingProvider\n): provider is LocalEmbeddingProvider {\n return 'fitCorpus' in provider && 'loadState' in provider && 'getState' in provider;\n}\n","/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n","/**\n * Host services: what the Quilltap host provides to every plugin it loads.\n *\n * This module is the one definition of that contract — the shape of each\n * service, the name it travels under, and the two functions that write and\n * read it. The host calls {@link provideHostServices}; plugin code (through\n * `@quilltap/plugin-utils`) calls {@link readHostServices}. Nothing else\n * should touch the names below.\n *\n * **Why globals.** A plugin is bundled with its own copy of this package and\n * of `@quilltap/plugin-utils`, so the host and a plugin never share a module\n * instance: a value the host stores in a module variable is invisible to the\n * plugin's copy of that module. `globalThis` is the only object both sides\n * have in common, so that is where the services are handed over.\n *\n * **The names are a wire format.** Every plugin already built reads these\n * exact keys through the copy of plugin-utils it was bundled with, and an\n * older host writes them. Renaming one, or folding them into a single object,\n * would silently cut those plugins off from the host's log and version. Add a\n * service by adding a field and a key; never change an existing one.\n *\n * **Every service is optional to the reader.** A plugin may be running outside\n * Quilltap (a test, a script) or under a host older than the service it wants,\n * so {@link readHostServices} returns only what is actually there and a plugin\n * must have a fallback for each.\n *\n * @module @quilltap/plugin-types/common/host-services\n */\n\nimport type { LogContext, PluginLogger } from './logger';\n\n/**\n * A plugin logger that can derive child loggers carrying extra context.\n */\nexport interface PluginLoggerWithChild extends PluginLogger {\n /**\n * Create a child logger with additional context\n * @param additionalContext Context to merge with the parent's context\n * @returns A new logger with the combined context\n */\n child(additionalContext: LogContext): PluginLoggerWithChild;\n}\n\n/**\n * Creates the logger a named plugin writes through.\n *\n * @param pluginName The plugin's identifier (e.g. `qtap-plugin-openai`)\n */\nexport type PluginLoggerFactory = (pluginName: string) => PluginLoggerWithChild;\n\n/**\n * The services the Quilltap host provides to the plugins it loads.\n */\nexport interface QuilltapHostServices {\n /**\n * Creates a logger that writes into the host's own log, tagged with the\n * plugin's name.\n */\n createLogger: PluginLoggerFactory;\n\n /**\n * The host application's version (e.g. `4.15.0`), so a plugin can identify\n * the application in the requests it makes.\n */\n appVersion: string;\n}\n\n/**\n * The `globalThis` key each service travels under. A wire format — see the\n * module notes before changing anything here.\n */\nconst HOST_SERVICE_GLOBALS: { readonly [Name in keyof QuilltapHostServices]: string } = {\n createLogger: '__quilltap_logger_factory',\n appVersion: '__quilltap_app_version',\n};\n\nconst SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS) as Array<keyof QuilltapHostServices>;\n\nfunction hostGlobals(): Record<string, unknown> {\n return globalThis as unknown as Record<string, unknown>;\n}\n\n/**\n * Provide host services to plugins.\n *\n * Called by the Quilltap host before it loads any plugin. Only the services\n * named in the argument are touched, so they can be provided one at a time; a\n * service passed as `undefined` is withdrawn.\n *\n * **Host API — not for plugin use.**\n *\n * @param services The services to provide\n */\nexport function provideHostServices(services: Partial<QuilltapHostServices>): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n if (name in services) {\n globals[HOST_SERVICE_GLOBALS[name]] = services[name];\n }\n }\n}\n\n/**\n * Withdraw every host service.\n *\n * Called by the host when it unloads the plugin system, and by tests.\n *\n * **Host API — not for plugin use.**\n */\nexport function withdrawHostServices(): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n globals[HOST_SERVICE_GLOBALS[name]] = undefined;\n }\n}\n\n/**\n * Read the services the host has provided.\n *\n * Returns only the services that are present and well-formed. Outside\n * Quilltap the result is empty, and under an older host a newer service is\n * simply missing — check each one before using it.\n *\n * @returns The services currently available\n */\nexport function readHostServices(): Partial<QuilltapHostServices> {\n const globals = hostGlobals();\n const services: Partial<QuilltapHostServices> = {};\n\n const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];\n if (typeof createLogger === 'function') {\n services.createLogger = createLogger as PluginLoggerFactory;\n }\n\n const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];\n if (typeof appVersion === 'string') {\n services.appVersion = appVersion;\n }\n\n return services;\n}\n","/**\n * @quilltap/plugin-types\n *\n * Type definitions for Quilltap plugin development.\n *\n * This package provides TypeScript types and interfaces for building\n * Quilltap plugins, including LLM providers, authentication providers,\n * and utility plugins.\n *\n * @packageDocumentation\n * @module @quilltap/plugin-types\n */\n\n// ============================================================================\n// Provider Interfaces — The Four Canonical Shapes\n// ============================================================================\n\nexport type {\n // Shape 1: Text -> Text\n TextProvider,\n LLMMessage,\n JSONSchemaDefinition,\n ResponseFormat,\n LLMParams,\n LLMResponse,\n StreamChunk,\n\n // Shape 2: Text -> Image\n ImageProvider,\n ImageOrientation,\n ImageGenParams,\n ImageLoraSpec,\n GeneratedImage,\n ImageGenResponse,\n\n // Shape 3: Text -> Vector\n EmbeddingProvider,\n EmbeddingResult,\n EmbeddingOptions,\n LocalEmbeddingProviderState,\n LocalEmbeddingProvider,\n\n // Shape 4: Text + Candidates -> Scores\n ScoringProvider,\n ScoringTask,\n ScoringInput,\n CategoryScore,\n ScoringResult,\n\n // Common types shared across shapes\n FileAttachment,\n TokenUsage,\n CacheUsage,\n AttachmentResults,\n ModelWarningLevel,\n ModelWarning,\n ModelMetadata,\n} from './providers';\n\nexport { isLocalEmbeddingProvider } from './providers';\n\n// ============================================================================\n// Deprecated Provider Aliases (backward compatibility)\n// ============================================================================\n\n/**\n * @deprecated Use `TextProvider` instead\n */\nexport type { TextProvider as LLMProvider } from './providers';\n\n/**\n * @deprecated Use `ImageProvider` instead\n */\nexport type { ImageProvider as ImageGenProvider } from './providers';\n\n// ============================================================================\n// LLM Tool Types\n// ============================================================================\n\nexport type {\n // Tool definitions\n OpenAIToolDefinition,\n UniversalTool,\n AnthropicToolDefinition,\n GoogleToolDefinition,\n\n // Tool calls\n ToolCall,\n ToolCallRequest,\n ToolResult,\n ToolFormatOptions,\n} from './llm/tools';\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\nexport type {\n // Text provider plugin types (primary)\n TextProviderPlugin,\n ProviderMetadata,\n ProviderConfigRequirements,\n ProviderCapabilities,\n AttachmentSupport,\n ModelInfo,\n ThinkingTurnRule,\n EmbeddingModelInfo,\n ImageGenerationModelInfo,\n ImageStyleInfo,\n ImageLoraSupport,\n ImageProviderConstraints,\n OrientationStrategy,\n OrientationMapping,\n ImageOrientationSupport,\n IconProps,\n PluginIconData,\n ProviderPluginExport,\n // Runtime configuration types\n MessageFormatSupport,\n CheapModelConfig,\n ToolFormatType,\n // Deprecated alias\n LLMProviderPlugin,\n} from './plugins/provider';\n\nexport type {\n // Provider options schema (rendered by the connection-profile editor)\n ProviderOptionFieldType,\n ProviderOptionEnumValue,\n ProviderOptionDirective,\n ProviderOptionShowIf,\n ProviderOptionField,\n ProviderOptionGroup,\n ProviderOptionsSchema,\n ProviderOptionsSchemaContext,\n} from './plugins/provider-options';\n\nexport type {\n // Scoring provider plugin types (primary)\n ScoringProviderMetadata,\n ScoringProviderConfigRequirements,\n ScoringProviderPlugin,\n ScoringProviderPluginExport,\n} from './plugins/scoring-provider';\n\nexport type {\n // Manifest types\n PluginCapability,\n PluginCategory,\n PluginStatus,\n PluginAuthor,\n PluginCompatibility,\n ProviderConfig,\n SearchProviderConfig,\n PluginPermissions,\n PluginManifest,\n InstalledPluginInfo,\n} from './plugins/manifest';\n\nexport type {\n // Theme plugin types\n ColorPalette,\n Typography,\n Spacing,\n Effects,\n ThemeTokens,\n FontDefinition,\n EmbeddedFont,\n ThemeMetadata,\n SubsystemOverrides,\n ThemePlugin,\n ThemePluginExport,\n} from './plugins/theme';\n\nexport type {\n // Roleplay template plugin types\n NarrationDelimiters,\n RoleplayTemplateConfig,\n RoleplayTemplateMetadata,\n RoleplayTemplatePlugin,\n RoleplayTemplatePluginExport,\n} from './plugins/roleplay-template';\n\nexport type {\n // System prompt plugin types\n SystemPromptData,\n SystemPromptMetadata,\n SystemPromptPlugin,\n SystemPromptPluginExport,\n} from './plugins/system-prompt';\n\nexport type {\n // Tool plugin types\n ToolMetadata,\n ToolHierarchyInfo,\n ToolEffect,\n ToolCallEffect,\n ToolExecutionContext,\n ToolExecutionResult,\n ToolPlugin,\n ToolPluginExport,\n} from './plugins/tool';\n\nexport type {\n // Search provider plugin types\n SearchProviderMetadata,\n SearchProviderConfigRequirements,\n SearchResult,\n SearchOutput,\n SearchProviderPlugin,\n SearchProviderPluginExport,\n} from './plugins/search-provider';\n\nexport type {\n // Moderation provider plugin types (deprecated, use scoring)\n ModerationProviderMetadata,\n ModerationProviderConfigRequirements,\n ModerationCategoryResult,\n ModerationResult,\n ModerationProviderPlugin,\n ModerationProviderPluginExport,\n} from './plugins/moderation-provider';\n\n// ============================================================================\n// Common Types\n// ============================================================================\n\nexport type { LogLevel, LogContext, PluginLogger } from './common/logger';\n\nexport type {\n CharacterPluginDataEntry,\n CharacterPluginDataMap,\n} from './common/character-plugin-data';\n\n// Error classes (these are values, not just types)\nexport {\n PluginError,\n ApiKeyError,\n ProviderApiError,\n RateLimitError,\n ModerationRejectionError,\n ConfigurationError,\n ModelNotFoundError,\n AttachmentError,\n ToolExecutionError,\n} from './common/errors';\n\n// Logger factories\nexport { createConsoleLogger, createNoopLogger } from './common/logger';\n\n// Host services: what the host provides to plugins, and the one pair of\n// functions that hands it over.\nexport type {\n PluginLoggerWithChild,\n PluginLoggerFactory,\n QuilltapHostServices,\n} from './common/host-services';\n\nexport {\n provideHostServices,\n withdrawHostServices,\n readHostServices,\n} from './common/host-services';\n\n// ============================================================================\n// Version\n// ============================================================================\n\n/**\n * Version of the plugin-types package.\n * Can be used at runtime to check compatibility.\n */\nexport const PLUGIN_TYPES_VERSION = '2.14.0';\n"]}
package/dist/index.mjs CHANGED
@@ -117,9 +117,46 @@ function createNoopLogger() {
117
117
  };
118
118
  }
119
119
 
120
+ // src/common/host-services.ts
121
+ var HOST_SERVICE_GLOBALS = {
122
+ createLogger: "__quilltap_logger_factory",
123
+ appVersion: "__quilltap_app_version"
124
+ };
125
+ var SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS);
126
+ function hostGlobals() {
127
+ return globalThis;
128
+ }
129
+ function provideHostServices(services) {
130
+ const globals = hostGlobals();
131
+ for (const name of SERVICE_NAMES) {
132
+ if (name in services) {
133
+ globals[HOST_SERVICE_GLOBALS[name]] = services[name];
134
+ }
135
+ }
136
+ }
137
+ function withdrawHostServices() {
138
+ const globals = hostGlobals();
139
+ for (const name of SERVICE_NAMES) {
140
+ globals[HOST_SERVICE_GLOBALS[name]] = void 0;
141
+ }
142
+ }
143
+ function readHostServices() {
144
+ const globals = hostGlobals();
145
+ const services = {};
146
+ const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];
147
+ if (typeof createLogger === "function") {
148
+ services.createLogger = createLogger;
149
+ }
150
+ const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];
151
+ if (typeof appVersion === "string") {
152
+ services.appVersion = appVersion;
153
+ }
154
+ return services;
155
+ }
156
+
120
157
  // src/index.ts
121
- var PLUGIN_TYPES_VERSION = "2.13.0";
158
+ var PLUGIN_TYPES_VERSION = "2.14.0";
122
159
 
123
- export { ApiKeyError, AttachmentError, ConfigurationError, ModelNotFoundError, ModerationRejectionError, PLUGIN_TYPES_VERSION, PluginError, ProviderApiError, RateLimitError, ToolExecutionError, createConsoleLogger, createNoopLogger, isLocalEmbeddingProvider };
160
+ export { ApiKeyError, AttachmentError, ConfigurationError, ModelNotFoundError, ModerationRejectionError, PLUGIN_TYPES_VERSION, PluginError, ProviderApiError, RateLimitError, ToolExecutionError, createConsoleLogger, createNoopLogger, isLocalEmbeddingProvider, provideHostServices, readHostServices, withdrawHostServices };
124
161
  //# sourceMappingURL=index.mjs.map
125
162
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/providers/embedding.ts","../src/common/errors.ts","../src/common/logger.ts","../src/index.ts"],"names":[],"mappings":";AAyLO,SAAS,yBACd,QAAA,EACoC;AACpC,EAAA,OAAO,WAAA,IAAe,QAAA,IAAY,WAAA,IAAe,QAAA,IAAY,UAAA,IAAc,QAAA;AAC7E;;;AClLO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAA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O,CAAA,EAAG,aAAA,CAAc,OAAO,CAAC,CAAA,CAAE,CAAA;AAAA,MAChE;AAAA,IACF,CAAA;AAAA,IAEA,KAAA,EAAO,CAAC,OAAA,EAAiB,OAAA,EAAsB,KAAA,KAAwB;AACrE,MAAA,IAAI,SAAA,CAAU,OAAO,CAAA,EAAG;AACtB,QAAA,OAAA,CAAQ,KAAA;AAAA,UACN,IAAI,MAAM,CAAA,EAAA,EAAK,OAAO,CAAA,EAAG,aAAA,CAAc,OAAO,CAAC,CAAA,CAAA;AAAA,UAC/C,KAAA,GAAQ;AAAA,EAAK,KAAA,CAAM,KAAA,IAAS,KAAA,CAAM,OAAO,CAAA,CAAA,GAAK;AAAA,SAChD;AAAA,MACF;AAAA,IACF;AAAA,GACF;AACF;AAOO,SAAS,gBAAA,GAAiC;AAC/C,EAAA,MAAM,OAAO,MAAY;AAAA,EAAC,CAAA;AAC1B,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,IAAA,EAAM,IAAA;AAAA,IACN,IAAA,EAAM,IAAA;AAAA,IACN,KAAA,EAAO;AAAA,GACT;AACF;;;AC4HO,IAAM,oBAAA,GAAuB","file":"index.mjs","sourcesContent":["/**\n * Embedding Provider — Shape 3: Text -> Vector\n *\n * Send text to an embedding model, receive a numeric vector representation.\n * Used for semantic search, RAG, and similarity matching.\n *\n * @module @quilltap/plugin-types/providers/embedding\n */\n\n/**\n * Result of an embedding operation\n */\nexport interface EmbeddingResult {\n /** The embedding vector (array of floating point numbers) */\n embedding: number[];\n /** The model used to generate the embedding */\n model: string;\n /** Number of dimensions in the embedding vector */\n dimensions: number;\n /** Token usage information (if available) */\n usage?: {\n promptTokens: number;\n totalTokens: number;\n cost?: number;\n };\n}\n\n/**\n * Options for embedding generation\n */\nexport interface EmbeddingOptions {\n /** Desired dimensions for the embedding (if model supports variable dimensions) */\n dimensions?: number;\n}\n\n/**\n * Embedding provider interface — Shape 3: Text -> Vector\n *\n * Sends text to an embedding model and receives a numeric vector\n * representation for use in semantic search, RAG, and similarity matching.\n */\nexport interface EmbeddingProvider {\n /**\n * Generate an embedding for a single text\n *\n * @param text The text to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns The embedding result\n */\n generateEmbedding(\n text: string,\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult>;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns Array of embedding results\n */\n generateBatchEmbeddings?(\n texts: string[],\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult[]>;\n\n /**\n * Get available embedding models\n *\n * @param apiKey The API key for authentication\n * @returns Array of model IDs\n */\n getAvailableModels?(apiKey: string): Promise<string[]>;\n\n /**\n * Check if the provider is available and properly configured\n *\n * @param apiKey Optional API key to validate\n * @returns True if the provider is ready to use\n */\n isAvailable?(apiKey?: string): Promise<boolean>;\n}\n\n/**\n * Serializable state for local embedding providers\n *\n * Used by providers like TF-IDF that maintain vocabulary state\n */\nexport interface LocalEmbeddingProviderState {\n /** The vocabulary as an array of [term, index] pairs */\n vocabulary: [string, number][];\n /** The IDF (Inverse Document Frequency) weights */\n idf: number[];\n /** Average document length across the corpus */\n avgDocLength: number;\n /** Size of the vocabulary */\n vocabularySize: number;\n /** Whether bigrams are included in the vocabulary */\n includeBigrams: boolean;\n /** Timestamp when the vocabulary was fitted */\n fittedAt: string;\n}\n\n/**\n * Local embedding provider interface\n *\n * Extended interface for local/offline embedding providers that\n * maintain vocabulary state (like TF-IDF). These providers don't\n * require API keys and can work entirely offline.\n */\nexport interface LocalEmbeddingProvider extends Omit<EmbeddingProvider, 'generateEmbedding' | 'generateBatchEmbeddings'> {\n /**\n * Generate an embedding for a single text\n * Local providers don't need apiKey parameter\n *\n * @param text The text to embed\n * @returns The embedding result\n */\n generateEmbedding(text: string): EmbeddingResult;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @returns Array of embedding results\n */\n generateBatchEmbeddings(texts: string[]): EmbeddingResult[];\n\n /**\n * Fit the vocabulary on a corpus of documents\n *\n * This method analyzes the corpus to build vocabulary, calculate IDF weights,\n * and other statistics needed for embedding generation.\n *\n * @param documents Array of text documents to analyze\n */\n fitCorpus(documents: string[]): void;\n\n /**\n * Check if the vocabulary has been fitted\n *\n * @returns True if fitCorpus has been called with documents\n */\n isFitted(): boolean;\n\n /**\n * Load state from a serialized representation\n *\n * @param state The serialized provider state\n */\n loadState(state: LocalEmbeddingProviderState): void;\n\n /**\n * Get the current state for serialization\n *\n * @returns The provider state, or null if not fitted\n */\n getState(): LocalEmbeddingProviderState | null;\n\n /**\n * Get the vocabulary size\n *\n * @returns Number of terms in the vocabulary\n */\n getVocabularySize(): number;\n\n /**\n * Get the embedding dimensions\n *\n * @returns Number of dimensions in generated embeddings\n */\n getDimensions(): number;\n}\n\n/**\n * Type guard to check if a provider is a local embedding provider\n */\nexport function isLocalEmbeddingProvider(\n provider: EmbeddingProvider | LocalEmbeddingProvider\n): provider is LocalEmbeddingProvider {\n return 'fitCorpus' in provider && 'loadState' in provider && 'getState' in provider;\n}\n","/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n","/**\n * @quilltap/plugin-types\n *\n * Type definitions for Quilltap plugin development.\n *\n * This package provides TypeScript types and interfaces for building\n * Quilltap plugins, including LLM providers, authentication providers,\n * and utility plugins.\n *\n * @packageDocumentation\n * @module @quilltap/plugin-types\n */\n\n// ============================================================================\n// Provider Interfaces — The Four Canonical Shapes\n// ============================================================================\n\nexport type {\n // Shape 1: Text -> Text\n TextProvider,\n LLMMessage,\n JSONSchemaDefinition,\n ResponseFormat,\n LLMParams,\n LLMResponse,\n StreamChunk,\n\n // Shape 2: Text -> Image\n ImageProvider,\n ImageOrientation,\n ImageGenParams,\n ImageLoraSpec,\n GeneratedImage,\n ImageGenResponse,\n\n // Shape 3: Text -> Vector\n EmbeddingProvider,\n EmbeddingResult,\n EmbeddingOptions,\n LocalEmbeddingProviderState,\n LocalEmbeddingProvider,\n\n // Shape 4: Text + Candidates -> Scores\n ScoringProvider,\n ScoringTask,\n ScoringInput,\n CategoryScore,\n ScoringResult,\n\n // Common types shared across shapes\n FileAttachment,\n TokenUsage,\n CacheUsage,\n AttachmentResults,\n ModelWarningLevel,\n ModelWarning,\n ModelMetadata,\n} from './providers';\n\nexport { isLocalEmbeddingProvider } from './providers';\n\n// ============================================================================\n// Deprecated Provider Aliases (backward compatibility)\n// ============================================================================\n\n/**\n * @deprecated Use `TextProvider` instead\n */\nexport type { TextProvider as LLMProvider } from './providers';\n\n/**\n * @deprecated Use `ImageProvider` instead\n */\nexport type { ImageProvider as ImageGenProvider } from './providers';\n\n// ============================================================================\n// LLM Tool Types\n// ============================================================================\n\nexport type {\n // Tool definitions\n OpenAIToolDefinition,\n UniversalTool,\n AnthropicToolDefinition,\n GoogleToolDefinition,\n\n // Tool calls\n ToolCall,\n ToolCallRequest,\n ToolResult,\n ToolFormatOptions,\n} from './llm/tools';\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\nexport type {\n // Text provider plugin types (primary)\n TextProviderPlugin,\n ProviderMetadata,\n ProviderConfigRequirements,\n ProviderCapabilities,\n AttachmentSupport,\n ModelInfo,\n ThinkingTurnRule,\n EmbeddingModelInfo,\n ImageGenerationModelInfo,\n ImageStyleInfo,\n ImageLoraSupport,\n ImageProviderConstraints,\n OrientationStrategy,\n OrientationMapping,\n ImageOrientationSupport,\n IconProps,\n PluginIconData,\n ProviderPluginExport,\n // Runtime configuration types\n MessageFormatSupport,\n CheapModelConfig,\n ToolFormatType,\n // Deprecated alias\n LLMProviderPlugin,\n} from './plugins/provider';\n\nexport type {\n // Provider options schema (rendered by the connection-profile editor)\n ProviderOptionFieldType,\n ProviderOptionEnumValue,\n ProviderOptionDirective,\n ProviderOptionShowIf,\n ProviderOptionField,\n ProviderOptionGroup,\n ProviderOptionsSchema,\n ProviderOptionsSchemaContext,\n} from './plugins/provider-options';\n\nexport type {\n // Scoring provider plugin types (primary)\n ScoringProviderMetadata,\n ScoringProviderConfigRequirements,\n ScoringProviderPlugin,\n ScoringProviderPluginExport,\n} from './plugins/scoring-provider';\n\nexport type {\n // Manifest types\n PluginCapability,\n PluginCategory,\n PluginStatus,\n PluginAuthor,\n PluginCompatibility,\n ProviderConfig,\n SearchProviderConfig,\n PluginPermissions,\n PluginManifest,\n InstalledPluginInfo,\n} from './plugins/manifest';\n\nexport type {\n // Theme plugin types\n ColorPalette,\n Typography,\n Spacing,\n Effects,\n ThemeTokens,\n FontDefinition,\n EmbeddedFont,\n ThemeMetadata,\n SubsystemOverrides,\n ThemePlugin,\n ThemePluginExport,\n} from './plugins/theme';\n\nexport type {\n // Roleplay template plugin types\n NarrationDelimiters,\n RoleplayTemplateConfig,\n RoleplayTemplateMetadata,\n RoleplayTemplatePlugin,\n RoleplayTemplatePluginExport,\n} from './plugins/roleplay-template';\n\nexport type {\n // System prompt plugin types\n SystemPromptData,\n SystemPromptMetadata,\n SystemPromptPlugin,\n SystemPromptPluginExport,\n} from './plugins/system-prompt';\n\nexport type {\n // Tool plugin types\n ToolMetadata,\n ToolHierarchyInfo,\n ToolEffect,\n ToolCallEffect,\n ToolExecutionContext,\n ToolExecutionResult,\n ToolPlugin,\n ToolPluginExport,\n} from './plugins/tool';\n\nexport type {\n // Search provider plugin types\n SearchProviderMetadata,\n SearchProviderConfigRequirements,\n SearchResult,\n SearchOutput,\n SearchProviderPlugin,\n SearchProviderPluginExport,\n} from './plugins/search-provider';\n\nexport type {\n // Moderation provider plugin types (deprecated, use scoring)\n ModerationProviderMetadata,\n ModerationProviderConfigRequirements,\n ModerationCategoryResult,\n ModerationResult,\n ModerationProviderPlugin,\n ModerationProviderPluginExport,\n} from './plugins/moderation-provider';\n\n// ============================================================================\n// Common Types\n// ============================================================================\n\nexport type { LogLevel, LogContext, PluginLogger } from './common/logger';\n\nexport type {\n CharacterPluginDataEntry,\n CharacterPluginDataMap,\n} from './common/character-plugin-data';\n\n// Error classes (these are values, not just types)\nexport {\n PluginError,\n ApiKeyError,\n ProviderApiError,\n RateLimitError,\n ModerationRejectionError,\n ConfigurationError,\n ModelNotFoundError,\n AttachmentError,\n ToolExecutionError,\n} from './common/errors';\n\n// Logger factories\nexport { createConsoleLogger, createNoopLogger } from './common/logger';\n\n// ============================================================================\n// Version\n// ============================================================================\n\n/**\n * Version of the plugin-types package.\n * Can be used at runtime to check compatibility.\n */\nexport const PLUGIN_TYPES_VERSION = '2.13.0';\n"]}
1
+ {"version":3,"sources":["../src/providers/embedding.ts","../src/common/errors.ts","../src/common/logger.ts","../src/common/host-services.ts","../src/index.ts"],"names":[],"mappings":";AAyLO,SAAS,yBACd,QAAA,EACoC;AACpC,EAAA,OAAO,WAAA,IAAe,QAAA,IAAY,WAAA,IAAe,QAAA,IAAY,UAAA,IAAc,QAAA;AAC7E;;;AClLO,IAAM,WAAA,GAAN,cAA0B,KAAA,CAAM;AAAA,EACrC,WAAA,CACE,OAAA,EACgB,IAAA,EACA,UAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AACA,IAAA,IAAA,CAAA,UAAA,GAAA,UAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,WAAA,GAAN,cAA0B,WAAA,CAAY;AAAA,EAC3C,WAAA,CAAY,SAAiB,UAAA,EAAqB;AAChD,IAAA,KAAA,CAAM,OAAA,EAAS,iBAAiB,UAAU,CAAA;AAC1C,IAAA,IAAA,CAAK,IAAA,GAAO,aAAA;AAAA,EACd;AACF;AAOO,IAAM,gBAAA,GAAN,cAA+B,WAAA,CAAY;AAAA,EAChD,WAAA,CACE,OAAA,EACgB,UAAA,EACA,QAAA,EAChB,UAAA,EACA;AACA,IAA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AA,QAAA,CAAS,YAAA,GAAe,YAAA;AAAA,EAC1B;AAEA,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,oBAAA,CAAqB,UAAU,CAAA;AAC1D,EAAA,IAAI,OAAO,eAAe,QAAA,EAAU;AAClC,IAAA,QAAA,CAAS,UAAA,GAAa,UAAA;AAAA,EACxB;AAEA,EAAA,OAAO,QAAA;AACT;;;ACoIO,IAAM,oBAAA,GAAuB","file":"index.mjs","sourcesContent":["/**\n * Embedding Provider — Shape 3: Text -> Vector\n *\n * Send text to an embedding model, receive a numeric vector representation.\n * Used for semantic search, RAG, and similarity matching.\n *\n * @module @quilltap/plugin-types/providers/embedding\n */\n\n/**\n * Result of an embedding operation\n */\nexport interface EmbeddingResult {\n /** The embedding vector (array of floating point numbers) */\n embedding: number[];\n /** The model used to generate the embedding */\n model: string;\n /** Number of dimensions in the embedding vector */\n dimensions: number;\n /** Token usage information (if available) */\n usage?: {\n promptTokens: number;\n totalTokens: number;\n cost?: number;\n };\n}\n\n/**\n * Options for embedding generation\n */\nexport interface EmbeddingOptions {\n /** Desired dimensions for the embedding (if model supports variable dimensions) */\n dimensions?: number;\n}\n\n/**\n * Embedding provider interface — Shape 3: Text -> Vector\n *\n * Sends text to an embedding model and receives a numeric vector\n * representation for use in semantic search, RAG, and similarity matching.\n */\nexport interface EmbeddingProvider {\n /**\n * Generate an embedding for a single text\n *\n * @param text The text to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns The embedding result\n */\n generateEmbedding(\n text: string,\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult>;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @param model The model to use\n * @param apiKey The API key for authentication\n * @param options Optional configuration\n * @returns Array of embedding results\n */\n generateBatchEmbeddings?(\n texts: string[],\n model: string,\n apiKey: string,\n options?: EmbeddingOptions\n ): Promise<EmbeddingResult[]>;\n\n /**\n * Get available embedding models\n *\n * @param apiKey The API key for authentication\n * @returns Array of model IDs\n */\n getAvailableModels?(apiKey: string): Promise<string[]>;\n\n /**\n * Check if the provider is available and properly configured\n *\n * @param apiKey Optional API key to validate\n * @returns True if the provider is ready to use\n */\n isAvailable?(apiKey?: string): Promise<boolean>;\n}\n\n/**\n * Serializable state for local embedding providers\n *\n * Used by providers like TF-IDF that maintain vocabulary state\n */\nexport interface LocalEmbeddingProviderState {\n /** The vocabulary as an array of [term, index] pairs */\n vocabulary: [string, number][];\n /** The IDF (Inverse Document Frequency) weights */\n idf: number[];\n /** Average document length across the corpus */\n avgDocLength: number;\n /** Size of the vocabulary */\n vocabularySize: number;\n /** Whether bigrams are included in the vocabulary */\n includeBigrams: boolean;\n /** Timestamp when the vocabulary was fitted */\n fittedAt: string;\n}\n\n/**\n * Local embedding provider interface\n *\n * Extended interface for local/offline embedding providers that\n * maintain vocabulary state (like TF-IDF). These providers don't\n * require API keys and can work entirely offline.\n */\nexport interface LocalEmbeddingProvider extends Omit<EmbeddingProvider, 'generateEmbedding' | 'generateBatchEmbeddings'> {\n /**\n * Generate an embedding for a single text\n * Local providers don't need apiKey parameter\n *\n * @param text The text to embed\n * @returns The embedding result\n */\n generateEmbedding(text: string): EmbeddingResult;\n\n /**\n * Generate embeddings for multiple texts in a batch\n *\n * @param texts Array of texts to embed\n * @returns Array of embedding results\n */\n generateBatchEmbeddings(texts: string[]): EmbeddingResult[];\n\n /**\n * Fit the vocabulary on a corpus of documents\n *\n * This method analyzes the corpus to build vocabulary, calculate IDF weights,\n * and other statistics needed for embedding generation.\n *\n * @param documents Array of text documents to analyze\n */\n fitCorpus(documents: string[]): void;\n\n /**\n * Check if the vocabulary has been fitted\n *\n * @returns True if fitCorpus has been called with documents\n */\n isFitted(): boolean;\n\n /**\n * Load state from a serialized representation\n *\n * @param state The serialized provider state\n */\n loadState(state: LocalEmbeddingProviderState): void;\n\n /**\n * Get the current state for serialization\n *\n * @returns The provider state, or null if not fitted\n */\n getState(): LocalEmbeddingProviderState | null;\n\n /**\n * Get the vocabulary size\n *\n * @returns Number of terms in the vocabulary\n */\n getVocabularySize(): number;\n\n /**\n * Get the embedding dimensions\n *\n * @returns Number of dimensions in generated embeddings\n */\n getDimensions(): number;\n}\n\n/**\n * Type guard to check if a provider is a local embedding provider\n */\nexport function isLocalEmbeddingProvider(\n provider: EmbeddingProvider | LocalEmbeddingProvider\n): provider is LocalEmbeddingProvider {\n return 'fitCorpus' in provider && 'loadState' in provider && 'getState' in provider;\n}\n","/**\n * Common error types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/errors\n */\n\n/**\n * Base plugin error\n *\n * All plugin-specific errors should extend this class.\n */\nexport class PluginError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly pluginName?: string\n ) {\n super(message);\n this.name = 'PluginError';\n }\n}\n\n/**\n * API key validation error\n *\n * Thrown when an API key is invalid or has insufficient permissions.\n */\nexport class ApiKeyError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'API_KEY_ERROR', pluginName);\n this.name = 'ApiKeyError';\n }\n}\n\n/**\n * Provider API error\n *\n * Thrown when the provider API returns an error.\n */\nexport class ProviderApiError extends PluginError {\n constructor(\n message: string,\n public readonly statusCode?: number,\n public readonly response?: unknown,\n pluginName?: string\n ) {\n super(message, 'PROVIDER_API_ERROR', pluginName);\n this.name = 'ProviderApiError';\n }\n}\n\n/**\n * Moderation rejection error\n *\n * Thrown when the provider declined a request on content-moderation grounds\n * (a safety filter, a content policy, a \"sensitive content\" stop) — as\n * distinct from any other failure. The host reroutes these to the user's\n * uncensored profile (the Concierge); it never reroutes a rate limit or an\n * auth failure, so a provider that can tell the difference **must** throw\n * this, or any error carrying `code: 'MODERATION_REJECTED'`.\n *\n * The host detects it by the `code` string, **never** by `instanceof`:\n * plugins bundle their own copy of this package, so the class a plugin throws\n * is not the class the host would compare against.\n */\nexport class ModerationRejectionError extends ProviderApiError {\n public override readonly code = 'MODERATION_REJECTED';\n\n constructor(\n message: string,\n statusCode?: number,\n /** The provider's own reason, when it gave one (e.g. `IMAGE_SAFETY`, `moderation_blocked`, `1301`). */\n public readonly providerReason?: string,\n pluginName?: string\n ) {\n super(message, statusCode, undefined, pluginName);\n this.name = 'ModerationRejectionError';\n }\n}\n\n/**\n * Rate limit error\n *\n * Thrown when the provider rate limits the request.\n */\nexport class RateLimitError extends ProviderApiError {\n public override readonly code = 'RATE_LIMIT_ERROR';\n\n constructor(\n message: string,\n public readonly retryAfter?: number,\n pluginName?: string\n ) {\n super(message, 429, undefined, pluginName);\n this.name = 'RateLimitError';\n }\n}\n\n/**\n * Configuration error\n *\n * Thrown when plugin configuration is invalid.\n */\nexport class ConfigurationError extends PluginError {\n constructor(message: string, pluginName?: string) {\n super(message, 'CONFIGURATION_ERROR', pluginName);\n this.name = 'ConfigurationError';\n }\n}\n\n/**\n * Model not found error\n *\n * Thrown when a requested model is not available.\n */\nexport class ModelNotFoundError extends PluginError {\n constructor(\n message: string,\n public readonly modelId?: string,\n pluginName?: string\n ) {\n super(message, 'MODEL_NOT_FOUND', pluginName);\n this.name = 'ModelNotFoundError';\n }\n}\n\n/**\n * Attachment error\n *\n * Thrown when there's an issue processing file attachments.\n */\nexport class AttachmentError extends PluginError {\n constructor(\n message: string,\n public readonly attachmentId?: string,\n pluginName?: string\n ) {\n super(message, 'ATTACHMENT_ERROR', pluginName);\n this.name = 'AttachmentError';\n }\n}\n\n/**\n * Tool execution error\n *\n * Thrown when a tool call fails to execute.\n */\nexport class ToolExecutionError extends PluginError {\n constructor(\n message: string,\n public readonly toolName?: string,\n pluginName?: string\n ) {\n super(message, 'TOOL_EXECUTION_ERROR', pluginName);\n this.name = 'ToolExecutionError';\n }\n}\n","/**\n * Logger types for Quilltap plugin development\n *\n * @module @quilltap/plugin-types/common/logger\n */\n\n/**\n * Log level type\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error';\n\n/**\n * Log context metadata\n */\nexport interface LogContext {\n /** Context identifier (e.g., module name) */\n context?: string;\n /** Additional metadata */\n [key: string]: unknown;\n}\n\n/**\n * Logger interface that plugins can implement or receive\n *\n * This interface is compatible with Quilltap's built-in logger.\n * Plugins can use this interface to accept a logger from the host\n * application or implement their own logging.\n */\nexport interface PluginLogger {\n /**\n * Log a debug message\n * @param message Message to log\n * @param context Optional context metadata\n */\n debug(message: string, context?: LogContext): void;\n\n /**\n * Log an info message\n * @param message Message to log\n * @param context Optional context metadata\n */\n info(message: string, context?: LogContext): void;\n\n /**\n * Log a warning message\n * @param message Message to log\n * @param context Optional context metadata\n */\n warn(message: string, context?: LogContext): void;\n\n /**\n * Log an error message\n * @param message Message to log\n * @param context Optional context metadata\n * @param error Optional error object\n */\n error(message: string, context?: LogContext, error?: Error): void;\n}\n\n/**\n * Simple console-based logger for standalone plugin development\n *\n * This logger writes to the console and is useful for local\n * plugin development and testing.\n *\n * @param prefix Prefix to add to all log messages\n * @param minLevel Minimum log level to output (default: 'info')\n * @returns A PluginLogger instance\n *\n * @example\n * ```typescript\n * const logger = createConsoleLogger('my-plugin', 'debug');\n * logger.debug('Initializing plugin', { version: '1.0.0' });\n * logger.info('Plugin ready');\n * logger.error('Failed to connect', { endpoint: 'api.example.com' }, new Error('Connection refused'));\n * ```\n */\nexport function createConsoleLogger(prefix: string, minLevel: LogLevel = 'info'): PluginLogger {\n const levels: LogLevel[] = ['debug', 'info', 'warn', 'error'];\n const shouldLog = (level: LogLevel): boolean =>\n levels.indexOf(level) >= levels.indexOf(minLevel);\n\n const formatContext = (context?: LogContext): string => {\n if (!context) return '';\n const entries = Object.entries(context)\n .filter(([key]) => key !== 'context')\n .map(([key, value]) => `${key}=${JSON.stringify(value)}`)\n .join(' ');\n return entries ? ` ${entries}` : '';\n };\n\n return {\n debug: (message: string, context?: LogContext): void => {\n if (shouldLog('debug')) {\n console.debug(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n info: (message: string, context?: LogContext): void => {\n if (shouldLog('info')) {\n console.info(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n warn: (message: string, context?: LogContext): void => {\n if (shouldLog('warn')) {\n console.warn(`[${prefix}] ${message}${formatContext(context)}`);\n }\n },\n\n error: (message: string, context?: LogContext, error?: Error): void => {\n if (shouldLog('error')) {\n console.error(\n `[${prefix}] ${message}${formatContext(context)}`,\n error ? `\\n${error.stack || error.message}` : ''\n );\n }\n },\n };\n}\n\n/**\n * No-op logger for production or when logging is disabled\n *\n * @returns A PluginLogger that does nothing\n */\nexport function createNoopLogger(): PluginLogger {\n const noop = (): void => {};\n return {\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n };\n}\n","/**\n * Host services: what the Quilltap host provides to every plugin it loads.\n *\n * This module is the one definition of that contract — the shape of each\n * service, the name it travels under, and the two functions that write and\n * read it. The host calls {@link provideHostServices}; plugin code (through\n * `@quilltap/plugin-utils`) calls {@link readHostServices}. Nothing else\n * should touch the names below.\n *\n * **Why globals.** A plugin is bundled with its own copy of this package and\n * of `@quilltap/plugin-utils`, so the host and a plugin never share a module\n * instance: a value the host stores in a module variable is invisible to the\n * plugin's copy of that module. `globalThis` is the only object both sides\n * have in common, so that is where the services are handed over.\n *\n * **The names are a wire format.** Every plugin already built reads these\n * exact keys through the copy of plugin-utils it was bundled with, and an\n * older host writes them. Renaming one, or folding them into a single object,\n * would silently cut those plugins off from the host's log and version. Add a\n * service by adding a field and a key; never change an existing one.\n *\n * **Every service is optional to the reader.** A plugin may be running outside\n * Quilltap (a test, a script) or under a host older than the service it wants,\n * so {@link readHostServices} returns only what is actually there and a plugin\n * must have a fallback for each.\n *\n * @module @quilltap/plugin-types/common/host-services\n */\n\nimport type { LogContext, PluginLogger } from './logger';\n\n/**\n * A plugin logger that can derive child loggers carrying extra context.\n */\nexport interface PluginLoggerWithChild extends PluginLogger {\n /**\n * Create a child logger with additional context\n * @param additionalContext Context to merge with the parent's context\n * @returns A new logger with the combined context\n */\n child(additionalContext: LogContext): PluginLoggerWithChild;\n}\n\n/**\n * Creates the logger a named plugin writes through.\n *\n * @param pluginName The plugin's identifier (e.g. `qtap-plugin-openai`)\n */\nexport type PluginLoggerFactory = (pluginName: string) => PluginLoggerWithChild;\n\n/**\n * The services the Quilltap host provides to the plugins it loads.\n */\nexport interface QuilltapHostServices {\n /**\n * Creates a logger that writes into the host's own log, tagged with the\n * plugin's name.\n */\n createLogger: PluginLoggerFactory;\n\n /**\n * The host application's version (e.g. `4.15.0`), so a plugin can identify\n * the application in the requests it makes.\n */\n appVersion: string;\n}\n\n/**\n * The `globalThis` key each service travels under. A wire format — see the\n * module notes before changing anything here.\n */\nconst HOST_SERVICE_GLOBALS: { readonly [Name in keyof QuilltapHostServices]: string } = {\n createLogger: '__quilltap_logger_factory',\n appVersion: '__quilltap_app_version',\n};\n\nconst SERVICE_NAMES = Object.keys(HOST_SERVICE_GLOBALS) as Array<keyof QuilltapHostServices>;\n\nfunction hostGlobals(): Record<string, unknown> {\n return globalThis as unknown as Record<string, unknown>;\n}\n\n/**\n * Provide host services to plugins.\n *\n * Called by the Quilltap host before it loads any plugin. Only the services\n * named in the argument are touched, so they can be provided one at a time; a\n * service passed as `undefined` is withdrawn.\n *\n * **Host API — not for plugin use.**\n *\n * @param services The services to provide\n */\nexport function provideHostServices(services: Partial<QuilltapHostServices>): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n if (name in services) {\n globals[HOST_SERVICE_GLOBALS[name]] = services[name];\n }\n }\n}\n\n/**\n * Withdraw every host service.\n *\n * Called by the host when it unloads the plugin system, and by tests.\n *\n * **Host API — not for plugin use.**\n */\nexport function withdrawHostServices(): void {\n const globals = hostGlobals();\n for (const name of SERVICE_NAMES) {\n globals[HOST_SERVICE_GLOBALS[name]] = undefined;\n }\n}\n\n/**\n * Read the services the host has provided.\n *\n * Returns only the services that are present and well-formed. Outside\n * Quilltap the result is empty, and under an older host a newer service is\n * simply missing — check each one before using it.\n *\n * @returns The services currently available\n */\nexport function readHostServices(): Partial<QuilltapHostServices> {\n const globals = hostGlobals();\n const services: Partial<QuilltapHostServices> = {};\n\n const createLogger = globals[HOST_SERVICE_GLOBALS.createLogger];\n if (typeof createLogger === 'function') {\n services.createLogger = createLogger as PluginLoggerFactory;\n }\n\n const appVersion = globals[HOST_SERVICE_GLOBALS.appVersion];\n if (typeof appVersion === 'string') {\n services.appVersion = appVersion;\n }\n\n return services;\n}\n","/**\n * @quilltap/plugin-types\n *\n * Type definitions for Quilltap plugin development.\n *\n * This package provides TypeScript types and interfaces for building\n * Quilltap plugins, including LLM providers, authentication providers,\n * and utility plugins.\n *\n * @packageDocumentation\n * @module @quilltap/plugin-types\n */\n\n// ============================================================================\n// Provider Interfaces — The Four Canonical Shapes\n// ============================================================================\n\nexport type {\n // Shape 1: Text -> Text\n TextProvider,\n LLMMessage,\n JSONSchemaDefinition,\n ResponseFormat,\n LLMParams,\n LLMResponse,\n StreamChunk,\n\n // Shape 2: Text -> Image\n ImageProvider,\n ImageOrientation,\n ImageGenParams,\n ImageLoraSpec,\n GeneratedImage,\n ImageGenResponse,\n\n // Shape 3: Text -> Vector\n EmbeddingProvider,\n EmbeddingResult,\n EmbeddingOptions,\n LocalEmbeddingProviderState,\n LocalEmbeddingProvider,\n\n // Shape 4: Text + Candidates -> Scores\n ScoringProvider,\n ScoringTask,\n ScoringInput,\n CategoryScore,\n ScoringResult,\n\n // Common types shared across shapes\n FileAttachment,\n TokenUsage,\n CacheUsage,\n AttachmentResults,\n ModelWarningLevel,\n ModelWarning,\n ModelMetadata,\n} from './providers';\n\nexport { isLocalEmbeddingProvider } from './providers';\n\n// ============================================================================\n// Deprecated Provider Aliases (backward compatibility)\n// ============================================================================\n\n/**\n * @deprecated Use `TextProvider` instead\n */\nexport type { TextProvider as LLMProvider } from './providers';\n\n/**\n * @deprecated Use `ImageProvider` instead\n */\nexport type { ImageProvider as ImageGenProvider } from './providers';\n\n// ============================================================================\n// LLM Tool Types\n// ============================================================================\n\nexport type {\n // Tool definitions\n OpenAIToolDefinition,\n UniversalTool,\n AnthropicToolDefinition,\n GoogleToolDefinition,\n\n // Tool calls\n ToolCall,\n ToolCallRequest,\n ToolResult,\n ToolFormatOptions,\n} from './llm/tools';\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\nexport type {\n // Text provider plugin types (primary)\n TextProviderPlugin,\n ProviderMetadata,\n ProviderConfigRequirements,\n ProviderCapabilities,\n AttachmentSupport,\n ModelInfo,\n ThinkingTurnRule,\n EmbeddingModelInfo,\n ImageGenerationModelInfo,\n ImageStyleInfo,\n ImageLoraSupport,\n ImageProviderConstraints,\n OrientationStrategy,\n OrientationMapping,\n ImageOrientationSupport,\n IconProps,\n PluginIconData,\n ProviderPluginExport,\n // Runtime configuration types\n MessageFormatSupport,\n CheapModelConfig,\n ToolFormatType,\n // Deprecated alias\n LLMProviderPlugin,\n} from './plugins/provider';\n\nexport type {\n // Provider options schema (rendered by the connection-profile editor)\n ProviderOptionFieldType,\n ProviderOptionEnumValue,\n ProviderOptionDirective,\n ProviderOptionShowIf,\n ProviderOptionField,\n ProviderOptionGroup,\n ProviderOptionsSchema,\n ProviderOptionsSchemaContext,\n} from './plugins/provider-options';\n\nexport type {\n // Scoring provider plugin types (primary)\n ScoringProviderMetadata,\n ScoringProviderConfigRequirements,\n ScoringProviderPlugin,\n ScoringProviderPluginExport,\n} from './plugins/scoring-provider';\n\nexport type {\n // Manifest types\n PluginCapability,\n PluginCategory,\n PluginStatus,\n PluginAuthor,\n PluginCompatibility,\n ProviderConfig,\n SearchProviderConfig,\n PluginPermissions,\n PluginManifest,\n InstalledPluginInfo,\n} from './plugins/manifest';\n\nexport type {\n // Theme plugin types\n ColorPalette,\n Typography,\n Spacing,\n Effects,\n ThemeTokens,\n FontDefinition,\n EmbeddedFont,\n ThemeMetadata,\n SubsystemOverrides,\n ThemePlugin,\n ThemePluginExport,\n} from './plugins/theme';\n\nexport type {\n // Roleplay template plugin types\n NarrationDelimiters,\n RoleplayTemplateConfig,\n RoleplayTemplateMetadata,\n RoleplayTemplatePlugin,\n RoleplayTemplatePluginExport,\n} from './plugins/roleplay-template';\n\nexport type {\n // System prompt plugin types\n SystemPromptData,\n SystemPromptMetadata,\n SystemPromptPlugin,\n SystemPromptPluginExport,\n} from './plugins/system-prompt';\n\nexport type {\n // Tool plugin types\n ToolMetadata,\n ToolHierarchyInfo,\n ToolEffect,\n ToolCallEffect,\n ToolExecutionContext,\n ToolExecutionResult,\n ToolPlugin,\n ToolPluginExport,\n} from './plugins/tool';\n\nexport type {\n // Search provider plugin types\n SearchProviderMetadata,\n SearchProviderConfigRequirements,\n SearchResult,\n SearchOutput,\n SearchProviderPlugin,\n SearchProviderPluginExport,\n} from './plugins/search-provider';\n\nexport type {\n // Moderation provider plugin types (deprecated, use scoring)\n ModerationProviderMetadata,\n ModerationProviderConfigRequirements,\n ModerationCategoryResult,\n ModerationResult,\n ModerationProviderPlugin,\n ModerationProviderPluginExport,\n} from './plugins/moderation-provider';\n\n// ============================================================================\n// Common Types\n// ============================================================================\n\nexport type { LogLevel, LogContext, PluginLogger } from './common/logger';\n\nexport type {\n CharacterPluginDataEntry,\n CharacterPluginDataMap,\n} from './common/character-plugin-data';\n\n// Error classes (these are values, not just types)\nexport {\n PluginError,\n ApiKeyError,\n ProviderApiError,\n RateLimitError,\n ModerationRejectionError,\n ConfigurationError,\n ModelNotFoundError,\n AttachmentError,\n ToolExecutionError,\n} from './common/errors';\n\n// Logger factories\nexport { createConsoleLogger, createNoopLogger } from './common/logger';\n\n// Host services: what the host provides to plugins, and the one pair of\n// functions that hands it over.\nexport type {\n PluginLoggerWithChild,\n PluginLoggerFactory,\n QuilltapHostServices,\n} from './common/host-services';\n\nexport {\n provideHostServices,\n withdrawHostServices,\n readHostServices,\n} from './common/host-services';\n\n// ============================================================================\n// Version\n// ============================================================================\n\n/**\n * Version of the plugin-types package.\n * Can be used at runtime to check compatibility.\n */\nexport const PLUGIN_TYPES_VERSION = '2.14.0';\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quilltap/plugin-types",
3
- "version": "2.13.0",
3
+ "version": "2.14.0",
4
4
  "description": "Type definitions for Quilltap plugin development",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -44,7 +44,7 @@
44
44
  "typecheck": "tsc --noEmit"
45
45
  },
46
46
  "devDependencies": {
47
- "@types/node": "^24.19.2",
47
+ "@types/node": "^24.19.4",
48
48
  "tsup": "^9.0.0",
49
49
  "typescript": "^6.0.3"
50
50
  },