@agent-smith/cli 0.0.115 → 0.0.118

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 (114) hide show
  1. package/README.md +274 -34
  2. package/dist/cli.js +4 -8
  3. package/dist/cmd/{clicmds/aliases.d.ts → aliases.d.ts} +1 -1
  4. package/dist/cmd/{clicmds/aliases.js → aliases.js} +1 -26
  5. package/dist/cmd/{clicmds/base.js → base.js} +21 -17
  6. package/dist/cmd/build.d.ts +9 -0
  7. package/dist/cmd/build.js +59 -0
  8. package/dist/cmd/callbacks.d.ts +11 -0
  9. package/dist/cmd/callbacks.js +90 -0
  10. package/dist/cmd/cmds.d.ts +8 -9
  11. package/dist/cmd/cmds.js +134 -103
  12. package/dist/cmd/features.d.ts +6 -0
  13. package/dist/cmd/features.js +57 -0
  14. package/dist/cmd/{sys/read_cmds.d.ts → read_cmds.d.ts} +1 -1
  15. package/dist/cmd/{sys/read_cmds.js → read_cmds.js} +1 -1
  16. package/dist/cmd/user_cmds.d.ts +3 -0
  17. package/dist/cmd/user_cmds.js +23 -0
  18. package/dist/index.js +11 -11
  19. package/dist/main.d.ts +3 -38
  20. package/dist/main.js +3 -37
  21. package/dist/state.d.ts +6 -0
  22. package/dist/state.js +8 -0
  23. package/dist/utils.d.ts +8 -0
  24. package/dist/utils.js +50 -0
  25. package/package.json +10 -20
  26. package/dist/cmd/clicmds/cmds.d.ts +0 -7
  27. package/dist/cmd/clicmds/cmds.js +0 -135
  28. package/dist/cmd/clicmds/updateconf.d.ts +0 -3
  29. package/dist/cmd/clicmds/updateconf.js +0 -74
  30. package/dist/cmd/lib/actions/cmd.d.ts +0 -6
  31. package/dist/cmd/lib/actions/cmd.js +0 -154
  32. package/dist/cmd/lib/actions/read.d.ts +0 -3
  33. package/dist/cmd/lib/actions/read.js +0 -17
  34. package/dist/cmd/lib/adaptaters/cmd.d.ts +0 -2
  35. package/dist/cmd/lib/adaptaters/cmd.js +0 -39
  36. package/dist/cmd/lib/agents/cmd.d.ts +0 -3
  37. package/dist/cmd/lib/agents/cmd.js +0 -11
  38. package/dist/cmd/lib/mcp.d.ts +0 -16
  39. package/dist/cmd/lib/mcp.js +0 -105
  40. package/dist/cmd/lib/options_parsers.d.ts +0 -7
  41. package/dist/cmd/lib/options_parsers.js +0 -52
  42. package/dist/cmd/lib/tasks/cmd.d.ts +0 -4
  43. package/dist/cmd/lib/tasks/cmd.js +0 -419
  44. package/dist/cmd/lib/tasks/conf.d.ts +0 -6
  45. package/dist/cmd/lib/tasks/conf.js +0 -131
  46. package/dist/cmd/lib/tasks/read.d.ts +0 -14
  47. package/dist/cmd/lib/tasks/read.js +0 -186
  48. package/dist/cmd/lib/tasks/utils.d.ts +0 -8
  49. package/dist/cmd/lib/tasks/utils.js +0 -48
  50. package/dist/cmd/lib/tools.d.ts +0 -15
  51. package/dist/cmd/lib/tools.js +0 -147
  52. package/dist/cmd/lib/utils.d.ts +0 -3
  53. package/dist/cmd/lib/utils.js +0 -54
  54. package/dist/cmd/lib/workflows/cmd.d.ts +0 -3
  55. package/dist/cmd/lib/workflows/cmd.js +0 -230
  56. package/dist/cmd/lib/workflows/read.d.ts +0 -6
  57. package/dist/cmd/lib/workflows/read.js +0 -61
  58. package/dist/cmd/sys/clipboard.d.ts +0 -3
  59. package/dist/cmd/sys/clipboard.js +0 -33
  60. package/dist/cmd/sys/delete_file.d.ts +0 -2
  61. package/dist/cmd/sys/delete_file.js +0 -10
  62. package/dist/cmd/sys/dirs.d.ts +0 -2
  63. package/dist/cmd/sys/dirs.js +0 -9
  64. package/dist/cmd/sys/execute.d.ts +0 -13
  65. package/dist/cmd/sys/execute.js +0 -48
  66. package/dist/cmd/sys/read.d.ts +0 -3
  67. package/dist/cmd/sys/read.js +0 -21
  68. package/dist/cmd/sys/read_conf.d.ts +0 -6
  69. package/dist/cmd/sys/read_conf.js +0 -12
  70. package/dist/cmd/sys/read_features.d.ts +0 -3
  71. package/dist/cmd/sys/read_features.js +0 -112
  72. package/dist/cmd/sys/read_task.d.ts +0 -6
  73. package/dist/cmd/sys/read_task.js +0 -23
  74. package/dist/cmd/sys/read_yml_file.d.ts +0 -5
  75. package/dist/cmd/sys/read_yml_file.js +0 -11
  76. package/dist/cmd/sys/run_python.d.ts +0 -6
  77. package/dist/cmd/sys/run_python.js +0 -39
  78. package/dist/conf.d.ts +0 -14
  79. package/dist/conf.js +0 -166
  80. package/dist/const.d.ts +0 -3
  81. package/dist/const.js +0 -24
  82. package/dist/db/db.d.ts +0 -4
  83. package/dist/db/db.js +0 -23
  84. package/dist/db/read.d.ts +0 -34
  85. package/dist/db/read.js +0 -128
  86. package/dist/db/schemas.d.ts +0 -2
  87. package/dist/db/schemas.js +0 -105
  88. package/dist/db/write.d.ts +0 -15
  89. package/dist/db/write.js +0 -376
  90. package/dist/interfaces.d.ts +0 -165
  91. package/dist/interfaces.js +0 -1
  92. package/dist/state/backends.d.ts +0 -7
  93. package/dist/state/backends.js +0 -159
  94. package/dist/state/chat.d.ts +0 -7
  95. package/dist/state/chat.js +0 -10
  96. package/dist/state/features.d.ts +0 -8
  97. package/dist/state/features.js +0 -35
  98. package/dist/state/plugins.d.ts +0 -6
  99. package/dist/state/plugins.js +0 -27
  100. package/dist/state/state.d.ts +0 -20
  101. package/dist/state/state.js +0 -80
  102. package/dist/state/tasks.d.ts +0 -6
  103. package/dist/state/tasks.js +0 -28
  104. package/dist/utils/perf.d.ts +0 -9
  105. package/dist/utils/perf.js +0 -63
  106. package/dist/utils/text.d.ts +0 -6
  107. package/dist/utils/text.js +0 -41
  108. package/dist/utils/user_msgs.d.ts +0 -5
  109. package/dist/utils/user_msgs.js +0 -19
  110. /package/dist/cmd/{clicmds/base.d.ts → base.d.ts} +0 -0
  111. /package/dist/{cmd/options.d.ts → options.d.ts} +0 -0
  112. /package/dist/{cmd/options.js → options.js} +0 -0
  113. /package/dist/{cmd/lib/user_msgs.d.ts → user_msgs.d.ts} +0 -0
  114. /package/dist/{cmd/lib/user_msgs.js → user_msgs.js} +0 -0
