tune-sdk 0.1.3 → 0.1.4

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.
package/bin/cli.js ADDED
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+
3
+ // Minimal inline argument parser
4
+ const args = {};
5
+ let currentKey = null;
6
+
7
+ process.argv.slice(2).forEach(arg => {
8
+ if (arg.startsWith('--')) {
9
+ const [key, value] = arg.substring(2).split('=');
10
+ if (typeof value !== 'undefined') {
11
+ args[key] = value;
12
+ currentKey = null;
13
+ } else {
14
+ currentKey = key;
15
+ args[currentKey] = true
16
+ }
17
+ } else if (currentKey) {
18
+ args[currentKey] = arg;
19
+ currentKey = null;
20
+ }
21
+ });
22
+
23
+ // Example usage outputs (replace with your real logic)
24
+ /*
25
+ if (args.filename) {
26
+ console.log('filename:', args.filename);
27
+ }
28
+ if (args.system) {
29
+ console.log('system:', args.system);
30
+ }
31
+ if (args.user) {
32
+ console.log('user:', args.user);
33
+ }
34
+ if ('save' in args) {
35
+ console.log('save flag set');
36
+ }
37
+ if (args.stop) {
38
+ console.log('stop:', args.stop);
39
+ }
40
+ */
41
+
42
+ // Place your main script/logic here
43
+ const tune = require('../dist/tune.js');
44
+ const { fsctx } = require('../dist/fsctx.js');
45
+ const fs = require("fs");
46
+ const path = require("path");
47
+
48
+ async function main() {
49
+ let chat = ""
50
+ // where to search for inclusions
51
+ let dirs = [];
52
+
53
+ if (args.filename && fs.existsSync(args.filename)) {
54
+ chat = fs.readFileSync(args.filename, "utf8")
55
+ dirs.push(path.dirname(path.resolve(args.filename)))
56
+ }
57
+
58
+ if (!chat && args.system) {
59
+ chat = `system:\n${args.system}`
60
+ }
61
+
62
+ if (args.user) {
63
+ chat = `${chat}\nuser:\n${args.user}`
64
+ }
65
+
66
+ if(process.env.TUNE_PATH) {
67
+ dirs = dirs.concat(process.env.TUNE_PATH.split(path.delimiter))
68
+ }
69
+
70
+ dirs.push(process.cwd())
71
+
72
+ const ctx = tune.makeContext(process.env)
73
+ if (args.filename) {
74
+ ctx.stack.push({
75
+ filename: args.filename,
76
+ name: path.basename(args.filename),
77
+ dirname: path.dirname(path.resolve(args.filename))
78
+ })
79
+ }
80
+ ctx.use(fsctx(dirs))
81
+
82
+ for (const dir of dirs) {
83
+ let filename = ["default.ctx.js", "default.ctx.cjs", "default.ctx.mjs"].find(name => fs.existsSync(path.join(dir, name)));
84
+ if (!filename) continue;
85
+ filename = path.join(dir, filename);
86
+ let ext = path.extname(filename);
87
+ let module
88
+ if ((ext === ".js" || ext === ".cjs")) {
89
+ module = require(filename);
90
+ } else {
91
+ module = await import(filename);
92
+ module = module.default;
93
+ }
94
+ if (typeof module === "function") {
95
+ ctx.use(module);
96
+ } else if (Array.isArray(module)) {
97
+ for (const m of module) {
98
+ if (typeof m === "function") {
99
+ ctx.use(m)
100
+ } else {
101
+ throw(Error(`err: Context file export is not an array of functions or function ${filename}`))
102
+ }
103
+ }
104
+ } else {
105
+ throw(Error(`err: Context file export is not an array of functions or function ${filename}`))
106
+ }
107
+ }
108
+
109
+ const longFormatRegex = /^(system|user|tool_call|tool_result|assistant|error):/;
110
+ let res = await tune.text2run(chat, ctx, args.step || "assistant")
111
+ res = tune.msg2text(res, longFormatRegex.test(chat))
112
+ if (args.filename && args.save) {
113
+ chat += "\n" + res
114
+ fs.writeFileSync(args.filename, chat)
115
+ }
116
+ if (!args.save) {
117
+ console.log(res)
118
+ }
119
+ }
120
+
121
+ main()
package/dist/fsctx.js ADDED
@@ -0,0 +1,1059 @@
1
+ var path, tune, makeContext, envmd, TuneError, text2run;
2
+
3
+ function extend() {
4
+ var _i;
5
+ var objects = 1 <= arguments.length ? [].slice.call(arguments, 0, _i = arguments.length - 0) : (_i = 0, []);
6
+ return (function(result) {
7
+ var object, key, value, _i0, _ref, _len, _ref0, _len0;
8
+ _ref = objects;
9
+ for (_i0 = 0, _len = _ref.length; _i0 < _len; ++_i0) {
10
+ object = _ref[_i0];
11
+ _ref0 = object;
12
+ for (key in _ref0) {
13
+ value = _ref0[key];
14
+ if ((typeof value !== 'undefined')) result[key] = JSON.parse(JSON.stringify(value));
15
+ }
16
+ }
17
+ return result;
18
+ })({});
19
+ }
20
+ extend;
21
+ let msgpack = (function() {
22
+ "use strict";
23
+
24
+ // Serializes a value to a MessagePack byte array.
25
+ //
26
+ // data: The value to serialize. This can be a scalar, array or object.
27
+ // options: An object that defines additional options.
28
+ // - multiple: (boolean) Indicates whether multiple values in data are concatenated to multiple MessagePack arrays. Default: false.
29
+ // - invalidTypeReplacement:
30
+ // (any) The value that is used to replace values of unsupported types.
31
+ // (function) A function that returns such a value, given the original value as parameter.
32
+ function serialize(data, options) {
33
+ if (options && options.multiple && !Array.isArray(data)) {
34
+ throw new Error(
35
+ "Invalid argument type: Expected an Array to serialize multiple values.",
36
+ );
37
+ }
38
+ const pow32 = 0x100000000; // 2^32
39
+ let floatBuffer, floatView;
40
+ let array = new Uint8Array(128);
41
+ let length = 0;
42
+ if (options && options.multiple) {
43
+ for (let i = 0; i < data.length; i++) {
44
+ append(data[i]);
45
+ }
46
+ } else {
47
+ append(data);
48
+ }
49
+ return array.subarray(0, length);
50
+
51
+ function append(data, isReplacement) {
52
+ switch (typeof data) {
53
+ case "undefined":
54
+ appendNull(data);
55
+ break;
56
+ case "boolean":
57
+ appendBoolean(data);
58
+ break;
59
+ case "number":
60
+ appendNumber(data);
61
+ break;
62
+ case "string":
63
+ appendString(data);
64
+ break;
65
+ case "object":
66
+ if (data === null) appendNull(data);
67
+ else if (data instanceof Date) appendDate(data);
68
+ else if (Array.isArray(data)) appendArray(data);
69
+ else if (
70
+ data instanceof Uint8Array ||
71
+ data instanceof Uint8ClampedArray
72
+ )
73
+ appendBinArray(data);
74
+ else if (
75
+ data instanceof Int8Array ||
76
+ data instanceof Int16Array ||
77
+ data instanceof Uint16Array ||
78
+ data instanceof Int32Array ||
79
+ data instanceof Uint32Array ||
80
+ data instanceof Float32Array ||
81
+ data instanceof Float64Array
82
+ )
83
+ appendArray(data);
84
+ else appendObject(data);
85
+ break;
86
+ default:
87
+ if (!isReplacement && options && options.invalidTypeReplacement) {
88
+ if (typeof options.invalidTypeReplacement === "function")
89
+ append(options.invalidTypeReplacement(data), true);
90
+ else append(options.invalidTypeReplacement, true);
91
+ } else {
92
+ throw new Error(
93
+ "Invalid argument type: The type '" +
94
+ typeof data +
95
+ "' cannot be serialized.",
96
+ );
97
+ }
98
+ }
99
+ }
100
+
101
+ function appendNull(data) {
102
+ appendByte(0xc0);
103
+ }
104
+
105
+ function appendBoolean(data) {
106
+ appendByte(data ? 0xc3 : 0xc2);
107
+ }
108
+
109
+ function appendNumber(data) {
110
+ if (isFinite(data) && Number.isSafeInteger(data)) {
111
+ // Integer
112
+ if (data >= 0 && data <= 0x7f) {
113
+ appendByte(data);
114
+ } else if (data < 0 && data >= -0x20) {
115
+ appendByte(data);
116
+ } else if (data > 0 && data <= 0xff) {
117
+ // uint8
118
+ appendBytes([0xcc, data]);
119
+ } else if (data >= -0x80 && data <= 0x7f) {
120
+ // int8
121
+ appendBytes([0xd0, data]);
122
+ } else if (data > 0 && data <= 0xffff) {
123
+ // uint16
124
+ appendBytes([0xcd, data >>> 8, data]);
125
+ } else if (data >= -0x8000 && data <= 0x7fff) {
126
+ // int16
127
+ appendBytes([0xd1, data >>> 8, data]);
128
+ } else if (data > 0 && data <= 0xffffffff) {
129
+ // uint32
130
+ appendBytes([0xce, data >>> 24, data >>> 16, data >>> 8, data]);
131
+ } else if (data >= -0x80000000 && data <= 0x7fffffff) {
132
+ // int32
133
+ appendBytes([0xd2, data >>> 24, data >>> 16, data >>> 8, data]);
134
+ } else if (data > 0 && data <= 0xffffffffffffffff) {
135
+ // uint64
136
+ appendByte(0xcf);
137
+ appendInt64(data);
138
+ } else if (data >= -0x8000000000000000 && data <= 0x7fffffffffffffff) {
139
+ // int64
140
+ appendByte(0xd3);
141
+ appendInt64(data);
142
+ } else if (data < 0) {
143
+ // below int64
144
+ appendBytes([0xd3, 0x80, 0, 0, 0, 0, 0, 0, 0]);
145
+ } else {
146
+ // above uint64
147
+ appendBytes([0xcf, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
148
+ }
149
+ } else {
150
+ // Float
151
+ if (!floatView) {
152
+ floatBuffer = new ArrayBuffer(8);
153
+ floatView = new DataView(floatBuffer);
154
+ }
155
+ floatView.setFloat64(0, data);
156
+ appendByte(0xcb);
157
+ appendBytes(new Uint8Array(floatBuffer));
158
+ }
159
+ }
160
+
161
+ function appendString(data) {
162
+ let bytes = encodeUtf8(data);
163
+ let length = bytes.length;
164
+
165
+ if (length <= 0x1f) appendByte(0xa0 + length);
166
+ else if (length <= 0xff) appendBytes([0xd9, length]);
167
+ else if (length <= 0xffff) appendBytes([0xda, length >>> 8, length]);
168
+ else
169
+ appendBytes([0xdb, length >>> 24, length >>> 16, length >>> 8, length]);
170
+
171
+ appendBytes(bytes);
172
+ }
173
+
174
+ function appendArray(data) {
175
+ let length = data.length;
176
+
177
+ if (length <= 0xf) appendByte(0x90 + length);
178
+ else if (length <= 0xffff) appendBytes([0xdc, length >>> 8, length]);
179
+ else
180
+ appendBytes([0xdd, length >>> 24, length >>> 16, length >>> 8, length]);
181
+
182
+ for (let index = 0; index < length; index++) {
183
+ append(data[index]);
184
+ }
185
+ }
186
+
187
+ function appendBinArray(data) {
188
+ let length = data.length;
189
+
190
+ if (length <= 0xff) appendBytes([0xc4, length]);
191
+ else if (length <= 0xffff) appendBytes([0xc5, length >>> 8, length]);
192
+ else
193
+ appendBytes([0xc6, length >>> 24, length >>> 16, length >>> 8, length]);
194
+
195
+ appendBytes(data);
196
+ }
197
+
198
+ function appendObject(data) {
199
+ let length = 0;
200
+ for (let key in data) {
201
+ if (data[key] !== undefined) {
202
+ length++;
203
+ }
204
+ }
205
+
206
+ if (length <= 0xf) appendByte(0x80 + length);
207
+ else if (length <= 0xffff) appendBytes([0xde, length >>> 8, length]);
208
+ else
209
+ appendBytes([0xdf, length >>> 24, length >>> 16, length >>> 8, length]);
210
+
211
+ for (let key in data) {
212
+ let value = data[key];
213
+ if (value !== undefined) {
214
+ append(key);
215
+ append(value);
216
+ }
217
+ }
218
+ }
219
+
220
+ function appendDate(data) {
221
+ let sec = data.getTime() / 1000;
222
+ if (data.getMilliseconds() === 0 && sec >= 0 && sec < 0x100000000) {
223
+ // 32 bit seconds
224
+ appendBytes([0xd6, 0xff, sec >>> 24, sec >>> 16, sec >>> 8, sec]);
225
+ } else if (sec >= 0 && sec < 0x400000000) {
226
+ // 30 bit nanoseconds, 34 bit seconds
227
+ let ns = data.getMilliseconds() * 1000000;
228
+ appendBytes([
229
+ 0xd7,
230
+ 0xff,
231
+ ns >>> 22,
232
+ ns >>> 14,
233
+ ns >>> 6,
234
+ ((ns << 2) >>> 0) | (sec / pow32),
235
+ sec >>> 24,
236
+ sec >>> 16,
237
+ sec >>> 8,
238
+ sec,
239
+ ]);
240
+ } else {
241
+ // 32 bit nanoseconds, 64 bit seconds, negative values allowed
242
+ let ns = data.getMilliseconds() * 1000000;
243
+ appendBytes([0xc7, 12, 0xff, ns >>> 24, ns >>> 16, ns >>> 8, ns]);
244
+ appendInt64(sec);
245
+ }
246
+ }
247
+
248
+ function appendByte(byte) {
249
+ if (array.length < length + 1) {
250
+ let newLength = array.length * 2;
251
+ while (newLength < length + 1) newLength *= 2;
252
+ let newArray = new Uint8Array(newLength);
253
+ newArray.set(array);
254
+ array = newArray;
255
+ }
256
+ array[length] = byte;
257
+ length++;
258
+ }
259
+
260
+ function appendBytes(bytes) {
261
+ if (array.length < length + bytes.length) {
262
+ let newLength = array.length * 2;
263
+ while (newLength < length + bytes.length) newLength *= 2;
264
+ let newArray = new Uint8Array(newLength);
265
+ newArray.set(array);
266
+ array = newArray;
267
+ }
268
+ array.set(bytes, length);
269
+ length += bytes.length;
270
+ }
271
+
272
+ function appendInt64(value) {
273
+ // Split 64 bit number into two 32 bit numbers because JavaScript only regards 32 bits for
274
+ // bitwise operations.
275
+ let hi, lo;
276
+ if (value >= 0) {
277
+ // Same as uint64
278
+ hi = value / pow32;
279
+ lo = value % pow32;
280
+ } else {
281
+ // Split absolute value to high and low, then NOT and ADD(1) to restore negativity
282
+ value++;
283
+ hi = Math.abs(value) / pow32;
284
+ lo = Math.abs(value) % pow32;
285
+ hi = ~hi;
286
+ lo = ~lo;
287
+ }
288
+ appendBytes([
289
+ hi >>> 24,
290
+ hi >>> 16,
291
+ hi >>> 8,
292
+ hi,
293
+ lo >>> 24,
294
+ lo >>> 16,
295
+ lo >>> 8,
296
+ lo,
297
+ ]);
298
+ }
299
+ }
300
+
301
+ // Deserializes a MessagePack byte array to a value.
302
+ //
303
+ // array: The MessagePack byte array to deserialize. This must be an Array or Uint8Array containing bytes, not a string.
304
+ // options: An object that defines additional options.
305
+ // - multiple: (boolean) Indicates whether multiple concatenated MessagePack arrays are returned as an array. Default: false.
306
+ function deserialize(array, options) {
307
+ const pow32 = 0x100000000; // 2^32
308
+ let pos = 0;
309
+ if (array instanceof ArrayBuffer) {
310
+ array = new Uint8Array(array);
311
+ }
312
+ if (typeof array !== "object" || typeof array.length === "undefined") {
313
+ throw new Error(
314
+ "Invalid argument type: Expected a byte array (Array or Uint8Array) to deserialize.",
315
+ );
316
+ }
317
+ if (!array.length) {
318
+ throw new Error(
319
+ "Invalid argument: The byte array to deserialize is empty.",
320
+ );
321
+ }
322
+ if (!(array instanceof Uint8Array)) {
323
+ array = new Uint8Array(array);
324
+ }
325
+ let data;
326
+ if (options && options.multiple) {
327
+ // Read as many messages as are available
328
+ data = [];
329
+ while (pos < array.length) {
330
+ data.push(read());
331
+ }
332
+ } else {
333
+ // Read only one message and ignore additional data
334
+ data = read();
335
+ }
336
+ return data;
337
+
338
+ function read() {
339
+ const byte = array[pos++];
340
+ if (byte >= 0x00 && byte <= 0x7f) return byte; // positive fixint
341
+ if (byte >= 0x80 && byte <= 0x8f) return readMap(byte - 0x80); // fixmap
342
+ if (byte >= 0x90 && byte <= 0x9f) return readArray(byte - 0x90); // fixarray
343
+ if (byte >= 0xa0 && byte <= 0xbf) return readStr(byte - 0xa0); // fixstr
344
+ if (byte === 0xc0) return null; // nil
345
+ if (byte === 0xc1) throw new Error("Invalid byte code 0xc1 found."); // never used
346
+ if (byte === 0xc2) return false; // false
347
+ if (byte === 0xc3) return true; // true
348
+ if (byte === 0xc4) return readBin(-1, 1); // bin 8
349
+ if (byte === 0xc5) return readBin(-1, 2); // bin 16
350
+ if (byte === 0xc6) return readBin(-1, 4); // bin 32
351
+ if (byte === 0xc7) return readExt(-1, 1); // ext 8
352
+ if (byte === 0xc8) return readExt(-1, 2); // ext 16
353
+ if (byte === 0xc9) return readExt(-1, 4); // ext 32
354
+ if (byte === 0xca) return readFloat(4); // float 32
355
+ if (byte === 0xcb) return readFloat(8); // float 64
356
+ if (byte === 0xcc) return readUInt(1); // uint 8
357
+ if (byte === 0xcd) return readUInt(2); // uint 16
358
+ if (byte === 0xce) return readUInt(4); // uint 32
359
+ if (byte === 0xcf) return readUInt(8); // uint 64
360
+ if (byte === 0xd0) return readInt(1); // int 8
361
+ if (byte === 0xd1) return readInt(2); // int 16
362
+ if (byte === 0xd2) return readInt(4); // int 32
363
+ if (byte === 0xd3) return readInt(8); // int 64
364
+ if (byte === 0xd4) return readExt(1); // fixext 1
365
+ if (byte === 0xd5) return readExt(2); // fixext 2
366
+ if (byte === 0xd6) return readExt(4); // fixext 4
367
+ if (byte === 0xd7) return readExt(8); // fixext 8
368
+ if (byte === 0xd8) return readExt(16); // fixext 16
369
+ if (byte === 0xd9) return readStr(-1, 1); // str 8
370
+ if (byte === 0xda) return readStr(-1, 2); // str 16
371
+ if (byte === 0xdb) return readStr(-1, 4); // str 32
372
+ if (byte === 0xdc) return readArray(-1, 2); // array 16
373
+ if (byte === 0xdd) return readArray(-1, 4); // array 32
374
+ if (byte === 0xde) return readMap(-1, 2); // map 16
375
+ if (byte === 0xdf) return readMap(-1, 4); // map 32
376
+ if (byte >= 0xe0 && byte <= 0xff) return byte - 256; // negative fixint
377
+ console.debug("msgpack array:", array);
378
+ throw new Error(
379
+ "Invalid byte value '" +
380
+ byte +
381
+ "' at index " +
382
+ (pos - 1) +
383
+ " in the MessagePack binary data (length " +
384
+ array.length +
385
+ "): Expecting a range of 0 to 255. This is not a byte array.",
386
+ );
387
+ }
388
+
389
+ function readInt(size) {
390
+ let value = 0;
391
+ let first = true;
392
+ while (size-- > 0) {
393
+ if (first) {
394
+ let byte = array[pos++];
395
+ value += byte & 0x7f;
396
+ if (byte & 0x80) {
397
+ value -= 0x80; // Treat most-significant bit as -2^i instead of 2^i
398
+ }
399
+ first = false;
400
+ } else {
401
+ value *= 256;
402
+ value += array[pos++];
403
+ }
404
+ }
405
+ return value;
406
+ }
407
+
408
+ function readUInt(size) {
409
+ let value = 0;
410
+ while (size-- > 0) {
411
+ value *= 256;
412
+ value += array[pos++];
413
+ }
414
+ return value;
415
+ }
416
+
417
+ function readFloat(size) {
418
+ let view = new DataView(array.buffer, pos + array.byteOffset, size);
419
+ pos += size;
420
+ if (size === 4) return view.getFloat32(0, false);
421
+ if (size === 8) return view.getFloat64(0, false);
422
+ }
423
+
424
+ function readBin(size, lengthSize) {
425
+ if (size < 0) size = readUInt(lengthSize);
426
+ let data = array.subarray(pos, pos + size);
427
+ pos += size;
428
+ return data;
429
+ }
430
+
431
+ function readMap(size, lengthSize) {
432
+ if (size < 0) size = readUInt(lengthSize);
433
+ let data = {};
434
+ while (size-- > 0) {
435
+ let key = read();
436
+ data[key] = read();
437
+ }
438
+ return data;
439
+ }
440
+
441
+ function readArray(size, lengthSize) {
442
+ if (size < 0) size = readUInt(lengthSize);
443
+ let data = [];
444
+ while (size-- > 0) {
445
+ data.push(read());
446
+ }
447
+ return data;
448
+ }
449
+
450
+ function readStr(size, lengthSize) {
451
+ if (size < 0) size = readUInt(lengthSize);
452
+ let start = pos;
453
+ pos += size;
454
+ return decodeUtf8(array, start, size);
455
+ }
456
+
457
+ function readExt(size, lengthSize) {
458
+ if (size < 0) size = readUInt(lengthSize);
459
+ let type = readUInt(1);
460
+ let data = readBin(size);
461
+ switch (type) {
462
+ case 255:
463
+ return readExtDate(data);
464
+ }
465
+ return {
466
+ type: type,
467
+ data: data
468
+ };
469
+ }
470
+
471
+ function readExtDate(data) {
472
+ if (data.length === 4) {
473
+ let sec =
474
+ ((data[0] << 24) >>> 0) +
475
+ ((data[1] << 16) >>> 0) +
476
+ ((data[2] << 8) >>> 0) +
477
+ data[3];
478
+ return new Date(sec * 1000);
479
+ }
480
+ if (data.length === 8) {
481
+ let ns =
482
+ ((data[0] << 22) >>> 0) +
483
+ ((data[1] << 14) >>> 0) +
484
+ ((data[2] << 6) >>> 0) +
485
+ (data[3] >>> 2);
486
+ let sec =
487
+ (data[3] & 0x3) * pow32 +
488
+ ((data[4] << 24) >>> 0) +
489
+ ((data[5] << 16) >>> 0) +
490
+ ((data[6] << 8) >>> 0) +
491
+ data[7];
492
+ return new Date(sec * 1000 + ns / 1000000);
493
+ }
494
+ if (data.length === 12) {
495
+ let ns =
496
+ ((data[0] << 24) >>> 0) +
497
+ ((data[1] << 16) >>> 0) +
498
+ ((data[2] << 8) >>> 0) +
499
+ data[3];
500
+ pos -= 8;
501
+ let sec = readInt(8);
502
+ return new Date(sec * 1000 + ns / 1000000);
503
+ }
504
+ throw new Error("Invalid data length for a date value.");
505
+ }
506
+ }
507
+
508
+ // Encodes a string to UTF-8 bytes.
509
+ function encodeUtf8(str) {
510
+ // Prevent excessive array allocation and slicing for all 7-bit characters
511
+ let ascii = true,
512
+ length = str.length;
513
+ for (let x = 0; x < length; x++) {
514
+ if (str.charCodeAt(x) > 127) {
515
+ ascii = false;
516
+ break;
517
+ }
518
+ }
519
+
520
+ // Based on: https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330
521
+ let i = 0,
522
+ bytes = new Uint8Array(str.length * (ascii ? 1 : 4));
523
+ for (let ci = 0; ci !== length; ci++) {
524
+ let c = str.charCodeAt(ci);
525
+ if (c < 128) {
526
+ bytes[i++] = c;
527
+ continue;
528
+ }
529
+ if (c < 2048) {
530
+ bytes[i++] = (c >> 6) | 192;
531
+ } else {
532
+ if (c > 0xd7ff && c < 0xdc00) {
533
+ if (++ci >= length)
534
+ throw new Error("UTF-8 encode: incomplete surrogate pair");
535
+ let c2 = str.charCodeAt(ci);
536
+ if (c2 < 0xdc00 || c2 > 0xdfff)
537
+ throw new Error(
538
+ "UTF-8 encode: second surrogate character 0x" +
539
+ c2.toString(16) +
540
+ " at index " +
541
+ ci +
542
+ " out of range",
543
+ );
544
+ c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
545
+ bytes[i++] = (c >> 18) | 240;
546
+ bytes[i++] = ((c >> 12) & 63) | 128;
547
+ } else bytes[i++] = (c >> 12) | 224;
548
+ bytes[i++] = ((c >> 6) & 63) | 128;
549
+ }
550
+ bytes[i++] = (c & 63) | 128;
551
+ }
552
+ return ascii ? bytes : bytes.subarray(0, i);
553
+ }
554
+
555
+ // Decodes a string from UTF-8 bytes.
556
+ function decodeUtf8(bytes, start, length) {
557
+ // Based on: https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330
558
+ let i = start,
559
+ str = "";
560
+ length += start;
561
+ while (i < length) {
562
+ let c = bytes[i++];
563
+ if (c > 127) {
564
+ if (c > 191 && c < 224) {
565
+ if (i >= length)
566
+ throw new Error("UTF-8 decode: incomplete 2-byte sequence");
567
+ c = ((c & 31) << 6) | (bytes[i++] & 63);
568
+ } else if (c > 223 && c < 240) {
569
+ if (i + 1 >= length)
570
+ throw new Error("UTF-8 decode: incomplete 3-byte sequence");
571
+ c = ((c & 15) << 12) | ((bytes[i++] & 63) << 6) | (bytes[i++] & 63);
572
+ } else if (c > 239 && c < 248) {
573
+ if (i + 2 >= length)
574
+ throw new Error("UTF-8 decode: incomplete 4-byte sequence");
575
+ c =
576
+ ((c & 7) << 18) |
577
+ ((bytes[i++] & 63) << 12) |
578
+ ((bytes[i++] & 63) << 6) |
579
+ (bytes[i++] & 63);
580
+ } else
581
+ throw new Error(
582
+ "UTF-8 decode: unknown multibyte start 0x" +
583
+ c.toString(16) +
584
+ " at index " +
585
+ (i - 1),
586
+ );
587
+ }
588
+ if (c <= 0xffff) str += String.fromCharCode(c);
589
+ else if (c <= 0x10ffff) {
590
+ c -= 0x10000;
591
+ str += String.fromCharCode((c >> 10) | 0xd800);
592
+ str += String.fromCharCode((c & 0x3ff) | 0xdc00);
593
+ } else
594
+ throw new Error(
595
+ "UTF-8 decode: code point 0x" +
596
+ c.toString(16) +
597
+ " exceeds UTF-16 reach",
598
+ );
599
+ }
600
+ return str;
601
+ }
602
+
603
+ // The exported functions
604
+ return {
605
+ serialize: serialize,
606
+ deserialize: deserialize,
607
+
608
+ // Compatibility with other libraries
609
+ encode: serialize,
610
+ decode: deserialize,
611
+ };
612
+ })();
613
+
614
+ if (typeof window !== "undefined") {
615
+ window.msgpack = msgpack;
616
+ }
617
+ path = require("path");
618
+ tune = require("./tune");
619
+ makeContext = tune.makeContext;
620
+ envmd = tune.envmd;
621
+ TuneError = tune.TuneError;
622
+ text2run = tune.text2run;
623
+
624
+ function env2vars(text) {
625
+ return text
626
+ .split(/^(\w+\s*=)/gm)
627
+ .reduce((function(memo, item, index, arr) {
628
+ (function(it) {
629
+ return (it ? memo.push({
630
+ name: it[1],
631
+ content: arr[index + 1]
632
+ .replace(/\n$/, "")
633
+ }) : undefined);
634
+ })(item.match(/^(\w+)\s*=/));
635
+ return memo;
636
+ }), [])
637
+ .reduce((function(memo, item) {
638
+ memo[item.name] = item
639
+ .content.replace(new RegExp("^\\s*'(.*)'\\s*$"), "$1")
640
+ .replace(new RegExp("^\\s*\"(.*)\"\\s*$"), "$1");
641
+ return memo;
642
+ }), {});
643
+ }
644
+ env2vars;
645
+
646
+ function pparse(filename) {
647
+ var parsed, parsed1;
648
+ var parsed;
649
+ var parsed1;
650
+ parsed = path.parse(filename);
651
+ parsed1 = path.parse(parsed.name);
652
+ if (parsed1.ext) {
653
+ parsed.ext2 = parsed1.ext;
654
+ parsed.name = parsed1.name;
655
+ }
656
+ return parsed;
657
+ }
658
+ pparse;
659
+ async function runFile(filename, ctx) {
660
+ var parsed, node, text, lctx, res, module, spawnSync, result, sres, _i, _ref, _ref0, _ref1, _ref2, _ref3;
661
+ var args = 3 <= arguments.length ? [].slice.call(arguments, 2, _i = arguments.length - 0) : (_i = 2, []);
662
+ try {
663
+ var parsed;
664
+ parsed = pparse(filename);
665
+ if ((parsed.ext === ".chat")) {
666
+ var node;
667
+ node = await ctx.resolve(filename);
668
+ var text;
669
+ text = await node.read();
670
+ var lctx;
671
+ lctx = ctx.clone();
672
+ lctx.ms.unshift(envmd(args[0]));
673
+ var res;
674
+ res = await text2run(text, lctx, {
675
+ stop: "assistant"
676
+ });
677
+ _ref = res["slice"](-1)[0].content.replace(/@/g, "\\@");
678
+ } else if (parsed.ext === ".mjs") {
679
+ var module;
680
+ module = await import(filename + "?t=" + Date.now());
681
+ if ((typeof module.default !== "function")) throw Error("JS file does not export default function");
682
+ _ref = module.default.call.apply(module.default, [].concat([ctx]).concat(args).concat([ctx]));
683
+ } else if (parsed.ext === ".js" || parsed.ext === ".cjs") {
684
+ var module;
685
+ module = require(filename);
686
+ if ((typeof module !== "function")) throw Error("JS file does not export default function");
687
+ _ref = module.call.apply(module, [].concat([ctx]).concat(args).concat([ctx]));
688
+ } else if (parsed.ext === ".py" || parsed.ext === ".php") {
689
+ var spawnSync;
690
+ spawnSync = require("child_process").spawnSync;
691
+ var res;
692
+ switch (parsed.ext) {
693
+ case ".py":
694
+ _ref0 = "python";
695
+ break;
696
+ case ".php":
697
+ _ref0 = "php";
698
+ break;
699
+ default:
700
+ _ref0 = undefined;
701
+ }
702
+ switch (parsed.ext) {
703
+ case ".py":
704
+ _ref1 = "run.py";
705
+ break;
706
+ case ".php":
707
+ _ref1 = "run.php";
708
+ break;
709
+ default:
710
+ _ref1 = undefined;
711
+ }
712
+ res = spawnSync(_ref0, Array(path.resolve(__dirname, _ref1)), {
713
+ input: JSON.stringify({
714
+ filename: filename,
715
+ arguments: args[0],
716
+ ctx: ""
717
+ }),
718
+ env: extend(process.env, ctx.env)
719
+ });
720
+ if (res.error) throw res.error;
721
+ var result;
722
+ result = Array();
723
+ if (res.stderr.length) result.push(res.stderr.toString("utf8"));
724
+ if (res.stdout.length) {
725
+ var sres;
726
+ try {
727
+ _ref2 = msgpack.deserialize(Buffer.from(res.stdout.toString("utf8"), "hex"));
728
+ } catch (e) {
729
+ console.log("cant decode messageback", e);
730
+ _ref2 = res.stdout.toString("utf8");
731
+ }
732
+ sres = _ref2;
733
+ Array.isArray(sres) ? result = result.concat(sres) : result.push(sres);
734
+ }
735
+ if ((result.length === 1)) result = result[0];
736
+ _ref = result;
737
+ } else {
738
+ _ref = undefined;
739
+ throw Error(tpl("{ext} extension is not supported, for {filename} ", {
740
+ ext: parsed.ext,
741
+ filename: filename
742
+ }));
743
+ }
744
+ _ref3 = _ref;
745
+ } catch (e) {
746
+ throw e;
747
+ }
748
+ return _ref3;
749
+ }
750
+ runFile;
751
+
752
+ function fsctx(paths, opts, fs) {
753
+ var imageExt, audioExt, envCache;
754
+ fs = fs || require("fs");
755
+ if (!Array.isArray(paths)) paths = Array(paths);
756
+ var imageExt;
757
+ var audioExt;
758
+ imageExt = "png jpeg jpg webp"
759
+ .split(" ")
760
+ .map((function(item) {
761
+ return ("." + item);
762
+ }));
763
+ audioExt = "mp3 wav"
764
+ .split(" ")
765
+ .map((function(item) {
766
+ return ("." + item);
767
+ }));
768
+
769
+ function mkfsmd1(p) {
770
+ return (async function(name, ctx, args) {
771
+ var fname, parsed, item, parsed1, fileType, fullname, schemaFile, schema, _i, _ref, _len, _ref0, _ref1, _ref2, _ref3;
772
+ if (!name) return;
773
+ var fname;
774
+ var parsed;
775
+ fname = path.resolve(p, ((name === "*") ? "default" : name));
776
+ parsed = pparse(fname);
777
+ if (!fs.existsSync(parsed.dir)) return;
778
+ _ref = fs.readdirSync(parsed.dir)
779
+ .sort((function(a, b) {
780
+ var exts, idx1, idx2;
781
+ var exts;
782
+ var idx1;
783
+ var idx2;
784
+ exts = [".js", ".mjs", ".cjs", ".py", ".php", ".chat"];
785
+ idx1 = exts.indexOf(path.extname(a));
786
+ idx2 = exts.indexOf(path.extname(b));
787
+ return (idx2 - idx1);
788
+ }));
789
+ for (_i = 0, _len = _ref.length; _i < _len; ++_i) {
790
+ item = _ref[_i];
791
+ var parsed1;
792
+ parsed1 = pparse(item);
793
+ if ((parsed1.name !== parsed.name)) continue;
794
+ var fileType;
795
+ if ((parsed1.ext2 === ".tool")) {
796
+ _ref0 = "tool";
797
+ } else if (parsed1.ext2 === ".llm") {
798
+ _ref0 = "llm";
799
+ } else if (parsed1.ext2 === ".proc") {
800
+ _ref0 = "processor";
801
+ } else if (parsed1.ext === ".jpg" || parsed1.ext === ".jpeg" || parsed1.ext === ".png" || parsed1.ext === ".webp") {
802
+ _ref0 = "image";
803
+ } else if (parsed1.ext === ".mp3" || parsed1.ext === ".wav") {
804
+ _ref0 = "audio";
805
+ } else if (parsed1.ext2 === ".ctx") {
806
+ _ref0 = "context";
807
+ } else {
808
+ _ref0 = "text";
809
+ }
810
+ fileType = _ref0;
811
+ var fullname;
812
+ fullname = path.resolve(parsed.dir, item);
813
+ if ((args && (args !== fileType))) continue;
814
+ if (((item === parsed.base) || !parsed.ext || (parsed1.ext2 && (parsed.base === (parsed1.name + parsed1.ext2))) || (name === "*"))) {
815
+ switch (fileType) {
816
+ case "tool":
817
+ var schemaFile;
818
+ schemaFile = path.format({
819
+ root: parsed.root,
820
+ dir: parsed.dir,
821
+ name: parsed1.name,
822
+ ext: ".schema.json"
823
+ });
824
+ var schema;
825
+ schema;
826
+ if (fs.existsSync(schemaFile)) {
827
+ schema = JSON.parse(fs.readFileSync(schemaFile, "utf8"));
828
+ } else if (opts && opts.makeSchema) {
829
+ schema = await opts.makeSchema({
830
+ text: fs.readFileSync(fullname, "utf8")
831
+ }, ctx);
832
+ fs.writeFileSync(schemaFile, schema);
833
+ schema = JSON.parse(schema);
834
+ } else {
835
+ throw new TuneError(("schema file not found " + schemaFile));
836
+ }
837
+ _ref1 = {
838
+ type: "tool",
839
+ schema: schema,
840
+ name: parsed1.name,
841
+ exec: (async function(params, ctx) {
842
+ return runFile(fullname, ctx, params);
843
+ }),
844
+ read: (async function() {
845
+ return fs.readFileSync(fullname, "utf8");
846
+ }),
847
+ dirname: parsed.dir,
848
+ fullname: fullname
849
+ }
850
+ break;
851
+ case "llm":
852
+ _ref1 = {
853
+ type: "llm",
854
+ dirname: parsed.dir,
855
+ fullname: fullname,
856
+ name: parsed1.name,
857
+ exec: (async function(payload, ctx) {
858
+ return runFile(fullname, ctx, payload);
859
+ }),
860
+ read: (async function() {
861
+ return fs.readFileSync(fullname, "utf8");
862
+ })
863
+ }
864
+ break;
865
+ case "context":
866
+ ctx.use((async function(name, ctx, args, next) {
867
+ return runFile(fullname, ctx, name, ctx, args, next);
868
+ }));
869
+ _ref1 = {
870
+ type: "text",
871
+ fullname: fullname,
872
+ name: parsed1.name,
873
+ dirname: parsed.dir,
874
+ read: (async function() {
875
+ return "";
876
+ })
877
+ }
878
+ break;
879
+ case "processor":
880
+ _ref1 = {
881
+ type: "processor",
882
+ name: parsed1.name,
883
+ exec: (function(node, args, ctx) {
884
+ return runFile(fullname, ctx, node, args);
885
+ }),
886
+ read: (async function() {
887
+ return fs.readFileSync(fullname, "utf8");
888
+ }),
889
+ dirname: parsed.dir,
890
+ fullname: fullname
891
+ }
892
+ break;
893
+ case "image":
894
+ if ((parsed1.ext === ".jpg" || parsed1.ext === ".jpeg")) {
895
+ _ref2 = "image/jpeg";
896
+ } else if (parsed1.ext === ".png") {
897
+ _ref2 = "image/png";
898
+ } else if (parsed1.ext === ".webp") {
899
+ _ref2 = "image/webp";
900
+ } else {
901
+ _ref2 = undefined;
902
+ }
903
+ _ref1 = {
904
+ type: "image",
905
+ dirname: parsed.dir,
906
+ fullname: fullname,
907
+ mimetype: _ref2,
908
+ read: (async function() {
909
+ return fs.readFileSync(fullname);
910
+ })
911
+ }
912
+ break;
913
+ case "audio":
914
+ if ((parsed1.ext === ".mp3")) {
915
+ _ref3 = "audio/mpeg";
916
+ } else if (parsed1.ext === ".wav") {
917
+ _ref3 = "audio/wav";
918
+ } else {
919
+ _ref3 = undefined;
920
+ }
921
+ _ref1 = {
922
+ type: "audio",
923
+ dirname: parsed.dir,
924
+ fullname: fullname,
925
+ mimetype: _ref3,
926
+ read: (async function() {
927
+ return fs.readFileSync(fullname);
928
+ })
929
+ }
930
+ break;
931
+ case "text":
932
+ _ref1 = {
933
+ type: "text",
934
+ dirname: parsed.dir,
935
+ fullname: fullname,
936
+ name: parsed1.name,
937
+ read: (async function(binary) {
938
+ var stat, buf, i, c;
939
+ var stat;
940
+ stat = fs.lstatSync(fullname);
941
+ if (stat.isDirectory()) return fs.readdirSync(fullname);
942
+ if (binary) return fs.readFileSync(fullname);
943
+ var buf;
944
+ buf = fs.readFileSync(fullname, "utf8");
945
+ var i;
946
+ i = 0;
947
+ while (i < Math.min(1024, buf.length)) {
948
+ var c;
949
+ c = buf.charCodeAt(i);
950
+ if (((c === 65533) || (c <= 8))) throw Error(tpl("{} is a binary file, can not include it", fullname));
951
+ i++;
952
+ }
953
+ return buf;
954
+ })
955
+ }
956
+ break;
957
+ default:
958
+ _ref1 = undefined;
959
+ }
960
+ return _ref1;
961
+ }
962
+ }
963
+ return undefined;
964
+ });
965
+ }
966
+ mkfsmd1;
967
+ envCache = {};
968
+ return (async function(name, ctx, args, next) {
969
+ var lpaths, handles, p, envFile, res, _i, _ref, _len;
970
+ var lpaths;
971
+ lpaths = ctx.stack
972
+ .filter((function(item) {
973
+ return !!item.dirname;
974
+ }))
975
+ .map((function(item) {
976
+ return item.dirname;
977
+ }))
978
+ .reverse()
979
+ .concat(paths);
980
+ var handles;
981
+ handles = [];
982
+ _ref = lpaths;
983
+ for (_i = 0, _len = _ref.length; _i < _len; ++_i) {
984
+ p = _ref[_i];
985
+ var envFile;
986
+ envFile = path.resolve(p, ".env");
987
+ if (!envCache[envFile]) envCache[envFile] = ((!envFile || !fs.existsSync(envFile)) ? {} : env2vars(fs.readFileSync(envFile, "utf8")));
988
+ if (envCache[envFile][name]) return {
989
+ type: "text",
990
+ read: (async function() {
991
+ return envCache[envFile][name];
992
+ })
993
+ };
994
+ handles.push(mkfsmd1(p));
995
+ }
996
+ while (handles.length) {
997
+ var res;
998
+ res = await handles.shift()(name, ctx, args);
999
+ if (res) return res;
1000
+ }
1001
+ return next();
1002
+ });
1003
+ }
1004
+ fsctx;
1005
+
1006
+ function tpl(str) {
1007
+ var _i;
1008
+ var params = 2 <= arguments.length ? [].slice.call(arguments, 1, _i = arguments.length - 0) : (_i = 1, []);
1009
+ return (function(paramIndex, params) {
1010
+ var _ref;
1011
+ try {
1012
+ _ref = str.replace(/{(\W*)(\w*)(\W*)}/gm, (function(_, pre, name, post) {
1013
+ return (function(res) {
1014
+ paramIndex += 1;
1015
+ return (res ? ((pre || "") + res + (post || "")) : "");
1016
+ })(params[name || paramIndex]);
1017
+ }));
1018
+ } catch (e) {
1019
+ _ref = console.log.apply(console, [].concat([e, str]).concat(params));
1020
+ }
1021
+ return _ref;
1022
+ })(0, (((typeof params[0] === "object") && (params.length === 1)) ? params[0] : params));
1023
+ }
1024
+ tpl;
1025
+
1026
+ function _once(cond, body) {
1027
+ return new Promise((function(resolve, reject) {
1028
+ function handler() {
1029
+ var _ref;
1030
+ try {
1031
+ _ref = cond() ? resolve(body()) : setTimeout(handler, 10);
1032
+ } catch (err) {
1033
+ _ref = reject(err);
1034
+ }
1035
+ return _ref;
1036
+ }
1037
+ setTimeout(handler, 10);
1038
+ return "";
1039
+ }));
1040
+ }
1041
+ _once;
1042
+
1043
+ function pick(obj) {
1044
+ var _i;
1045
+ var props = 2 <= arguments.length ? [].slice.call(arguments, 1, _i = arguments.length - 0) : (_i = 1, []);
1046
+ return (function(it) {
1047
+ var prop, _i0, _ref, _len;
1048
+ _ref = props;
1049
+ for (_i0 = 0, _len = _ref.length; _i0 < _len; ++_i0) {
1050
+ prop = _ref[_i0];
1051
+ it[prop] = obj[prop];
1052
+ }
1053
+ return it;
1054
+ })({});
1055
+ }
1056
+ pick;
1057
+ exports.runFile = runFile;
1058
+ exports.fsctx = fsctx;
1059
+ exports.pparse = pparse;
package/dist/tune.js CHANGED
@@ -1,4 +1,4 @@
1
- var $roles, fs, path, assert, util;
1
+ var $roles, fs, assert, util;
2
2
 
3
3
  function extend() {
4
4
  var _i;
@@ -1059,6 +1059,11 @@ Context.prototype.text2ast = (async function(text) {
1059
1059
  Context.prototype.text2paylod = (async function(text) {
1060
1060
  return text2payload(text, this);
1061
1061
  });
1062
+ Context.prototype.msg2text = msg2text;
1063
+ Context.prototype.envmd = envmd;
1064
+ Context.prototype.text2roles = text2roles;
1065
+ Context.prototype.roles2text = roles2text;
1066
+ Context.prototype.text2call = text2call;
1062
1067
  Context.prototype.read = (async function(name, args) {
1063
1068
  var resolved, _ref;
1064
1069
  var resolved;
@@ -1212,7 +1217,7 @@ function text2roles(text, lineNum) {
1212
1217
  memo.push(res);
1213
1218
  _ref = (memo.row += res.content.split("\n").length);
1214
1219
  } else {
1215
- _ref = undefined;
1220
+ _ref = (((index === 0) && item) ? (memo.row += (item.split("\n").length - 1)) : undefined);
1216
1221
  }
1217
1222
  return _ref;
1218
1223
  })(item.match(/^(s|system|u|user|a|assistant|tc|tool_call|tr|tool_result|c|comment|au|audio|err|error)\s*:/));
@@ -1851,15 +1856,6 @@ TunePromise.prototype.catch = (function(onRejected) {
1851
1856
  TunePromise.prototype.finally = (function(onFinally) {
1852
1857
  return this.promise.finally(onFinally);
1853
1858
  });
1854
- fs = require('fs');
1855
- path = require('path');
1856
-
1857
- function log() {
1858
- var _i;
1859
- var msgs = 1 <= arguments.length ? [].slice.call(arguments, 0, _i = arguments.length - 0) : (_i = 0, []);
1860
- return fs.appendFileSync(path.join(process.cwd(), "tune.log"), msgs.join(" ") + "\n");
1861
- }
1862
- log;
1863
1859
 
1864
1860
  function text2run(text, ctx, opts) {
1865
1861
  var msgs, stopVal, stream, ires, ierr, ifinish, resolve, reject, p;
@@ -1888,7 +1884,10 @@ function text2run(text, ctx, opts) {
1888
1884
  }));
1889
1885
  if (stream) p = new TunePromise((function(res, rej) {
1890
1886
  resolve = res;
1891
- return (reject = rej);
1887
+ return (reject = (function(err) {
1888
+ ierr = err;
1889
+ return rej(err);
1890
+ }));
1892
1891
  }), (async function() {
1893
1892
  var val;
1894
1893
  await _once((function() {
@@ -1923,7 +1922,7 @@ function text2run(text, ctx, opts) {
1923
1922
  }
1924
1923
  stop;
1925
1924
  async function doit() {
1926
- var ast, payload, res, ctype, err, reader, data, reData, reComment;
1925
+ var ast, payload, res, ctype, err, reader, data, done, reData, reComment;
1927
1926
  while (!stop(msgs)) {
1928
1927
  var ast;
1929
1928
  ast = await text2ast(text + "\n" + msg2text(msgs), ctx);
@@ -1956,17 +1955,20 @@ function text2run(text, ctx, opts) {
1956
1955
  }
1957
1956
  var reader;
1958
1957
  var data;
1958
+ var done;
1959
1959
  var reData;
1960
1960
  var reComment;
1961
1961
  reader = res.body
1962
1962
  .pipeThrough(new TextDecoderStream("utf8"))
1963
1963
  .getReader();
1964
1964
  data = "";
1965
+ done = false;
1965
1966
  reData = new RegExp("^data: (.*)");
1966
1967
  reComment = new RegExp("^:.*");
1967
1968
  if (ctype.includes("text/event-stream")) {
1968
- while (res = await reader.read()) {
1969
- if (res.done) break;
1969
+ while (!done) {
1970
+ res = await reader.read();
1971
+ done = (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res.done !== "undefined") && (res.done !== null) && !Number.isNaN(res.done)) ? res.done : (((typeof true !== "undefined") && (true !== null) && !Number.isNaN(true)) ? true : undefined));
1970
1972
  (function(it) {
1971
1973
  it = it.split(/\n/);
1972
1974
  it = it.map((function(item) {
@@ -1979,17 +1981,21 @@ function text2run(text, ctx, opts) {
1979
1981
  var m;
1980
1982
  var m;
1981
1983
  m = item.match(reData);
1982
- return ((m && ('' === it[(index + 1)])) ? m[1] : undefined);
1984
+ if ((!m || ('' !== it[(index + 1)]))) return;
1985
+ if ((m[1] === '[DONE]')) {
1986
+ done = true;
1987
+ return;
1988
+ }
1989
+ return m[1];
1983
1990
  }));
1984
1991
  it = it.filter((function(item) {
1985
1992
  return item;
1986
1993
  }));
1987
1994
  it = it.map((function(item) {
1988
- return ((item === '[DONE]') ? item : JSON.parse(item));
1995
+ return JSON.parse(item);
1989
1996
  }));
1990
1997
  it = it.reduce((function(msg, chunk) {
1991
1998
  var delta, tc, tcIdx;
1992
- if ((chunk === "[DONE]")) return msg;
1993
1999
  var delta;
1994
2000
  delta = (((typeof chunk !== "undefined") && (chunk !== null) && !Number.isNaN(chunk) && (typeof chunk.choices !== "undefined") && (chunk.choices !== null) && !Number.isNaN(chunk.choices) && (typeof chunk.choices[0] !== "undefined") && (chunk.choices[0] !== null) && !Number.isNaN(chunk.choices[0]) && (typeof chunk.choices[0].delta !== "undefined") && (chunk.choices[0].delta !== null) && !Number.isNaN(chunk.choices[0].delta)) ? chunk.choices[0].delta : (((typeof {} !== "undefined") && ({} !== null) && !Number.isNaN({})) ? {} : undefined));
1995
2001
  if ((((typeof chunk !== "undefined") && (chunk !== null) && !Number.isNaN(chunk) && (typeof chunk.error !== "undefined") && (chunk.error !== null) && !Number.isNaN(chunk.error)) ? chunk.error : undefined)) {
@@ -2017,7 +2023,7 @@ function text2run(text, ctx, opts) {
2017
2023
  value: msgs.concat(Array(it))
2018
2024
  });
2019
2025
  return it;
2020
- })(data += res.value);
2026
+ })(data += (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res.value !== "undefined") && (res.value !== null) && !Number.isNaN(res.value)) ? res.value : (((typeof "" !== "undefined") && ("" !== null) && !Number.isNaN("")) ? "" : undefined)));
2021
2027
  }
2022
2028
  }
2023
2029
  if (ires) msgs = ires.value;
@@ -2205,8 +2211,8 @@ function text2cut(text, cursor) {
2205
2211
  return (function(line) {
2206
2212
  return (function(it) {
2207
2213
  it = it.map((function(item) {
2208
- item.start = line;
2209
- line = line + item.content.split("\n").length;
2214
+ item.start = item.row;
2215
+ line = item.row + item.content.split("\n").length;
2210
2216
  item.end = line;
2211
2217
  if (((item.role === "comment") && item.content.match(/^\s*\-{3,}\s*$/))) item.delim = true;
2212
2218
  return item;
@@ -2234,7 +2240,7 @@ function text2cut(text, cursor) {
2234
2240
  end: it["slice"](-1)[0].end
2235
2241
  });
2236
2242
  return it;
2237
- })(text2roles(text));
2243
+ })(text2roles(text, true));
2238
2244
  })(0);
2239
2245
  }
2240
2246
  text2cut;
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "tune-sdk",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "tune - your everyday LLM toolkit.",
5
5
  "main": "dist/tune.js",
6
6
  "module": "dist/tune.mjs",
7
+ "bin": "bin/cli.js",
7
8
  "exports": {
8
9
  ".": {
9
10
  "require": "./dist/tune.js",