@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

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 (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -1,20 +1,1611 @@
1
1
  import { createRequire as __flowCreateRequire } from 'node:module'; const require = __flowCreateRequire(import.meta.url);
2
+ import "./chunk-LAEUXDNH.mjs";
2
3
  import {
4
+ DIFF_EXCERPT_INSTRUCTIONS,
3
5
  EFFORT_ORDER,
6
+ anthropicPlanLimits,
4
7
  clampEffort,
5
8
  inspectDescription,
6
9
  recoverDescription,
7
10
  relayEnquiryDescription,
8
11
  relayPermissionDescription,
12
+ sessionCreateDescription,
13
+ sessionCreateInput,
14
+ sessionInspectDescription,
15
+ sessionInspectInput,
16
+ sessionListDescription,
17
+ sessionListInput,
18
+ sessionSendDescription,
19
+ sessionSendInput,
9
20
  workflowBuilderTools,
10
21
  workflowInspectInput,
11
22
  workflowRecoverInput,
12
23
  workflowRelayInput
13
- } from "./chunk-J2DBNTL7.mjs";
24
+ } from "./chunk-3KDHJA5P.mjs";
14
25
  import {
26
+ __commonJS,
15
27
  __export,
28
+ __require,
29
+ __toESM,
16
30
  external_exports
17
- } from "./chunk-MLOUI3ZM.mjs";
31
+ } from "./chunk-NZZME2I3.mjs";
32
+
33
+ // node_modules/graceful-fs/polyfills.js
34
+ var require_polyfills = __commonJS({
35
+ "node_modules/graceful-fs/polyfills.js"(exports, module) {
36
+ var constants = __require("constants");
37
+ var origCwd = process.cwd;
38
+ var cwd = null;
39
+ var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform;
40
+ process.cwd = function() {
41
+ if (!cwd)
42
+ cwd = origCwd.call(process);
43
+ return cwd;
44
+ };
45
+ try {
46
+ process.cwd();
47
+ } catch (er) {
48
+ }
49
+ if (typeof process.chdir === "function") {
50
+ chdir = process.chdir;
51
+ process.chdir = function(d) {
52
+ cwd = null;
53
+ chdir.call(process, d);
54
+ };
55
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir);
56
+ }
57
+ var chdir;
58
+ module.exports = patch;
59
+ function patch(fs) {
60
+ if (constants.hasOwnProperty("O_SYMLINK") && process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
61
+ patchLchmod(fs);
62
+ }
63
+ if (!fs.lutimes) {
64
+ patchLutimes(fs);
65
+ }
66
+ fs.chown = chownFix(fs.chown);
67
+ fs.fchown = chownFix(fs.fchown);
68
+ fs.lchown = chownFix(fs.lchown);
69
+ fs.chmod = chmodFix(fs.chmod);
70
+ fs.fchmod = chmodFix(fs.fchmod);
71
+ fs.lchmod = chmodFix(fs.lchmod);
72
+ fs.chownSync = chownFixSync(fs.chownSync);
73
+ fs.fchownSync = chownFixSync(fs.fchownSync);
74
+ fs.lchownSync = chownFixSync(fs.lchownSync);
75
+ fs.chmodSync = chmodFixSync(fs.chmodSync);
76
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync);
77
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync);
78
+ fs.stat = statFix(fs.stat);
79
+ fs.fstat = statFix(fs.fstat);
80
+ fs.lstat = statFix(fs.lstat);
81
+ fs.statSync = statFixSync(fs.statSync);
82
+ fs.fstatSync = statFixSync(fs.fstatSync);
83
+ fs.lstatSync = statFixSync(fs.lstatSync);
84
+ if (fs.chmod && !fs.lchmod) {
85
+ fs.lchmod = function(path, mode, cb) {
86
+ if (cb) process.nextTick(cb);
87
+ };
88
+ fs.lchmodSync = function() {
89
+ };
90
+ }
91
+ if (fs.chown && !fs.lchown) {
92
+ fs.lchown = function(path, uid, gid, cb) {
93
+ if (cb) process.nextTick(cb);
94
+ };
95
+ fs.lchownSync = function() {
96
+ };
97
+ }
98
+ if (platform === "win32") {
99
+ fs.rename = typeof fs.rename !== "function" ? fs.rename : (function(fs$rename) {
100
+ function rename(from, to, cb) {
101
+ var start = Date.now();
102
+ var backoff = 0;
103
+ fs$rename(from, to, function CB(er) {
104
+ if (er && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") && Date.now() - start < 6e4) {
105
+ setTimeout(function() {
106
+ fs.stat(to, function(stater, st) {
107
+ if (stater && stater.code === "ENOENT")
108
+ fs$rename(from, to, CB);
109
+ else
110
+ cb(er);
111
+ });
112
+ }, backoff);
113
+ if (backoff < 100)
114
+ backoff += 10;
115
+ return;
116
+ }
117
+ if (cb) cb(er);
118
+ });
119
+ }
120
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename);
121
+ return rename;
122
+ })(fs.rename);
123
+ }
124
+ fs.read = typeof fs.read !== "function" ? fs.read : (function(fs$read) {
125
+ function read(fd, buffer, offset, length, position, callback_) {
126
+ var callback;
127
+ if (callback_ && typeof callback_ === "function") {
128
+ var eagCounter = 0;
129
+ callback = function(er, _, __) {
130
+ if (er && er.code === "EAGAIN" && eagCounter < 10) {
131
+ eagCounter++;
132
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
133
+ }
134
+ callback_.apply(this, arguments);
135
+ };
136
+ }
137
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback);
138
+ }
139
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read);
140
+ return read;
141
+ })(fs.read);
142
+ fs.readSync = typeof fs.readSync !== "function" ? fs.readSync : /* @__PURE__ */ (function(fs$readSync) {
143
+ return function(fd, buffer, offset, length, position) {
144
+ var eagCounter = 0;
145
+ while (true) {
146
+ try {
147
+ return fs$readSync.call(fs, fd, buffer, offset, length, position);
148
+ } catch (er) {
149
+ if (er.code === "EAGAIN" && eagCounter < 10) {
150
+ eagCounter++;
151
+ continue;
152
+ }
153
+ throw er;
154
+ }
155
+ }
156
+ };
157
+ })(fs.readSync);
158
+ function patchLchmod(fs2) {
159
+ fs2.lchmod = function(path, mode, callback) {
160
+ fs2.open(
161
+ path,
162
+ constants.O_WRONLY | constants.O_SYMLINK,
163
+ mode,
164
+ function(err, fd) {
165
+ if (err) {
166
+ if (callback) callback(err);
167
+ return;
168
+ }
169
+ fs2.fchmod(fd, mode, function(err2) {
170
+ fs2.close(fd, function(err22) {
171
+ if (callback) callback(err2 || err22);
172
+ });
173
+ });
174
+ }
175
+ );
176
+ };
177
+ fs2.lchmodSync = function(path, mode) {
178
+ var fd = fs2.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode);
179
+ var threw = true;
180
+ var ret;
181
+ try {
182
+ ret = fs2.fchmodSync(fd, mode);
183
+ threw = false;
184
+ } finally {
185
+ if (threw) {
186
+ try {
187
+ fs2.closeSync(fd);
188
+ } catch (er) {
189
+ }
190
+ } else {
191
+ fs2.closeSync(fd);
192
+ }
193
+ }
194
+ return ret;
195
+ };
196
+ }
197
+ function patchLutimes(fs2) {
198
+ if (constants.hasOwnProperty("O_SYMLINK") && fs2.futimes) {
199
+ fs2.lutimes = function(path, at, mt, cb) {
200
+ fs2.open(path, constants.O_SYMLINK, function(er, fd) {
201
+ if (er) {
202
+ if (cb) cb(er);
203
+ return;
204
+ }
205
+ fs2.futimes(fd, at, mt, function(er2) {
206
+ fs2.close(fd, function(er22) {
207
+ if (cb) cb(er2 || er22);
208
+ });
209
+ });
210
+ });
211
+ };
212
+ fs2.lutimesSync = function(path, at, mt) {
213
+ var fd = fs2.openSync(path, constants.O_SYMLINK);
214
+ var ret;
215
+ var threw = true;
216
+ try {
217
+ ret = fs2.futimesSync(fd, at, mt);
218
+ threw = false;
219
+ } finally {
220
+ if (threw) {
221
+ try {
222
+ fs2.closeSync(fd);
223
+ } catch (er) {
224
+ }
225
+ } else {
226
+ fs2.closeSync(fd);
227
+ }
228
+ }
229
+ return ret;
230
+ };
231
+ } else if (fs2.futimes) {
232
+ fs2.lutimes = function(_a, _b, _c, cb) {
233
+ if (cb) process.nextTick(cb);
234
+ };
235
+ fs2.lutimesSync = function() {
236
+ };
237
+ }
238
+ }
239
+ function chmodFix(orig) {
240
+ if (!orig) return orig;
241
+ return function(target, mode, cb) {
242
+ return orig.call(fs, target, mode, function(er) {
243
+ if (chownErOk(er)) er = null;
244
+ if (cb) cb.apply(this, arguments);
245
+ });
246
+ };
247
+ }
248
+ function chmodFixSync(orig) {
249
+ if (!orig) return orig;
250
+ return function(target, mode) {
251
+ try {
252
+ return orig.call(fs, target, mode);
253
+ } catch (er) {
254
+ if (!chownErOk(er)) throw er;
255
+ }
256
+ };
257
+ }
258
+ function chownFix(orig) {
259
+ if (!orig) return orig;
260
+ return function(target, uid, gid, cb) {
261
+ return orig.call(fs, target, uid, gid, function(er) {
262
+ if (chownErOk(er)) er = null;
263
+ if (cb) cb.apply(this, arguments);
264
+ });
265
+ };
266
+ }
267
+ function chownFixSync(orig) {
268
+ if (!orig) return orig;
269
+ return function(target, uid, gid) {
270
+ try {
271
+ return orig.call(fs, target, uid, gid);
272
+ } catch (er) {
273
+ if (!chownErOk(er)) throw er;
274
+ }
275
+ };
276
+ }
277
+ function statFix(orig) {
278
+ if (!orig) return orig;
279
+ return function(target, options, cb) {
280
+ if (typeof options === "function") {
281
+ cb = options;
282
+ options = null;
283
+ }
284
+ function callback(er, stats) {
285
+ if (stats) {
286
+ if (stats.uid < 0) stats.uid += 4294967296;
287
+ if (stats.gid < 0) stats.gid += 4294967296;
288
+ }
289
+ if (cb) cb.apply(this, arguments);
290
+ }
291
+ return options ? orig.call(fs, target, options, callback) : orig.call(fs, target, callback);
292
+ };
293
+ }
294
+ function statFixSync(orig) {
295
+ if (!orig) return orig;
296
+ return function(target, options) {
297
+ var stats = options ? orig.call(fs, target, options) : orig.call(fs, target);
298
+ if (stats) {
299
+ if (stats.uid < 0) stats.uid += 4294967296;
300
+ if (stats.gid < 0) stats.gid += 4294967296;
301
+ }
302
+ return stats;
303
+ };
304
+ }
305
+ function chownErOk(er) {
306
+ if (!er)
307
+ return true;
308
+ if (er.code === "ENOSYS")
309
+ return true;
310
+ var nonroot = !process.getuid || process.getuid() !== 0;
311
+ if (nonroot) {
312
+ if (er.code === "EINVAL" || er.code === "EPERM")
313
+ return true;
314
+ }
315
+ return false;
316
+ }
317
+ }
318
+ }
319
+ });
320
+
321
+ // node_modules/graceful-fs/legacy-streams.js
322
+ var require_legacy_streams = __commonJS({
323
+ "node_modules/graceful-fs/legacy-streams.js"(exports, module) {
324
+ var Stream = __require("stream").Stream;
325
+ module.exports = legacy;
326
+ function legacy(fs) {
327
+ return {
328
+ ReadStream,
329
+ WriteStream
330
+ };
331
+ function ReadStream(path, options) {
332
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
333
+ Stream.call(this);
334
+ var self = this;
335
+ this.path = path;
336
+ this.fd = null;
337
+ this.readable = true;
338
+ this.paused = false;
339
+ this.flags = "r";
340
+ this.mode = 438;
341
+ this.bufferSize = 64 * 1024;
342
+ options = options || {};
343
+ var keys = Object.keys(options);
344
+ for (var index = 0, length = keys.length; index < length; index++) {
345
+ var key = keys[index];
346
+ this[key] = options[key];
347
+ }
348
+ if (this.encoding) this.setEncoding(this.encoding);
349
+ if (this.start !== void 0) {
350
+ if ("number" !== typeof this.start) {
351
+ throw TypeError("start must be a Number");
352
+ }
353
+ if (this.end === void 0) {
354
+ this.end = Infinity;
355
+ } else if ("number" !== typeof this.end) {
356
+ throw TypeError("end must be a Number");
357
+ }
358
+ if (this.start > this.end) {
359
+ throw new Error("start must be <= end");
360
+ }
361
+ this.pos = this.start;
362
+ }
363
+ if (this.fd !== null) {
364
+ process.nextTick(function() {
365
+ self._read();
366
+ });
367
+ return;
368
+ }
369
+ fs.open(this.path, this.flags, this.mode, function(err, fd) {
370
+ if (err) {
371
+ self.emit("error", err);
372
+ self.readable = false;
373
+ return;
374
+ }
375
+ self.fd = fd;
376
+ self.emit("open", fd);
377
+ self._read();
378
+ });
379
+ }
380
+ function WriteStream(path, options) {
381
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
382
+ Stream.call(this);
383
+ this.path = path;
384
+ this.fd = null;
385
+ this.writable = true;
386
+ this.flags = "w";
387
+ this.encoding = "binary";
388
+ this.mode = 438;
389
+ this.bytesWritten = 0;
390
+ options = options || {};
391
+ var keys = Object.keys(options);
392
+ for (var index = 0, length = keys.length; index < length; index++) {
393
+ var key = keys[index];
394
+ this[key] = options[key];
395
+ }
396
+ if (this.start !== void 0) {
397
+ if ("number" !== typeof this.start) {
398
+ throw TypeError("start must be a Number");
399
+ }
400
+ if (this.start < 0) {
401
+ throw new Error("start must be >= zero");
402
+ }
403
+ this.pos = this.start;
404
+ }
405
+ this.busy = false;
406
+ this._queue = [];
407
+ if (this.fd === null) {
408
+ this._open = fs.open;
409
+ this._queue.push([this._open, this.path, this.flags, this.mode, void 0]);
410
+ this.flush();
411
+ }
412
+ }
413
+ }
414
+ }
415
+ });
416
+
417
+ // node_modules/graceful-fs/clone.js
418
+ var require_clone = __commonJS({
419
+ "node_modules/graceful-fs/clone.js"(exports, module) {
420
+ "use strict";
421
+ module.exports = clone;
422
+ var getPrototypeOf = Object.getPrototypeOf || function(obj) {
423
+ return obj.__proto__;
424
+ };
425
+ function clone(obj) {
426
+ if (obj === null || typeof obj !== "object")
427
+ return obj;
428
+ if (obj instanceof Object)
429
+ var copy = { __proto__: getPrototypeOf(obj) };
430
+ else
431
+ var copy = /* @__PURE__ */ Object.create(null);
432
+ Object.getOwnPropertyNames(obj).forEach(function(key) {
433
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key));
434
+ });
435
+ return copy;
436
+ }
437
+ }
438
+ });
439
+
440
+ // node_modules/graceful-fs/graceful-fs.js
441
+ var require_graceful_fs = __commonJS({
442
+ "node_modules/graceful-fs/graceful-fs.js"(exports, module) {
443
+ var fs = __require("fs");
444
+ var polyfills = require_polyfills();
445
+ var legacy = require_legacy_streams();
446
+ var clone = require_clone();
447
+ var util = __require("util");
448
+ var gracefulQueue;
449
+ var previousSymbol;
450
+ if (typeof Symbol === "function" && typeof Symbol.for === "function") {
451
+ gracefulQueue = /* @__PURE__ */ Symbol.for("graceful-fs.queue");
452
+ previousSymbol = /* @__PURE__ */ Symbol.for("graceful-fs.previous");
453
+ } else {
454
+ gracefulQueue = "___graceful-fs.queue";
455
+ previousSymbol = "___graceful-fs.previous";
456
+ }
457
+ function noop() {
458
+ }
459
+ function publishQueue(context, queue2) {
460
+ Object.defineProperty(context, gracefulQueue, {
461
+ get: function() {
462
+ return queue2;
463
+ }
464
+ });
465
+ }
466
+ var debug = noop;
467
+ if (util.debuglog)
468
+ debug = util.debuglog("gfs4");
469
+ else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ""))
470
+ debug = function() {
471
+ var m = util.format.apply(util, arguments);
472
+ m = "GFS4: " + m.split(/\n/).join("\nGFS4: ");
473
+ console.error(m);
474
+ };
475
+ if (!fs[gracefulQueue]) {
476
+ queue = global[gracefulQueue] || [];
477
+ publishQueue(fs, queue);
478
+ fs.close = (function(fs$close) {
479
+ function close(fd, cb) {
480
+ return fs$close.call(fs, fd, function(err) {
481
+ if (!err) {
482
+ resetQueue();
483
+ }
484
+ if (typeof cb === "function")
485
+ cb.apply(this, arguments);
486
+ });
487
+ }
488
+ Object.defineProperty(close, previousSymbol, {
489
+ value: fs$close
490
+ });
491
+ return close;
492
+ })(fs.close);
493
+ fs.closeSync = (function(fs$closeSync) {
494
+ function closeSync(fd) {
495
+ fs$closeSync.apply(fs, arguments);
496
+ resetQueue();
497
+ }
498
+ Object.defineProperty(closeSync, previousSymbol, {
499
+ value: fs$closeSync
500
+ });
501
+ return closeSync;
502
+ })(fs.closeSync);
503
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || "")) {
504
+ process.on("exit", function() {
505
+ debug(fs[gracefulQueue]);
506
+ __require("assert").equal(fs[gracefulQueue].length, 0);
507
+ });
508
+ }
509
+ }
510
+ var queue;
511
+ if (!global[gracefulQueue]) {
512
+ publishQueue(global, fs[gracefulQueue]);
513
+ }
514
+ module.exports = patch(clone(fs));
515
+ if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
516
+ module.exports = patch(fs);
517
+ fs.__patched = true;
518
+ }
519
+ function patch(fs2) {
520
+ polyfills(fs2);
521
+ fs2.gracefulify = patch;
522
+ fs2.createReadStream = createReadStream;
523
+ fs2.createWriteStream = createWriteStream;
524
+ var fs$readFile = fs2.readFile;
525
+ fs2.readFile = readFile;
526
+ function readFile(path, options, cb) {
527
+ if (typeof options === "function")
528
+ cb = options, options = null;
529
+ return go$readFile(path, options, cb);
530
+ function go$readFile(path2, options2, cb2, startTime) {
531
+ return fs$readFile(path2, options2, function(err) {
532
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
533
+ enqueue([go$readFile, [path2, options2, cb2], err, startTime || Date.now(), Date.now()]);
534
+ else {
535
+ if (typeof cb2 === "function")
536
+ cb2.apply(this, arguments);
537
+ }
538
+ });
539
+ }
540
+ }
541
+ var fs$writeFile = fs2.writeFile;
542
+ fs2.writeFile = writeFile;
543
+ function writeFile(path, data, options, cb) {
544
+ if (typeof options === "function")
545
+ cb = options, options = null;
546
+ return go$writeFile(path, data, options, cb);
547
+ function go$writeFile(path2, data2, options2, cb2, startTime) {
548
+ return fs$writeFile(path2, data2, options2, function(err) {
549
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
550
+ enqueue([go$writeFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
551
+ else {
552
+ if (typeof cb2 === "function")
553
+ cb2.apply(this, arguments);
554
+ }
555
+ });
556
+ }
557
+ }
558
+ var fs$appendFile = fs2.appendFile;
559
+ if (fs$appendFile)
560
+ fs2.appendFile = appendFile;
561
+ function appendFile(path, data, options, cb) {
562
+ if (typeof options === "function")
563
+ cb = options, options = null;
564
+ return go$appendFile(path, data, options, cb);
565
+ function go$appendFile(path2, data2, options2, cb2, startTime) {
566
+ return fs$appendFile(path2, data2, options2, function(err) {
567
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
568
+ enqueue([go$appendFile, [path2, data2, options2, cb2], err, startTime || Date.now(), Date.now()]);
569
+ else {
570
+ if (typeof cb2 === "function")
571
+ cb2.apply(this, arguments);
572
+ }
573
+ });
574
+ }
575
+ }
576
+ var fs$copyFile = fs2.copyFile;
577
+ if (fs$copyFile)
578
+ fs2.copyFile = copyFile;
579
+ function copyFile(src, dest, flags, cb) {
580
+ if (typeof flags === "function") {
581
+ cb = flags;
582
+ flags = 0;
583
+ }
584
+ return go$copyFile(src, dest, flags, cb);
585
+ function go$copyFile(src2, dest2, flags2, cb2, startTime) {
586
+ return fs$copyFile(src2, dest2, flags2, function(err) {
587
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
588
+ enqueue([go$copyFile, [src2, dest2, flags2, cb2], err, startTime || Date.now(), Date.now()]);
589
+ else {
590
+ if (typeof cb2 === "function")
591
+ cb2.apply(this, arguments);
592
+ }
593
+ });
594
+ }
595
+ }
596
+ var fs$readdir = fs2.readdir;
597
+ fs2.readdir = readdir;
598
+ var noReaddirOptionVersions = /^v[0-5]\./;
599
+ function readdir(path, options, cb) {
600
+ if (typeof options === "function")
601
+ cb = options, options = null;
602
+ var go$readdir = noReaddirOptionVersions.test(process.version) ? function go$readdir2(path2, options2, cb2, startTime) {
603
+ return fs$readdir(path2, fs$readdirCallback(
604
+ path2,
605
+ options2,
606
+ cb2,
607
+ startTime
608
+ ));
609
+ } : function go$readdir2(path2, options2, cb2, startTime) {
610
+ return fs$readdir(path2, options2, fs$readdirCallback(
611
+ path2,
612
+ options2,
613
+ cb2,
614
+ startTime
615
+ ));
616
+ };
617
+ return go$readdir(path, options, cb);
618
+ function fs$readdirCallback(path2, options2, cb2, startTime) {
619
+ return function(err, files) {
620
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
621
+ enqueue([
622
+ go$readdir,
623
+ [path2, options2, cb2],
624
+ err,
625
+ startTime || Date.now(),
626
+ Date.now()
627
+ ]);
628
+ else {
629
+ if (files && files.sort)
630
+ files.sort();
631
+ if (typeof cb2 === "function")
632
+ cb2.call(this, err, files);
633
+ }
634
+ };
635
+ }
636
+ }
637
+ if (process.version.substr(0, 4) === "v0.8") {
638
+ var legStreams = legacy(fs2);
639
+ ReadStream = legStreams.ReadStream;
640
+ WriteStream = legStreams.WriteStream;
641
+ }
642
+ var fs$ReadStream = fs2.ReadStream;
643
+ if (fs$ReadStream) {
644
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype);
645
+ ReadStream.prototype.open = ReadStream$open;
646
+ }
647
+ var fs$WriteStream = fs2.WriteStream;
648
+ if (fs$WriteStream) {
649
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype);
650
+ WriteStream.prototype.open = WriteStream$open;
651
+ }
652
+ Object.defineProperty(fs2, "ReadStream", {
653
+ get: function() {
654
+ return ReadStream;
655
+ },
656
+ set: function(val) {
657
+ ReadStream = val;
658
+ },
659
+ enumerable: true,
660
+ configurable: true
661
+ });
662
+ Object.defineProperty(fs2, "WriteStream", {
663
+ get: function() {
664
+ return WriteStream;
665
+ },
666
+ set: function(val) {
667
+ WriteStream = val;
668
+ },
669
+ enumerable: true,
670
+ configurable: true
671
+ });
672
+ var FileReadStream = ReadStream;
673
+ Object.defineProperty(fs2, "FileReadStream", {
674
+ get: function() {
675
+ return FileReadStream;
676
+ },
677
+ set: function(val) {
678
+ FileReadStream = val;
679
+ },
680
+ enumerable: true,
681
+ configurable: true
682
+ });
683
+ var FileWriteStream = WriteStream;
684
+ Object.defineProperty(fs2, "FileWriteStream", {
685
+ get: function() {
686
+ return FileWriteStream;
687
+ },
688
+ set: function(val) {
689
+ FileWriteStream = val;
690
+ },
691
+ enumerable: true,
692
+ configurable: true
693
+ });
694
+ function ReadStream(path, options) {
695
+ if (this instanceof ReadStream)
696
+ return fs$ReadStream.apply(this, arguments), this;
697
+ else
698
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments);
699
+ }
700
+ function ReadStream$open() {
701
+ var that = this;
702
+ open(that.path, that.flags, that.mode, function(err, fd) {
703
+ if (err) {
704
+ if (that.autoClose)
705
+ that.destroy();
706
+ that.emit("error", err);
707
+ } else {
708
+ that.fd = fd;
709
+ that.emit("open", fd);
710
+ that.read();
711
+ }
712
+ });
713
+ }
714
+ function WriteStream(path, options) {
715
+ if (this instanceof WriteStream)
716
+ return fs$WriteStream.apply(this, arguments), this;
717
+ else
718
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments);
719
+ }
720
+ function WriteStream$open() {
721
+ var that = this;
722
+ open(that.path, that.flags, that.mode, function(err, fd) {
723
+ if (err) {
724
+ that.destroy();
725
+ that.emit("error", err);
726
+ } else {
727
+ that.fd = fd;
728
+ that.emit("open", fd);
729
+ }
730
+ });
731
+ }
732
+ function createReadStream(path, options) {
733
+ return new fs2.ReadStream(path, options);
734
+ }
735
+ function createWriteStream(path, options) {
736
+ return new fs2.WriteStream(path, options);
737
+ }
738
+ var fs$open = fs2.open;
739
+ fs2.open = open;
740
+ function open(path, flags, mode, cb) {
741
+ if (typeof mode === "function")
742
+ cb = mode, mode = null;
743
+ return go$open(path, flags, mode, cb);
744
+ function go$open(path2, flags2, mode2, cb2, startTime) {
745
+ return fs$open(path2, flags2, mode2, function(err, fd) {
746
+ if (err && (err.code === "EMFILE" || err.code === "ENFILE"))
747
+ enqueue([go$open, [path2, flags2, mode2, cb2], err, startTime || Date.now(), Date.now()]);
748
+ else {
749
+ if (typeof cb2 === "function")
750
+ cb2.apply(this, arguments);
751
+ }
752
+ });
753
+ }
754
+ }
755
+ return fs2;
756
+ }
757
+ function enqueue(elem) {
758
+ debug("ENQUEUE", elem[0].name, elem[1]);
759
+ fs[gracefulQueue].push(elem);
760
+ retry();
761
+ }
762
+ var retryTimer;
763
+ function resetQueue() {
764
+ var now = Date.now();
765
+ for (var i = 0; i < fs[gracefulQueue].length; ++i) {
766
+ if (fs[gracefulQueue][i].length > 2) {
767
+ fs[gracefulQueue][i][3] = now;
768
+ fs[gracefulQueue][i][4] = now;
769
+ }
770
+ }
771
+ retry();
772
+ }
773
+ function retry() {
774
+ clearTimeout(retryTimer);
775
+ retryTimer = void 0;
776
+ if (fs[gracefulQueue].length === 0)
777
+ return;
778
+ var elem = fs[gracefulQueue].shift();
779
+ var fn = elem[0];
780
+ var args = elem[1];
781
+ var err = elem[2];
782
+ var startTime = elem[3];
783
+ var lastTime = elem[4];
784
+ if (startTime === void 0) {
785
+ debug("RETRY", fn.name, args);
786
+ fn.apply(null, args);
787
+ } else if (Date.now() - startTime >= 6e4) {
788
+ debug("TIMEOUT", fn.name, args);
789
+ var cb = args.pop();
790
+ if (typeof cb === "function")
791
+ cb.call(null, err);
792
+ } else {
793
+ var sinceAttempt = Date.now() - lastTime;
794
+ var sinceStart = Math.max(lastTime - startTime, 1);
795
+ var desiredDelay = Math.min(sinceStart * 1.2, 100);
796
+ if (sinceAttempt >= desiredDelay) {
797
+ debug("RETRY", fn.name, args);
798
+ fn.apply(null, args.concat([startTime]));
799
+ } else {
800
+ fs[gracefulQueue].push(elem);
801
+ }
802
+ }
803
+ if (retryTimer === void 0) {
804
+ retryTimer = setTimeout(retry, 0);
805
+ }
806
+ }
807
+ }
808
+ });
809
+
810
+ // node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js
811
+ var require_retry_operation = __commonJS({
812
+ "node_modules/proper-lockfile/node_modules/retry/lib/retry_operation.js"(exports, module) {
813
+ function RetryOperation(timeouts, options) {
814
+ if (typeof options === "boolean") {
815
+ options = { forever: options };
816
+ }
817
+ this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
818
+ this._timeouts = timeouts;
819
+ this._options = options || {};
820
+ this._maxRetryTime = options && options.maxRetryTime || Infinity;
821
+ this._fn = null;
822
+ this._errors = [];
823
+ this._attempts = 1;
824
+ this._operationTimeout = null;
825
+ this._operationTimeoutCb = null;
826
+ this._timeout = null;
827
+ this._operationStart = null;
828
+ if (this._options.forever) {
829
+ this._cachedTimeouts = this._timeouts.slice(0);
830
+ }
831
+ }
832
+ module.exports = RetryOperation;
833
+ RetryOperation.prototype.reset = function() {
834
+ this._attempts = 1;
835
+ this._timeouts = this._originalTimeouts;
836
+ };
837
+ RetryOperation.prototype.stop = function() {
838
+ if (this._timeout) {
839
+ clearTimeout(this._timeout);
840
+ }
841
+ this._timeouts = [];
842
+ this._cachedTimeouts = null;
843
+ };
844
+ RetryOperation.prototype.retry = function(err) {
845
+ if (this._timeout) {
846
+ clearTimeout(this._timeout);
847
+ }
848
+ if (!err) {
849
+ return false;
850
+ }
851
+ var currentTime = (/* @__PURE__ */ new Date()).getTime();
852
+ if (err && currentTime - this._operationStart >= this._maxRetryTime) {
853
+ this._errors.unshift(new Error("RetryOperation timeout occurred"));
854
+ return false;
855
+ }
856
+ this._errors.push(err);
857
+ var timeout = this._timeouts.shift();
858
+ if (timeout === void 0) {
859
+ if (this._cachedTimeouts) {
860
+ this._errors.splice(this._errors.length - 1, this._errors.length);
861
+ this._timeouts = this._cachedTimeouts.slice(0);
862
+ timeout = this._timeouts.shift();
863
+ } else {
864
+ return false;
865
+ }
866
+ }
867
+ var self = this;
868
+ var timer = setTimeout(function() {
869
+ self._attempts++;
870
+ if (self._operationTimeoutCb) {
871
+ self._timeout = setTimeout(function() {
872
+ self._operationTimeoutCb(self._attempts);
873
+ }, self._operationTimeout);
874
+ if (self._options.unref) {
875
+ self._timeout.unref();
876
+ }
877
+ }
878
+ self._fn(self._attempts);
879
+ }, timeout);
880
+ if (this._options.unref) {
881
+ timer.unref();
882
+ }
883
+ return true;
884
+ };
885
+ RetryOperation.prototype.attempt = function(fn, timeoutOps) {
886
+ this._fn = fn;
887
+ if (timeoutOps) {
888
+ if (timeoutOps.timeout) {
889
+ this._operationTimeout = timeoutOps.timeout;
890
+ }
891
+ if (timeoutOps.cb) {
892
+ this._operationTimeoutCb = timeoutOps.cb;
893
+ }
894
+ }
895
+ var self = this;
896
+ if (this._operationTimeoutCb) {
897
+ this._timeout = setTimeout(function() {
898
+ self._operationTimeoutCb();
899
+ }, self._operationTimeout);
900
+ }
901
+ this._operationStart = (/* @__PURE__ */ new Date()).getTime();
902
+ this._fn(this._attempts);
903
+ };
904
+ RetryOperation.prototype.try = function(fn) {
905
+ console.log("Using RetryOperation.try() is deprecated");
906
+ this.attempt(fn);
907
+ };
908
+ RetryOperation.prototype.start = function(fn) {
909
+ console.log("Using RetryOperation.start() is deprecated");
910
+ this.attempt(fn);
911
+ };
912
+ RetryOperation.prototype.start = RetryOperation.prototype.try;
913
+ RetryOperation.prototype.errors = function() {
914
+ return this._errors;
915
+ };
916
+ RetryOperation.prototype.attempts = function() {
917
+ return this._attempts;
918
+ };
919
+ RetryOperation.prototype.mainError = function() {
920
+ if (this._errors.length === 0) {
921
+ return null;
922
+ }
923
+ var counts = {};
924
+ var mainError = null;
925
+ var mainErrorCount = 0;
926
+ for (var i = 0; i < this._errors.length; i++) {
927
+ var error = this._errors[i];
928
+ var message = error.message;
929
+ var count = (counts[message] || 0) + 1;
930
+ counts[message] = count;
931
+ if (count >= mainErrorCount) {
932
+ mainError = error;
933
+ mainErrorCount = count;
934
+ }
935
+ }
936
+ return mainError;
937
+ };
938
+ }
939
+ });
940
+
941
+ // node_modules/proper-lockfile/node_modules/retry/lib/retry.js
942
+ var require_retry = __commonJS({
943
+ "node_modules/proper-lockfile/node_modules/retry/lib/retry.js"(exports) {
944
+ var RetryOperation = require_retry_operation();
945
+ exports.operation = function(options) {
946
+ var timeouts = exports.timeouts(options);
947
+ return new RetryOperation(timeouts, {
948
+ forever: options && options.forever,
949
+ unref: options && options.unref,
950
+ maxRetryTime: options && options.maxRetryTime
951
+ });
952
+ };
953
+ exports.timeouts = function(options) {
954
+ if (options instanceof Array) {
955
+ return [].concat(options);
956
+ }
957
+ var opts = {
958
+ retries: 10,
959
+ factor: 2,
960
+ minTimeout: 1 * 1e3,
961
+ maxTimeout: Infinity,
962
+ randomize: false
963
+ };
964
+ for (var key in options) {
965
+ opts[key] = options[key];
966
+ }
967
+ if (opts.minTimeout > opts.maxTimeout) {
968
+ throw new Error("minTimeout is greater than maxTimeout");
969
+ }
970
+ var timeouts = [];
971
+ for (var i = 0; i < opts.retries; i++) {
972
+ timeouts.push(this.createTimeout(i, opts));
973
+ }
974
+ if (options && options.forever && !timeouts.length) {
975
+ timeouts.push(this.createTimeout(i, opts));
976
+ }
977
+ timeouts.sort(function(a, b) {
978
+ return a - b;
979
+ });
980
+ return timeouts;
981
+ };
982
+ exports.createTimeout = function(attempt, opts) {
983
+ var random = opts.randomize ? Math.random() + 1 : 1;
984
+ var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
985
+ timeout = Math.min(timeout, opts.maxTimeout);
986
+ return timeout;
987
+ };
988
+ exports.wrap = function(obj, options, methods) {
989
+ if (options instanceof Array) {
990
+ methods = options;
991
+ options = null;
992
+ }
993
+ if (!methods) {
994
+ methods = [];
995
+ for (var key in obj) {
996
+ if (typeof obj[key] === "function") {
997
+ methods.push(key);
998
+ }
999
+ }
1000
+ }
1001
+ for (var i = 0; i < methods.length; i++) {
1002
+ var method = methods[i];
1003
+ var original = obj[method];
1004
+ obj[method] = function retryWrapper(original2) {
1005
+ var op = exports.operation(options);
1006
+ var args = Array.prototype.slice.call(arguments, 1);
1007
+ var callback = args.pop();
1008
+ args.push(function(err) {
1009
+ if (op.retry(err)) {
1010
+ return;
1011
+ }
1012
+ if (err) {
1013
+ arguments[0] = op.mainError();
1014
+ }
1015
+ callback.apply(this, arguments);
1016
+ });
1017
+ op.attempt(function() {
1018
+ original2.apply(obj, args);
1019
+ });
1020
+ }.bind(obj, original);
1021
+ obj[method].options = options;
1022
+ }
1023
+ };
1024
+ }
1025
+ });
1026
+
1027
+ // node_modules/proper-lockfile/node_modules/retry/index.js
1028
+ var require_retry2 = __commonJS({
1029
+ "node_modules/proper-lockfile/node_modules/retry/index.js"(exports, module) {
1030
+ module.exports = require_retry();
1031
+ }
1032
+ });
1033
+
1034
+ // node_modules/proper-lockfile/node_modules/signal-exit/signals.js
1035
+ var require_signals = __commonJS({
1036
+ "node_modules/proper-lockfile/node_modules/signal-exit/signals.js"(exports, module) {
1037
+ module.exports = [
1038
+ "SIGABRT",
1039
+ "SIGALRM",
1040
+ "SIGHUP",
1041
+ "SIGINT",
1042
+ "SIGTERM"
1043
+ ];
1044
+ if (process.platform !== "win32") {
1045
+ module.exports.push(
1046
+ "SIGVTALRM",
1047
+ "SIGXCPU",
1048
+ "SIGXFSZ",
1049
+ "SIGUSR2",
1050
+ "SIGTRAP",
1051
+ "SIGSYS",
1052
+ "SIGQUIT",
1053
+ "SIGIOT"
1054
+ // should detect profiler and enable/disable accordingly.
1055
+ // see #21
1056
+ // 'SIGPROF'
1057
+ );
1058
+ }
1059
+ if (process.platform === "linux") {
1060
+ module.exports.push(
1061
+ "SIGIO",
1062
+ "SIGPOLL",
1063
+ "SIGPWR",
1064
+ "SIGSTKFLT",
1065
+ "SIGUNUSED"
1066
+ );
1067
+ }
1068
+ }
1069
+ });
1070
+
1071
+ // node_modules/proper-lockfile/node_modules/signal-exit/index.js
1072
+ var require_signal_exit = __commonJS({
1073
+ "node_modules/proper-lockfile/node_modules/signal-exit/index.js"(exports, module) {
1074
+ var process2 = global.process;
1075
+ var processOk = function(process3) {
1076
+ return process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
1077
+ };
1078
+ if (!processOk(process2)) {
1079
+ module.exports = function() {
1080
+ return function() {
1081
+ };
1082
+ };
1083
+ } else {
1084
+ assert = __require("assert");
1085
+ signals = require_signals();
1086
+ isWin = /^win/i.test(process2.platform);
1087
+ EE = __require("events");
1088
+ if (typeof EE !== "function") {
1089
+ EE = EE.EventEmitter;
1090
+ }
1091
+ if (process2.__signal_exit_emitter__) {
1092
+ emitter = process2.__signal_exit_emitter__;
1093
+ } else {
1094
+ emitter = process2.__signal_exit_emitter__ = new EE();
1095
+ emitter.count = 0;
1096
+ emitter.emitted = {};
1097
+ }
1098
+ if (!emitter.infinite) {
1099
+ emitter.setMaxListeners(Infinity);
1100
+ emitter.infinite = true;
1101
+ }
1102
+ module.exports = function(cb, opts) {
1103
+ if (!processOk(global.process)) {
1104
+ return function() {
1105
+ };
1106
+ }
1107
+ assert.equal(typeof cb, "function", "a callback must be provided for exit handler");
1108
+ if (loaded === false) {
1109
+ load();
1110
+ }
1111
+ var ev = "exit";
1112
+ if (opts && opts.alwaysLast) {
1113
+ ev = "afterexit";
1114
+ }
1115
+ var remove = function() {
1116
+ emitter.removeListener(ev, cb);
1117
+ if (emitter.listeners("exit").length === 0 && emitter.listeners("afterexit").length === 0) {
1118
+ unload();
1119
+ }
1120
+ };
1121
+ emitter.on(ev, cb);
1122
+ return remove;
1123
+ };
1124
+ unload = function unload2() {
1125
+ if (!loaded || !processOk(global.process)) {
1126
+ return;
1127
+ }
1128
+ loaded = false;
1129
+ signals.forEach(function(sig) {
1130
+ try {
1131
+ process2.removeListener(sig, sigListeners[sig]);
1132
+ } catch (er) {
1133
+ }
1134
+ });
1135
+ process2.emit = originalProcessEmit;
1136
+ process2.reallyExit = originalProcessReallyExit;
1137
+ emitter.count -= 1;
1138
+ };
1139
+ module.exports.unload = unload;
1140
+ emit = function emit2(event, code, signal) {
1141
+ if (emitter.emitted[event]) {
1142
+ return;
1143
+ }
1144
+ emitter.emitted[event] = true;
1145
+ emitter.emit(event, code, signal);
1146
+ };
1147
+ sigListeners = {};
1148
+ signals.forEach(function(sig) {
1149
+ sigListeners[sig] = function listener() {
1150
+ if (!processOk(global.process)) {
1151
+ return;
1152
+ }
1153
+ var listeners = process2.listeners(sig);
1154
+ if (listeners.length === emitter.count) {
1155
+ unload();
1156
+ emit("exit", null, sig);
1157
+ emit("afterexit", null, sig);
1158
+ if (isWin && sig === "SIGHUP") {
1159
+ sig = "SIGINT";
1160
+ }
1161
+ process2.kill(process2.pid, sig);
1162
+ }
1163
+ };
1164
+ });
1165
+ module.exports.signals = function() {
1166
+ return signals;
1167
+ };
1168
+ loaded = false;
1169
+ load = function load2() {
1170
+ if (loaded || !processOk(global.process)) {
1171
+ return;
1172
+ }
1173
+ loaded = true;
1174
+ emitter.count += 1;
1175
+ signals = signals.filter(function(sig) {
1176
+ try {
1177
+ process2.on(sig, sigListeners[sig]);
1178
+ return true;
1179
+ } catch (er) {
1180
+ return false;
1181
+ }
1182
+ });
1183
+ process2.emit = processEmit;
1184
+ process2.reallyExit = processReallyExit;
1185
+ };
1186
+ module.exports.load = load;
1187
+ originalProcessReallyExit = process2.reallyExit;
1188
+ processReallyExit = function processReallyExit2(code) {
1189
+ if (!processOk(global.process)) {
1190
+ return;
1191
+ }
1192
+ process2.exitCode = code || /* istanbul ignore next */
1193
+ 0;
1194
+ emit("exit", process2.exitCode, null);
1195
+ emit("afterexit", process2.exitCode, null);
1196
+ originalProcessReallyExit.call(process2, process2.exitCode);
1197
+ };
1198
+ originalProcessEmit = process2.emit;
1199
+ processEmit = function processEmit2(ev, arg) {
1200
+ if (ev === "exit" && processOk(global.process)) {
1201
+ if (arg !== void 0) {
1202
+ process2.exitCode = arg;
1203
+ }
1204
+ var ret = originalProcessEmit.apply(this, arguments);
1205
+ emit("exit", process2.exitCode, null);
1206
+ emit("afterexit", process2.exitCode, null);
1207
+ return ret;
1208
+ } else {
1209
+ return originalProcessEmit.apply(this, arguments);
1210
+ }
1211
+ };
1212
+ }
1213
+ var assert;
1214
+ var signals;
1215
+ var isWin;
1216
+ var EE;
1217
+ var emitter;
1218
+ var unload;
1219
+ var emit;
1220
+ var sigListeners;
1221
+ var loaded;
1222
+ var load;
1223
+ var originalProcessReallyExit;
1224
+ var processReallyExit;
1225
+ var originalProcessEmit;
1226
+ var processEmit;
1227
+ }
1228
+ });
1229
+
1230
+ // node_modules/proper-lockfile/lib/mtime-precision.js
1231
+ var require_mtime_precision = __commonJS({
1232
+ "node_modules/proper-lockfile/lib/mtime-precision.js"(exports, module) {
1233
+ "use strict";
1234
+ var cacheSymbol = /* @__PURE__ */ Symbol();
1235
+ function probe(file, fs, callback) {
1236
+ const cachedPrecision = fs[cacheSymbol];
1237
+ if (cachedPrecision) {
1238
+ return fs.stat(file, (err, stat) => {
1239
+ if (err) {
1240
+ return callback(err);
1241
+ }
1242
+ callback(null, stat.mtime, cachedPrecision);
1243
+ });
1244
+ }
1245
+ const mtime = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
1246
+ fs.utimes(file, mtime, mtime, (err) => {
1247
+ if (err) {
1248
+ return callback(err);
1249
+ }
1250
+ fs.stat(file, (err2, stat) => {
1251
+ if (err2) {
1252
+ return callback(err2);
1253
+ }
1254
+ const precision = stat.mtime.getTime() % 1e3 === 0 ? "s" : "ms";
1255
+ Object.defineProperty(fs, cacheSymbol, { value: precision });
1256
+ callback(null, stat.mtime, precision);
1257
+ });
1258
+ });
1259
+ }
1260
+ function getMtime(precision) {
1261
+ let now = Date.now();
1262
+ if (precision === "s") {
1263
+ now = Math.ceil(now / 1e3) * 1e3;
1264
+ }
1265
+ return new Date(now);
1266
+ }
1267
+ module.exports.probe = probe;
1268
+ module.exports.getMtime = getMtime;
1269
+ }
1270
+ });
1271
+
1272
+ // node_modules/proper-lockfile/lib/lockfile.js
1273
+ var require_lockfile = __commonJS({
1274
+ "node_modules/proper-lockfile/lib/lockfile.js"(exports, module) {
1275
+ "use strict";
1276
+ var path = __require("path");
1277
+ var fs = require_graceful_fs();
1278
+ var retry = require_retry2();
1279
+ var onExit = require_signal_exit();
1280
+ var mtimePrecision = require_mtime_precision();
1281
+ var locks = {};
1282
+ function getLockFile(file, options) {
1283
+ return options.lockfilePath || `${file}.lock`;
1284
+ }
1285
+ function resolveCanonicalPath(file, options, callback) {
1286
+ if (!options.realpath) {
1287
+ return callback(null, path.resolve(file));
1288
+ }
1289
+ options.fs.realpath(file, callback);
1290
+ }
1291
+ function acquireLock(file, options, callback) {
1292
+ const lockfilePath = getLockFile(file, options);
1293
+ options.fs.mkdir(lockfilePath, (err) => {
1294
+ if (!err) {
1295
+ return mtimePrecision.probe(lockfilePath, options.fs, (err2, mtime, mtimePrecision2) => {
1296
+ if (err2) {
1297
+ options.fs.rmdir(lockfilePath, () => {
1298
+ });
1299
+ return callback(err2);
1300
+ }
1301
+ callback(null, mtime, mtimePrecision2);
1302
+ });
1303
+ }
1304
+ if (err.code !== "EEXIST") {
1305
+ return callback(err);
1306
+ }
1307
+ if (options.stale <= 0) {
1308
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1309
+ }
1310
+ options.fs.stat(lockfilePath, (err2, stat) => {
1311
+ if (err2) {
1312
+ if (err2.code === "ENOENT") {
1313
+ return acquireLock(file, { ...options, stale: 0 }, callback);
1314
+ }
1315
+ return callback(err2);
1316
+ }
1317
+ if (!isLockStale(stat, options)) {
1318
+ return callback(Object.assign(new Error("Lock file is already being held"), { code: "ELOCKED", file }));
1319
+ }
1320
+ removeLock(file, options, (err3) => {
1321
+ if (err3) {
1322
+ return callback(err3);
1323
+ }
1324
+ acquireLock(file, { ...options, stale: 0 }, callback);
1325
+ });
1326
+ });
1327
+ });
1328
+ }
1329
+ function isLockStale(stat, options) {
1330
+ return stat.mtime.getTime() < Date.now() - options.stale;
1331
+ }
1332
+ function removeLock(file, options, callback) {
1333
+ options.fs.rmdir(getLockFile(file, options), (err) => {
1334
+ if (err && err.code !== "ENOENT") {
1335
+ return callback(err);
1336
+ }
1337
+ callback();
1338
+ });
1339
+ }
1340
+ function updateLock(file, options) {
1341
+ const lock2 = locks[file];
1342
+ if (lock2.updateTimeout) {
1343
+ return;
1344
+ }
1345
+ lock2.updateDelay = lock2.updateDelay || options.update;
1346
+ lock2.updateTimeout = setTimeout(() => {
1347
+ lock2.updateTimeout = null;
1348
+ options.fs.stat(lock2.lockfilePath, (err, stat) => {
1349
+ const isOverThreshold = lock2.lastUpdate + options.stale < Date.now();
1350
+ if (err) {
1351
+ if (err.code === "ENOENT" || isOverThreshold) {
1352
+ return setLockAsCompromised(file, lock2, Object.assign(err, { code: "ECOMPROMISED" }));
1353
+ }
1354
+ lock2.updateDelay = 1e3;
1355
+ return updateLock(file, options);
1356
+ }
1357
+ const isMtimeOurs = lock2.mtime.getTime() === stat.mtime.getTime();
1358
+ if (!isMtimeOurs) {
1359
+ return setLockAsCompromised(
1360
+ file,
1361
+ lock2,
1362
+ Object.assign(
1363
+ new Error("Unable to update lock within the stale threshold"),
1364
+ { code: "ECOMPROMISED" }
1365
+ )
1366
+ );
1367
+ }
1368
+ const mtime = mtimePrecision.getMtime(lock2.mtimePrecision);
1369
+ options.fs.utimes(lock2.lockfilePath, mtime, mtime, (err2) => {
1370
+ const isOverThreshold2 = lock2.lastUpdate + options.stale < Date.now();
1371
+ if (lock2.released) {
1372
+ return;
1373
+ }
1374
+ if (err2) {
1375
+ if (err2.code === "ENOENT" || isOverThreshold2) {
1376
+ return setLockAsCompromised(file, lock2, Object.assign(err2, { code: "ECOMPROMISED" }));
1377
+ }
1378
+ lock2.updateDelay = 1e3;
1379
+ return updateLock(file, options);
1380
+ }
1381
+ lock2.mtime = mtime;
1382
+ lock2.lastUpdate = Date.now();
1383
+ lock2.updateDelay = null;
1384
+ updateLock(file, options);
1385
+ });
1386
+ });
1387
+ }, lock2.updateDelay);
1388
+ if (lock2.updateTimeout.unref) {
1389
+ lock2.updateTimeout.unref();
1390
+ }
1391
+ }
1392
+ function setLockAsCompromised(file, lock2, err) {
1393
+ lock2.released = true;
1394
+ if (lock2.updateTimeout) {
1395
+ clearTimeout(lock2.updateTimeout);
1396
+ }
1397
+ if (locks[file] === lock2) {
1398
+ delete locks[file];
1399
+ }
1400
+ lock2.options.onCompromised(err);
1401
+ }
1402
+ function lock(file, options, callback) {
1403
+ options = {
1404
+ stale: 1e4,
1405
+ update: null,
1406
+ realpath: true,
1407
+ retries: 0,
1408
+ fs,
1409
+ onCompromised: (err) => {
1410
+ throw err;
1411
+ },
1412
+ ...options
1413
+ };
1414
+ options.retries = options.retries || 0;
1415
+ options.retries = typeof options.retries === "number" ? { retries: options.retries } : options.retries;
1416
+ options.stale = Math.max(options.stale || 0, 2e3);
1417
+ options.update = options.update == null ? options.stale / 2 : options.update || 0;
1418
+ options.update = Math.max(Math.min(options.update, options.stale / 2), 1e3);
1419
+ resolveCanonicalPath(file, options, (err, file2) => {
1420
+ if (err) {
1421
+ return callback(err);
1422
+ }
1423
+ const operation = retry.operation(options.retries);
1424
+ operation.attempt(() => {
1425
+ acquireLock(file2, options, (err2, mtime, mtimePrecision2) => {
1426
+ if (operation.retry(err2)) {
1427
+ return;
1428
+ }
1429
+ if (err2) {
1430
+ return callback(operation.mainError());
1431
+ }
1432
+ const lock2 = locks[file2] = {
1433
+ lockfilePath: getLockFile(file2, options),
1434
+ mtime,
1435
+ mtimePrecision: mtimePrecision2,
1436
+ options,
1437
+ lastUpdate: Date.now()
1438
+ };
1439
+ updateLock(file2, options);
1440
+ callback(null, (releasedCallback) => {
1441
+ if (lock2.released) {
1442
+ return releasedCallback && releasedCallback(Object.assign(new Error("Lock is already released"), { code: "ERELEASED" }));
1443
+ }
1444
+ unlock(file2, { ...options, realpath: false }, releasedCallback);
1445
+ });
1446
+ });
1447
+ });
1448
+ });
1449
+ }
1450
+ function unlock(file, options, callback) {
1451
+ options = {
1452
+ fs,
1453
+ realpath: true,
1454
+ ...options
1455
+ };
1456
+ resolveCanonicalPath(file, options, (err, file2) => {
1457
+ if (err) {
1458
+ return callback(err);
1459
+ }
1460
+ const lock2 = locks[file2];
1461
+ if (!lock2) {
1462
+ return callback(Object.assign(new Error("Lock is not acquired/owned by you"), { code: "ENOTACQUIRED" }));
1463
+ }
1464
+ lock2.updateTimeout && clearTimeout(lock2.updateTimeout);
1465
+ lock2.released = true;
1466
+ delete locks[file2];
1467
+ removeLock(file2, options, callback);
1468
+ });
1469
+ }
1470
+ function check(file, options, callback) {
1471
+ options = {
1472
+ stale: 1e4,
1473
+ realpath: true,
1474
+ fs,
1475
+ ...options
1476
+ };
1477
+ options.stale = Math.max(options.stale || 0, 2e3);
1478
+ resolveCanonicalPath(file, options, (err, file2) => {
1479
+ if (err) {
1480
+ return callback(err);
1481
+ }
1482
+ options.fs.stat(getLockFile(file2, options), (err2, stat) => {
1483
+ if (err2) {
1484
+ return err2.code === "ENOENT" ? callback(null, false) : callback(err2);
1485
+ }
1486
+ return callback(null, !isLockStale(stat, options));
1487
+ });
1488
+ });
1489
+ }
1490
+ function getLocks() {
1491
+ return locks;
1492
+ }
1493
+ onExit(() => {
1494
+ for (const file in locks) {
1495
+ const options = locks[file].options;
1496
+ try {
1497
+ options.fs.rmdirSync(getLockFile(file, options));
1498
+ } catch (e) {
1499
+ }
1500
+ }
1501
+ });
1502
+ module.exports.lock = lock;
1503
+ module.exports.unlock = unlock;
1504
+ module.exports.check = check;
1505
+ module.exports.getLocks = getLocks;
1506
+ }
1507
+ });
1508
+
1509
+ // node_modules/proper-lockfile/lib/adapter.js
1510
+ var require_adapter = __commonJS({
1511
+ "node_modules/proper-lockfile/lib/adapter.js"(exports, module) {
1512
+ "use strict";
1513
+ var fs = require_graceful_fs();
1514
+ function createSyncFs(fs2) {
1515
+ const methods = ["mkdir", "realpath", "stat", "rmdir", "utimes"];
1516
+ const newFs = { ...fs2 };
1517
+ methods.forEach((method) => {
1518
+ newFs[method] = (...args) => {
1519
+ const callback = args.pop();
1520
+ let ret;
1521
+ try {
1522
+ ret = fs2[`${method}Sync`](...args);
1523
+ } catch (err) {
1524
+ return callback(err);
1525
+ }
1526
+ callback(null, ret);
1527
+ };
1528
+ });
1529
+ return newFs;
1530
+ }
1531
+ function toPromise(method) {
1532
+ return (...args) => new Promise((resolve, reject) => {
1533
+ args.push((err, result) => {
1534
+ if (err) {
1535
+ reject(err);
1536
+ } else {
1537
+ resolve(result);
1538
+ }
1539
+ });
1540
+ method(...args);
1541
+ });
1542
+ }
1543
+ function toSync(method) {
1544
+ return (...args) => {
1545
+ let err;
1546
+ let result;
1547
+ args.push((_err, _result) => {
1548
+ err = _err;
1549
+ result = _result;
1550
+ });
1551
+ method(...args);
1552
+ if (err) {
1553
+ throw err;
1554
+ }
1555
+ return result;
1556
+ };
1557
+ }
1558
+ function toSyncOptions(options) {
1559
+ options = { ...options };
1560
+ options.fs = createSyncFs(options.fs || fs);
1561
+ if (typeof options.retries === "number" && options.retries > 0 || options.retries && typeof options.retries.retries === "number" && options.retries.retries > 0) {
1562
+ throw Object.assign(new Error("Cannot use retries with the sync api"), { code: "ESYNC" });
1563
+ }
1564
+ return options;
1565
+ }
1566
+ module.exports = {
1567
+ toPromise,
1568
+ toSync,
1569
+ toSyncOptions
1570
+ };
1571
+ }
1572
+ });
1573
+
1574
+ // node_modules/proper-lockfile/index.js
1575
+ var require_proper_lockfile = __commonJS({
1576
+ "node_modules/proper-lockfile/index.js"(exports, module) {
1577
+ "use strict";
1578
+ var lockfile2 = require_lockfile();
1579
+ var { toPromise, toSync, toSyncOptions } = require_adapter();
1580
+ async function lock(file, options) {
1581
+ const release = await toPromise(lockfile2.lock)(file, options);
1582
+ return toPromise(release);
1583
+ }
1584
+ function lockSync(file, options) {
1585
+ const release = toSync(lockfile2.lock)(file, toSyncOptions(options));
1586
+ return toSync(release);
1587
+ }
1588
+ function unlock(file, options) {
1589
+ return toPromise(lockfile2.unlock)(file, options);
1590
+ }
1591
+ function unlockSync(file, options) {
1592
+ return toSync(lockfile2.unlock)(file, toSyncOptions(options));
1593
+ }
1594
+ function check(file, options) {
1595
+ return toPromise(lockfile2.check)(file, options);
1596
+ }
1597
+ function checkSync(file, options) {
1598
+ return toSync(lockfile2.check)(file, toSyncOptions(options));
1599
+ }
1600
+ module.exports = lock;
1601
+ module.exports.lock = lock;
1602
+ module.exports.unlock = unlock;
1603
+ module.exports.lockSync = lockSync;
1604
+ module.exports.unlockSync = unlockSync;
1605
+ module.exports.check = check;
1606
+ module.exports.checkSync = checkSync;
1607
+ }
1608
+ });
18
1609
 
