@ultrst-armada/kloks 1.24.5 → 1.24.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.krusbl-release-attestation.json +3 -3
  2. package/README.md +11 -0
  3. package/package.json +15 -12
  4. package/packages/audio-midi/dist/index.js +16 -16
  5. package/packages/backend/dist/ai-inference/index.js +0 -1
  6. package/packages/backend/dist/ai-keys/index.js +0 -1
  7. package/packages/backend/dist/ai-models/index.js +0 -1
  8. package/packages/backend/dist/ai-provider/index.js +0 -1
  9. package/packages/backend/dist/ai-routing/index.js +0 -1
  10. package/packages/backend/dist/ai-tools/index.js +0 -1
  11. package/packages/backend/dist/api/index.js +0 -1
  12. package/packages/backend/dist/auth/index.d.ts +5 -74
  13. package/packages/backend/dist/auth/index.js +16 -19
  14. package/packages/backend/dist/{chunk-2OPIDIIB.js → chunk-3VWBZEMG.js} +26 -2
  15. package/packages/backend/dist/{chunk-AHJ2EWQW.js → chunk-6D55GT3L.js} +9 -28
  16. package/packages/backend/dist/chunk-ED32WV3T.js +75 -0
  17. package/packages/backend/dist/chunk-EO5VUYYU.js +20 -0
  18. package/packages/backend/dist/{chunk-B3VJ4HDV.js → chunk-JOTDEFRG.js} +1 -1
  19. package/packages/backend/dist/{chunk-OB65KZ2M.js → chunk-M45KQRPR.js} +1 -1
  20. package/packages/backend/dist/chunk-SXDYW3QA.js +579 -0
  21. package/packages/backend/dist/client/index.js +0 -1
  22. package/packages/backend/dist/connectivity/index.js +0 -1
  23. package/packages/backend/dist/control-plane/index.d.ts +3 -3
  24. package/packages/backend/dist/control-plane/index.js +0 -1
  25. package/packages/backend/dist/development/client.d.ts +20 -6
  26. package/packages/backend/dist/development/client.js +42 -28
  27. package/packages/backend/dist/development/index.d.ts +20 -6
  28. package/packages/backend/dist/development/index.js +43 -32
  29. package/packages/backend/dist/development/playwrightInspectionService.js +2 -3
  30. package/packages/backend/dist/development/playwrightInspectionTypes.d.ts +1 -0
  31. package/packages/backend/dist/index.d.ts +3 -54
  32. package/packages/backend/dist/index.js +44 -127
  33. package/packages/backend/dist/krnl-ai-services.js +2 -3
  34. package/packages/backend/dist/krnl-services.js +6 -7
  35. package/packages/backend/dist/services/index.js +4 -5
  36. package/packages/backend/dist/srkl/index.js +1 -2
  37. package/packages/backend/dist/storage/index.js +0 -1
  38. package/packages/backend/dist/workspace/index.js +0 -1
  39. package/packages/backend/package.json +3 -10
  40. package/packages/client/dist/index.d.ts +2 -0
  41. package/packages/client/dist/index.js +29 -1
  42. package/packages/client/package.json +2 -1
  43. package/packages/fod/dist/index.d.ts +11 -1
  44. package/packages/fod/dist/index.js +2 -0
  45. package/packages/fod/package.json +2 -3
  46. package/packages/functions/dist/index.js +16 -16
  47. package/packages/functions/package.json +2 -1
  48. package/packages/services/dist/index.d.ts +46 -1
  49. package/packages/services/dist/index.js +96 -18
  50. package/packages/services/kloks.manifest.json +19 -0
  51. package/packages/state-graph/dist/index.js +31 -31
  52. package/packages/backend/dist/BaseAccountProvider-DduKf5HG.d.ts +0 -66
  53. package/packages/backend/dist/chunk-2HCQ2SIR.js +0 -213
  54. package/packages/backend/dist/chunk-A3BE6ROS.js +0 -180
  55. package/packages/backend/dist/chunk-MWSYNRNZ.js +0 -871
  56. package/packages/backend/dist/chunk-QGM4M3NI.js +0 -37
  57. package/packages/backend/dist/dist-XMSSRYDR.js +0 -899
  58. package/packages/backend/dist/transformers.node-HWHOAE4H.js +0 -43879
  59. package/packages/backend/dist/{chunk-IGZB4RYT.js → chunk-R6ZNF6FW.js} +3 -3
