@nemesis-oss/ollama-sdk 1.10.0 → 1.12.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.
@@ -1,7 +1,7 @@
1
1
  import { a as McpToolDescriptor } from './types-CI-gM2u5.cjs';
2
- import { O as OllamaRuntime } from './runtime-BsdBbuOv.cjs';
2
+ import { O as OllamaRuntime } from './runtime-DmI1cOEq.cjs';
3
3
  import 'zod';
4
- import './types-BtQexFpT.cjs';
4
+ import './types-B57ZZfp3.cjs';
5
5
 
6
6
  interface GeneratedToolEntry extends McpToolDescriptor {
7
7
  readonly _operationId: string;
@@ -1,7 +1,7 @@
1
1
  import { a as McpToolDescriptor } from './types-CI-gM2u5.js';
2
- import { O as OllamaRuntime } from './runtime-BV9SK_cf.js';
2
+ import { O as OllamaRuntime } from './runtime-CIQYCRL3.js';
3
3
  import 'zod';
4
- import './types-BtQexFpT.js';
4
+ import './types-B57ZZfp3.js';
5
5
 
6
6
  interface GeneratedToolEntry extends McpToolDescriptor {
7
7
  readonly _operationId: string;
@@ -1,4 +1,4 @@
1
- import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-BtQexFpT.js';
1
+ import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-B57ZZfp3.js';
2
2
  import { z } from 'zod';
3
3
 
4
4
  /**
@@ -383,6 +383,33 @@ declare class OllamaAgentMaxIterationsError extends OllamaClientError {
383
383
  maxIterations: number;
384
384
  });
385
385
  }
386
+ /**
387
+ * Thrown when the agent's cycle detection fires: the same tool call —
388
+ * identical name **and** identical arguments — would execute more times than
389
+ * `maxRepeatedToolCalls` allows during one run.
390
+ *
391
+ * This is the fail-fast diagnosis for a model stuck in a tool loop (repeatedly
392
+ * calling the same function with the same arguments, never reacting to the
393
+ * results); without it, a looping model only surfaces as a generic
394
+ * {@link OllamaAgentMaxIterationsError} after burning the full iteration
395
+ * budget on wasted calls.
396
+ */
397
+ declare class OllamaAgentToolLoopError extends OllamaClientError {
398
+ /** Name of the tool whose identical call would exceed the repeat budget. */
399
+ readonly toolName: string;
400
+ /** How many times this exact call would have executed including the rejected one. */
401
+ readonly repeatedExecutions: number;
402
+ /** The configured per-signature execution budget. */
403
+ readonly maxRepeatedToolCalls: number;
404
+ /** Canonical `name(args)` signature of the repeated call (very large payloads truncated). */
405
+ readonly signature: string;
406
+ constructor(message: string, options: Omit<OllamaClientErrorOptions, 'code'> & {
407
+ toolName: string;
408
+ repeatedExecutions: number;
409
+ maxRepeatedToolCalls: number;
410
+ signature: string;
411
+ });
412
+ }
386
413
  declare class OllamaMcpError extends OllamaClientError {
387
414
  readonly mcpMethod: 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | 'tasks/cancel';
388
415
  readonly toolName?: string | undefined;
@@ -901,4 +928,4 @@ declare class OllamaRuntime {
901
928
  private assertOperationAllowed;
902
929
  }
903
930
 
904
- export { OllamaRequestTooLargeError as $, type AbortableAsyncIterable as A, type BinaryBody as B, type ChatStreamResult as C, type DoneEvent as D, type ErrorEvent as E, type FetchLike as F, type GenerateStreamResult as G, HttpClient as H, type InvokeRequest as I, type OllamaErrorResponseContext as J, OllamaGenericClientError as K, type Logger as L, type Middleware as M, NANOS_PER_MS as N, OllamaRuntime as O, type ProgressStreamResult as P, OllamaIncompatibleModelError as Q, type RequestLifecycleHook as R, type SchemaRef as S, type TokenUsage as T, OllamaMcpError as U, OllamaModelRoutingError as V, OllamaNetworkError as W, OllamaNotFoundError as X, OllamaOverloadedError as Y, OllamaQuotaExceededError as Z, OllamaRateLimitError as _, type OperationDefinition as a, OllamaRequestValidationError as a0, OllamaResponseValidationError as a1, OllamaServerError as a2, OllamaServerVersionUnknownError as a3, OllamaSkillInvalidError as a4, OllamaSkillNotFoundError as a5, OllamaStreamError as a6, OllamaTimeoutError as a7, OllamaToolTimeoutError as a8, OllamaToolValidationError as a9, OllamaUnsupportedCapabilityError as aa, type RequestContext as ab, type RequestLifecycleEvent as ac, type ResponseContext as ad, type SseEvent as ae, type ThinkingEvent as af, type TokenEvent as ag, type ToolCallEvent as ah, composeMiddleware as ai, createConsoleLogger as aj, extractUsage as ak, mapError as al, parseSseStream as am, type OllamaRuntimeOptions as b, type OllamaStreamEvent as c, type OllamaStreamEventType as d, type RawUsageSource as e, type HttpBody as f, type HttpClientOptions as g, type HttpRequestOptions as h, type LifecycleErrorEvent as i, type LifecycleRetryEvent as j, type LifecycleStartEvent as k, type LifecycleSuccessEvent as l, type LogFn as m, type MessageEvent as n, type MiddlewareContext as o, NANOS_PER_SECOND as p, NOOP_LOGGER as q, type NextFunction as r, OllamaAbortError as s, OllamaAgentMaxIterationsError as t, OllamaAgentMaxToolCallsError as u, OllamaAuthError as v, OllamaBadGatewayError as w, OllamaClientError as x, type OllamaClientErrorOptions as y, type OllamaErrorRequestContext as z };
931
+ export { OllamaRateLimitError as $, type AbortableAsyncIterable as A, type BinaryBody as B, type ChatStreamResult as C, type DoneEvent as D, type ErrorEvent as E, type FetchLike as F, type GenerateStreamResult as G, HttpClient as H, type InvokeRequest as I, type OllamaErrorRequestContext as J, type OllamaErrorResponseContext as K, type Logger as L, type Middleware as M, NANOS_PER_MS as N, OllamaRuntime as O, type ProgressStreamResult as P, OllamaGenericClientError as Q, type RequestLifecycleHook as R, type SchemaRef as S, type TokenUsage as T, OllamaIncompatibleModelError as U, OllamaMcpError as V, OllamaModelRoutingError as W, OllamaNetworkError as X, OllamaNotFoundError as Y, OllamaOverloadedError as Z, OllamaQuotaExceededError as _, type OperationDefinition as a, OllamaRequestTooLargeError as a0, OllamaRequestValidationError as a1, OllamaResponseValidationError as a2, OllamaServerError as a3, OllamaServerVersionUnknownError as a4, OllamaSkillInvalidError as a5, OllamaSkillNotFoundError as a6, OllamaStreamError as a7, OllamaTimeoutError as a8, OllamaToolTimeoutError as a9, OllamaToolValidationError as aa, OllamaUnsupportedCapabilityError as ab, type RequestContext as ac, type RequestLifecycleEvent as ad, type ResponseContext as ae, type SseEvent as af, type ThinkingEvent as ag, type TokenEvent as ah, type ToolCallEvent as ai, composeMiddleware as aj, createConsoleLogger as ak, extractUsage as al, mapError as am, parseSseStream as an, type OllamaRuntimeOptions as b, type OllamaStreamEvent as c, type OllamaStreamEventType as d, type RawUsageSource as e, type HttpBody as f, type HttpClientOptions as g, type HttpRequestOptions as h, type LifecycleErrorEvent as i, type LifecycleRetryEvent as j, type LifecycleStartEvent as k, type LifecycleSuccessEvent as l, type LogFn as m, type MessageEvent as n, type MiddlewareContext as o, NANOS_PER_SECOND as p, NOOP_LOGGER as q, type NextFunction as r, OllamaAbortError as s, OllamaAgentMaxIterationsError as t, OllamaAgentMaxToolCallsError as u, OllamaAgentToolLoopError as v, OllamaAuthError as w, OllamaBadGatewayError as x, OllamaClientError as y, type OllamaClientErrorOptions as z };
@@ -1,4 +1,4 @@
1
- import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-BtQexFpT.cjs';
1
+ import { n as Message, m as ChatResponse, i as ToolCall, b as ProgressResponse, o as GenerateResponse } from './types-B57ZZfp3.cjs';
2
2
  import { z } from 'zod';
3
3
 
4
4
  /**
@@ -383,6 +383,33 @@ declare class OllamaAgentMaxIterationsError extends OllamaClientError {
383
383
  maxIterations: number;
384
384
  });
385
385
  }
386
+ /**
387
+ * Thrown when the agent's cycle detection fires: the same tool call —
388
+ * identical name **and** identical arguments — would execute more times than
389
+ * `maxRepeatedToolCalls` allows during one run.
390
+ *
391
+ * This is the fail-fast diagnosis for a model stuck in a tool loop (repeatedly
392
+ * calling the same function with the same arguments, never reacting to the
393
+ * results); without it, a looping model only surfaces as a generic
394
+ * {@link OllamaAgentMaxIterationsError} after burning the full iteration
395
+ * budget on wasted calls.
396
+ */
397
+ declare class OllamaAgentToolLoopError extends OllamaClientError {
398
+ /** Name of the tool whose identical call would exceed the repeat budget. */
399
+ readonly toolName: string;
400
+ /** How many times this exact call would have executed including the rejected one. */
401
+ readonly repeatedExecutions: number;
402
+ /** The configured per-signature execution budget. */
403
+ readonly maxRepeatedToolCalls: number;
404
+ /** Canonical `name(args)` signature of the repeated call (very large payloads truncated). */
405
+ readonly signature: string;
406
+ constructor(message: string, options: Omit<OllamaClientErrorOptions, 'code'> & {
407
+ toolName: string;
408
+ repeatedExecutions: number;
409
+ maxRepeatedToolCalls: number;
410
+ signature: string;
411
+ });
412
+ }
386
413
  declare class OllamaMcpError extends OllamaClientError {
387
414
  readonly mcpMethod: 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | 'tasks/cancel';
388
415
  readonly toolName?: string | undefined;
@@ -901,4 +928,4 @@ declare class OllamaRuntime {
901
928
  private assertOperationAllowed;
902
929
  }
903
930
 
904
- export { OllamaRequestTooLargeError as $, type AbortableAsyncIterable as A, type BinaryBody as B, type ChatStreamResult as C, type DoneEvent as D, type ErrorEvent as E, type FetchLike as F, type GenerateStreamResult as G, HttpClient as H, type InvokeRequest as I, type OllamaErrorResponseContext as J, OllamaGenericClientError as K, type Logger as L, type Middleware as M, NANOS_PER_MS as N, OllamaRuntime as O, type ProgressStreamResult as P, OllamaIncompatibleModelError as Q, type RequestLifecycleHook as R, type SchemaRef as S, type TokenUsage as T, OllamaMcpError as U, OllamaModelRoutingError as V, OllamaNetworkError as W, OllamaNotFoundError as X, OllamaOverloadedError as Y, OllamaQuotaExceededError as Z, OllamaRateLimitError as _, type OperationDefinition as a, OllamaRequestValidationError as a0, OllamaResponseValidationError as a1, OllamaServerError as a2, OllamaServerVersionUnknownError as a3, OllamaSkillInvalidError as a4, OllamaSkillNotFoundError as a5, OllamaStreamError as a6, OllamaTimeoutError as a7, OllamaToolTimeoutError as a8, OllamaToolValidationError as a9, OllamaUnsupportedCapabilityError as aa, type RequestContext as ab, type RequestLifecycleEvent as ac, type ResponseContext as ad, type SseEvent as ae, type ThinkingEvent as af, type TokenEvent as ag, type ToolCallEvent as ah, composeMiddleware as ai, createConsoleLogger as aj, extractUsage as ak, mapError as al, parseSseStream as am, type OllamaRuntimeOptions as b, type OllamaStreamEvent as c, type OllamaStreamEventType as d, type RawUsageSource as e, type HttpBody as f, type HttpClientOptions as g, type HttpRequestOptions as h, type LifecycleErrorEvent as i, type LifecycleRetryEvent as j, type LifecycleStartEvent as k, type LifecycleSuccessEvent as l, type LogFn as m, type MessageEvent as n, type MiddlewareContext as o, NANOS_PER_SECOND as p, NOOP_LOGGER as q, type NextFunction as r, OllamaAbortError as s, OllamaAgentMaxIterationsError as t, OllamaAgentMaxToolCallsError as u, OllamaAuthError as v, OllamaBadGatewayError as w, OllamaClientError as x, type OllamaClientErrorOptions as y, type OllamaErrorRequestContext as z };
931
+ export { OllamaRateLimitError as $, type AbortableAsyncIterable as A, type BinaryBody as B, type ChatStreamResult as C, type DoneEvent as D, type ErrorEvent as E, type FetchLike as F, type GenerateStreamResult as G, HttpClient as H, type InvokeRequest as I, type OllamaErrorRequestContext as J, type OllamaErrorResponseContext as K, type Logger as L, type Middleware as M, NANOS_PER_MS as N, OllamaRuntime as O, type ProgressStreamResult as P, OllamaGenericClientError as Q, type RequestLifecycleHook as R, type SchemaRef as S, type TokenUsage as T, OllamaIncompatibleModelError as U, OllamaMcpError as V, OllamaModelRoutingError as W, OllamaNetworkError as X, OllamaNotFoundError as Y, OllamaOverloadedError as Z, OllamaQuotaExceededError as _, type OperationDefinition as a, OllamaRequestTooLargeError as a0, OllamaRequestValidationError as a1, OllamaResponseValidationError as a2, OllamaServerError as a3, OllamaServerVersionUnknownError as a4, OllamaSkillInvalidError as a5, OllamaSkillNotFoundError as a6, OllamaStreamError as a7, OllamaTimeoutError as a8, OllamaToolTimeoutError as a9, OllamaToolValidationError as aa, OllamaUnsupportedCapabilityError as ab, type RequestContext as ac, type RequestLifecycleEvent as ad, type ResponseContext as ae, type SseEvent as af, type ThinkingEvent as ag, type TokenEvent as ah, type ToolCallEvent as ai, composeMiddleware as aj, createConsoleLogger as ak, extractUsage as al, mapError as am, parseSseStream as an, type OllamaRuntimeOptions as b, type OllamaStreamEvent as c, type OllamaStreamEventType as d, type RawUsageSource as e, type HttpBody as f, type HttpClientOptions as g, type HttpRequestOptions as h, type LifecycleErrorEvent as i, type LifecycleRetryEvent as j, type LifecycleStartEvent as k, type LifecycleSuccessEvent as l, type LogFn as m, type MessageEvent as n, type MiddlewareContext as o, NANOS_PER_SECOND as p, NOOP_LOGGER as q, type NextFunction as r, OllamaAbortError as s, OllamaAgentMaxIterationsError as t, OllamaAgentMaxToolCallsError as u, OllamaAgentToolLoopError as v, OllamaAuthError as w, OllamaBadGatewayError as x, OllamaClientError as y, type OllamaClientErrorOptions as z };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/skills/frontmatter.ts","../src/skills/compose.ts","../src/skills/skill-registry.ts"],"names":["readdir","join","readFile"],"mappings":";;;;;;AA0BO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAClC,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EAET,WAAA,CAAY,SAAiB,OAAA,EAAmC;AAC9D,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,CAAQ,OAAO,CAAA;AACvC,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAC7B,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,KAAA;AACtC,IAAA,IAAA,CAAK,UAAU,OAAA,CAAQ,OAAA;AACvB,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAAA,EAC1B;AACF,CAAA;AA2bO,IAAM,wBAAA,GAAN,cAAuC,iBAAA,CAAkB;AAAA,EACrD,SAAA;AAAA,EACT,WAAA,CACE,SACA,OAAA,EACA;AACA,IAAA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b,IAAA,EAAM,OAAO,WAAA,CAAY,IAAA;AAAA,UACzB,WAAA,EAAa,OAAO,WAAA,CAAY,WAAA;AAAA,UAChC,IAAA,EAAM;AAAA,SACP,CAAA;AAAA,MACH,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAEA,IAAA,OAAO,SAAA;AAAA,EACT;AAAA,EAEA,MAAM,KAAK,IAAA,EAA8B;AACvC,IAAA,MAAM,SAAA,GAAYD,SAAA,CAAK,IAAA,CAAK,SAAA,EAAW,MAAM,UAAU,CAAA;AACvD,IAAA,IAAI;AACF,MAAA,MAAM,OAAA,GAAU,MAAMC,iBAAA,CAAS,SAAA,EAAW,OAAO,CAAA;AACjD,MAAA,MAAM,MAAA,GAAS,gBAAA,CAAiB,OAAA,EAAS,SAAS,CAAA;AAClD,MAAA,OAAO;AAAA,QACL,IAAA,EAAM,OAAO,WAAA,CAAY,IAAA;AAAA,QACzB,WAAA,EAAa,OAAO,WAAA,CAAY,WAAA;AAAA,QAChC,IAAA,EAAM,SAAA;AAAA,QACN,aAAa,MAAA,CAAO,WAAA;AAAA,QACpB,MAAM,MAAA,CAAO,IAAA;AAAA,QACb,YAAA,EAAc,MAAA,CAAO,WAAA,CAAY,eAAe;AAAA,OAClD;AAAA,IACF,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,IAAI,wBAAA,CAAyB,CAAA,OAAA,EAAU,IAAI,CAAA,eAAA,EAAkB,SAAS,CAAA,CAAA,EAAI;AAAA,QAC9E,SAAA,EAAW,IAAA;AAAA,QACX,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"skills.cjs","sourcesContent":["/**\n * Structured, typed error hierarchy for OllamaClient.\n */\n\nimport type { z } from 'zod';\n\nexport interface OllamaErrorRequestContext {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n readonly model?: string | undefined;\n}\n\nexport interface OllamaErrorResponseContext {\n readonly status?: number | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly body?: unknown;\n}\n\nexport interface OllamaClientErrorOptions extends ErrorOptions {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable?: boolean | undefined;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n}\n\nexport class OllamaClientError extends Error {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable: boolean;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n\n constructor(message: string, options: OllamaClientErrorOptions) {\n super(message, { cause: options.cause });\n this.name = this.constructor.name;\n this.code = options.code;\n this.status = options.status;\n this.retryable = options.retryable ?? false;\n this.request = options.request;\n this.response = options.response;\n }\n}\n\nexport class OllamaNetworkError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'network_error', retryable: true });\n }\n}\n\nexport class OllamaTimeoutError extends OllamaClientError {\n readonly timeoutMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { timeoutMs?: number | undefined })\n | undefined,\n ) {\n super(message, { ...options, code: 'timeout', retryable: true });\n this.timeoutMs = options?.timeoutMs;\n }\n}\n\nexport class OllamaAuthError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'auth_error', retryable: false });\n }\n}\n\nexport class OllamaNotFoundError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'not_found', retryable: false });\n }\n}\n\nexport class OllamaRateLimitError extends OllamaClientError {\n readonly retryAfterMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n retryAfterMs?: number | undefined;\n })\n | undefined,\n ) {\n super(message, { ...options, code: 'rate_limited', retryable: true });\n this.retryAfterMs = options?.retryAfterMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, by `QuotaManager.assertCanProceed`\n * (see `src/quota.ts`) when issuing the request would exceed a configured usage budget for\n * one of its rolling windows. This is distinct from `OllamaRateLimitError`, which reflects\n * the server's own 429 response — Ollama Cloud does not expose account-level quota via the\n * API, so `QuotaManager` tracks usage against budgets the caller configures locally and\n * fails fast rather than waiting for the server to reject the request.\n */\nexport class OllamaQuotaExceededError extends OllamaClientError {\n readonly windowId: string;\n readonly resetAt: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n windowId: string;\n resetAt: number;\n },\n ) {\n super(message, { ...options, code: 'quota_exceeded', retryable: false });\n this.windowId = options.windowId;\n this.resetAt = options.resetAt;\n }\n}\n\nexport class OllamaServerError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'server_error', retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **503 Service Unavailable**,\n * indicating that the request queue is saturated (`OLLAMA_MAX_QUEUE`\n * exceeded, default 512 — see the FAQ).\n *\n * Semantically a specialization of {@link OllamaServerError} (503 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'overloaded'` —\n * `OllamaServerError`'s constructor unconditionally forces\n * `code: 'server_error'`. Callers wanting to catch any 5xx should\n * use `error.status >= 500 && error.status < 600` OR explicitly\n * list both `OllamaServerError` and `OllamaOverloadedError`/\n * `OllamaBadGatewayError` in their `instanceof` checks.\n *\n * `retryable` is `true` because the queue will eventually drain;\n * callers using {@link withRetry} will get automatic backoff.\n */\nexport class OllamaOverloadedError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'overloaded', status: 503, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **502 Bad Gateway**,\n * indicating that a cloud model could not be reached by the\n * Ollama Cloud proxy. The model may be temporarily down, the\n * cloud provider may be experiencing an outage, or the model\n * may have been deprovisioned.\n *\n * Semantically a specialization of {@link OllamaServerError} (502 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'bad_gateway'` —\n * see {@link OllamaOverloadedError} for the rationale. Callers wanting\n * to catch any 5xx should use `error.status >= 500 && error.status < 600`\n * OR explicitly list both classes in their `instanceof` checks.\n *\n * `retryable` is `true` for transient cloud-provider outages.\n */\nexport class OllamaBadGatewayError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'bad_gateway', status: 502, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server emits an in-band error frame inside\n * an NDJSON stream (chat / generate / pull / push / create).\n *\n * Ollama streams start with HTTP 200 OK and chunked transfer encoding.\n * If an error occurs mid-generation (GPU OOM, driver crash, context\n * window overflow, model unload race, etc.), the server emits a final\n * JSON chunk of the form `{\"error\": \"...\"}` and closes the stream.\n * The HTTP status code never changes from 200, so HTTP-status-based\n * error detection misses these errors entirely — they would silently\n * bleed into the assistant's content stream as garbage tokens or\n * undefined-field accesses.\n *\n * `partialContent` carries whatever was accumulated before the error\n * frame, so callers can log/diagnose what the model produced before\n * failing. For chat streams this is the concatenated `message.content`;\n * for generate streams it's the concatenated `response`; for pull/push\n * streams it's empty (progress events don't accumulate content).\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/api.md\n */\nexport class OllamaStreamError extends OllamaClientError {\n /** Content accumulated before the in-band error frame, or '' if none. */\n readonly partialContent: string;\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n partialContent?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'stream_error', retryable: false });\n this.partialContent = options?.partialContent ?? '';\n }\n}\n\nexport class OllamaAbortError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'aborted', retryable: false });\n }\n}\n\nexport class OllamaToolValidationError extends OllamaClientError {\n readonly toolName: string;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { toolName: string; issues?: unknown },\n ) {\n super(message, { ...options, code: 'tool_validation_error', retryable: false });\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` when `validateRequests: true` is set and\n * the request body fails Zod validation against the operation's registered\n * schema. See ADR 0020 (runtime Zod validation).\n *\n * The error carries the original Zod issues so callers can inspect which\n * fields failed. No HTTP request is made when this error is thrown.\n */\nexport class OllamaRequestValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'request_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * serialized request body exceeds the operation's declared\n * `constraints.maxRequestBytes`. The Ollama server returns 413 for such\n * payloads; this client-side check fails fast so the round-trip is avoided.\n *\n * Wave 12 (P0 #5): the IR has carried `maxRequestBytes` for System One\n * (64 KiB) since v1.7.0, but the runtime never enforced it. This closes\n * that contract/runtime gap.\n */\nexport class OllamaRequestTooLargeError extends OllamaClientError {\n readonly operationId: string;\n readonly actualBytes: number;\n readonly maxBytes: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> & {\n operationId: string;\n actualBytes: number;\n maxBytes: number;\n },\n ) {\n super(message, { ...options, code: 'request_too_large', retryable: false, status: 413 });\n this.operationId = options.operationId;\n this.actualBytes = options.actualBytes;\n this.maxBytes = options.maxBytes;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` AFTER the HTTP response is received\n * when `validateResponses: true` is set and the response body fails Zod\n * validation against the operation's registered response schema.\n *\n * Wave 13: the runtime previously never validated responses (see ADR\n * 0020). This opt-in error gives callers a way to detect wire-format\n * mismatches for operations where typed response semantics are critical\n * (e.g. System One). The error carries the original Zod issues so\n * callers can inspect which fields failed.\n */\nexport class OllamaResponseValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'response_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * operation declares `constraints.minOllamaVersion` and the runtime could\n * not obtain a server version to compare against (e.g. `enforceVersion:\n * 'strict'` was set and `/api/version` was unreachable). Distinct from\n * {@link OllamaGenericClientError} so callers can branch on the failure\n * mode rather than parsing the message.\n */\nexport class OllamaServerVersionUnknownError extends OllamaClientError {\n readonly operationId: string;\n readonly minRequiredVersion: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n minRequiredVersion: string;\n },\n ) {\n super(message, { ...options, code: 'server_version_unknown', retryable: false });\n this.operationId = options.operationId;\n this.minRequiredVersion = options.minRequiredVersion;\n }\n}\n\nexport class OllamaToolTimeoutError extends OllamaClientError {\n readonly toolName: string;\n readonly timeoutMs: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n toolName: string;\n timeoutMs: number;\n },\n ) {\n super(message, { ...options, code: 'tool_timeout', retryable: false });\n this.toolName = options.toolName;\n this.timeoutMs = options.timeoutMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, when a request asks for a\n * capability an endpoint is known not to support (e.g. structured output `format` against\n * an Ollama Cloud endpoint — see `ModelCapabilities.supportsStructuredOutputRequest` in\n * `src/capabilities/capabilities.ts`). Its `code` is included in `DEFAULT_FAILOVER_CODES`\n * by default, so in a multi-endpoint setup it causes failover to the next candidate rather\n * than failing outright — it only surfaces to the caller if every candidate is rejected.\n */\nexport class OllamaUnsupportedCapabilityError extends OllamaClientError {\n readonly capability: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { capability: string },\n ) {\n super(message, { ...options, code: 'unsupported_capability', retryable: false });\n this.capability = options.capability;\n }\n}\n\n/**\n * Thrown client-side, before any network call, when `config.endpoints` uses\n * `OllamaEndpoint.models` to scope endpoints/credentials to specific models and the\n * requested `model` isn't in any configured endpoint's allow-list. This is a routing\n * misconfiguration, not a connectivity problem — the SDK deliberately does not \"probe\"\n * unauthorized endpoints to find one that happens to work (that would burn quota on keys\n * that were never entitled to the model and produce non-deterministic startup behavior).\n */\nexport class OllamaModelRoutingError extends OllamaClientError {\n readonly model: string;\n readonly availableModels: readonly string[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n availableModels: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'model_routing_error', retryable: false });\n this.model = options.model;\n this.availableModels = options.availableModels;\n }\n}\n\n/**\n * Thrown before an agent tool loop starts when the selected model's /api/show metadata\n * does not advertise a capability required by the loop.\n */\nexport class OllamaIncompatibleModelError extends OllamaClientError {\n readonly model: string;\n readonly capability: string;\n readonly reportedCapabilities: readonly string[];\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n capability: string;\n reportedCapabilities: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'incompatible_model', retryable: false });\n this.model = options.model;\n this.capability = options.capability;\n this.reportedCapabilities = options.reportedCapabilities;\n }\n}\nexport class OllamaAgentMaxToolCallsError extends OllamaClientError {\n readonly maxToolCalls: number;\n readonly toolCallsExecuted: number;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n maxToolCalls: number;\n toolCallsExecuted: number;\n },\n ) {\n super(message, { ...options, code: 'agent_max_tool_calls_exceeded', retryable: false });\n this.maxToolCalls = options.maxToolCalls;\n this.toolCallsExecuted = options.toolCallsExecuted;\n }\n}\n\nexport class OllamaAgentMaxIterationsError extends OllamaClientError {\n readonly maxIterations: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { maxIterations: number },\n ) {\n super(message, { ...options, code: 'agent_max_iterations_exceeded', retryable: false });\n this.maxIterations = options.maxIterations;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n readonly toolName?: string | undefined;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n toolName?: string | undefined;\n issues?: unknown;\n },\n ) {\n super(message, { ...options, code: 'mcp_error', retryable: options.retryable ?? false });\n this.mcpMethod = options.mcpMethod;\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaSkillNotFoundError extends OllamaClientError {\n readonly skillName: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { skillName: string },\n ) {\n super(message, { ...options, code: 'skill_not_found', retryable: false });\n this.skillName = options.skillName;\n }\n}\n\nexport class OllamaSkillInvalidError extends OllamaClientError {\n readonly skillName: string;\n readonly path?: string | undefined;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n skillName: string;\n path?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'skill_invalid', retryable: false });\n this.skillName = options.skillName;\n this.path = options.path;\n }\n}\n\nexport class OllamaGenericClientError extends OllamaClientError {\n constructor(message: string, options?: Omit<OllamaClientErrorOptions, 'code'> | undefined) {\n super(message, { ...options, code: 'client_error' });\n }\n}\n\nfunction isDomAbortError(error: unknown): error is DOMException {\n return (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === 'AbortError'\n );\n}\n\nfunction statusToError(\n status: number,\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'status'>,\n): OllamaClientError {\n if (status === 401 || status === 403) {\n return new OllamaAuthError(message, { ...options, status });\n }\n if (status === 404) {\n return new OllamaNotFoundError(message, { ...options, status });\n }\n if (status === 429) {\n return new OllamaRateLimitError(message, { ...options, status });\n }\n if (status === 502) {\n // Cloud model could not be reached. Distinct from generic 5xx so\n // callers running multi-model agents can branch on cloud-provider\n // failures specifically (fail over to a different model/endpoint\n // rather than blindly retrying the same one).\n return new OllamaBadGatewayError(message, { ...options });\n }\n if (status === 503) {\n // Queue saturation (OLLAMA_MAX_QUEUE exceeded). Retryable — the\n // queue will eventually drain. Distinct from generic 5xx so\n // callers running parallel swarms can branch on saturation.\n return new OllamaOverloadedError(message, { ...options });\n }\n if (status >= 500) {\n return new OllamaServerError(message, { ...options, status });\n }\n return new OllamaGenericClientError(message, { ...options, status });\n}\n\n/**\n * Maps arbitrary thrown exceptions into structured OllamaClientError instances.\n */\nexport function mapError(\n error: unknown,\n context: {\n request?: OllamaErrorRequestContext | undefined;\n response?: OllamaErrorResponseContext | undefined;\n } = {},\n): OllamaClientError {\n if (error instanceof OllamaClientError) {\n return error;\n }\n if (isDomAbortError(error)) {\n return new OllamaAbortError(error.message || 'Request was aborted', {\n cause: error,\n request: context.request,\n });\n }\n if (error instanceof TypeError) {\n return new OllamaNetworkError(error.message || 'Network request failed', {\n cause: error,\n request: context.request,\n });\n }\n if (context.response?.status !== undefined) {\n const message = error instanceof Error ? error.message : String(error);\n return statusToError(context.response.status, message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new OllamaGenericClientError(message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n}\n","/**\n * Lightweight frontmatter parser for SKILL.md files.\n */\n\nimport { OllamaSkillInvalidError } from '../errors.js';\nimport type { SkillFrontmatter } from './types.js';\n\nexport interface ParsedFrontmatter {\n readonly frontmatter: SkillFrontmatter;\n readonly body: string;\n}\n\nfunction parseYamlValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') return true;\n if (trimmed === 'false') return false;\n if (!Number.isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed);\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction parseYamlBlock(yamlText: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = yamlText.split('\\n');\n let currentKey: string | undefined;\n let currentList: unknown[] | undefined;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.startsWith('- ') && currentKey) {\n if (!currentList) {\n currentList = [];\n result[currentKey] = currentList;\n }\n currentList.push(parseYamlValue(trimmed.slice(2)));\n continue;\n }\n\n currentList = undefined;\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const valStr = line.slice(colonIndex + 1).trim();\n currentKey = key;\n if (valStr.length > 0) {\n result[key] = parseYamlValue(valStr);\n }\n }\n }\n\n return result;\n}\n\nexport function parseFrontmatter(source: string, path = ''): ParsedFrontmatter {\n const match = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new OllamaSkillInvalidError('Missing YAML frontmatter delimiters (---)', {\n skillName: path || 'unknown',\n path,\n });\n }\n\n const rawYaml = match[1] ?? '';\n const body = match[2]?.trim() ?? '';\n const parsed = parseYamlBlock(rawYaml);\n\n if (!parsed['name'] || typeof parsed['name'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"name\"', {\n skillName: String(parsed['name'] ?? 'unknown'),\n path,\n });\n }\n if (!parsed['description'] || typeof parsed['description'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"description\"', {\n skillName: parsed['name'],\n path,\n });\n }\n\n return {\n frontmatter: parsed as unknown as SkillFrontmatter,\n body,\n };\n}\n","/**\n * Skill composition and context injection.\n */\n\nimport type { Message } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { Skill } from './types.js';\n\nexport interface ApplySkillOptions {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\nexport interface AppliedSkillResult {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\n/**\n * Injects a skill's body into messages as a system prompt and applies allowed tool filters.\n */\nexport function applySkill(skill: Skill, options: ApplySkillOptions): AppliedSkillResult {\n const systemPrompt = `[Skill: ${skill.name}]\\n${skill.description}\\n\\n${skill.body}`;\n const messages = [...options.messages];\n const systemIndex = messages.findIndex((m) => m.role === 'system');\n\n if (systemIndex >= 0) {\n const existing = messages[systemIndex];\n if (existing) {\n messages[systemIndex] = {\n role: 'system',\n content: `${existing.content}\\n\\n${systemPrompt}`,\n };\n }\n } else {\n messages.unshift({ role: 'system', content: systemPrompt });\n }\n\n return {\n messages,\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n };\n}\n","/**\n * Node.js filesystem skill registry for SKILL.md packages.\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { OllamaSkillNotFoundError } from '../errors.js';\nimport { parseFrontmatter } from './frontmatter.js';\nimport type { Skill, SkillSummary } from './types.js';\n\nexport interface SkillRegistryOptions {\n readonly directory: string;\n}\n\nexport class SkillRegistry {\n readonly directory: string;\n\n constructor(options: SkillRegistryOptions) {\n this.directory = options.directory;\n }\n\n async list(): Promise<SkillSummary[]> {\n const entries = await readdir(this.directory, { withFileTypes: true });\n const summaries: SkillSummary[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillPath = join(this.directory, entry.name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n summaries.push({\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n });\n } catch {\n // Skip directories without valid SKILL.md\n }\n }\n\n return summaries;\n }\n\n async load(name: string): Promise<Skill> {\n const skillPath = join(this.directory, name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n return {\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n frontmatter: parsed.frontmatter,\n body: parsed.body,\n allowedTools: parsed.frontmatter['allowed-tools'],\n };\n } catch (err) {\n throw new OllamaSkillNotFoundError(`Skill \"${name}\" not found at ${skillPath}`, {\n skillName: name,\n cause: err,\n });\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/skills/frontmatter.ts","../src/skills/compose.ts","../src/skills/skill-registry.ts"],"names":["readdir","join","readFile"],"mappings":";;;;;;AA0BO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAClC,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EAET,WAAA,CAAY,SAAiB,OAAA,EAAmC;AAC9D,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,CAAQ,OAAO,CAAA;AACvC,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAC7B,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,S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EAAO;AAAA,OACR,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"skills.cjs","sourcesContent":["/**\n * Structured, typed error hierarchy for OllamaClient.\n */\n\nimport type { z } from 'zod';\n\nexport interface OllamaErrorRequestContext {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n readonly model?: string | undefined;\n}\n\nexport interface OllamaErrorResponseContext {\n readonly status?: number | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly body?: unknown;\n}\n\nexport interface OllamaClientErrorOptions extends ErrorOptions {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable?: boolean | undefined;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n}\n\nexport class OllamaClientError extends Error {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable: boolean;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n\n constructor(message: string, options: OllamaClientErrorOptions) {\n super(message, { cause: options.cause });\n this.name = this.constructor.name;\n this.code = options.code;\n this.status = options.status;\n this.retryable = options.retryable ?? false;\n this.request = options.request;\n this.response = options.response;\n }\n}\n\nexport class OllamaNetworkError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'network_error', retryable: true });\n }\n}\n\nexport class OllamaTimeoutError extends OllamaClientError {\n readonly timeoutMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { timeoutMs?: number | undefined })\n | undefined,\n ) {\n super(message, { ...options, code: 'timeout', retryable: true });\n this.timeoutMs = options?.timeoutMs;\n }\n}\n\nexport class OllamaAuthError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'auth_error', retryable: false });\n }\n}\n\nexport class OllamaNotFoundError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'not_found', retryable: false });\n }\n}\n\nexport class OllamaRateLimitError extends OllamaClientError {\n readonly retryAfterMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n retryAfterMs?: number | undefined;\n })\n | undefined,\n ) {\n super(message, { ...options, code: 'rate_limited', retryable: true });\n this.retryAfterMs = options?.retryAfterMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, by `QuotaManager.assertCanProceed`\n * (see `src/quota.ts`) when issuing the request would exceed a configured usage budget for\n * one of its rolling windows. This is distinct from `OllamaRateLimitError`, which reflects\n * the server's own 429 response — Ollama Cloud does not expose account-level quota via the\n * API, so `QuotaManager` tracks usage against budgets the caller configures locally and\n * fails fast rather than waiting for the server to reject the request.\n */\nexport class OllamaQuotaExceededError extends OllamaClientError {\n readonly windowId: string;\n readonly resetAt: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n windowId: string;\n resetAt: number;\n },\n ) {\n super(message, { ...options, code: 'quota_exceeded', retryable: false });\n this.windowId = options.windowId;\n this.resetAt = options.resetAt;\n }\n}\n\nexport class OllamaServerError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'server_error', retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **503 Service Unavailable**,\n * indicating that the request queue is saturated (`OLLAMA_MAX_QUEUE`\n * exceeded, default 512 — see the FAQ).\n *\n * Semantically a specialization of {@link OllamaServerError} (503 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'overloaded'` —\n * `OllamaServerError`'s constructor unconditionally forces\n * `code: 'server_error'`. Callers wanting to catch any 5xx should\n * use `error.status >= 500 && error.status < 600` OR explicitly\n * list both `OllamaServerError` and `OllamaOverloadedError`/\n * `OllamaBadGatewayError` in their `instanceof` checks.\n *\n * `retryable` is `true` because the queue will eventually drain;\n * callers using {@link withRetry} will get automatic backoff.\n */\nexport class OllamaOverloadedError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'overloaded', status: 503, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **502 Bad Gateway**,\n * indicating that a cloud model could not be reached by the\n * Ollama Cloud proxy. The model may be temporarily down, the\n * cloud provider may be experiencing an outage, or the model\n * may have been deprovisioned.\n *\n * Semantically a specialization of {@link OllamaServerError} (502 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'bad_gateway'` —\n * see {@link OllamaOverloadedError} for the rationale. Callers wanting\n * to catch any 5xx should use `error.status >= 500 && error.status < 600`\n * OR explicitly list both classes in their `instanceof` checks.\n *\n * `retryable` is `true` for transient cloud-provider outages.\n */\nexport class OllamaBadGatewayError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'bad_gateway', status: 502, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server emits an in-band error frame inside\n * an NDJSON stream (chat / generate / pull / push / create).\n *\n * Ollama streams start with HTTP 200 OK and chunked transfer encoding.\n * If an error occurs mid-generation (GPU OOM, driver crash, context\n * window overflow, model unload race, etc.), the server emits a final\n * JSON chunk of the form `{\"error\": \"...\"}` and closes the stream.\n * The HTTP status code never changes from 200, so HTTP-status-based\n * error detection misses these errors entirely — they would silently\n * bleed into the assistant's content stream as garbage tokens or\n * undefined-field accesses.\n *\n * `partialContent` carries whatever was accumulated before the error\n * frame, so callers can log/diagnose what the model produced before\n * failing. For chat streams this is the concatenated `message.content`;\n * for generate streams it's the concatenated `response`; for pull/push\n * streams it's empty (progress events don't accumulate content).\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/api.md\n */\nexport class OllamaStreamError extends OllamaClientError {\n /** Content accumulated before the in-band error frame, or '' if none. */\n readonly partialContent: string;\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n partialContent?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'stream_error', retryable: false });\n this.partialContent = options?.partialContent ?? '';\n }\n}\n\nexport class OllamaAbortError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'aborted', retryable: false });\n }\n}\n\nexport class OllamaToolValidationError extends OllamaClientError {\n readonly toolName: string;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { toolName: string; issues?: unknown },\n ) {\n super(message, { ...options, code: 'tool_validation_error', retryable: false });\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` when `validateRequests: true` is set and\n * the request body fails Zod validation against the operation's registered\n * schema. See ADR 0020 (runtime Zod validation).\n *\n * The error carries the original Zod issues so callers can inspect which\n * fields failed. No HTTP request is made when this error is thrown.\n */\nexport class OllamaRequestValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'request_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * serialized request body exceeds the operation's declared\n * `constraints.maxRequestBytes`. The Ollama server returns 413 for such\n * payloads; this client-side check fails fast so the round-trip is avoided.\n *\n * Wave 12 (P0 #5): the IR has carried `maxRequestBytes` for System One\n * (64 KiB) since v1.7.0, but the runtime never enforced it. This closes\n * that contract/runtime gap.\n */\nexport class OllamaRequestTooLargeError extends OllamaClientError {\n readonly operationId: string;\n readonly actualBytes: number;\n readonly maxBytes: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> & {\n operationId: string;\n actualBytes: number;\n maxBytes: number;\n },\n ) {\n super(message, { ...options, code: 'request_too_large', retryable: false, status: 413 });\n this.operationId = options.operationId;\n this.actualBytes = options.actualBytes;\n this.maxBytes = options.maxBytes;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` AFTER the HTTP response is received\n * when `validateResponses: true` is set and the response body fails Zod\n * validation against the operation's registered response schema.\n *\n * Wave 13: the runtime previously never validated responses (see ADR\n * 0020). This opt-in error gives callers a way to detect wire-format\n * mismatches for operations where typed response semantics are critical\n * (e.g. System One). The error carries the original Zod issues so\n * callers can inspect which fields failed.\n */\nexport class OllamaResponseValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'response_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * operation declares `constraints.minOllamaVersion` and the runtime could\n * not obtain a server version to compare against (e.g. `enforceVersion:\n * 'strict'` was set and `/api/version` was unreachable). Distinct from\n * {@link OllamaGenericClientError} so callers can branch on the failure\n * mode rather than parsing the message.\n */\nexport class OllamaServerVersionUnknownError extends OllamaClientError {\n readonly operationId: string;\n readonly minRequiredVersion: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n minRequiredVersion: string;\n },\n ) {\n super(message, { ...options, code: 'server_version_unknown', retryable: false });\n this.operationId = options.operationId;\n this.minRequiredVersion = options.minRequiredVersion;\n }\n}\n\nexport class OllamaToolTimeoutError extends OllamaClientError {\n readonly toolName: string;\n readonly timeoutMs: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n toolName: string;\n timeoutMs: number;\n },\n ) {\n super(message, { ...options, code: 'tool_timeout', retryable: false });\n this.toolName = options.toolName;\n this.timeoutMs = options.timeoutMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, when a request asks for a\n * capability an endpoint is known not to support (e.g. structured output `format` against\n * an Ollama Cloud endpoint — see `ModelCapabilities.supportsStructuredOutputRequest` in\n * `src/capabilities/capabilities.ts`). Its `code` is included in `DEFAULT_FAILOVER_CODES`\n * by default, so in a multi-endpoint setup it causes failover to the next candidate rather\n * than failing outright — it only surfaces to the caller if every candidate is rejected.\n */\nexport class OllamaUnsupportedCapabilityError extends OllamaClientError {\n readonly capability: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { capability: string },\n ) {\n super(message, { ...options, code: 'unsupported_capability', retryable: false });\n this.capability = options.capability;\n }\n}\n\n/**\n * Thrown client-side, before any network call, when `config.endpoints` uses\n * `OllamaEndpoint.models` to scope endpoints/credentials to specific models and the\n * requested `model` isn't in any configured endpoint's allow-list. This is a routing\n * misconfiguration, not a connectivity problem — the SDK deliberately does not \"probe\"\n * unauthorized endpoints to find one that happens to work (that would burn quota on keys\n * that were never entitled to the model and produce non-deterministic startup behavior).\n */\nexport class OllamaModelRoutingError extends OllamaClientError {\n readonly model: string;\n readonly availableModels: readonly string[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n availableModels: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'model_routing_error', retryable: false });\n this.model = options.model;\n this.availableModels = options.availableModels;\n }\n}\n\n/**\n * Thrown before an agent tool loop starts when the selected model's /api/show metadata\n * does not advertise a capability required by the loop.\n */\nexport class OllamaIncompatibleModelError extends OllamaClientError {\n readonly model: string;\n readonly capability: string;\n readonly reportedCapabilities: readonly string[];\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n capability: string;\n reportedCapabilities: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'incompatible_model', retryable: false });\n this.model = options.model;\n this.capability = options.capability;\n this.reportedCapabilities = options.reportedCapabilities;\n }\n}\nexport class OllamaAgentMaxToolCallsError extends OllamaClientError {\n readonly maxToolCalls: number;\n readonly toolCallsExecuted: number;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n maxToolCalls: number;\n toolCallsExecuted: number;\n },\n ) {\n super(message, { ...options, code: 'agent_max_tool_calls_exceeded', retryable: false });\n this.maxToolCalls = options.maxToolCalls;\n this.toolCallsExecuted = options.toolCallsExecuted;\n }\n}\n\nexport class OllamaAgentMaxIterationsError extends OllamaClientError {\n readonly maxIterations: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { maxIterations: number },\n ) {\n super(message, { ...options, code: 'agent_max_iterations_exceeded', retryable: false });\n this.maxIterations = options.maxIterations;\n }\n}\n\n/**\n * Thrown when the agent's cycle detection fires: the same tool call —\n * identical name **and** identical arguments — would execute more times than\n * `maxRepeatedToolCalls` allows during one run.\n *\n * This is the fail-fast diagnosis for a model stuck in a tool loop (repeatedly\n * calling the same function with the same arguments, never reacting to the\n * results); without it, a looping model only surfaces as a generic\n * {@link OllamaAgentMaxIterationsError} after burning the full iteration\n * budget on wasted calls.\n */\nexport class OllamaAgentToolLoopError extends OllamaClientError {\n /** Name of the tool whose identical call would exceed the repeat budget. */\n readonly toolName: string;\n /** How many times this exact call would have executed including the rejected one. */\n readonly repeatedExecutions: number;\n /** The configured per-signature execution budget. */\n readonly maxRepeatedToolCalls: number;\n /** Canonical `name(args)` signature of the repeated call (very large payloads truncated). */\n readonly signature: string;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n toolName: string;\n repeatedExecutions: number;\n maxRepeatedToolCalls: number;\n signature: string;\n },\n ) {\n super(message, { ...options, code: 'agent_tool_loop_detected', retryable: false });\n this.toolName = options.toolName;\n this.repeatedExecutions = options.repeatedExecutions;\n this.maxRepeatedToolCalls = options.maxRepeatedToolCalls;\n this.signature = options.signature;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | 'tasks/cancel';\n readonly toolName?: string | undefined;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n mcpMethod:\n 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | 'tasks/cancel';\n toolName?: string | undefined;\n issues?: unknown;\n },\n ) {\n super(message, { ...options, code: 'mcp_error', retryable: options.retryable ?? false });\n this.mcpMethod = options.mcpMethod;\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaSkillNotFoundError extends OllamaClientError {\n readonly skillName: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { skillName: string },\n ) {\n super(message, { ...options, code: 'skill_not_found', retryable: false });\n this.skillName = options.skillName;\n }\n}\n\nexport class OllamaSkillInvalidError extends OllamaClientError {\n readonly skillName: string;\n readonly path?: string | undefined;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n skillName: string;\n path?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'skill_invalid', retryable: false });\n this.skillName = options.skillName;\n this.path = options.path;\n }\n}\n\nexport class OllamaGenericClientError extends OllamaClientError {\n constructor(message: string, options?: Omit<OllamaClientErrorOptions, 'code'> | undefined) {\n super(message, { ...options, code: 'client_error' });\n }\n}\n\nfunction isDomAbortError(error: unknown): error is DOMException {\n return (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === 'AbortError'\n );\n}\n\nfunction statusToError(\n status: number,\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'status'>,\n): OllamaClientError {\n if (status === 401 || status === 403) {\n return new OllamaAuthError(message, { ...options, status });\n }\n if (status === 404) {\n return new OllamaNotFoundError(message, { ...options, status });\n }\n if (status === 429) {\n return new OllamaRateLimitError(message, { ...options, status });\n }\n if (status === 502) {\n // Cloud model could not be reached. Distinct from generic 5xx so\n // callers running multi-model agents can branch on cloud-provider\n // failures specifically (fail over to a different model/endpoint\n // rather than blindly retrying the same one).\n return new OllamaBadGatewayError(message, { ...options });\n }\n if (status === 503) {\n // Queue saturation (OLLAMA_MAX_QUEUE exceeded). Retryable — the\n // queue will eventually drain. Distinct from generic 5xx so\n // callers running parallel swarms can branch on saturation.\n return new OllamaOverloadedError(message, { ...options });\n }\n if (status >= 500) {\n return new OllamaServerError(message, { ...options, status });\n }\n return new OllamaGenericClientError(message, { ...options, status });\n}\n\n/**\n * Maps arbitrary thrown exceptions into structured OllamaClientError instances.\n */\nexport function mapError(\n error: unknown,\n context: {\n request?: OllamaErrorRequestContext | undefined;\n response?: OllamaErrorResponseContext | undefined;\n } = {},\n): OllamaClientError {\n if (error instanceof OllamaClientError) {\n return error;\n }\n if (isDomAbortError(error)) {\n return new OllamaAbortError(error.message || 'Request was aborted', {\n cause: error,\n request: context.request,\n });\n }\n if (error instanceof TypeError) {\n return new OllamaNetworkError(error.message || 'Network request failed', {\n cause: error,\n request: context.request,\n });\n }\n if (context.response?.status !== undefined) {\n const message = error instanceof Error ? error.message : String(error);\n return statusToError(context.response.status, message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new OllamaGenericClientError(message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n}\n","/**\n * Lightweight frontmatter parser for SKILL.md files.\n */\n\nimport { OllamaSkillInvalidError } from '../errors.js';\nimport type { SkillFrontmatter } from './types.js';\n\nexport interface ParsedFrontmatter {\n readonly frontmatter: SkillFrontmatter;\n readonly body: string;\n}\n\nfunction parseYamlValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') return true;\n if (trimmed === 'false') return false;\n if (!Number.isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed);\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction parseYamlBlock(yamlText: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = yamlText.split('\\n');\n let currentKey: string | undefined;\n let currentList: unknown[] | undefined;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.startsWith('- ') && currentKey) {\n if (!currentList) {\n currentList = [];\n result[currentKey] = currentList;\n }\n currentList.push(parseYamlValue(trimmed.slice(2)));\n continue;\n }\n\n currentList = undefined;\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const valStr = line.slice(colonIndex + 1).trim();\n currentKey = key;\n if (valStr.length > 0) {\n result[key] = parseYamlValue(valStr);\n }\n }\n }\n\n return result;\n}\n\nexport function parseFrontmatter(source: string, path = ''): ParsedFrontmatter {\n const match = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new OllamaSkillInvalidError('Missing YAML frontmatter delimiters (---)', {\n skillName: path || 'unknown',\n path,\n });\n }\n\n const rawYaml = match[1] ?? '';\n const body = match[2]?.trim() ?? '';\n const parsed = parseYamlBlock(rawYaml);\n\n if (!parsed['name'] || typeof parsed['name'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"name\"', {\n skillName: String(parsed['name'] ?? 'unknown'),\n path,\n });\n }\n if (!parsed['description'] || typeof parsed['description'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"description\"', {\n skillName: parsed['name'],\n path,\n });\n }\n\n return {\n frontmatter: parsed as unknown as SkillFrontmatter,\n body,\n };\n}\n","/**\n * Skill composition and context injection.\n */\n\nimport type { Message } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { Skill } from './types.js';\n\nexport interface ApplySkillOptions {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\nexport interface AppliedSkillResult {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\n/**\n * Injects a skill's body into messages as a system prompt and applies allowed tool filters.\n */\nexport function applySkill(skill: Skill, options: ApplySkillOptions): AppliedSkillResult {\n const systemPrompt = `[Skill: ${skill.name}]\\n${skill.description}\\n\\n${skill.body}`;\n const messages = [...options.messages];\n const systemIndex = messages.findIndex((m) => m.role === 'system');\n\n if (systemIndex >= 0) {\n const existing = messages[systemIndex];\n if (existing) {\n messages[systemIndex] = {\n role: 'system',\n content: `${existing.content}\\n\\n${systemPrompt}`,\n };\n }\n } else {\n messages.unshift({ role: 'system', content: systemPrompt });\n }\n\n return {\n messages,\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n };\n}\n","/**\n * Node.js filesystem skill registry for SKILL.md packages.\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { OllamaSkillNotFoundError } from '../errors.js';\nimport { parseFrontmatter } from './frontmatter.js';\nimport type { Skill, SkillSummary } from './types.js';\n\nexport interface SkillRegistryOptions {\n readonly directory: string;\n}\n\nexport class SkillRegistry {\n readonly directory: string;\n\n constructor(options: SkillRegistryOptions) {\n this.directory = options.directory;\n }\n\n async list(): Promise<SkillSummary[]> {\n const entries = await readdir(this.directory, { withFileTypes: true });\n const summaries: SkillSummary[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillPath = join(this.directory, entry.name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n summaries.push({\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n });\n } catch {\n // Skip directories without valid SKILL.md\n }\n }\n\n return summaries;\n }\n\n async load(name: string): Promise<Skill> {\n const skillPath = join(this.directory, name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n return {\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n frontmatter: parsed.frontmatter,\n body: parsed.body,\n allowedTools: parsed.frontmatter['allowed-tools'],\n };\n } catch (err) {\n throw new OllamaSkillNotFoundError(`Skill \"${name}\" not found at ${skillPath}`, {\n skillName: name,\n cause: err,\n });\n }\n }\n}\n"]}
package/dist/skills.d.cts CHANGED
@@ -1,6 +1,6 @@
1
- import { g as SkillSummary, S as Skill } from './compose-lt-Qz3lI.cjs';
2
- export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-lt-Qz3lI.cjs';
3
- import './types-BtQexFpT.cjs';
1
+ import { g as SkillSummary, S as Skill } from './compose-DhvoUrWa.cjs';
2
+ export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-DhvoUrWa.cjs';
3
+ import './types-B57ZZfp3.cjs';
4
4
  import 'zod';
5
5
 
6
6
  /**
package/dist/skills.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { g as SkillSummary, S as Skill } from './compose-BQYXdpar.js';
2
- export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-BQYXdpar.js';
3
- import './types-BtQexFpT.js';
1
+ import { g as SkillSummary, S as Skill } from './compose-6UOPEknN.js';
2
+ export { d as AppliedSkillResult, e as ApplySkillOptions, P as ParsedFrontmatter, f as SkillFrontmatter, l as applySkill, p as parseFrontmatter } from './compose-6UOPEknN.js';
3
+ import './types-B57ZZfp3.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/errors.ts","../src/skills/frontmatter.ts","../src/skills/compose.ts","../src/skills/skill-registry.ts"],"names":[],"mappings":";;;;AA0BO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAClC,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EAET,WAAA,CAAY,SAAiB,OAAA,EAAmC;AAC9D,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,CAAQ,OAAO,CAAA;AACvC,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAC7B,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,KAAA;AACtC,IAAA,IAAA,CAAK,UAAU,OAAA,CAAQ,OAAA;AACvB,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAAA,EAC1B;AACF,CAAA;AA2bO,IAAM,wBAAA,GAAN,cAAuC,iBAAA,CAAkB;AAAA,EACrD,SAAA;AAAA,EACT,WAAA,CACE,SACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,GAAG,OAAA,EAAS,MAAM,iBAAA,EAAmB,SAAA,EAAW,OAAO,CAAA;AACxE,IAAA,IAAA,CAAK,YAAY,OAAA,CAAQ,SAAA;AAAA,EAC3B;AACF,CAAA;AAEO,IAAM,uBAAA,GAAN,cAAsC,iBAAA,CAAkB;AAAA,EACpD,SAAA;AAAA,EACA,IAAA;AAAA,EACT,WAAA,CACE,SACA,OAAA,EAIA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,GAAG,OAAA,EAAS,MAAM,eAAA,EAAiB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OAAA,GAAU,MAAM,QAAA,CAAS,SAAA,EAAW,OAAO,CAAA;AACjD,MAAA,MAAM,MAAA,GAAS,gBAAA,CAAiB,OAAA,EAAS,SAAS,CAAA;AAClD,MAAA,OAAO;AAAA,QACL,IAAA,EAAM,OAAO,WAAA,CAAY,IAAA;AAAA,QACzB,WAAA,EAAa,OAAO,WAAA,CAAY,WAAA;AAAA,QAChC,IAAA,EAAM,SAAA;AAAA,QACN,aAAa,MAAA,CAAO,WAAA;AAAA,QACpB,MAAM,MAAA,CAAO,IAAA;AAAA,QACb,YAAA,EAAc,MAAA,CAAO,WAAA,CAAY,eAAe;AAAA,OAClD;AAAA,IACF,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,IAAI,wBAAA,CAAyB,CAAA,OAAA,EAAU,IAAI,CAAA,eAAA,EAAkB,SAAS,CAAA,CAAA,EAAI;AAAA,QAC9E,SAAA,EAAW,IAAA;AAAA,QACX,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"skills.js","sourcesContent":["/**\n * Structured, typed error hierarchy for OllamaClient.\n */\n\nimport type { z } from 'zod';\n\nexport interface OllamaErrorRequestContext {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n readonly model?: string | undefined;\n}\n\nexport interface OllamaErrorResponseContext {\n readonly status?: number | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly body?: unknown;\n}\n\nexport interface OllamaClientErrorOptions extends ErrorOptions {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable?: boolean | undefined;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n}\n\nexport class OllamaClientError extends Error {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable: boolean;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n\n constructor(message: string, options: OllamaClientErrorOptions) {\n super(message, { cause: options.cause });\n this.name = this.constructor.name;\n this.code = options.code;\n this.status = options.status;\n this.retryable = options.retryable ?? false;\n this.request = options.request;\n this.response = options.response;\n }\n}\n\nexport class OllamaNetworkError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'network_error', retryable: true });\n }\n}\n\nexport class OllamaTimeoutError extends OllamaClientError {\n readonly timeoutMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { timeoutMs?: number | undefined })\n | undefined,\n ) {\n super(message, { ...options, code: 'timeout', retryable: true });\n this.timeoutMs = options?.timeoutMs;\n }\n}\n\nexport class OllamaAuthError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'auth_error', retryable: false });\n }\n}\n\nexport class OllamaNotFoundError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'not_found', retryable: false });\n }\n}\n\nexport class OllamaRateLimitError extends OllamaClientError {\n readonly retryAfterMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n retryAfterMs?: number | undefined;\n })\n | undefined,\n ) {\n super(message, { ...options, code: 'rate_limited', retryable: true });\n this.retryAfterMs = options?.retryAfterMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, by `QuotaManager.assertCanProceed`\n * (see `src/quota.ts`) when issuing the request would exceed a configured usage budget for\n * one of its rolling windows. This is distinct from `OllamaRateLimitError`, which reflects\n * the server's own 429 response — Ollama Cloud does not expose account-level quota via the\n * API, so `QuotaManager` tracks usage against budgets the caller configures locally and\n * fails fast rather than waiting for the server to reject the request.\n */\nexport class OllamaQuotaExceededError extends OllamaClientError {\n readonly windowId: string;\n readonly resetAt: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n windowId: string;\n resetAt: number;\n },\n ) {\n super(message, { ...options, code: 'quota_exceeded', retryable: false });\n this.windowId = options.windowId;\n this.resetAt = options.resetAt;\n }\n}\n\nexport class OllamaServerError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'server_error', retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **503 Service Unavailable**,\n * indicating that the request queue is saturated (`OLLAMA_MAX_QUEUE`\n * exceeded, default 512 — see the FAQ).\n *\n * Semantically a specialization of {@link OllamaServerError} (503 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'overloaded'` —\n * `OllamaServerError`'s constructor unconditionally forces\n * `code: 'server_error'`. Callers wanting to catch any 5xx should\n * use `error.status >= 500 && error.status < 600` OR explicitly\n * list both `OllamaServerError` and `OllamaOverloadedError`/\n * `OllamaBadGatewayError` in their `instanceof` checks.\n *\n * `retryable` is `true` because the queue will eventually drain;\n * callers using {@link withRetry} will get automatic backoff.\n */\nexport class OllamaOverloadedError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'overloaded', status: 503, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **502 Bad Gateway**,\n * indicating that a cloud model could not be reached by the\n * Ollama Cloud proxy. The model may be temporarily down, the\n * cloud provider may be experiencing an outage, or the model\n * may have been deprovisioned.\n *\n * Semantically a specialization of {@link OllamaServerError} (502 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'bad_gateway'` —\n * see {@link OllamaOverloadedError} for the rationale. Callers wanting\n * to catch any 5xx should use `error.status >= 500 && error.status < 600`\n * OR explicitly list both classes in their `instanceof` checks.\n *\n * `retryable` is `true` for transient cloud-provider outages.\n */\nexport class OllamaBadGatewayError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'bad_gateway', status: 502, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server emits an in-band error frame inside\n * an NDJSON stream (chat / generate / pull / push / create).\n *\n * Ollama streams start with HTTP 200 OK and chunked transfer encoding.\n * If an error occurs mid-generation (GPU OOM, driver crash, context\n * window overflow, model unload race, etc.), the server emits a final\n * JSON chunk of the form `{\"error\": \"...\"}` and closes the stream.\n * The HTTP status code never changes from 200, so HTTP-status-based\n * error detection misses these errors entirely — they would silently\n * bleed into the assistant's content stream as garbage tokens or\n * undefined-field accesses.\n *\n * `partialContent` carries whatever was accumulated before the error\n * frame, so callers can log/diagnose what the model produced before\n * failing. For chat streams this is the concatenated `message.content`;\n * for generate streams it's the concatenated `response`; for pull/push\n * streams it's empty (progress events don't accumulate content).\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/api.md\n */\nexport class OllamaStreamError extends OllamaClientError {\n /** Content accumulated before the in-band error frame, or '' if none. */\n readonly partialContent: string;\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n partialContent?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'stream_error', retryable: false });\n this.partialContent = options?.partialContent ?? '';\n }\n}\n\nexport class OllamaAbortError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'aborted', retryable: false });\n }\n}\n\nexport class OllamaToolValidationError extends OllamaClientError {\n readonly toolName: string;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { toolName: string; issues?: unknown },\n ) {\n super(message, { ...options, code: 'tool_validation_error', retryable: false });\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` when `validateRequests: true` is set and\n * the request body fails Zod validation against the operation's registered\n * schema. See ADR 0020 (runtime Zod validation).\n *\n * The error carries the original Zod issues so callers can inspect which\n * fields failed. No HTTP request is made when this error is thrown.\n */\nexport class OllamaRequestValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'request_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * serialized request body exceeds the operation's declared\n * `constraints.maxRequestBytes`. The Ollama server returns 413 for such\n * payloads; this client-side check fails fast so the round-trip is avoided.\n *\n * Wave 12 (P0 #5): the IR has carried `maxRequestBytes` for System One\n * (64 KiB) since v1.7.0, but the runtime never enforced it. This closes\n * that contract/runtime gap.\n */\nexport class OllamaRequestTooLargeError extends OllamaClientError {\n readonly operationId: string;\n readonly actualBytes: number;\n readonly maxBytes: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> & {\n operationId: string;\n actualBytes: number;\n maxBytes: number;\n },\n ) {\n super(message, { ...options, code: 'request_too_large', retryable: false, status: 413 });\n this.operationId = options.operationId;\n this.actualBytes = options.actualBytes;\n this.maxBytes = options.maxBytes;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` AFTER the HTTP response is received\n * when `validateResponses: true` is set and the response body fails Zod\n * validation against the operation's registered response schema.\n *\n * Wave 13: the runtime previously never validated responses (see ADR\n * 0020). This opt-in error gives callers a way to detect wire-format\n * mismatches for operations where typed response semantics are critical\n * (e.g. System One). The error carries the original Zod issues so\n * callers can inspect which fields failed.\n */\nexport class OllamaResponseValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'response_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * operation declares `constraints.minOllamaVersion` and the runtime could\n * not obtain a server version to compare against (e.g. `enforceVersion:\n * 'strict'` was set and `/api/version` was unreachable). Distinct from\n * {@link OllamaGenericClientError} so callers can branch on the failure\n * mode rather than parsing the message.\n */\nexport class OllamaServerVersionUnknownError extends OllamaClientError {\n readonly operationId: string;\n readonly minRequiredVersion: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n minRequiredVersion: string;\n },\n ) {\n super(message, { ...options, code: 'server_version_unknown', retryable: false });\n this.operationId = options.operationId;\n this.minRequiredVersion = options.minRequiredVersion;\n }\n}\n\nexport class OllamaToolTimeoutError extends OllamaClientError {\n readonly toolName: string;\n readonly timeoutMs: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n toolName: string;\n timeoutMs: number;\n },\n ) {\n super(message, { ...options, code: 'tool_timeout', retryable: false });\n this.toolName = options.toolName;\n this.timeoutMs = options.timeoutMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, when a request asks for a\n * capability an endpoint is known not to support (e.g. structured output `format` against\n * an Ollama Cloud endpoint — see `ModelCapabilities.supportsStructuredOutputRequest` in\n * `src/capabilities/capabilities.ts`). Its `code` is included in `DEFAULT_FAILOVER_CODES`\n * by default, so in a multi-endpoint setup it causes failover to the next candidate rather\n * than failing outright — it only surfaces to the caller if every candidate is rejected.\n */\nexport class OllamaUnsupportedCapabilityError extends OllamaClientError {\n readonly capability: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { capability: string },\n ) {\n super(message, { ...options, code: 'unsupported_capability', retryable: false });\n this.capability = options.capability;\n }\n}\n\n/**\n * Thrown client-side, before any network call, when `config.endpoints` uses\n * `OllamaEndpoint.models` to scope endpoints/credentials to specific models and the\n * requested `model` isn't in any configured endpoint's allow-list. This is a routing\n * misconfiguration, not a connectivity problem — the SDK deliberately does not \"probe\"\n * unauthorized endpoints to find one that happens to work (that would burn quota on keys\n * that were never entitled to the model and produce non-deterministic startup behavior).\n */\nexport class OllamaModelRoutingError extends OllamaClientError {\n readonly model: string;\n readonly availableModels: readonly string[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n availableModels: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'model_routing_error', retryable: false });\n this.model = options.model;\n this.availableModels = options.availableModels;\n }\n}\n\n/**\n * Thrown before an agent tool loop starts when the selected model's /api/show metadata\n * does not advertise a capability required by the loop.\n */\nexport class OllamaIncompatibleModelError extends OllamaClientError {\n readonly model: string;\n readonly capability: string;\n readonly reportedCapabilities: readonly string[];\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n capability: string;\n reportedCapabilities: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'incompatible_model', retryable: false });\n this.model = options.model;\n this.capability = options.capability;\n this.reportedCapabilities = options.reportedCapabilities;\n }\n}\nexport class OllamaAgentMaxToolCallsError extends OllamaClientError {\n readonly maxToolCalls: number;\n readonly toolCallsExecuted: number;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n maxToolCalls: number;\n toolCallsExecuted: number;\n },\n ) {\n super(message, { ...options, code: 'agent_max_tool_calls_exceeded', retryable: false });\n this.maxToolCalls = options.maxToolCalls;\n this.toolCallsExecuted = options.toolCallsExecuted;\n }\n}\n\nexport class OllamaAgentMaxIterationsError extends OllamaClientError {\n readonly maxIterations: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { maxIterations: number },\n ) {\n super(message, { ...options, code: 'agent_max_iterations_exceeded', retryable: false });\n this.maxIterations = options.maxIterations;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n readonly toolName?: string | undefined;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n mcpMethod:\n | 'listTools'\n | 'callTool'\n | 'tools/call'\n | 'tasks/get'\n | 'tasks/result'\n | 'tasks/cancel';\n toolName?: string | undefined;\n issues?: unknown;\n },\n ) {\n super(message, { ...options, code: 'mcp_error', retryable: options.retryable ?? false });\n this.mcpMethod = options.mcpMethod;\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaSkillNotFoundError extends OllamaClientError {\n readonly skillName: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { skillName: string },\n ) {\n super(message, { ...options, code: 'skill_not_found', retryable: false });\n this.skillName = options.skillName;\n }\n}\n\nexport class OllamaSkillInvalidError extends OllamaClientError {\n readonly skillName: string;\n readonly path?: string | undefined;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n skillName: string;\n path?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'skill_invalid', retryable: false });\n this.skillName = options.skillName;\n this.path = options.path;\n }\n}\n\nexport class OllamaGenericClientError extends OllamaClientError {\n constructor(message: string, options?: Omit<OllamaClientErrorOptions, 'code'> | undefined) {\n super(message, { ...options, code: 'client_error' });\n }\n}\n\nfunction isDomAbortError(error: unknown): error is DOMException {\n return (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === 'AbortError'\n );\n}\n\nfunction statusToError(\n status: number,\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'status'>,\n): OllamaClientError {\n if (status === 401 || status === 403) {\n return new OllamaAuthError(message, { ...options, status });\n }\n if (status === 404) {\n return new OllamaNotFoundError(message, { ...options, status });\n }\n if (status === 429) {\n return new OllamaRateLimitError(message, { ...options, status });\n }\n if (status === 502) {\n // Cloud model could not be reached. Distinct from generic 5xx so\n // callers running multi-model agents can branch on cloud-provider\n // failures specifically (fail over to a different model/endpoint\n // rather than blindly retrying the same one).\n return new OllamaBadGatewayError(message, { ...options });\n }\n if (status === 503) {\n // Queue saturation (OLLAMA_MAX_QUEUE exceeded). Retryable — the\n // queue will eventually drain. Distinct from generic 5xx so\n // callers running parallel swarms can branch on saturation.\n return new OllamaOverloadedError(message, { ...options });\n }\n if (status >= 500) {\n return new OllamaServerError(message, { ...options, status });\n }\n return new OllamaGenericClientError(message, { ...options, status });\n}\n\n/**\n * Maps arbitrary thrown exceptions into structured OllamaClientError instances.\n */\nexport function mapError(\n error: unknown,\n context: {\n request?: OllamaErrorRequestContext | undefined;\n response?: OllamaErrorResponseContext | undefined;\n } = {},\n): OllamaClientError {\n if (error instanceof OllamaClientError) {\n return error;\n }\n if (isDomAbortError(error)) {\n return new OllamaAbortError(error.message || 'Request was aborted', {\n cause: error,\n request: context.request,\n });\n }\n if (error instanceof TypeError) {\n return new OllamaNetworkError(error.message || 'Network request failed', {\n cause: error,\n request: context.request,\n });\n }\n if (context.response?.status !== undefined) {\n const message = error instanceof Error ? error.message : String(error);\n return statusToError(context.response.status, message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new OllamaGenericClientError(message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n}\n","/**\n * Lightweight frontmatter parser for SKILL.md files.\n */\n\nimport { OllamaSkillInvalidError } from '../errors.js';\nimport type { SkillFrontmatter } from './types.js';\n\nexport interface ParsedFrontmatter {\n readonly frontmatter: SkillFrontmatter;\n readonly body: string;\n}\n\nfunction parseYamlValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') return true;\n if (trimmed === 'false') return false;\n if (!Number.isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed);\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction parseYamlBlock(yamlText: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = yamlText.split('\\n');\n let currentKey: string | undefined;\n let currentList: unknown[] | undefined;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.startsWith('- ') && currentKey) {\n if (!currentList) {\n currentList = [];\n result[currentKey] = currentList;\n }\n currentList.push(parseYamlValue(trimmed.slice(2)));\n continue;\n }\n\n currentList = undefined;\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const valStr = line.slice(colonIndex + 1).trim();\n currentKey = key;\n if (valStr.length > 0) {\n result[key] = parseYamlValue(valStr);\n }\n }\n }\n\n return result;\n}\n\nexport function parseFrontmatter(source: string, path = ''): ParsedFrontmatter {\n const match = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new OllamaSkillInvalidError('Missing YAML frontmatter delimiters (---)', {\n skillName: path || 'unknown',\n path,\n });\n }\n\n const rawYaml = match[1] ?? '';\n const body = match[2]?.trim() ?? '';\n const parsed = parseYamlBlock(rawYaml);\n\n if (!parsed['name'] || typeof parsed['name'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"name\"', {\n skillName: String(parsed['name'] ?? 'unknown'),\n path,\n });\n }\n if (!parsed['description'] || typeof parsed['description'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"description\"', {\n skillName: parsed['name'],\n path,\n });\n }\n\n return {\n frontmatter: parsed as unknown as SkillFrontmatter,\n body,\n };\n}\n","/**\n * Skill composition and context injection.\n */\n\nimport type { Message } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { Skill } from './types.js';\n\nexport interface ApplySkillOptions {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\nexport interface AppliedSkillResult {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\n/**\n * Injects a skill's body into messages as a system prompt and applies allowed tool filters.\n */\nexport function applySkill(skill: Skill, options: ApplySkillOptions): AppliedSkillResult {\n const systemPrompt = `[Skill: ${skill.name}]\\n${skill.description}\\n\\n${skill.body}`;\n const messages = [...options.messages];\n const systemIndex = messages.findIndex((m) => m.role === 'system');\n\n if (systemIndex >= 0) {\n const existing = messages[systemIndex];\n if (existing) {\n messages[systemIndex] = {\n role: 'system',\n content: `${existing.content}\\n\\n${systemPrompt}`,\n };\n }\n } else {\n messages.unshift({ role: 'system', content: systemPrompt });\n }\n\n return {\n messages,\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n };\n}\n","/**\n * Node.js filesystem skill registry for SKILL.md packages.\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { OllamaSkillNotFoundError } from '../errors.js';\nimport { parseFrontmatter } from './frontmatter.js';\nimport type { Skill, SkillSummary } from './types.js';\n\nexport interface SkillRegistryOptions {\n readonly directory: string;\n}\n\nexport class SkillRegistry {\n readonly directory: string;\n\n constructor(options: SkillRegistryOptions) {\n this.directory = options.directory;\n }\n\n async list(): Promise<SkillSummary[]> {\n const entries = await readdir(this.directory, { withFileTypes: true });\n const summaries: SkillSummary[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillPath = join(this.directory, entry.name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n summaries.push({\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n });\n } catch {\n // Skip directories without valid SKILL.md\n }\n }\n\n return summaries;\n }\n\n async load(name: string): Promise<Skill> {\n const skillPath = join(this.directory, name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n return {\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n frontmatter: parsed.frontmatter,\n body: parsed.body,\n allowedTools: parsed.frontmatter['allowed-tools'],\n };\n } catch (err) {\n throw new OllamaSkillNotFoundError(`Skill \"${name}\" not found at ${skillPath}`, {\n skillName: name,\n cause: err,\n });\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/skills/frontmatter.ts","../src/skills/compose.ts","../src/skills/skill-registry.ts"],"names":[],"mappings":";;;;AA0BO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EAClC,IAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,OAAA;AAAA,EACA,QAAA;AAAA,EAET,WAAA,CAAY,SAAiB,OAAA,EAAmC;AAC9D,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAA,CAAQ,OAAO,CAAA;AACvC,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAC7B,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,SAAA,GAAY,QAAQ,SAAA,IAAa,KAAA;AACtC,IAAA,IAAA,CAAK,UAAU,OAAA,CAAQ,OAAA;AACvB,IAAA,IAAA,CAAK,WAAW,OAAA,CAAQ,QAAA;AAAA,EAC1B;AACF,CAAA;AAudO,IAAM,wBAAA,GAAN,cAAuC,iBAAA,CAAkB;AAAA,EACrD,SAAA;AAAA,EACT,WAAA,CACE,SACA,OAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,GAAG,OAAA,EAAS,MAAM,iBAAA,EAAmB,SAAA,EAAW,OAAO,CAAA;AACxE,IAAA,IAAA,CAAK,YA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AA;AAAA,MACH,CAAA,CAAA,MAAQ;AAAA,MAER;AAAA,IACF;AAEA,IAAA,OAAO,SAAA;AAAA,EACT;AAAA,EAEA,MAAM,KAAK,IAAA,EAA8B;AACvC,IAAA,MAAM,SAAA,GAAY,IAAA,CAAK,IAAA,CAAK,SAAA,EAAW,MAAM,UAAU,CAAA;AACvD,IAAA,IAAI;AACF,MAAA,MAAM,OAAA,GAAU,MAAM,QAAA,CAAS,SAAA,EAAW,OAAO,CAAA;AACjD,MAAA,MAAM,MAAA,GAAS,gBAAA,CAAiB,OAAA,EAAS,SAAS,CAAA;AAClD,MAAA,OAAO;AAAA,QACL,IAAA,EAAM,OAAO,WAAA,CAAY,IAAA;AAAA,QACzB,WAAA,EAAa,OAAO,WAAA,CAAY,WAAA;AAAA,QAChC,IAAA,EAAM,SAAA;AAAA,QACN,aAAa,MAAA,CAAO,WAAA;AAAA,QACpB,MAAM,MAAA,CAAO,IAAA;AAAA,QACb,YAAA,EAAc,MAAA,CAAO,WAAA,CAAY,eAAe;AAAA,OAClD;AAAA,IACF,SAAS,GAAA,EAAK;AACZ,MAAA,MAAM,IAAI,wBAAA,CAAyB,CAAA,OAAA,EAAU,IAAI,CAAA,eAAA,EAAkB,SAAS,CAAA,CAAA,EAAI;AAAA,QAC9E,SAAA,EAAW,IAAA;AAAA,QACX,KAAA,EAAO;AAAA,OACR,CAAA;AAAA,IACH;AAAA,EACF;AACF","file":"skills.js","sourcesContent":["/**\n * Structured, typed error hierarchy for OllamaClient.\n */\n\nimport type { z } from 'zod';\n\nexport interface OllamaErrorRequestContext {\n readonly method?: string | undefined;\n readonly url?: string | undefined;\n readonly model?: string | undefined;\n}\n\nexport interface OllamaErrorResponseContext {\n readonly status?: number | undefined;\n readonly headers?: Record<string, string> | undefined;\n readonly body?: unknown;\n}\n\nexport interface OllamaClientErrorOptions extends ErrorOptions {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable?: boolean | undefined;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n}\n\nexport class OllamaClientError extends Error {\n readonly code: string;\n readonly status?: number | undefined;\n readonly retryable: boolean;\n readonly request?: OllamaErrorRequestContext | undefined;\n readonly response?: OllamaErrorResponseContext | undefined;\n\n constructor(message: string, options: OllamaClientErrorOptions) {\n super(message, { cause: options.cause });\n this.name = this.constructor.name;\n this.code = options.code;\n this.status = options.status;\n this.retryable = options.retryable ?? false;\n this.request = options.request;\n this.response = options.response;\n }\n}\n\nexport class OllamaNetworkError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'network_error', retryable: true });\n }\n}\n\nexport class OllamaTimeoutError extends OllamaClientError {\n readonly timeoutMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { timeoutMs?: number | undefined })\n | undefined,\n ) {\n super(message, { ...options, code: 'timeout', retryable: true });\n this.timeoutMs = options?.timeoutMs;\n }\n}\n\nexport class OllamaAuthError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'auth_error', retryable: false });\n }\n}\n\nexport class OllamaNotFoundError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'not_found', retryable: false });\n }\n}\n\nexport class OllamaRateLimitError extends OllamaClientError {\n readonly retryAfterMs?: number | undefined;\n constructor(\n message: string,\n options?:\n | (Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n retryAfterMs?: number | undefined;\n })\n | undefined,\n ) {\n super(message, { ...options, code: 'rate_limited', retryable: true });\n this.retryAfterMs = options?.retryAfterMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, by `QuotaManager.assertCanProceed`\n * (see `src/quota.ts`) when issuing the request would exceed a configured usage budget for\n * one of its rolling windows. This is distinct from `OllamaRateLimitError`, which reflects\n * the server's own 429 response — Ollama Cloud does not expose account-level quota via the\n * API, so `QuotaManager` tracks usage against budgets the caller configures locally and\n * fails fast rather than waiting for the server to reject the request.\n */\nexport class OllamaQuotaExceededError extends OllamaClientError {\n readonly windowId: string;\n readonly resetAt: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n windowId: string;\n resetAt: number;\n },\n ) {\n super(message, { ...options, code: 'quota_exceeded', retryable: false });\n this.windowId = options.windowId;\n this.resetAt = options.resetAt;\n }\n}\n\nexport class OllamaServerError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'server_error', retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **503 Service Unavailable**,\n * indicating that the request queue is saturated (`OLLAMA_MAX_QUEUE`\n * exceeded, default 512 — see the FAQ).\n *\n * Semantically a specialization of {@link OllamaServerError} (503 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'overloaded'` —\n * `OllamaServerError`'s constructor unconditionally forces\n * `code: 'server_error'`. Callers wanting to catch any 5xx should\n * use `error.status >= 500 && error.status < 600` OR explicitly\n * list both `OllamaServerError` and `OllamaOverloadedError`/\n * `OllamaBadGatewayError` in their `instanceof` checks.\n *\n * `retryable` is `true` because the queue will eventually drain;\n * callers using {@link withRetry} will get automatic backoff.\n */\nexport class OllamaOverloadedError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'overloaded', status: 503, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server returns HTTP **502 Bad Gateway**,\n * indicating that a cloud model could not be reached by the\n * Ollama Cloud proxy. The model may be temporarily down, the\n * cloud provider may be experiencing an outage, or the model\n * may have been deprovisioned.\n *\n * Semantically a specialization of {@link OllamaServerError} (502 is a\n * kind of 5xx server error), but extends {@link OllamaClientError}\n * directly to preserve the subclass-specific `code: 'bad_gateway'` —\n * see {@link OllamaOverloadedError} for the rationale. Callers wanting\n * to catch any 5xx should use `error.status >= 500 && error.status < 600`\n * OR explicitly list both classes in their `instanceof` checks.\n *\n * `retryable` is `true` for transient cloud-provider outages.\n */\nexport class OllamaBadGatewayError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> | undefined,\n ) {\n super(message, { ...options, code: 'bad_gateway', status: 502, retryable: true });\n }\n}\n\n/**\n * Thrown when the Ollama server emits an in-band error frame inside\n * an NDJSON stream (chat / generate / pull / push / create).\n *\n * Ollama streams start with HTTP 200 OK and chunked transfer encoding.\n * If an error occurs mid-generation (GPU OOM, driver crash, context\n * window overflow, model unload race, etc.), the server emits a final\n * JSON chunk of the form `{\"error\": \"...\"}` and closes the stream.\n * The HTTP status code never changes from 200, so HTTP-status-based\n * error detection misses these errors entirely — they would silently\n * bleed into the assistant's content stream as garbage tokens or\n * undefined-field accesses.\n *\n * `partialContent` carries whatever was accumulated before the error\n * frame, so callers can log/diagnose what the model produced before\n * failing. For chat streams this is the concatenated `message.content`;\n * for generate streams it's the concatenated `response`; for pull/push\n * streams it's empty (progress events don't accumulate content).\n *\n * See: https://github.com/ollama/ollama/blob/main/docs/api.md\n */\nexport class OllamaStreamError extends OllamaClientError {\n /** Content accumulated before the in-band error frame, or '' if none. */\n readonly partialContent: string;\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n partialContent?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'stream_error', retryable: false });\n this.partialContent = options?.partialContent ?? '';\n }\n}\n\nexport class OllamaAbortError extends OllamaClientError {\n constructor(\n message: string,\n options?: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> | undefined,\n ) {\n super(message, { ...options, code: 'aborted', retryable: false });\n }\n}\n\nexport class OllamaToolValidationError extends OllamaClientError {\n readonly toolName: string;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { toolName: string; issues?: unknown },\n ) {\n super(message, { ...options, code: 'tool_validation_error', retryable: false });\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` when `validateRequests: true` is set and\n * the request body fails Zod validation against the operation's registered\n * schema. See ADR 0020 (runtime Zod validation).\n *\n * The error carries the original Zod issues so callers can inspect which\n * fields failed. No HTTP request is made when this error is thrown.\n */\nexport class OllamaRequestValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'request_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * serialized request body exceeds the operation's declared\n * `constraints.maxRequestBytes`. The Ollama server returns 413 for such\n * payloads; this client-side check fails fast so the round-trip is avoided.\n *\n * Wave 12 (P0 #5): the IR has carried `maxRequestBytes` for System One\n * (64 KiB) since v1.7.0, but the runtime never enforced it. This closes\n * that contract/runtime gap.\n */\nexport class OllamaRequestTooLargeError extends OllamaClientError {\n readonly operationId: string;\n readonly actualBytes: number;\n readonly maxBytes: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable' | 'status'> & {\n operationId: string;\n actualBytes: number;\n maxBytes: number;\n },\n ) {\n super(message, { ...options, code: 'request_too_large', retryable: false, status: 413 });\n this.operationId = options.operationId;\n this.actualBytes = options.actualBytes;\n this.maxBytes = options.maxBytes;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` AFTER the HTTP response is received\n * when `validateResponses: true` is set and the response body fails Zod\n * validation against the operation's registered response schema.\n *\n * Wave 13: the runtime previously never validated responses (see ADR\n * 0020). This opt-in error gives callers a way to detect wire-format\n * mismatches for operations where typed response semantics are critical\n * (e.g. System One). The error carries the original Zod issues so\n * callers can inspect which fields failed.\n */\nexport class OllamaResponseValidationError extends OllamaClientError {\n readonly operationId: string;\n readonly issues: readonly z.ZodIssue[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n issues: readonly z.ZodIssue[];\n },\n ) {\n super(message, { ...options, code: 'response_validation_error', retryable: false });\n this.operationId = options.operationId;\n this.issues = options.issues;\n }\n}\n\n/**\n * Thrown by `OllamaRuntime.invoke` BEFORE any HTTP request is made when the\n * operation declares `constraints.minOllamaVersion` and the runtime could\n * not obtain a server version to compare against (e.g. `enforceVersion:\n * 'strict'` was set and `/api/version` was unreachable). Distinct from\n * {@link OllamaGenericClientError} so callers can branch on the failure\n * mode rather than parsing the message.\n */\nexport class OllamaServerVersionUnknownError extends OllamaClientError {\n readonly operationId: string;\n readonly minRequiredVersion: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n operationId: string;\n minRequiredVersion: string;\n },\n ) {\n super(message, { ...options, code: 'server_version_unknown', retryable: false });\n this.operationId = options.operationId;\n this.minRequiredVersion = options.minRequiredVersion;\n }\n}\n\nexport class OllamaToolTimeoutError extends OllamaClientError {\n readonly toolName: string;\n readonly timeoutMs: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n toolName: string;\n timeoutMs: number;\n },\n ) {\n super(message, { ...options, code: 'tool_timeout', retryable: false });\n this.toolName = options.toolName;\n this.timeoutMs = options.timeoutMs;\n }\n}\n\n/**\n * Thrown client-side, before a network request is made, when a request asks for a\n * capability an endpoint is known not to support (e.g. structured output `format` against\n * an Ollama Cloud endpoint — see `ModelCapabilities.supportsStructuredOutputRequest` in\n * `src/capabilities/capabilities.ts`). Its `code` is included in `DEFAULT_FAILOVER_CODES`\n * by default, so in a multi-endpoint setup it causes failover to the next candidate rather\n * than failing outright — it only surfaces to the caller if every candidate is rejected.\n */\nexport class OllamaUnsupportedCapabilityError extends OllamaClientError {\n readonly capability: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & { capability: string },\n ) {\n super(message, { ...options, code: 'unsupported_capability', retryable: false });\n this.capability = options.capability;\n }\n}\n\n/**\n * Thrown client-side, before any network call, when `config.endpoints` uses\n * `OllamaEndpoint.models` to scope endpoints/credentials to specific models and the\n * requested `model` isn't in any configured endpoint's allow-list. This is a routing\n * misconfiguration, not a connectivity problem — the SDK deliberately does not \"probe\"\n * unauthorized endpoints to find one that happens to work (that would burn quota on keys\n * that were never entitled to the model and produce non-deterministic startup behavior).\n */\nexport class OllamaModelRoutingError extends OllamaClientError {\n readonly model: string;\n readonly availableModels: readonly string[];\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n availableModels: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'model_routing_error', retryable: false });\n this.model = options.model;\n this.availableModels = options.availableModels;\n }\n}\n\n/**\n * Thrown before an agent tool loop starts when the selected model's /api/show metadata\n * does not advertise a capability required by the loop.\n */\nexport class OllamaIncompatibleModelError extends OllamaClientError {\n readonly model: string;\n readonly capability: string;\n readonly reportedCapabilities: readonly string[];\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'retryable'> & {\n model: string;\n capability: string;\n reportedCapabilities: readonly string[];\n },\n ) {\n super(message, { ...options, code: 'incompatible_model', retryable: false });\n this.model = options.model;\n this.capability = options.capability;\n this.reportedCapabilities = options.reportedCapabilities;\n }\n}\nexport class OllamaAgentMaxToolCallsError extends OllamaClientError {\n readonly maxToolCalls: number;\n readonly toolCallsExecuted: number;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n maxToolCalls: number;\n toolCallsExecuted: number;\n },\n ) {\n super(message, { ...options, code: 'agent_max_tool_calls_exceeded', retryable: false });\n this.maxToolCalls = options.maxToolCalls;\n this.toolCallsExecuted = options.toolCallsExecuted;\n }\n}\n\nexport class OllamaAgentMaxIterationsError extends OllamaClientError {\n readonly maxIterations: number;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { maxIterations: number },\n ) {\n super(message, { ...options, code: 'agent_max_iterations_exceeded', retryable: false });\n this.maxIterations = options.maxIterations;\n }\n}\n\n/**\n * Thrown when the agent's cycle detection fires: the same tool call —\n * identical name **and** identical arguments — would execute more times than\n * `maxRepeatedToolCalls` allows during one run.\n *\n * This is the fail-fast diagnosis for a model stuck in a tool loop (repeatedly\n * calling the same function with the same arguments, never reacting to the\n * results); without it, a looping model only surfaces as a generic\n * {@link OllamaAgentMaxIterationsError} after burning the full iteration\n * budget on wasted calls.\n */\nexport class OllamaAgentToolLoopError extends OllamaClientError {\n /** Name of the tool whose identical call would exceed the repeat budget. */\n readonly toolName: string;\n /** How many times this exact call would have executed including the rejected one. */\n readonly repeatedExecutions: number;\n /** The configured per-signature execution budget. */\n readonly maxRepeatedToolCalls: number;\n /** Canonical `name(args)` signature of the repeated call (very large payloads truncated). */\n readonly signature: string;\n\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n toolName: string;\n repeatedExecutions: number;\n maxRepeatedToolCalls: number;\n signature: string;\n },\n ) {\n super(message, { ...options, code: 'agent_tool_loop_detected', retryable: false });\n this.toolName = options.toolName;\n this.repeatedExecutions = options.repeatedExecutions;\n this.maxRepeatedToolCalls = options.maxRepeatedToolCalls;\n this.signature = options.signature;\n }\n}\n\nexport class OllamaMcpError extends OllamaClientError {\n readonly mcpMethod:\n 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | 'tasks/cancel';\n readonly toolName?: string | undefined;\n readonly issues?: unknown;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n mcpMethod:\n 'listTools' | 'callTool' | 'tools/call' | 'tasks/get' | 'tasks/result' | 'tasks/cancel';\n toolName?: string | undefined;\n issues?: unknown;\n },\n ) {\n super(message, { ...options, code: 'mcp_error', retryable: options.retryable ?? false });\n this.mcpMethod = options.mcpMethod;\n this.toolName = options.toolName;\n this.issues = options.issues;\n }\n}\n\nexport class OllamaSkillNotFoundError extends OllamaClientError {\n readonly skillName: string;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & { skillName: string },\n ) {\n super(message, { ...options, code: 'skill_not_found', retryable: false });\n this.skillName = options.skillName;\n }\n}\n\nexport class OllamaSkillInvalidError extends OllamaClientError {\n readonly skillName: string;\n readonly path?: string | undefined;\n constructor(\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code'> & {\n skillName: string;\n path?: string | undefined;\n },\n ) {\n super(message, { ...options, code: 'skill_invalid', retryable: false });\n this.skillName = options.skillName;\n this.path = options.path;\n }\n}\n\nexport class OllamaGenericClientError extends OllamaClientError {\n constructor(message: string, options?: Omit<OllamaClientErrorOptions, 'code'> | undefined) {\n super(message, { ...options, code: 'client_error' });\n }\n}\n\nfunction isDomAbortError(error: unknown): error is DOMException {\n return (\n typeof DOMException !== 'undefined' &&\n error instanceof DOMException &&\n error.name === 'AbortError'\n );\n}\n\nfunction statusToError(\n status: number,\n message: string,\n options: Omit<OllamaClientErrorOptions, 'code' | 'status'>,\n): OllamaClientError {\n if (status === 401 || status === 403) {\n return new OllamaAuthError(message, { ...options, status });\n }\n if (status === 404) {\n return new OllamaNotFoundError(message, { ...options, status });\n }\n if (status === 429) {\n return new OllamaRateLimitError(message, { ...options, status });\n }\n if (status === 502) {\n // Cloud model could not be reached. Distinct from generic 5xx so\n // callers running multi-model agents can branch on cloud-provider\n // failures specifically (fail over to a different model/endpoint\n // rather than blindly retrying the same one).\n return new OllamaBadGatewayError(message, { ...options });\n }\n if (status === 503) {\n // Queue saturation (OLLAMA_MAX_QUEUE exceeded). Retryable — the\n // queue will eventually drain. Distinct from generic 5xx so\n // callers running parallel swarms can branch on saturation.\n return new OllamaOverloadedError(message, { ...options });\n }\n if (status >= 500) {\n return new OllamaServerError(message, { ...options, status });\n }\n return new OllamaGenericClientError(message, { ...options, status });\n}\n\n/**\n * Maps arbitrary thrown exceptions into structured OllamaClientError instances.\n */\nexport function mapError(\n error: unknown,\n context: {\n request?: OllamaErrorRequestContext | undefined;\n response?: OllamaErrorResponseContext | undefined;\n } = {},\n): OllamaClientError {\n if (error instanceof OllamaClientError) {\n return error;\n }\n if (isDomAbortError(error)) {\n return new OllamaAbortError(error.message || 'Request was aborted', {\n cause: error,\n request: context.request,\n });\n }\n if (error instanceof TypeError) {\n return new OllamaNetworkError(error.message || 'Network request failed', {\n cause: error,\n request: context.request,\n });\n }\n if (context.response?.status !== undefined) {\n const message = error instanceof Error ? error.message : String(error);\n return statusToError(context.response.status, message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n }\n const message = error instanceof Error ? error.message : String(error);\n return new OllamaGenericClientError(message, {\n cause: error,\n request: context.request,\n response: context.response,\n });\n}\n","/**\n * Lightweight frontmatter parser for SKILL.md files.\n */\n\nimport { OllamaSkillInvalidError } from '../errors.js';\nimport type { SkillFrontmatter } from './types.js';\n\nexport interface ParsedFrontmatter {\n readonly frontmatter: SkillFrontmatter;\n readonly body: string;\n}\n\nfunction parseYamlValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') return true;\n if (trimmed === 'false') return false;\n if (!Number.isNaN(Number(trimmed)) && trimmed !== '') return Number(trimmed);\n if (\n (trimmed.startsWith('\"') && trimmed.endsWith('\"')) ||\n (trimmed.startsWith(\"'\") && trimmed.endsWith(\"'\"))\n ) {\n return trimmed.slice(1, -1);\n }\n return trimmed;\n}\n\nfunction parseYamlBlock(yamlText: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n const lines = yamlText.split('\\n');\n let currentKey: string | undefined;\n let currentList: unknown[] | undefined;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n if (trimmed.startsWith('- ') && currentKey) {\n if (!currentList) {\n currentList = [];\n result[currentKey] = currentList;\n }\n currentList.push(parseYamlValue(trimmed.slice(2)));\n continue;\n }\n\n currentList = undefined;\n const colonIndex = line.indexOf(':');\n if (colonIndex > 0) {\n const key = line.slice(0, colonIndex).trim();\n const valStr = line.slice(colonIndex + 1).trim();\n currentKey = key;\n if (valStr.length > 0) {\n result[key] = parseYamlValue(valStr);\n }\n }\n }\n\n return result;\n}\n\nexport function parseFrontmatter(source: string, path = ''): ParsedFrontmatter {\n const match = source.match(/^---\\r?\\n([\\s\\S]*?)\\r?\\n---\\r?\\n?([\\s\\S]*)$/);\n if (!match) {\n throw new OllamaSkillInvalidError('Missing YAML frontmatter delimiters (---)', {\n skillName: path || 'unknown',\n path,\n });\n }\n\n const rawYaml = match[1] ?? '';\n const body = match[2]?.trim() ?? '';\n const parsed = parseYamlBlock(rawYaml);\n\n if (!parsed['name'] || typeof parsed['name'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"name\"', {\n skillName: String(parsed['name'] ?? 'unknown'),\n path,\n });\n }\n if (!parsed['description'] || typeof parsed['description'] !== 'string') {\n throw new OllamaSkillInvalidError('Frontmatter missing required string \"description\"', {\n skillName: parsed['name'],\n path,\n });\n }\n\n return {\n frontmatter: parsed as unknown as SkillFrontmatter,\n body,\n };\n}\n","/**\n * Skill composition and context injection.\n */\n\nimport type { Message } from '../types.js';\nimport type { ToolRegistry } from '../tools/registry.js';\nimport type { Skill } from './types.js';\n\nexport interface ApplySkillOptions {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\nexport interface AppliedSkillResult {\n readonly messages: readonly Message[];\n readonly tools?: ToolRegistry;\n}\n\n/**\n * Injects a skill's body into messages as a system prompt and applies allowed tool filters.\n */\nexport function applySkill(skill: Skill, options: ApplySkillOptions): AppliedSkillResult {\n const systemPrompt = `[Skill: ${skill.name}]\\n${skill.description}\\n\\n${skill.body}`;\n const messages = [...options.messages];\n const systemIndex = messages.findIndex((m) => m.role === 'system');\n\n if (systemIndex >= 0) {\n const existing = messages[systemIndex];\n if (existing) {\n messages[systemIndex] = {\n role: 'system',\n content: `${existing.content}\\n\\n${systemPrompt}`,\n };\n }\n } else {\n messages.unshift({ role: 'system', content: systemPrompt });\n }\n\n return {\n messages,\n ...(options.tools !== undefined ? { tools: options.tools } : {}),\n };\n}\n","/**\n * Node.js filesystem skill registry for SKILL.md packages.\n */\n\nimport { readdir, readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { OllamaSkillNotFoundError } from '../errors.js';\nimport { parseFrontmatter } from './frontmatter.js';\nimport type { Skill, SkillSummary } from './types.js';\n\nexport interface SkillRegistryOptions {\n readonly directory: string;\n}\n\nexport class SkillRegistry {\n readonly directory: string;\n\n constructor(options: SkillRegistryOptions) {\n this.directory = options.directory;\n }\n\n async list(): Promise<SkillSummary[]> {\n const entries = await readdir(this.directory, { withFileTypes: true });\n const summaries: SkillSummary[] = [];\n\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const skillPath = join(this.directory, entry.name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n summaries.push({\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n });\n } catch {\n // Skip directories without valid SKILL.md\n }\n }\n\n return summaries;\n }\n\n async load(name: string): Promise<Skill> {\n const skillPath = join(this.directory, name, 'SKILL.md');\n try {\n const content = await readFile(skillPath, 'utf-8');\n const parsed = parseFrontmatter(content, skillPath);\n return {\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n frontmatter: parsed.frontmatter,\n body: parsed.body,\n allowedTools: parsed.frontmatter['allowed-tools'],\n };\n } catch (err) {\n throw new OllamaSkillNotFoundError(`Skill \"${name}\" not found at ${skillPath}`, {\n skillName: name,\n cause: err,\n });\n }\n }\n}\n"]}
@@ -199,6 +199,20 @@ interface RequestCancellationOptions {
199
199
  readonly signal?: AbortSignal | undefined;
200
200
  readonly timeoutMs?: number | undefined;
201
201
  }
202
+ /**
203
+ * Result of {@link OllamaClient.ping} — the ultra-lightweight `HEAD /` root
204
+ * liveness probe Ollama's documentation defines for load-balancer health checks.
205
+ * `healthy: false` carries a human-readable `error` (connection refused, timeout,
206
+ * …); the probe resolves instead of throwing so monitoring loops can treat it as
207
+ * a datapoint rather than an exception path.
208
+ */
209
+ interface PingResult {
210
+ readonly healthy: boolean;
211
+ readonly latencyMs: number;
212
+ /** Base URL of the concrete endpoint that was probed. */
213
+ readonly baseUrl: string;
214
+ readonly error?: string | undefined;
215
+ }
202
216
  interface ChatRequestOptions extends RequestCancellationOptions {
203
217
  readonly model: string;
204
218
  readonly messages: readonly Message[];
@@ -503,4 +517,4 @@ type UsageScope = 'self' | 'team';
503
517
  */
504
518
  type BalanceRequestOptions = RequestCancellationOptions;
505
519
 
506
- export { type ToolCallFunction as A, type BalanceRequestOptions as B, type CreateRequestOptions as C, type DeleteRequestOptions as D, type EmbedRequestOptions as E, type FormatOption as F, type GenerateRequestOptions as G, type ToolFunctionDefinition as H, type ToolProperty as I, type UsageRange as J, type UsageScope as K, type ListResponse as L, type ModelResponse as M, type WebSearchResult as N, imageStringNeedsResolution as O, type PullRequestOptions as P, resolveImageInput as Q, type RequestCancellationOptions as R, type ShowRequestOptions as S, type ThinkingMetadata as T, type UsageRequestOptions as U, type VersionResponse as V, type WebSearchRequestOptions as W, type ShowResponse as a, type ProgressResponse as b, type PushRequestOptions as c, type StatusResponse as d, type CopyRequestOptions as e, type PsResponse as f, type ToolParameters as g, type ThinkValue as h, type ToolCall as i, type ChatRequestOptions as j, type ModelOptions as k, type ToolDefinition as l, type ChatResponse as m, type Message as n, type GenerateResponse as o, type EmbedResponse as p, type EmbeddingsRequestOptions as q, type EmbeddingsResponse as r, type WebSearchResponse as s, type WebFetchRequestOptions as t, type WebFetchResponse as u, type VisionInput as v, type Logprob as w, type LogprobToken as x, type ModelDetails as y, type Role as z };
520
+ export { type Role as A, type BalanceRequestOptions as B, type CreateRequestOptions as C, type DeleteRequestOptions as D, type EmbedRequestOptions as E, type FormatOption as F, type GenerateRequestOptions as G, type ToolCallFunction as H, type ToolFunctionDefinition as I, type ToolProperty as J, type UsageRange as K, type ListResponse as L, type ModelResponse as M, type UsageScope as N, type WebSearchResult as O, type PullRequestOptions as P, imageStringNeedsResolution as Q, type RequestCancellationOptions as R, type ShowRequestOptions as S, type ThinkingMetadata as T, type UsageRequestOptions as U, type VersionResponse as V, type WebSearchRequestOptions as W, resolveImageInput as X, type ShowResponse as a, type ProgressResponse as b, type PushRequestOptions as c, type StatusResponse as d, type CopyRequestOptions as e, type PsResponse as f, type ToolParameters as g, type ThinkValue as h, type ToolCall as i, type ChatRequestOptions as j, type ModelOptions as k, type ToolDefinition as l, type ChatResponse as m, type Message as n, type GenerateResponse as o, type EmbedResponse as p, type EmbeddingsRequestOptions as q, type EmbeddingsResponse as r, type WebSearchResponse as s, type WebFetchRequestOptions as t, type WebFetchResponse as u, type PingResult as v, type VisionInput as w, type Logprob as x, type LogprobToken as y, type ModelDetails as z };
@@ -199,6 +199,20 @@ interface RequestCancellationOptions {
199
199
  readonly signal?: AbortSignal | undefined;
200
200
  readonly timeoutMs?: number | undefined;
201
201
  }
202
+ /**
203
+ * Result of {@link OllamaClient.ping} — the ultra-lightweight `HEAD /` root
204
+ * liveness probe Ollama's documentation defines for load-balancer health checks.
205
+ * `healthy: false` carries a human-readable `error` (connection refused, timeout,
206
+ * …); the probe resolves instead of throwing so monitoring loops can treat it as
207
+ * a datapoint rather than an exception path.
208
+ */
209
+ interface PingResult {
210
+ readonly healthy: boolean;
211
+ readonly latencyMs: number;
212
+ /** Base URL of the concrete endpoint that was probed. */
213
+ readonly baseUrl: string;
214
+ readonly error?: string | undefined;
215
+ }
202
216
  interface ChatRequestOptions extends RequestCancellationOptions {
203
217
  readonly model: string;
204
218
  readonly messages: readonly Message[];
@@ -503,4 +517,4 @@ type UsageScope = 'self' | 'team';
503
517
  */
504
518
  type BalanceRequestOptions = RequestCancellationOptions;
505
519
 
506
- export { type ToolCallFunction as A, type BalanceRequestOptions as B, type CreateRequestOptions as C, type DeleteRequestOptions as D, type EmbedRequestOptions as E, type FormatOption as F, type GenerateRequestOptions as G, type ToolFunctionDefinition as H, type ToolProperty as I, type UsageRange as J, type UsageScope as K, type ListResponse as L, type ModelResponse as M, type WebSearchResult as N, imageStringNeedsResolution as O, type PullRequestOptions as P, resolveImageInput as Q, type RequestCancellationOptions as R, type ShowRequestOptions as S, type ThinkingMetadata as T, type UsageRequestOptions as U, type VersionResponse as V, type WebSearchRequestOptions as W, type ShowResponse as a, type ProgressResponse as b, type PushRequestOptions as c, type StatusResponse as d, type CopyRequestOptions as e, type PsResponse as f, type ToolParameters as g, type ThinkValue as h, type ToolCall as i, type ChatRequestOptions as j, type ModelOptions as k, type ToolDefinition as l, type ChatResponse as m, type Message as n, type GenerateResponse as o, type EmbedResponse as p, type EmbeddingsRequestOptions as q, type EmbeddingsResponse as r, type WebSearchResponse as s, type WebFetchRequestOptions as t, type WebFetchResponse as u, type VisionInput as v, type Logprob as w, type LogprobToken as x, type ModelDetails as y, type Role as z };
520
+ export { type Role as A, type BalanceRequestOptions as B, type CreateRequestOptions as C, type DeleteRequestOptions as D, type EmbedRequestOptions as E, type FormatOption as F, type GenerateRequestOptions as G, type ToolCallFunction as H, type ToolFunctionDefinition as I, type ToolProperty as J, type UsageRange as K, type ListResponse as L, type ModelResponse as M, type UsageScope as N, type WebSearchResult as O, type PullRequestOptions as P, imageStringNeedsResolution as Q, type RequestCancellationOptions as R, type ShowRequestOptions as S, type ThinkingMetadata as T, type UsageRequestOptions as U, type VersionResponse as V, type WebSearchRequestOptions as W, resolveImageInput as X, type ShowResponse as a, type ProgressResponse as b, type PushRequestOptions as c, type StatusResponse as d, type CopyRequestOptions as e, type PsResponse as f, type ToolParameters as g, type ThinkValue as h, type ToolCall as i, type ChatRequestOptions as j, type ModelOptions as k, type ToolDefinition as l, type ChatResponse as m, type Message as n, type GenerateResponse as o, type EmbedResponse as p, type EmbeddingsRequestOptions as q, type EmbeddingsResponse as r, type WebSearchResponse as s, type WebFetchRequestOptions as t, type WebFetchResponse as u, type PingResult as v, type VisionInput as w, type Logprob as x, type LogprobToken as y, type ModelDetails as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nemesis-oss/ollama-sdk",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "description": "Production-grade TypeScript SDK for Ollama with native fetch, high availability failover, multi-turn tool calling, structured outputs, reasoning stream tokens, OpenAI/Anthropic bridges, MCP, Web Stream adapters, and a contract-first hybrid architecture that generates TypeScript types, API classes, MCP tools, and Zod schemas from a single canonical IR.",
5
5
  "keywords": [
6
6
  "ollama",