19
1610
  // node_modules/typebox/build/system/memory/memory.mjs
20
1611
  var memory_exports = {};
@@ -604,8 +2195,8 @@ function IsSchema(value) {
604
2195
  }
605
2196
 
606
2197
  // node_modules/typebox/build/type/types/deferred.mjs
607
- function Deferred(action, parameters3, options) {
608
- return memory_exports.Create({ "~kind": "Deferred" }, { type: "deferred", action, parameters: parameters3, options }, {});
2198
+ function Deferred(action, parameters4, options) {
2199
+ return memory_exports.Create({ "~kind": "Deferred" }, { type: "deferred", action, parameters: parameters4, options }, {});
609
2200
  }
610
2201
  function IsDeferred(value) {
611
2202
  return IsKind(value, "Deferred");
@@ -649,8 +2240,8 @@ function ArrayOptions(type) {
649
2240
  }
650
2241
 
651
2242
  // node_modules/typebox/build/type/types/constructor.mjs
652
- function Constructor(parameters3, instanceType, options = {}) {
653
- return memory_exports.Create({ "~kind": "Constructor" }, { type: "constructor", parameters: parameters3, instanceType }, options);
2243
+ function Constructor(parameters4, instanceType, options = {}) {
2244
+ return memory_exports.Create({ "~kind": "Constructor" }, { type: "constructor", parameters: parameters4, instanceType }, options);
654
2245
  }
655
2246
  function IsConstructor2(value) {
656
2247
  return IsKind(value, "Constructor");
@@ -660,8 +2251,8 @@ function ConstructorOptions(type) {
660
2251
  }
661
2252
 
662
2253
  // node_modules/typebox/build/type/types/function.mjs
663
- function _Function_(parameters3, returnType, options = {}) {
664
- return memory_exports.Create({ ["~kind"]: "Function" }, { type: "function", parameters: parameters3, returnType }, options);
2254
+ function _Function_(parameters4, returnType, options = {}) {
2255
+ return memory_exports.Create({ ["~kind"]: "Function" }, { type: "function", parameters: parameters4, returnType }, options);
665
2256
  }
666
2257
  function IsFunction2(value) {
667
2258
  return IsKind(value, "Function");
@@ -679,8 +2270,8 @@ function IsRef(value) {
679
2270
  }
680
2271
 
681
2272
  // node_modules/typebox/build/type/types/generic.mjs
682
- function Generic(parameters3, expression) {
683
- return memory_exports.Create({ "~kind": "Generic" }, { type: "generic", parameters: parameters3, expression });
2273
+ function Generic(parameters4, expression) {
2274
+ return memory_exports.Create({ "~kind": "Generic" }, { type: "generic", parameters: parameters4, expression });
684
2275
  }
685
2276
  function IsGeneric(value) {
686
2277
  return IsKind(value, "Generic");
@@ -1037,7 +2628,7 @@ function IsNumber3(value) {
1037
2628
  }
1038
2629
 
1039
2630
  // node_modules/typebox/build/type/types/symbol.mjs
1040
- function Symbol(options) {
2631
+ function Symbol2(options) {
1041
2632
  return memory_exports.Create({ "~kind": "Symbol" }, { type: "symbol" }, options);
1042
2633
  }
1043
2634
  function IsSymbol2(value) {
@@ -1520,8 +3111,8 @@ function IsVoid(value) {
1520
3111
  }
1521
3112
 
1522
3113
  // node_modules/typebox/build/type/script/mapping.mjs
1523
- function IntrinsicOrCall(ref, parameters3) {
1524
- return guard_exports.IsEqual(ref, "Array") ? _Array_(parameters3[0]) : guard_exports.IsEqual(ref, "Capitalize") ? CapitalizeDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "ConstructorParameters") ? ConstructorParametersDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Evaluate") ? EvaluateDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Exclude") ? ExcludeDeferred(parameters3[0], parameters3[1]) : guard_exports.IsEqual(ref, "Extract") ? ExtractDeferred(parameters3[0], parameters3[1]) : guard_exports.IsEqual(ref, "Index") ? IndexDeferred(parameters3[0], parameters3[1]) : guard_exports.IsEqual(ref, "InstanceType") ? InstanceTypeDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Lowercase") ? LowercaseDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "NonNullable") ? NonNullableDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Omit") ? OmitDeferred(parameters3[0], parameters3[1]) : guard_exports.IsEqual(ref, "Parameters") ? ParametersDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Partial") ? PartialDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Pick") ? PickDeferred(parameters3[0], parameters3[1]) : guard_exports.IsEqual(ref, "Readonly") ? ReadonlyObjectDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "KeyOf") ? KeyOfDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Record") ? RecordDeferred(parameters3[0], parameters3[1]) : guard_exports.IsEqual(ref, "Required") ? RequiredDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "ReturnType") ? ReturnTypeDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Uncapitalize") ? UncapitalizeDeferred(parameters3[0]) : guard_exports.IsEqual(ref, "Uppercase") ? UppercaseDeferred(parameters3[0]) : CallConstruct(Ref(ref), parameters3);
3114
+ function IntrinsicOrCall(ref, parameters4) {
3115
+ return guard_exports.IsEqual(ref, "Array") ? _Array_(parameters4[0]) : guard_exports.IsEqual(ref, "Capitalize") ? CapitalizeDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "ConstructorParameters") ? ConstructorParametersDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Evaluate") ? EvaluateDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Exclude") ? ExcludeDeferred(parameters4[0], parameters4[1]) : guard_exports.IsEqual(ref, "Extract") ? ExtractDeferred(parameters4[0], parameters4[1]) : guard_exports.IsEqual(ref, "Index") ? IndexDeferred(parameters4[0], parameters4[1]) : guard_exports.IsEqual(ref, "InstanceType") ? InstanceTypeDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Lowercase") ? LowercaseDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "NonNullable") ? NonNullableDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Omit") ? OmitDeferred(parameters4[0], parameters4[1]) : guard_exports.IsEqual(ref, "Parameters") ? ParametersDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Partial") ? PartialDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Pick") ? PickDeferred(parameters4[0], parameters4[1]) : guard_exports.IsEqual(ref, "Readonly") ? ReadonlyObjectDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "KeyOf") ? KeyOfDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Record") ? RecordDeferred(parameters4[0], parameters4[1]) : guard_exports.IsEqual(ref, "Required") ? RequiredDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "ReturnType") ? ReturnTypeDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Uncapitalize") ? UncapitalizeDeferred(parameters4[0]) : guard_exports.IsEqual(ref, "Uppercase") ? UppercaseDeferred(parameters4[0]) : CallConstruct(Ref(ref), parameters4);
1525
3116
  }
