@fgv/ts-extras 5.1.0-34 → 5.1.0-35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/packlets/ai-assist/apiClient.js +54 -108
- package/dist/packlets/ai-assist/apiClient.js.map +1 -1
- package/dist/packlets/ai-assist/chatRequestBuilders.js +55 -42
- package/dist/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
- package/dist/packlets/ai-assist/embeddingClient.js +346 -0
- package/dist/packlets/ai-assist/embeddingClient.js.map +1 -0
- package/dist/packlets/ai-assist/http.js +75 -0
- package/dist/packlets/ai-assist/http.js.map +1 -0
- package/dist/packlets/ai-assist/index.js +3 -2
- package/dist/packlets/ai-assist/index.js.map +1 -1
- package/dist/packlets/ai-assist/jsonCompletion.js +6 -8
- package/dist/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/dist/packlets/ai-assist/model.js +36 -1
- package/dist/packlets/ai-assist/model.js.map +1 -1
- package/dist/packlets/ai-assist/registry.js +77 -7
- package/dist/packlets/ai-assist/registry.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +22 -5
- package/dist/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js +15 -8
- package/dist/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
- package/dist/packlets/ai-assist/streamingClient.js +11 -5
- package/dist/packlets/ai-assist/streamingClient.js.map +1 -1
- package/dist/ts-extras.d.ts +349 -51
- package/lib/packlets/ai-assist/apiClient.d.ts +24 -34
- package/lib/packlets/ai-assist/apiClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/apiClient.js +64 -118
- package/lib/packlets/ai-assist/apiClient.js.map +1 -1
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts +56 -20
- package/lib/packlets/ai-assist/chatRequestBuilders.d.ts.map +1 -1
- package/lib/packlets/ai-assist/chatRequestBuilders.js +55 -40
- package/lib/packlets/ai-assist/chatRequestBuilders.js.map +1 -1
- package/lib/packlets/ai-assist/embeddingClient.d.ts +69 -0
- package/lib/packlets/ai-assist/embeddingClient.d.ts.map +1 -0
- package/lib/packlets/ai-assist/embeddingClient.js +350 -0
- package/lib/packlets/ai-assist/embeddingClient.js.map +1 -0
- package/lib/packlets/ai-assist/http.d.ts +24 -0
- package/lib/packlets/ai-assist/http.d.ts.map +1 -0
- package/lib/packlets/ai-assist/http.js +78 -0
- package/lib/packlets/ai-assist/http.js.map +1 -0
- package/lib/packlets/ai-assist/index.d.ts +3 -2
- package/lib/packlets/ai-assist/index.d.ts.map +1 -1
- package/lib/packlets/ai-assist/index.js +7 -1
- package/lib/packlets/ai-assist/index.js.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.d.ts.map +1 -1
- package/lib/packlets/ai-assist/jsonCompletion.js +6 -8
- package/lib/packlets/ai-assist/jsonCompletion.js.map +1 -1
- package/lib/packlets/ai-assist/model.d.ts +194 -2
- package/lib/packlets/ai-assist/model.d.ts.map +1 -1
- package/lib/packlets/ai-assist/model.js +37 -2
- package/lib/packlets/ai-assist/model.js.map +1 -1
- package/lib/packlets/ai-assist/registry.d.ts +23 -1
- package/lib/packlets/ai-assist/registry.d.ts.map +1 -1
- package/lib/packlets/ai-assist/registry.js +79 -7
- package/lib/packlets/ai-assist/registry.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts +21 -7
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js +22 -5
- package/lib/packlets/ai-assist/streamingAdapters/clientToolContinuationBuilder.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts +8 -11
- package/lib/packlets/ai-assist/streamingAdapters/common.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/common.js.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/proxy.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js +14 -7
- package/lib/packlets/ai-assist/streamingAdapters/proxy.js.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.d.ts.map +1 -1
- package/lib/packlets/ai-assist/streamingClient.js +11 -5
- package/lib/packlets/ai-assist/streamingClient.js.map +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"embeddingClient.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/embeddingClient.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ;;;;;;;;GAQG;AAEH,OAAO,EAAE,IAAI,EAAwB,OAAO,EAAkB,UAAU,EAAE,MAAM,eAAe,CAAC;AAEhG,OAAO,EAQL,YAAY,EACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,YAAY,CAAC;AACvE,OAAO,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC3E,OAAO,EAAqB,SAAS,EAAE,MAAM,QAAQ,CAAC;AAqDtD,MAAM,mBAAmB,GAAoC,UAAU,CAAC,MAAM,CAAuB;IACnG,KAAK,EAAE,UAAU,CAAC,MAAM;IACxB,SAAS,EAAE,UAAU,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC;CACjD,CAAC,CAAC;AACH,MAAM,oBAAoB,GAAqC,UAAU,CAAC,MAAM,CAAwB;I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MAAM,CAAE,IAAI,CAAC,wCAAwC,UAAU,CAAC,EAAE,WAAW,QAAQ,EAAE,CAAC,CAAC;IAEzF,MAAM,GAAG,GAAG,GAAG,QAAQ,mBAAmB,CAAC;IAC3C,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,GAAG,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;IAClE,IAAI,UAAU,CAAC,SAAS,EAAE,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IAClC,CAAC;IAED,MAAM,QAAQ,GAAG,UAAU,CAAC,KAAK,CAAC;IAClC,IAAI,OAAO,QAAQ,CAAC,KAAK,KAAK,QAAQ,EAAE,CAAC;QACvC,OAAO,IAAI,CAAC,UAAU,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;IAC1C,CAAC;IAED,OAAO,wBAAwB;SAC5B,QAAQ,CAAC,QAAQ,CAAC;SAClB,eAAe,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,oCAAoC,GAAG,EAAE,CAAC,CAAC;AACzE,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Cross-provider embedding client for AI assist. Mirrors the completion and\n * image-generation primitives in `apiClient.ts`: a single dispatcher\n * ({@link AiAssist.callProviderEmbedding}) resolves the provider descriptor's\n * embedding capability and routes to the per-format adapter. `text -> vector`,\n * batch in, `number[][]` out.\n *\n * @packageDocumentation\n */\n\nimport { fail, type Logging, Result, succeed, type Validator, Validators } from '@fgv/ts-utils';\n\nimport {\n type AiEmbeddingApiFormat,\n type IAiEmbeddingModelCapability,\n type IAiEmbeddingParams,\n type IAiEmbeddingResult,\n type IAiEmbeddingUsage,\n type IAiProviderDescriptor,\n type ModelSpec,\n resolveModel\n} from './model';\nimport { bearerAuthHeader, resolveEffectiveBaseUrl } from './endpoint';\nimport { resolveEmbeddingCapability, supportsEmbedding } from './registry';\nimport { type IAiApiConfig, fetchJson } from './http';\n\n// ============================================================================\n// Request types\n// ============================================================================\n\n/**\n * Parameters for a provider embedding request. Mirrors\n * {@link AiAssist.IProviderImageGenerationParams}.\n * @public\n */\nexport interface IProviderEmbeddingParams {\n /** The provider descriptor. */\n readonly descriptor: IAiProviderDescriptor;\n /** API key for authentication (empty string for keyless self-hosted providers). */\n readonly apiKey: string;\n /** The embedding request (input + optional knobs). */\n readonly params: IAiEmbeddingParams;\n /**\n * Optional model override — string or context-aware map. Uses\n * `descriptor.defaultModel.embedding` otherwise. Self-hosted providers\n * (`ollama`, `openai-compat`) have no default and require this.\n */\n readonly modelOverride?: ModelSpec;\n /** Optional logger for request/response observability. */\n readonly logger?: Logging.ILogger;\n /** Optional abort signal for cancelling the in-flight request. */\n readonly signal?: AbortSignal;\n /** Optional override of the descriptor's base URL; the `/embeddings` suffix is appended unchanged. */\n readonly endpoint?: string;\n}\n\n// ============================================================================\n// OpenAI-format (`/v1/embeddings`) response validators\n// ============================================================================\n\n/** @internal */\ninterface IOpenAiEmbeddingItem {\n index: number;\n embedding: number[];\n}\n/** @internal */\ninterface IOpenAiEmbeddingUsage {\n prompt_tokens?: number;\n total_tokens?: number;\n}\n/** @internal */\ninterface IOpenAiEmbeddingResponse {\n data: IOpenAiEmbeddingItem[];\n model?: string;\n usage?: IOpenAiEmbeddingUsage;\n}\n\nconst openAiEmbeddingItem: Validator<IOpenAiEmbeddingItem> = Validators.object<IOpenAiEmbeddingItem>({\n index: Validators.number,\n embedding: Validators.arrayOf(Validators.number)\n});\nconst openAiEmbeddingUsage: Validator<IOpenAiEmbeddingUsage> = Validators.object<IOpenAiEmbeddingUsage>({\n prompt_tokens: Validators.number.optional(),\n total_tokens: Validators.number.optional()\n});\nconst openAiEmbeddingResponse: Validator<IOpenAiEmbeddingResponse> =\n Validators.object<IOpenAiEmbeddingResponse>({\n data: Validators.arrayOf(openAiEmbeddingItem).withConstraint((arr) => arr.length > 0),\n model: Validators.string.optional(),\n usage: openAiEmbeddingUsage.optional()\n });\n\n// ============================================================================\n// Shared helpers\n// ============================================================================\n\n/**\n * Normalizes the `input` field (string | string[]) into a concrete string array.\n * @internal\n */\nfunction toInputArray(input: string | ReadonlyArray<string>): ReadonlyArray<string> {\n return typeof input === 'string' ? [input] : input;\n}\n\n/**\n * Builds an {@link IAiEmbeddingUsage} from OpenAI-format usage, or `undefined`\n * when no token counts are reported.\n * @internal\n */\nfunction toEmbeddingUsage(usage: IOpenAiEmbeddingUsage | undefined): IAiEmbeddingUsage | undefined {\n if (usage === undefined || (usage.prompt_tokens === undefined && usage.total_tokens === undefined)) {\n return undefined;\n }\n return {\n ...(usage.prompt_tokens !== undefined ? { promptTokens: usage.prompt_tokens } : {}),\n ...(usage.total_tokens !== undefined ? { totalTokens: usage.total_tokens } : {})\n };\n}\n\n// ============================================================================\n// OpenAI-format adapter\n// ============================================================================\n\n/**\n * Calls the OpenAI `/v1/embeddings` endpoint. Serves OpenAI, Ollama (via `/v1`),\n * openai-compat self-hosted servers, and Mistral. Sends `dimensions` only when\n * the capability declares `supportsDimensions`; always requests\n * `encoding_format: 'float'`.\n *\n * @remarks\n * `encoding_format: 'float'` is a known assumption (design §14 #5): a strict\n * openai-compat server could in principle reject the field, but mainstream\n * servers accept it and it keeps us off the base64 decode path. Low risk.\n *\n * @internal\n */\nasync function callOpenAiEmbeddings(\n config: IAiApiConfig,\n inputs: ReadonlyArray<string>,\n request: IAiEmbeddingParams,\n capability: IAiEmbeddingModelCapability,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<IAiEmbeddingResult>> {\n const body: Record<string, unknown> = {\n model: config.model,\n input: inputs,\n encoding_format: 'float'\n };\n if (capability.supportsDimensions && request.dimensions !== undefined) {\n body.dimensions = request.dimensions;\n }\n const headers: Record<string, string> = bearerAuthHeader(config.apiKey);\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI embedding: format=openai-embeddings, model=${config.model}, inputs=${inputs.length}`);\n\n const jsonResult = await fetchJson(`${config.baseUrl}/embeddings`, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return openAiEmbeddingResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `OpenAI embeddings API response: ${msg}`)\n .onSuccess((response) => {\n // The spec allows `data` in any order; align to request order by `index`.\n const ordered = [...response.data].sort((a, b) => a.index - b.index);\n // Validate the response is well-formed against the request before trusting\n // the alignment: a compat server could return an incomplete batch, gapped\n // or duplicate indices, or ragged dimensions — all of which would silently\n // yield misaligned/partial vectors. (inputs is non-empty here; the\n // empty-input case short-circuits before the wire call.)\n if (ordered.length !== inputs.length) {\n return fail(\n `OpenAI embeddings API response: expected ${inputs.length} embedding(s), got ${ordered.length}`\n );\n }\n // After sorting, a perfect 0..n-1 sequence has item.index === position at\n // every slot. Any gap OR duplicate shifts a later element off its position\n // (the second copy of value k, or the element after a missing k, lands at\n // position > its index), so this single walk catches both.\n const misindexed = ordered.findIndex((item, i) => item.index !== i);\n if (misindexed !== -1) {\n return fail(\n `OpenAI embeddings API response: malformed embedding indices ` +\n `(expected 0..${inputs.length - 1}; gap or duplicate at position ${misindexed})`\n );\n }\n const vectors = ordered.map((item) => item.embedding);\n const dimensions = vectors[0].length;\n const ragged = vectors.findIndex((v) => v.length !== dimensions);\n if (ragged !== -1) {\n return fail(\n `OpenAI embeddings API response: inconsistent vector dimensionality ` +\n `(vector ${ragged} has length ${vectors[ragged].length}, expected ${dimensions})`\n );\n }\n const usage = toEmbeddingUsage(response.usage);\n return succeed({\n vectors,\n model: response.model ?? config.model,\n dimensions,\n ...(usage !== undefined ? { usage } : {})\n });\n });\n}\n\n// ============================================================================\n// Gemini-format (`:batchEmbedContents`) response validators + adapter\n// ============================================================================\n\n/** @internal */\ninterface IGeminiEmbedding {\n values: number[];\n}\n/** @internal */\ninterface IGeminiEmbeddingResponse {\n embeddings: IGeminiEmbedding[];\n}\n\nconst geminiEmbedding: Validator<IGeminiEmbedding> = Validators.object<IGeminiEmbedding>({\n values: Validators.arrayOf(Validators.number)\n});\nconst geminiEmbeddingResponse: Validator<IGeminiEmbeddingResponse> =\n Validators.object<IGeminiEmbeddingResponse>({\n embeddings: Validators.arrayOf(geminiEmbedding).withConstraint((arr) => arr.length > 0)\n });\n\n/**\n * Maps a cross-provider {@link AiAssist.AiEmbeddingTaskType} (kebab-case) to the\n * Gemini wire form (`SCREAMING_SNAKE_CASE`), e.g. `'retrieval-document'` becomes\n * `'RETRIEVAL_DOCUMENT'`.\n * @internal\n */\nfunction toGeminiTaskType(taskType: string): string {\n return taskType.replace(/-/g, '_').toUpperCase();\n}\n\n/**\n * Strips a leading `models/` from a model id so the URL path and the per-request\n * `model` field can each apply the prefix exactly once.\n * @internal\n */\nfunction bareGeminiModel(model: string): string {\n return model.startsWith('models/') ? model.slice('models/'.length) : model;\n}\n\n/**\n * Calls the Google Gemini `:batchEmbedContents` endpoint. Always uses the batch\n * route (a single input is a one-element batch). Sends `taskType` /\n * `outputDimensionality` only when the capability declares support. Gemini does\n * not report token usage for embeddings, so `usage` is omitted.\n * @internal\n */\nasync function callGeminiEmbeddings(\n config: IAiApiConfig,\n inputs: ReadonlyArray<string>,\n request: IAiEmbeddingParams,\n capability: IAiEmbeddingModelCapability,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<IAiEmbeddingResult>> {\n const bare = bareGeminiModel(config.model);\n const qualified = `models/${bare}`;\n // `request.taskType` is the open `AiEmbeddingTaskType` union (includes `string & {}`),\n // which `!== undefined` cannot narrow to `string`; resolve it cast-free here.\n const taskType =\n capability.supportsTaskType && request.taskType !== undefined\n ? toGeminiTaskType(request.taskType)\n : undefined;\n const sendDimensions = capability.supportsDimensions && request.dimensions !== undefined;\n\n const requests = inputs.map((text) => ({\n model: qualified,\n content: { parts: [{ text }] },\n ...(taskType !== undefined ? { taskType } : {}),\n ...(sendDimensions ? { outputDimensionality: request.dimensions } : {})\n }));\n const body: Record<string, unknown> = { requests };\n const headers: Record<string, string> = { 'x-goog-api-key': config.apiKey };\n const url = `${config.baseUrl}/models/${bare}:batchEmbedContents`;\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI embedding: format=gemini-embeddings, model=${bare}, inputs=${inputs.length}`);\n\n const jsonResult = await fetchJson(url, headers, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n return geminiEmbeddingResponse\n .validate(jsonResult.value)\n .withErrorFormat((msg) => `Gemini embeddings API response: ${msg}`)\n .onSuccess((response) => {\n // Gemini returns embeddings aligned to request order (no index field), so\n // there is no per-item index to re-sort or gap-check (unlike the OpenAI\n // path). Validate the response is well-formed against the request before\n // trusting the positional alignment: a truncated batch or ragged\n // dimensions would silently yield misaligned/partial vectors. (inputs is\n // non-empty here; the empty-input case short-circuits before the wire call.)\n const vectors = response.embeddings.map((e) => e.values);\n if (vectors.length !== inputs.length) {\n return fail(\n `Gemini embeddings API response: expected ${inputs.length} embedding(s), got ${vectors.length}`\n );\n }\n const dimensions = vectors[0].length;\n const ragged = vectors.findIndex((v) => v.length !== dimensions);\n if (ragged !== -1) {\n return fail(\n `Gemini embeddings API response: inconsistent vector dimensionality ` +\n `(vector ${ragged} has length ${vectors[ragged].length}, expected ${dimensions})`\n );\n }\n const result: IAiEmbeddingResult = { vectors, model: bare, dimensions };\n return succeed(result);\n });\n}\n\n// ============================================================================\n// Dispatcher\n// ============================================================================\n\n/**\n * Notes any caller-supplied embedding knobs that the resolved capability does\n * not honor. Per design §7 these are a no-op (logged, never a failure) so a\n * cross-provider call site can pass `taskType`/`dimensions` once and have them\n * apply only where supported.\n * @internal\n */\nfunction noteUnsupportedKnobs(\n model: string,\n request: IAiEmbeddingParams,\n capability: IAiEmbeddingModelCapability,\n logger?: Logging.ILogger\n): void {\n if (logger === undefined) {\n return;\n }\n if (request.taskType !== undefined && !capability.supportsTaskType) {\n logger.info(`AI embedding: model \"${model}\" ignores taskType (not supported); proceeding without it`);\n }\n if (request.dimensions !== undefined && !capability.supportsDimensions) {\n logger.info(`AI embedding: model \"${model}\" ignores dimensions (not supported); proceeding without it`);\n }\n}\n\n/**\n * Calls the appropriate embedding API for a given provider. Routes by the\n * `format` of the resolved {@link AiAssist.IAiEmbeddingModelCapability}:\n * `'openai-embeddings'` or `'gemini-embeddings'`.\n *\n * @remarks\n * - Rejects up front when the provider declares no embedding capability, when no\n * embedding model resolves, or when the batch exceeds the capability's\n * `maxBatchSize` (no auto-chunking).\n * - An empty `input` array short-circuits to an empty result with no wire call\n * (most providers HTTP-400 on empty input).\n * - Caller-supplied `dimensions`/`taskType` that the model doesn't support are a\n * no-op (logged), not a failure (design §7).\n *\n * @param params - Request parameters including descriptor, API key, and input.\n * @returns The embedding vectors aligned to input order, or a failure.\n * @public\n */\nexport async function callProviderEmbedding(\n params: IProviderEmbeddingParams\n): Promise<Result<IAiEmbeddingResult>> {\n const { descriptor, apiKey, params: request, modelOverride, logger, signal, endpoint } = params;\n\n if (!supportsEmbedding(descriptor)) {\n return fail(`provider \"${descriptor.id}\" does not support embeddings`);\n }\n\n const model = resolveModel(modelOverride ?? descriptor.defaultModel, 'embedding');\n if (model.length === 0) {\n return fail(\n `provider \"${descriptor.id}\": no embedding model resolved; ` +\n `pass modelOverride or set descriptor.defaultModel ` +\n `(a plain string, or an object with an \"embedding\" entry)`\n );\n }\n\n const capability = resolveEmbeddingCapability(descriptor, model);\n if (capability === undefined) {\n return fail(`provider \"${descriptor.id}\" does not support embeddings for model \"${model}\"`);\n }\n\n const inputs = toInputArray(request.input);\n if (inputs.length === 0) {\n // Short-circuit: empty batch never hits the wire (design §14 #2).\n return succeed({ vectors: [], model, dimensions: 0 });\n }\n if (capability.maxBatchSize !== undefined && inputs.length > capability.maxBatchSize) {\n return fail(\n `provider \"${descriptor.id}\": embedding batch of ${inputs.length} exceeds ` +\n `model \"${model}\" maximum of ${capability.maxBatchSize}`\n );\n }\n\n const baseUrlResult = resolveEffectiveBaseUrl(descriptor, endpoint);\n if (baseUrlResult.isFailure()) {\n return fail(baseUrlResult.message);\n }\n\n noteUnsupportedKnobs(model, request, capability, logger);\n\n const config: IAiApiConfig = { baseUrl: baseUrlResult.value, apiKey, model };\n\n return dispatchEmbedding(capability.format, config, inputs, request, capability, logger, signal);\n}\n\n/**\n * Routes a resolved embedding request to the per-format adapter.\n * @internal\n */\nfunction dispatchEmbedding(\n format: AiEmbeddingApiFormat,\n config: IAiApiConfig,\n inputs: ReadonlyArray<string>,\n request: IAiEmbeddingParams,\n capability: IAiEmbeddingModelCapability,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<IAiEmbeddingResult>> {\n switch (format) {\n case 'openai-embeddings':\n return callOpenAiEmbeddings(config, inputs, request, capability, logger, signal);\n case 'gemini-embeddings':\n return callGeminiEmbeddings(config, inputs, request, capability, logger, signal);\n /* c8 ignore next 4 - defensive: exhaustive switch guaranteed by TypeScript */\n default: {\n const _exhaustive: never = format;\n return Promise.resolve(fail(`unsupported embedding API format: ${String(_exhaustive)}`));\n }\n }\n}\n\n// ============================================================================\n// Proxied embedding\n// ============================================================================\n\nconst proxiedEmbeddingUsage: Validator<IAiEmbeddingUsage> = Validators.object<IAiEmbeddingUsage>({\n promptTokens: Validators.number.optional(),\n totalTokens: Validators.number.optional()\n});\nconst proxiedEmbeddingResponse: Validator<IAiEmbeddingResult> = Validators.object<IAiEmbeddingResult>({\n vectors: Validators.arrayOf(Validators.arrayOf(Validators.number)),\n model: Validators.string,\n dimensions: Validators.number,\n usage: proxiedEmbeddingUsage.optional()\n});\n\n/**\n * Calls the embedding endpoint on a proxy server instead of calling the provider\n * API directly from the browser. Endpoint: `POST ${proxyUrl}/api/ai/embedding`.\n * Request body: `{ providerId, apiKey, params, modelOverride? }`. The proxy\n * handles descriptor lookup, model/capability resolution, and provider dispatch.\n * Error body `{ error: string }` is surfaced as `proxy: ${error}`.\n *\n * @param proxyUrl - Base URL of the proxy server (e.g. `http://localhost:3001`).\n * @param params - Same parameters as {@link AiAssist.callProviderEmbedding}.\n * @returns The embedding result, or a failure.\n * @public\n */\nexport async function callProxiedEmbedding(\n proxyUrl: string,\n params: IProviderEmbeddingParams\n): Promise<Result<IAiEmbeddingResult>> {\n const { descriptor, apiKey, params: request, modelOverride, logger, signal } = params;\n\n const body: Record<string, unknown> = {\n providerId: descriptor.id,\n apiKey,\n params: request\n };\n if (modelOverride !== undefined) {\n body.modelOverride = modelOverride;\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.info(`AI embedding proxy request: provider=${descriptor.id}, proxy=${proxyUrl}`);\n\n const url = `${proxyUrl}/api/ai/embedding`;\n const jsonResult = await fetchJson(url, {}, body, logger, signal);\n if (jsonResult.isFailure()) {\n return fail(jsonResult.message);\n }\n\n const response = jsonResult.value;\n if (typeof response.error === 'string') {\n return fail(`proxy: ${response.error}`);\n }\n\n return proxiedEmbeddingResponse\n .validate(response)\n .withErrorFormat((msg) => `proxy returned invalid response: ${msg}`);\n}\n"]}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Copyright (c) 2026 Erik Fortune
|
|
2
|
+
//
|
|
3
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
// of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
// in the Software without restriction, including without limitation the rights
|
|
6
|
+
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
// copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
// furnished to do so, subject to the following conditions:
|
|
9
|
+
//
|
|
10
|
+
// The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
// copies or substantial portions of the Software.
|
|
12
|
+
//
|
|
13
|
+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
// SOFTWARE.
|
|
20
|
+
/**
|
|
21
|
+
* Shared low-level HTTP helpers for the AI-assist provider clients (completion,
|
|
22
|
+
* image generation, embedding). Internal to the packlet.
|
|
23
|
+
* @packageDocumentation
|
|
24
|
+
*/
|
|
25
|
+
import { isJsonObject } from '@fgv/ts-json-base';
|
|
26
|
+
import { fail, succeed } from '@fgv/ts-utils';
|
|
27
|
+
/**
|
|
28
|
+
* Makes a JSON POST request and returns the parsed object body, or a failure.
|
|
29
|
+
* Non-2xx responses, network errors, invalid JSON, and non-object JSON bodies
|
|
30
|
+
* are all surfaced as `Result.fail`.
|
|
31
|
+
* @internal
|
|
32
|
+
*/
|
|
33
|
+
export async function fetchJson(url, headers, body, logger, signal) {
|
|
34
|
+
/* c8 ignore next 1 - optional logger */
|
|
35
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API request: POST ${url}`);
|
|
36
|
+
let response;
|
|
37
|
+
try {
|
|
38
|
+
response = await fetch(url, {
|
|
39
|
+
method: 'POST',
|
|
40
|
+
headers: Object.assign({ 'Content-Type': 'application/json' }, headers),
|
|
41
|
+
body: JSON.stringify(body),
|
|
42
|
+
signal
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
47
|
+
/* c8 ignore next 1 - optional logger */
|
|
48
|
+
logger === null || logger === void 0 ? void 0 : logger.error(`AI API request failed: ${detail}`);
|
|
49
|
+
return fail(`AI API request failed: ${detail}`);
|
|
50
|
+
}
|
|
51
|
+
if (!response.ok) {
|
|
52
|
+
const errorText = await response.text().catch(() => 'unknown error');
|
|
53
|
+
/* c8 ignore next 1 - optional logger */
|
|
54
|
+
logger === null || logger === void 0 ? void 0 : logger.error(`AI API returned ${response.status}: ${errorText}`);
|
|
55
|
+
return fail(`AI API returned ${response.status}: ${errorText}`);
|
|
56
|
+
}
|
|
57
|
+
/* c8 ignore next 1 - optional logger */
|
|
58
|
+
logger === null || logger === void 0 ? void 0 : logger.detail(`AI API response: ${response.status}`);
|
|
59
|
+
let json;
|
|
60
|
+
try {
|
|
61
|
+
json = await response.json();
|
|
62
|
+
}
|
|
63
|
+
catch (_a) {
|
|
64
|
+
/* c8 ignore next 1 - optional logger */
|
|
65
|
+
logger === null || logger === void 0 ? void 0 : logger.error('AI API returned invalid JSON response');
|
|
66
|
+
return fail('AI API returned invalid JSON response');
|
|
67
|
+
}
|
|
68
|
+
if (!isJsonObject(json)) {
|
|
69
|
+
/* c8 ignore next 1 - optional logger */
|
|
70
|
+
logger === null || logger === void 0 ? void 0 : logger.error('AI API returned non-object JSON response');
|
|
71
|
+
return fail('AI API returned non-object JSON response');
|
|
72
|
+
}
|
|
73
|
+
return succeed(json);
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=http.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/http.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AACxE,2DAA2D;AAC3D,EAAE;AACF,iFAAiF;AACjF,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,yEAAyE;AACzE,gFAAgF;AAChF,gFAAgF;AAChF,YAAY;AAEZ;;;;GAIG;AAEH,OAAO,EAAE,YAAY,EAAmB,MAAM,mBAAmB,CAAC;AAClE,OAAO,EAAE,IAAI,EAAwB,OAAO,EAAE,MAAM,eAAe,CAAC;AAYpE;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,GAAW,EACX,OAA+B,EAC/B,IAAa,EACb,MAAwB,EACxB,MAAoB;IAEpB,wCAAwC;IACxC,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,CAAC,wBAAwB,GAAG,EAAE,CAAC,CAAC;IAE9C,IAAI,QAAkB,CAAC;IACvB,IAAI,CAAC;QACH,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,EAAE;YAC1B,MAAM,EAAE,MAAM;YACd,OAAO,kBACL,cAAc,EAAE,kBAAkB,IAC/B,OAAO,CACX;YACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;YAC1B,MAAM;SACP,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,GAAY,EAAE,CAAC;QACtB,MAAM,MAAM,GAAG,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM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yright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * Shared low-level HTTP helpers for the AI-assist provider clients (completion,\n * image generation, embedding). Internal to the packlet.\n * @packageDocumentation\n */\n\nimport { isJsonObject, type JsonObject } from '@fgv/ts-json-base';\nimport { fail, type Logging, Result, succeed } from '@fgv/ts-utils';\n\n/**\n * Internal API configuration built from a provider descriptor.\n * @internal\n */\nexport interface IAiApiConfig {\n readonly baseUrl: string;\n readonly apiKey: string;\n readonly model: string;\n}\n\n/**\n * Makes a JSON POST request and returns the parsed object body, or a failure.\n * Non-2xx responses, network errors, invalid JSON, and non-object JSON bodies\n * are all surfaced as `Result.fail`.\n * @internal\n */\nexport async function fetchJson(\n url: string,\n headers: Record<string, string>,\n body: unknown,\n logger?: Logging.ILogger,\n signal?: AbortSignal\n): Promise<Result<JsonObject>> {\n /* c8 ignore next 1 - optional logger */\n logger?.detail(`AI API request: POST ${url}`);\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...headers\n },\n body: JSON.stringify(body),\n signal\n });\n } catch (err: unknown) {\n const detail = err instanceof Error ? err.message : String(err);\n /* c8 ignore next 1 - optional logger */\n logger?.error(`AI API request failed: ${detail}`);\n return fail(`AI API request failed: ${detail}`);\n }\n\n if (!response.ok) {\n const errorText = await response.text().catch(() => 'unknown error');\n /* c8 ignore next 1 - optional logger */\n logger?.error(`AI API returned ${response.status}: ${errorText}`);\n return fail(`AI API returned ${response.status}: ${errorText}`);\n }\n\n /* c8 ignore next 1 - optional logger */\n logger?.detail(`AI API response: ${response.status}`);\n\n let json: unknown;\n try {\n json = await response.json();\n } catch {\n /* c8 ignore next 1 - optional logger */\n logger?.error('AI API returned invalid JSON response');\n return fail('AI API returned invalid JSON response');\n }\n\n if (!isJsonObject(json)) {\n /* c8 ignore next 1 - optional logger */\n logger?.error('AI API returned non-object JSON response');\n return fail('AI API returned non-object JSON response');\n }\n return succeed(json);\n}\n"]}
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
* AI assist packlet - provider registry, prompt class, settings, and API client.
|
|
3
3
|
* @packageDocumentation
|
|
4
4
|
*/
|
|
5
|
-
export { AiPrompt, DEFAULT_AI_ASSIST, allModelSpecKeys, MODEL_SPEC_BASE_KEY, resolveModel, toDataUrl } from './model';
|
|
5
|
+
export { AiPrompt, allModelCapabilities, DEFAULT_AI_ASSIST, allModelSpecKeys, MODEL_SPEC_BASE_KEY, resolveModel, toDataUrl } from './model';
|
|
6
6
|
export { resolveImageOptions, validateResolvedOptions } from './imageOptionsResolver';
|
|
7
|
-
export { allProviderIds, getProviderDescriptors, getProviderDescriptor, resolveImageCapability, supportsImageGeneration, DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';
|
|
7
|
+
export { allProviderIds, getProviderDescriptors, getProviderDescriptor, resolveImageCapability, supportsImageGeneration, resolveEmbeddingCapability, supportsEmbedding, DEFAULT_MODEL_CAPABILITY_CONFIG } from './registry';
|
|
8
8
|
export { callProviderCompletion, callProxiedCompletion, callProviderImageGeneration, callProxiedImageGeneration, callProviderListModels, callProxiedListModels } from './apiClient';
|
|
9
|
+
export { callProviderEmbedding, callProxiedEmbedding } from './embeddingClient';
|
|
9
10
|
export { callProviderCompletionStream, callProxiedCompletionStream, executeClientToolTurn } from './streamingClient';
|
|
10
11
|
export { aiProviderId, aiServerToolType, aiWebSearchToolConfig, aiServerToolConfig, aiClientToolConfig, aiToolEnablement, aiAssistProviderConfig, aiAssistSettings, modelSpecKey, modelSpec } from './converters';
|
|
11
12
|
export { resolveEffectiveTools } from './toolFormats';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EACL,QAAQ,EAER,oBAAoB,EA2BpB,iBAAiB,EA8CjB,gBAAgB,EAChB,mBAAmB,EACnB,YAAY,EACZ,SAAS,EAiBV,MAAM,SAAS,CAAC;AAEjB,OAAO,EAEL,mBAAmB,EACnB,uBAAuB,EACxB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,EACL,cAAc,EACd,sBAAsB,EACtB,qBAAqB,EACrB,sBAAsB,EACtB,uBAAuB,EACvB,0BAA0B,EAC1B,iBAAiB,EACjB,+BAA+B,EAChC,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,EAC1B,sBAAsB,EACtB,qBAAqB,EAItB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,qBAAqB,EACrB,oBAAoB,EAErB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,4BAA4B,EAC5B,2BAA2B,EAE3B,qBAAqB,EAGtB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,EAClB,kBAAkB,EAClB,gBAAgB,EAChB,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,SAAS,EACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EACL,eAAe,EACf,qBAAqB,EAItB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EAIvB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAAE,6BAA6B,EAAgC,MAAM,2BAA2B,CAAC","sourcesContent":["/**\n * AI assist packlet - provider registry, prompt class, settings, and API client.\n * @packageDocumentation\n */\n\nexport {\n AiPrompt,\n type AiModelCapability,\n allModelCapabilities,\n type AiProviderId,\n type AiServerToolType,\n type AiServerToolConfig,\n type AiToolConfig,\n type IAiWebSearchToolConfig,\n type IAiClientToolConfig,\n type IAiClientTool,\n type IAiClientToolCallSummary,\n type IAiClientToolContinuation,\n type IAiClientToolTurnResult,\n type IAiToolEnablement,\n type IAiCompletionResponse,\n type IChatMessage,\n type IChatRequest,\n type AiApiFormat,\n type AiImageApiFormat,\n type AiEmbeddingApiFormat,\n type AiEmbeddingTaskType,\n type IAiEmbeddingModelCapability,\n type IAiEmbeddingParams,\n type IAiEmbeddingUsage,\n type IAiEmbeddingResult,\n type IAiImageModelCapability,\n type IAiProviderDescriptor,\n type IAiAssistProviderConfig,\n type IAiAssistSettings,\n DEFAULT_AI_ASSIST,\n type IAiAssistKeyStore,\n type IAiImageAttachment,\n type IAiImageData,\n type AiImageSize,\n type AiImageQuality,\n type DallE2Size,\n type DallE3Size,\n type GptImageSize,\n type DallE3Quality,\n type GptImageQuality,\n type DallEModelNames,\n type GptImageModelNames,\n type GrokImagineModelNames,\n type Imagen4ModelNames,\n type GeminiFlashImageModelNames,\n type IDallEImageGenerationConfig,\n type IGptImageGenerationConfig,\n type IGrokImagineImageGenerationConfig,\n type IImagen4GenerationConfig,\n type IGeminiFlashImageGenerationConfig,\n type IDallEModelOptions,\n type IGptImageModelOptions,\n type IGrokImagineModelOptions,\n type IImagen4ModelOptions,\n type IGeminiFlashImageModelOptions,\n type IOtherModelOptions,\n type IModelFamilyConfig,\n type IAiImageGenerationOptions,\n type IAiImageGenerationParams,\n type IAiGeneratedImage,\n type IAiImageGenerationResponse,\n type IAiModelCapabilityRule,\n type IAiModelCapabilityConfig,\n type IAiModelInfo,\n type IAiStreamEvent,\n type IAiStreamTextDelta,\n type IAiStreamToolEvent,\n type IAiStreamToolUseStart,\n type IAiStreamToolUseDelta,\n type IAiStreamToolUseComplete,\n type IAiStreamDone,\n type IAiStreamError,\n type ModelSpec,\n type ModelSpecKey,\n type IModelSpecMap,\n allModelSpecKeys,\n MODEL_SPEC_BASE_KEY,\n resolveModel,\n toDataUrl,\n type AiThinkingMode,\n type IThinkingConfig,\n type IThinkingProviderConfig,\n type IAnthropicThinkingOptions,\n type IOpenAiThinkingOptions,\n type IGeminiThinkingOptions,\n type IXAiThinkingOptions,\n type IOtherThinkingOptions,\n type IAnthropicThinkingConfig,\n type IOpenAiThinkingConfig,\n type IGeminiThinkingConfig,\n type IXAiThinkingConfig,\n type AnthropicThinkingModelNames,\n type OpenAiThinkingModelNames,\n type GeminiThinkingModelNames,\n type XAiThinkingModelNames\n} from './model';\n\nexport {\n type IResolvedImageOptions,\n resolveImageOptions,\n validateResolvedOptions\n} from './imageOptionsResolver';\n\nexport {\n allProviderIds,\n getProviderDescriptors,\n getProviderDescriptor,\n resolveImageCapability,\n supportsImageGeneration,\n resolveEmbeddingCapability,\n supportsEmbedding,\n DEFAULT_MODEL_CAPABILITY_CONFIG\n} from './registry';\n\nexport {\n callProviderCompletion,\n callProxiedCompletion,\n callProviderImageGeneration,\n callProxiedImageGeneration,\n callProviderListModels,\n callProxiedListModels,\n type IProviderCompletionParams,\n type IProviderImageGenerationParams,\n type IProviderListModelsParams\n} from './apiClient';\n\nexport {\n callProviderEmbedding,\n callProxiedEmbedding,\n type IProviderEmbeddingParams\n} from './embeddingClient';\n\nexport {\n callProviderCompletionStream,\n callProxiedCompletionStream,\n type IProviderCompletionStreamParams,\n executeClientToolTurn,\n type IExecuteClientToolTurnParams,\n type IExecuteClientToolTurnResult\n} from './streamingClient';\n\nexport {\n aiProviderId,\n aiServerToolType,\n aiWebSearchToolConfig,\n aiServerToolConfig,\n aiClientToolConfig,\n aiToolEnablement,\n aiAssistProviderConfig,\n aiAssistSettings,\n modelSpecKey,\n modelSpec\n} from './converters';\n\nexport { resolveEffectiveTools } from './toolFormats';\n\nexport {\n extractJsonText,\n fencedStringifiedJson,\n type IFencedStringifiedJsonExtractorOptions,\n type IFencedStringifiedJsonOptions,\n type JsonTextExtractor\n} from './jsonResponse';\n\nexport {\n generateJsonCompletion,\n SMART_JSON_PROMPT_HINT,\n type IGenerateJsonCompletionParams,\n type IGenerateJsonCompletionResult,\n type JsonPromptHint\n} from './jsonCompletion';\n\nexport { anthropicEffortToBudgetTokens, type IResolvedThinkingConfig } from './thinkingOptionsResolver';\n"]}
|
|
@@ -39,7 +39,6 @@ var __rest = (this && this.__rest) || function (s, e) {
|
|
|
39
39
|
import { fail, succeed } from '@fgv/ts-utils';
|
|
40
40
|
import { callProviderCompletion } from './apiClient';
|
|
41
41
|
import { fencedStringifiedJson } from './jsonResponse';
|
|
42
|
-
import { AiPrompt } from './model';
|
|
43
42
|
/**
|
|
44
43
|
* Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}
|
|
45
44
|
* is `'smart'` (the default). Designed to discourage code fences and prose in
|
|
@@ -48,13 +47,12 @@ import { AiPrompt } from './model';
|
|
|
48
47
|
*/
|
|
49
48
|
export const SMART_JSON_PROMPT_HINT = 'Respond with raw JSON only — no Markdown code fences, no explanatory prose, ' +
|
|
50
49
|
'no preamble or trailing commentary. The response must parse with JSON.parse.';
|
|
51
|
-
function applyPromptHint(
|
|
50
|
+
function applyPromptHint(system, hint) {
|
|
52
51
|
if (hint === 'none') {
|
|
53
|
-
return
|
|
52
|
+
return system;
|
|
54
53
|
}
|
|
55
54
|
const suffix = hint === 'smart' ? SMART_JSON_PROMPT_HINT : hint;
|
|
56
|
-
|
|
57
|
-
return new AiPrompt(prompt.user, system, prompt.attachments);
|
|
55
|
+
return system !== undefined && system.length > 0 ? `${system}\n\n${suffix}` : suffix;
|
|
58
56
|
}
|
|
59
57
|
/**
|
|
60
58
|
* Calls {@link AiAssist.callProviderCompletion}, then runs the response text
|
|
@@ -76,13 +74,13 @@ function applyPromptHint(prompt, hint) {
|
|
|
76
74
|
* @public
|
|
77
75
|
*/
|
|
78
76
|
export async function generateJsonCompletion(params) {
|
|
79
|
-
const { converter, jsonConverter, promptHint = 'smart',
|
|
77
|
+
const { converter, jsonConverter, promptHint = 'smart', system } = params, rest = __rest(params, ["converter", "jsonConverter", "promptHint", "system"]);
|
|
80
78
|
if (jsonConverter === undefined && converter === undefined) {
|
|
81
79
|
return fail('generateJsonCompletion: either converter or jsonConverter must be provided.');
|
|
82
80
|
}
|
|
83
81
|
const pipeline = jsonConverter !== null && jsonConverter !== void 0 ? jsonConverter : fencedStringifiedJson({ inner: converter });
|
|
84
|
-
const
|
|
85
|
-
const response = await callProviderCompletion(Object.assign(Object.assign({}, rest), {
|
|
82
|
+
const augmentedSystem = applyPromptHint(system, promptHint);
|
|
83
|
+
const response = await callProviderCompletion(Object.assign(Object.assign({}, rest), { system: augmentedSystem }));
|
|
86
84
|
if (response.isFailure()) {
|
|
87
85
|
return fail(response.message);
|
|
88
86
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"jsonCompletion.js","sourceRoot":"","sources":["../../../src/packlets/ai-assist/jsonCompletion.ts"],"names":[],"mappings":"AAAA,kCAAkC;AAClC,EAAE;AACF,+EAA+E;AAC/E,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,wEAAwE;AAC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E,CAAC,CAAC,CAAC;AAC7F,CAAC","sourcesContent":["// Copyright (c) 2026 Erik Fortune\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n/**\n * `generateJsonCompletion<T>` — request a JSON-shaped completion from any\n * provider supported by AiAssist and validate it against a caller-supplied\n * `Converter<T>` or `Validator<T>`. Wraps fence/preamble tolerance + parsing +\n * validation into a single call so consumers don't reinvent the pipeline.\n *\n * @packageDocumentation\n */\n\nimport { type Converter, fail, Result, succeed, type Validator } from '@fgv/ts-utils';\n\nimport { callProviderCompletion, type IProviderCompletionParams } from './apiClient';\nimport { fencedStringifiedJson } from './jsonResponse';\nimport { type IAiCompletionResponse } from './model';\n\n/**\n * Default system-prompt suffix appended when {@link AiAssist.IGenerateJsonCompletionParams.promptHint}\n * is `'smart'` (the default). Designed to discourage code fences and prose in\n * the model's response while still tolerating them via the read-side extractor.\n * @public\n */\nexport const SMART_JSON_PROMPT_HINT: string =\n 'Respond with raw JSON only — no Markdown code fences, no explanatory prose, ' +\n 'no preamble or trailing commentary. The response must parse with JSON.parse.';\n\n/**\n * Controls the optional system-prompt augmentation applied by\n * {@link AiAssist.generateJsonCompletion}.\n *\n * - `'smart'` (default): append {@link AiAssist.SMART_JSON_PROMPT_HINT}.\n * - `'none'`: do not modify the prompt.\n * - A string: append the supplied text verbatim.\n *\n * @remarks\n * The `string & {}` branch is the standard TypeScript trick that prevents\n * the literal members from being widened away — callers still get\n * autocomplete for `'smart'` and `'none'` while accepting any string.\n *\n * @public\n */\nexport type JsonPromptHint = 'smart' | 'none' | (string & {});\n\n/**\n * Parameters for {@link AiAssist.generateJsonCompletion}. Extends\n * {@link AiAssist.IProviderCompletionParams} with JSON-validation knobs.\n * @public\n */\nexport interface IGenerateJsonCompletionParams<T> extends IProviderCompletionParams {\n /**\n * Caller-supplied `Converter<T>` or `Validator<T>` applied to the parsed\n * JSON value. Wrapped internally in {@link AiAssist.fencedStringifiedJson}\n * unless {@link AiAssist.IGenerateJsonCompletionParams.jsonConverter} is\n * provided.\n */\n readonly converter?: Converter<T> | Validator<T>;\n\n /**\n * Full string-to-`T` pipeline override. When supplied, takes precedence over\n * {@link AiAssist.IGenerateJsonCompletionParams.converter} and lets the\n * caller plug in a custom extractor or skip the default fence tolerance\n * entirely.\n */\n readonly jsonConverter?: Converter<T>;\n\n /**\n * Controls the optional system-prompt augmentation. Defaults to `'smart'`.\n * Pass `'none'` to disable, or a string to append custom guidance.\n */\n readonly promptHint?: JsonPromptHint;\n}\n\n/**\n * Successful result of {@link AiAssist.generateJsonCompletion}.\n * @public\n */\nexport interface IGenerateJsonCompletionResult<T> {\n /** The validated JSON value. */\n readonly value: T;\n /** The raw response text returned by the provider. */\n readonly raw: string;\n /** The full underlying completion response. */\n readonly response: IAiCompletionResponse;\n}\n\nfunction applyPromptHint(system: string | undefined, hint: JsonPromptHint): string | undefined {\n if (hint === 'none') {\n return system;\n }\n const suffix = hint === 'smart' ? SMART_JSON_PROMPT_HINT : hint;\n return system !== undefined && system.length > 0 ? `${system}\\n\\n${suffix}` : suffix;\n}\n\n/**\n * Calls {@link AiAssist.callProviderCompletion}, then runs the response text\n * through a tolerant JSON converter (default:\n * {@link AiAssist.fencedStringifiedJson}) and the caller's\n * `converter`/`validator`. Returns the validated value plus the raw text and\n * underlying completion response for diagnostics.\n *\n * @remarks\n * The default smart prompt hint asks the model to emit raw JSON. The read-side\n * extractor still tolerates fences and prose, so models that ignore the hint\n * are still handled.\n *\n * Either `converter` or `jsonConverter` must be provided; passing both lets\n * `jsonConverter` win.\n *\n * @param params - Provider parameters plus JSON validation options.\n * @returns The validated value, the raw text, and the underlying response.\n * @public\n */\nexport async function generateJsonCompletion<T>(\n params: IGenerateJsonCompletionParams<T>\n): Promise<Result<IGenerateJsonCompletionResult<T>>> {\n const { converter, jsonConverter, promptHint = 'smart', system, ...rest } = params;\n\n if (jsonConverter === undefined && converter === undefined) {\n return fail('generateJsonCompletion: either converter or jsonConverter must be provided.');\n }\n\n const pipeline: Converter<T> = jsonConverter ?? fencedStringifiedJson<T>({ inner: converter! });\n const augmentedSystem = applyPromptHint(system, promptHint);\n\n const response = await callProviderCompletion({ ...rest, system: augmentedSystem });\n if (response.isFailure()) {\n return fail(response.message);\n }\n const completion = response.value;\n\n return pipeline\n .convert(completion.content)\n .withErrorFormat((msg) => `generateJsonCompletion: ${msg}`)\n .onSuccess((value) => succeed({ value, raw: completion.content, response: completion }));\n}\n"]}
|
|
@@ -51,12 +51,34 @@ export class AiPrompt {
|
|
|
51
51
|
: '';
|
|
52
52
|
return `${this.user}${sentinel}\n\n${this.system}`;
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* Lowers this prompt to the unified {@link AiAssist.IChatRequest} shape consumed
|
|
56
|
+
* by the turn entry points (`callProviderCompletion`,
|
|
57
|
+
* `callProviderCompletionStream`, `generateJsonCompletion`,
|
|
58
|
+
* `executeClientToolTurn`). The prompt becomes a single current `user` turn
|
|
59
|
+
* (carrying any attachments) with the system instructions in the distinct
|
|
60
|
+
* `system` field.
|
|
61
|
+
*/
|
|
62
|
+
toRequest() {
|
|
63
|
+
return {
|
|
64
|
+
system: this.system,
|
|
65
|
+
messages: [
|
|
66
|
+
Object.assign({ role: 'user', content: this.user }, (this.attachments.length > 0 ? { attachments: this.attachments } : {}))
|
|
67
|
+
]
|
|
68
|
+
};
|
|
69
|
+
}
|
|
54
70
|
}
|
|
55
71
|
/**
|
|
56
72
|
* All valid {@link ModelSpecKey} values.
|
|
57
73
|
* @public
|
|
58
74
|
*/
|
|
59
|
-
export const allModelSpecKeys = [
|
|
75
|
+
export const allModelSpecKeys = [
|
|
76
|
+
'base',
|
|
77
|
+
'tools',
|
|
78
|
+
'image',
|
|
79
|
+
'thinking',
|
|
80
|
+
'embedding'
|
|
81
|
+
];
|
|
60
82
|
/**
|
|
61
83
|
* Default context key used as fallback when resolving a {@link ModelSpec}.
|
|
62
84
|
* @public
|
|
@@ -97,6 +119,19 @@ export function resolveModel(spec, context) {
|
|
|
97
119
|
}
|
|
98
120
|
return resolveModel(first);
|
|
99
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* All valid `AiModelCapability` values — the single source of truth for
|
|
124
|
+
* the capability vocabulary (used by validators and capability filters).
|
|
125
|
+
* @public
|
|
126
|
+
*/
|
|
127
|
+
export const allModelCapabilities = [
|
|
128
|
+
'chat',
|
|
129
|
+
'tools',
|
|
130
|
+
'vision',
|
|
131
|
+
'image-generation',
|
|
132
|
+
'thinking',
|
|
133
|
+
'embedding'
|
|
134
|
+
];
|
|
100
135
|
/**
|
|
101
136
|
* Default AI assist settings (copy-paste only).
|
|
102
137
|
* @public
|