@@ -1,105 +0,0 @@
1
- import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2
- import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
3
- import { confirmToolUsage } from "./tools.js";
4
- class McpClient {
5
- name;
6
- transport;
7
- client;
8
- authorizedTools = null;
9
- askUserTools = null;
10
- tools = {};
11
- constructor(servername, command, args, authorizedTools = null, askUserTools = null) {
12
- //console.log("MCP servername", servername);
13
- //console.log("MCP command", command);
14
- //console.log("MCP ARGS", typeof args, args);
15
- this.name = servername;
16
- const okargs = new Array();
17
- for (const arg of args) {
18
- let _arg = arg;
19
- if (arg.startsWith("Authorization:")) {
20
- const k = `MCP_${servername.toUpperCase()}_AUTH`;
21
- const v = process.env[k];
22
- if (!v) {
23
- throw new Error(`Env variable ${k} not found for ${servername} mcp auth`);
24
- }
25
- _arg = arg.replace("$MCP_AUTH", v);
26
- }
27
- okargs.push(_arg);
28
- }
29
- this.transport = new StdioClientTransport({
30
- command: command,
31
- args: args
32
- });
33
- this.client = new Client({ name: "AgentSmith", version: "0.1.0" });
34
- if (authorizedTools) {
35
- this.authorizedTools = authorizedTools;
36
- }
37
- if (askUserTools) {
38
- this.askUserTools = askUserTools;
39
- }
40
- }
41
- async start() {
42
- await this.client.connect(this.transport);
43
- }
44
- async stop() {
45
- await this.client.close();
46
- }
47
- async extractTools() {
48
- const toolSpecs = new Array();
49
- const serverToolsList = await this.client.listTools();
50
- for (const tool of serverToolsList.tools) {
51
- if (this.authorizedTools) {
52
- if (!this.authorizedTools.includes(tool.name)) {
53
- continue;
54
- }
55
- }
56
- const defargs = {};
57
- const argsTypes = {};
58
- if (tool.inputSchema.properties) {
59
- for (const [k, v] of Object.entries(tool.inputSchema.properties)) {
60
- const vv = v;
61
- defargs[k] = { description: vv.description + " (" + vv.type + ")" };
62
- argsTypes[k] = vv.type;
63
- }
64
- }
65
- //console.log("MCP ARGS TYPES", argsTypes);
66
- const exec = async (args) => {
67
- //console.log("MCP EXEC ARGS", args);
68
- const _iargs = args;
69
- for (const [k, v] of Object.entries(_iargs)) {
70
- if (argsTypes[k] == "array") {
71
- try {
72
- _iargs[k] = JSON.parse(v);
73
- }
74
- catch (e) {
75
- console.warn("Error parsing array data from model for tool call", k, "Data:", v);
76
- }
77
- }
78
- }
79
- ;
80
- const payload = {
81
- name: tool.name,
82
- arguments: _iargs,
83
- };
84
- //console.log("PAY", payload);
85
- const res = await this.client.callTool(payload);
86
- return res;
87
- };
88
- const t = {
89
- name: tool.name,
90
- description: tool.description ?? "",
91
- arguments: defargs,
92
- execute: exec
93
- };
94
- if (this.askUserTools) {
95
- if (this.askUserTools.includes(tool.name)) {
96
- t.canRun = confirmToolUsage;
97
- }
98
- }
99
- this.tools[tool.name] = t;
100
- toolSpecs.push(t);
101
- }
102
- return toolSpecs;
103
- }
104
- }
105
- export { McpClient, };
@@ -1,7 +0,0 @@
1
- import { LmTaskConfig } from "../../interfaces.js";
2
- declare function parseCommandArgs(args: Array<any>): {
3
- args: Array<string>;
4
- options: Record<string, any>;
5
- };
6
- declare function parseTaskConfigOptions(options: Record<string, any>): LmTaskConfig;
7
- export { parseCommandArgs, parseTaskConfigOptions, };
@@ -1,52 +0,0 @@
1
- function parseCommandArgs(args) {
2
- //return { args: program.args, options: program.opts() }
3
- //discard the command (last arg)
4
- args.pop();
5
- //console.log("Raw command args:", args);
6
- const res = {
7
- args: new Array(),
8
- options: {},
9
- };
10
- res.options = args.pop();
11
- res.args = Array.isArray(args[0]) ? args[0] : args;
12
- //console.log("PARSE ARGS RES", res.args);
13
- //console.log("PARSE OPTS RES", res.options);
14
- return res;
15
- }
16
- function parseTaskConfigOptions(options) {
17
- const conf = { inferParams: {}, templateName: "" };
18
- const optionsInferParams = {};
19
- if (options?.temperature) {
20
- optionsInferParams.temperature = options.temperature;
21
- }
22
- if (options?.top_k !== undefined) {
23
- optionsInferParams.top_k = options.top_k;
24
- }
25
- if (options?.top_p !== undefined) {
26
- optionsInferParams.top_p = options.top_p;
27
- }
28
- if (options?.min_p !== undefined) {
29
- optionsInferParams.min_p = options.min_p;
30
- }
31
- if (options?.max_tokens !== undefined) {
32
- optionsInferParams.max_tokens = options.max_tokens;
33
- }
34
- if (options?.repeat_penalty !== undefined) {
35
- optionsInferParams.repeat_penalty = options.repeat_penalty;
36
- }
37
- if (options?.images) {
38
- optionsInferParams.images = options.images;
39
- }
40
- if (options?.model !== undefined) {
41
- if (!conf?.model) {
42
- conf.model = { name: "" };
43
- }
44
- conf.model.name = options.model;
45
- }
46
- if (options?.template !== undefined) {
47
- conf.templateName = options.template;
48
- }
49
- conf.inferParams = optionsInferParams;
50
- return conf;
51
- }
52
- export { parseCommandArgs, parseTaskConfigOptions, };
@@ -1,4 +0,0 @@
1
- import { TaskOutput } from "@agent-smith/task";
2
- declare function executeTask(name: string, payload: Record<string, any>, options: Record<string, any>): Promise<TaskOutput>;
3
- declare function executeTaskCmd(name: string, targs?: Array<any>): Promise<TaskOutput>;
4
- export { executeTask, executeTaskCmd };
@@ -1,419 +0,0 @@
1
- import { compile, serializeGrammar } from "@intrinsicai/gbnfgen";
2
- import { default as color, default as colors } from "ansi-colors";
3
- import { PromptTemplate, templates } from "modprompt";
4
- import ora from 'ora';
5
- import { usePerfTimer } from "../../../main.js";
6
- import { backend, backends, listBackends } from "../../../state/backends.js";
7
- import { setChatInferenceParams, setChatTemplate } from "../../../state/chat.js";
8
- import { isChatMode } from "../../../state/state.js";
9
- import { initTaskSettings, isTaskSettingsInitialized, tasksSettings } from "../../../state/tasks.js";
10
- import { chat, program } from "../../cmds.js";
11
- import { parseCommandArgs } from "../options_parsers.js";
12
- import { runtimeDataError, runtimeError, runtimeWarning } from "../user_msgs.js";
13
- import { processOutput } from "../utils.js";
14
- import { readTask } from "./read.js";
15
- import { getTaskPrompt } from "./utils.js";
16
- import { Agent } from "@agent-smith/agent";
17
- async function executeTask(name, payload, options) {
18
- //console.log("EXEC TASK", payload, options);
19
- //console.log("TN", name);
20
- //console.log("AGENT", agent);
21
- if (!isTaskSettingsInitialized.value) {
22
- initTaskSettings();
23
- }
24
- const agent = new Agent(backend.value, name);
25
- const hasSettings = Object.keys(tasksSettings).includes(name);
26
- let settings = {};
27
- if (hasSettings) {
28
- settings = tasksSettings[name];
29
- }
30
- if (options?.backend) {
31
- if (options.backend in backends) {
32
- agent.lm = backends[options.backend];
33
- //console.log("SET AGENT BACKEND TO", backends[options.backend]);
34
- }
35
- else {
36
- const bks = await listBackends(false);
37
- runtimeDataError(`The backend ${options.backend} is not registered in config. Available backends:\n`, bks);
38
- }
39
- }
40
- else if (settings?.backend) {
41
- //console.log("SET AGENT BACKEND TO", backends[options.backend]);
42
- agent.lm = backends[settings.backend];
43
- }
44
- if (options?.debug || options?.backend) {
45
- console.log("Agent:", colors.bold(agent.name), "( " + agent.lm.providerType + " backend type)");
46
- }
47
- const { task, model, conf, vars, mcpServers, taskDir } = await readTask(name, payload, options, agent);
48
- if (options?.debug && mcpServers.length > 0) {
49
- console.log("Starting", mcpServers.length, "mcp servers");
50
- }
51
- for (const mcp of mcpServers) {
52
- await mcp.start();
53
- const tools = await mcp.extractTools();
54
- tools.forEach(t => task.def.tools?.push(t));
55
- if (options?.debug) {
56
- console.log("MCP start", mcp.name);
57
- }
58
- }
59
- //console.log("TASKCONF IP", conf.inferParams);
60
- if (hasSettings) {
61
- if (!model?.inferParams) {
62
- model.inferParams = {};
63
- }
64
- if (settings?.model && !conf?.model?.name) {
65
- model.name = settings.model;
66
- }
67
- if (settings?.template && !conf?.model?.template) {
68
- model.template = settings.template;
69
- }
70
- if (settings?.ctx && !conf?.model?.ctx) {
71
- model.ctx = settings.ctx;
72
- }
73
- if (settings?.max_tokens && !conf?.inferParams?.max_tokens) {
74
- model.inferParams.max_tokens = settings.max_tokens;
75
- }
76
- if (settings?.top_k && !conf?.inferParams?.top_k) {
77
- model.inferParams.top_k = settings.top_k;
78
- }
79
- if (settings?.top_p && !conf?.inferParams?.top_p) {
80
- model.inferParams.top_p = settings.top_p;
81
- }
82
- if (settings?.min_p && !conf?.inferParams?.min_p) {
83
- model.inferParams.min_p = settings.min_p;
84
- }
85
- if (settings?.temperature && !conf?.inferParams?.temperature) {
86
- model.inferParams.temperature = settings.temperature;
87
- }
88
- if (settings?.repeat_penalty && !conf?.inferParams?.repeat_penalty) {
89
- model.inferParams.repeat_penalty = settings.repeat_penalty;
90
- }
91
- }
92
- //console.log("TASK MODEL", model);
93
- // check for grammars
94
- if (model?.inferParams?.tsGrammar) {
95
- //console.log("TSG");
96
- model.inferParams.grammar = serializeGrammar(await compile(model.inferParams.tsGrammar, "Grammar"));
97
- delete model.inferParams.tsGrammar;
98
- }
99
- //let i = 0;
100
- let c = false;
101
- //const useTemplates = agent.lm.providerType !== "openai";
102
- let hasThink = false;
103
- let tpl = null;
104
- //console.log("Use templates:", useTemplates);
105
- //if (useTemplates) {
106
- try {
107
- tpl = new PromptTemplate(model.template ?? "none");
108
- }
109
- catch (e) {
110
- throw new Error(`Can not load template ${model.template}\nAvailable templates: ${Object.keys(templates)}\n`);
111
- }
112
- //console.log("TPL:", tpl.id);
113
- hasThink = tpl.tags?.think ? true : false;
114
- //console.log("HT", hasThink);
115
- //}
116
- if (options?.debug) {
117
- console.log("Task model:", model);
118
- console.log("Task vars:", vars);
119
- }
120
- //const hasTools = ex.template?.tags?.toolCall;
121
- //console.log("EX TPL", ex.template);
122
- //console.log("ST", thinkStart);
123
- //console.log("ET", thinkEnd);
124
- //let fullTxt = ""
125
- let emittedTokens = 0;
126
- const printToken = (t) => {
127
- if (options?.tokens === true) {
128
- let txt = t;
129
- txt = c ? t : `\x1b[100m${t}\x1b[0m`;
130
- process.stdout.write(txt);
131
- c = !c;
132
- }
133
- else {
134
- /*if (formatMode.value == "markdown") {
135
- fullTxt += t;
136
- process.stdout.write('\u001Bc\u001B[3J');
137
- process.stdout.write(marked.parse(fullTxt) as string);*/
138
- //} else {
139
- process.stdout.write(t);
140
- //}
141
- }
142
- };
143
- let hasTools = false;
144
- if (task.def?.tools) {
145
- if (task.def.tools.length > 0) {
146
- hasTools = true;
147
- }
148
- }
149
- //console.log("HAS TOOLS", hasTools);
150
- let continueWrite = true;
151
- let skipNextEmptyLinesToken = false;
152
- const spinner = ora("Thinking ...");
153
- const ts = "Thinking";
154
- const te = color.dim("tokens");
155
- const formatTokenCount = (i) => {
156
- return `${ts} ${color.bold(i.toString())} ${te}`;
157
- };
158
- const perfTimer = usePerfTimer(false);
159
- let abort = options?.abort ? options.abort : new AbortController();
160
- const abortTicker = setInterval(() => {
161
- //console.log("ABS", abort.signal.aborted);
162
- if (abort.signal.aborted) {
163
- agent.lm.abort();
164
- abort = new AbortController();
165
- }
166
- }, 200);
167
- const processToken = (t) => {
168
- if (emittedTokens == 0) {
169
- perfTimer.start();
170
- }
171
- spinner.text = formatTokenCount(emittedTokens);
172
- if (!options?.verbose && !options?.debug) {
173
- //console.log("TTTTTT", hasThink && tpl);
174
- if (hasThink && tpl) {
175
- if (t == tpl.tags.think?.start) {
176
- //console.log("Start thinking token", thinkStart);
177
- spinner.start();
178
- continueWrite = false;
179
- return;
180
- }
181
- else if (t == tpl.tags.think?.end) {
182
- //console.log("End thinking token", thinkEnd);
183
- continueWrite = true;
184
- skipNextEmptyLinesToken = true;
185
- let msg = color.dim("Thinking:") + ` ${emittedTokens} ${color.dim("tokens")}`;
186
- msg = msg + " " + color.dim(perfTimer.time());
187
- spinner.info(msg);
188
- return;
189
- }
190
- }
191
- }
192
- else {
193
- if (tpl) {
194
- if (t == tpl.tags.think?.end) {
195
- let msg = color.dim("Thinking:") + ` ${emittedTokens} ${color.dim("tokens")}`;
196
- msg = msg + " " + color.dim(perfTimer.time());
197
- console.log(msg);
198
- }
199
- }
200
- }
201
- if (hasTools && tpl) {
202
- // check for tool call and silence the output
203
- if (t == tpl.tags.toolCall?.start) {
204
- if (!options?.debug) {
205
- continueWrite = false;
206
- if (emittedTokens > 0) {
207
- console.log();
208
- }
209
- return;
210
- }
211
- }
212
- else if (t == tpl.tags.toolCall?.end) {
213
- skipNextEmptyLinesToken = true;
214
- continueWrite = true;
215
- if (!options?.debug) {
216
- return;
217
- }
218
- }
219
- }
220
- if (continueWrite) {
221
- if (skipNextEmptyLinesToken) {
222
- if (t == "\n\n" || t == "\n") {
223
- skipNextEmptyLinesToken = false;
224
- return;
225
- }
226
- }
227
- if (!options?.quiet) {
228
- if (!options?.isToolCall) {
229
- printToken(t);
230
- }
231
- else {
232
- if (options?.debug) {
233
- printToken(t);
234
- }
235
- }
236
- }
237
- }
238
- ++emittedTokens;
239
- };
240
- //const spinnerInit = (name: string) => ora(`Executing the ${name} tool ...\n`);
241
- //let tcspinner: Ora;
242
- const _onToolCall = (tc) => {
243
- //console.log("TC START");
244
- console.log("⚒️ ", color.bold(name), "=>", `${color.yellowBright(tc.name)}`, tc.arguments);
245
- };
246
- const onToolCall = options?.onToolCall ?? _onToolCall;
247
- const _onToolCallEnd = (tr) => {
248
- if (options?.debug) {
249
- console.log("TOOL RESULT", tr);
250
- }
251
- };
252
- const onToolCallEnd = options?.onToolCallEnd ?? _onToolCallEnd;
253
- const onToolsTurnStart = options?.onToolsTurnStart ?? undefined;
254
- const onToolsTurnEnd = options?.onToolsTurnEnd ?? undefined;
255
- const onTurnEnd = options?.onTurnEnd ?? undefined;
256
- const onAssistant = options?.onAssistant ?? undefined;
257
- const onThink = options?.onThink ?? undefined;
258
- //console.log("OOT", options?.onToken, "/", processToken);
259
- if (options?.onToken) {
260
- task.agent.lm.onToken = options.onToken;
261
- }
262
- else {
263
- task.agent.lm.onToken = processToken;
264
- }
265
- if (!conf?.inferParams) {
266
- conf.inferParams = {};
267
- }
268
- conf.inferParams.stream = true;
269
- if (conf?.model) {
270
- delete conf.model;
271
- }
272
- const tconf = {
273
- baseDir: taskDir,
274
- model: model,
275
- //debug: options?.debug ?? false,
276
- onToolCall: onToolCall,
277
- onToolCallEnd: onToolCallEnd,
278
- onToolsTurnStart: onToolsTurnStart,
279
- onToolsTurnEnd: onToolsTurnEnd,
280
- onTurnEnd: onTurnEnd,
281
- onAssistant: onAssistant,
282
- onThink: onThink,
283
- ...conf,
284
- };
285
- if (options?.history) {
286
- agent.history = options.history;
287
- }
288
- const initialInferParams = Object.assign({}, conf.inferParams);
289
- initialInferParams.model = tconf.model;
290
- //console.log("CONF", conf);
291
- //console.log("TCONF", tconf);
292
- //console.log("RUN", task);
293
- let out;
294
- //console.log("CLI EXEC TASK", payload.prompt, "\nVARS:", vars, "\nOPTS", tconf)
295
- try {
296
- out = await task.run({ prompt: payload.prompt, ...vars }, tconf);
297
- }
298
- catch (e) {
299
- //console.log("ERR CATCH", e);
300
- const errMsg = `${e}`;
301
- if (errMsg.includes("502 Bad Gateway")) {
302
- clearInterval(abortTicker);
303
- runtimeError("The server answered with a 502 Bad Gateway error. It might be down or misconfigured. Check your inference server.");
304
- if (options?.nocli) {
305
- throw new Error(errMsg);
306
- }
307
- //@ts-ignore
308
- return;
309
- }
310
- else if (errMsg.includes("404 Not Found")) {
311
- clearInterval(abortTicker);
312
- runtimeError("The server answered with a 404 Not Found error. That might mean that the model you are requesting does not exist on the server.");
313
- if (options?.nocli) {
314
- throw new Error(errMsg);
315
- }
316
- //@ts-ignore
317
- return;
318
- }
319
- else if (errMsg.includes("400 Bad Request")) {
320
- clearInterval(abortTicker);
321
- runtimeError("The server answered with a 400 Bad Request error. That might mean that the model you are requesting does not exist on the server, a parameter is wrong or missing in your request.");
322
- if (options?.nocli) {
323
- throw new Error(errMsg);
324
- }
325
- //@ts-ignore
326
- return;
327
- }
328
- else if (errMsg.includes("fetch failed")) {
329
- clearInterval(abortTicker);
330
- runtimeError("The server is not responding. Check if your inference backend is running.");
331
- if (options?.nocli) {
332
- throw new Error(errMsg);
333
- }
334
- //@ts-ignore
335
- return;
336
- }
337
- else if (e instanceof DOMException && e.name === 'AbortError') {
338
- if (options?.debug || options?.verbose) {
339
- console.warn("\n*** The request was canceled by the user ***");
340
- }
341
- clearInterval(abortTicker);
342
- return {};
343
- }
344
- else {
345
- throw new Error(errMsg);
346
- }
347
- }
348
- clearInterval(abortTicker);
349
- //console.log("END TASK", out);
350
- if (!options?.isToolCall) {
351
- if (!out.answer.text.endsWith("\n")) {
352
- console.log();
353
- }
354
- }
355
- //console.log("END", name, "ISCM", isChatMode.value, "isTC", options?.isToolCall)
356
- if (!isChatMode.value || options?.isToolCall) {
357
- // close mcp connections
358
- if (options?.debug && mcpServers.length > 0) {
359
- console.log("Closing", mcpServers.length, "mcp server(s)");
360
- }
361
- mcpServers.forEach((s) => {
362
- s.stop();
363
- if (options?.debug) {
364
- console.log("MCP stop", s.name);
365
- }
366
- });
367
- }
368
- await processOutput(out);
369
- // chat mode
370
- //console.log("CLI CONF IP", initialInferParams);
371
- if (!options?.isToolCall && isChatMode.value) {
372
- setChatTemplate(tpl);
373
- if (task.def.tools) {
374
- options.tools = task.def.tools;
375
- }
376
- if (task.def.shots) {
377
- options.history = options?.history ? [...options.history, ...task.def.shots] : task.def.shots;
378
- }
379
- if (task.def.template?.system) {
380
- options.system = task.def.template.system;
381
- }
382
- /*if (task.def.template?.afterSystem) {
383
- options.system = (tpl?.system ?? "") + task.def.template.afterSystem
384
- }*/
385
- if (task.def.template?.assistant) {
386
- options.assistant = task.def.template.assistant;
387
- }
388
- setChatInferenceParams(initialInferParams);
389
- await chat(program, options, agent, mcpServers);
390
- }
391
- if (options?.debug === true || options?.verbose === true) {
392
- try {
393
- console.log(emittedTokens.toString(), color.dim("tokens"), out.answer.stats.tokensPerSecond, color.dim("tps"));
394
- //console.log("\n", formatStats(out.answer.stats))
395
- if (options?.debug === true) {
396
- console.log(out.answer.stats);
397
- }
398
- }
399
- catch (e) {
400
- runtimeWarning("Error formating stats:", `${e}`);
401
- }
402
- }
403
- if (options?.backend || settings?.backend) {
404
- //console.log("SET BACK AGENT BACKEND TO", backend.value);
405
- // set back the default backend
406
- agent.lm = backend.value;
407
- }
408
- //console.log("TASK OUT", out);
409
- return out;
410
- }
411
- async function executeTaskCmd(name, targs = []) {
412
- const ca = parseCommandArgs(targs);
413
- //console.log("ARGS", ca);
414
- const prompt = await getTaskPrompt(name, ca.args, ca.options);
415
- const tr = await executeTask(name, { prompt: prompt }, ca.options);
416
- //console.log("TR", tr);
417
- return tr;
418
- }
419
- export { executeTask, executeTaskCmd };
@@ -1,6 +0,0 @@
1
- import type { InferenceParams } from "@locallm/types";
2
- import type { LmTaskConfig, LmTaskFileSpec, ModelSpec } from "../../../interfaces.js";
3
- declare function configureTaskModel(itConf: LmTaskConfig, taskSpec: LmTaskFileSpec): ModelSpec;
4
- declare function mergeConfOptions(conf: LmTaskConfig, options: Record<string, any>): LmTaskConfig;
5
- declare function mergeInferParams(userInferParams: Record<string, any>, taskInferParams: InferenceParams): InferenceParams;
6
- export { mergeConfOptions, mergeInferParams, configureTaskModel, };