1526
3117
  function Unreachable2() {
1527
3118
  throw Error("Unreachable");
@@ -1599,7 +3190,7 @@ function KeywordNeverMapping(input) {
1599
3190
  return Never();
1600
3191
  }
1601
3192
  function KeywordSymbolMapping(input) {
1602
- return Symbol();
3193
+ return Symbol2();
1603
3194
  }
1604
3195
  function KeywordVoidMapping(input) {
1605
3196
  return Void();
@@ -1909,11 +3500,11 @@ function InterfaceDeclarationHeritageMapping(input) {
1909
3500
  return guard_exports.IsEqual(input.length, 2) ? input[1] : [];
1910
3501
  }
1911
3502
  function InterfaceDeclarationGenericMapping(input) {
1912
- const parameters3 = input[2];
3503
+ const parameters4 = input[2];
1913
3504
  const heritage = input[3];
1914
3505
  const [properties, patternProperties] = input[4];
1915
3506
  const options = guard_exports.IsEqual(guard_exports.Keys(patternProperties).length, 0) ? {} : { patternProperties };
1916
- return { [input[1]]: Generic(parameters3, InterfaceDeferred(heritage, properties, options)) };
3507
+ return { [input[1]]: Generic(parameters4, InterfaceDeferred(heritage, properties, options)) };
1917
3508
  }
1918
3509
  function InterfaceDeclarationMapping(input) {
1919
3510
  const heritage = input[2];
@@ -2563,8 +4154,8 @@ function ExtendsReturnType(inferred, left, right) {
2563
4154
  }
2564
4155
 
2565
4156
  // node_modules/typebox/build/type/extends/constructor.mjs
2566
- function ExtendsConstructor(inferred, parameters3, returnType, right) {
2567
- return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsConstructor2(right) ? Match3(ExtendsParameters(inferred, parameters3, right["parameters"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right["instanceType"]), () => ExtendsFalse()) : ExtendsFalse();
4157
+ function ExtendsConstructor(inferred, parameters4, returnType, right) {
4158
+ return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsConstructor2(right) ? Match3(ExtendsParameters(inferred, parameters4, right["parameters"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right["instanceType"]), () => ExtendsFalse()) : ExtendsFalse();
2568
4159
  }
2569
4160
 
2570
4161
  // node_modules/typebox/build/type/extends/dependent.mjs
@@ -2579,8 +4170,8 @@ function ExtendsEnum(inferred, left, right) {
2579
4170
  }
2580
4171
 
2581
4172
  // node_modules/typebox/build/type/extends/function.mjs
2582
- function ExtendsFunction(inferred, parameters3, returnType, right) {
2583
- return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsFunction2(right) ? Match3(ExtendsParameters(inferred, parameters3, right["parameters"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right["returnType"]), () => ExtendsFalse()) : ExtendsFalse();
4173
+ function ExtendsFunction(inferred, parameters4, returnType, right) {
4174
+ return IsAny(right) ? ExtendsTrue(inferred) : IsUnknown(right) ? ExtendsTrue(inferred) : IsFunction2(right) ? Match3(ExtendsParameters(inferred, parameters4, right["parameters"]), (inferred2) => ExtendsReturnType(inferred2, returnType, right["returnType"]), () => ExtendsFalse()) : ExtendsFalse();
2584
4175
  }
2585
4176
 
2586
4177
  // node_modules/typebox/build/type/extends/integer.mjs
@@ -3008,8 +4599,8 @@ function CollectDistributionNames(expression, result = []) {
3008
4599
  IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Conditional") ? IsRef(expression.parameters[0]) ? CollectDistributionNames(expression.parameters[2], CollectDistributionNames(expression.parameters[3], [...result, expression.parameters[0]["$ref"]])) : CollectDistributionNames(expression.parameters[2], CollectDistributionNames(expression.parameters[3], result)) : IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Mapped") ? IsDeferred(expression.parameters[1]) && guard_exports.IsEqual(expression.parameters[1].action, "KeyOf") && IsRef(expression.parameters[1].parameters[0]) ? [...result, expression.parameters[1].parameters[0]["$ref"]] : result : result
3009
4600
  );
3010
4601
  }
3011
- function BuildDistributionArray(parameters3, names) {
3012
- return parameters3.reduce((result, left) => [...result, names.includes(left.name)], []);
4602
+ function BuildDistributionArray(parameters4, names) {
4603
+ return parameters4.reduce((result, left) => [...result, names.includes(left.name)], []);
3013
4604
  }
3014
4605
  function ZipDistributionArray(arguments_, distributionArray, result = []) {
3015
4606
  return guard_exports.ShiftLeft(arguments_, (argumentLeft, argumentRight) => guard_exports.ShiftLeft(distributionArray, (booleanLeft, booleanRight) => ZipDistributionArray(argumentRight, booleanRight, [...result, [booleanLeft, argumentLeft]]), () => result), () => result);
@@ -3034,9 +4625,9 @@ function Distribute2(zipped) {
3034
4625
  return guard_exports.IsEqual(left[0], true) ? Cross(result, Expand(left[1])) : Cross(result, [left[1]]);
3035
4626
  }, [[]]);
3036
4627
  }
3037
- function DistributeArguments(parameters3, arguments_, expression) {
4628
+ function DistributeArguments(parameters4, arguments_, expression) {
3038
4629
  const distributionNames = CollectDistributionNames(expression);
3039
- const distributionArray = BuildDistributionArray(parameters3, distributionNames);
4630
+ const distributionArray = BuildDistributionArray(parameters4, distributionNames);
3040
4631
  const zippedArguments = ZipDistributionArray(arguments_, distributionArray);
3041
4632
  return IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Conditional") ? Distribute2(zippedArguments) : IsDeferred(expression) && guard_exports.IsEqual(expression.action, "Mapped") ? Distribute2(zippedArguments) : [arguments_];
3042
4633
  }
@@ -3048,8 +4639,8 @@ function FromNotResolvable() {
3048
4639
  function FromNotGeneric() {
3049
4640
  return ["(not-generic)", Never()];
3050
4641
  }
3051
- function FromGeneric(name, parameters3, expression) {
3052
- return [name, Generic(parameters3, expression)];
4642
+ function FromGeneric(name, parameters4, expression) {
4643
+ return [name, Generic(parameters4, expression)];
3053
4644
  }
3054
4645
  function FromRef4(context, ref, arguments_) {
3055
4646
  return ref in context ? FromType6(context, ref, context[ref], arguments_) : FromNotResolvable();
@@ -3078,11 +4669,11 @@ function BindArguments(context, state, parameterLeft, parameterRight, arguments_
3078
4669
  const instantiatedEquals = InstantiateType(context, state, parameterLeft.equals);
3079
4670
  return guard_exports.ShiftLeft(arguments_, (left, right) => BindParameters(BindArgument(context, state, parameterLeft["name"], instantiatedExtends, left), state, parameterRight, right), () => BindParameters(BindArgument(context, state, parameterLeft["name"], instantiatedExtends, instantiatedEquals), state, parameterRight, []));
3080
4671
  }
3081
- function BindParameters(context, state, parameters3, arguments_) {
3082
- return guard_exports.ShiftLeft(parameters3, (left, right) => BindArguments(context, state, left, right, arguments_), () => context);
4672
+ function BindParameters(context, state, parameters4, arguments_) {
4673
+ return guard_exports.ShiftLeft(parameters4, (left, right) => BindArguments(context, state, left, right, arguments_), () => context);
3083
4674
  }
3084
- function ResolveArgumentsContext(context, state, parameters3, arguments_) {
3085
- return BindParameters(context, state, parameters3, arguments_);
4675
+ function ResolveArgumentsContext(context, state, parameters4, arguments_) {
4676
+ return BindParameters(context, state, parameters4, arguments_);
3086
4677
  }
3087
4678
 
3088
4679
  // node_modules/typebox/build/type/engine/call/instantiate.mjs
@@ -3111,25 +4702,25 @@ function IsTailCall(state, name) {
3111
4702
  const result = guard_exports.IsEqual(Peek(state), name);
3112
4703
  return result;
3113
4704
  }
3114
- function CallDispatch(context, state, target, parameters3, expression, arguments_) {
4705
+ function CallDispatch(context, state, target, parameters4, expression, arguments_) {
3115
4706
  InstantiationIncrement();
3116
4707
  try {
3117
- const argumentsContext = ResolveArgumentsContext(context, state, parameters3, arguments_);
4708
+ const argumentsContext = ResolveArgumentsContext(context, state, parameters4, arguments_);
3118
4709
  const returnType = InstantiateType(argumentsContext, State([...state["callstack"], target["$ref"]], state["visited"]), expression);
3119
4710
  return InstantiateType(argumentsContext, State([], []), returnType);
3120
4711
  } finally {
3121
4712
  InstantiationDecrement();
3122
4713
  }
3123
4714
  }
3124
- function CallDistributed(context, state, target, parameters3, expression, distributedArguments) {
4715
+ function CallDistributed(context, state, target, parameters4, expression, distributedArguments) {
3125
4716
  return distributedArguments.reduce((result, arguments_) => {
3126
- const returnType = CallDispatch(context, state, target, parameters3, expression, arguments_);
4717
+ const returnType = CallDispatch(context, state, target, parameters4, expression, arguments_);
3127
4718
  return [...result, returnType];
3128
4719
  }, []);
3129
4720
  }
3130
- function CallImmediate(context, state, target, parameters3, expression, arguments_) {
3131
- const distributedArguments = DistributeArguments(parameters3, arguments_, expression);
3132
- const returnTypes = CallDistributed(context, state, target, parameters3, expression, distributedArguments);
4721
+ function CallImmediate(context, state, target, parameters4, expression, arguments_) {
4722
+ const distributedArguments = DistributeArguments(parameters4, arguments_, expression);
4723
+ const returnTypes = CallDistributed(context, state, target, parameters4, expression, distributedArguments);
3133
4724
  const result = guard_exports.IsEqual(returnTypes.length, 1) ? returnTypes[0] : EvaluateUnion(returnTypes);
3134
4725
  return result;
3135
4726
  }
@@ -3297,8 +4888,8 @@ function ConstructorParameters(type, options = {}) {
3297
4888
 
3298
4889
  // node_modules/typebox/build/type/engine/constructor_parameters/instantiate.mjs
3299
4890
  function ConstructorParametersOperation(type) {
3300
- const parameters3 = IsConstructor2(type) ? type["parameters"] : [];
3301
- const instantiatedParameters = InstantiateElements({}, State([], []), parameters3);
4891
+ const parameters4 = IsConstructor2(type) ? type["parameters"] : [];
4892
+ const instantiatedParameters = InstantiateElements({}, State([], []), parameters4);
3302
4893
  const result = Tuple(instantiatedParameters);
3303
4894
  return result;
3304
4895
  }
@@ -3674,7 +5265,7 @@ function KeyOf2(type, options = {}) {
3674
5265
 
3675
5266
  // node_modules/typebox/build/type/engine/keyof/from_any.mjs
3676
5267
  function FromAny() {
3677
- return Union([Number2(), String2(), Symbol()]);
5268
+ return Union([Number2(), String2(), Symbol2()]);
3678
5269
  }
3679
5270
 
3680
5271
  // node_modules/typebox/build/type/engine/keyof/from_array.mjs
@@ -3903,8 +5494,8 @@ function Parameters(type, options = {}) {
3903
5494
 
3904
5495
  // node_modules/typebox/build/type/engine/parameters/instantiate.mjs
3905
5496
  function ParametersOperation(type) {
3906
- const parameters3 = IsFunction2(type) ? type["parameters"] : [];
3907
- const instantiatedParameters = InstantiateElements({}, State([], []), parameters3);
5497
+ const parameters4 = IsFunction2(type) ? type["parameters"] : [];
5498
+ const instantiatedParameters = InstantiateElements({}, State([], []), parameters4);
3908
5499
  const result = Tuple(instantiatedParameters);
3909
5500
  return result;
3910
5501
  }
@@ -4227,12 +5818,12 @@ function WithModifiers(type, instantiatedType) {
4227
5818
  const withImmutable = IsImmutable(type) ? AddImmutableAction(withReadonly, {}) : withReadonly;
4228
5819
  return withImmutable;
4229
5820
  }
4230
- function InstantiateDeferred(context, state, action, parameters3, options) {
5821
+ function InstantiateDeferred(context, state, action, parameters4, options) {
4231
5822
  return (
4232
5823
  // Modifiers
4233
- guard_exports.IsEqual(action, "AddImmutable") ? AddImmutableInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "RemoveImmutable") ? RemoveImmutableInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "AddReadonly") ? AddReadonlyInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "RemoveReadonly") ? RemoveReadonlyInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "AddOptional") ? AddOptionalInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "RemoveOptional") ? RemoveOptionalInstantiate(context, state, parameters3[0], options) : (
5824
+ guard_exports.IsEqual(action, "AddImmutable") ? AddImmutableInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "RemoveImmutable") ? RemoveImmutableInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "AddReadonly") ? AddReadonlyInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "RemoveReadonly") ? RemoveReadonlyInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "AddOptional") ? AddOptionalInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "RemoveOptional") ? RemoveOptionalInstantiate(context, state, parameters4[0], options) : (
4234
5825
  // Actions
4235
- guard_exports.IsEqual(action, "Capitalize") ? CapitalizeInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Conditional") ? ConditionalInstantiate(context, state, parameters3[0], parameters3[1], parameters3[2], parameters3[3], options) : guard_exports.IsEqual(action, "ConstructorParameters") ? ConstructorParametersInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Evaluate") ? EvaluateInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Exclude") ? ExcludeInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "Extract") ? ExtractInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "Index") ? IndexInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "InstanceType") ? InstanceTypeInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Interface") ? InterfaceInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "KeyOf") ? KeyOfInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Lowercase") ? LowercaseInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Mapped") ? MappedInstantiate(context, state, parameters3[0], parameters3[1], parameters3[2], parameters3[3], options) : guard_exports.IsEqual(action, "Module") ? ModuleInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "NonNullable") ? NonNullableInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Pick") ? PickInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "Parameters") ? ParametersInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Partial") ? PartialInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Omit") ? OmitInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "ReadonlyObject") ? ReadonlyObjectInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Record") ? RecordInstantiate(context, state, parameters3[0], parameters3[1], options) : guard_exports.IsEqual(action, "Required") ? RequiredInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "ReturnType") ? ReturnTypeInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "TemplateLiteral") ? TemplateLiteralInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Uncapitalize") ? UncapitalizeInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "Uppercase") ? UppercaseInstantiate(context, state, parameters3[0], options) : guard_exports.IsEqual(action, "With") ? WithInstantiate(context, state, parameters3[0], parameters3[1]) : Deferred(action, parameters3, options)
5826
+ guard_exports.IsEqual(action, "Capitalize") ? CapitalizeInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Conditional") ? ConditionalInstantiate(context, state, parameters4[0], parameters4[1], parameters4[2], parameters4[3], options) : guard_exports.IsEqual(action, "ConstructorParameters") ? ConstructorParametersInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Evaluate") ? EvaluateInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Exclude") ? ExcludeInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "Extract") ? ExtractInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "Index") ? IndexInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "InstanceType") ? InstanceTypeInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Interface") ? InterfaceInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "KeyOf") ? KeyOfInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Lowercase") ? LowercaseInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Mapped") ? MappedInstantiate(context, state, parameters4[0], parameters4[1], parameters4[2], parameters4[3], options) : guard_exports.IsEqual(action, "Module") ? ModuleInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "NonNullable") ? NonNullableInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Pick") ? PickInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "Parameters") ? ParametersInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Partial") ? PartialInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Omit") ? OmitInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "ReadonlyObject") ? ReadonlyObjectInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Record") ? RecordInstantiate(context, state, parameters4[0], parameters4[1], options) : guard_exports.IsEqual(action, "Required") ? RequiredInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "ReturnType") ? ReturnTypeInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "TemplateLiteral") ? TemplateLiteralInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Uncapitalize") ? UncapitalizeInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "Uppercase") ? UppercaseInstantiate(context, state, parameters4[0], options) : guard_exports.IsEqual(action, "With") ? WithInstantiate(context, state, parameters4[0], parameters4[1]) : Deferred(action, parameters4, options)
4236
5827
  )
