@lucid-agents/taskmarket 1.16.0 → 1.17.1

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 (128) hide show
  1. package/THIRD_PARTY_NOTICES.md +14 -0
  2. package/dist/THIRD_PARTY_NOTICES.md +3108 -0
  3. package/dist/agent-compatibility.json +54 -0
  4. package/dist/budget-view-XKZC3GY5.js +36 -0
  5. package/dist/channels-Q7XMSUSO.js +29 -0
  6. package/dist/chunk-3S63AB3C.js +16068 -0
  7. package/dist/chunk-73RXOYME.js +185 -0
  8. package/dist/chunk-EIHZYRIU.js +1099 -0
  9. package/dist/chunk-F5SS4NUF.js +1062 -0
  10. package/dist/chunk-JAZ5BWPB.js +181 -0
  11. package/dist/chunk-MI2GPMCZ.js +154 -0
  12. package/dist/chunk-OKZ2NRYZ.js +133 -0
  13. package/dist/chunk-S7SJMJ2I.js +38 -0
  14. package/dist/chunk-YM4S6IE4.js +15 -0
  15. package/dist/compatibility-KUYGZSUC.js +19 -0
  16. package/dist/doctor-BY2PBHS7.js +216 -0
  17. package/dist/errors-2L357HGA.js +8 -0
  18. package/dist/index.js +1186 -13492
  19. package/dist/launch-DE65XO5C.js +22476 -0
  20. package/dist/pi/CHANGELOG.md +5689 -0
  21. package/dist/pi/README.md +718 -0
  22. package/dist/pi/dist/bundle/chunks/anthropic-messages-VWZZOSJQ.js +6 -0
  23. package/dist/pi/dist/bundle/chunks/anthropic.js +75 -0
  24. package/dist/pi/dist/bundle/chunks/azure-openai-responses-BJLAM6CD.js +2 -0
  25. package/dist/pi/dist/bundle/chunks/bedrock-converse-stream.js +74 -0
  26. package/dist/pi/dist/bundle/chunks/chunk-4L3WN2XY.js +2 -0
  27. package/dist/pi/dist/bundle/chunks/chunk-6CYCI3EJ.js +12 -0
  28. package/dist/pi/dist/bundle/chunks/chunk-6R7UI4IY.js +2 -0
  29. package/dist/pi/dist/bundle/chunks/chunk-7ZC4UXSL.js +2 -0
  30. package/dist/pi/dist/bundle/chunks/chunk-AXIIZGTV.js +2 -0
  31. package/dist/pi/dist/bundle/chunks/chunk-CLNPYIDP.js +42 -0
  32. package/dist/pi/dist/bundle/chunks/chunk-DRQDKNXA.js +2 -0
  33. package/dist/pi/dist/bundle/chunks/chunk-GMWCTUPB.js +2 -0
  34. package/dist/pi/dist/bundle/chunks/chunk-IDDQWTHI.js +2 -0
  35. package/dist/pi/dist/bundle/chunks/chunk-JVUZSMYM.js +1547 -0
  36. package/dist/pi/dist/bundle/chunks/chunk-L2ZPNLYD.js +2 -0
  37. package/dist/pi/dist/bundle/chunks/chunk-NUHFSC37.js +25 -0
  38. package/dist/pi/dist/bundle/chunks/chunk-OUXLLA64.js +11 -0
  39. package/dist/pi/dist/bundle/chunks/chunk-PGXDEOVV.js +2 -0
  40. package/dist/pi/dist/bundle/chunks/chunk-PJACZCIR.js +2 -0
  41. package/dist/pi/dist/bundle/chunks/chunk-PRRNXB7S.js +2 -0
  42. package/dist/pi/dist/bundle/chunks/chunk-TEPMHNKQ.js +2 -0
  43. package/dist/pi/dist/bundle/chunks/chunk-TRDNDS6A.js +4 -0
  44. package/dist/pi/dist/bundle/chunks/chunk-U6ZMQKGD.js +50 -0
  45. package/dist/pi/dist/bundle/chunks/chunk-UAQELI3K.js +2 -0
  46. package/dist/pi/dist/bundle/chunks/chunk-USJZMAIR.js +2 -0
  47. package/dist/pi/dist/bundle/chunks/chunk-XDUWOHPL.js +6 -0
  48. package/dist/pi/dist/bundle/chunks/chunk-XNGRGP62.js +2 -0
  49. package/dist/pi/dist/bundle/chunks/github-copilot.js +2 -0
  50. package/dist/pi/dist/bundle/chunks/google-generative-ai-Q2K7FBDI.js +2 -0
  51. package/dist/pi/dist/bundle/chunks/google-vertex-7UJBF4S7.js +2 -0
  52. package/dist/pi/dist/bundle/chunks/https-proxy-agent-2VXB7436.js +13 -0
  53. package/dist/pi/dist/bundle/chunks/image-resize-worker.js +2 -0
  54. package/dist/pi/dist/bundle/chunks/kimi-coding.js +2 -0
  55. package/dist/pi/dist/bundle/chunks/lib-HGQMNYVT.js +9 -0
  56. package/dist/pi/dist/bundle/chunks/mistral-conversations-4M6BZBX6.js +5 -0
  57. package/dist/pi/dist/bundle/chunks/multipart-parser-SQ6GDJL7.js +3 -0
  58. package/dist/pi/dist/bundle/chunks/node-KG362ECQ.js +16 -0
  59. package/dist/pi/dist/bundle/chunks/node-TWVVAGPO.js +2 -0
  60. package/dist/pi/dist/bundle/chunks/openai-codex-responses-R6VYZTVY.js +10 -0
  61. package/dist/pi/dist/bundle/chunks/openai-codex.js +75 -0
  62. package/dist/pi/dist/bundle/chunks/openai-completions-EKZT2IH2.js +7 -0
  63. package/dist/pi/dist/bundle/chunks/openai-responses-TFDINO6W.js +2 -0
  64. package/dist/pi/dist/bundle/chunks/openrouter-images-N4XVVFSD.js +2 -0
  65. package/dist/pi/dist/bundle/chunks/openrouter.js +75 -0
  66. package/dist/pi/dist/bundle/chunks/pi-messages-PML4SPVJ.js +8 -0
  67. package/dist/pi/dist/bundle/chunks/radius.js +75 -0
  68. package/dist/pi/dist/bundle/chunks/src-UK77SYZE.js +4 -0
  69. package/dist/pi/dist/bundle/chunks/xai.js +2 -0
  70. package/dist/pi/dist/bundle/cli.js +3 -0
  71. package/dist/pi/dist/bundle/index.js +2 -0
  72. package/dist/pi/dist/bundle/rpc-entry.js +3 -0
  73. package/dist/pi/dist/core/export-html/template.css +1066 -0
  74. package/dist/pi/dist/core/export-html/template.html +55 -0
  75. package/dist/pi/dist/core/export-html/template.js +1864 -0
  76. package/dist/pi/dist/core/export-html/vendor/highlight.min.js +1213 -0
  77. package/dist/pi/dist/core/export-html/vendor/marked.min.js +78 -0
  78. package/dist/pi/dist/modes/interactive/assets/clankolas.png +0 -0
  79. package/dist/pi/dist/modes/interactive/theme/dark.json +91 -0
  80. package/dist/pi/dist/modes/interactive/theme/light.json +90 -0
  81. package/dist/pi/dist/modes/interactive/theme/theme-schema.json +356 -0
  82. package/dist/pi/docs/compaction.md +418 -0
  83. package/dist/pi/docs/containerization.md +156 -0
  84. package/dist/pi/docs/custom-provider.md +777 -0
  85. package/dist/pi/docs/development.md +90 -0
  86. package/dist/pi/docs/environment-variables.md +99 -0
  87. package/dist/pi/docs/extensions.md +3023 -0
  88. package/dist/pi/docs/index.md +84 -0
  89. package/dist/pi/docs/json.md +98 -0
  90. package/dist/pi/docs/keybindings.md +239 -0
  91. package/dist/pi/docs/llama-cpp.md +101 -0
  92. package/dist/pi/docs/models.md +574 -0
  93. package/dist/pi/docs/packages.md +228 -0
  94. package/dist/pi/docs/prompt-templates.md +96 -0
  95. package/dist/pi/docs/providers.md +317 -0
  96. package/dist/pi/docs/quickstart.md +167 -0
  97. package/dist/pi/docs/rpc.md +1618 -0
  98. package/dist/pi/docs/sdk.md +1224 -0
  99. package/dist/pi/docs/security.md +59 -0
  100. package/dist/pi/docs/session-format.md +438 -0
  101. package/dist/pi/docs/sessions.md +145 -0
  102. package/dist/pi/docs/settings.md +369 -0
  103. package/dist/pi/docs/shell-aliases.md +13 -0
  104. package/dist/pi/docs/skills.md +232 -0
  105. package/dist/pi/docs/terminal-setup.md +192 -0
  106. package/dist/pi/docs/termux.md +127 -0
  107. package/dist/pi/docs/themes.md +322 -0
  108. package/dist/pi/docs/tmux.md +63 -0
  109. package/dist/pi/docs/tui.md +961 -0
  110. package/dist/pi/docs/usage.md +311 -0
  111. package/dist/pi/docs/windows.md +39 -0
  112. package/dist/pi/package.json +15 -0
  113. package/dist/pi/vendor/chord-context.js +96 -0
  114. package/dist/pi/vendor/jiti/LICENSE +21 -0
  115. package/dist/pi/vendor/jiti/dist/babel.cjs +257 -0
  116. package/dist/pi/vendor/jiti/dist/jiti.cjs +1 -0
  117. package/dist/pi/vendor/jiti/lib/jiti.cjs +30 -0
  118. package/dist/pi/vendor/jiti/package.json +6 -0
  119. package/dist/pi/vendor/photon-node/LICENSE.md +201 -0
  120. package/dist/pi/vendor/photon-node/package.json +6 -0
  121. package/dist/pi/vendor/photon-node/photon_rs.js +4521 -0
  122. package/dist/pi/vendor/photon-node/photon_rs_bg.wasm +0 -0
  123. package/dist/pi-extensions/lockdown.cjs +433 -0
  124. package/dist/pi-extensions/remote-tools.cjs +22320 -0
  125. package/dist/pi-extensions/xgate.cjs +2565 -0
  126. package/dist/reconcile-VEMPNIAO.js +83 -0
  127. package/dist/status-3Q55PBFC.js +18 -0
  128. package/package.json +13 -2
