tune-sdk 0.1.5 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/cli.js CHANGED
@@ -20,26 +20,6 @@ process.argv.slice(2).forEach(arg => {
20
20
  }
21
21
  });
22
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
23
  const tune = require('../dist/tune.js');
44
24
  const { fsctx } = require('../dist/fsctx.js');
45
25
  const fs = require("fs");
@@ -105,9 +85,19 @@ async function main() {
105
85
  throw(Error(`err: Context file export is not an array of functions or function ${filename}`))
106
86
  }
107
87
  }
88
+ let stopVal = args.stop || "assistant";
89
+ if (stopVal !== "step" && stopVal != "assistant") {
90
+ stopVal = function(msgs) {
91
+ if (!msgs.length) return false
92
+ const lastMsg = msgs[msgs.length - 1]
93
+ if (!lastMsg.content) return false
94
+ return (lastMsg.content.indexOf(args.stop) !== -1)
95
+ }
96
+ }
97
+
98
+ let res = await tune.text2run(chat, ctx, { stop: stopVal })
108
99
 
109
100
  const longFormatRegex = /^(system|user|tool_call|tool_result|assistant|error):/;
110
- let res = await tune.text2run(chat, ctx, { stop: args.stop || "assistant" })
111
101
  res = tune.msg2text(res, longFormatRegex.test(chat))
