buckyos 0.7.169 → 0.7.175

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 (233) hide show
  1. package/cli/core/app.ts +2 -0
  2. package/cli/core/argv.ts +45 -239
  3. package/cli/core/command.ts +3 -35
  4. package/cli/dist/cli.mjs +2151 -673
  5. package/cli/dist/cli.mjs.map +1 -1
  6. package/cli/modules/agent.ts +3 -1
  7. package/cli/modules/app.ts +13 -2
  8. package/cli/modules/pikg.ts +70 -1
  9. package/cli/modules/runtime.ts +497 -0
  10. package/cli/modules/skill.ts +583 -161
  11. package/cli/modules/skill_lint.ts +462 -0
  12. package/cli/version.ts +1 -1
  13. package/dist/account-7a7bde6f.mjs +105 -0
  14. package/dist/account-7a7bde6f.mjs.map +1 -0
  15. package/dist/account-b12ac6b9.js +2 -0
  16. package/dist/account-b12ac6b9.js.map +1 -0
  17. package/dist/aicc-67851c41.mjs +582 -0
  18. package/dist/aicc-67851c41.mjs.map +1 -0
  19. package/dist/aicc-ccb36ef7.js +2 -0
  20. package/dist/aicc-ccb36ef7.js.map +1 -0
  21. package/dist/app-frame.cjs +1 -1
  22. package/dist/app-frame.cjs.map +1 -1
  23. package/dist/app-frame.mjs +1 -0
  24. package/dist/app-frame.mjs.map +1 -1
  25. package/dist/browser.cjs +1 -1
  26. package/dist/browser.cjs.map +1 -1
  27. package/dist/browser.d.ts +3 -1
  28. package/dist/browser.d.ts.map +1 -1
  29. package/dist/browser.mjs +223 -212
  30. package/dist/browser.mjs.map +1 -1
  31. package/dist/content.cjs +1 -1
  32. package/dist/content.cjs.map +1 -1
  33. package/dist/content.d.ts +2 -1
  34. package/dist/content.d.ts.map +1 -1
  35. package/dist/content.mjs +32 -167
  36. package/dist/content.mjs.map +1 -1
  37. package/dist/content_mime-dc80d960.js +2 -0
  38. package/dist/content_mime-dc80d960.js.map +1 -0
  39. package/dist/content_mime-e42d5f8d.mjs +335 -0
  40. package/dist/content_mime-e42d5f8d.mjs.map +1 -0
  41. package/dist/content_mime.d.ts +18 -0
  42. package/dist/content_mime.d.ts.map +1 -1
  43. package/dist/did_object_client-6a1b108a.js +2 -0
  44. package/dist/did_object_client-6a1b108a.js.map +1 -0
  45. package/dist/did_object_client-7fa36f90.mjs +87 -0
  46. package/dist/did_object_client-7fa36f90.mjs.map +1 -0
  47. package/dist/did_object_client.d.ts +39 -0
  48. package/dist/did_object_client.d.ts.map +1 -0
  49. package/dist/{executor_client-a32bc377.mjs → executor_client-c620d25c.mjs} +1794 -844
  50. package/dist/executor_client-c620d25c.mjs.map +1 -0
  51. package/dist/executor_client-d4439d54.js +13 -0
  52. package/dist/executor_client-d4439d54.js.map +1 -0
  53. package/dist/executor_client.d.ts +129 -0
  54. package/dist/executor_client.d.ts.map +1 -1
  55. package/dist/file_meta.d.ts +26 -0
  56. package/dist/file_meta.d.ts.map +1 -0
  57. package/dist/index.cjs +1 -1
  58. package/dist/index.cjs.map +1 -1
  59. package/dist/index.d.ts +3 -1
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.mjs +228 -217
  62. package/dist/index.mjs.map +1 -1
  63. package/dist/internal/command_args.d.ts +67 -0
  64. package/dist/internal/command_args.d.ts.map +1 -0
  65. package/dist/krpc_client-26c2dc8b.js +2 -0
  66. package/dist/krpc_client-26c2dc8b.js.map +1 -0
  67. package/dist/krpc_client-673448e5.mjs +173 -0
  68. package/dist/krpc_client-673448e5.mjs.map +1 -0
  69. package/dist/krpc_client.d.ts +5 -1
  70. package/dist/krpc_client.d.ts.map +1 -1
  71. package/dist/msg_center_client.d.ts +2 -1
  72. package/dist/msg_center_client.d.ts.map +1 -1
  73. package/dist/namelib.d.ts.map +1 -1
  74. package/dist/ndm_client.d.ts +7 -0
  75. package/dist/ndm_client.d.ts.map +1 -1
  76. package/dist/ndn.d.ts +3 -0
  77. package/dist/ndn.d.ts.map +1 -0
  78. package/dist/{namelib-b41b10cc.mjs → ndn_types-0fac2499.mjs} +3096 -2816
  79. package/dist/ndn_types-0fac2499.mjs.map +1 -0
  80. package/dist/ndn_types-5b138882.js +2 -0
  81. package/dist/ndn_types-5b138882.js.map +1 -0
  82. package/dist/ndn_types.d.ts +268 -16
  83. package/dist/ndn_types.d.ts.map +1 -1
  84. package/dist/node.cjs +1 -1
  85. package/dist/node.cjs.map +1 -1
  86. package/dist/node.d.ts +1 -1
  87. package/dist/node.d.ts.map +1 -1
  88. package/dist/node.mjs +220 -212
  89. package/dist/node.mjs.map +1 -1
  90. package/dist/object_url-8fb5a7bf.js +2 -0
  91. package/dist/object_url-8fb5a7bf.js.map +1 -0
  92. package/dist/object_url-f72c1704.mjs +412 -0
  93. package/dist/object_url-f72c1704.mjs.map +1 -0
  94. package/dist/openai-ae2978de.mjs +163 -0
  95. package/dist/openai-ae2978de.mjs.map +1 -0
  96. package/dist/openai-f560d518.js +2 -0
  97. package/dist/openai-f560d518.js.map +1 -0
  98. package/dist/provision.cjs +6 -6
  99. package/dist/provision.cjs.map +1 -1
  100. package/dist/provision.d.ts +1 -2
  101. package/dist/provision.d.ts.map +1 -1
  102. package/dist/provision.mjs +4 -31
  103. package/dist/provision.mjs.map +1 -1
  104. package/dist/repo_client.d.ts +2 -1
  105. package/dist/repo_client.d.ts.map +1 -1
  106. package/dist/site_manager-11a7a468.mjs +6410 -0
  107. package/dist/site_manager-11a7a468.mjs.map +1 -0
  108. package/dist/site_manager-334b1a51.js +2 -0
  109. package/dist/site_manager-334b1a51.js.map +1 -0
  110. package/dist/{tus_client-4f7254e9.js → tus_client-809c90ab.js} +2 -2
  111. package/dist/{tus_client-4f7254e9.js.map → tus_client-809c90ab.js.map} +1 -1
  112. package/dist/{tus_client-04080b1e.mjs → tus_client-893a3287.mjs} +2 -2
  113. package/dist/{tus_client-04080b1e.mjs.map → tus_client-893a3287.mjs.map} +1 -1
  114. package/dist/xllm/core/action_parser.d.ts +15 -0
  115. package/dist/xllm/core/action_parser.d.ts.map +1 -0
  116. package/dist/xllm/core/behavior_loop.d.ts +20 -0
  117. package/dist/xllm/core/behavior_loop.d.ts.map +1 -0
  118. package/dist/xllm/core/behavior_result.d.ts +11 -0
  119. package/dist/xllm/core/behavior_result.d.ts.map +1 -0
  120. package/dist/xllm/core/config.d.ts +62 -0
  121. package/dist/xllm/core/config.d.ts.map +1 -0
  122. package/dist/xllm/core/context_window.d.ts +15 -0
  123. package/dist/xllm/core/context_window.d.ts.map +1 -0
  124. package/dist/xllm/core/deps.d.ts +97 -0
  125. package/dist/xllm/core/deps.d.ts.map +1 -0
  126. package/dist/xllm/core/errors.d.ts +94 -0
  127. package/dist/xllm/core/errors.d.ts.map +1 -0
  128. package/dist/xllm/core/interrupt.d.ts +31 -0
  129. package/dist/xllm/core/interrupt.d.ts.map +1 -0
  130. package/dist/xllm/core/json.d.ts +11 -0
  131. package/dist/xllm/core/json.d.ts.map +1 -0
  132. package/dist/xllm/core/json_check.d.ts +17 -0
  133. package/dist/xllm/core/json_check.d.ts.map +1 -0
  134. package/dist/xllm/core/loop.d.ts +135 -0
  135. package/dist/xllm/core/loop.d.ts.map +1 -0
  136. package/dist/xllm/core/messages.d.ts +18 -0
  137. package/dist/xllm/core/messages.d.ts.map +1 -0
  138. package/dist/xllm/core/observer.d.ts +14 -0
  139. package/dist/xllm/core/observer.d.ts.map +1 -0
  140. package/dist/xllm/core/open_runtime.d.ts +22 -0
  141. package/dist/xllm/core/open_runtime.d.ts.map +1 -0
  142. package/dist/xllm/core/prepare.d.ts +54 -0
  143. package/dist/xllm/core/prepare.d.ts.map +1 -0
  144. package/dist/xllm/core/prompt.d.ts +40 -0
  145. package/dist/xllm/core/prompt.d.ts.map +1 -0
  146. package/dist/xllm/core/protocol.d.ts +15 -0
  147. package/dist/xllm/core/protocol.d.ts.map +1 -0
  148. package/dist/xllm/core/result.d.ts +12 -0
  149. package/dist/xllm/core/result.d.ts.map +1 -0
  150. package/dist/xllm/core/run.d.ts +198 -0
  151. package/dist/xllm/core/run.d.ts.map +1 -0
  152. package/dist/xllm/core/rust_text.d.ts +20 -0
  153. package/dist/xllm/core/rust_text.d.ts.map +1 -0
  154. package/dist/xllm/core/site_policy.d.ts +5 -0
  155. package/dist/xllm/core/site_policy.d.ts.map +1 -0
  156. package/dist/xllm/core/store.d.ts +60 -0
  157. package/dist/xllm/core/store.d.ts.map +1 -0
  158. package/dist/xllm/core/suspension.d.ts +13 -0
  159. package/dist/xllm/core/suspension.d.ts.map +1 -0
  160. package/dist/xllm/core/tokenizer.d.ts +8 -0
  161. package/dist/xllm/core/tokenizer.d.ts.map +1 -0
  162. package/dist/xllm/core/types.d.ts +826 -0
  163. package/dist/xllm/core/types.d.ts.map +1 -0
  164. package/dist/xllm/core/xml.d.ts +19 -0
  165. package/dist/xllm/core/xml.d.ts.map +1 -0
  166. package/dist/xllm/dev/openai.d.ts +17 -0
  167. package/dist/xllm/dev/openai.d.ts.map +1 -0
  168. package/dist/xllm/dev/scripted.d.ts +46 -0
  169. package/dist/xllm/dev/scripted.d.ts.map +1 -0
  170. package/dist/xllm/dev.d.ts +5 -0
  171. package/dist/xllm/dev.d.ts.map +1 -0
  172. package/dist/xllm/hosts/browser/store.d.ts +41 -0
  173. package/dist/xllm/hosts/browser/store.d.ts.map +1 -0
  174. package/dist/xllm/hosts/deno/deno_api.d.ts +103 -0
  175. package/dist/xllm/hosts/deno/deno_api.d.ts.map +1 -0
  176. package/dist/xllm/hosts/deno/identity.d.ts +29 -0
  177. package/dist/xllm/hosts/deno/identity.d.ts.map +1 -0
  178. package/dist/xllm/hosts/deno/index.d.ts +47 -0
  179. package/dist/xllm/hosts/deno/index.d.ts.map +1 -0
  180. package/dist/xllm/hosts/deno/native_runtime.d.ts +93 -0
  181. package/dist/xllm/hosts/deno/native_runtime.d.ts.map +1 -0
  182. package/dist/xllm/hosts/deno/native_tools.d.ts +105 -0
  183. package/dist/xllm/hosts/deno/native_tools.d.ts.map +1 -0
  184. package/dist/xllm/hosts/deno/provider.d.ts +13 -0
  185. package/dist/xllm/hosts/deno/provider.d.ts.map +1 -0
  186. package/dist/xllm/hosts/deno/store.d.ts +60 -0
  187. package/dist/xllm/hosts/deno/store.d.ts.map +1 -0
  188. package/dist/xllm/index.d.ts +48 -0
  189. package/dist/xllm/index.d.ts.map +1 -0
  190. package/dist/xllm/providers/aicc.d.ts +22 -0
  191. package/dist/xllm/providers/aicc.d.ts.map +1 -0
  192. package/dist/xllm/providers/timeout.d.ts +12 -0
  193. package/dist/xllm/providers/timeout.d.ts.map +1 -0
  194. package/dist/xllm/runtime/compress.d.ts +149 -0
  195. package/dist/xllm/runtime/compress.d.ts.map +1 -0
  196. package/dist/xllm/runtime/did_object_resources.d.ts +21 -0
  197. package/dist/xllm/runtime/did_object_resources.d.ts.map +1 -0
  198. package/dist/xllm/runtime/hints.d.ts +23 -0
  199. package/dist/xllm/runtime/hints.d.ts.map +1 -0
  200. package/dist/xllm/runtime/site.d.ts +22 -0
  201. package/dist/xllm/runtime/site.d.ts.map +1 -0
  202. package/dist/xllm/runtime/site_manager.d.ts +38 -0
  203. package/dist/xllm/runtime/site_manager.d.ts.map +1 -0
  204. package/dist/xllm/runtime/site_tools.d.ts +76 -0
  205. package/dist/xllm/runtime/site_tools.d.ts.map +1 -0
  206. package/dist/xllm/runtime/step_renderer.d.ts +54 -0
  207. package/dist/xllm/runtime/step_renderer.d.ts.map +1 -0
  208. package/dist/xllm/runtime/task_model.d.ts +64 -0
  209. package/dist/xllm/runtime/task_model.d.ts.map +1 -0
  210. package/dist/xllm/runtime/tool_result.d.ts +39 -0
  211. package/dist/xllm/runtime/tool_result.d.ts.map +1 -0
  212. package/dist/xllm/runtime/types.d.ts +99 -0
  213. package/dist/xllm/runtime/types.d.ts.map +1 -0
  214. package/dist/xllm.cjs +2 -0
  215. package/dist/xllm.cjs.map +1 -0
  216. package/dist/xllm.mjs +1167 -0
  217. package/dist/xllm.mjs.map +1 -0
  218. package/dist/xllm_deno.cjs +2 -0
  219. package/dist/xllm_deno.cjs.map +1 -0
  220. package/dist/xllm_deno.mjs +2487 -0
  221. package/dist/xllm_deno.mjs.map +1 -0
  222. package/dist/xllm_dev.cjs +2 -0
  223. package/dist/xllm_dev.cjs.map +1 -0
  224. package/dist/xllm_dev.mjs +70 -0
  225. package/dist/xllm_dev.mjs.map +1 -0
  226. package/package.json +22 -1
  227. package/src/internal/command_args.ts +268 -0
  228. package/dist/executor_client-a32bc377.mjs.map +0 -1
  229. package/dist/executor_client-e026942b.js +0 -13
  230. package/dist/executor_client-e026942b.js.map +0 -1
  231. package/dist/namelib-b41b10cc.mjs.map +0 -1
  232. package/dist/namelib-f8ff0045.js +0 -2
  233. package/dist/namelib-f8ff0045.js.map +0 -1