@@ -0,0 +1,2565 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // ../../node_modules/.pnpm/tsup@8.5.1_tsx@4.21.0_typescript@5.7.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js
34
+ var getImportMetaUrl, importMetaUrl;
35
+ var init_cjs_shims = __esm({
36
+ "../../node_modules/.pnpm/tsup@8.5.1_tsx@4.21.0_typescript@5.7.3_yaml@2.8.1/node_modules/tsup/assets/cjs_shims.js"() {
37
+ "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+ }
41
+ });
42
+
43
+ // src/pi-extensions/xgate.ts
44
+ var xgate_exports = {};
45
+ __export(xgate_exports, {
46
+ default: () => taskmarketXgate
47
+ });
48
+ module.exports = __toCommonJS(xgate_exports);
49
+ init_cjs_shims();
50
+
51
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/index.js
52
+ init_cjs_shims();
53
+
54
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/provider.js
55
+ init_cjs_shims();
56
+ var import_node_crypto2 = require("crypto");
57
+ var import_pi_ai = require("@earendil-works/pi-ai");
58
+
59
+ // ../../node_modules/.pnpm/@lucid-agents+xgate-client@0.1.6_@solana+sysvars@5.5.1_typescript@5.7.3_zod@3.25.76/node_modules/@lucid-agents/xgate-client/dist/types.js
60
+ init_cjs_shims();
61
+ var XgateError = class extends Error {
62
+ code;
63
+ constructor(code) {
64
+ super(`Xgate: ${code}. Inspect /xgate status before another purchase.`);
65
+ this.name = "XgateError";
66
+ this.code = code;
67
+ }
68
+ };
69
+ function requireValue(condition, code) {
70
+ if (!condition)
71
+ throw new XgateError(code);
72
+ }
73
+ function record(value) {
74
+ return value !== null && typeof value === "object" && !Array.isArray(value);
75
+ }
76
+ function origin(value, loopback = false) {
77
+ const u = new URL(value);
78
+ requireValue((u.protocol === "https:" || loopback && u.protocol === "http:" && ["127.0.0.1", "[::1]"].includes(u.hostname)) && !u.username && !u.password && u.pathname === "/" && !u.search && !u.hash, "invalid_origin");
79
+ return u.origin;
80
+ }
81
+
82
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/codec.js
83
+ init_cjs_shims();
84
+ var pi = __toESM(require("@earendil-works/pi-ai"), 1);
85
+
86
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/generated/openai-model-capabilities.json
87
+ var openai_model_capabilities_default = {
88
+ "gpt-5": {
89
+ canonical: "gpt-5",
90
+ price_label: "gpt-5",
91
+ operations: [
92
+ "chat",
93
+ "responses"
94
+ ],
95
+ reasoning_efforts: [
96
+ "minimal",
97
+ "low",
98
+ "medium",
99
+ "high"
100
+ ],
101
+ cache: "implicit",
102
+ tools: true,
103
+ chat_legacy_max_tokens: false,
104
+ response_models: [
105
+ "gpt-5",
106
+ "gpt-5-2025-08-07"
107
+ ]
108
+ },
109
+ "gpt-5-2025-08-07": {
110
+ canonical: "gpt-5",
111
+ price_label: "gpt-5",
112
+ operations: [
113
+ "chat",
114
+ "responses"
115
+ ],
116
+ reasoning_efforts: [
117
+ "minimal",
118
+ "low",
119
+ "medium",
120
+ "high"
121
+ ],
122
+ cache: "implicit",
123
+ tools: true,
124
+ chat_legacy_max_tokens: false,
125
+ response_models: [
126
+ "gpt-5-2025-08-07"
127
+ ]
128
+ },
129
+ "gpt-5-chat-latest": {
130
+ canonical: "gpt-5-chat-latest",
131
+ price_label: "gpt-5-chat-latest",
132
+ operations: [
133
+ "chat",
134
+ "responses"
135
+ ],
136
+ reasoning_efforts: [],
137
+ cache: "implicit",
138
+ tools: true,
139
+ chat_legacy_max_tokens: false,
140
+ response_models: [
141
+ "gpt-5-chat-latest"
142
+ ]
143
+ },
144
+ "gpt-5-codex": {
145
+ canonical: "gpt-5-codex",
146
+ price_label: "gpt-5-codex",
147
+ operations: [
148
+ "responses"
149
+ ],
150
+ reasoning_efforts: [],
151
+ cache: "implicit",
152
+ tools: true,
153
+ chat_legacy_max_tokens: false,
154
+ response_models: [
155
+ "gpt-5-codex"
156
+ ]
157
+ },
158
+ "gpt-5-mini": {
159
+ canonical: "gpt-5-mini",
160
+ price_label: "gpt-5-mini",
161
+ operations: [
162
+ "chat",
163
+ "responses"
164
+ ],
165
+ reasoning_efforts: [
166
+ "minimal"
167
+ ],
168
+ cache: "implicit",
169
+ tools: true,
170
+ chat_legacy_max_tokens: false,
171
+ response_models: [
172
+ "gpt-5-mini",
173
+ "gpt-5-mini-2025-08-07"
174
+ ]
175
+ },
176
+ "gpt-5-mini-2025-08-07": {
177
+ canonical: "gpt-5-mini",
178
+ price_label: "gpt-5-mini",
179
+ operations: [
180
+ "chat",
181
+ "responses"
182
+ ],
183
+ reasoning_efforts: [
184
+ "minimal"
185
+ ],
186
+ cache: "implicit",
187
+ tools: true,
188
+ chat_legacy_max_tokens: false,
189
+ response_models: [
190
+ "gpt-5-mini-2025-08-07"
191
+ ]
192
+ },
193
+ "gpt-5-nano": {
194
+ canonical: "gpt-5-nano",
195
+ price_label: "gpt-5-nano",
196
+ operations: [
197
+ "chat",
198
+ "responses"
199
+ ],
200
+ reasoning_efforts: [
201
+ "minimal",
202
+ "low",
203
+ "medium",
204
+ "high"
205
+ ],
206
+ cache: "implicit",
207
+ tools: true,
208
+ chat_legacy_max_tokens: false,
209
+ response_models: [
210
+ "gpt-5-nano",
211
+ "gpt-5-nano-2025-08-07"
212
+ ]
213
+ },
214
+ "gpt-5-nano-2025-08-07": {
215
+ canonical: "gpt-5-nano",
216
+ price_label: "gpt-5-nano",
217
+ operations: [
218
+ "chat",
219
+ "responses"
220
+ ],
221
+ reasoning_efforts: [
222
+ "minimal",
223
+ "low",
224
+ "medium",
225
+ "high"
226
+ ],
227
+ cache: "implicit",
228
+ tools: true,
229
+ chat_legacy_max_tokens: false,
230
+ response_models: [
231
+ "gpt-5-nano-2025-08-07"
232
+ ]
233
+ },
234
+ "gpt-5-pro": {
235
+ canonical: "gpt-5-pro",
236
+ price_label: "gpt-5-pro",
237
+ operations: [
238
+ "responses"
239
+ ],
240
+ reasoning_efforts: [
241
+ "high"
242
+ ],
243
+ cache: "uncached",
244
+ tools: true,
245
+ chat_legacy_max_tokens: false,
246
+ response_models: [
247
+ "gpt-5-pro",
248
+ "gpt-5-pro-2025-10-06"
249
+ ]
250
+ },
251
+ "gpt-5-pro-2025-10-06": {
252
+ canonical: "gpt-5-pro",
253
+ price_label: "gpt-5-pro",
254
+ operations: [
255
+ "responses"
256
+ ],
257
+ reasoning_efforts: [
258
+ "high"
259
+ ],
260
+ cache: "uncached",
261
+ tools: true,
262
+ chat_legacy_max_tokens: false,
263
+ response_models: [
264
+ "gpt-5-pro-2025-10-06"
265
+ ]
266
+ },
267
+ "gpt-5.1": {
268
+ canonical: "gpt-5.1",
269
+ price_label: "gpt-5.1",
270
+ operations: [
271
+ "chat",
272
+ "responses"
273
+ ],
274
+ reasoning_efforts: [
275
+ "none",
276
+ "low",
277
+ "medium",
278
+ "high"
279
+ ],
280
+ cache: "implicit",
281
+ tools: true,
282
+ chat_legacy_max_tokens: false,
283
+ response_models: [
284
+ "gpt-5.1",
285
+ "gpt-5.1-2025-11-13"
286
+ ]
287
+ },
288
+ "gpt-5.1-2025-11-13": {
289
+ canonical: "gpt-5.1",
290
+ price_label: "gpt-5.1",
291
+ operations: [
292
+ "chat",
293
+ "responses"
294
+ ],
295
+ reasoning_efforts: [
296
+ "none",
297
+ "low",
298
+ "medium",
299
+ "high"
300
+ ],
301
+ cache: "implicit",
302
+ tools: true,
303
+ chat_legacy_max_tokens: false,
304
+ response_models: [
305
+ "gpt-5.1-2025-11-13"
306
+ ]
307
+ },
308
+ "gpt-5.1-chat-latest": {
309
+ canonical: "gpt-5.1-chat-latest",
310
+ price_label: "gpt-5.1-chat-latest",
311
+ operations: [
312
+ "chat",
313
+ "responses"
314
+ ],
315
+ reasoning_efforts: [],
316
+ cache: "implicit",
317
+ tools: true,
318
+ chat_legacy_max_tokens: false,
319
+ response_models: [
320
+ "gpt-5.1-chat-latest"
321
+ ]
322
+ },
323
+ "gpt-5.1-codex": {
324
+ canonical: "gpt-5.1-codex",
325
+ price_label: "gpt-5.1-codex",
326
+ operations: [
327
+ "responses"
328
+ ],
329
+ reasoning_efforts: [],
330
+ cache: "implicit",
331
+ tools: true,
332
+ chat_legacy_max_tokens: false,
333
+ response_models: [
334
+ "gpt-5.1-codex"
335
+ ]
336
+ },
337
+ "gpt-5.1-codex-max": {
338
+ canonical: "gpt-5.1-codex-max",
339
+ price_label: "gpt-5.1-codex-max",
340
+ operations: [
341
+ "responses"
342
+ ],
343
+ reasoning_efforts: [],
344
+ cache: "implicit",
345
+ tools: true,
346
+ chat_legacy_max_tokens: false,
347
+ response_models: [
348
+ "gpt-5.1-codex-max"
349
+ ]
350
+ },
351
+ "gpt-5.1-codex-mini": {
352
+ canonical: "gpt-5.1-codex-mini",
353
+ price_label: "gpt-5.1-codex-mini",
354
+ operations: [
355
+ "responses"
356
+ ],
357
+ reasoning_efforts: [],
358
+ cache: "implicit",
359
+ tools: true,
360
+ chat_legacy_max_tokens: false,
361
+ response_models: [
362
+ "gpt-5.1-codex-mini"
363
+ ]
364
+ },
365
+ "gpt-5.2": {
366
+ canonical: "gpt-5.2",
367
+ price_label: "gpt-5.2",
368
+ operations: [
369
+ "chat",
370
+ "responses"
371
+ ],
372
+ reasoning_efforts: [
373
+ "none",
374
+ "low",
375
+ "medium",
376
+ "high",
377
+ "xhigh"
378
+ ],
379
+ cache: "implicit",
380
+ tools: true,
381
+ chat_legacy_max_tokens: false,
382
+ response_models: [
383
+ "gpt-5.2",
384
+ "gpt-5.2-2025-12-11"
385
+ ]
386
+ },
387
+ "gpt-5.2-2025-12-11": {
388
+ canonical: "gpt-5.2",
389
+ price_label: "gpt-5.2",
390
+ operations: [
391
+ "chat",
392
+ "responses"
393
+ ],
394
+ reasoning_efforts: [
395
+ "none",
396
+ "low",
397
+ "medium",
398
+ "high",
399
+ "xhigh"
400
+ ],
401
+ cache: "implicit",
402
+ tools: true,
403
+ chat_legacy_max_tokens: false,
404
+ response_models: [
405
+ "gpt-5.2-2025-12-11"
406
+ ]
407
+ },
408
+ "gpt-5.2-chat-latest": {
409
+ canonical: "gpt-5.2-chat-latest",
410
+ price_label: "gpt-5.2-chat-latest",
411
+ operations: [
412
+ "chat",
413
+ "responses"
414
+ ],
415
+ reasoning_efforts: [],
416
+ cache: "implicit",
417
+ tools: true,
418
+ chat_legacy_max_tokens: false,
419
+ response_models: [
420
+ "gpt-5.2-chat-latest"
421
+ ]
422
+ },
423
+ "gpt-5.2-codex": {
424
+ canonical: "gpt-5.2-codex",
425
+ price_label: "gpt-5.2-codex",
426
+ operations: [
427
+ "responses"
428
+ ],
429
+ reasoning_efforts: [],
430
+ cache: "implicit",
431
+ tools: true,
432
+ chat_legacy_max_tokens: false,
433
+ response_models: [
434
+ "gpt-5.2-codex"
435
+ ]
436
+ },
437
+ "gpt-5.2-pro": {
438
+ canonical: "gpt-5.2-pro",
439
+ price_label: "gpt-5.2-pro",
440
+ operations: [
441
+ "responses"
442
+ ],
443
+ reasoning_efforts: [
444
+ "medium",
445
+ "high",
446
+ "xhigh"
447
+ ],
448
+ cache: "uncached",
449
+ tools: true,
450
+ chat_legacy_max_tokens: false,
451
+ response_models: [
452
+ "gpt-5.2-pro",
453
+ "gpt-5.2-pro-2025-12-11"
454
+ ]
455
+ },
456
+ "gpt-5.2-pro-2025-12-11": {
457
+ canonical: "gpt-5.2-pro",
458
+ price_label: "gpt-5.2-pro",
459
+ operations: [
460
+ "responses"
461
+ ],
462
+ reasoning_efforts: [
463
+ "medium",
464
+ "high",
465
+ "xhigh"
466
+ ],
467
+ cache: "uncached",
468
+ tools: true,
469
+ chat_legacy_max_tokens: false,
470
+ response_models: [
471
+ "gpt-5.2-pro-2025-12-11"
472
+ ]
473
+ },
474
+ "gpt-5.3-chat-latest": {
475
+ canonical: "gpt-5.3-chat-latest",
476
+ price_label: "gpt-5.3-chat-latest",
477
+ operations: [
478
+ "chat",
479
+ "responses"
480
+ ],
481
+ reasoning_efforts: [],
482
+ cache: "implicit",
483
+ tools: true,
484
+ chat_legacy_max_tokens: false,
485
+ response_models: [
486
+ "gpt-5.3-chat-latest"
487
+ ]
488
+ },
489
+ "gpt-5.3-codex": {
490
+ canonical: "gpt-5.3-codex",
491
+ price_label: "gpt-5.3-codex",
492
+ operations: [
493
+ "responses"
494
+ ],
495
+ reasoning_efforts: [
496
+ "low",
497
+ "medium",
498
+ "high",
499
+ "xhigh"
500
+ ],
501
+ cache: "implicit",
502
+ tools: true,
503
+ chat_legacy_max_tokens: false,
504
+ response_models: [
505
+ "gpt-5.3-codex"
506
+ ]
507
+ },
508
+ "gpt-5.4": {
509
+ canonical: "gpt-5.4",
510
+ price_label: "gpt-5.4 (<272K context length)",
511
+ operations: [
512
+ "chat",
513
+ "responses"
514
+ ],
515
+ reasoning_efforts: [
516
+ "none",
517
+ "low",
518
+ "medium",
519
+ "high",
520
+ "xhigh"
521
+ ],
522
+ cache: "implicit",
523
+ tools: true,
524
+ chat_legacy_max_tokens: false,
525
+ response_models: [
526
+ "gpt-5.4",
527
+ "gpt-5.4-2026-03-05"
528
+ ]
529
+ },
530
+ "gpt-5.4-2026-03-05": {
531
+ canonical: "gpt-5.4",
532
+ price_label: "gpt-5.4 (<272K context length)",
533
+ operations: [
534
+ "chat",
535
+ "responses"
536
+ ],
537
+ reasoning_efforts: [
538
+ "none",
539
+ "low",
540
+ "medium",
541
+ "high",
542
+ "xhigh"
543
+ ],
544
+ cache: "implicit",
545
+ tools: true,
546
+ chat_legacy_max_tokens: false,
547
+ response_models: [
548
+ "gpt-5.4-2026-03-05"
549
+ ]
550
+ },
551
+ "gpt-5.4-mini": {
552
+ canonical: "gpt-5.4-mini",
553
+ price_label: "gpt-5.4-mini",
554
+ operations: [
555
+ "chat",
556
+ "responses"
557
+ ],
558
+ reasoning_efforts: [
559
+ "none",
560
+ "low",
561
+ "medium",
562
+ "high",
563
+ "xhigh"
564
+ ],
565
+ cache: "implicit",
566
+ tools: true,
567
+ chat_legacy_max_tokens: false,
568
+ response_models: [
569
+ "gpt-5.4-mini",
570
+ "gpt-5.4-mini-2026-03-17"
571
+ ]
572
+ },
573
+ "gpt-5.4-mini-2026-03-17": {
574
+ canonical: "gpt-5.4-mini",
575
+ price_label: "gpt-5.4-mini",
576
+ operations: [
577
+ "chat",
578
+ "responses"
579
+ ],
580
+ reasoning_efforts: [
581
+ "none",
582
+ "low",
583
+ "medium",
584
+ "high",
585
+ "xhigh"
586
+ ],
587
+ cache: "implicit",
588
+ tools: true,
589
+ chat_legacy_max_tokens: false,
590
+ response_models: [
591
+ "gpt-5.4-mini-2026-03-17"
592
+ ]
593
+ },
594
+ "gpt-5.4-nano": {
595
+ canonical: "gpt-5.4-nano",
596
+ price_label: "gpt-5.4-nano",
597
+ operations: [
598
+ "chat",
599
+ "responses"
600
+ ],
601
+ reasoning_efforts: [
602
+ "none",
603
+ "low",
604
+ "medium",
605
+ "high",
606
+ "xhigh"
607
+ ],
608
+ cache: "implicit",
609
+ tools: true,
610
+ chat_legacy_max_tokens: false,
611
+ response_models: [
612
+ "gpt-5.4-nano",
613
+ "gpt-5.4-nano-2026-03-17"
614
+ ]
615
+ },
616
+ "gpt-5.4-nano-2026-03-17": {
617
+ canonical: "gpt-5.4-nano",
618
+ price_label: "gpt-5.4-nano",
619
+ operations: [
620
+ "chat",
621
+ "responses"
622
+ ],
623
+ reasoning_efforts: [
624
+ "none",
625
+ "low",
626
+ "medium",
627
+ "high",
628
+ "xhigh"
629
+ ],
630
+ cache: "implicit",
631
+ tools: true,
632
+ chat_legacy_max_tokens: false,
633
+ response_models: [
634
+ "gpt-5.4-nano-2026-03-17"
635
+ ]
636
+ },
637
+ "gpt-5.4-pro": {
638
+ canonical: "gpt-5.4-pro",
639
+ price_label: "gpt-5.4-pro (<272K context length)",
640
+ operations: [
641
+ "responses"
642
+ ],
643
+ reasoning_efforts: [
644
+ "medium",
645
+ "high",
646
+ "xhigh"
647
+ ],
648
+ cache: "uncached",
649
+ tools: true,
650
+ chat_legacy_max_tokens: false,
651
+ response_models: [
652
+ "gpt-5.4-pro",
653
+ "gpt-5.4-pro-2026-03-05"
654
+ ]
655
+ },
656
+ "gpt-5.4-pro-2026-03-05": {
657
+ canonical: "gpt-5.4-pro",
658
+ price_label: "gpt-5.4-pro (<272K context length)",
659
+ operations: [
660
+ "responses"
661
+ ],
662
+ reasoning_efforts: [
663
+ "medium",
664
+ "high",
665
+ "xhigh"
666
+ ],
667
+ cache: "uncached",
668
+ tools: true,
669
+ chat_legacy_max_tokens: false,
670
+ response_models: [
671
+ "gpt-5.4-pro-2026-03-05"
672
+ ]
673
+ },
674
+ "gpt-5.5": {
675
+ canonical: "gpt-5.5",
676
+ price_label: "gpt-5.5 (<272K context length)",
677
+ operations: [
678
+ "chat",
679
+ "responses"
680
+ ],
681
+ reasoning_efforts: [
682
+ "none",
683
+ "low",
684
+ "medium",
685
+ "high",
686
+ "xhigh"
687
+ ],
688
+ cache: "implicit",
689
+ tools: true,
690
+ chat_legacy_max_tokens: false,
691
+ response_models: [
692
+ "gpt-5.5",
693
+ "gpt-5.5-2026-04-23"
694
+ ]
695
+ },
696
+ "gpt-5.5-2026-04-23": {
697
+ canonical: "gpt-5.5",
698
+ price_label: "gpt-5.5 (<272K context length)",
699
+ operations: [
700
+ "chat",
701
+ "responses"
702
+ ],
703
+ reasoning_efforts: [
704
+ "none",
705
+ "low",
706
+ "medium",
707
+ "high",
708
+ "xhigh"
709
+ ],
710
+ cache: "implicit",
711
+ tools: true,
712
+ chat_legacy_max_tokens: false,
713
+ response_models: [
714
+ "gpt-5.5-2026-04-23"
715
+ ]
716
+ },
717
+ "gpt-5.5-pro": {
718
+ canonical: "gpt-5.5-pro",
719
+ price_label: "gpt-5.5-pro (<272K context length)",
720
+ operations: [
721
+ "responses"
722
+ ],
723
+ reasoning_efforts: [
724
+ "medium",
725
+ "high",
726
+ "xhigh"
727
+ ],
728
+ cache: "uncached",
729
+ tools: true,
730
+ chat_legacy_max_tokens: false,
731
+ response_models: [
732
+ "gpt-5.5-pro",
733
+ "gpt-5.5-pro-2026-04-23"
734
+ ]
735
+ },
736
+ "gpt-5.5-pro-2026-04-23": {
737
+ canonical: "gpt-5.5-pro",
738
+ price_label: "gpt-5.5-pro (<272K context length)",
739
+ operations: [
740
+ "responses"
741
+ ],
742
+ reasoning_efforts: [
743
+ "medium",
744
+ "high",
745
+ "xhigh"
746
+ ],
747
+ cache: "uncached",
748
+ tools: true,
749
+ chat_legacy_max_tokens: false,
750
+ response_models: [
751
+ "gpt-5.5-pro-2026-04-23"
752
+ ]
753
+ },
754
+ "gpt-5.6": {
755
+ canonical: "gpt-5.6-sol",
756
+ price_label: "gpt-5.6-sol",
757
+ operations: [
758
+ "chat",
759
+ "responses"
760
+ ],
761
+ reasoning_efforts: [
762
+ "none",
763
+ "low",
764
+ "medium",
765
+ "high",
766
+ "xhigh",
767
+ "max"
768
+ ],
769
+ cache: "write_priced",
770
+ tools: true,
771
+ chat_legacy_max_tokens: false,
772
+ response_models: [
773
+ "gpt-5.6",
774
+ "gpt-5.6-sol"
775
+ ]
776
+ },
777
+ "gpt-5.6-luna": {
778
+ canonical: "gpt-5.6-luna",
779
+ price_label: "gpt-5.6-luna",
780
+ operations: [
781
+ "chat",
782
+ "responses"
783
+ ],
784
+ reasoning_efforts: [
785
+ "none",
786
+ "low",
787
+ "medium",
788
+ "high",
789
+ "xhigh",
790
+ "max"
791
+ ],
792
+ cache: "write_priced",
793
+ tools: true,
794
+ chat_legacy_max_tokens: false,
795
+ response_models: [
796
+ "gpt-5.6-luna"
797
+ ]
798
+ },
799
+ "gpt-5.6-sol": {
800
+ canonical: "gpt-5.6-sol",
801
+ price_label: "gpt-5.6-sol",
802
+ operations: [
803
+ "chat",
804
+ "responses"
805
+ ],
806
+ reasoning_efforts: [
807
+ "none",
808
+ "low",
809
+ "medium",
810
+ "high",
811
+ "xhigh",
812
+ "max"
813
+ ],
814
+ cache: "write_priced",
815
+ tools: true,
816
+ chat_legacy_max_tokens: false,
817
+ response_models: [
818
+ "gpt-5.6-sol"
819
+ ]
820
+ },
821
+ "gpt-5.6-terra": {
822
+ canonical: "gpt-5.6-terra",
823
+ price_label: "gpt-5.6-terra",
824
+ operations: [
825
+ "chat",
826
+ "responses"
827
+ ],
828
+ reasoning_efforts: [
829
+ "none",
830
+ "low",
831
+ "medium",
832
+ "high",
833
+ "xhigh",
834
+ "max"
835
+ ],
836
+ cache: "write_priced",
837
+ tools: true,
838
+ chat_legacy_max_tokens: false,
839
+ response_models: [
840
+ "gpt-5.6-terra"
841
+ ]
842
+ },
843
+ "gpt-6-astra": {
844
+ canonical: "gpt-6-astra",
845
+ price_label: "gpt-6-astra",
846
+ operations: [
847
+ "chat",
848
+ "responses"
849
+ ],
850
+ reasoning_efforts: [
851
+ "low",
852
+ "medium",
853
+ "high",
854
+ "xhigh",
855
+ "max"
856
+ ],
857
+ cache: "write_priced",
858
+ tools: true,
859
+ chat_legacy_max_tokens: false,
860
+ response_models: [
861
+ "gpt-6-astra"
862
+ ],
863
+ chat_tools: "unsupported"
864
+ },
865
+ "gpt-6-sol": {
866
+ canonical: "gpt-6-sol",
867
+ price_label: "gpt-6-sol",
868
+ operations: [
869
+ "chat",
870
+ "responses"
871
+ ],
872
+ reasoning_efforts: [
873
+ "none",
874
+ "low",
875
+ "medium",
876
+ "high",
877
+ "xhigh",
878
+ "max"
879
+ ],
880
+ cache: "write_priced",
881
+ tools: true,
882
+ chat_legacy_max_tokens: false,
883
+ response_models: [
884
+ "gpt-6-sol"
885
+ ],
886
+ chat_tools: "reasoning_none"
887
+ },
888
+ "gpt-6-luna": {
889
+ canonical: "gpt-6-luna",
890
+ price_label: "gpt-6-luna",
891
+ operations: [
892
+ "chat",
893
+ "responses"
894
+ ],
895
+ reasoning_efforts: [
896
+ "none",
897
+ "low",
898
+ "medium",
899
+ "high",
900
+ "xhigh",
901
+ "max"
902
+ ],
903
+ cache: "write_priced",
904
+ tools: true,
905
+ chat_legacy_max_tokens: false,
906
+ response_models: [
907
+ "gpt-6-luna"
908
+ ],
909
+ chat_tools: "reasoning_none"
910
+ },
911
+ "gpt-6.1-sol": {
912
+ canonical: "gpt-6.1-sol",
913
+ price_label: "gpt-6.1-sol",
914
+ operations: [
915
+ "chat",
916
+ "responses"
917
+ ],
918
+ reasoning_efforts: [
919
+ "low",
920
+ "medium",
921
+ "high",
922
+ "xhigh",
923
+ "max"
924
+ ],
925
+ cache: "write_priced",
926
+ tools: true,
927
+ chat_legacy_max_tokens: false,
928
+ response_models: [
929
+ "gpt-6.1-sol"
930
+ ],
931
+ chat_tools: "unsupported"
932
+ }
933
+ };
934
+
935
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/codec.js
936
+ var import_node_crypto = require("crypto");
937
+ var need = (x, code) => {
938
+ if (!x)
939
+ throw new XgateError(code);
940
+ };
941
+ var object = (x) => x !== null && typeof x === "object" && !Array.isArray(x);
942
+ var rate = (x) => {
943
+ need(x && typeof x.numerator === "string" && /^[0-9]{1,13}$/.test(x.numerator) && Number(x.numerator) <= 1e12 && Number.isSafeInteger(x.denominator) && x.denominator > 0 && x.denominator <= 1e6, "invalid_catalog_rate");
944
+ return Number(x.numerator) / x.denominator;
945
+ };
946
+ function catalogEntries(rows) {
947
+ need(Array.isArray(rows) && rows.length <= 128, "invalid_catalog");
948
+ const entries = [];
949
+ for (const row of rows) {
950
+ const p = row?.execution_profile;
951
+ if (!object(p) || p.model !== row.id || !Array.isArray(row.qualified_profiles))
952
+ continue;
953
+ const anthropic = row.owned_by === "anthropic", cap = anthropic ? p.capabilities : openai_model_capabilities_default[row.id];
954
+ if (!cap || !anthropic && !cap.tools)
955
+ continue;
956
+ const op = anthropic ? "messages" : "responses";
957
+ const q = row.qualified_profiles.find((q2) => q2.model === row.id && q2.operation === op && q2.provider === (anthropic ? "anthropic" : "open_ai") && q2.normalizer_revision === (anthropic ? "anthropic-anonymous-usage-v3" : "openai-anonymous-usage-v1") && q2.transformation_revision === (anthropic ? "anthropic-anonymous-messages-v1" : "openai-anonymous-tools-v2"));
958
+ if (!q || row.privacy?.revision !== "anonymous-volatile-v1" || row.privacy.result_replay_available !== false || anthropic && q.cache_mode !== "anthropic_no_cache")
959
+ continue;
960
+ if (q.valid_until !== void 0 && Number(q.valid_until) * 1e3 <= Date.now())
961
+ continue;
962
+ if (row.lifecycle?.stop_before != null && Number(row.lifecycle.stop_before) * 1e3 <= Date.now())
963
+ continue;
964
+ const contextWindow = Math.min(p.max_input_tokens, p.provider_limits?.context_window ?? cap.context_window ?? p.max_input_tokens), maxTokens = Math.min(8192, p.max_output_tokens);
965
+ need(Number.isSafeInteger(contextWindow) && contextWindow > 0 && Number.isSafeInteger(maxTokens) && maxTokens > 0, "invalid_catalog_limits");
966
+ const efforts = anthropic ? cap.effort : cap.reasoning_efforts;
967
+ const levels = [
968
+ "minimal",
969
+ "low",
970
+ "medium",
971
+ "high",
972
+ "xhigh",
973
+ "max"
974
+ ];
975
+ const thinkingLevelMap = {
976
+ off: anthropic ? cap.thinking.disabled ? "disabled" : null : efforts.length === 0 || efforts.includes("none") ? "none" : null
977
+ };
978
+ for (const level of levels) {
979
+ const allowed = efforts.includes(level) || anthropic && cap.thinking.enabled && ["minimal", "low", "medium", "high"].includes(level);
980
+ thinkingLevelMap[level] = allowed ? level : null;
981
+ }
982
+ entries.push({
983
+ catalog: row,
984
+ route: anthropic ? "/providers/anthropic/v1/messages" : "/providers/openai/v1/responses",
985
+ efforts,
986
+ model: {
987
+ id: row.id,
988
+ name: `${row.id} (xgate)`,
989
+ api: anthropic ? "xgate-messages" : "xgate-responses",
990
+ provider: "xgate",
991
+ baseUrl: row.xgate_origin ?? "https://api.xgate.run",
992
+ input: ["text"],
993
+ contextWindow,
994
+ maxTokens,
995
+ reasoning: anthropic ? Boolean(cap.thinking?.adaptive || cap.thinking?.enabled) : efforts.some((effort) => effort !== "none"),
996
+ thinkingLevelMap,
997
+ cost: {
998
+ input: rate(p.rates.input_uncached),
999
+ output: rate(p.rates.output),
1000
+ cacheRead: rate(p.rates.input_cache_read),
1001
+ cacheWrite: p.rates.input_cache_write ? rate(p.rates.input_cache_write) : 0
1002
+ },
1003
+ inputLimits: { maxRequestBytes: 8 * 1024 * 1024 }
1004
+ }
1005
+ });
1006
+ }
1007
+ return entries;
1008
+ }
1009
+ function transcript(context) {
1010
+ const legacy = "systemPrompt" in context || "tools" in context;
1011
+ if (typeof pi.collapseSystemMessages !== "function") {
1012
+ need(!context.messages.some((m) => m.role === "system"), "unsupported_context");
1013
+ const raw = context;
1014
+ return {
1015
+ system: raw.systemPrompt ?? "",
1016
+ tools: raw.tools ?? [],
1017
+ messages: raw.messages
1018
+ };
1019
+ }
1020
+ const collapsed = pi.collapseSystemMessages(legacy ? pi.normalizeContext(context) : context);
1021
+ return {
1022
+ system: pi.getCurrentSystemPrompt(collapsed.messages),
1023
+ tools: pi.getCurrentTools(collapsed.messages),
1024
+ messages: collapsed.messages.filter((m) => m.role !== "system")
1025
+ };
1026
+ }
1027
+ function text(content) {
1028
+ if (typeof content === "string")
1029
+ return content;
1030
+ need(Array.isArray(content) && content.every((b) => b.type === "text" && typeof b.text === "string"), "text_only_request");
1031
+ return content.map((b) => b.text).join("\n");
1032
+ }
1033
+ function callId(id) {
1034
+ return /^[A-Za-z0-9_:.\-]{1,128}$/.test(id) ? id : "call_" + (0, import_node_crypto.createHash)("sha256").update(id).digest("hex").slice(0, 40);
1035
+ }
1036
+ function validateTools(tools, anthropic) {
1037
+ need(tools.length <= (anthropic ? 32 : 8), "too_many_tools");
1038
+ need(tools.every((t) => /^[A-Za-z0-9_-]{1,64}$/.test(t.name) && object(t.parameters) && t.parameters.type === "object"), "unsupported_tool_schema");
1039
+ need(new Set(tools.map((t) => t.name)).size === tools.length, "duplicate_tools");
1040
+ }
1041
+ function encode(entry, context, options = {}) {
1042
+ need(options.toolChoice === void 0 || options.toolChoice === "auto", "unsupported_tool_choice");
1043
+ need(options.reasoning === void 0 || typeof options.reasoning === "string", "unsupported_reasoning");
1044
+ need(options.temperature === void 0 && (!options.samplingParams || Object.keys(options.samplingParams).length === 0), "unsupported_sampling");
1045
+ const anthropic = entry.route.endsWith("/messages"), { system, tools, messages } = transcript(context);
1046
+ validateTools(tools, anthropic);
1047
+ const max = options.maxTokens ?? Math.min(4096, entry.model.maxTokens);
1048
+ need(Number.isSafeInteger(max) && max > 0 && max <= entry.model.maxTokens, "output_limit");
1049
+ const requested = options.reasoning, effort = requested && entry.efforts.includes(requested) ? requested : entry.efforts[0];
1050
+ if (requested)
1051
+ need(entry.model.thinkingLevelMap?.[requested] !== null && (entry.efforts.includes(requested) || anthropic && entry.catalog.execution_profile.capabilities.thinking.enabled), "unsupported_reasoning");
1052
+ const history = [];
1053
+ const append = (role, content) => {
1054
+ const previous = history.at(-1);
1055
+ if (previous?.role === role)
1056
+ previous.content.push(...content);
1057
+ else
1058
+ history.push({ role, content });
1059
+ };
1060
+ if (!anthropic && system)
1061
+ history.push({ role: "system", content: system });
1062
+ for (const message of messages) {
1063
+ if (message.role === "user") {
1064
+ const value = text(message.content);
1065
+ if (anthropic)
1066
+ append("user", [{ type: "text", text: value }]);
1067
+ else
1068
+ history.push({ role: "user", content: value });
1069
+ continue;
1070
+ }
1071
+ if (message.role === "toolResult") {
1072
+ const value = text(message.content), id = callId(message.toolCallId);
1073
+ if (anthropic)
1074
+ append("user", [
1075
+ {
1076
+ type: "tool_result",
1077
+ tool_use_id: id,
1078
+ content: value,
1079
+ ...message.isError ? { is_error: true } : {}
1080
+ }
1081
+ ]);
1082
+ else
1083
+ history.push({
1084
+ type: "function_call_output",
1085
+ call_id: id,
1086
+ output: message.isError ? "Tool error: " + value : value
1087
+ });
1088
+ continue;
1089
+ }
1090
+ need(message.role === "assistant", "unsupported_message");
1091
+ if (message.stopReason === "error" || message.stopReason === "aborted")
1092
+ continue;
1093
+ const same = message.provider === "xgate" && message.model === entry.model.id && message.api === entry.model.api;
1094
+ const blocks = [];
1095
+ for (const block of message.content) {
1096
+ if (block.type === "text") {
1097
+ if (anthropic) {
1098
+ if (block.text)
1099
+ blocks.push({ type: "text", text: block.text });
1100
+ } else if (block.text) {
1101
+ let signature;
1102
+ try {
1103
+ signature = block.textSignature ? JSON.parse(block.textSignature) : void 0;
1104
+ } catch {
1105
+ }
1106
+ const previous = history.at(-1);
1107
+ if (same && signature?.id && previous?.type === "message" && previous.id === signature.id && previous.phase === signature.phase) {
1108
+ previous.content.push({ type: "output_text", text: block.text });
1109
+ continue;
1110
+ }
1111
+ history.push({
1112
+ type: "message",
1113
+ role: "assistant",
1114
+ content: [{ type: "output_text", text: block.text }],
1115
+ ...same && signature?.id ? {
1116
+ id: signature.id,
1117
+ ...signature.phase ? { phase: signature.phase } : {}
1118
+ } : {}
1119
+ });
1120
+ }
1121
+ } else if (block.type === "toolCall") {
1122
+ need(!block.namespace && object(block.arguments), "unsupported_tool_call");
1123
+ const id = callId(block.id);
1124
+ if (anthropic) {
1125
+ need(tools.some((t) => t.name === block.name), "history_tool_not_declared");
1126
+ blocks.push({
1127
+ type: "tool_use",
1128
+ id,
1129
+ name: block.name,
1130
+ input: block.arguments
1131
+ });
1132
+ } else
1133
+ history.push({
1134
+ type: "function_call",
1135
+ call_id: id,
1136
+ name: block.name,
1137
+ arguments: JSON.stringify(block.arguments)
1138
+ });
1139
+ } else if (block.type === "thinking" && same) {
1140
+ if (anthropic) {
1141
+ need(typeof block.thinkingSignature === "string" && block.thinkingSignature.length > 0, "missing_thinking_signature");
1142
+ blocks.push(block.redacted ? { type: "redacted_thinking", data: block.thinkingSignature } : {
1143
+ type: "thinking",
1144
+ thinking: block.thinking,
1145
+ signature: block.thinkingSignature
1146
+ });
1147
+ } else if (block.thinkingSignature) {
1148
+ const reasoning = JSON.parse(block.thinkingSignature);
1149
+ need(reasoning.type === "reasoning" && typeof reasoning.encrypted_content === "string", "invalid_reasoning_history");
1150
+ history.push(reasoning);
1151
+ }
1152
+ }
1153
+ }
1154
+ if (anthropic && blocks.length)
1155
+ append("assistant", blocks);
1156
+ }
1157
+ need(history.length > 0 && history.length <= 256, "history_limit");
1158
+ let request;
1159
+ if (anthropic) {
1160
+ const cap = entry.catalog.execution_profile.capabilities;
1161
+ request = {
1162
+ model: entry.model.id,
1163
+ messages: history,
1164
+ max_tokens: max,
1165
+ stream: false,
1166
+ ...system ? { system } : {},
1167
+ ...tools.length ? {
1168
+ tools: tools.map((t) => ({
1169
+ name: t.name,
1170
+ description: t.description,
1171
+ input_schema: t.parameters
1172
+ }))
1173
+ } : {}
1174
+ };
1175
+ if (effort)
1176
+ request.output_config = { effort };
1177
+ if (cap.thinking.adaptive)
1178
+ request.thinking = { type: "adaptive" };
1179
+ else if (requested && cap.thinking.enabled) {
1180
+ need(max > 1024, "thinking_output_limit");
1181
+ request.thinking = {
1182
+ type: "enabled",
1183
+ budget_tokens: Math.min(2048, max - 1)
1184
+ };
1185
+ }
1186
+ } else
1187
+ request = {
1188
+ model: entry.model.id,
1189
+ input: history,
1190
+ max_output_tokens: max,
1191
+ stream: false,
1192
+ store: false,
1193
+ include: ["reasoning.encrypted_content"],
1194
+ ...effort ? { reasoning: { effort } } : {},
1195
+ ...tools.length ? {
1196
+ tools: tools.map((t) => ({
1197
+ type: "function",
1198
+ name: t.name,
1199
+ description: t.description,
1200
+ parameters: t.parameters
1201
+ })),
1202
+ parallel_tool_calls: false
1203
+ } : {}
1204
+ };
1205
+ if (request.tools)
1206
+ need(Buffer.byteLength(JSON.stringify(request.tools)) <= (anthropic ? 65536 : 8192), "tool_schema_bound");
1207
+ need(Buffer.byteLength(JSON.stringify(request)) <= 8 * 1024 * 1024, "request_bound");
1208
+ return request;
1209
+ }
1210
+ function tokens(value) {
1211
+ need(Number.isSafeInteger(value) && value >= 0, "invalid_usage");
1212
+ return value;
1213
+ }
1214
+ function decode(entry, body) {
1215
+ need(object(body) && typeof body.id === "string" && object(body.usage), "invalid_result");
1216
+ const anthropic = entry.route.endsWith("/messages"), content = [];
1217
+ let stopReason;
1218
+ if (anthropic) {
1219
+ need(body.type === "message" && body.role === "assistant" && body.model === entry.model.id && ["end_turn", "tool_use", "stop_sequence"].includes(body.stop_reason) && Array.isArray(body.content), "invalid_result");
1220
+ stopReason = body.stop_reason === "tool_use" ? "toolUse" : "stop";
1221
+ for (const b of body.content) {
1222
+ if (b.type === "text") {
1223
+ need(typeof b.text === "string", "invalid_text");
1224
+ content.push({ type: "text", text: b.text });
1225
+ } else if (b.type === "tool_use") {
1226
+ need(typeof b.id === "string" && typeof b.name === "string" && object(b.input), "invalid_tool_result");
1227
+ content.push({
1228
+ type: "toolCall",
1229
+ id: b.id,
1230
+ name: b.name,
1231
+ arguments: b.input
1232
+ });
1233
+ } else if (b.type === "thinking") {
1234
+ need(typeof b.thinking === "string" && typeof b.signature === "string", "invalid_thinking");
1235
+ content.push({
1236
+ type: "thinking",
1237
+ thinking: b.thinking,
1238
+ thinkingSignature: b.signature
1239
+ });
1240
+ } else if (b.type === "redacted_thinking") {
1241
+ need(typeof b.data === "string", "invalid_thinking");
1242
+ content.push({
1243
+ type: "thinking",
1244
+ thinking: "",
1245
+ thinkingSignature: b.data,
1246
+ redacted: true
1247
+ });
1248
+ } else
1249
+ throw new XgateError("unsupported_result_block");
1250
+ }
1251
+ } else {
1252
+ const cap = openai_model_capabilities_default[entry.model.id];
1253
+ need(cap.response_models.includes(body.model) && body.status === "completed" && !body.error && !body.incomplete_details && Array.isArray(body.output), "invalid_result");
1254
+ stopReason = "stop";
1255
+ for (const b of body.output) {
1256
+ if (b.type === "message") {
1257
+ need(b.status === "completed" && Array.isArray(b.content), "invalid_result");
1258
+ for (const t of b.content) {
1259
+ need(t.type === "output_text" && typeof t.text === "string", "invalid_text");
1260
+ content.push({
1261
+ type: "text",
1262
+ text: t.text,
1263
+ ...b.id ? {
1264
+ textSignature: JSON.stringify({
1265
+ v: 1,
1266
+ id: b.id,
1267
+ ...b.phase ? { phase: b.phase } : {}
1268
+ })
1269
+ } : {}
1270
+ });
1271
+ }
1272
+ } else if (b.type === "function_call") {
1273
+ need(typeof b.call_id === "string" && typeof b.name === "string" && typeof b.arguments === "string", "invalid_tool_result");
1274
+ const args = JSON.parse(b.arguments);
1275
+ need(object(args), "invalid_tool_result");
1276
+ content.push({
1277
+ type: "toolCall",
1278
+ id: b.call_id,
1279
+ name: b.name,
1280
+ arguments: args
1281
+ });
1282
+ stopReason = "toolUse";
1283
+ } else if (b.type === "reasoning") {
1284
+ need(Array.isArray(b.summary), "invalid_thinking");
1285
+ const summary = b.summary.map((s) => {
1286
+ need(s.type === "summary_text" && typeof s.text === "string", "invalid_thinking");
1287
+ return s.text;
1288
+ }).join("\n");
1289
+ need(typeof b.encrypted_content === "string" && b.encrypted_content.length > 0, "missing_encrypted_reasoning");
1290
+ content.push({
1291
+ type: "thinking",
1292
+ thinking: summary,
1293
+ thinkingSignature: JSON.stringify({
1294
+ type: "reasoning",
1295
+ id: b.id,
1296
+ summary: b.summary,
1297
+ encrypted_content: b.encrypted_content,
1298
+ ...b.status === "completed" ? { status: b.status } : {}
1299
+ })
1300
+ });
1301
+ } else
1302
+ throw new XgateError("unsupported_result_block");
1303
+ }
1304
+ }
1305
+ need(content.some((c) => c.type === "text" && c.text.length > 0 || c.type === "toolCall"), "empty_result");
1306
+ need(stopReason === "toolUse" === content.some((c) => c.type === "toolCall"), "tool_stop_mismatch");
1307
+ const u = body.usage, read = tokens(anthropic ? u.cache_read_input_tokens ?? 0 : u.input_tokens_details?.cached_tokens), write = tokens(anthropic ? u.cache_creation_input_tokens ?? 0 : u.input_tokens_details?.cache_write_tokens ?? 0), totalInput = tokens(u.input_tokens), output = tokens(u.output_tokens), input = anthropic ? totalInput : totalInput - read - write;
1308
+ need(input >= 0 && (!anthropic || read === 0 && write === 0), "cache_usage_mismatch");
1309
+ const rates = entry.model.cost;
1310
+ const cost = {
1311
+ input: input * rates.input / 1e6,
1312
+ output: output * rates.output / 1e6,
1313
+ cacheRead: read * rates.cacheRead / 1e6,
1314
+ cacheWrite: write * rates.cacheWrite / 1e6,
1315
+ total: 0
1316
+ };
1317
+ cost.total = cost.input + cost.output + cost.cacheRead + cost.cacheWrite;
1318
+ return {
1319
+ content,
1320
+ usage: {
1321
+ input,
1322
+ output,
1323
+ cacheRead: read,
1324
+ cacheWrite: write,
1325
+ totalTokens: input + read + write + output,
1326
+ cost
1327
+ },
1328
+ stopReason,
1329
+ responseId: body.id
1330
+ };
1331
+ }
1332
+
1333
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/transport.js
1334
+ init_cjs_shims();
1335
+ var XgatePurchaseError = class extends XgateError {
1336
+ invocationId;
1337
+ pending;
1338
+ payment;
1339
+ constructor(code, invocationId2, pending, payment) {
1340
+ super(code);
1341
+ this.name = "XgatePurchaseError";
1342
+ this.message = pending ? `Xgate: ${code}. The payment outcome is unknown; do not retry. Reconcile it before another purchase.` : `Xgate: ${code}. Inspect the payment status before another purchase.`;
1343
+ this.invocationId = invocationId2;
1344
+ this.pending = pending;
1345
+ if (payment)
1346
+ this.payment = payment;
1347
+ }
1348
+ };
1349
+
1350
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/provider.js
1351
+ var hash = (value) => (0, import_node_crypto2.createHash)("sha256").update(value).digest("hex");
1352
+ var zero = () => ({
1353
+ input: 0,
1354
+ output: 0,
1355
+ cacheRead: 0,
1356
+ cacheWrite: 0,
1357
+ totalTokens: 0,
1358
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
1359
+ });
1360
+ function invocationId(model, context, session) {
1361
+ const legacy = "systemPrompt" in context || "tools" in context ? { systemPrompt: context.systemPrompt, tools: context.tools } : {};
1362
+ return hash(JSON.stringify({
1363
+ session,
1364
+ model,
1365
+ messages: context.messages.filter((m) => m.role !== "assistant" || !["error", "aborted"].includes(m.stopReason)),
1366
+ ...legacy
1367
+ }));
1368
+ }
1369
+ async function createXgateProvider(transport, { sessionId: identity = () => "standalone", onPaid, onPurchaseFailed } = {}) {
1370
+ let entries = catalogEntries(await transport.models());
1371
+ const stream = (model, context, options = {}) => {
1372
+ const events = (0, import_pi_ai.createAssistantMessageEventStream)();
1373
+ const timeout = options.timeoutMs ?? 18e4;
1374
+ if (!Number.isSafeInteger(timeout) || timeout <= 0 || timeout > 18e4)
1375
+ options = { ...options, timeoutMs: 18e4 };
1376
+ const deadline = AbortSignal.timeout(Math.min(options.timeoutMs ?? 18e4, 18e4));
1377
+ options = {
1378
+ ...options,
1379
+ signal: options.signal ? AbortSignal.any([options.signal, deadline]) : deadline
1380
+ };
1381
+ const message = {
1382
+ role: "assistant",
1383
+ provider: "xgate",
1384
+ api: model.api,
1385
+ model: model.id,
1386
+ content: [],
1387
+ usage: zero(),
1388
+ stopReason: "pending",
1389
+ timestamp: Date.now()
1390
+ };
1391
+ let attempted, paid;
1392
+ void (async () => {
1393
+ try {
1394
+ options.signal?.throwIfAborted();
1395
+ const current = catalogEntries(await transport.models(options.signal)), entry = current.find((e) => e.model.id === model.id && e.model.api === model.api);
1396
+ if (!entry)
1397
+ throw new XgateError("model_not_qualified");
1398
+ const original = encode(entry, context, {
1399
+ ...options,
1400
+ // Respect a lower Pi model override without exceeding live catalog limits.
1401
+ maxTokens: options.maxTokens ?? Math.min(4096, model.maxTokens, entry.model.maxTokens)
1402
+ }), replacement = await options.onPayload?.(structuredClone(original), model), payload = replacement === void 0 ? original : replacement;
1403
+ const limit = entry.route.endsWith("/messages") ? "max_tokens" : "max_output_tokens";
1404
+ if (!payload || payload.model !== model.id || payload.stream !== false || payload[limit] !== original[limit] || JSON.stringify(payload.tools) !== JSON.stringify(original.tools) || !entry.route.endsWith("/messages") && payload.store !== false)
1405
+ throw new XgateError("payload_hook_changed_scope");
1406
+ const body = JSON.stringify(payload);
1407
+ if (Buffer.byteLength(body) > 8 * 1024 * 1024)
1408
+ throw new XgateError("request_bound");
1409
+ const id = invocationId(model.id, context, options.sessionId ?? identity());
1410
+ let observed = false;
1411
+ attempted = id;
1412
+ const result = await transport.purchase({ id, route: entry.route, body }, options.signal, async (response) => {
1413
+ observed = true;
1414
+ await options.onResponse?.(response, model);
1415
+ });
1416
+ paid = result;
1417
+ if (!observed)
1418
+ await options.onResponse?.({
1419
+ status: 200,
1420
+ headers: {
1421
+ "content-type": "application/json",
1422
+ "cache-control": "no-store"
1423
+ }
1424
+ }, model);
1425
+ const value = decode(entry, result.body);
1426
+ message.usage = value.usage;
1427
+ message.responseId = value.responseId;
1428
+ options.signal?.throwIfAborted();
1429
+ events.push({ type: "start", partial: message });
1430
+ for (const block of value.content) {
1431
+ const contentIndex = message.content.length;
1432
+ if (block.type === "text") {
1433
+ message.content.push({ ...block, text: "" });
1434
+ events.push({ type: "text_start", contentIndex, partial: message });
1435
+ message.content[contentIndex].text = block.text;
1436
+ events.push({
1437
+ type: "text_delta",
1438
+ contentIndex,
1439
+ delta: block.text,
1440
+ partial: message
1441
+ });
1442
+ events.push({
1443
+ type: "text_end",
1444
+ contentIndex,
1445
+ content: block.text,
1446
+ partial: message
1447
+ });
1448
+ } else if (block.type === "thinking") {
1449
+ message.content.push({
1450
+ ...block,
1451
+ thinking: block.redacted ? block.thinking : ""
1452
+ });
1453
+ events.push({
1454
+ type: "thinking_start",
1455
+ contentIndex,
1456
+ partial: message
1457
+ });
1458
+ if (!block.redacted) {
1459
+ message.content[contentIndex].thinking = block.thinking;
1460
+ events.push({
1461
+ type: "thinking_delta",
1462
+ contentIndex,
1463
+ delta: block.thinking,
1464
+ partial: message
1465
+ });
1466
+ }
1467
+ events.push({
1468
+ type: "thinking_end",
1469
+ contentIndex,
1470
+ content: block.thinking,
1471
+ partial: message
1472
+ });
1473
+ } else {
1474
+ message.content.push({ ...block, arguments: {} });
1475
+ events.push({
1476
+ type: "toolcall_start",
1477
+ contentIndex,
1478
+ partial: message
1479
+ });
1480
+ message.content[contentIndex].arguments = block.arguments;
1481
+ events.push({
1482
+ type: "toolcall_delta",
1483
+ contentIndex,
1484
+ delta: JSON.stringify(block.arguments),
1485
+ partial: message
1486
+ });
1487
+ events.push({
1488
+ type: "toolcall_end",
1489
+ contentIndex,
1490
+ toolCall: block,
1491
+ partial: message
1492
+ });
1493
+ }
1494
+ }
1495
+ message.stopReason = value.stopReason;
1496
+ try {
1497
+ onPaid?.(result);
1498
+ } catch {
1499
+ }
1500
+ events.push({ type: "done", reason: value.stopReason, message });
1501
+ } catch (error) {
1502
+ const aborted = options.signal?.aborted === true;
1503
+ message.stopReason = aborted ? "aborted" : "error";
1504
+ message.errorMessage = aborted ? "Xgate operation stopped. Inspect /xgate status; payment may require reconciliation." : error instanceof XgateError ? error.message : "Xgate operation stopped. Inspect /xgate status before requesting another purchase.";
1505
+ if (attempted !== void 0) {
1506
+ const payment = paid?.payment ?? (error instanceof XgatePurchaseError ? error.payment : void 0);
1507
+ const failure = {
1508
+ invocationId: attempted,
1509
+ code: error instanceof XgateError ? error.code : "purchase_failed",
1510
+ pending: paid === void 0 && !(error instanceof XgatePurchaseError && !error.pending),
1511
+ ...payment ? { payment } : {}
1512
+ };
1513
+ message.errorMessage += ` Billing invocation: ${attempted}.`;
1514
+ try {
1515
+ onPurchaseFailed?.(failure);
1516
+ } catch {
1517
+ }
1518
+ }
1519
+ events.push({
1520
+ type: "error",
1521
+ reason: message.stopReason,
1522
+ error: message
1523
+ });
1524
+ } finally {
1525
+ events.end();
1526
+ }
1527
+ })();
1528
+ return events;
1529
+ };
1530
+ return {
1531
+ id: "xgate",
1532
+ name: "xgate",
1533
+ auth: {
1534
+ apiKey: {
1535
+ name: "Policy constrained xgate wallet",
1536
+ resolve: async () => ({ auth: {}, source: "xgate wallet broker" })
1537
+ }
1538
+ },
1539
+ getModels: () => entries.map((e) => e.model),
1540
+ refreshModels: async (context) => {
1541
+ if (!context.allowNetwork)
1542
+ return;
1543
+ const updated = catalogEntries(await transport.models(context.signal));
1544
+ await context.publish({
1545
+ update: () => {
1546
+ entries = updated;
1547
+ }
1548
+ });
1549
+ },
1550
+ stream: (model, context, options) => stream(model, context, options),
1551
+ streamSimple: stream
1552
+ };
1553
+ }
1554
+
1555
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/extension.js
1556
+ init_cjs_shims();
1557
+
1558
+ // ../../node_modules/.pnpm/@lucid-agents+xgate-client@0.1.6_@solana+sysvars@5.5.1_typescript@5.7.3_zod@3.25.76/node_modules/@lucid-agents/xgate-client/dist/broker.js
1559
+ init_cjs_shims();
1560
+ var import_node_http = require("http");
1561
+ var import_node_crypto3 = require("crypto");
1562
+
1563
+ // ../../node_modules/.pnpm/@lucid-agents+xgate-client@0.1.6_@solana+sysvars@5.5.1_typescript@5.7.3_zod@3.25.76/node_modules/@lucid-agents/xgate-client/dist/http.js
1564
+ init_cjs_shims();
1565
+ var MAX_BODY = 16 * 1024 * 1024;
1566
+ async function bytes(response, limit = MAX_BODY) {
1567
+ requireValue(response.body, "missing_body");
1568
+ const reader = response.body.getReader();
1569
+ const chunks = [];
1570
+ let length = 0;
1571
+ try {
1572
+ for (; ; ) {
1573
+ const part = await reader.read();
1574
+ if (part.done)
1575
+ break;
1576
+ length += part.value.byteLength;
1577
+ requireValue(length <= limit, "body_bound");
1578
+ chunks.push(part.value);
1579
+ }
1580
+ } catch {
1581
+ await reader.cancel().catch(() => {
1582
+ });
1583
+ throw new XgateError("body_unavailable");
1584
+ } finally {
1585
+ reader.releaseLock();
1586
+ }
1587
+ return Buffer.concat(chunks, length);
1588
+ }
1589
+ async function json(response, limit = MAX_BODY) {
1590
+ try {
1591
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(await bytes(response, limit)));
1592
+ } catch {
1593
+ throw new XgateError("invalid_response");
1594
+ }
1595
+ }
1596
+ function signalWithDeadline(signal, ms = 13e4) {
1597
+ return signal ? AbortSignal.any([signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
1598
+ }
1599
+ async function http(fetcher, url, options = {}) {
1600
+ try {
1601
+ return await fetcher(url, {
1602
+ ...options,
1603
+ redirect: "error",
1604
+ cache: "no-store",
1605
+ credentials: "omit",
1606
+ referrerPolicy: "no-referrer"
1607
+ });
1608
+ } catch {
1609
+ throw new XgateError("transport_unresolved");
1610
+ }
1611
+ }
1612
+
1613
+ // ../../node_modules/.pnpm/@lucid-agents+xgate-client@0.1.6_@solana+sysvars@5.5.1_typescript@5.7.3_zod@3.25.76/node_modules/@lucid-agents/xgate-client/dist/broker.js
1614
+ var BrokerClient = class {
1615
+ token;
1616
+ fetcher;
1617
+ url;
1618
+ constructor(url, token, fetcher = fetch) {
1619
+ this.token = token;
1620
+ this.fetcher = fetcher;
1621
+ this.url = origin(url, true);
1622
+ requireValue(/^[a-f0-9]{64}$/.test(token), "invalid_broker_token");
1623
+ }
1624
+ async call(path4, body, signal, onResponse) {
1625
+ const r = await http(this.fetcher, this.url + path4, {
1626
+ method: body === void 0 ? "GET" : "POST",
1627
+ headers: {
1628
+ authorization: "Bearer " + this.token,
1629
+ ...body === void 0 ? {} : { "content-type": "application/json" }
1630
+ },
1631
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
1632
+ signal: signalWithDeadline(signal, 19e4)
1633
+ });
1634
+ if (onResponse) {
1635
+ try {
1636
+ await onResponse({
1637
+ status: r.status,
1638
+ headers: {
1639
+ "content-type": r.headers.get("content-type") ?? "application/json",
1640
+ "cache-control": "no-store"
1641
+ }
1642
+ });
1643
+ } catch (error) {
1644
+ await r.body?.cancel().catch(() => {
1645
+ });
1646
+ throw error;
1647
+ }
1648
+ }
1649
+ const v = await json(r);
1650
+ if (!r.ok)
1651
+ throw new XgateError(record(v) && typeof v.code === "string" && /^[a-z_]{1,64}$/.test(v.code) ? v.code : "broker_request_failed");
1652
+ return v;
1653
+ }
1654
+ async models(signal) {
1655
+ const v = await this.call("/models", void 0, signal);
1656
+ requireValue(record(v) && Array.isArray(v.data), "invalid_catalog");
1657
+ return v.data;
1658
+ }
1659
+ async purchase(input, signal, onResponse) {
1660
+ const v = await this.call("/purchase", input, signal, onResponse);
1661
+ requireValue(record(v) && record(v.body) && record(v.settlement) && typeof v.purchase === "string", "invalid_broker_result");
1662
+ return v;
1663
+ }
1664
+ async status(signal) {
1665
+ return this.call("/status", void 0, signal);
1666
+ }
1667
+ async receipts(signal) {
1668
+ return this.call("/receipts", void 0, signal);
1669
+ }
1670
+ async reconcile(id, signal) {
1671
+ return this.call("/reconcile", { id }, signal);
1672
+ }
1673
+ };
1674
+
1675
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/extension.js
1676
+ var import_node_fs = require("fs");
1677
+ var import_node_path = require("path");
1678
+ var import_node_os = require("os");
1679
+ function privateText(path4, max = 8192) {
1680
+ if (!(0, import_node_path.isAbsolute)(path4))
1681
+ throw new XgateError("absolute_config_path_required");
1682
+ const s = (0, import_node_fs.lstatSync)(path4);
1683
+ if (!s.isFile() || s.isSymbolicLink() || (s.mode & 63) !== 0 || s.size > max)
1684
+ throw new XgateError("private_config_required");
1685
+ return (0, import_node_fs.readFileSync)(path4, "utf8").trim();
1686
+ }
1687
+ function standalone(configPath) {
1688
+ const cfg = JSON.parse(privateText(configPath));
1689
+ if (typeof cfg.url !== "string" || typeof cfg.tokenFile !== "string")
1690
+ throw new XgateError("invalid_config");
1691
+ return new BrokerClient(cfg.url, privateText(cfg.tokenFile, 128));
1692
+ }
1693
+ function paymentStatus(p) {
1694
+ const left = p.channel ? `; channel ${p.channel.refundableAtomic} refundable` : "";
1695
+ return `xgate paid ${p.chargedAtomic ?? "?"}/${p.authorizedAtomic} ${p.asset} on ${p.network} (${p.scheme})${left}`;
1696
+ }
1697
+ function createXgateExtension(options = {}) {
1698
+ return (pi2) => register(pi2, options);
1699
+ }
1700
+ var extension_default = createXgateExtension();
1701
+ async function register(pi2, options) {
1702
+ const injected = options.transport;
1703
+ const configPath = process.env.XGATE_CONFIG ?? (0, import_node_path.join)((0, import_node_os.homedir)(), ".pi", "agent", "xgate.json");
1704
+ let broker;
1705
+ let context;
1706
+ const load = async () => {
1707
+ const next = injected === void 0 ? standalone(configPath) : typeof injected === "function" ? await injected() : injected;
1708
+ const provider = await createXgateProvider(next, {
1709
+ sessionId: () => context?.sessionManager.getSessionId() ?? "standalone",
1710
+ onPaid: (r) => context?.ui.setStatus("xgate", r.payment ? paymentStatus(r.payment) : `xgate paid ${(Number(r.settlement.chargedAtomic) / 1e6).toFixed(6)}`),
1711
+ onPurchaseFailed: (f) => context?.ui.setStatus("xgate", `xgate ${f.pending ? "unresolved" : "failed"}: ${f.invocationId}`)
1712
+ });
1713
+ pi2.registerProvider(provider);
1714
+ broker = next;
1715
+ };
1716
+ try {
1717
+ await load();
1718
+ } catch {
1719
+ }
1720
+ pi2.on("session_start", async (_event, ctx) => {
1721
+ context = ctx;
1722
+ ctx.ui.setStatus("xgate", broker ? "xgate wallet ready" : "xgate: /xgate refresh or /xgate setup");
1723
+ });
1724
+ pi2.on("cache_warming_decision", async (event, ctx) => ctx.model?.provider === "xgate" ? { action: "stop" } : void 0);
1725
+ pi2.registerCommand("xgate", {
1726
+ description: "Set up the wallet broker; show budget or reconcile an existing purchase.",
1727
+ handler: async (args, ctx) => {
1728
+ context = ctx;
1729
+ const [command, id] = args.trim().split(/\s+/);
1730
+ try {
1731
+ if (command === "setup") {
1732
+ if (injected !== void 0)
1733
+ throw new XgateError("transport_managed_by_host");
1734
+ if (!ctx.hasUI)
1735
+ throw new XgateError("configure_XGATE_CONFIG_for_headless_mode");
1736
+ const url = await ctx.ui.input("xgate wallet service", "http://127.0.0.1:4021");
1737
+ if (!url)
1738
+ return;
1739
+ const tokenFile = await ctx.ui.input("Absolute path to the broker token file", "/private/path/broker-token");
1740
+ if (!tokenFile)
1741
+ return;
1742
+ const next = new BrokerClient(url, privateText(tokenFile, 128));
1743
+ await next.status();
1744
+ (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(configPath), { recursive: true, mode: 448 });
1745
+ (0, import_node_fs.writeFileSync)(configPath, JSON.stringify({ url, tokenFile }) + "\n", {
1746
+ mode: 384,
1747
+ flag: "wx"
1748
+ });
1749
+ await load();
1750
+ ctx.ui.notify("xgate configured. Select a qualified model with /model.", "info");
1751
+ return;
1752
+ }
1753
+ if (command === "refresh") {
1754
+ await load();
1755
+ ctx.ui.notify("xgate model list refreshed.", "info");
1756
+ return;
1757
+ }
1758
+ if (!broker)
1759
+ throw new XgateError("wallet_not_configured");
1760
+ if (command === "reconcile") {
1761
+ if (!id)
1762
+ throw new XgateError("purchase_id_required");
1763
+ if (!broker.reconcile)
1764
+ throw new XgateError("unsupported_by_transport");
1765
+ const result = await broker.reconcile(id);
1766
+ ctx.ui.notify(JSON.stringify(result), "info");
1767
+ return;
1768
+ }
1769
+ if (command === "receipts") {
1770
+ if (!broker.receipts)
1771
+ throw new XgateError("unsupported_by_transport");
1772
+ ctx.ui.notify(JSON.stringify(await broker.receipts(), null, 2), "info");
1773
+ return;
1774
+ }
1775
+ if (command === "status" || command === "budget" || !command) {
1776
+ if (!broker.status)
1777
+ throw new XgateError("unsupported_by_transport");
1778
+ const status = await broker.status();
1779
+ ctx.ui.notify(JSON.stringify(status, null, 2), "info");
1780
+ return;
1781
+ }
1782
+ ctx.ui.notify("Use /xgate setup, refresh, status, budget, receipts or reconcile <invocation ID>. Budgets are configured at the wallet service.", "info");
1783
+ } catch (error) {
1784
+ ctx.ui.notify(error instanceof XgateError ? error.message : "xgate setup failed; check the private configuration and wallet service.", "error");
1785
+ }
1786
+ }
1787
+ });
1788
+ }
1789
+
1790
+ // ../../node_modules/.pnpm/@lucid-agents+pi-xgate@0.1.6_@earendil-works+pi-ai@0.85.1_@earendil-works+pi-coding-agent@0.8_344x6vs3jrzh5eh3xewwgv3ik4/node_modules/@lucid-agents/pi-xgate/dist/taskmarket.js
1791
+ init_cjs_shims();
1792
+ var CATALOG_BYTES = 2 * 1024 * 1024;
1793
+ var REQUEST_BYTES = 8 * 1024 * 1024;
1794
+
1795
+ // ../../packages/agent-host/dist/index.js
1796
+ init_cjs_shims();
1797
+
1798
+ // ../../packages/agent-host/dist/context.js
1799
+ init_cjs_shims();
1800
+
1801
+ // ../../packages/agent-host/dist/custody.js
1802
+ init_cjs_shims();
1803
+ var import_node_util = require("util");
1804
+
1805
+ // ../../packages/agent-host/dist/redact.js
1806
+ init_cjs_shims();
1807
+ var REDACTED = "[REDACTED]";
1808
+ var MIN_SECRET_LENGTH = 8;
1809
+ var MIN_PEM_LINE_LENGTH = 16;
1810
+ var PEM_WRAP_WIDTHS = [64, 70, 76];
1811
+ function escapeRegExp(value) {
1812
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1813
+ }
1814
+ var toUrlSafe = (b64) => b64.replace(/\+/g, "-").replace(/\//g, "_");
1815
+ function base64Forms(bytes2) {
1816
+ const forms = [];
1817
+ const padded = bytes2.toString("base64");
1818
+ forms.push(padded, padded.replace(/=+$/, ""));
1819
+ const skip = [0, 2, 3];
1820
+ for (let offset = 0; offset < 3; offset++) {
1821
+ const encoded = Buffer.concat([Buffer.alloc(offset), bytes2]).toString("base64").replace(/=+$/, "");
1822
+ forms.push(encoded.slice(skip[offset], Math.floor((offset + bytes2.length) * 8 / 6)));
1823
+ }
1824
+ return [...forms, ...forms.map(toUrlSafe)];
1825
+ }
1826
+ function wrap(text2, width) {
1827
+ const lines2 = [];
1828
+ for (let i = 0; i < text2.length; i += width)
1829
+ lines2.push(text2.slice(i, i + width));
1830
+ return lines2;
1831
+ }
1832
+ function secretVariants(secret) {
1833
+ const variants = /* @__PURE__ */ new Set();
1834
+ const trimmed = secret.trim();
1835
+ const bases = /* @__PURE__ */ new Set([secret, trimmed]);
1836
+ if (/^0x[0-9a-fA-F]+$/.test(trimmed))
1837
+ bases.add(trimmed.slice(2));
1838
+ for (const base of bases) {
1839
+ const bytes2 = Buffer.from(base, "utf8");
1840
+ const hex = bytes2.toString("hex");
1841
+ for (const form of [
1842
+ base,
1843
+ ...base64Forms(bytes2),
1844
+ encodeURIComponent(base),
1845
+ hex,
1846
+ hex.toUpperCase(),
1847
+ JSON.stringify(base).slice(1, -1)
1848
+ ]) {
1849
+ variants.add(form);
1850
+ }
1851
+ }
1852
+ if (trimmed.includes("-----BEGIN ")) {
1853
+ const bodyLines = trimmed.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("-----"));
1854
+ for (const line of bodyLines) {
1855
+ if (line.length >= MIN_PEM_LINE_LENGTH)
1856
+ variants.add(line);
1857
+ }
1858
+ const body = bodyLines.join("");
1859
+ variants.add(body);
1860
+ for (const width of PEM_WRAP_WIDTHS) {
1861
+ const lines2 = wrap(body, width);
1862
+ variants.add(lines2.join("\n"));
1863
+ variants.add(lines2.join("\r\n"));
1864
+ }
1865
+ }
1866
+ return [...variants].filter((variant) => variant.length >= MIN_SECRET_LENGTH);
1867
+ }
1868
+ function createRedactor(secrets) {
1869
+ const variants = /* @__PURE__ */ new Set();
1870
+ for (const secret of secrets) {
1871
+ if (secret.trim().length < MIN_SECRET_LENGTH)
1872
+ continue;
1873
+ for (const variant of secretVariants(secret))
1874
+ variants.add(variant);
1875
+ }
1876
+ if (variants.size === 0)
1877
+ return (text2) => text2;
1878
+ const ordered = [...variants].sort((a, b) => b.length - a.length);
1879
+ const pattern = new RegExp(ordered.map(escapeRegExp).join("|"), "gi");
1880
+ return (text2) => text2.replace(pattern, REDACTED);
1881
+ }
1882
+
1883
+ // ../../packages/agent-host/dist/custody.js
1884
+ var CustodyError = class extends Error {
1885
+ constructor(message) {
1886
+ super(message);
1887
+ this.name = "CustodyError";
1888
+ }
1889
+ };
1890
+ var ControllerCustody = class {
1891
+ #wallets = /* @__PURE__ */ new Map();
1892
+ #handles = /* @__PURE__ */ new Map();
1893
+ #secrets = /* @__PURE__ */ new Set();
1894
+ #apiToken;
1895
+ #sandbox;
1896
+ #redactor = (text2) => text2;
1897
+ /** Adds a rail wallet. A rail holds one wallet; replacing it needs an explicit `removeWallet`. */
1898
+ addWallet(wallet) {
1899
+ if (this.#wallets.has(wallet.rail)) {
1900
+ throw new CustodyError(`A wallet is already held for rail ${wallet.rail}`);
1901
+ }
1902
+ for (const secret of wallet.secrets ?? [])
1903
+ this.addSecret(secret);
1904
+ this.#wallets.set(wallet.rail, { ...wallet, secrets: void 0 });
1905
+ }
1906
+ removeWallet(rail) {
1907
+ return this.#wallets.delete(rail);
1908
+ }
1909
+ wallet(rail) {
1910
+ return this.#wallets.get(rail);
1911
+ }
1912
+ rails() {
1913
+ return [...this.#wallets.keys()];
1914
+ }
1915
+ setApiToken(apiToken) {
1916
+ this.addSecret(apiToken);
1917
+ this.#apiToken = apiToken;
1918
+ }
1919
+ apiToken() {
1920
+ if (!this.#apiToken)
1921
+ throw new CustodyError("No apiToken is held");
1922
+ return this.#apiToken;
1923
+ }
1924
+ setSandboxCredentials(credentials) {
1925
+ this.addSecret(credentials.apiKey);
1926
+ this.addSecret(credentials.sshPrivateKey);
1927
+ this.#sandbox = { ...credentials };
1928
+ }
1929
+ sandboxCredentials() {
1930
+ if (!this.#sandbox)
1931
+ throw new CustodyError("No sandbox credentials are held");
1932
+ return { ...this.#sandbox };
1933
+ }
1934
+ /** Stores an opaque controller-side handle, such as the x402 payer or a channel state store. */
1935
+ setHandle(name, handle) {
1936
+ this.#handles.set(name, handle);
1937
+ }
1938
+ handle(name) {
1939
+ return this.#handles.get(name);
1940
+ }
1941
+ /** Registers any other secret value (a provider key, a session token) for redaction. */
1942
+ addSecret(secret) {
1943
+ if (secret.trim().length < MIN_SECRET_LENGTH) {
1944
+ throw new CustodyError(`Secrets must be at least ${MIN_SECRET_LENGTH} characters`);
1945
+ }
1946
+ if (this.#secrets.has(secret))
1947
+ return;
1948
+ this.#secrets.add(secret);
1949
+ this.#redactor = createRedactor(this.#secrets);
1950
+ }
1951
+ /** Scrubs every held secret from a string (a tool result, a log line, an error message). */
1952
+ redact(text2) {
1953
+ return this.#redactor(text2);
1954
+ }
1955
+ /** The current redactor, as a plain function that can be handed to a seam. */
1956
+ redactor() {
1957
+ return this.#redactor;
1958
+ }
1959
+ summary() {
1960
+ return {
1961
+ rails: [...this.#wallets.values()].map(({ rail, address }) => ({ rail, address })),
1962
+ hasApiToken: this.#apiToken !== void 0,
1963
+ hasSandboxCredentials: this.#sandbox !== void 0,
1964
+ handles: [...this.#handles.keys()]
1965
+ };
1966
+ }
1967
+ toJSON() {
1968
+ return this.summary();
1969
+ }
1970
+ [import_node_util.inspect.custom]() {
1971
+ return `ControllerCustody ${JSON.stringify(this.summary())}`;
1972
+ }
1973
+ };
1974
+
1975
+ // ../../packages/agent-host/dist/env.js
1976
+ init_cjs_shims();
1977
+
1978
+ // ../../packages/agent-host/dist/home.js
1979
+ init_cjs_shims();
1980
+ var import_node_os2 = __toESM(require("os"), 1);
1981
+ var import_node_path2 = __toESM(require("path"), 1);
1982
+
1983
+ // ../../packages/agent-host/dist/launch.js
1984
+ init_cjs_shims();
1985
+ var import_node_fs2 = require("fs");
1986
+ var import_node_path3 = __toESM(require("path"), 1);
1987
+ var import_node_url = require("url");
1988
+
1989
+ // ../../packages/agent-host/dist/lockdown-extension.js
1990
+ init_cjs_shims();
1991
+
1992
+ // ../../packages/agent-host/dist/tools.js
1993
+ init_cjs_shims();
1994
+
1995
+ // ../../packages/agent-host/dist/secrets-channel.js
1996
+ init_cjs_shims();
1997
+ var import_node_net = __toESM(require("net"), 1);
1998
+ var MAX_SECRETS_PAYLOAD_BYTES = 1024 * 1024;
1999
+
2000
+ // ../../packages/agent-host/dist/launch.js
2001
+ var INFERENCE_CHANNEL_FDS_ENV = "TASKMARKET_PI_INFERENCE_FDS";
2002
+ var here = import_node_path3.default.dirname((0, import_node_url.fileURLToPath)(importMetaUrl));
2003
+
2004
+ // ../../packages/agent-host/dist/sdk.js
2005
+ init_cjs_shims();
2006
+ var import_node_path4 = __toESM(require("path"), 1);
2007
+ var import_pi_coding_agent = require("@earendil-works/pi-coding-agent");
2008
+
2009
+ // src/lib/agent/budget-ui.ts
2010
+ init_cjs_shims();
2011
+
2012
+ // src/lib/agent/budget-view.ts
2013
+ init_cjs_shims();
2014
+ var USDC_DECIMALS = 6;
2015
+ function formatUsdc(atomic2) {
2016
+ let value;
2017
+ try {
2018
+ value = typeof atomic2 === "bigint" ? atomic2 : BigInt(atomic2);
2019
+ } catch {
2020
+ return "$?";
2021
+ }
2022
+ const negative = value < 0n;
2023
+ const abs = negative ? -value : value;
2024
+ const scale = 10n ** BigInt(USDC_DECIMALS);
2025
+ const fraction = (abs % scale).toString().padStart(USDC_DECIMALS, "0").replace(/0+$/, "");
2026
+ return `${negative ? "-" : ""}$${abs / scale}.${fraction.padEnd(2, "0")}`;
2027
+ }
2028
+ function formatCredits(value) {
2029
+ const number = Number(value);
2030
+ if (!Number.isFinite(number)) return value;
2031
+ return number >= 100 ? number.toFixed(0) : number.toFixed(1);
2032
+ }
2033
+ function remainingBudget(view) {
2034
+ const channels = view.channels.filter((channel) => channel.state === "open" && !channel.retired).reduce(
2035
+ (sum, channel) => sum + BigInt(channel.amounts.refundable) + BigInt(channel.amounts.lifetimeRoom),
2036
+ 0n
2037
+ );
2038
+ if (!view.budget) return channels;
2039
+ const left = BigInt(view.budget.cap) - BigInt(view.budget.used);
2040
+ const budget = left > 0n ? left : 0n;
2041
+ return channels < budget ? channels : budget;
2042
+ }
2043
+ function blockingPurchases(view) {
2044
+ const ids = new Set(view.unresolved);
2045
+ for (const channel of view.channels) {
2046
+ if (channel.pendingOperation?.kind === "payment") ids.add(channel.pendingOperation.id);
2047
+ }
2048
+ return [...ids];
2049
+ }
2050
+ function statusBarText(view) {
2051
+ const parts = [];
2052
+ parts.push(view.lastTurn ? `turn ${formatUsdc(view.lastTurn.chargedAtomic)}` : "turn -");
2053
+ const active = view.channels.filter((channel) => !channel.retired);
2054
+ if (active.length > 0) {
2055
+ const open = active.some((channel) => channel.state === "open");
2056
+ parts.push(
2057
+ open ? `budget ${formatUsdc(remainingBudget(view))} left` : `channel ${active[0].state.replace("_", " ")}`
2058
+ );
2059
+ }
2060
+ const compute = view.compute;
2061
+ if (compute?.configured && compute.availableCredits !== null) {
2062
+ const burn = compute.burnCreditsPerHour !== null ? ` at ${formatCredits(compute.burnCreditsPerHour)}/h` : "";
2063
+ parts.push(
2064
+ `compute ${formatCredits(compute.availableCredits)} cr${burn}${compute.low ? " LOW: /credits" : ""}`
2065
+ );
2066
+ } else if (compute && !compute.configured) {
2067
+ parts.push("compute: not set up");
2068
+ }
2069
+ const blocking = blockingPurchases(view);
2070
+ if (blocking.length > 0) {
2071
+ const id = blocking[0].length > 12 ? `${blocking[0].slice(0, 12)}...` : blocking[0];
2072
+ parts.push(`purchase ${id} unresolved: new turns blocked, see /budget`);
2073
+ }
2074
+ return parts.join(" | ");
2075
+ }
2076
+ function channelLines(channel) {
2077
+ const a = channel.amounts;
2078
+ return [
2079
+ `Channel ${channel.rail}${channel.retired ? " (retired)" : ""} ${channel.channelId} (${channel.network}, ${channel.route}): ${channel.state.replace("_", " ")}`,
2080
+ ` Locked ${formatUsdc(a.locked)} (deposited, not spent); charged ${formatUsdc(a.charged)}; pending vouchers ${formatUsdc(a.pending)}; refunded ${formatUsdc(a.refunded)}`,
2081
+ ` Refundable ${formatUsdc(a.refundable)}: what further turns can use and a close returns`,
2082
+ ` Budget ${formatUsdc(a.budget)}; ${formatUsdc(a.lifetimeRoom)} may still be deposited; next deposit ${formatUsdc(a.depositTarget)}${Number(a.depositing) > 0 ? `; ${formatUsdc(a.depositing)} being deposited` : ""}`,
2083
+ ...channel.pendingOperation ? [
2084
+ channel.pendingOperation.kind === "payment" ? ` Purchase ${channel.pendingOperation.id} is unresolved and blocks new turns: taskmarket agent reconcile ${channel.pendingOperation.id}` : ` A refund or withdrawal (${channel.pendingOperation.id}) is unresolved: taskmarket agent close checks it again`
2085
+ ] : [],
2086
+ ...channel.blockingDivergences.length > 0 ? [
2087
+ ` Blocked: the journal, the router and the chain disagree (${channel.blockingDivergences.join(", ")})`
2088
+ ] : []
2089
+ ];
2090
+ }
2091
+ function budgetLines(view) {
2092
+ const lines2 = [
2093
+ `This session: ${view.session.turns} paid turn${view.session.turns === 1 ? "" : "s"}, ${formatUsdc(view.session.chargedAtomic)}${view.lastTurn ? `; last turn ${formatUsdc(view.lastTurn.chargedAtomic)}` : ""}`
2094
+ ];
2095
+ for (const channel of view.channels) lines2.push(...channelLines(channel));
2096
+ for (const allocation of view.allocations) {
2097
+ lines2.push(
2098
+ `Allocation ${allocation.allocationId} (${allocation.exposure})${allocation.closed ? ", closed" : ""}: used ${formatUsdc(allocation.used.total)} of ${formatUsdc(allocation.caps.amount)}${allocation.caps.perDay ? `; today ${formatUsdc(allocation.used.today)} of ${formatUsdc(allocation.caps.perDay)}` : ""}`
2099
+ );
2100
+ }
2101
+ for (const id of blockingPurchases(view)) {
2102
+ lines2.push(uncertainPurchaseMessage(id));
2103
+ }
2104
+ const compute = view.compute;
2105
+ if (compute) lines2.push(...computeLines(compute));
2106
+ return lines2;
2107
+ }
2108
+ function computeLines(compute) {
2109
+ if (!compute.configured) {
2110
+ return ["Compute credit: not set up; run taskmarket agent credits setup"];
2111
+ }
2112
+ if (compute.error !== void 0 || compute.availableCredits === null) {
2113
+ return [`Compute credit: unavailable (${compute.error ?? "not read"})`];
2114
+ }
2115
+ return [
2116
+ `Compute credit: ${formatCredits(compute.availableCredits)} available${compute.burnCreditsPerHour !== null ? `, burning ${formatCredits(compute.burnCreditsPerHour)} an hour while the sandbox runs` : ""}${compute.low ? ". Low: buy more with /credits" : ""}`,
2117
+ ...compute.pendingPurchases > 0 ? [
2118
+ ` ${compute.pendingPurchases} purchase(s) not settled yet: taskmarket agent credits reconcile`
2119
+ ] : [],
2120
+ ...compute.autoTopUp ? [
2121
+ ` Auto-top-up: $${compute.autoTopUp.amountUsd} below ${compute.autoTopUp.thresholdCredits} credits, at most ${compute.autoTopUp.maxChunksPerDay} a day`
2122
+ ] : []
2123
+ ];
2124
+ }
2125
+ var LOST_RESPONSE_TEXT = "It was charged, and the response cannot be recovered or regenerated: xgate delivers it live only and keeps no copy. Asking again is a new paid turn.";
2126
+ function uncertainPurchaseMessage(invocationId2) {
2127
+ return `The outcome of purchase ${invocationId2} is unknown. It is never sent again, and new turns on its channel are blocked until it is reconciled: taskmarket agent reconcile ${invocationId2}. If it was charged, its response cannot be recovered or regenerated.`;
2128
+ }
2129
+ var CHARGED_UNDELIVERED = /* @__PURE__ */ new Set([
2130
+ "result_too_large",
2131
+ "response_rejected",
2132
+ "invalid_response",
2133
+ "response_hook_failed"
2134
+ ]);
2135
+ function purchaseFailureNotice(failure) {
2136
+ if (failure.pending) {
2137
+ return {
2138
+ level: "warning",
2139
+ text: uncertainPurchaseMessage(failure.invocationId || "(unknown)")
2140
+ };
2141
+ }
2142
+ const charged = failure.payment?.chargedAtomic;
2143
+ if (charged !== void 0 || CHARGED_UNDELIVERED.has(failure.code)) {
2144
+ return {
2145
+ level: "error",
2146
+ text: `This turn was paid${charged !== void 0 ? ` (${formatUsdc(charged)})` : ""} but its response was lost (${failure.code}). ${LOST_RESPONSE_TEXT}`
2147
+ };
2148
+ }
2149
+ return void 0;
2150
+ }
2151
+
2152
+ // src/lib/agent/budget-ui.ts
2153
+ var BUDGET_STATUS_KEY = "xgate-taskmarket";
2154
+ function isBudgetView(value) {
2155
+ const view = value;
2156
+ return !!view && view.version === 1 && Array.isArray(view.channels) && Array.isArray(view.unresolved) && Array.isArray(view.allocations) && typeof view.session === "object";
2157
+ }
2158
+ function errorCode(error) {
2159
+ const code = error?.code;
2160
+ return typeof code === "string" ? code : "controller_unavailable";
2161
+ }
2162
+ function withPurchaseNotices(transport, notify) {
2163
+ const wrapped = {
2164
+ models: (signal) => transport.models(signal),
2165
+ async purchase(invocation, signal, onResponse) {
2166
+ try {
2167
+ return await transport.purchase(invocation, signal, onResponse);
2168
+ } catch (error) {
2169
+ const failure = error;
2170
+ if (typeof failure?.pending === "boolean" && typeof failure.code === "string") {
2171
+ const notice = purchaseFailureNotice({
2172
+ code: failure.code,
2173
+ invocationId: typeof failure.invocationId === "string" && failure.invocationId ? failure.invocationId : invocation.id,
2174
+ pending: failure.pending,
2175
+ ...failure.payment ? { payment: failure.payment } : {}
2176
+ });
2177
+ if (notice) notify(notice.text, notice.level);
2178
+ }
2179
+ throw error;
2180
+ }
2181
+ }
2182
+ };
2183
+ if (transport.status) wrapped.status = (signal) => transport.status(signal);
2184
+ if (transport.receipts) wrapped.receipts = (signal) => transport.receipts(signal);
2185
+ if (transport.reconcile) {
2186
+ wrapped.reconcile = (id, signal) => transport.reconcile(id, signal);
2187
+ }
2188
+ return wrapped;
2189
+ }
2190
+ function isOffer(value) {
2191
+ const offer = value;
2192
+ return !!offer && typeof offer.usdPerCredit === "string" && Array.isArray(offer.denominations) && offer.denominations.every(
2193
+ (entry) => Number.isSafeInteger(entry?.amountUsd) && typeof entry?.credits === "string"
2194
+ );
2195
+ }
2196
+ function registerBudgetUi(pi2, channel) {
2197
+ let context;
2198
+ let inFlight;
2199
+ const read = async () => {
2200
+ if (!channel) throw Object.assign(new Error("unavailable"), { code: "controller_unavailable" });
2201
+ const value = await channel.budget();
2202
+ if (!isBudgetView(value)) throw Object.assign(new Error("invalid"), { code: "invalid_budget" });
2203
+ return value;
2204
+ };
2205
+ const refresh = (ctx) => {
2206
+ if (ctx) context = ctx;
2207
+ inFlight ??= read().then((view) => {
2208
+ context?.ui.setStatus(BUDGET_STATUS_KEY, statusBarText(view));
2209
+ return view;
2210
+ }).catch(() => {
2211
+ context?.ui.setStatus(BUDGET_STATUS_KEY, "budget unavailable");
2212
+ return void 0;
2213
+ }).finally(() => {
2214
+ inFlight = void 0;
2215
+ });
2216
+ return inFlight;
2217
+ };
2218
+ pi2.on("session_start", async (_event, ctx) => {
2219
+ await refresh(ctx);
2220
+ });
2221
+ pi2.on("turn_end", async (_event, ctx) => {
2222
+ await refresh(ctx);
2223
+ });
2224
+ pi2.registerCommand("budget", {
2225
+ description: "Show what this session cost, the channel (locked, charged, pending vouchers, refundable), allocations, unresolved purchases and compute credit",
2226
+ handler: async (_args, ctx) => {
2227
+ context = ctx;
2228
+ try {
2229
+ const view = await read();
2230
+ ctx.ui.setStatus(BUDGET_STATUS_KEY, statusBarText(view));
2231
+ ctx.ui.notify(budgetLines(view).join("\n"), "info");
2232
+ } catch (error) {
2233
+ ctx.ui.notify(`The budget is unavailable (${errorCode(error)})`, "error");
2234
+ }
2235
+ }
2236
+ });
2237
+ pi2.registerCommand("credits", {
2238
+ description: "Show compute credit and buy a chunk from your compute allocation (asks first; /credits <usd> picks the size)",
2239
+ handler: async (args, ctx) => {
2240
+ context = ctx;
2241
+ if (!channel) {
2242
+ ctx.ui.notify("Compute credit is unavailable (controller_unavailable)", "error");
2243
+ return;
2244
+ }
2245
+ try {
2246
+ const view = await read();
2247
+ if (view.compute) ctx.ui.notify(computeLines(view.compute).join("\n"), "info");
2248
+ if (view.compute && !view.compute.configured) return;
2249
+ const offer = await channel.creditOffer();
2250
+ if (!isOffer(offer) || offer.denominations.length === 0) {
2251
+ ctx.ui.notify("Compute credit is not on sale right now", "error");
2252
+ return;
2253
+ }
2254
+ const requested = args.trim().replace(/^\$/, "");
2255
+ const size = requested ? offer.denominations.find((entry) => String(entry.amountUsd) === requested) : offer.denominations.find((entry) => entry.default) ?? offer.denominations[0];
2256
+ if (!size) {
2257
+ ctx.ui.notify(
2258
+ `Compute credit is sold in $${offer.denominations.map((entry) => entry.amountUsd).join(", $")} chunks`,
2259
+ "error"
2260
+ );
2261
+ return;
2262
+ }
2263
+ if (!ctx.hasUI) {
2264
+ ctx.ui.notify("Buying compute credit needs the interactive session", "error");
2265
+ return;
2266
+ }
2267
+ const approved = await ctx.ui.confirm(
2268
+ "Buy compute credit",
2269
+ `Buy $${size.amountUsd} of compute credit (${size.credits} credits at $${offer.usdPerCredit} each) in USDC from your compute allocation? Its daily and monthly caps apply.`
2270
+ );
2271
+ if (!approved) return;
2272
+ const bought = await channel.buyCredits(size.amountUsd);
2273
+ ctx.ui.notify(
2274
+ `Bought ${bought?.purchase?.credits ?? size.credits} credits; ${bought?.balance?.availableCredits ?? "?"} available`,
2275
+ "info"
2276
+ );
2277
+ await refresh(ctx);
2278
+ } catch (error) {
2279
+ const code = errorCode(error);
2280
+ ctx.ui.notify(
2281
+ code === "purchase_pending" ? "Nothing was bought: an earlier compute purchase may have been paid and is not settled yet. Run taskmarket agent credits reconcile; it never pays again." : code === "controller_unavailable" || code === "aborted" ? "The controller did not answer, so the purchase may still complete. It is never repeated automatically; check with /budget or taskmarket agent credits status." : `Nothing was bought (${code})`,
2282
+ "error"
2283
+ );
2284
+ }
2285
+ }
2286
+ });
2287
+ return { refresh };
2288
+ }
2289
+
2290
+ // src/lib/agent/inference-channel.ts
2291
+ init_cjs_shims();
2292
+ var import_net = __toESM(require("net"), 1);
2293
+ var MAX_MESSAGE_BYTES = 48 * 1024 * 1024;
2294
+ var VIEW_TIMEOUT_MS = 6e4;
2295
+ var BUY_TIMEOUT_MS = 5 * 6e4;
2296
+ var CODE = /^[a-z0-9_]{1,64}$/;
2297
+ function lines(stream, onLine, onOverflow, maxBytes) {
2298
+ let chunks = [];
2299
+ let size = 0;
2300
+ let discarding = false;
2301
+ const head = (rest) => Buffer.concat([...chunks, rest]).subarray(0, 64).toString("utf8");
2302
+ stream.on("data", (chunk) => {
2303
+ let data = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
2304
+ for (let i = data.indexOf(10); i >= 0; i = data.indexOf(10)) {
2305
+ if (discarding) {
2306
+ discarding = false;
2307
+ } else if (size + i > maxBytes) {
2308
+ onOverflow(head(data.subarray(0, i)));
2309
+ } else {
2310
+ const line = Buffer.concat([...chunks, data.subarray(0, i)]).toString("utf8");
2311
+ if (line.trim()) onLine(line);
2312
+ }
2313
+ chunks = [];
2314
+ size = 0;
2315
+ data = data.subarray(i + 1);
2316
+ }
2317
+ if (data.length === 0 || discarding) return;
2318
+ if (size + data.length > maxBytes) {
2319
+ onOverflow(head(data));
2320
+ chunks = [];
2321
+ size = 0;
2322
+ discarding = true;
2323
+ return;
2324
+ }
2325
+ chunks.push(data);
2326
+ size += data.length;
2327
+ });
2328
+ }
2329
+ function wireToError(wire, invocationId2) {
2330
+ const e = wire ?? {};
2331
+ const code = typeof e.code === "string" && CODE.test(e.code) ? e.code : "controller_failed";
2332
+ if (invocationId2 !== void 0) {
2333
+ return new XgatePurchaseError(
2334
+ code,
2335
+ invocationId2,
2336
+ e.pending !== false,
2337
+ e.payment && typeof e.payment === "object" ? e.payment : void 0
2338
+ );
2339
+ }
2340
+ return new XgateError(code);
2341
+ }
2342
+ var ChannelXgateTransport = class _ChannelXgateTransport {
2343
+ /** `replies` carries the controller's answers; `requests` carries Pi's requests to it. */
2344
+ constructor(replies, requests, options = {}) {
2345
+ this.requests = requests;
2346
+ this.maxBytes = options.maxMessageBytes ?? MAX_MESSAGE_BYTES;
2347
+ lines(
2348
+ replies,
2349
+ (line) => this.onLine(line),
2350
+ () => this.fail("the controller sent an oversized message"),
2351
+ this.maxBytes
2352
+ );
2353
+ for (const stream of [replies, requests]) {
2354
+ stream.on("error", (error) => this.fail(`the inference channel failed: ${error.message}`));
2355
+ stream.on("close", () => this.fail("the controller closed the inference channel"));
2356
+ }
2357
+ replies.on("end", () => this.fail("the controller closed the inference channel"));
2358
+ }
2359
+ nextId = 1;
2360
+ pending = /* @__PURE__ */ new Map();
2361
+ closedReason;
2362
+ closeListeners = [];
2363
+ maxBytes;
2364
+ /** Opens the inherited descriptors the launcher named. */
2365
+ static fromFds(fds) {
2366
+ const requests = new import_net.default.Socket({ fd: fds.request, readable: false, writable: true });
2367
+ const replies = new import_net.default.Socket({ fd: fds.reply, readable: true, writable: false });
2368
+ requests.unref();
2369
+ replies.unref();
2370
+ return new _ChannelXgateTransport(replies, requests);
2371
+ }
2372
+ fail(reason) {
2373
+ if (this.closedReason) return;
2374
+ this.closedReason = reason;
2375
+ for (const { reject } of this.pending.values()) reject(new Error(reason));
2376
+ this.pending.clear();
2377
+ for (const listener of this.closeListeners.splice(0)) listener(reason);
2378
+ }
2379
+ /** Calls `listener` once when the controller is gone (now, if it already is). */
2380
+ onClose(listener) {
2381
+ if (this.closedReason) listener(this.closedReason);
2382
+ else this.closeListeners.push(listener);
2383
+ }
2384
+ onLine(line) {
2385
+ let reply;
2386
+ try {
2387
+ reply = JSON.parse(line);
2388
+ } catch {
2389
+ return;
2390
+ }
2391
+ const waiter = this.pending.get(reply?.id);
2392
+ if (!waiter) return;
2393
+ this.pending.delete(reply.id);
2394
+ waiter.resolve(reply);
2395
+ }
2396
+ send(body, options) {
2397
+ if (this.closedReason) return void 0;
2398
+ const id = this.nextId++;
2399
+ const line = `${JSON.stringify({ id, ...body })}
2400
+ `;
2401
+ if (Buffer.byteLength(line) > this.maxBytes) return "too_large";
2402
+ const reply = new Promise((resolve, reject) => {
2403
+ const timer = options.timeoutMs === void 0 ? void 0 : setTimeout(() => {
2404
+ this.pending.delete(id);
2405
+ reject(new Error("the controller did not answer in time"));
2406
+ }, options.timeoutMs);
2407
+ const onAbort = () => {
2408
+ clearTimeout(timer);
2409
+ this.pending.delete(id);
2410
+ options.onAbort?.(id);
2411
+ reject(new Error("aborted"));
2412
+ };
2413
+ options.signal?.addEventListener("abort", onAbort, { once: true });
2414
+ const settle = () => {
2415
+ clearTimeout(timer);
2416
+ options.signal?.removeEventListener("abort", onAbort);
2417
+ };
2418
+ this.pending.set(id, {
2419
+ resolve: (value) => {
2420
+ settle();
2421
+ resolve(value);
2422
+ },
2423
+ reject: (error) => {
2424
+ settle();
2425
+ reject(error);
2426
+ }
2427
+ });
2428
+ });
2429
+ this.requests.write(line);
2430
+ return { id, reply };
2431
+ }
2432
+ async view(body, signal, timeoutMs = VIEW_TIMEOUT_MS) {
2433
+ const sent = this.send(body, { timeoutMs, signal });
2434
+ if (sent === "too_large") throw new XgateError("message_too_large");
2435
+ if (!sent) throw new XgateError("controller_unavailable");
2436
+ let reply;
2437
+ try {
2438
+ reply = await sent.reply;
2439
+ } catch {
2440
+ throw new XgateError(signal?.aborted ? "aborted" : "controller_unavailable");
2441
+ }
2442
+ if (reply.error) throw wireToError(reply.error);
2443
+ return reply;
2444
+ }
2445
+ async models(signal) {
2446
+ signal?.throwIfAborted();
2447
+ let reply;
2448
+ try {
2449
+ reply = await this.view({ op: "models" }, signal);
2450
+ } catch (error) {
2451
+ throw error instanceof XgateError && error.code !== "controller_unavailable" ? error : new XgateError("catalog_unavailable");
2452
+ }
2453
+ if (!Array.isArray(reply.rows)) throw new XgateError("invalid_catalog");
2454
+ return reply.rows;
2455
+ }
2456
+ async purchase(invocation, signal) {
2457
+ const id = invocation.id;
2458
+ if (signal?.aborted) throw new XgatePurchaseError("aborted", id, false);
2459
+ const sent = this.send(
2460
+ { op: "purchase", invocation: { id, route: invocation.route, body: invocation.body } },
2461
+ {
2462
+ signal,
2463
+ // Tell the controller to stop; its payer records the real outcome in the journal.
2464
+ onAbort: (target) => {
2465
+ if (!this.closedReason)
2466
+ this.requests.write(`${JSON.stringify({ id: this.nextId++, op: "abort", target })}
2467
+ `);
2468
+ }
2469
+ }
2470
+ );
2471
+ if (sent === "too_large") throw new XgatePurchaseError("message_too_large", id, false);
2472
+ if (!sent) throw new XgatePurchaseError("controller_unavailable", id, false);
2473
+ let reply;
2474
+ try {
2475
+ reply = await sent.reply;
2476
+ } catch {
2477
+ throw new XgatePurchaseError(
2478
+ signal?.aborted ? "aborted" : "controller_unavailable",
2479
+ id,
2480
+ true
2481
+ );
2482
+ }
2483
+ if (reply.error) throw wireToError(reply.error, id);
2484
+ const result = reply.result;
2485
+ if (!result || typeof result !== "object" || !("body" in result) || !result.settlement) {
2486
+ throw new XgatePurchaseError("invalid_result", id, true);
2487
+ }
2488
+ return result;
2489
+ }
2490
+ async status(signal) {
2491
+ return (await this.view({ op: "status" }, signal)).value;
2492
+ }
2493
+ async reconcile(invocationId2, signal) {
2494
+ return (await this.view({ op: "reconcile", invocationId: invocationId2 }, signal)).value;
2495
+ }
2496
+ /** The controller's budget view (`BudgetView`) for the status bar and `/budget`. */
2497
+ async budget(signal) {
2498
+ return (await this.view({ op: "budget" }, signal)).value;
2499
+ }
2500
+ /** The compute credit sizes and price the controller can buy, for `/credits`. */
2501
+ async creditOffer(signal) {
2502
+ return (await this.view({ op: "credit_offer" }, signal)).value;
2503
+ }
2504
+ /**
2505
+ * `/credits`: ask the controller to buy one chunk of compute credit. The controller's purchase
2506
+ * is journaled and capped; a reply lost here never makes it buy again.
2507
+ */
2508
+ async buyCredits(amountUsd, signal) {
2509
+ return (await this.view(
2510
+ { op: "buy_credits", ...amountUsd !== void 0 ? { amountUsd } : {} },
2511
+ signal,
2512
+ BUY_TIMEOUT_MS
2513
+ )).value;
2514
+ }
2515
+ };
2516
+ function unavailableTransport() {
2517
+ return {
2518
+ models: () => Promise.reject(new XgateError("catalog_unavailable")),
2519
+ purchase: (invocation) => Promise.reject(new XgatePurchaseError("controller_unavailable", invocation.id, false))
2520
+ };
2521
+ }
2522
+
2523
+ // src/pi-extensions/xgate.ts
2524
+ var log = (message) => console.error(`[taskmarket] ${message}`);
2525
+ function openTransport() {
2526
+ const [request, reply] = (process.env[INFERENCE_CHANNEL_FDS_ENV] ?? "").split(",").map(Number);
2527
+ if (!Number.isInteger(request) || !Number.isInteger(reply) || request <= 2 || reply <= 2) {
2528
+ log("Pi was launched without an inference channel; xgate models are unavailable");
2529
+ return unavailableTransport();
2530
+ }
2531
+ try {
2532
+ return ChannelXgateTransport.fromFds({ request, reply });
2533
+ } catch (error) {
2534
+ log(`The inference channel cannot be opened: ${error.message}`);
2535
+ return unavailableTransport();
2536
+ }
2537
+ }
2538
+ async function taskmarketXgate(pi2) {
2539
+ const transport = openTransport();
2540
+ const channel = transport instanceof ChannelXgateTransport ? transport : void 0;
2541
+ let context;
2542
+ let controllerGone = false;
2543
+ pi2.on("session_start", async (_event, ctx) => {
2544
+ context = ctx;
2545
+ if (controllerGone) ctx.shutdown();
2546
+ });
2547
+ if (channel) {
2548
+ channel.onClose((reason) => {
2549
+ log(`The taskmarket controller is gone (${reason}); ending the session`);
2550
+ controllerGone = true;
2551
+ context?.shutdown();
2552
+ });
2553
+ }
2554
+ await createXgateExtension({
2555
+ transport: withPurchaseNotices(transport, (text2, level) => context?.ui.notify(text2, level))
2556
+ })(pi2);
2557
+ registerBudgetUi(pi2, channel);
2558
+ pi2.on("model_select", async (event, ctx) => {
2559
+ if (event.model.provider === "xgate") return;
2560
+ const fallback = event.previousModel?.provider === "xgate" ? event.previousModel : ctx.modelRegistry.getAvailable().find((model) => model.provider === "xgate");
2561
+ if (fallback) await pi2.setModel(fallback);
2562
+ ctx.ui.notify("taskmarket agent offers only the xgate models your policy approves", "warning");
2563
+ });
2564
+ }
2565
+ module.exports = module.exports.default;