112
102
  if (args.filename && args.save) {
113
103
  chat += "\n" + res
package/dist/fsctx.js CHANGED
@@ -1,4 +1,4 @@
1
- var path, tune, makeContext, envmd, TuneError, text2run;
1
+ var path, tune, envmd, TuneError, text2run;
2
2
 
3
3
  function extend() {
4
4
  var _i;
@@ -616,7 +616,6 @@ if (typeof window !== "undefined") {
616
616
  }
617
617
  path = require("path");
618
618
  tune = require("./tune");
619
- makeContext = tune.makeContext;
620
619
  envmd = tune.envmd;
621
620
  TuneError = tune.TuneError;
622
621
  text2run = tune.text2run;
@@ -669,9 +668,10 @@ async function runFile(filename, ctx) {
669
668
  text = await node.read();
670
669
  var lctx;
671
670
  lctx = ctx.clone();
671
+ lctx.stack.push(node);
672
672
  lctx.ms.unshift(envmd(args[0]));
673
673
  var res;
674
- res = await text2run(text, lctx, {
674
+ res = await lctx.text2run(text, {
675
675
  stop: "assistant"
676
676
  });
677
677
  _ref = res["slice"](-1)[0].content.replace(/@/g, "\\@");
@@ -767,15 +767,21 @@ function fsctx(paths, opts, fs) {
767
767
  }));
768
768
 
769
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;
770
+ async function fsmd(name, args) {
771
+ var self, result, parsed, dir, re, item, parsed1, fileType, fullname, schemaFile, schema, res, _i, _ref, _len, _ref0, _ref1, _ref2, _ref3;
772
+ var self;
773
+ var result;
774
+ self = this;
775
+ result = ((args.output === "all") ? [] : undefined);
772
776
  if (!name) return;
773
- var fname;
774
777
  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)
778
+ var dir;
779
+ var re;
780
+ parsed = ((args.match === "exact") ? pparse(path.resolve(p, name)) : undefined);
781
+ dir = (((typeof parsed !== "undefined") && (parsed !== null) && !Number.isNaN(parsed) && (typeof parsed.dir !== "undefined") && (parsed.dir !== null) && !Number.isNaN(parsed.dir)) ? parsed.dir : (((typeof p !== "undefined") && (p !== null) && !Number.isNaN(p)) ? p : undefined));
782
+ re = ((args.match === "regex") ? new RegExp(name) : undefined);
783
+ if (!fs.existsSync(dir)) return;
784
+ _ref = fs.readdirSync(dir)
779
785
  .sort((function(a, b) {
780
786
  var exts, idx1, idx2;
781
787
  var exts;
@@ -789,8 +795,9 @@ function fsctx(paths, opts, fs) {
789
795
  for (_i = 0, _len = _ref.length; _i < _len; ++_i) {
790
796
  item = _ref[_i];
791
797
  var parsed1;
792
- parsed1 = pparse(item);
793
- if ((parsed1.name !== parsed.name)) continue;
798
+ parsed1 = pparse(path.join(dir, item));
799
+ if (((args.match === "exact") && (parsed.base !== item) && (parsed.base !== (parsed1.name + parsed1.ext2)) && (parsed.base !== parsed1.name))) continue;
800
+ if ((re && !re.test(item))) continue;
794
801
  var fileType;
795
802
  if ((parsed1.ext2 === ".tool")) {
796
803
  _ref0 = "tool";
@@ -809,166 +816,172 @@ function fsctx(paths, opts, fs) {
809
816
  }
810
817
  fileType = _ref0;
811
818
  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;
819
+ fullname = path.resolve(dir, item);
820
+ if (((args.type !== "any") && (args.type !== fileType))) continue;
821
+ var res;
822
+ switch (fileType) {
823
+ case "tool":
824
+ var schemaFile;
825
+ schemaFile = path.format({
826
+ root: parsed1.root,
827
+ dir: parsed1.dir,
828
+ name: parsed1.name,
829
+ ext: ".schema.json"
830
+ });
831
+ var schema;
832
+ schema;
833
+ if (fs.existsSync(schemaFile)) {
834
+ schema = JSON.parse(fs.readFileSync(schemaFile, "utf8"));
835
+ } else if (opts && opts.makeSchema && (opts.output !== "all")) {
836
+ schema = await opts.makeSchema({
837
+ text: fs.readFileSync(fullname, "utf8")
838
+ }, self);
839
+ fs.writeFileSync(schemaFile, schema);
840
+ schema = JSON.parse(schema);
841
+ } else {
842
+ throw new Error(("schema file not found " + schemaFile));
843
+ }
844
+ _ref1 = {
845
+ type: "tool",
846
+ schema: schema,
847
+ name: parsed1.name,
848
+ exec: (async function(params, ctx) {
849
+ return runFile(fullname, ctx, params);
850
+ }),
851
+ read: (async function() {
852
+ return fs.readFileSync(fullname, "utf8");
853
+ }),
854
+ dirname: parsed1.dir,
855
+ fullname: fullname
856
+ }
857
+ break;
858
+ case "llm":
859
+ _ref1 = {
860
+ type: "llm",
861
+ dirname: parsed1.dir,
862
+ fullname: fullname,
863
+ name: parsed1.name,
864
+ exec: (async function(payload, ctx) {
865
+ return runFile(fullname, ctx, payload);
866
+ }),
867
+ read: (async function() {
868
+ return fs.readFileSync(fullname, "utf8");
869
+ })
870
+ }
871
+ break;
872
+ case "context":
873
+ if ((args.output !== "all")) self.use((async function(name, args) {
874
+ return runFile(fullname, this, name, args);
875
+ }));
876
+ _ref1 = {
877
+ type: "text",
878
+ fullname: fullname,
879
+ name: parsed1.name,
880
+ dirname: parsed1.dir,
881
+ read: (async function() {
882
+ return "";
883
+ })
884
+ }
885
+ break;
886
+ case "processor":
887
+ _ref1 = {
888
+ type: "processor",
889
+ name: parsed1.name,
890
+ exec: (function(node, args, ctx) {
891
+ return runFile(fullname, ctx, node, args);
892
+ }),
893
+ read: (async function() {
894
+ return fs.readFileSync(fullname, "utf8");
895
+ }),
896
+ dirname: parsed1.dir,
897
+ fullname: fullname
898
+ }
899
+ break;
900
+ case "image":
901
+ if ((parsed1.ext === ".jpg" || parsed1.ext === ".jpeg")) {
902
+ _ref2 = "image/jpeg";
903
+ } else if (parsed1.ext === ".png") {
904
+ _ref2 = "image/png";
905
+ } else if (parsed1.ext === ".webp") {
906
+ _ref2 = "image/webp";
907
+ } else {
908
+ _ref2 = undefined;
909
+ }
910
+ _ref1 = {
911
+ type: "image",
912
+ dirname: parsed1.dir,
913
+ fullname: fullname,
914
+ mimetype: _ref2,
915
+ read: (async function() {
916
+ return fs.readFileSync(fullname);
917
+ })
918
+ }
919
+ break;
920
+ case "audio":
921
+ if ((parsed1.ext === ".mp3")) {
922
+ _ref3 = "audio/mpeg";
923
+ } else if (parsed1.ext === ".wav") {
924
+ _ref3 = "audio/wav";
925
+ } else {
926
+ _ref3 = undefined;
927
+ }
928
+ _ref1 = {
929
+ type: "audio",
930
+ dirname: parsed1.dir,
931
+ fullname: fullname,
932
+ mimetype: _ref3,
933
+ read: (async function() {
934
+ return fs.readFileSync(fullname);
935
+ })
936
+ }
937
+ break;
938
+ case "text":
939
+ _ref1 = {
940
+ type: "text",
941
+ dirname: parsed1.dir,
942
+ fullname: fullname,
943
+ name: parsed1.name,
944
+ read: (async function(binary) {
945
+ var stat, buf, i, c;
946
+ var stat;
947
+ stat = fs.lstatSync(fullname);
948
+ if (stat.isDirectory()) return fs.readdirSync(fullname);
949
+ if (binary) return fs.readFileSync(fullname);
950
+ var buf;
951
+ buf = fs.readFileSync(fullname, "utf8");
952
+ var i;
953
+ i = 0;
954
+ while (i < Math.min(1024, buf.length)) {
955
+ var c;
956
+ c = buf.charCodeAt(i);
957
+ if (((c === 65533) || (c <= 8))) throw Error(tpl("{} is a binary file, can not include it", fullname));
958
+ i++;
959
+ }
960
+ return buf;
961
+ })
962
+ }
963
+ break;
964
+ default:
965
+ _ref1 = undefined;
966
+ }
967
+ res = _ref1;
968
+ if ((args.output === "all")) {
969
+ result.push(res);
970
+ } else {
971
+ result = res;
972
+ break;
961
973
  }
962
974
  }
963
- return undefined;
964
- });
975
+ return result;
976
+ }
977
+ return fsmd;
965
978
  }
966
979
  mkfsmd1;
967
980
  envCache = {};
968
- return (async function(name, ctx, args, next) {
969
- var lpaths, handles, p, envFile, res, _i, _ref, _len;
981
+ return (async function(name, args) {
982
+ var lpaths, handles, result, p, envFile, handle, res, _i, _ref, _len;
970
983
  var lpaths;
971
- lpaths = ctx.stack
984
+ lpaths = this.stack
972
985
  .filter((function(item) {
973
986
  return !!item.dirname;
974
987
  }))
@@ -979,6 +992,8 @@ function fsctx(paths, opts, fs) {
979
992
  .concat(paths);
980
993
  var handles;
981
994
  handles = [];
995
+ var result;
996
+ result = ((args.output === "all") ? [] : undefined);
982
997
  _ref = lpaths;
983
998
  for (_i = 0, _len = _ref.length; _i < _len; ++_i) {
984
999
  p = _ref[_i];
@@ -994,11 +1009,19 @@ function fsctx(paths, opts, fs) {
994
1009
  handles.push(mkfsmd1(p));
995
1010
  }
996
1011
  while (handles.length) {
1012
+ var handle;
1013
+ handle = handles.shift();
997
1014
  var res;
998
- res = await handles.shift()(name, ctx, args);
999
- if (res) return res;
1015
+ res = await handle.call(this, name, args);
1016
+ if (!res) continue;
1017
+ if ((args.output === "all")) {
1018
+ Array.isArray(res) ? result = result.concat(res) : result.push();
1019
+ } else {
1020
+ result = res;
1021
+ break;
1022
+ }
1000
1023
  }
1001
- return next();
1024
+ return result;
1002
1025
  });
1003
1026
  }
1004
1027
  fsctx;
@@ -1012,7 +1035,7 @@ function tpl(str) {
1012
1035
  _ref = str.replace(/{(\W*)(\w*)(\W*)}/gm, (function(_, pre, name, post) {
1013
1036
  return (function(res) {
1014
1037
  paramIndex += 1;
1015
- return (res ? ((pre || "") + res + (post || "")) : "");
1038
+ return ((typeof res !== 'undefined') ? ((pre || "") + res + (post || "")) : "");
1016
1039
  })(params[name || paramIndex]);
1017
1040
  }));
1018
1041
  } catch (e) {
package/dist/tune.js CHANGED
@@ -19,6 +19,26 @@ function extend() {
19
19
  }
20
20
  extend;
21
21
 
22
+ function AsyncIter() {
23
+ return (this[Symbol.asyncIterator] = this);
24
+ }
25
+ AsyncIter;
26
+ AsyncIter.prototype.next = (async function() {
27
+ var self, result;
28
+ var self;
29
+ self = this;
30
+ await _once((function() {
31
+ return (!!self.err || !!self.result);
32
+ }), (function() {
33
+ return undefined;
34
+ }));
35
+ var result;
36
+ result = self.result;
37
+ self.result = undefined;
38
+ if (self.err) throw self.err;
39
+ return result;
40
+ });
41
+
22
42
  function TuneError(message, filename, row, col, stack, originalError) {
23
43
  var lastItem;
24
44
  var stack;
@@ -34,7 +54,7 @@ function TuneError(message, filename, row, col, stack, originalError) {
34
54
  this.message = message;
35
55
  this.row = row;
36
56
  this.col = col;
37
- this.stack = stack;
57
+ this._stack = stack;
38
58
  this.error = originalError;
39
59
  return this;
40
60
  }
@@ -42,7 +62,7 @@ TuneError;
42
62
  TuneError.prototype = Object.create(Error.prototype);
43
63
  TuneError.prototype.constructor = TuneError;
44
64
  TuneError.wrap = (function(err, filename, row, col) {
45
- return ((err.name === "TuneError") ? new TuneError(err.message, filename, row, col, err.stack, err.error) : new TuneError("Internal Error", filename, row, col, undefined, err));
65
+ return ((err.name === "TuneError") ? new TuneError(err.message, filename, row, col, err._stack, err.error) : new TuneError("Internal Error", filename, row, col, undefined, err));
46
66
  });
47
67
  TuneError.ctx2stack = (function(ctx) {
48
68
  return ctx.stack.map((function(item) {
@@ -54,11 +74,16 @@ TuneError.ctx2stack = (function(ctx) {
54
74
  }));
55
75
  });
56
76
  TuneError.prototype.toString = (function() {
57
- return (this.message + "\n" + (this.stack || [])
58
- .map((function() {
59
- return (" at " + arguments[0].filename + (((typeof arguments !== 'undefined') && (typeof arguments[0] !== 'undefined') && (typeof arguments[0].row !== 'undefined')) ? (":" + arguments[0].row) : "") + (((typeof arguments !== 'undefined') && (typeof arguments[0] !== 'undefined') && (typeof arguments[0].col !== 'undefined')) ? (":" + arguments[0].col) : ""));
60
- }))
61
- .join("\n") + (this.error ? (this.error.stack ? ("\n" + this.error.stack) : this.error.message) : ""));
77
+ return this.stack;
78
+ });
79
+ Object.defineProperty(TuneError.prototype, "stack", {
80
+ get: (function() {
81
+ return ("TuneError: " + this.message + "\n" + (this._stack || [])
82
+ .map((function() {
83
+ return (" at " + arguments[0].filename + (((typeof arguments !== 'undefined') && (typeof arguments[0] !== 'undefined') && (typeof arguments[0].row !== 'undefined')) ? (":" + arguments[0].row) : "") + (((typeof arguments !== 'undefined') && (typeof arguments[0] !== 'undefined') && (typeof arguments[0].col !== 'undefined')) ? (":" + arguments[0].col) : ""));
84
+ }))
85
+ .join("\n") + (this.error ? (this.error.stack ? ("\n" + this.error.stack) : this.error.message) : ""));
86
+ })
62
87
  });
63
88
  var dJSON = (() => {
64
89
  var de = Object.create;
@@ -1017,6 +1042,7 @@ function Context() {
1017
1042
  return (item.name === "write");
1018
1043
  }));
1019
1044
  this.stack = [];
1045
+ this.type = "Context";
1020
1046
  return this;
1021
1047
  }
1022
1048
  Context;
@@ -1033,24 +1059,55 @@ Context.prototype.clone = (function() {
1033
1059
  Context.prototype.use = (function(middleware) {
1034
1060
  return ((middleware.name === "write") ? this.ws.push(middleware) : this.ms.push(middleware));
1035
1061
  });
1036
- Context.prototype.resolve = (async function(name, args, ms) {
1062
+ Context.prototype.resolve = (async function(name, args) {
1063
+ var i, output, match, type, result, res, md;
1064
+ if (!this.ms.length) return;
1065
+ var i;
1066
+ var output;
1067
+ var match;
1068
+ var type;
1069
+ var result;
1037
1070
  var res;
1038
- ms = ms || this.ms;
1039
- if (!ms.length) return;
1040
- var res;
1041
- res = ms[0](name, this, args, this.resolve.bind(this, name, args, ms.slice(1)));
1042
- res = await res;
1043
- if (!res) return res;
1044
- if ((typeof res !== "object")) throw Error(tpl("resolved '@{name}' node must be 'object' but got '{res}'", {
1045
- name: name,
1046
- res: typeof res
1047
- }));
1048
- if (!res.type) throw Error(tpl("resolved '@{name}' node must have a 'type' property", {
1049
- name: name
1050
- }));
1051
- return res;
1071
+ i = 0;
1072
+ output = (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.output !== "undefined") && (args.output !== null) && !Number.isNaN(args.output)) ? args.output : (((typeof "first" !== "undefined") && ("first" !== null) && !Number.isNaN("first")) ? "first" : undefined));
1073
+ match = (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.match !== "undefined") && (args.match !== null) && !Number.isNaN(args.match)) ? args.match : (((typeof "exact" !== "undefined") && ("exact" !== null) && !Number.isNaN("exact")) ? "exact" : undefined));
1074
+ type = (((typeof args !== "undefined") && (args !== null) && !Number.isNaN(args) && (typeof args.type !== "undefined") && (args.type !== null) && !Number.isNaN(args.type)) ? args.type : (((typeof "any" !== "undefined") && ("any" !== null) && !Number.isNaN("any")) ? "any" : undefined));
1075
+ result = ((output === "all") ? [] : undefined);
1076
+ res = undefined;
1077
+ while (i < this.ms.length) {
1078
+ var md;
1079
+ md = this.ms[i];
1080
+ res = await md.call(this, name, {
1081
+ output: output,
1082
+ match: match,
1083
+ type: type
1084
+ });
1085
+ if (!res) {
1086
+ i++;
1087
+ continue;
1088
+ }
1089
+ if (((output === "all") && Array.isArray(res))) {
1090
+ result = result.concat(res);
1091
+ i++;
1092
+ continue;
1093
+ }
1094
+ if ((typeof res !== "object")) throw Error(tpl("resolved '@{name}' node must be 'object' but got '{res}'", {
1095
+ name: name,
1096
+ res: typeof res
1097
+ }));
1098
+ if (!res.type) throw Error(tpl("resolved '@{name}' node must have a 'type' property", {
1099
+ name: name
1100
+ }));
1101
+ if ((output === "first")) {
1102
+ result = res;
1103
+ break;
1104
+ }
1105
+ result.push(res);
1106
+ i++;
1107
+ }
1108
+ return result;
1052
1109
  });
1053
- Context.prototype.text2run = (async function(text, opts) {
1110
+ Context.prototype.text2run = (function(text, opts) {
1054
1111
  return text2run(text, this, opts);
1055
1112
  });
1056
1113
  Context.prototype.text2ast = (async function(text) {
@@ -1080,7 +1137,7 @@ Context.prototype.exec = (async function(name, args) {
1080
1137
  var resolved;
1081
1138
  resolved = await this.resolve(name);
1082
1139
  if ((resolved && resolved.exec)) {
1083
- return _ref = await resolved.exec(args);
1140
+ return _ref = await resolved.exec.call(this, args, this);
1084
1141
  } else {
1085
1142
  _ref = undefined;
1086
1143
  }
@@ -1103,49 +1160,49 @@ function envmd(md) {
1103
1160
  if ((typeof md[name] === "string" || typeof md[name] === "number" || typeof md[name] === "boolean")) {
1104
1161
  _ref = (lmd[name] = {
1105
1162
  type: "text",
1163
+ name: name,
1106
1164
  read: (function() {
1107
1165
  return md[name];
1108
1166
  })
1109
1167
  });
1110
1168
  } else if (typeof md[name] === "object") {
1111
- _ref = (lmd[name] = md[name]);
1169
+ lmd[name] = md[name];
1170
+ _ref = (lmd[name].name = name);
1112
1171
  } else {
1113
1172
  _ref = undefined;
1114
1173
  throw new TuneError(("unsupported type of value '" + name + "': " + util.inspect(md)));
1115
1174
  }
1116
1175
  return _ref;
1117
1176
  }));
1118
- return (async function(name, ctx, args, next) {
1119
- var llmd, key, val, firstKey, _ref, _len, _ref0;
1177
+ async function hash(name, args) {
1178
+ var llmd, result, re, key, val, _ref, _len;
1120
1179
  var llmd;
1180
+ var result;
1181
+ var re;
1121
1182
  llmd = {};
1183
+ result = ((args.output === "all") ? [] : undefined);
1184
+ re = ((args.match === "regex") ? new RegExp(name) : undefined);
1122
1185
  _ref = lmd;
1123
1186
  for (key in _ref) {
1124
1187
  val = _ref[key];
1125
- if ((args && (args === val.type))) {
1126
- llmd[key] = val;
1127
- } else if (!args) {
1128
- llmd[key] = val;
1188
+ if (((args.type !== val.type) && (args.type !== "any"))) continue;
1189
+ if (((args.match === "exact") && (name !== key))) continue;
1190
+ if ((re && !re.test(key))) continue;
1191
+ if ((args.output === "first")) {
1192
+ result = Object.assign({}, val);
1193
+ break;
1129
1194
  }
1195
+ result.push(Object.assign({}, val));
1130
1196
  }
1131
- var firstKey;
1132
- firstKey = Object.keys(llmd)[0];
1133
- if ((firstKey && (name === "*"))) {
1134
- _ref0 = llmd[firstKey];
1135
- } else if (llmd.hasOwnProperty(name)) {
1136
- _ref0 = llmd[name];
1137
- } else {
1138
- _ref0 = next();
1139
- }
1140
- return _ref0;
1141
- });
1197
+ return result;
1198
+ }
1199
+ return hash;
1142
1200
  }
1143
1201
  envmd;
1144
1202
 
1145
1203
  function makeContext() {
1146
1204
  var ctx, _i;
1147
1205
  var args = 1 <= arguments.length ? [].slice.call(arguments, 0, _i = arguments.length - 0) : (_i = 0, []);
1148
- if ((args[0] instanceof Context)) return args[0];
1149
1206
  var ctx;
1150
1207
  ctx = new Context();
1151
1208
  if (!args[0]) return ctx;
@@ -1353,25 +1410,26 @@ async function text2payload(text, ctx) {
1353
1410
  return await ast2payload(ast);
1354
1411
  }
1355
1412
  text2payload;
1356
- async function text2ast(text, ctx) {
1413
+ async function text2ast(text, ctx, resolve) {
1357
1414
  var lastChar, lastRole;
1358
1415
  var lastChar;
1359
1416
  lastChar = '';
1360
1417
  var lastRole;
1361
1418
  lastRole = '';
1362
1419
  async function parse(text, recursive, ctx) {
1363
- var nodeStack, re, nodes, index, m, match, role, roleName, name, prefix, args, proc, row, col, filename, resolved, pargs, pname, p, err, schema, lctx, _ref, _i, _i0, _ref0, _len;
1364
- ctx = makeContext(ctx);
1420
+ var nodeStack, nodes, index, reAst, m, row, col, match, role, roleName, name, prefix, args, proc, filename, resolved, pargs, pname, p, err, schema, lctx, _ref, _i, _i0, _ref0, _len;
1365
1421
  nodeStack = nodeStack || [];
1366
- var re;
1367
- re = /(?<prefix1>@{1,2})\{(?<name1>(?:\\\}|[^}])+)\}|(?<prefix>@{1,2})(?<name>[\S]+)|(?<role>^(?:s|system|u|user|a|assistant|tc|tool_call|tr|tool_result|c|comment|au|audio|err|error))\s*(?<roleName>\([^\)]+\))?\s*:/gm;
1368
1422
  var nodes;
1369
1423
  nodes = [];
1370
1424
  var index;
1371
1425
  index = 0;
1372
- while (m = re.exec(text)) {
1426
+ reAst = /(?<prefix1>@{1,2})\{(?<name1>(?:\\\}|[^}])+)\}|(?<prefix>@{1,2})(?<name>[\S]+)|(?<role>^(?:s|system|u|user|a|assistant|tc|tool_call|tr|tool_result|c|comment|au|audio|err|error))\s*(?<roleName>\([^\)]+\))?\s*:/gm;
1427
+ while (m = reAst.exec(text)) {
1373
1428
  if (((lastRole === "a" || lastRole === "tc" || lastRole === "err" || lastRole === "assistant" || lastRole === "tool_call" || lastRole === "error") && !m.groups.role)) continue;
1374
1429
  if (((m.index > 0) && (text.charAt(m.index - 1) === String.fromCharCode(92)))) continue;
1430
+ _ref = getPos(m.index, text);
1431
+ row = _ref[0];
1432
+ col = _ref[1];
1375
1433
  if ((m.index - index)) {
1376
1434
  nodes.push({
1377
1435
  type: "text",
@@ -1379,6 +1437,7 @@ async function text2ast(text, ctx) {
1379
1437
  end: m.index,
1380
1438
  value: text.slice(index, m.index)
1381
1439
  });
1440
+ index = m.index;
1382
1441
  lastChar = text.charAt(m.index - 1);
1383
1442
  }
1384
1443
  var match;
@@ -1391,7 +1450,7 @@ async function text2ast(text, ctx) {
1391
1450
  nodes.push({
1392
1451
  type: ((lastChar === '' || lastChar === "\n") ? "role" : "text"),
1393
1452
  start: index,
1394
- end: m.index,
1453
+ end: m.index + match.length,
1395
1454
  role: role,
1396
1455
  roleName: (roleName ? roleName.slice(1, -1) : undefined),
1397
1456
  value: match
@@ -1409,7 +1468,16 @@ async function text2ast(text, ctx) {
1409
1468
  prefix = m.groups.prefix || m.groups.prefix1;
1410
1469
  args = undefined;
1411
1470
  proc = undefined;
1412
- (function(it) {
1471
+ if (!ctx) {
1472
+ nodes.push({
1473
+ type: "var",
1474
+ start: m.index,
1475
+ end: m.index + match.length,
1476
+ value: match
1477
+ });
1478
+ index = m.index + match.length;
1479
+ continue;
1480
+ }(function(it) {
1413
1481
  it = it.replace(/\\\}/g, "}");
1414
1482
  it = it.split("|");
1415
1483
  it = it.map((function(it) {
@@ -1427,9 +1495,6 @@ async function text2ast(text, ctx) {
1427
1495
  it = (proc = ((it.length > 1) ? it.slice(1) : undefined));
1428
1496
  return it;
1429
1497
  })(name);
1430
- _ref = getPos(m.index, text);
1431
- row = _ref[0];
1432
- col = _ref[1];
1433
1498
  var filename;
1434
1499
  filename = (function(it) {
1435
1500
  it = it["slice"](-1)[0];
@@ -1443,15 +1508,17 @@ async function text2ast(text, ctx) {
1443
1508
  var pname;
1444
1509
  pname = pargs.shift();
1445
1510
  var p;
1446
- p = await ctx.resolve(pname, "processor");
1511
+ p = await ctx.resolve(pname, {
1512
+ type: "processor"
1513
+ });
1447
1514
  if (!p) throw new TuneError(("'" + pname + "' processor not found"), filename, row, col);
1448
1515
  if ((typeof p.exec !== "function")) throw new TuneError(("'" + pname + "' does not have exec function"), filename, row, col);
1449
1516
  try {
1450
- resolved = await p.exec(resolved, pargs[0], ctx);
1517
+ resolved = await p.exec.call(ctx, resolved, pargs[0], ctx);
1451
1518
  } catch (e) {
1452
1519
  var err;
1453
1520
  err = new TuneError(e.message, (p.fullname || p.name), undefined, undefined, [], e);
1454
- err.stack.push({
1521
+ err._stack.push({
1455
1522
  filename: filename,
1456
1523
  row: row,
1457
1524
  col: col
@@ -1491,7 +1558,7 @@ async function text2ast(text, ctx) {
1491
1558
  lctx = ctx.clone();
1492
1559
  lctx.stack.push(resolved);
1493
1560
  try {
1494
- resolved.nodes = await parse(await resolved.read(), true, lctx);
1561
+ resolved.nodes = await parse(resolved.value, true, lctx);
1495
1562
  } catch (e) {
1496
1563
  throw TuneError.wrap(e, filename, row, col);
1497
1564
  }
@@ -1756,11 +1823,12 @@ function ast2payload(ast) {
1756
1823
  ast2payload;
1757
1824
  async function payload2http(payload, ctx) {
1758
1825
  var llm, stack, lastStack, body, _ref;
1759
- ctx = makeContext(ctx);
1760
1826
  var llm;
1761
1827
  llm = payload.llm;
1762
1828
  delete payload.llm;
1763
- if (!llm) llm = await ctx.resolve("*", "llm");
1829
+ if (!llm) llm = await ctx.resolve("default", {
1830
+ type: "llm"
1831
+ });
1764
1832
  if (!llm) {
1765
1833
  var stack;
1766
1834
  stack = TuneError.ctx2stack(ctx);
@@ -1777,7 +1845,7 @@ async function payload2http(payload, ctx) {
1777
1845
  }
1778
1846
  }));
1779
1847
  try {
1780
- _ref = await llm.exec(body, ctx);
1848
+ _ref = await llm.exec.call(ctx, body, ctx);
1781
1849
  } catch (e) {
1782
1850
  throw new TuneError(e.message, (llm.filename || llm.fullname || llm.name), llm.row, llm.col, llm.stack, e);
1783
1851
  }
@@ -1789,7 +1857,6 @@ async function toolCall(payload, ctx) {
1789
1857
  var lastMsg;
1790
1858
  lastMsg = payload.messages["slice"](-1)[0];
1791
1859
  if (((((typeof lastMsg !== "undefined") && (lastMsg !== null) && !Number.isNaN(lastMsg) && (typeof lastMsg.tool_calls !== "undefined") && (lastMsg.tool_calls !== null) && !Number.isNaN(lastMsg.tool_calls) && (typeof lastMsg.tool_calls.length !== "undefined") && (lastMsg.tool_calls.length !== null) && !Number.isNaN(lastMsg.tool_calls.length)) ? lastMsg.tool_calls.length : (((typeof 0 !== "undefined") && (0 !== null) && !Number.isNaN(0)) ? 0 : undefined)) === 0)) return [];
1792
- ctx = makeContext(ctx);
1793
1860
  var tools;
1794
1861
  tools = (payload.tools || [])
1795
1862
  .reduce((function(memo, tool) {
@@ -1806,7 +1873,7 @@ async function toolCall(payload, ctx) {
1806
1873
  tool = tools[tc.name];
1807
1874
  if (!tool) throw new TuneError(("tool '" + tc.name + "' not defined"), "", undefined, undefined, TuneError.ctx2stack(ctx));
1808
1875
  try {
1809
- res = await tools[tc.name].exec(JSON.parse(tc.arguments), ctx);
1876
+ res = await tools[tc.name].exec.call(ctx, JSON.parse(tc.arguments), ctx);
1810
1877
  } catch (e) {
1811
1878
  throw new TuneError(e.message, (tool.filename || tool.fullname || tool.name), tool.row, tool.col, tool.stack, e);
1812
1879
  }
@@ -1858,55 +1925,29 @@ TunePromise.prototype.finally = (function(onFinally) {
1858
1925
  });
1859
1926
 
1860
1927
  function text2run(text, ctx, opts) {
1861
- var msgs, stopVal, stream, ires, ierr, ifinish, resolve, reject, p;
1928
+ var msgs, stopVal, stream, resolve, reject, p, iter;
1862
1929
  if (!ctx) throw Error("context not set");
1863
- ctx = makeContext(ctx);
1864
1930
  var msgs;
1865
1931
  var stopVal;
1866
1932
  var stream;
1867
- var ires;
1868
- var ierr;
1869
- var ifinish;
1870
1933
  var resolve;
1871
1934
  var reject;
1872
1935
  msgs = [];
1873
1936
  stopVal = (((typeof opts !== "undefined") && (opts !== null) && !Number.isNaN(opts) && (typeof opts.stop !== "undefined") && (opts.stop !== null) && !Number.isNaN(opts.stop)) ? opts.stop : (((typeof "step" !== "undefined") && ("step" !== null) && !Number.isNaN("step")) ? "step" : undefined));
1874
1937
  stream = (((typeof opts !== "undefined") && (opts !== null) && !Number.isNaN(opts) && (typeof opts.stream !== "undefined") && (opts.stream !== null) && !Number.isNaN(opts.stream)) ? opts.stream : (((typeof false !== "undefined") && (false !== null) && !Number.isNaN(false)) ? false : undefined));
1875
- ires = undefined;
1876
- ierr = undefined;
1877
- ifinish = false;
1878
1938
  resolve = undefined;
1879
1939
  reject = undefined;
1880
1940
  var p;
1941
+ var iter;
1881
1942
  p = new Promise((function(res, rej) {
1882
1943
  resolve = res;
1883
1944
  return (reject = rej);
1884
1945
  }));
1885
- if (stream) p = new TunePromise((function(res, rej) {
1886
- resolve = res;
1887
- return (reject = (function(err) {
1888
- ierr = err;
1889
- return rej(err);
1890
- }));
1891
- }), (async function() {
1892
- var val;
1893
- await _once((function() {
1894
- return (!!ires || !!ierr || !!ifinish);
1895
- }), (function() {
1896
- return undefined;
1897
- }));
1898
- if (ierr) throw ierr;
1899
- if (ires) {
1900
- var val;
1901
- val = ires;
1902
- ires = undefined;
1903
- return val;
1904
- }
1905
- return ifinish;
1906
- }));
1946
+ iter = new AsyncIter();
1907
1947
 
1908
1948
  function stop() {
1909
1949
  var lastMsg, _ref;
1950
+ if ((!msgs || !msgs.length)) return;
1910
1951
  var lastMsg;
1911
1952
  lastMsg = msgs["slice"](-1)[0];
1912
1953
  if ((stopVal === "step")) {
@@ -1933,7 +1974,7 @@ function text2run(text, ctx, opts) {
1933
1974
  res = await toolCall(payload, ctx);
1934
1975
  if (res.length) {
1935
1976
  msgs = msgs.concat(res);
1936
- ires = {
1977
+ iter.result = {
1937
1978
  value: msgs
1938
1979
  };
1939
1980
  continue;
@@ -1947,10 +1988,14 @@ function text2run(text, ctx, opts) {
1947
1988
  if (((((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res[0] !== "undefined") && (res[0] !== null) && !Number.isNaN(res[0]) && (typeof res[0].error !== "undefined") && (res[0].error !== null) && !Number.isNaN(res[0].error)) ? res[0].error : (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res.error !== "undefined") && (res.error !== null) && !Number.isNaN(res.error)) ? res.error : undefined)) || (res.object === "error"))) {
1948
1989
  var err;
1949
1990
  err = new TuneError(tpl("{type: }{message}", (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res[0] !== "undefined") && (res[0] !== null) && !Number.isNaN(res[0]) && (typeof res[0].error !== "undefined") && (res[0].error !== null) && !Number.isNaN(res[0].error)) ? res[0].error : (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res.error !== "undefined") && (res.error !== null) && !Number.isNaN(res.error)) ? res.error : (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res)) ? res : undefined)))));
1950
- err.stack = TuneError.ctx2stack(ctx);
1991
+ err._stack = TuneError.ctx2stack(ctx);
1951
1992
  throw err;
1952
1993
  }
1953
1994
  msgs.push((((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res.message !== "undefined") && (res.message !== null) && !Number.isNaN(res.message)) ? res.message : (((typeof res !== "undefined") && (res !== null) && !Number.isNaN(res) && (typeof res.choices !== "undefined") && (res.choices !== null) && !Number.isNaN(res.choices) && (typeof res.choices[0] !== "undefined") && (res.choices[0] !== null) && !Number.isNaN(res.choices[0]) && (typeof res.choices[0].message !== "undefined") && (res.choices[0].message !== null) && !Number.isNaN(res.choices[0].message)) ? res.choices[0].message : undefined)));
1995
+ iter.result = {
1996
+ value: msgs,
1997
+ done: true
1998
+ };
1954
1999
  continue;
1955
2000
  }
1956
2001
  var reader;
@@ -2001,7 +2046,7 @@ function text2run(text, ctx, opts) {
2001
2046
  if ((((typeof chunk !== "undefined") && (chunk !== null) && !Number.isNaN(chunk) && (typeof chunk.error !== "undefined") && (chunk.error !== null) && !Number.isNaN(chunk.error)) ? chunk.error : undefined)) {
2002
2047
  var err;
2003
2048
  err = new TuneError(JSON.stringify((((typeof chunk !== "undefined") && (chunk !== null) && !Number.isNaN(chunk) && (typeof chunk.error !== "undefined") && (chunk.error !== null) && !Number.isNaN(chunk.error)) ? chunk.error : undefined), null, " "));
2004
- err.stack = TuneError.ctx2stack(ctx);
2049
+ err._stack = TuneError.ctx2stack(ctx);
2005
2050
  throw err;
2006
2051
  }
2007
2052
  if (delta.content) {
@@ -2019,35 +2064,34 @@ function text2run(text, ctx, opts) {
2019
2064
  role: "assistant",
2020
2065
  content: ""
2021
2066
  });
2022
- it = (ires = {
2067
+ it = (iter.result = {
2023
2068
  value: msgs.concat(Array(it))
2024
2069
  });
2025
2070
  return it;
2026
2071
  })(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)));
2027
2072
  }
2073
+ msgs = iter.result.value;
2028
2074
  }
2029
- if (ires) msgs = ires.value;
2030
2075
  }
2031
- ires = {
2076
+ return (stream ? (iter.result = {
2032
2077
  value: msgs,
2033
- done: false
2034
- };
2035
- ifinish = {
2036
2078
  done: true
2037
- };
2038
- return resolve(msgs);
2079
+ }) : resolve(msgs));
2039
2080
  }
2040
2081
  doit;
2041
2082
  doit()
2042
2083
  .catch((function(e) {
2043
2084
  var err;
2044
- if ((e.name === "TuneError")) return reject(e);
2045
2085
  var err;
2046
- err = new TuneError(e.message);
2047
- err.stack = TuneError.ctx2stack(ctx);
2048
- err.error = e;
2049
- return reject(err);
2086
+ err = e;
2087
+ if ((e.name !== "TuneError")) {
2088
+ err = new TuneError(e.message);
2089
+ err._stack = TuneError.ctx2stack(ctx);
2090
+ err.error = e;
2091
+ }
2092
+ return (stream ? (iter.err = err) : reject(err));
2050
2093
  }));
2094
+ if (stream) resolve(iter);
2051
2095
  return p;
2052
2096
  }
2053
2097
  text2run;
@@ -2106,7 +2150,7 @@ function msg2text(msg, long) {
2106
2150
  break;
2107
2151
  case "assistant":
2108
2152
  _ref = (function(res) {
2109
- if ((msg.content && ((typeof msg.content === "string") || (msg.content instanceof String)))) {
2153
+ if ((((typeof msg !== 'undefined') && (typeof msg.content !== 'undefined')) && ((typeof msg.content === "string") || (msg.content instanceof String)))) {
2110
2154
  res.push(mkline("assistant", msg.content));
2111
2155
  } else if (Array.isArray(msg.content)) {
2112
2156
  res.push(msg.content
@@ -2139,10 +2183,15 @@ function msg2text(msg, long) {
2139
2183
  })));
2140
2184
  if (msg.tool_calls) res.push(msg.tool_calls
2141
2185
  .map((function(tc) {
2142
- var args, text;
2186
+ var args, text, _ref1, _err;
2143
2187
  var args;
2144
2188
  var text;
2145
- args = dJSON.parse(tc.function.arguments || "{}");
2189
+ try {
2190
+ _ref1 = dJSON.parse(tc.function.arguments || "{}");
2191
+ } catch (_err) {
2192
+ _ref1 = {}
2193
+ }
2194
+ args = _ref1;
2146
2195
  text = args.text;
2147
2196
  delete args.text;
2148
2197
  args = (Object.keys(args).length ? JSON.stringify(args) : undefined);
@@ -2254,7 +2303,7 @@ function tpl(str) {
2254
2303
  _ref = str.replace(/{(\W*)(\w*)(\W*)}/gm, (function(_, pre, name, post) {
2255
2304
  return (function(res) {
2256
2305
  paramIndex += 1;
2257
- return (res ? ((pre || "") + res + (post || "")) : "");
2306
+ return ((typeof res !== 'undefined') ? ((pre || "") + res + (post || "")) : "");
2258
2307
  })(params[name || paramIndex]);
2259
2308
  }));
2260
2309
  } catch (e) {
@@ -2300,6 +2349,7 @@ fs = require("fs");
2300
2349
  assert = require("node:assert/strict");
2301
2350
  util = require("util");
2302
2351
  exports.makeContext = makeContext;
2352
+ exports.Context = Context;
2303
2353
  exports.text2roles = text2roles;
2304
2354
  exports.roles2text = roles2text;
2305
2355
  exports.text2call = text2call;
package/dist/tune.mjs CHANGED
@@ -20,8 +20,10 @@ const {
20
20
  envmd,
21
21
  unescape,
22
22
  escape,
23
+ Context,
23
24
  } = require("./tune.js");
24
25
  export {
26
+ Context,
25
27
  makeContext,
26
28
  text2roles,
27
29
  roles2text,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tune-sdk",
3
- "version": "0.1.5",
3
+ "version": "0.1.8",
4
4
  "description": "tune - your everyday LLM toolkit.",
5
5
  "main": "dist/tune.js",
6
6
  "module": "dist/tune.mjs",
@@ -23,6 +23,9 @@
23
23
  },
24
24
  "license": "MIT",
25
25
  "files": [
26
- "dist"
26
+ "dist/tune.js",
27
+ "dist/tune.mjs",
28
+ "dist/fsctx.js",
29
+ "bin/cli.js"
27
30
  ]
28
31
  }