4237
5828
  );
4238
5829
  }
@@ -4406,7 +5997,7 @@ __export(typebox_exports, {
4406
5997
  ReturnType: () => ReturnType,
4407
5998
  Script: () => Script2,
4408
5999
  String: () => String2,
4409
- Symbol: () => Symbol,
6000
+ Symbol: () => Symbol2,
4410
6001
  TemplateLiteral: () => TemplateLiteral2,
4411
6002
  This: () => This,
4412
6003
  Tuple: () => Tuple,
@@ -4455,6 +6046,41 @@ function workflowParentTools(parent) {
4455
6046
  ];
4456
6047
  }
4457
6048
 
6049
+ // src/backend/pi/session-tools.ts
6050
+ function piSessionTools(sessions) {
6051
+ if (!sessions) return [];
6052
+ return [
6053
+ {
6054
+ name: "session_list",
6055
+ label: "List Agent Sessions",
6056
+ description: sessionListDescription,
6057
+ parameters: typebox_exports.Unsafe(external_exports.toJSONSchema(sessionListInput, { io: "input" })),
6058
+ execute: async (_id, input) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.list(input)) }], details: {} })
6059
+ },
6060
+ {
6061
+ name: "session_inspect",
6062
+ label: "Inspect Agent Session",
6063
+ description: sessionInspectDescription,
6064
+ parameters: typebox_exports.Unsafe(external_exports.toJSONSchema(sessionInspectInput, { io: "input" })),
6065
+ execute: async (_id, input) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.inspect(input)) }], details: {} })
6066
+ },
6067
+ {
6068
+ name: "session_create",
6069
+ label: "Create Agent Session",
6070
+ description: sessionCreateDescription,
6071
+ parameters: typebox_exports.Unsafe(external_exports.toJSONSchema(sessionCreateInput, { io: "input" })),
6072
+ execute: async (_id, input, signal) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.create(input, signal)) }], details: {} })
6073
+ },
6074
+ {
6075
+ name: "session_send",
6076
+ label: "Send to Agent Session",
6077
+ description: sessionSendDescription,
6078
+ parameters: typebox_exports.Unsafe(external_exports.toJSONSchema(sessionSendInput, { io: "input" })),
6079
+ execute: async (_id, input, signal) => ({ content: [{ type: "text", text: JSON.stringify(await sessions.send(input, signal)) }], details: {} })
6080
+ }
6081
+ ];
6082
+ }
6083
+
4458
6084
  // src/backend/pi/workflow-builder.ts