@@ -0,0 +1,163 @@
1
+ import { u as textContent, w as toolCalls, j as anyJsonObjectSchema, L as LLMComputeException, p as providerError } from "./aicc-67851c41.mjs";
2
+ function openaiHttpFailure(status, body) {
3
+ var _a, _b;
4
+ let code;
5
+ try {
6
+ code = (_b = (_a = JSON.parse(body)) == null ? void 0 : _a.error) == null ? void 0 : _b.code;
7
+ } catch {
8
+ code = void 0;
9
+ }
10
+ if (code === "context_length_exceeded")
11
+ return "context_limit";
12
+ if (status === 401 || status === 403)
13
+ return { refused: { code: "credentials" } };
14
+ if ([400, 404, 422].includes(status))
15
+ return "permanent";
16
+ if ([408, 409, 425, 429, 500, 502, 503, 504].includes(status))
17
+ return "transient";
18
+ return "unknown";
19
+ }
20
+ function contentToOpenai(content) {
21
+ const parts = [];
22
+ for (const c of content) {
23
+ if (c.type === "text")
24
+ parts.push({ type: "text", text: c.text });
25
+ else if (c.type === "image") {
26
+ const s = c.source;
27
+ const url = s.kind === "url" ? s.url : s.kind === "base64" ? `data:${s.mime};base64,${s.data_base64}` : s.obj_id;
28
+ parts.push({ type: "image_url", image_url: { url } });
29
+ } else if (c.type === "document") {
30
+ const label = c.title ?? "document";
31
+ const desc = c.source.kind === "url" ? c.source.url : "(inline document omitted)";
32
+ parts.push({ type: "text", text: `[${label}: ${desc}]` });
33
+ }
34
+ }
35
+ const only = parts[0];
36
+ if (parts.length === 1 && (only == null ? void 0 : only.type) === "text")
37
+ return only.text;
38
+ return parts;
39
+ }
40
+ function messagesToOpenai(messages) {
41
+ const out = [];
42
+ for (const m of messages) {
43
+ if (m.role === "system" || m.role === "developer")
44
+ out.push({ role: "system", content: textContent(m) });
45
+ else if (m.role === "user")
46
+ out.push({ role: "user", content: contentToOpenai(m.content) });
47
+ else if (m.role === "assistant") {
48
+ const text = textContent(m);
49
+ const calls = toolCalls(m).map((c) => ({ id: c.call_id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args) } }));
50
+ const obj = { role: "assistant", content: text === "" ? null : text };
51
+ if (calls.length)
52
+ obj.tool_calls = calls;
53
+ out.push(obj);
54
+ } else {
55
+ for (const b of m.content) {
56
+ if (b.type === "tool_result") {
57
+ out.push({ role: "tool", tool_call_id: b.call_id, content: b.content.filter((c) => c.type === "text").map((c) => c.text).join("\n") });
58
+ }
59
+ }
60
+ }
61
+ }
62
+ return out;
63
+ }
64
+ function truncateChars(s, max) {
65
+ const chars = [...s];
66
+ return chars.length <= max ? s : chars.slice(0, max).join("") + "…";
67
+ }
68
+ class OpenAiLlmClient {
69
+ constructor(options) {
70
+ var _a, _b;
71
+ this.options = options;
72
+ this.baseUrl = (((_a = options.baseUrl) == null ? void 0 : _a.trim()) || "https://api.openai.com/v1").replace(/\/+$/, "");
73
+ if (!((_b = options.apiKey) == null ? void 0 : _b.trim()))
74
+ throw new Error("openai provider: no API key");
75
+ }
76
+ async infer(req) {
77
+ var _a, _b, _c;
78
+ const body = { model: req.model_alias, messages: messagesToOpenai(req.messages) };
79
+ if (req.temperature !== void 0)
80
+ body.temperature = req.temperature;
81
+ if (req.max_completion_tokens !== void 0)
82
+ body.max_tokens = req.max_completion_tokens;
83
+ if (req.allow_tool_calls && req.tool_specs.length) {
84
+ body.tools = req.tool_specs.map((s) => ({ type: "function", function: { name: s.name, description: s.description, parameters: s.args_schema } }));
85
+ body.tool_choice = "auto";
86
+ }
87
+ if (req.force_json)
88
+ body.response_format = { type: "json_schema", json_schema: { name: "xllm_result", schema: req.json_schema ?? anyJsonObjectSchema() } };
89
+ if (req.provider_options && typeof req.provider_options === "object" && !Array.isArray(req.provider_options)) {
90
+ Object.assign(body, req.provider_options);
91
+ }
92
+ const f = this.options.fetch ?? globalThis.fetch.bind(globalThis);
93
+ let response;
94
+ try {
95
+ response = await f(`${this.baseUrl}/chat/completions`, {
96
+ method: "POST",
97
+ headers: { "content-type": "application/json", authorization: `Bearer ${this.options.apiKey}`, ...this.options.headers ?? {} },
98
+ body: JSON.stringify(body),
99
+ signal: req.signal
100
+ });
101
+ } catch (e) {
102
+ if (req.signal.aborted)
103
+ throw new LLMComputeException({ kind: "cancelled" });
104
+ throw providerError("transient", `openai request failed: ${e instanceof Error ? e.message : String(e)}`);
105
+ }
106
+ let text;
107
+ try {
108
+ text = await response.text();
109
+ } catch (e) {
110
+ throw providerError("transient", `openai read body failed: ${e instanceof Error ? e.message : String(e)}`);
111
+ }
112
+ if (!response.ok)
113
+ throw providerError(openaiHttpFailure(response.status, text), `openai http ${response.status}: ${truncateChars(text, 512)}`);
114
+ let parsed;
115
+ try {
116
+ parsed = JSON.parse(text);
117
+ } catch (e) {
118
+ throw providerError("unknown", `openai invalid JSON: ${e instanceof Error ? e.message : String(e)}`);
119
+ }
120
+ const choice = (_a = parsed.choices) == null ? void 0 : _a[0];
121
+ if (!choice)
122
+ throw providerError("unknown", "openai response has no choices");
123
+ const message = choice.message ?? {};
124
+ const content = [];
125
+ if (typeof message.content === "string")
126
+ content.push({ type: "text", text: message.content });
127
+ for (const c of message.tool_calls ?? []) {
128
+ let args = {};
129
+ try {
130
+ const v = JSON.parse(((_b = c.function) == null ? void 0 : _b.arguments) ?? "{}");
131
+ if (v && typeof v === "object" && !Array.isArray(v))
132
+ args = v;
133
+ } catch {
134
+ args = {};
135
+ }
136
+ content.push({ type: "tool_use", call_id: c.id ?? "", name: ((_c = c.function) == null ? void 0 : _c.name) ?? "", args });
137
+ }
138
+ if (content.length === 0)
139
+ content.push({ type: "text", text: "" });
140
+ const out = { message: { role: "assistant", content } };
141
+ if (typeof choice.finish_reason === "string")
142
+ out.finish_reason = choice.finish_reason;
143
+ const u = parsed.usage;
144
+ if (u) {
145
+ out.usage = { request_units: 1 };
146
+ if (typeof u.prompt_tokens === "number")
147
+ out.usage.input_tokens = u.prompt_tokens;
148
+ if (typeof u.completion_tokens === "number")
149
+ out.usage.output_tokens = u.completion_tokens;
150
+ if (typeof u.total_tokens === "number")
151
+ out.usage.total_tokens = u.total_tokens;
152
+ }
153
+ if (typeof parsed.model === "string")
154
+ out.extra = { model: parsed.model };
155
+ return out;
156
+ }
157
+ }
158
+ export {
159
+ OpenAiLlmClient as O,
160
+ messagesToOpenai as m,
161
+ openaiHttpFailure as o
162
+ };
163
+ //# sourceMappingURL=openai-ae2978de.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-ae2978de.mjs","sources":["../src/xllm/dev/openai.ts"],"sourcesContent":["// OpenAI-compatible Chat Completions client (Rust `OpenAiLlmClient`), for\n// development and mocks. Only page code can inject it; configuration cannot\n// select it. CORS is the endpoint's business.\n\nimport type { AiContent, AiMessage, AiResponse, AiToolCall, JsonValue, LlmClient, LlmInferenceRequest, ProviderFailure } from '../core/types'\nimport { LLMComputeException, providerError } from '../core/errors'\nimport { textContent, toolCalls } from '../core/messages'\nimport { anyJsonObjectSchema } from '../providers/aicc'\n\n/** Failure class of a non-2xx response (Rust `openai_http_failure` after T2-0). */\nexport function openaiHttpFailure(status: number, body: string): ProviderFailure {\n let code: unknown\n try {\n code = (JSON.parse(body) as { error?: { code?: unknown } })?.error?.code\n } catch {\n code = undefined\n }\n if (code === 'context_length_exceeded') return 'context_limit'\n if (status === 401 || status === 403) return { refused: { code: 'credentials' } }\n if ([400, 404, 422].includes(status)) return 'permanent'\n if ([408, 409, 425, 429, 500, 502, 503, 504].includes(status)) return 'transient'\n return 'unknown'\n}\n\nfunction contentToOpenai(content: AiContent[]): JsonValue {\n const parts: JsonValue[] = []\n for (const c of content) {\n if (c.type === 'text') parts.push({ type: 'text', text: c.text })\n else if (c.type === 'image') {\n const s = c.source\n const url = s.kind === 'url' ? s.url : s.kind === 'base64' ? `data:${s.mime};base64,${s.data_base64}` : s.obj_id\n parts.push({ type: 'image_url', image_url: { url } })\n } else if (c.type === 'document') {\n const label = c.title ?? 'document'\n const desc = c.source.kind === 'url' ? c.source.url : '(inline document omitted)'\n parts.push({ type: 'text', text: `[${label}: ${desc}]` })\n }\n }\n const only = parts[0] as { type?: string; text?: string } | undefined\n if (parts.length === 1 && only?.type === 'text') return only.text as string\n return parts\n}\n\nexport function messagesToOpenai(messages: AiMessage[]): JsonValue[] {\n const out: JsonValue[] = []\n for (const m of messages) {\n if (m.role === 'system' || m.role === 'developer') out.push({ role: 'system', content: textContent(m) })\n else if (m.role === 'user') out.push({ role: 'user', content: contentToOpenai(m.content) })\n else if (m.role === 'assistant') {\n const text = textContent(m)\n const calls = toolCalls(m).map(c => ({ id: c.call_id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.args) } }))\n const obj: { [k: string]: JsonValue } = { role: 'assistant', content: text === '' ? null : text }\n if (calls.length) obj.tool_calls = calls\n out.push(obj)\n } else {\n for (const b of m.content) {\n if (b.type === 'tool_result') {\n out.push({ role: 'tool', tool_call_id: b.call_id, content: b.content.filter(c => c.type === 'text').map(c => (c as { text: string }).text).join('\\n') })\n }\n }\n }\n }\n return out\n}\n\nfunction truncateChars(s: string, max: number): string {\n const chars = [...s]\n return chars.length <= max ? s : chars.slice(0, max).join('') + '…'\n}\n\nexport interface OpenAiLlmOptions {\n baseUrl?: string\n apiKey: string\n headers?: Record<string, string>\n fetch?: typeof fetch\n}\n\nexport class OpenAiLlmClient implements LlmClient {\n private readonly baseUrl: string\n\n constructor(private readonly options: OpenAiLlmOptions) {\n this.baseUrl = (options.baseUrl?.trim() || 'https://api.openai.com/v1').replace(/\\/+$/, '')\n if (!options.apiKey?.trim()) throw new Error('openai provider: no API key')\n }\n\n async infer(req: LlmInferenceRequest): Promise<AiResponse> {\n const body: { [k: string]: JsonValue } = { model: req.model_alias, messages: messagesToOpenai(req.messages) }\n if (req.temperature !== undefined) body.temperature = req.temperature\n if (req.max_completion_tokens !== undefined) body.max_tokens = req.max_completion_tokens\n if (req.allow_tool_calls && req.tool_specs.length) {\n body.tools = req.tool_specs.map(s => ({ type: 'function', function: { name: s.name, description: s.description, parameters: s.args_schema } }))\n body.tool_choice = 'auto'\n }\n if (req.force_json) body.response_format = { type: 'json_schema', json_schema: { name: 'xllm_result', schema: req.json_schema ?? anyJsonObjectSchema() } }\n if (req.provider_options && typeof req.provider_options === 'object' && !Array.isArray(req.provider_options)) {\n Object.assign(body, req.provider_options)\n }\n const f = this.options.fetch ?? globalThis.fetch.bind(globalThis)\n let response: Response\n try {\n response = await f(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${this.options.apiKey}`, ...(this.options.headers ?? {}) },\n body: JSON.stringify(body),\n signal: req.signal,\n })\n } catch (e) {\n if (req.signal.aborted) throw new LLMComputeException({ kind: 'cancelled' })\n throw providerError('transient', `openai request failed: ${e instanceof Error ? e.message : String(e)}`)\n }\n let text: string\n try {\n text = await response.text()\n } catch (e) {\n throw providerError('transient', `openai read body failed: ${e instanceof Error ? e.message : String(e)}`)\n }\n if (!response.ok) throw providerError(openaiHttpFailure(response.status, text), `openai http ${response.status}: ${truncateChars(text, 512)}`)\n let parsed: { choices?: { message?: { content?: unknown; tool_calls?: unknown[] }; finish_reason?: unknown }[]; usage?: Record<string, unknown>; model?: unknown }\n try {\n parsed = JSON.parse(text)\n } catch (e) {\n throw providerError('unknown', `openai invalid JSON: ${e instanceof Error ? e.message : String(e)}`)\n }\n const choice = parsed.choices?.[0]\n if (!choice) throw providerError('unknown', 'openai response has no choices')\n const message = choice.message ?? {}\n const content: AiMessage['content'] = []\n if (typeof message.content === 'string') content.push({ type: 'text', text: message.content })\n for (const c of (message.tool_calls ?? []) as { id?: string; function?: { name?: string; arguments?: string } }[]) {\n let args: AiToolCall['args'] = {}\n try {\n const v = JSON.parse(c.function?.arguments ?? '{}')\n if (v && typeof v === 'object' && !Array.isArray(v)) args = v\n } catch {\n args = {}\n }\n content.push({ type: 'tool_use', call_id: c.id ?? '', name: c.function?.name ?? '', args })\n }\n if (content.length === 0) content.push({ type: 'text', text: '' })\n const out: AiResponse = { message: { role: 'assistant', content } }\n if (typeof choice.finish_reason === 'string') out.finish_reason = choice.finish_reason\n const u = parsed.usage\n if (u) {\n out.usage = { request_units: 1 }\n if (typeof u.prompt_tokens === 'number') out.usage.input_tokens = u.prompt_tokens\n if (typeof u.completion_tokens === 'number') out.usage.output_tokens = u.completion_tokens\n if (typeof u.total_tokens === 'number') out.usage.total_tokens = u.total_tokens\n }\n if (typeof parsed.model === 'string') out.extra = { model: parsed.model }\n return out\n }\n}\n"],"names":[],"mappings":";AAUgB,SAAA,kBAAkB,QAAgB,MAA+B;;AAC3E,MAAA;AACA,MAAA;AACF,YAAQ,gBAAK,MAAM,IAAI,MAAf,mBAAqD,UAArD,mBAA4D;AAAA,EAAA,QAC9D;AACC,WAAA;AAAA,EACT;AACA,MAAI,SAAS;AAAkC,WAAA;AAC3C,MAAA,WAAW,OAAO,WAAW;AAAK,WAAO,EAAE,SAAS,EAAE,MAAM,cAAgB,EAAA;AAChF,MAAI,CAAC,KAAK,KAAK,GAAG,EAAE,SAAS,MAAM;AAAU,WAAA;AACzC,MAAA,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,EAAE,SAAS,MAAM;AAAU,WAAA;AAC/D,SAAA;AACT;AAEA,SAAS,gBAAgB,SAAiC;AACxD,QAAM,QAAqB,CAAA;AAC3B,aAAW,KAAK,SAAS;AACvB,QAAI,EAAE,SAAS;AAAQ,YAAM,KAAK,EAAE,MAAM,QAAQ,MAAM,EAAE,MAAM;AAAA,aACvD,EAAE,SAAS,SAAS;AAC3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AAY;AAAU,cAAQ,KAAK,EAAE,MAAM,QAAQ,MAAM,QAAQ,SAAS;AAC7F,eAAW,KAAM,QAAQ,cAAc,CAAA,GAA4E;AACjH,UAAI,OAA2B,CAAA;AAC3B,UAAA;AACF,cAAM,IAAI,KAAK,QAAM,OAAE,aAAF,mBAAY,cAAa,IAAI;AAClD,YAAI,KAAK,OAAO,MAAM,YAAY,CAAC,MAAM,QAAQ,CAAC;AAAU,iBAAA;AAAA,MAAA,QACtD;AACN,eAAO,CAAA;AAAA,MACT;AACA,cAAQ,KAAK,EAAE,MAAM,YAAY,SAAS,EAAE,MAAM,IAAI,QAAM,OAAE,aAAF,mBAAY,SAAQ,IAAI,MAAM;AAAA,IAC5F;AACA,QAAI,QAAQ,WAAW;AAAG,cAAQ,KAAK,EAAE,MAAM,QAAQ,MAAM,IAAI;AACjE,UAAM,MAAkB,EAAE,SAAS,EAAE,MAAM,aAAa;AACpD,QAAA,OAAO,OAAO,kBAAkB;AAAU,UAAI,gBAAgB,OAAO;AACzE,UAAM,IAAI,OAAO;AACjB,QAAI,GAAG;AACD,UAAA,QAAQ,EAAE,eAAe,EAAE;AAC3B,UAAA,OAAO,EAAE,kBAAkB;AAAc,YAAA,MAAM,eAAe,EAAE;AAChE,UAAA,OAAO,EAAE,sBAAsB;AAAc,YAAA,MAAM,gBAAgB,EAAE;AACrE,UAAA,OAAO,EAAE,iBAAiB;AAAc,YAAA,MAAM,eAAe,EAAE;AAAA,IACrE;AACI,QAAA,OAAO,OAAO,UAAU;AAAU,UAAI,QAAQ,EAAE,OAAO,OAAO,MAAM;AACjE,WAAA;AAAA,EACT;AACF;"}
@@ -0,0 +1,2 @@
1
+ "use strict";const t=require("./aicc-ccb36ef7.js");function e(t,e){var o,n;let s;try{s=null==(n=null==(o=JSON.parse(e))?void 0:o.error)?void 0:n.code}catch{s=void 0}return"context_length_exceeded"===s?"context_limit":401===t||403===t?{refused:{code:"credentials"}}:[400,404,422].includes(t)?"permanent":[408,409,425,429,500,502,503,504].includes(t)?"transient":"unknown"}function o(t){const e=[];for(const n of t)if("text"===n.type)e.push({type:"text",text:n.text});else if("image"===n.type){const t=n.source,o="url"===t.kind?t.url:"base64"===t.kind?`data:${t.mime};base64,${t.data_base64}`:t.obj_id;e.push({type:"image_url",image_url:{url:o}})}else if("document"===n.type){const t=n.title??"document",o="url"===n.source.kind?n.source.url:"(inline document omitted)";e.push({type:"text",text:`[${t}: ${o}]`})}const o=e[0];return 1===e.length&&"text"===(null==o?void 0:o.type)?o.text:e}function n(e){const n=[];for(const s of e)if("system"===s.role||"developer"===s.role)n.push({role:"system",content:t.textContent(s)});else if("user"===s.role)n.push({role:"user",content:o(s.content)});else if("assistant"===s.role){const e=t.textContent(s),o=t.toolCalls(s).map((t=>({id:t.call_id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}))),r={role:"assistant",content:""===e?null:e};o.length&&(r.tool_calls=o),n.push(r)}else for(const t of s.content)"tool_result"===t.type&&n.push({role:"tool",tool_call_id:t.call_id,content:t.content.filter((t=>"text"===t.type)).map((t=>t.text)).join("\n")});return n}exports.OpenAiLlmClient=class{constructor(t){var e,o;if(this.options=t,this.baseUrl=((null==(e=t.baseUrl)?void 0:e.trim())||"https://api.openai.com/v1").replace(/\/+$/,""),!(null==(o=t.apiKey)?void 0:o.trim()))throw new Error("openai provider: no API key")}async infer(o){var s,r,i;const a={model:o.model_alias,messages:n(o.messages)};void 0!==o.temperature&&(a.temperature=o.temperature),void 0!==o.max_completion_tokens&&(a.max_tokens=o.max_completion_tokens),o.allow_tool_calls&&o.tool_specs.length&&(a.tools=o.tool_specs.map((t=>({type:"function",function:{name:t.name,description:t.description,parameters:t.args_schema}}))),a.tool_choice="auto"),o.force_json&&(a.response_format={type:"json_schema",json_schema:{name:"xllm_result",schema:o.json_schema??t.anyJsonObjectSchema()}}),o.provider_options&&"object"==typeof o.provider_options&&!Array.isArray(o.provider_options)&&Object.assign(a,o.provider_options);const l=this.options.fetch??globalThis.fetch.bind(globalThis);let c,p,u;try{c=await l(`${this.baseUrl}/chat/completions`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${this.options.apiKey}`,...this.options.headers??{}},body:JSON.stringify(a),signal:o.signal})}catch(y){if(o.signal.aborted)throw new t.LLMComputeException({kind:"cancelled"});throw t.providerError("transient",`openai request failed: ${y instanceof Error?y.message:String(y)}`)}try{p=await c.text()}catch(y){throw t.providerError("transient",`openai read body failed: ${y instanceof Error?y.message:String(y)}`)}if(!c.ok)throw t.providerError(e(c.status,p),`openai http ${c.status}: ${function(t,e){const o=[...t];return o.length<=e?t:o.slice(0,e).join("")+"…"}(p,512)}`);try{u=JSON.parse(p)}catch(y){throw t.providerError("unknown",`openai invalid JSON: ${y instanceof Error?y.message:String(y)}`)}const m=null==(s=u.choices)?void 0:s[0];if(!m)throw t.providerError("unknown","openai response has no choices");const d=m.message??{},h=[];"string"==typeof d.content&&h.push({type:"text",text:d.content});for(const t of d.tool_calls??[]){let e={};try{const o=JSON.parse((null==(r=t.function)?void 0:r.arguments)??"{}");o&&"object"==typeof o&&!Array.isArray(o)&&(e=o)}catch{e={}}h.push({type:"tool_use",call_id:t.id??"",name:(null==(i=t.function)?void 0:i.name)??"",args:e})}0===h.length&&h.push({type:"text",text:""});const f={message:{role:"assistant",content:h}};"string"==typeof m.finish_reason&&(f.finish_reason=m.finish_reason);const _=u.usage;return _&&(f.usage={request_units:1},"number"==typeof _.prompt_tokens&&(f.usage.input_tokens=_.prompt_tokens),"number"==typeof _.completion_tokens&&(f.usage.output_tokens=_.completion_tokens),"number"==typeof _.total_tokens&&(f.usage.total_tokens=_.total_tokens)),"string"==typeof u.model&&(f.extra={model:u.model}),f}},exports.messagesToOpenai=n,exports.openaiHttpFailure=e;
2
+ //# sourceMappingURL=openai-f560d518.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"openai-f560d518.js","sources":["../src/xllm/dev/openai.ts"],"sourcesContent":["// OpenAI-compatible Chat Completions client (Rust `OpenAiLlmClient`), for\n// development and mocks. Only page code can inject it; configuration cannot\n// select it. CORS is the endpoint's business.\n\nimport type { AiContent, AiMessage, AiResponse, AiToolCall, JsonValue, LlmClient, LlmInferenceRequest, ProviderFailure } from '../core/types'\nimport { LLMComputeException, providerError } from '../core/errors'\nimport { textContent, toolCalls } from '../core/messages'\nimport { anyJsonObjectSchema } from '../providers/aicc'\n\n/** Failure class of a non-2xx response (Rust `openai_http_failure` after T2-0). */\nexport function openaiHttpFailure(status: number, body: string): ProviderFailure {\n let code: unknown\n try {\n code = (JSON.parse(body) as { error?: { code?: unknown } })?.error?.code\n } catch {\n code = undefined\n }\n if (code === 'context_length_exceeded') return 'context_limit'\n if (status === 401 || status === 403) return { refused: { code: 'credentials' } }\n if ([400, 404, 422].includes(status)) return 'permanent'\n if ([408, 409, 425, 429, 500, 502, 503, 504].includes(status)) return 'transient'\n return 'unknown'\n}\n\nfunction contentToOpenai(content: AiContent[]): JsonValue {\n const parts: JsonValue[] = []\n for (const c of content) {\n if (c.type === 'text') parts.push({ type: 'text', text: c.text })\n else if (c.type === 'image') {\n const s = c.source\n const url = s.kind === 'url' ? s.url : s.kind === 'base64' ? `data:${s.mime};base64,${s.data_base64}` : s.obj_id\n parts.push({ type: 'image_url', image_url: { url } })\n } else if (c.type === 'document') {\n const label = c.title ?? 'document'\n const desc = c.source.kind === 'url' ? c.source.url : '(inline document omitted)'\n parts.push({ type: 'text', text: `[${label}: ${desc}]` })\n }\n }\n const only = parts[0] as { type?: string; text?: string } | undefined\n if (parts.length === 1 && only?.type === 'text') return only.text as string\n return parts\n}\n\nexport function messagesToOpenai(messages: AiMessage[]): JsonValue[] {\n const out: JsonValue[] = []\n for (const m of messages) {\n if (m.role === 'system' || m.role === 'developer') out.push({ role: 'system', content: textContent(m) })\n else if (m.role === 'user') out.push({ role: 'user', content: contentToOpenai(m.content) })\n else if (m.role === 'assistant') {\n const text = textContent(m)\n const calls = toolCalls(m).map(c => ({ id: c.call_id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.args) } }))\n const obj: { [k: string]: JsonValue } = { role: 'assistant', content: text === '' ? null : text }\n if (calls.length) obj.tool_calls = calls\n out.push(obj)\n } else {\n for (const b of m.content) {\n if (b.type === 'tool_result') {\n out.push({ role: 'tool', tool_call_id: b.call_id, content: b.content.filter(c => c.type === 'text').map(c => (c as { text: string }).text).join('\\n') })\n }\n }\n }\n }\n return out\n}\n\nfunction truncateChars(s: string, max: number): string {\n const chars = [...s]\n return chars.length <= max ? s : chars.slice(0, max).join('') + '…'\n}\n\nexport interface OpenAiLlmOptions {\n baseUrl?: string\n apiKey: string\n headers?: Record<string, string>\n fetch?: typeof fetch\n}\n\nexport class OpenAiLlmClient implements LlmClient {\n private readonly baseUrl: string\n\n constructor(private readonly options: OpenAiLlmOptions) {\n this.baseUrl = (options.baseUrl?.trim() || 'https://api.openai.com/v1').replace(/\\/+$/, '')\n if (!options.apiKey?.trim()) throw new Error('openai provider: no API key')\n }\n\n async infer(req: LlmInferenceRequest): Promise<AiResponse> {\n const body: { [k: string]: JsonValue } = { model: req.model_alias, messages: messagesToOpenai(req.messages) }\n if (req.temperature !== undefined) body.temperature = req.temperature\n if (req.max_completion_tokens !== undefined) body.max_tokens = req.max_completion_tokens\n if (req.allow_tool_calls && req.tool_specs.length) {\n body.tools = req.tool_specs.map(s => ({ type: 'function', function: { name: s.name, description: s.description, parameters: s.args_schema } }))\n body.tool_choice = 'auto'\n }\n if (req.force_json) body.response_format = { type: 'json_schema', json_schema: { name: 'xllm_result', schema: req.json_schema ?? anyJsonObjectSchema() } }\n if (req.provider_options && typeof req.provider_options === 'object' && !Array.isArray(req.provider_options)) {\n Object.assign(body, req.provider_options)\n }\n const f = this.options.fetch ?? globalThis.fetch.bind(globalThis)\n let response: Response\n try {\n response = await f(`${this.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${this.options.apiKey}`, ...(this.options.headers ?? {}) },\n body: JSON.stringify(body),\n signal: req.signal,\n })\n } catch (e) {\n if (req.signal.aborted) throw new LLMComputeException({ kind: 'cancelled' })\n throw providerError('transient', `openai request failed: ${e instanceof Error ? e.message : String(e)}`)\n }\n let text: string\n try {\n text = await response.text()\n } catch (e) {\n throw providerError('transient', `openai read body failed: ${e instanceof Error ? e.message : String(e)}`)\n }\n if (!response.ok) throw providerError(openaiHttpFailure(response.status, text), `openai http ${response.status}: ${truncateChars(text, 512)}`)\n let parsed: { choices?: { message?: { content?: unknown; tool_calls?: unknown[] }; finish_reason?: unknown }[]; usage?: Record<string, unknown>; model?: unknown }\n try {\n parsed = JSON.parse(text)\n } catch (e) {\n throw providerError('unknown', `openai invalid JSON: ${e instanceof Error ? e.message : String(e)}`)\n }\n const choice = parsed.choices?.[0]\n if (!choice) throw providerError('unknown', 'openai response has no choices')\n const message = choice.message ?? {}\n const content: AiMessage['content'] = []\n if (typeof message.content === 'string') content.push({ type: 'text', text: message.content })\n for (const c of (message.tool_calls ?? []) as { id?: string; function?: { name?: string; arguments?: string } }[]) {\n let args: AiToolCall['args'] = {}\n try {\n const v = JSON.parse(c.function?.arguments ?? '{}')\n if (v && typeof v === 'object' && !Array.isArray(v)) args = v\n } catch {\n args = {}\n }\n content.push({ type: 'tool_use', call_id: c.id ?? '', name: c.function?.name ?? '', args })\n }\n if (content.length === 0) content.push({ type: 'text', text: '' })\n const out: AiResponse = { message: { role: 'assistant', content } }\n if (typeof choice.finish_reason === 'string') out.finish_reason = choice.finish_reason\n const u = parsed.usage\n if (u) {\n out.usage = { request_units: 1 }\n if (typeof u.prompt_tokens === 'number') out.usage.input_tokens = u.prompt_tokens\n if (typeof u.completion_tokens === 'number') out.usage.output_tokens = u.completion_tokens\n if (typeof u.total_tokens === 'number') out.usage.total_tokens = u.total_tokens\n }\n if (typeof parsed.model === 'string') out.extra = { model: parsed.model }\n return out\n }\n}\n"],"names":["openaiHttpFailure","status","body","code","_b","parse","_a","error","refused","includes","contentToOpenai","content","parts","c","type","push","text","s","source","url","kind","mime","data_base64","obj_id","image_url","label","title","desc","only","length","messagesToOpenai","messages","out","m","role","textContent","calls","toolCalls","map","id","call_id","function","name","arguments","JSON","stringify","args","obj","tool_calls","b","tool_call_id","filter","join","constructor","options","this","baseUrl","trim","replace","apiKey","Error","infer","req","model","model_alias","temperature","max_completion_tokens","max_tokens","allow_tool_calls","tool_specs","tools","description","parameters","args_schema","tool_choice","force_json","response_format","json_schema","schema","anyJsonObjectSchema","provider_options","Array","isArray","Object","assign","f","fetch","globalThis","bind","response","parsed","method","headers","authorization","signal","e","aborted","LLMComputeException","providerError","message","String","ok","max","chars","slice","truncateChars","choice","choices","v","_c","finish_reason","u","usage","request_units","prompt_tokens","input_tokens","completion_tokens","output_tokens","total_tokens","extra"],"mappings":"mDAUgB,SAAAA,EAAkBC,EAAgBC,WAC5C,IAAAC,EACA,IACFA,EAAQ,OAAAC,EAAA,cAAKC,MAAMH,SAAX,EAAAI,EAAqDC,YAAO,EAAAH,EAAAD,IAAA,CAC9D,MACCA,OAAA,CACT,CACA,MAAa,4BAATA,EAA2C,gBAChC,MAAXF,GAA6B,MAAXA,EAAuB,CAAEO,QAAS,CAAEL,KAAM,gBAC5D,CAAC,IAAK,IAAK,KAAKM,SAASR,GAAgB,YACzC,CAAC,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,IAAK,KAAKQ,SAASR,GAAgB,YAC/D,SACT,CAEA,SAASS,EAAgBC,GACvB,MAAMC,EAAqB,GAC3B,IAAA,MAAWC,KAAKF,EACd,GAAe,SAAXE,EAAEC,KAAiBF,EAAMG,KAAK,CAAED,KAAM,OAAQE,KAAMH,EAAEG,YACjD,GAAW,UAAXH,EAAEC,KAAkB,CAC3B,MAAMG,EAAIJ,EAAEK,OACNC,EAAiB,QAAXF,EAAEG,KAAiBH,EAAEE,IAAiB,WAAXF,EAAEG,KAAoB,QAAQH,EAAEI,eAAeJ,EAAEK,cAAgBL,EAAEM,OACpGX,EAAAG,KAAK,CAAED,KAAM,YAAaU,UAAW,CAAEL,Q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