@@ -1,871 +0,0 @@
1
- // ../../node_modules/.pnpm/@ultrst-armada+krnl@1.0.9_@types+node@22.20.5/node_modules/@ultrst-armada/krnl/packages/core/dist/index.js
2
- import { randomUUID } from "crypto";
3
-
4
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/define-api.js
5
- function defineApi(definition) {
6
- const properties = Object.fromEntries(definition.parameters.map((parameter) => [
7
- parameter.name,
8
- {
9
- ...parameter.schema,
10
- description: parameter.description
11
- }
12
- ]));
13
- return Object.freeze({
14
- ...definition,
15
- inputSchema: {
16
- type: "object",
17
- description: `Arguments for ${definition.name}.`,
18
- properties,
19
- required: definition.parameters.filter((parameter) => parameter.required).map((parameter) => parameter.name),
20
- additionalProperties: false
21
- }
22
- });
23
- }
24
-
25
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/array-apis.js
26
- var array = { type: "array" };
27
- var integer = { type: "integer" };
28
- var arrayApis = [
29
- defineApi({ id: "gutts.arrays.compact", name: "compact", category: "arrays", description: "Removes null and undefined values from an array while preserving the remaining values and their order.", parameters: [{ name: "values", description: "The array whose nullish elements should be removed.", required: true, schema: array }], output: { type: "array", description: "The array without null or undefined elements." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
30
- defineApi({ id: "gutts.arrays.unique", name: "unique", category: "arrays", description: "Removes duplicate values from an array while preserving the first occurrence of each value.", parameters: [{ name: "values", description: "The array from which duplicate values should be removed.", required: true, schema: array }], output: { type: "array", description: "The array containing only the first occurrence of each value." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
31
- defineApi({ id: "gutts.arrays.chunk", name: "chunk", category: "arrays", description: "Splits an array into consecutive subarrays of the requested maximum size.", parameters: [{ name: "values", description: "The array to split into chunks.", required: true, schema: array }, { name: "size", description: "The positive integer maximum number of elements in each chunk.", required: true, schema: integer }], output: { type: "array", items: array, description: "An array of consecutive subarrays." }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws RangeError when size is not a positive integer."] }),
32
- defineApi({ id: "gutts.arrays.flatten", name: "flatten", category: "arrays", description: "Flattens one level of nested arrays into a single array.", parameters: [{ name: "values", description: "The array containing values or one-level nested arrays.", required: true, schema: array }], output: { type: "array", description: "The flattened array." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
33
- defineApi({ id: "gutts.arrays.last", name: "last", category: "arrays", description: "Returns the final element of an array, or undefined when the array is empty.", parameters: [{ name: "values", description: "The array whose final element should be returned.", required: true, schema: array }], output: { description: "The final array element, or undefined for an empty array." }, semantics: { deterministic: true, pure: true, sideEffects: false } })
34
- ];
35
-
36
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/json-apis.js
37
- var json = { type: "object", description: "A JSON-compatible value." };
38
- var jsonApis = [
39
- defineApi({ id: "gutts.json.isJsonValue", name: "isJsonValue", category: "json", description: "Checks whether an unknown value can be represented as a finite JSON value.", parameters: [{ name: "value", description: "The value to validate as JSON-compatible data.", required: true, schema: {} }], output: { type: "boolean", description: "True when the value is a valid JSON value." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
40
- defineApi({ id: "gutts.json.parseJson", name: "parseJson", category: "json", description: "Parses a JSON text string into a JSON-compatible value.", parameters: [{ name: "text", description: "The JSON document to parse.", required: true, schema: { type: "string" } }], output: json, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws SyntaxError when text is not valid JSON."] }),
41
- defineApi({ id: "gutts.json.tryParseJson", name: "tryParseJson", category: "json", description: "Attempts to parse JSON text and returns undefined instead of throwing when parsing fails.", parameters: [{ name: "text", description: "The JSON document to parse.", required: true, schema: { type: "string" } }], output: { description: "The parsed JSON value, or undefined when parsing fails." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
42
- defineApi({ id: "gutts.json.stringifyJson", name: "stringifyJson", category: "json", description: "Serializes a JSON-compatible value into JSON text, optionally using indentation.", parameters: [{ name: "value", description: "The JSON-compatible value to serialize.", required: true, schema: {} }, { name: "space", description: "Optional number of indentation spaces to use in the serialized output.", required: false, schema: { type: "number" } }], output: { type: "string", description: "The serialized JSON text." }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws TypeError when the value cannot be serialized as JSON."] })
43
- ];
44
-
45
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/number-apis.js
46
- var numberApis = [
47
- defineApi({ id: "gutts.numbers.clamp", name: "clamp", category: "numbers", description: "Restricts a numeric value to an inclusive minimum and maximum range.", parameters: [{ name: "value", description: "The numeric value to constrain.", required: true, schema: { type: "number" } }, { name: "min", description: "The inclusive lower bound.", required: true, schema: { type: "number" } }, { name: "max", description: "The inclusive upper bound.", required: true, schema: { type: "number" } }], output: { type: "number", description: "The value constrained to the inclusive range." }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws RangeError when min exceeds max."] }),
48
- defineApi({ id: "gutts.numbers.inRange", name: "inRange", category: "numbers", description: "Checks whether a numeric value falls within the configured range.", parameters: [{ name: "value", description: "The numeric value to test.", required: true, schema: { type: "number" } }, { name: "min", description: "The lower range boundary.", required: true, schema: { type: "number" } }, { name: "max", description: "The upper range boundary.", required: true, schema: { type: "number" } }], output: { type: "boolean", description: "Whether the value is inside the range." }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws RangeError when min exceeds max."] }),
49
- defineApi({ id: "gutts.numbers.roundTo", name: "roundTo", category: "numbers", description: "Rounds a number to a specified non-negative number of decimal places.", parameters: [{ name: "value", description: "The number to round.", required: true, schema: { type: "number" } }, { name: "decimals", description: "The non-negative integer number of decimal places.", required: false, schema: { type: "integer" } }], output: { type: "number", description: "The rounded number." }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws RangeError when decimals is negative or not an integer."] }),
50
- defineApi({ id: "gutts.numbers.isFiniteNumber", name: "isFiniteNumber", category: "numbers", description: "Checks whether a value is a JavaScript number and is finite.", parameters: [{ name: "value", description: "The value to test.", required: true, schema: {} }], output: { type: "boolean", description: "True only for finite JavaScript numbers." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
51
- defineApi({ id: "gutts.numbers.sum", name: "sum", category: "numbers", description: "Adds all numbers in an array and returns their total.", parameters: [{ name: "values", description: "The numeric values to add.", required: true, schema: { type: "array", items: { type: "number" } } }], output: { type: "number", description: "The sum of all input numbers." }, semantics: { deterministic: true, pure: true, sideEffects: false } })
52
- ];
53
-
54
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/object-apis.js
55
- var objectApis = [
56
- defineApi({ id: "gutts.objects.hasOwn", name: "hasOwn", category: "objects", description: "Checks whether an object contains a requested property.", parameters: [{ name: "value", description: "The object to inspect.", required: true, schema: { type: "object" } }, { name: "key", description: "The property key to look for.", required: true, schema: { type: "string" } }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
57
- defineApi({ id: "gutts.objects.pick", name: "pick", category: "objects", description: "Creates an object containing only requested properties.", parameters: [{ name: "value", description: "The source object.", required: true, schema: { type: "object" } }, { name: "keys", description: "The property keys to retain.", required: true, schema: { type: "array", items: { type: "string" } } }], output: { type: "object" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
58
- defineApi({ id: "gutts.objects.omit", name: "omit", category: "objects", description: "Creates an object without requested properties.", parameters: [{ name: "value", description: "The source object.", required: true, schema: { type: "object" } }, { name: "keys", description: "The property keys to remove.", required: true, schema: { type: "array", items: { type: "string" } } }], output: { type: "object" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
59
- defineApi({ id: "gutts.objects.isPlainObject", name: "isPlainObject", category: "objects", description: "Checks whether a value is a plain JavaScript object.", parameters: [{ name: "value", description: "The value to classify.", required: true, schema: {} }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } })
60
- ];
61
-
62
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/string-apis.js
63
- var string = { type: "string" };
64
- var stringApis = [
65
- defineApi({ id: "gutts.strings.isBlank", name: "isBlank", category: "strings", description: "Checks whether a string contains no non-whitespace characters.", parameters: [{ name: "value", description: "The string to inspect.", required: true, schema: string }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
66
- defineApi({ id: "gutts.strings.isNonBlank", name: "isNonBlank", category: "strings", description: "Checks whether a string contains at least one non-whitespace character.", parameters: [{ name: "value", description: "The string to inspect.", required: true, schema: string }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
67
- defineApi({ id: "gutts.strings.isEmail", name: "isEmail", category: "strings", description: "Checks whether a string conforms to the email-address validation rules used by GutTS.", parameters: [{ name: "value", description: "The string to validate as an email address.", required: true, schema: string }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
68
- defineApi({ id: "gutts.strings.startsWithAny", name: "startsWithAny", category: "strings", description: "Checks whether a string starts with at least one supplied prefix.", parameters: [{ name: "value", description: "The string to inspect.", required: true, schema: string }, { name: "prefixes", description: "The prefixes to test.", required: true, schema: { type: "array", items: string } }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
69
- defineApi({ id: "gutts.strings.endsWithAny", name: "endsWithAny", category: "strings", description: "Checks whether a string ends with at least one supplied suffix.", parameters: [{ name: "value", description: "The string to inspect.", required: true, schema: string }, { name: "suffixes", description: "The suffixes to test.", required: true, schema: { type: "array", items: string } }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
70
- defineApi({ id: "gutts.strings.capitalize", name: "capitalize", category: "strings", description: "Capitalizes a string using the library's existing capitalization behavior.", parameters: [{ name: "value", description: "The string to capitalize.", required: true, schema: string }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
71
- defineApi({ id: "gutts.strings.camelCase", name: "camelCase", category: "strings", description: "Converts a string into lower camel case.", parameters: [{ name: "value", description: "The string to convert.", required: true, schema: string }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
72
- defineApi({ id: "gutts.strings.kebabCase", name: "kebabCase", category: "strings", description: "Converts a string into lower kebab case.", parameters: [{ name: "value", description: "The string to convert.", required: true, schema: string }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
73
- defineApi({ id: "gutts.strings.snakeCase", name: "snakeCase", category: "strings", description: "Converts a string into lower snake case.", parameters: [{ name: "value", description: "The string to convert.", required: true, schema: string }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
74
- defineApi({ id: "gutts.strings.truncate", name: "truncate", category: "strings", description: "Shortens a string to a maximum length and appends a suffix when truncation is required.", parameters: [{ name: "value", description: "The string to shorten.", required: true, schema: string }, { name: "maxLength", description: "The non-negative maximum output length.", required: true, schema: { type: "number" } }, { name: "suffix", description: "The suffix used when truncation occurs.", required: false, schema: string }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws RangeError when maxLength is negative."] }),
75
- defineApi({ id: "gutts.strings.truncateWords", name: "truncateWords", category: "strings", description: "Shortens a string to a maximum number of words and appends a suffix when truncation is required.", parameters: [{ name: "value", description: "The string to shorten.", required: true, schema: string }, { name: "maxWords", description: "The non-negative maximum number of words.", required: true, schema: { type: "number" } }, { name: "suffix", description: "The suffix used when truncation occurs.", required: false, schema: string }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws RangeError when maxWords is negative."] })
76
- ];
77
-
78
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/url-apis.js
79
- var string2 = { type: "string" };
80
- var urlApis = [
81
- defineApi({ id: "gutts.urls.isUrl", name: "isUrl", category: "urls", description: "Checks whether a string can be parsed as a URL by the standard URL constructor.", parameters: [{ name: "value", description: "The string to validate.", required: true, schema: string2 }], output: { type: "boolean" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
82
- defineApi({ id: "gutts.urls.joinUrl", name: "joinUrl", category: "urls", description: "Joins a base URL-like string and path segments using single separators.", parameters: [{ name: "base", description: "The base URL or path.", required: true, schema: string2 }, { name: "parts", description: "The path segments to append.", required: true, schema: { type: "array", items: string2 } }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
83
- defineApi({ id: "gutts.urls.getQueryParam", name: "getQueryParam", category: "urls", description: "Reads one query-string parameter from a URL.", parameters: [{ name: "url", description: "The URL to inspect.", required: true, schema: string2 }, { name: "key", description: "The query parameter name.", required: true, schema: string2 }], output: { type: "string", description: "The value, or null when absent." }, semantics: { deterministic: true, pure: true, sideEffects: false } }),
84
- defineApi({ id: "gutts.urls.setQueryParam", name: "setQueryParam", category: "urls", description: "Returns a URL with one query-string parameter set to the supplied value.", parameters: [{ name: "url", description: "The URL to modify.", required: true, schema: string2 }, { name: "key", description: "The query parameter name.", required: true, schema: string2 }, { name: "value", description: "The query parameter value.", required: true, schema: string2 }], output: { type: "string" }, semantics: { deterministic: true, pure: true, sideEffects: false }, errors: ["Throws when url cannot be parsed as a URL."] })
85
- ];
86
-
87
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/needle3/index.js
88
- var needle3Metadata = {
89
- id: "model.cactus-needle3",
90
- name: "Needle 3",
91
- provider: "Cactus Compute",
92
- version: "3",
93
- description: "Tiny structured inference model for tool selection, argument extraction, classification, and embeddings.",
94
- examples: ["select a tool", "extract fields", "classify an intent"],
95
- avoidWhen: "Avoid for open-ended long-form generation or complex multi-step reasoning.",
96
- whenToUse: "Use when natural language must be mapped to a small tool set or structured schema.",
97
- size: { min: 8, max: 29, unit: "MB", qualifier: "range" },
98
- capabilities: ["tool-selection", "argument-extraction", "classification", "structured-output", "embeddings"],
99
- input: "Natural-language text with optional tools or extraction schema",
100
- output: "Structured JSON or embedding vector",
101
- runtime: "Cactus Needle runtime adapter",
102
- modelUri: "Cactus-Compute/needle3"
103
- };
104
- var needle3CompleteApi = defineApi({
105
- id: "model.cactus-needle3.complete",
106
- name: "Needle3.complete",
107
- category: "models",
108
- description: "Select tools or extract structured data from natural-language input.",
109
- parameters: [
110
- { name: "prompt", description: "Natural-language input.", required: true, schema: { type: "string" } },
111
- { name: "tools", description: "Optional tool definitions.", required: false, schema: { type: "array" } },
112
- { name: "schema", description: "Optional extraction schema.", required: false, schema: { type: "object" } }
113
- ],
114
- output: { type: "object", description: "Structured model result." },
115
- semantics: { deterministic: false, pure: false, sideEffects: false }
116
- });
117
-
118
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/runtimes/ettin-head.js
119
- import fs from "fs";
120
- import path from "path";
121
- import os from "os";
122
-
123
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/smollm2/index.js
124
- var smolLM2Metadata = {
125
- id: "model.smollm2-135m-instruct",
126
- name: "SmolLM2-135M-Instruct",
127
- provider: "Hugging Face",
128
- version: "135M",
129
- description: "Compact instruction-tuned language model for general text generation.",
130
- examples: ["summarize text", "rewrite text", "draft a short response"],
131
- avoidWhen: "Avoid for high-stakes reasoning, broad factual knowledge, or tasks requiring large context.",
132
- whenToUse: "Use for short general-purpose text generation when a local model is preferred.",
133
- size: { value: 105, unit: "MB", qualifier: "artifact" },
134
- capabilities: ["text-generation", "instruction-following"],
135
- input: "Natural-language prompt",
136
- output: "Generated natural-language text",
137
- runtime: "ModelRuntime adapter",
138
- modelUri: "HuggingFaceTB/SmolLM2-135M-Instruct",
139
- license: "Apache-2.0"
140
- };
141
- var smolLM2GenerateApi = defineApi({
142
- id: "model.smollm2-135m-instruct.generate",
143
- name: "SmolLM2-135M-Instruct.generate",
144
- category: "models",
145
- description: "Generate natural-language text with SmolLM2-135M-Instruct.",
146
- parameters: [
147
- { name: "prompt", description: "Prompt supplied to the model.", required: true, schema: { type: "string" } },
148
- { name: "maxNewTokens", description: "Maximum number of new tokens.", required: false, schema: { type: "number" } }
149
- ],
150
- output: { type: "string", description: "Generated natural-language text." },
151
- semantics: { deterministic: false, pure: false, sideEffects: false },
152
- errors: ["Model load failure", "Inference failure"]
153
- });
154
-
155
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/whistle/index.js
156
- var whistleMetadata = {
157
- id: "model.cactus-whistle",
158
- name: "Whistle",
159
- provider: "Cactus Compute",
160
- version: "1",
161
- description: "Compact CPU speech-recognition model for on-device transcription.",
162
- examples: ["transcribe a voice note", "transcribe a command"],
163
- avoidWhen: "Avoid when audio understanding beyond transcription is required.",
164
- whenToUse: "Use for local speech-to-text when low resource use and privacy matter.",
165
- size: { value: 16.9, unit: "MB", qualifier: "artifact" },
166
- capabilities: ["speech-to-text", "on-device", "cpu"],
167
- input: "Audio bytes",
168
- output: "Transcribed natural-language text",
169
- runtime: "Cactus Needle runtime adapter",
170
- modelUri: "Cactus-Compute/whistle"
171
- };
172
- var whistleTranscribeApi = defineApi({
173
- id: "model.cactus-whistle.transcribe",
174
- name: "Whistle.transcribe",
175
- category: "models",
176
- description: "Transcribe speech audio into natural-language text.",
177
- parameters: [
178
- { name: "audio", description: "Audio bytes supplied to the speech model.", required: true, schema: { type: "string" } },
179
- { name: "language", description: "Optional language identifier.", required: false, schema: { type: "string" } }
180
- ],
181
- output: { type: "string", description: "Transcribed text." },
182
- semantics: { deterministic: true, pure: false, sideEffects: false }
183
- });
184
-
185
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/ettin/index.js
186
- var defineEttin = (id2, name, parameters, description) => ({
187
- id: id2,
188
- name,
189
- provider: "Hugging Face",
190
- version: String(parameters),
191
- description,
192
- examples: ["rank search results", "order retrieved documents by relevance"],
193
- whenToUse: "Use for cross-encoder reranking when candidate texts must be sorted by semantic relevance.",
194
- avoidWhen: "Avoid for text generation, embeddings, or transcription.",
195
- size: { value: parameters * 1e6, unit: "parameters", qualifier: "parameters" },
196
- capabilities: ["reranking", "relevance-scoring"],
197
- input: "Query and candidate texts",
198
- output: "Candidate relevance scores",
199
- runtime: "ModelRuntime adapter",
200
- modelUri: `cross-encoder/ettin-reranker-${parameters}m-v1`,
201
- license: "Apache-2.0"
202
- });
203
- var ettinReranker17MMetadata = defineEttin("model.ettin-reranker-17m", "Ettin-Reranker-17M", 17, "Very small relevance model for ranking candidate text.");
204
- var ettinReranker32MMetadata = defineEttin("model.ettin-reranker-32m", "Ettin-Reranker-32M", 32, "Small relevance model for ranking candidate text.");
205
- var ettinReranker68MMetadata = defineEttin("model.ettin-reranker-68m", "Ettin-Reranker-68M", 68, "Compact relevance model for higher-quality candidate ranking.");
206
- var ettinReranker150MMetadata = defineEttin("model.ettin-reranker-150m", "Ettin-Reranker-150M", 150, "Larger compact relevance model for candidate ranking.");
207
- var ettinRerankApi = defineApi({
208
- id: "model.ettin-reranker.rerank",
209
- name: "EttinReranker.rerank",
210
- category: "models",
211
- description: "Rank candidate texts by relevance to a query.",
212
- parameters: [
213
- { name: "query", description: "Query text.", required: true, schema: { type: "string" } },
214
- { name: "candidates", description: "Candidate texts to rank.", required: true, schema: { type: "array", items: { type: "string" } } }
215
- ],
216
- output: { type: "array", description: "Relevance scores in candidate order.", items: { type: "number" } },
217
- semantics: { deterministic: true, pure: false, sideEffects: false }
218
- });
219
-
220
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/minilm/index.js
221
- var miniLML6Metadata = {
222
- id: "model.minilm-l6-v2",
223
- name: "MiniLM-L6-v2",
224
- provider: "Sentence Transformers",
225
- version: "L6-v2",
226
- description: "Compact sentence embedding model for semantic similarity.",
227
- examples: ["compare two texts", "match a query to a short description"],
228
- avoidWhen: "Avoid when generation, extraction, or tool calling is required.",
229
- whenToUse: "Use for lightweight semantic similarity and embedding-based matching.",
230
- size: { value: 227e5, unit: "parameters", qualifier: "parameters" },
231
- capabilities: ["embeddings", "semantic-similarity"],
232
- input: "Two text strings",
233
- output: "Similarity score",
234
- runtime: "ModelRuntime adapter",
235
- modelUri: "sentence-transformers/all-MiniLM-L6-v2",
236
- license: "Apache-2.0"
237
- };
238
- var miniLMSimilarityApi = defineApi({
239
- id: "model.minilm-l6-v2.similarity",
240
- name: "MiniLM-L6-v2.similarity",
241
- category: "models",
242
- description: "Compute semantic similarity between two texts.",
243
- parameters: [
244
- { name: "left", description: "First text.", required: true, schema: { type: "string" } },
245
- { name: "right", description: "Second text.", required: true, schema: { type: "string" } }
246
- ],
247
- output: { type: "number", description: "Semantic similarity score." },
248
- semantics: { deterministic: true, pure: false, sideEffects: false }
249
- });
250
-
251
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/api-registry.js
252
- var guttsApiDefinitions = Object.freeze([
253
- ...arrayApis,
254
- ...jsonApis,
255
- ...numberApis,
256
- ...objectApis,
257
- ...stringApis,
258
- ...urlApis,
259
- smolLM2GenerateApi,
260
- needle3CompleteApi,
261
- whistleTranscribeApi,
262
- ettinRerankApi,
263
- miniLMSimilarityApi
264
- ]);
265
- var guttsApiById = Object.freeze(Object.fromEntries(guttsApiDefinitions.map((api) => [api.id, api])));
266
-
267
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/api/fod-node-provider.js
268
- var schemaType = (schema) => String(schema?.type ?? "any");
269
- function guttsApiToFodNode(api) {
270
- return {
271
- type: `gutts/${api.id}`,
272
- label: api.name,
273
- description: api.description,
274
- category: "gutts",
275
- group: api.category,
276
- inputs: api.parameters.map((parameter) => ({ id: parameter.name, name: parameter.name, direction: "input", dataType: schemaType(parameter.schema), required: parameter.required, description: parameter.description, schema: parameter.schema })),
277
- outputs: [{ id: "result", name: "result", direction: "output", dataType: schemaType(api.output), ...api.output.description ? { description: api.output.description } : {}, schema: api.output }],
278
- metadata: { apiId: api.id, package: "@dinilmusick/gutts", semantics: api.semantics }
279
- };
280
- }
281
- var guttsFodNodeDefinitions = Object.freeze(guttsApiDefinitions.map(guttsApiToFodNode));
282
-
283
- // ../../node_modules/.pnpm/@dinilmusick+gutts@1.1.0_@types+node@22.20.5/node_modules/@dinilmusick/gutts/dist/models/model-registry.js
284
- var guttsModelDefinitions = Object.freeze([
285
- smolLM2Metadata,
286
- needle3Metadata,
287
- whistleMetadata,
288
- ettinReranker17MMetadata,
289
- ettinReranker32MMetadata,
290
- ettinReranker68MMetadata,
291
- ettinReranker150MMetadata,
292
- miniLML6Metadata
293
- ]);
294
- var guttsModelById = Object.freeze(Object.fromEntries(guttsModelDefinitions.map((model) => [model.id, model])));
295
-
296
- // ../../node_modules/.pnpm/@ultrst-armada+krnl@1.0.9_@types+node@22.20.5/node_modules/@ultrst-armada/krnl/packages/core/dist/index.js
297
- var ServiceStateStore = class {
298
- state;
299
- listeners = /* @__PURE__ */ new Set();
300
- constructor(initialState) {
301
- this.state = { ...initialState };
302
- }
303
- getState() {
304
- return Object.freeze({ ...this.state });
305
- }
306
- setState(mutation) {
307
- this.state = { ...this.state, ...mutation };
308
- const snapshot = this.getState();
309
- for (const listener of this.listeners) {
310
- listener(snapshot, mutation);
311
- }
312
- }
313
- subscribe(listener) {
314
- this.listeners.add(listener);
315
- return () => {
316
- this.listeners.delete(listener);
317
- };
318
- }
319
- reset(newState) {
320
- this.state = { ...newState || {} };
321
- }
322
- };
323
- var TRANSITIONS = {
324
- uninitialized: ["initializing"],
325
- initializing: ["ready", "uninitialized"],
326
- ready: ["starting"],
327
- starting: ["running", "ready"],
328
- running: ["stopping"],
329
- stopping: ["stopped", "running"],
330
- stopped: ["starting"]
331
- };
332
- var LifecycleManager = class {
333
- status = "uninitialized";
334
- getStatus() {
335
- return this.status;
336
- }
337
- canTransitionTo(next) {
338
- return TRANSITIONS[this.status].includes(next);
339
- }
340
- transitionTo(next) {
341
- if (!this.canTransitionTo(next)) {
342
- throw new Error("[Lifecycle] Invalid transition '" + this.status + "' -> '" + next + "'.");
343
- }
344
- this.status = next;
345
- }
346
- setStatus(next) {
347
- this.transitionTo(next);
348
- }
349
- assertRunning(serviceName) {
350
- if (this.status !== "running") {
351
- throw new Error(
352
- "[Service:" + serviceName + "] Cannot invoke operation while status is '" + this.status + "' (expected 'running')."
353
- );
354
- }
355
- }
356
- };
357
- var runtimeProcess = typeof globalThis !== "undefined" ? globalThis.process : void 0;
358
- var runtimePerformance = typeof globalThis !== "undefined" ? globalThis.performance : void 0;
359
- function telemetryNow() {
360
- return runtimePerformance?.now ? runtimePerformance.now() : Date.now();
361
- }
362
- function sampleResources() {
363
- const memory = runtimeProcess?.memoryUsage?.();
364
- const cpu = runtimeProcess?.cpuUsage?.();
365
- const eventLoop = runtimePerformance?.eventLoopUtilization?.();
366
- return {
367
- cpuUserMicros: cpu?.user,
368
- cpuSystemMicros: cpu?.system,
369
- heapUsedBytes: memory?.heapUsed,
370
- heapTotalBytes: memory?.heapTotal,
371
- rssBytes: memory?.rss,
372
- externalBytes: memory?.external,
373
- arrayBuffersBytes: memory?.arrayBuffers,
374
- eventLoopUtilization: eventLoop?.utilization,
375
- scope: memory || cpu || eventLoop ? "process" : "runtime"
376
- };
377
- }
378
- function deltaResources(start, end) {
379
- const delta = (a, b) => a === void 0 || b === void 0 ? void 0 : b - a;
380
- return {
381
- cpuUserMicros: delta(start.cpuUserMicros, end.cpuUserMicros),
382
- cpuSystemMicros: delta(start.cpuSystemMicros, end.cpuSystemMicros),
383
- heapUsedBytes: delta(start.heapUsedBytes, end.heapUsedBytes),
384
- heapTotalBytes: delta(start.heapTotalBytes, end.heapTotalBytes),
385
- rssBytes: delta(start.rssBytes, end.rssBytes),
386
- externalBytes: delta(start.externalBytes, end.externalBytes),
387
- arrayBuffersBytes: delta(start.arrayBuffersBytes, end.arrayBuffersBytes),
388
- eventLoopUtilization: delta(start.eventLoopUtilization, end.eventLoopUtilization),
389
- scope: start.scope
390
- };
391
- }
392
- var id = (prefix) => `${prefix}_${randomUUID()}`;
393
- function percentiles(values) {
394
- if (!values.length) return { min: 0, mean: 0, p50: 0, p90: 0, p95: 0, p99: 0, max: 0 };
395
- const sorted = [...values].sort((a, b) => a - b);
396
- const pick2 = (p) => sorted[Math.min(sorted.length - 1, Math.floor((sorted.length - 1) * p))];
397
- return {
398
- min: sorted[0],
399
- mean: sorted.reduce((sum2, value) => sum2 + value, 0) / sorted.length,
400
- p50: pick2(0.5),
401
- p90: pick2(0.9),
402
- p95: pick2(0.95),
403
- p99: pick2(0.99),
404
- max: sorted[sorted.length - 1]
405
- };
406
- }
407
- var TelemetryController = class {
408
- constructor(serviceId, options = {}) {
409
- this.serviceId = serviceId;
410
- this.mode = options.mode ?? "off";
411
- this.maxSamples = Math.max(1, options.maxSamples ?? 2048);
412
- this.maxRecentInvocations = Math.max(1, options.maxRecentInvocations ?? 100);
413
- }
414
- serviceId;
415
- mode;
416
- maxSamples;
417
- maxRecentInvocations;
418
- samples = [];
419
- active = /* @__PURE__ */ new Map();
420
- totalInvocationCount = 0;
421
- totalSuccessCount = 0;
422
- totalErrorCount = 0;
423
- lastInvocationAt;
424
- enable(mode = "standard") {
425
- this.mode = mode;
426
- }
427
- disable() {
428
- this.mode = "off";
429
- this.active.clear();
430
- }
431
- setMode(mode) {
432
- this.mode = mode;
433
- if (mode === "off") this.active.clear();
434
- }
435
- getMode() {
436
- return this.mode;
437
- }
438
- status() {
439
- return {
440
- enabled: this.mode !== "off",
441
- mode: this.mode,
442
- serviceId: this.serviceId,
443
- invocationCount: this.totalInvocationCount,
444
- activeInvocations: this.active.size,
445
- lastInvocationAt: this.lastInvocationAt
446
- };
447
- }
448
- begin(target, kind, correlationId, parentSpanId) {
449
- if (this.mode === "off") {
450
- return {
451
- invocationId: "",
452
- traceId: "",
453
- spanId: "",
454
- parentSpanId,
455
- end: () => void 0
456
- };
457
- }
458
- const invocationId = id("inv");
459
- const spanId = id("span");
460
- const traceId = parentSpanId ? this.findTraceId(parentSpanId) ?? id("trace") : id("trace");
461
- const active = {
462
- invocationId,
463
- traceId,
464
- spanId,
465
- parentSpanId,
466
- serviceId: this.serviceId,
467
- target,
468
- kind,
469
- correlationId,
470
- startedAt: telemetryNow(),
471
- resourcesStart: this.mode === "standard" ? void 0 : sampleResources()
472
- };
473
- this.active.set(invocationId, active);
474
- return {
475
- invocationId,
476
- traceId,
477
- spanId,
478
- parentSpanId,
479
- end: (error) => this.finish(active, error)
480
- };
481
- }
482
- reset() {
483
- this.samples.length = 0;
484
- this.active.clear();
485
- this.totalInvocationCount = 0;
486
- this.totalSuccessCount = 0;
487
- this.totalErrorCount = 0;
488
- this.lastInvocationAt = void 0;
489
- }
490
- snapshot() {
491
- const invocations = this.samples.slice();
492
- const durations = invocations.map((item) => item.durationMs);
493
- const targetMap = /* @__PURE__ */ new Map();
494
- for (const invocation of invocations) {
495
- const key = `${invocation.kind}:${invocation.target}`;
496
- const group = targetMap.get(key) ?? [];
497
- group.push(invocation);
498
- targetMap.set(key, group);
499
- }
500
- const targets = [...targetMap.values()].map((group) => ({
501
- target: group[0].target,
502
- kind: group[0].kind,
503
- count: group.length,
504
- successCount: group.filter((item) => item.status === "completed").length,
505
- errorCount: group.filter((item) => item.status === "failed").length,
506
- durationMs: percentiles(group.map((item) => item.durationMs)),
507
- lastInvocationAt: group[group.length - 1]?.completedAt
508
- }));
509
- return {
510
- serviceId: this.serviceId,
511
- mode: this.mode,
512
- capturedAt: Date.now(),
513
- status: this.status(),
514
- totals: {
515
- invocationCount: this.totalInvocationCount,
516
- successCount: this.totalSuccessCount,
517
- errorCount: this.totalErrorCount,
518
- durationMs: percentiles(durations)
519
- },
520
- targets,
521
- activeInvocations: this.active.size,
522
- recentInvocations: invocations.slice(-this.maxRecentInvocations)
523
- };
524
- }
525
- functionality(name) {
526
- return this.snapshot().targets.find((target) => target.kind === "functionality" && target.target === name);
527
- }
528
- functionalities() {
529
- return this.snapshot().targets.filter((target) => target.kind === "functionality");
530
- }
531
- findTraceId(parentSpanId) {
532
- for (let index = this.samples.length - 1; index >= 0; index -= 1) {
533
- if (this.samples[index].spanId === parentSpanId) return this.samples[index].traceId;
534
- }
535
- for (const active of this.active.values()) {
536
- if (active.spanId === parentSpanId) return active.traceId;
537
- }
538
- return void 0;
539
- }
540
- finish(active, error) {
541
- if (!this.active.delete(active.invocationId)) return;
542
- const completedAt = telemetryNow();
543
- const resourcesEnd = this.mode === "standard" ? void 0 : sampleResources();
544
- const invocation = {
545
- invocationId: active.invocationId,
546
- traceId: active.traceId,
547
- spanId: active.spanId,
548
- parentSpanId: active.parentSpanId,
549
- serviceId: active.serviceId,
550
- target: active.target,
551
- kind: active.kind,
552
- correlationId: active.correlationId,
553
- startedAt: active.startedAt,
554
- completedAt,
555
- durationMs: Math.max(0, completedAt - active.startedAt),
556
- status: error === void 0 ? "completed" : "failed",
557
- error: error === void 0 ? void 0 : {
558
- name: error instanceof Error ? error.name : "Error",
559
- message: error instanceof Error ? error.message : String(error)
560
- },
561
- resources: active.resourcesStart && resourcesEnd ? { start: active.resourcesStart, end: resourcesEnd, delta: deltaResources(active.resourcesStart, resourcesEnd) } : void 0
562
- };
563
- this.samples.push(invocation);
564
- this.totalInvocationCount += 1;
565
- if (invocation.status === "completed") this.totalSuccessCount += 1;
566
- else this.totalErrorCount += 1;
567
- if (this.samples.length > this.maxSamples) this.samples.splice(0, this.samples.length - this.maxSamples);
568
- this.lastInvocationAt = Date.now();
569
- }
570
- };
571
- var ServiceInstance = class {
572
- constructor(definition) {
573
- this.definition = definition;
574
- this.id = definition.id;
575
- this.name = definition.name;
576
- this.version = definition.version;
577
- this.telemetry = new TelemetryController(this.id);
578
- this.lifecycle = new LifecycleManager();
579
- if (definition.state) {
580
- this.stateStore = new ServiceStateStore(definition.state.initial);
581
- }
582
- }
583
- definition;
584
- id;
585
- name;
586
- version;
587
- telemetry;
588
- stateStore;
589
- lifecycle;
590
- initialized = false;
591
- disposed = false;
592
- getDefinition() {
593
- return this.definition;
594
- }
595
- getStatus() {
596
- return this.lifecycle.getStatus();
597
- }
598
- async start() {
599
- if (this.disposed) throw new Error("[Service:" + this.name + "] Cannot start a disposed service.");
600
- const current = this.lifecycle.getStatus();
601
- if (current === "running") return;
602
- if (current === "initializing" || current === "starting" || current === "stopping") {
603
- throw new Error("[Service:" + this.name + "] Cannot start while status is '" + current + "'.");
604
- }
605
- if (!this.initialized) {
606
- this.lifecycle.transitionTo("initializing");
607
- try {
608
- await this.definition.lifecycle?.onInit?.();
609
- this.initialized = true;
610
- this.lifecycle.transitionTo("ready");
611
- } catch (error) {
612
- this.lifecycle.transitionTo("uninitialized");
613
- throw error;
614
- }
615
- }
616
- this.lifecycle.transitionTo("starting");
617
- try {
618
- await this.definition.lifecycle?.onStart?.();
619
- this.lifecycle.transitionTo("running");
620
- } catch (error) {
621
- this.lifecycle.transitionTo("ready");
622
- throw error;
623
- }
624
- }
625
- async stop() {
626
- const current = this.lifecycle.getStatus();
627
- if (current === "stopped") return;
628
- if (current !== "running") {
629
- throw new Error("[Service:" + this.name + "] Cannot stop while status is '" + current + "'.");
630
- }
631
- this.lifecycle.transitionTo("stopping");
632
- try {
633
- await this.definition.lifecycle?.onStop?.();
634
- this.lifecycle.transitionTo("stopped");
635
- } catch (error) {
636
- this.lifecycle.transitionTo("running");
637
- throw error;
638
- }
639
- }
640
- async dispose() {
641
- if (this.disposed) return;
642
- if (this.lifecycle.getStatus() === "running") await this.stop();
643
- await this.definition.lifecycle?.onDispose?.();
644
- this.disposed = true;
645
- }
646
- async call(op, input, ctx = {}) {
647
- this.lifecycle.assertRunning(this.name);
648
- const operation = this.definition.operations[op];
649
- if (!operation) {
650
- throw new Error("[Service:" + this.name + "] Operation '" + op + "' not found.");
651
- }
652
- if (ctx.metadata?.__krnlTelemetryInternal === true) {
653
- return await operation.handler(input, ctx);
654
- }
655
- const parentSpanId = typeof ctx.metadata?.__krnlTelemetryParentSpanId === "string" ? ctx.metadata.__krnlTelemetryParentSpanId : void 0;
656
- const handle = this.telemetry.begin(op, "service", ctx.correlationId, parentSpanId);
657
- try {
658
- const output = await operation.handler(input, ctx);
659
- handle.end();
660
- return output;
661
- } catch (error) {
662
- handle.end(error);
663
- throw error;
664
- }
665
- }
666
- getState() {
667
- return this.stateStore?.getState() ?? Object.freeze({});
668
- }
669
- setState(mutation) {
670
- if (!this.stateStore) {
671
- this.stateStore = new ServiceStateStore({ ...mutation });
672
- return;
673
- }
674
- this.stateStore.setState(mutation);
675
- }
676
- };
677
- var ServiceProxy = class {
678
- constructor(definition, adapter, endpoint) {
679
- this.definition = definition;
680
- this.adapter = adapter;
681
- this.endpoint = endpoint;
682
- if (!definition) {
683
- throw new Error("[ServiceProxy] Missing service definition.");
684
- }
685
- if (!adapter || typeof adapter.send !== "function") {
686
- throw new Error("[ServiceProxy:" + (definition.name || "unknown") + "] Missing or invalid protocol adapter.");
687
- }
688
- if (!endpoint || typeof endpoint.address !== "string" || endpoint.address.length === 0) {
689
- throw new Error("[ServiceProxy:" + (definition.name || "unknown") + "] Missing or invalid endpoint descriptor.");
690
- }
691
- this.id = definition.id;
692
- this.name = definition.name;
693
- this.version = definition.version;
694
- this.telemetry = new TelemetryController(this.id);
695
- this.stateCache = { ...definition.state?.initial ?? {} };
696
- }
697
- definition;
698
- adapter;
699
- endpoint;
700
- id;
701
- name;
702
- version;
703
- telemetry;
704
- stateCache;
705
- eventHandlers = /* @__PURE__ */ new Map();
706
- lifecycle = new LifecycleManager();
707
- disposed = false;
708
- getDefinition() {
709
- return this.definition;
710
- }
711
- getStatus() {
712
- return this.lifecycle.getStatus();
713
- }
714
- async start() {
715
- if (this.disposed) {
716
- throw new Error("[ServiceProxy:" + this.name + "] Cannot start a disposed service proxy.");
717
- }
718
- const status = this.lifecycle.getStatus();
719
- if (status === "running") return;
720
- if (status === "stopping" || status === "starting" || status === "initializing") {
721
- throw new Error("[ServiceProxy:" + this.name + "] Cannot start while status is '" + status + "'.");
722
- }
723
- if (status === "uninitialized") {
724
- this.lifecycle.transitionTo("initializing");
725
- this.lifecycle.transitionTo("ready");
726
- }
727
- this.lifecycle.transitionTo("starting");
728
- this.lifecycle.transitionTo("running");
729
- }
730
- async stop() {
731
- const status = this.lifecycle.getStatus();
732
- if (status === "stopped") return;
733
- if (status !== "running") {
734
- throw new Error("[ServiceProxy:" + this.name + "] Cannot stop while status is '" + status + "'.");
735
- }
736
- this.lifecycle.transitionTo("stopping");
737
- this.lifecycle.transitionTo("stopped");
738
- }
739
- async dispose() {
740
- if (this.disposed) return;
741
- if (this.lifecycle.getStatus() === "running") await this.stop();
742
- this.disposed = true;
743
- }
744
- async call(op, input, ctx = {}) {
745
- if (!this.definition.operations[op]) {
746
- throw new Error("[ServiceProxy:" + this.name + "] Operation '" + op + "' not found.");
747
- }
748
- if (this.lifecycle.getStatus() !== "running") {
749
- await this.start();
750
- }
751
- if (!this.adapter.send) {
752
- throw new Error("[ServiceProxy:" + this.name + "] Adapter does not support send().");
753
- }
754
- const envelope = {
755
- id: "req-" + Date.now() + "-" + Math.random().toString(36).slice(2, 7),
756
- type: "request",
757
- operation: op,
758
- payload: input,
759
- timestamp: Date.now()
760
- };
761
- const parentSpanId = typeof ctx.metadata?.__krnlTelemetryParentSpanId === "string" ? ctx.metadata.__krnlTelemetryParentSpanId : void 0;
762
- const handle = this.telemetry.begin(op, "service", ctx.correlationId, parentSpanId);
763
- try {
764
- const response = await this.adapter.send(this.endpoint, envelope);
765
- if (response.error) {
766
- const error = new Error("[ServiceProxy:" + this.name + "] Remote error: " + response.error);
767
- handle.end(error);
768
- throw error;
769
- }
770
- handle.end();
771
- return response.payload;
772
- } catch (error) {
773
- handle.end(error);
774
- throw error;
775
- }
776
- }
777
- getState() {
778
- return Object.freeze({ ...this.stateCache });
779
- }
780
- setState(mutation) {
781
- this.stateCache = { ...this.stateCache, ...mutation };
782
- }
783
- on(event, handler) {
784
- if (!this.eventHandlers.has(event)) this.eventHandlers.set(event, /* @__PURE__ */ new Set());
785
- const handlers = this.eventHandlers.get(event);
786
- handlers.add(handler);
787
- return () => handlers.delete(handler);
788
- }
789
- emit(event, payload) {
790
- const handlers = this.eventHandlers.get(event);
791
- if (!handlers) return;
792
- for (const handler of Array.from(handlers)) {
793
- try {
794
- handler(payload);
795
- } catch (error) {
796
- console.error("[ServiceProxy:" + this.name + "] Event handler error for '" + event + "':", error);
797
- }
798
- }
799
- }
800
- };
801
- function assertRecord(value, field) {
802
- if (!value || typeof value !== "object" || Array.isArray(value)) {
803
- throw new Error("[KrnlTS] Invalid service definition: '" + field + "' must be an object.");
804
- }
805
- }
806
- function assertNonEmptyString(value, field) {
807
- if (typeof value !== "string" || value.trim().length === 0) {
808
- throw new Error("[KrnlTS] Invalid service definition: '" + field + "' must be a non-empty string.");
809
- }
810
- }
811
- function validateServiceDefinition(definition) {
812
- if (!definition || typeof definition !== "object") {
813
- throw new Error("[KrnlTS] Invalid service definition: expected an object.");
814
- }
815
- assertNonEmptyString(definition.id, "id");
816
- assertNonEmptyString(definition.name, "name");
817
- assertNonEmptyString(definition.version, "version");
818
- if (!definition.operations || typeof definition.operations !== "object") {
819
- throw new Error("[Service:" + definition.name + "] Invalid operations: expected an object.");
820
- }
821
- for (const [key, operation] of Object.entries(definition.operations)) {
822
- if (!operation || typeof operation !== "object") {
823
- throw new Error("[Service:" + definition.name + "] Invalid operation '" + key + "'.");
824
- }
825
- assertNonEmptyString(operation.id, "operations." + key + ".id");
826
- assertNonEmptyString(operation.name, "operations." + key + ".name");
827
- if (operation.inputSchema !== void 0) assertRecord(operation.inputSchema, "operations." + key + ".inputSchema");
828
- if (operation.outputSchema !== void 0) assertRecord(operation.outputSchema, "operations." + key + ".outputSchema");
829
- if (typeof operation.handler !== "function") {
830
- throw new Error("[Service:" + definition.name + "] Operation '" + key + "' must define a handler.");
831
- }
832
- }
833
- for (const [key, schema] of Object.entries(definition.inputs ?? {})) assertRecord(schema, "inputs." + key);
834
- for (const [key, schema] of Object.entries(definition.outputs ?? {})) assertRecord(schema, "outputs." + key);
835
- if (definition.state?.schema !== void 0) assertRecord(definition.state.schema, "state.schema");
836
- for (const capability of definition.capabilities ?? []) {
837
- assertNonEmptyString(capability.id, "capability.id");
838
- assertNonEmptyString(capability.name, "capability.name");
839
- if (!Array.isArray(capability.protocols)) {
840
- throw new Error("[Service:" + definition.name + "] Capability '" + capability.name + "' protocols must be an array.");
841
- }
842
- }
843
- for (const dependency of definition.dependencies ?? []) {
844
- assertNonEmptyString(dependency.serviceId, "dependency.serviceId");
845
- }
846
- return definition;
847
- }
848
- function createServiceDefinition(definition) {
849
- return validateServiceDefinition(definition);
850
- }
851
- function createService(definition) {
852
- return new ServiceInstance(validateServiceDefinition(definition));
853
- }
854
- function createServiceProxy(definition, adapter, endpoint) {
855
- validateServiceDefinition(definition);
856
- if (!adapter || typeof adapter.send !== "function") {
857
- throw new Error("[ServiceProxy:" + definition.name + "] Adapter must implement send().");
858
- }
859
- if (!endpoint || typeof endpoint.address !== "string" || endpoint.address.length === 0) {
860
- throw new Error("[ServiceProxy:" + definition.name + "] Endpoint must have an address.");
861
- }
862
- return new ServiceProxy(definition, adapter, endpoint);
863
- }
864
- var asyncHooks = globalThis.process?.getBuiltinModule?.("node:async_hooks");
865
-
866
- export {
867
- TelemetryController,
868
- createServiceDefinition,
869
- createService,
870
- createServiceProxy
871
- };