4459
6085
  function piWorkflowBuilderTools(builder) {
4460
6086
  return workflowBuilderTools.map(({ name, label, field, method, description }) => ({
@@ -4502,10 +6128,17 @@ function piMcpTools(mcp) {
4502
6128
 
4503
6129
  // src/backend/pi/index.ts
4504
6130
  import { randomUUID } from "node:crypto";
6131
+ import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "node:fs";
6132
+ import { join as join2 } from "node:path";
6133
+
6134
+ // src/backend/pi/state.ts
6135
+ var USER_MESSAGE_MAP = "flow-user-messages.json";
6136
+
6137
+ // src/backend/pi/index.ts
4505
6138
  import {
4506
6139
  createAgentSession as createAgentSession2,
4507
6140
  DefaultResourceLoader as DefaultResourceLoader2,
4508
- getAgentDir as getAgentDir2,
6141
+ getAgentDir as getAgentDir3,
4509
6142
  SessionManager as SessionManager2,
4510
6143
  SettingsManager as SettingsManager2
4511
6144
  } from "@earendil-works/pi-coding-agent";
@@ -4515,7 +6148,7 @@ import {
4515
6148
  createAgentSession,
4516
6149
  DefaultPackageManager,
4517
6150
  DefaultResourceLoader,
4518
- getAgentDir,
6151
+ getAgentDir as getAgentDir2,
4519
6152
  SessionManager,
4520
6153
  SettingsManager,
4521
6154
  createReadToolDefinition,
@@ -4538,6 +6171,42 @@ function piAcceptsWorkflowEffort(model, effort) {
4538
6171
  return levels.length === 0 ? effort === "off" : levels.includes(effort);
4539
6172
  }
4540
6173
 
6174
+ // src/backend/pi/model-selection.ts
6175
+ import { existsSync, readFileSync } from "node:fs";
6176
+ import { join } from "node:path";
6177
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
6178
+
6179
+ // src/backend/pi/model-config.ts
6180
+ function parsePiModelConfig(content) {
6181
+ return JSON.parse(content.replace(/^\uFEFF/, "").replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (match) => match.startsWith('"') ? match : "").replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (match, closing) => closing ?? match));
6182
+ }
6183
+
6184
+ // src/backend/pi/model-selection.ts
6185
+ var legacyAzure = "azure-openai-responses";
6186
+ function findPiModel(available, modelId, allowBareId = false, agentDir = getAgentDir()) {
6187
+ const canonicalId = modelId.startsWith(`${legacyAzure}/`) ? `azure/${modelId.slice(legacyAzure.length + 1)}` : modelId;
6188
+ if (canonicalId.startsWith("azure/")) {
6189
+ for (const name of ["auth.json", "models.json"]) {
6190
+ const path = join(agentDir, name);
6191
+ if (!existsSync(path)) continue;
6192
+ const content = readFileSync(path, "utf8");
6193
+ const data = name === "models.json" ? parsePiModelConfig(content) : JSON.parse(content.replace(/^\uFEFF/, ""));
6194
+ const providers = name === "models.json" ? data.providers : data;
6195
+ if (providers && Object.hasOwn(providers, legacyAzure) && !Object.hasOwn(providers, "azure")) {
6196
+ throw new Error(`Pi 1.6 renamed Provider ${legacyAzure} to azure. Rename its Provider key in ${path} to azure; keep the API name azure-openai-responses unchanged. Flow did not change this file or select another model.`);
6197
+ }
6198
+ }
6199
+ }
6200
+ const qualified = available.find((model) => (model.provider ? `${model.provider}/${model.id}` : model.id) === canonicalId);
6201
+ if (qualified || !allowBareId || canonicalId.startsWith("azure/")) return qualified;
6202
+ const bare = available.filter((model) => model.id === modelId);
6203
+ return bare.length === 1 ? bare[0] : void 0;
6204
+ }
6205
+ function piModelUnavailable(modelId, label = "Unknown model") {
6206
+ const azure = modelId.startsWith(`${legacyAzure}/`) || modelId.startsWith("azure/");
6207
+ return `${label}: ${modelId}. Select an available model explicitly; no replacement was used.${azure ? " Pi 1.6 uses Provider azure. Check the azure Provider keys in Pi auth.json and models.json, and confirm the exact model ID is still available. The API name remains azure-openai-responses." : ""}`;
6208
+ }
6209
+
4541
6210
  // src/backend/pi/auto-compaction.ts
4542
6211
  function piAutoCompaction(settings2, setting) {
4543
6212
  const defaults = settings2.getCompactionSettings();
@@ -4562,8 +6231,8 @@ function compactionModelExtension(modelId, notice) {
4562
6231
  return { name: "flow-compaction-model", hidden: true, factory: (pi) => {
4563
6232
  pi.on("session_before_compact", async (event, ctx) => {
4564
6233
  try {
4565
- const model = ctx.modelRegistry.getAvailable().find((candidate) => `${candidate.provider}/${candidate.id}` === modelId);
4566
- if (!model) throw new Error(`Configured compaction model \u201C${modelId}\u201D is unavailable`);
6234
+ const model = findPiModel(ctx.modelRegistry.getAvailable(), modelId);
6235
+ if (!model) throw new Error(piModelUnavailable(modelId, "Configured compaction model is unavailable"));
4567
6236
  const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
4568
6237
  if (!auth.ok) throw new Error(auth.error);
4569
6238
  const requestModel = auth.baseUrl ? { ...model, baseUrl: auth.baseUrl } : model;
@@ -4696,7 +6365,7 @@ var PiWork = class {
4696
6365
  work.state = completion2.state;
4697
6366
  work.result = completion2.result;
4698
6367
  if (brief.type === "subagent") this.jobs.delete(id);
4699
- this.emit({ ...brief, state: completion2.state });
6368
+ this.emit({ ...work.brief, state: completion2.state });
4700
6369
  if (background && !this.disposed) this.completed(completion2);
4701
6370
  return completion2;
4702
6371
  });
@@ -4708,6 +6377,13 @@ var PiWork = class {
4708
6377
  if (completion.state !== "complete") throw new Error(resultText(completion.result));
4709
6378
  return completion.result;
4710
6379
  }
6380
+ /** Record the model and Effort a running Subagent resolved to. */
6381
+ refine(id, patch) {
6382
+ const work = this.jobs.get(id);
6383
+ if (!work || work.brief.type !== "subagent") return;
6384
+ work.brief = { ...work.brief, ...patch };
6385
+ this.emit({ ...work.brief, state: "running" });
6386
+ }
4711
6387
  waiting(id, waiting) {
4712
6388
  const work = this.jobs.get(id);
4713
6389
  if (!work || work.brief.type !== "subagent" || !["running", "waiting"].includes(work.state)) return;
@@ -4890,11 +6566,11 @@ var PiWorkflowSubagent = class {
4890
6566
  let compacting = false;
4891
6567
  try {
4892
6568
  controller.signal.throwIfAborted();
4893
- const model = parent.modelRuntime.getAvailableSnapshot().find((model2) => `${model2.provider}/${model2.id}` === options.modelId);
4894
- if (!model) throw new Error(`Unknown workflow model: ${options.modelId}`);
6569
+ const model = findPiModel(parent.modelRuntime.getAvailableSnapshot(), options.modelId);
6570
+ if (!model) throw new Error(piModelUnavailable(options.modelId, "Unknown workflow model"));
4895
6571
  if (!["ask", "auto-accept"].includes(options.permissionMode)) throw new Error("Unsupported workflow permission mode");
4896
6572
  const scope = parent.sessionManager.getCwd();
4897
- const settingsManager = SettingsManager.inMemory({ retry: { enabled: false } });
6573
+ const settingsManager = SettingsManager.inMemory({ retry: { enabled: false }, cacheWarming: "streaming" });
4898
6574
  const skillContext = options.skill ? `The leading Skill invocation is expanded as the user prompt. Follow it together with the mapped workflow input below.
4899
6575
 
4900
6576
  Mapped workflow input (JSON):
@@ -4903,12 +6579,12 @@ ${JSON.stringify(options.input)}
4903
6579
  Workflow constraints:${options.instructions.slice(options.skill.invocation.length)}` : options.instructions;
4904
6580
  const resources = options.skill ? await new DefaultPackageManager({
4905
6581
  cwd: scope,
4906
- agentDir: getAgentDir(),
4907
- settingsManager: SettingsManager.create(scope, getAgentDir())
6582
+ agentDir: getAgentDir2(),
6583
+ settingsManager: SettingsManager.create(scope, getAgentDir2())
4908
6584
  }).resolve(async () => "skip") : void 0;
4909
6585
  const resourceLoader = new DefaultResourceLoader({
4910
6586
  cwd: scope,
4911
- agentDir: getAgentDir(),
6587
+ agentDir: getAgentDir2(),
4912
6588
  settingsManager,
4913
6589
  noExtensions: true,
4914
6590
  noSkills: true,
@@ -5034,10 +6710,250 @@ ${skillContext}`
5034
6710
  }
5035
6711
  };
5036
6712
 
5037
- // src/backend/pi/subagents.ts
6713
+ // src/backend/pi/model-catalog.ts
6714
+ function registerPiNativeProvider(runtime, provider) {
6715
+ const refresh = runtime.refresh;
6716
+ runtime.refresh = async () => ({ aborted: false, errors: /* @__PURE__ */ new Map() });
6717
+ try {
6718
+ runtime.registerNativeProvider(provider);
6719
+ } finally {
6720
+ runtime.refresh = refresh;
6721
+ }
6722
+ }
6723
+ function unregisterPiNativeProvider(runtime, providerId) {
6724
+ const refresh = runtime.refresh;
6725
+ runtime.refresh = async () => ({ aborted: false, errors: /* @__PURE__ */ new Map() });
6726
+ try {
6727
+ runtime.unregisterProvider(providerId);
6728
+ } finally {
6729
+ runtime.refresh = refresh;
6730
+ }
6731
+ }
6732
+ function withPi099RadiusCatalog(provider, cached) {
6733
+ return {
6734
+ ...provider,
6735
+ async refreshModels(context) {
6736
+ const legacy = context.stored ? void 0 : cached();
6737
+ if (legacy) {
6738
+ const stored = { models: [...legacy], checkedAt: Date.now() };
6739
+ if (!await context.publish({ persist: stored })) return;
6740
+ context = { ...context, stored };
6741
+ }
6742
+ await provider.refreshModels?.(context);
6743
+ }
6744
+ };
6745
+ }
6746
+
6747
+ // src/backend/pi/canonical-json.ts
6748
+ var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
6749
+
6750
+ // src/backend/pi/model-auth.ts
6751
+ var emptyCredentials = {
6752
+ async read(_providerId, options) {
6753
+ options?.signal?.throwIfAborted();
6754
+ return void 0;
6755
+ },
6756
+ async list(options) {
6757
+ options?.signal?.throwIfAborted();
6758
+ return [];
6759
+ },
6760
+ async modify() {
6761
+ throw new Error("Worker Pi credentials are read-only");
6762
+ },
6763
+ async delete() {
6764
+ throw new Error("Worker Pi credentials are read-only");
6765
+ }
6766
+ };
6767
+ async function createWorkerPiModelRuntime(auth, modelsPath, signal, options = {}) {
6768
+ let metadata = new Map((await auth.snapshot(signal)).map((entry) => [entry.providerId, entry]));
6769
+ const storedKey = /* @__PURE__ */ Symbol("host credential metadata");
6770
+ const credentials = {
6771
+ ...emptyCredentials,
6772
+ async read(id, options2) {
6773
+ options2?.signal?.throwIfAborted();
6774
+ const entry = metadata.get(id);
6775
+ if (entry?.check?.type === "api_key") return { type: "api_key", [storedKey]: true };
6776
+ if (entry?.check?.type === "oauth") return {
6777
+ type: "oauth",
6778
+ access: "",
6779
+ refresh: "",
6780
+ expires: Number.MAX_SAFE_INTEGER,
6781
+ ...entry.availableModelIds ? { availableModelIds: [...entry.availableModelIds] } : {}
6782
+ };
6783
+ return void 0;
6784
+ }
6785
+ };
6786
+ const { ModelRuntime } = await import("@earendil-works/pi-coding-agent");
6787
+ const { radiusProvider } = await import("@earendil-works/pi-ai/providers/all");
6788
+ const catalog = await ModelRuntime.create({ credentials: emptyCredentials, modelsPath: null, refreshOnCreate: false });
6789
+ const runtime = await ModelRuntime.create({
6790
+ credentials,
6791
+ modelsPath,
6792
+ ...options.modelsStorePath ? { modelsStorePath: options.modelsStorePath } : {},
6793
+ refreshOnCreate: false,
6794
+ ...signal ? { signal } : {}
6795
+ });
6796
+ const refresh = runtime.refresh.bind(runtime);
6797
+ const builtins = new Map(catalog.getProviders().map((provider) => [provider.id, provider]));
6798
+ const registered = /* @__PURE__ */ new Set();
6799
+ const registeredGateways = /* @__PURE__ */ new Map();
6800
+ const expandKey = async (key, env, signal2) => {
6801
+ if (!key?.includes("$")) return key;
6802
+ const resolver = await ModelRuntime.create({ credentials: emptyCredentials, modelsPath: null, refreshOnCreate: false, signal: signal2 });
6803
+ const refresh2 = resolver.refresh;
6804
+ resolver.refresh = async () => ({ aborted: false, errors: /* @__PURE__ */ new Map() });
6805
+ try {
6806
+ resolver.registerProvider("worker-key-template", { apiKey: key });
6807
+ } finally {
6808
+ resolver.refresh = refresh2;
6809
+ }
6810
+ return (await resolver.getAuth("worker-key-template", { ...env ? { env } : {}, signal: signal2 }))?.auth.apiKey;
6811
+ };
6812
+ const genericApiKey = {
6813
+ name: "API key",
6814
+ async resolve({ credential }) {
6815
+ return credential?.key ? { auth: { apiKey: credential.key }, ...credential.env ? { env: credential.env } : {} } : void 0;
6816
+ }
6817
+ };
6818
+ const brokered = (provider, catalogAuth = provider.id === "radius") => {
6819
+ const id = provider.id;
6820
+ const apiKey = provider.auth.apiKey ?? genericApiKey;
6821
+ const oauth = provider.auth.oauth;
6822
+ return {
6823
+ ...provider,
6824
+ auth: {
6825
+ ...apiKey ? { apiKey: {
6826
+ ...apiKey,
6827
+ async check(input) {
6828
+ input.signal.throwIfAborted();
6829
+ if (input.credential?.[storedKey]) return metadata.get(id)?.check;
6830
+ if (apiKey.check) return apiKey.check(input);
6831
+ const result = await apiKey.resolve(input);
6832
+ return result ? { type: "api_key", ...result.source !== void 0 ? { source: result.source } : {} } : void 0;
6833
+ },
6834
+ async resolve(input) {
6835
+ if (!input.credential?.[storedKey]) return apiKey.resolve(input);
6836
+ const result = await auth.resolve(id, input.signal);
6837
+ if (!result) return void 0;
6838
+ const env = { ...result.env, ...input.credential?.env };
6839
+ const key = await expandKey(result.auth.apiKey, env, input.signal);
6840
+ return apiKey.resolve({
6841
+ ...input,
6842
+ credential: { type: "api_key", ...key !== void 0 ? { key } : {}, env },
6843
+ ctx: { ...input.ctx, env: async (name) => env[name] ?? input.ctx.env(name) }
6844
+ });
6845
+ }
6846
+ } } : {},
6847
+ ...oauth ? { oauth: {
6848
+ ...oauth,
6849
+ async toAuth() {
6850
+ const result = await auth.resolve(id);
6851
+ if (!result) throw new Error("Session Host auth is unavailable");
6852
+ return result.auth;
6853
+ }
6854
+ } } : {}
6855
+ },
6856
+ ...provider.refreshModels ? { async refreshModels(context) {
6857
+ if (catalogAuth && context.allowNetwork && context.credential?.type === "oauth") {
6858
+ const result = await auth.resolve(id, context.signal);
6859
+ if (!result) return;
6860
+ return provider.refreshModels({ ...context, credential: {
6861
+ ...context.credential,
6862
+ access: result.auth.apiKey ?? "",
6863
+ refresh: ""
6864
+ } });
6865
+ }
6866
+ return provider.refreshModels(context);
6867
+ } } : {}
6868
+ };
6869
+ };
6870
+ const registerProviders = () => {
6871
+ if (!metadata.has("radius") && registered.delete("radius")) {
6872
+ unregisterPiNativeProvider(runtime, "radius");
6873
+ registeredGateways.delete("radius");
6874
+ }
6875
+ const gateways = new Map([...metadata.values()].flatMap((entry) => entry.radiusGateway !== void 0 ? [[entry.providerId, entry.radiusGateway]] : []));
6876
+ const baseUrl = runtime.getProvider("radius")?.baseUrl;
6877
+ if (metadata.has("radius") && !gateways.has("radius") && (!baseUrl || /^https:\/\/radius\.pi\.dev(?:\/v1)?\/?$/u.test(baseUrl) || registeredGateways.has("radius"))) gateways.set("radius", "");
6878
+ for (const [id, gateway] of gateways) {
6879
+ if (registeredGateways.get(id) === gateway) continue;
6880
+ const provider = radiusProvider({ id, ...gateway ? { gateway } : {} });
6881
+ registerPiNativeProvider(runtime, brokered(withPi099RadiusCatalog(provider, () => metadata.get(id)?.cachedModels), true));
6882
+ registeredGateways.set(id, gateway);
6883
+ registered.add(id);
6884
+ }
6885
+ for (const entry of metadata.values()) {
6886
+ const id = entry.providerId;
6887
+ if (registered.has(id)) continue;
6888
+ const provider = builtins.get(id) ?? {
6889
+ id,
6890
+ name: id,
6891
+ getModels: () => [],
6892
+ auth: { apiKey: genericApiKey },
6893
+ stream() {
6894
+ throw new Error("Provider requires configured models and API");
6895
+ },
6896
+ streamSimple() {
6897
+ throw new Error("Provider requires configured models and API");
6898
+ }
6899
+ };
6900
+ registerPiNativeProvider(runtime, brokered(provider));
6901
+ registered.add(id);
6902
+ }
6903
+ };
6904
+ registerProviders();
6905
+ runtime.refresh = async (options2 = {}) => {
6906
+ metadata = new Map((await auth.snapshot(options2.signal)).map((entry) => [entry.providerId, entry]));
6907
+ registerProviders();
6908
+ return refresh(options2);
6909
+ };
6910
+ await refresh({ allowNetwork: false, ...signal ? { signal } : {} });
6911
+ if (options.discovery && process.env["PI_OFFLINE"] === void 0) {
6912
+ const force = options.discovery === "refresh";
6913
+ const providers = runtime.getProviders().filter((provider) => runtime.hasConfiguredAuth(provider.id) && (force || builtins.has(provider.id) && provider.id !== "radius" && !registeredGateways.has(provider.id))).map((provider) => provider.id);
6914
+ const timeout = AbortSignal.timeout(5e3);
6915
+ await runtime.refresh({ allowNetwork: true, force, providers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
6916
+ }
6917
+ return runtime;
6918
+ }
6919
+
6920
+ // src/backend/pi/cache-warming.ts
6921
+ function streamingCacheWarming(settings2) {
6922
+ return { name: "flow-streaming-cache-warming", hidden: true, factory: (pi) => {
6923
+ pi.on("cache_warming_decision", (_event, ctx) => {
6924
+ if (settings2.getGlobalSettings().cacheWarming !== "idle" && ctx.isIdle()) return { action: "stop" };
6925
+ });
6926
+ } };
6927
+ }
6928
+
6929
+ // src/backend/pi/todo-list.ts
5038
6930
  import { defineTool as defineTool3 } from "@earendil-works/pi-coding-agent";
5039
- var SUBAGENT_TOOL = "subagent";
6931
+ var TODO_TOOL = "todo_write";
5040
6932
  var parameters2 = typebox_exports.Object({
6933
+ todos: typebox_exports.Array(typebox_exports.Object({
6934
+ content: typebox_exports.String({ minLength: 1 }),
6935
+ status: typebox_exports.Union([typebox_exports.Literal("pending"), typebox_exports.Literal("in_progress"), typebox_exports.Literal("completed")]),
6936
+ priority: typebox_exports.Optional(typebox_exports.Union([typebox_exports.Literal("high"), typebox_exports.Literal("medium"), typebox_exports.Literal("low")]))
6937
+ }))
6938
+ });
6939
+ function piTodoTool(emit) {
6940
+ return defineTool3({
6941
+ name: TODO_TOOL,
6942
+ label: "Update todo list",
6943
+ description: "Replace your todo list for this session with the full list given. Use it to plan and track multi-step work: keep one item in_progress at a time and mark items completed as soon as they are done. Send an empty list to remove it.",
6944
+ promptSnippet: "Plan and track multi-step work as a todo list",
6945
+ parameters: parameters2,
6946
+ execute: async (callId, { todos }) => {
6947
+ emit({ type: "plan", entries: todos, callId });
6948
+ return { content: [{ type: "text", text: "Todo list updated." }], details: {} };
6949
+ }
6950
+ });
6951
+ }
6952
+
6953
+ // src/backend/pi/subagents.ts
6954
+ import { defineTool as defineTool4 } from "@earendil-works/pi-coding-agent";
6955
+ var SUBAGENT_TOOL = "subagent";
6956
+ var parameters3 = typebox_exports.Object({
5041
6957
  description: typebox_exports.String({ minLength: 1, description: "Short description of the delegated work" }),
5042
6958
  prompt: typebox_exports.String({ minLength: 1, description: "Complete instructions; the Subagent cannot see your conversation" }),
5043
6959
  name: typebox_exports.Optional(typebox_exports.String({ minLength: 1 })),
@@ -5045,24 +6961,23 @@ var parameters2 = typebox_exports.Object({
5045
6961
  effort: typebox_exports.Optional(typebox_exports.String({ enum: EFFORT_ORDER, description: "Defaults to the parent's Effort at launch" })),
5046
6962
  run_in_background: typebox_exports.Optional(typebox_exports.Boolean({ description: "Defaults to true. Set false only when your next action requires the result." }))
5047
6963
  });
5048
- function subagentTool(work, run) {
5049
- return defineTool3({
6964
+ function subagentTool(work, run, producer) {
6965
+ return defineTool4({
5050
6966
  name: SUBAGENT_TOOL,
5051
6967
  label: "Subagent",
5052
6968
  description: "Delegate work to a Subagent with its own Conversation Context. Subagents run in the background by default and report back automatically. Multiple Subagents may run concurrently. They cannot ask the human or create further Subagents.",
5053
6969
  promptSnippet: "Delegate independent work to Subagents",
5054
- parameters: parameters2,
5055
- execute: async (id, input, signal) => work.run(
5056
- {
6970
+ parameters: parameters3,
6971
+ execute: async (id, input, signal) => {
6972
+ const subagentId = callIdFor(id, producer);
6973
+ return work.run({
5057
6974
  type: "subagent",
5058
- subagentId: id,
6975
+ subagentId,
5059
6976
  name: input.name ?? "Subagent",
5060
- description: input.description
5061
- },
5062
- (childSignal) => run(id, input, childSignal),
5063
- input.run_in_background !== false,
5064
- signal
5065
- )
6977
+ description: input.description,
6978
+ ...producer ? { producer } : {}
6979
+ }, (childSignal) => run(subagentId, input, childSignal), input.run_in_background !== false, signal);
6980
+ }
5066
6981
  });
5067
6982
  }
5068
6983
 
@@ -5098,7 +7013,7 @@ var PiAgentPermissions = class {
5098
7013
  return { name: "flow-agent-permissions", hidden: true, factory: (pi) => {
5099
7014
  pi.on("tool_call", async (event, ctx) => {
5100
7015
  const tool = event.toolName;
5101
- if (tool === "read" || tool === "ask_question" || tool === "subagent" || tool === "bash_output" || tool === "kill_shell" || tool.startsWith("workflow_") || this.grants.has(tool) || this.mode === "always") return;
7016
+ if (tool === "read" || tool === "session_list" || tool === "session_inspect" || tool === "ask_question" || tool === "todo_write" || tool === "subagent" || tool === "bash_output" || tool === "kill_shell" || tool.startsWith("workflow_") || this.grants.has(tool) || this.mode === "always") return;
5102
7017
  const refusedKey = `${producer?.subagentId ?? "parent"}/${tool}`;
5103
7018
  if (this.refused.has(refusedKey)) return { block: true, reason: `${tool} is not authorised` };
5104
7019
  const id = callIdFor(event.toolCallId, producer);
@@ -5129,9 +7044,57 @@ var PiAgentPermissions = class {
5129
7044
  }
5130
7045
  };
5131
7046
 
7047
+ // src/backend/pi/plan-limits.ts
7048
+ async function fetchAnthropicPlanLimits(token, signal) {
7049
+ const usage = await getJson(
7050
+ "https://api.anthropic.com/api/oauth/usage",
7051
+ { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" },
7052
+ signal
7053
+ );
7054
+ const limits = anthropicPlanLimits(usage);
7055
+ return limits && { provider: "Anthropic", ...limits };
7056
+ }
7057
+ async function fetchCodexPlanLimits(token, signal) {
7058
+ const usage = await getJson(
7059
+ "https://chatgpt.com/backend-api/wham/usage",
7060
+ { authorization: `Bearer ${token}`, "chatgpt-account-id": codexAccountId(token), "user-agent": "codex-cli" },
7061
+ signal
7062
+ );
7063
+ return codexPlanLimits(usage);
7064
+ }
7065
+ function codexPlanLimits(usage) {
7066
+ const short = codexWindow("", usage.rate_limit?.primary_window);
7067
+ const long = codexWindow("", usage.rate_limit?.secondary_window);
7068
+ if (!short || !long) return void 0;
7069
+ const others = (usage.additional_rate_limits ?? []).flatMap((limit) => [
7070
+ codexWindow(`${limit.limit_name} `, limit.rate_limit?.primary_window),
7071
+ codexWindow(`${limit.limit_name} `, limit.rate_limit?.secondary_window)
7072
+ ]).filter((window) => window !== void 0);
7073
+ return { provider: "Codex", short, long, others };
7074
+ }
7075
+ function codexWindow(prefix, window) {
7076
+ if (!window) return void 0;
7077
+ const hours = window.limit_window_seconds / 3600;
7078
+ const span = hours < 24 ? `${Math.round(hours)}-hour` : `${Math.round(hours / 24)}-day`;
7079
+ return { label: `${prefix}${span}`, utilization: window.used_percent, resetsAt: new Date(window.reset_at * 1e3).toISOString() };
7080
+ }
7081
+ function codexAccountId(token) {
7082
+ const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString());
7083
+ const id = payload["https://api.openai.com/auth"]?.chatgpt_account_id;
7084
+ if (!id) throw new Error("No ChatGPT account ID in the Codex token");
7085
+ return id;
7086
+ }
7087
+ async function getJson(url, headers, signal) {
7088
+ const response = await fetch(url, { headers, ...signal ? { signal } : {} });
7089
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
7090
+ return await response.json();
7091
+ }
7092
+
5132
7093
  // src/backend/pi/index.ts
5133
7094
  var PiSession = class {
5134
7095
  capabilities;
7096
+ spend;
7097
+ counted;
5135
7098
  answerEnquiry;
5136
7099
  enquiries;
5137
7100
  work;
@@ -5146,7 +7109,7 @@ var PiSession = class {
5146
7109
  this.unsubscribe();
5147
7110
  current.dispose();
5148
7111
  this.session = await this.recreate(current);
5149
- this.unsubscribe = this.session.subscribe((event) => this.translate(event));
7112
+ this.unsubscribe = this.bindSession();
5150
7113
  }
5151
7114
  standingAuthorisations;
5152
7115
  agentPermissions;
@@ -5175,6 +7138,8 @@ var PiSession = class {
5175
7138
  effort;
5176
7139
  messageSeq = 0;
5177
7140
  currentMessageId;
7141
+ /** Host user message ids sent but not yet seen as pi user messages, oldest first. */
7142
+ unmappedMessageIds = [];
5178
7143
  constructor(session, emit, sessionDir, support = {}) {
5179
7144
  this.workflowBuilder = support.workflowBuilder ?? false;
5180
7145
  this.mcp = support.mcp;
@@ -5183,6 +7148,8 @@ var PiSession = class {
5183
7148
  this.agentPermissions = support.agentPermissions;
5184
7149
  if (support.permissionProducer) this.permissionProducer = support.permissionProducer;
5185
7150
  this.session = session;
7151
+ this.spend = support.priorSpend;
7152
+ this.counted = statsOf(session);
5186
7153
  this.applyAutoCompaction = support.autoCompaction;
5187
7154
  this.workflowAutoCompaction = support.workflowAutoCompaction;
5188
7155
  this.workflowCompactionModelId = support.workflowCompactionModelId;
@@ -5195,7 +7162,15 @@ var PiSession = class {
5195
7162
  if (this.agentPermissions) this.answerPermission = async (callId, decision) => this.agentPermissions.answer(callId, decision);
5196
7163
  if (enquiries) this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
5197
7164
  this.capabilities = capabilitiesOf(session, support.enquiries !== void 0, support.subagents ?? false, !this.workflowBuilder);
5198
- this.unsubscribe = session.subscribe((event) => this.translate(event));
7165
+ this.unsubscribe = this.bindSession();
7166
+ }
7167
+ bindSession() {
7168
+ const stream = this.session.agent?.streamFunction;
7169
+ if (stream) this.session.agent.streamFunction = (...args) => {
7170
+ if (this.disposed) throw new Error("Backend Session stopped");
7171
+ return stream(...args);
7172
+ };
7173
+ return this.session.subscribe((event) => this.translate(event));
5199
7174
  }
5200
7175
  startWorkflowSubagent(options) {
5201
7176
  if (this.disposed) throw new Error("Backend Session stopped");
@@ -5217,7 +7192,9 @@ var PiSession = class {
5217
7192
  resumeToken() {
5218
7193
  return this.sessionDir;
5219
7194
  }
5220
- async prompt(text, attachments) {
7195
+ async prompt(text, attachments, messageId) {
7196
+ if (this.disposed) return;
7197
+ if (messageId && this.sessionDir) this.unmappedMessageIds.push(messageId);
5221
7198
  this.turnId = `turn-${++this.messageSeq}`;
5222
7199
  this.emit({ type: "turn_started", turnId: this.turnId });
5223
7200
  await this.session.prompt(text, {
@@ -5237,10 +7214,8 @@ var PiSession = class {
5237
7214
  }
5238
7215
  async setModel(modelId) {
5239
7216
  const available = await this.session.modelRuntime.getAvailable();
5240
- const qualified = available.find((candidate) => describeModel(candidate).id === modelId);
5241
- const legacy = available.filter((candidate) => candidate.id === modelId);
5242
- const model = qualified ?? (legacy.length === 1 ? legacy[0] : void 0);
5243
- if (!model) throw new Error(`Unknown model: ${modelId}`);
7217
+ const model = findPiModel(available, modelId, true);
7218
+ if (!model) throw new Error(piModelUnavailable(modelId));
5244
7219
  await this.session.setModel(model);
5245
7220
  this.applyAutoCompaction?.(this.session.model);
5246
7221
  this.capabilities = capabilitiesOf(this.session, this.enquiries !== void 0, this.capabilities.subagents, !this.workflowBuilder);
@@ -5299,6 +7274,7 @@ var PiSession = class {
5299
7274
  */
5300
7275
  async skills() {
5301
7276
  await this.session.resourceLoader.reload();
7277
+ this.session.setActiveToolsByName(this.session.getActiveToolNames());
5302
7278
  const { skills } = this.session.resourceLoader.getSkills();
5303
7279
  const { prompts } = this.session.resourceLoader.getPrompts();
5304
7280
  return [
@@ -5310,6 +7286,14 @@ var PiSession = class {
5310
7286
  }))
5311
7287
  ];
5312
7288
  }
7289
+ async planLimits() {
7290
+ const read = async (provider, fetchLimits) => {
7291
+ const token = (await this.session.modelRuntime.getAuth(provider).catch(() => void 0))?.auth.apiKey;
7292
+ return token ? await fetchLimits(token).catch(() => void 0) : void 0;
7293
+ };
7294
+ const limits = await Promise.all([read("anthropic", fetchAnthropicPlanLimits), read("openai-codex", fetchCodexPlanLimits)]);
7295
+ return limits.filter((limit) => limit !== void 0);
7296
+ }
5313
7297
  applyEffort(wanted) {
5314
7298
  const level = clampEffort(wanted, availableEffort(this.session));
5315
7299
  if (!level) {
@@ -5389,6 +7373,14 @@ var PiSession = class {
5389
7373
  this.emit({ type: "turn_ended", turnId, reason });
5390
7374
  this.scheduleCompletions();
5391
7375
  }
7376
+ /** pi appends the entry just after `message_end` reaches listeners, so look it up after that. */
7377
+ mapUserMessage(messageId, message) {
7378
+ queueMicrotask(() => {
7379
+ const entry = this.session.sessionManager.getBranch().findLast((candidate) => candidate.type === "message" && candidate.message === message);
7380
+ if (!entry || !this.sessionDir) return;
7381
+ writeFileSync(join2(this.sessionDir, USER_MESSAGE_MAP), JSON.stringify({ ...readUserMessageMap(this.sessionDir), [messageId]: entry.id }), { mode: 384 });
7382
+ });
7383
+ }
5392
7384
  translate(event) {
5393
7385
  switch (event.type) {
5394
7386
  case "agent_start":
@@ -5403,6 +7395,7 @@ var PiSession = class {
5403
7395
  case "message_end":
5404
7396
  this.emitMessage(event.message, true);
5405
7397
  this.currentMessageId = void 0;
7398
+ if (event.message.role === "user" && this.unmappedMessageIds.length) this.mapUserMessage(this.unmappedMessageIds.shift(), event.message);
5406
7399
  return;
5407
7400
  case "tool_execution_start":
5408
7401
  this.emit({ type: "tool_started", callId: event.toolCallId, name: event.toolName, input: event.args });
@@ -5428,7 +7421,7 @@ var PiSession = class {
5428
7421
  return;
5429
7422
  }
5430
7423
  case "agent_settled":
5431
- this.finishTurn(this.aborting ? "aborted" : this.turnReason);
7424
+ this.finishTurn(event.aborted || this.aborting ? "aborted" : this.turnReason);
5432
7425
  return;
5433
7426
  case "auto_retry_start":
5434
7427
  this.emit({
@@ -5488,11 +7481,27 @@ var PiSession = class {
5488
7481
  if (thinking) this.emit({ type: "thinking", id: `${id}-thinking`, text: thinking, final });
5489
7482
  }
5490
7483
  reportContextUsage() {
7484
+ this.countSpend();
5491
7485
  const usage = this.session.getContextUsage();
5492
7486
  if (usage && typeof usage.tokens === "number") {
5493
- this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow });
7487
+ this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow, ...this.spend ? { spend: this.spend } : {} });
5494
7488
  }
5495
7489
  }
7490
+ countSpend() {
7491
+ const now = statsOf(this.session);
7492
+ const added = { tokens: now.tokens - this.counted.tokens, cached: now.cached - this.counted.cached, costUSD: now.costUSD - this.counted.costUSD };
7493
+ this.counted = now;
7494
+ if (added.tokens <= 0 && added.costUSD <= 0) return;
7495
+ const id = this.session.model ? describeModel(this.session.model).id : "unknown";
7496
+ const spend = this.spend ?? { tokens: 0, cached: 0, costUSD: 0, models: [] };
7497
+ const model = spend.models.find((item) => item.id === id) ?? { id, tokens: 0, cached: 0, costUSD: 0 };
7498
+ this.spend = {
7499
+ tokens: spend.tokens + added.tokens,
7500
+ cached: spend.cached + added.cached,
7501
+ costUSD: spend.costUSD + added.costUSD,
7502
+ models: [...spend.models.filter((item) => item.id !== id), { id, tokens: model.tokens + added.tokens, cached: model.cached + added.cached, costUSD: model.costUSD + added.costUSD }]
7503
+ };
7504
+ }
5496
7505
  };
5497
7506
  var PiBackend = class {
5498
7507
  name = "pi";
@@ -5501,9 +7510,13 @@ var PiBackend = class {
5501
7510
  this.options = options;
5502
7511
  }
5503
7512
  async create(options) {
5504
- const agentDir = getAgentDir2();
7513
+ const agentDir = getAgentDir3();
7514
+ const modelRuntime = options.piAuth ? await createWorkerPiModelRuntime(options.piAuth, join2(agentDir, "models.json"), options.signal, {
7515
+ ...options.stateDir ? { modelsStorePath: join2(options.stateDir, "models-store.json") } : {},
7516
+ discovery: options.refreshModels ? "refresh" : "automatic"
7517
+ }) : void 0;
5505
7518
  const builder = options.workflowBuilder;
5506
- const settingsManager = builder ? SettingsManager2.inMemory() : SettingsManager2.create(options.scope, agentDir);
7519
+ const settingsManager = builder ? SettingsManager2.inMemory({ cacheWarming: "streaming" }) : SettingsManager2.create(options.scope, agentDir);
5507
7520
  const agentPermissions = builder || options.tools === "none" ? void 0 : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
5508
7521
  const resourceLoader = new DefaultResourceLoader2({
5509
7522
  cwd: options.scope,
@@ -5518,7 +7531,9 @@ var PiBackend = class {
5518
7531
  appendSystemPromptOverride: () => [],
5519
7532
  systemPromptOverride: () => builder.instructions
5520
7533
  } : {
7534
+ appendSystemPromptOverride: (base) => [...base, DIFF_EXCERPT_INSTRUCTIONS],
5521
7535
  extensionFactories: [
7536
+ streamingCacheWarming(settingsManager),
5522
7537
  ...agentPermissions ? [agentPermissions.extension()] : [],
5523
7538
  ...options.compactionModelId ? [compactionModelExtension(
5524
7539
  options.compactionModelId,
@@ -5535,20 +7550,24 @@ var PiBackend = class {
5535
7550
  const tools = builder ? builderTools.map((tool) => tool.name) : options.tools === "none" ? [] : [...this.options.tools ?? [
5536
7551
  ...defaults,
5537
7552
  ASK_TOOL,
7553
+ TODO_TOOL,
5538
7554
  SUBAGENT_TOOL,
5539
7555
  ...defaults.includes("bash") ? ["bash_output", "kill_shell"] : []
5540
- ]];
7556
+ ]].filter((name) => !readOnlyDeniedTools(options.readOnly).includes(name));
5541
7557
  const mcp = builder || options.tools === "none" ? void 0 : options.mcp;
5542
7558
  const workflowTools = workflowParentTools(builder || options.tools === "none" ? void 0 : options.workflow);
5543
- tools.push(...workflowTools.map((tool) => tool.name));
7559
+ const sessionTools = piSessionTools(builder || options.tools === "none" ? void 0 : options.sessionTools);
7560
+ tools.push(...workflowTools.map((tool) => tool.name), ...sessionTools.map((tool) => tool.name));
5544
7561
  const enabled = (name) => tools.includes(name);
5545
7562
  const enquiries = enabled(ASK_TOOL) ? new PiEnquiries(options.emit) : void 0;
5546
7563
  const work = new PiWork(options.emit, (completion) => piSession.completed(completion));
5547
7564
  const subagents = enabled(SUBAGENT_TOOL);
5548
7565
  const customTools = builder ? builderTools : [
5549
7566
  ...workflowTools,
7567
+ ...sessionTools,
5550
7568
  ...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
5551
7569
  ...enquiries ? [enquiries.tool] : [],
7570
+ ...enabled(TODO_TOOL) ? [piTodoTool(options.emit)] : [],
5552
7571
  ...subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId, agentPermissions))] : []
5553
7572
  ];
5554
7573
  const start = (current) => {
@@ -5558,6 +7577,7 @@ var PiBackend = class {
5558
7577
  agentDir,
5559
7578
  resourceLoader,
5560
7579
  settingsManager,
7580
+ ...modelRuntime ? { modelRuntime } : {},
5561
7581
  customTools: [...customTools, ...mcpTools],
5562
7582
  tools: [...tools, ...mcpTools.map((tool) => tool.name)],
5563
7583
  ...current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...current.model ? { model: current.model } : {} } : sessionManager ? { sessionManager } : {},
@@ -5565,16 +7585,25 @@ var PiBackend = class {
5565
7585
  });
5566
7586
  };
5567
7587
  let { session, extensionsResult } = await start();
7588
+ if (options.resumeBefore && sessionDir) {
7589
+ const entryId = readUserMessageMap(sessionDir)[options.resumeBefore];
7590
+ if (!entryId) {
7591
+ session.dispose();
7592
+ throw new Error("This message cannot be rewound: pi has no record of it");
7593
+ }
7594
+ await session.navigateTree(entryId);
7595
+ }
5568
7596
  const extensionError = options.compactionModelId && compactionExtensionError(extensionsResult.errors);
5569
7597
  if (extensionError) {
5570
7598
  session.dispose();
5571
7599
  throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
5572
7600
  }
5573
7601
  const autoCompaction = structuredClone(options.autoCompaction);
5574
- const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...mcp ? { mcp } : {}, work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...agentPermissions ? { agentPermissions } : {}, autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}, ...options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}, ...enquiries ? { enquiries } : {}, ...mcp ? { recreate: async (current) => session = (await start(current)).session } : {} });
5575
- if (options.modelId) {
7602
+ const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...mcp ? { mcp } : {}, work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...agentPermissions ? { agentPermissions } : {}, ...options.priorSpend ? { priorSpend: options.priorSpend } : {}, autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}, ...options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}, ...enquiries ? { enquiries } : {}, ...mcp ? { recreate: async (current) => session = (await start(current)).session } : {} });
7603
+ const modelId = options.modelId ?? (settingsManager.getDefaultProvider() === "azure-openai-responses" && settingsManager.getDefaultModel() ? `azure-openai-responses/${settingsManager.getDefaultModel()}` : void 0);
7604
+ if (modelId) {
5576
7605
  try {
5577
- await piSession.setModel(options.modelId);
7606
+ await piSession.setModel(modelId);
5578
7607
  } catch (error) {
5579
7608
  await piSession.dispose();
5580
7609
  throw error;
@@ -5598,12 +7627,16 @@ var PiBackend = class {
5598
7627
  return piSession;
5599
7628
  }
5600
7629
  };
7630
+ function readOnlyDeniedTools(readOnly) {
7631
+ if (!readOnly) return [];
7632
+ return ["edit", "write", ...readOnly === "tools" ? ["bash", "bash_output", "kill_shell", "powershell"] : []];
7633
+ }
5601
7634
  async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId, agentPermissions) {
5602
7635
  const available = parent.modelRuntime.getAvailableSnapshot();
5603
- const model = input.model ? available.find((model2) => describeModel(model2).id === input.model) : parent.model;
5604
- if (!model) throw new Error(`Unknown model: ${input.model}. Available: ${available.map((model2) => describeModel(model2).id).join(", ")}`);
7636
+ const model = input.model ? findPiModel(available, input.model) : parent.model;
7637
+ if (!model) throw new Error(`${piModelUnavailable(input.model ?? "(inherited)")} Available: ${available.map((model2) => describeModel(model2).id).join(", ")}`);
5605
7638
  const effort = input.effort ?? parent.thinkingLevel;
5606
- const tools = [.../* @__PURE__ */ new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_"));
7639
+ const tools = [.../* @__PURE__ */ new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== TODO_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_") && !name.startsWith("session_"));
5607
7640
  const settingsManager = SettingsManager2.create(scope, agentDir);
5608
7641
  const producer = { subagentId: id };
5609
7642
  const resourceLoader = new DefaultResourceLoader2({
@@ -5612,13 +7645,14 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
5612
7645
  settingsManager,
5613
7646
  noExtensions: true,
5614
7647
  extensionFactories: [
7648
+ streamingCacheWarming(settingsManager),
5615
7649
  ...agentPermissions ? [agentPermissions.extension(producer)] : [],
5616
7650
  ...compactionModelId ? [compactionModelExtension(
5617
7651
  compactionModelId,
5618
7652
  (text) => emit({ type: "notice", level: "error", text })
5619
7653
  )] : []
5620
7654
  ],
5621
- appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents."]
7655
+ appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents.", DIFF_EXCERPT_INSTRUCTIONS]
5622
7656
  });
5623
7657
  await resourceLoader.reload();
5624
7658
  signal.throwIfAborted();
@@ -5673,7 +7707,9 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
5673
7707
  try {
5674
7708
  signal.throwIfAborted();
5675
7709
  await adapter.setEffort(effort);
7710
+ work.refine(id, { model: describeModel(model).id, effort: child.thinkingLevel });
5676
7711
  signal.throwIfAborted();
7712
+ emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
5677
7713
  await adapter.prompt(input.prompt);
5678
7714
  if (reason !== "complete") throw new Error(failure ?? `Subagent ${reason}`);
5679
7715
  return textResult(output || "Subagent completed without text output");
@@ -5684,6 +7720,10 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
5684
7720
  if (input.run_in_background === false) await work.stopOwnedCalls(id);
5685
7721
  }
5686
7722
  }
7723
+ function readUserMessageMap(sessionDir) {
7724
+ const path = join2(sessionDir, USER_MESSAGE_MAP);
7725
+ return existsSync2(path) ? JSON.parse(readFileSync2(path, "utf8")) : {};
7726
+ }
5687
7727
  function capabilitiesOf(session, enquiries, subagents, permissions = true) {
5688
7728
  const models = session.modelRuntime.getAvailableSnapshot().map(describeModel);
5689
7729
  const providers = [...new Set(models.map((model) => model.provider).filter(isString))];
@@ -5692,7 +7732,8 @@ function capabilitiesOf(session, enquiries, subagents, permissions = true) {
5692
7732
  models,
5693
7733
  compaction: true,
5694
7734
  autoCompaction: "model-change",
5695
- fork: false,
7735
+ fork: true,
7736
+ rewind: true,
5696
7737
  subagents,
5697
7738
  enquiries,
5698
7739
  permissions
@@ -5723,6 +7764,10 @@ function joinBlocks(content, kind) {
5723
7764
  function isString(value) {
5724
7765
  return typeof value === "string";
5725
7766
  }
7767
+ function statsOf(session) {
7768
+ const stats = session.getSessionStats();
7769
+ return { tokens: stats.tokens.total, cached: stats.tokens.cacheRead, costUSD: stats.cost };
7770
+ }
5726
7771
  export {
5727
7772
  PiBackend,
5728
7773
  PiSession,