@wheatley-ai/cli 0.3.0 → 0.4.0
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/dist/cli/ask.js +8 -4
- package/dist/cli/chat.js +8 -4
- package/dist/cli/daemon.js +45 -0
- package/dist/cli/io.js +1 -0
- package/dist/cli/main.js +145 -163
- package/dist/cli/session.js +59 -3
- package/dist/cli/status.js +4 -4
- package/dist/cli/tui/app.js +14 -2
- package/dist/cli/tui/controller.js +80 -19
- package/dist/cli/tui/markdown.js +229 -104
- package/dist/cli/tui/model-picker.js +76 -0
- package/dist/cli/tui/picker-panel.js +39 -0
- package/dist/core/agent/agent.js +23 -12
- package/dist/core/config/config-store.js +11 -6
- package/dist/core/config/diagnostics.js +116 -0
- package/dist/core/config/secret-store.js +13 -9
- package/dist/core/deployment.js +19 -1
- package/dist/core/markdown-tokens.js +60 -0
- package/dist/core/model-catalog.js +54 -0
- package/dist/core/rpc/deployment-handlers.js +2 -1
- package/dist/core/server/control-server.js +19 -21
- package/dist/core/server/http-server.js +17 -0
- package/dist/core/server/static-files.js +40 -66
- package/dist/dashboard/assets/index-DGa2Ps9u.js +12 -0
- package/dist/dashboard/assets/index-DeERxJOJ.css +2 -0
- package/dist/dashboard/assets/{sheet-presentation-CkgiDsTg.js → sheet-presentation-CZ1dO2kr.js} +1 -1
- package/dist/dashboard/index.html +2 -2
- package/dist/frontends/discord/approvals.js +8 -43
- package/dist/frontends/discord/binding.js +81 -8
- package/dist/frontends/discord/json-file.js +57 -0
- package/dist/frontends/discord/model-picker.js +276 -0
- package/dist/frontends/slack/binding.js +33 -3
- package/dist/frontends/slack/inbound.js +21 -12
- package/dist/frontends/slack/model-picker-blocks.js +147 -0
- package/dist/frontends/slack/outbound.js +27 -2
- package/dist/frontends/slack/schemas.js +9 -2
- package/dist/frontends/telegram/approvals.js +13 -48
- package/dist/frontends/telegram/binding.js +5 -0
- package/dist/frontends/telegram/client.js +7 -0
- package/dist/frontends/telegram/delivery.js +19 -6
- package/dist/frontends/telegram/inbound.js +64 -8
- package/dist/frontends/telegram/markdown.js +120 -83
- package/dist/frontends/telegram/model-picker.js +160 -0
- package/dist/frontends/telegram/token-store.js +73 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +13 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +9 -1
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +2 -2
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +2 -2
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +23 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +1 -1
- package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
- package/dist/ops/cli.js +92 -98
- package/dist/ops/service.js +6 -1
- package/dist/ops/update.js +14 -27
- package/dist/triggers/delivery-codec.js +13 -0
- package/dist/triggers/webhook-ingress.js +89 -82
- package/package.json +9 -2
- package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
- package/dist/dashboard/assets/index-DThc2x_d.js +0 -11
package/dist/core/agent/agent.js
CHANGED
|
@@ -10,6 +10,7 @@ import { ConcurrencyGate } from "../concurrency-gate.js";
|
|
|
10
10
|
import { SerialQueue } from "../config/atomic-file.js";
|
|
11
11
|
import { CLI_BINDING_ID } from "../config/validate.js";
|
|
12
12
|
import { errorMessage } from "../error-message.js";
|
|
13
|
+
import { availableModels, modelPickerText, parseModelRef, } from "../model-catalog.js";
|
|
13
14
|
import { toolErrorResult, withExtraTools } from "../tool-routing.js";
|
|
14
15
|
import { AgentStore, CORE_NAMESPACE, coreMigrations } from "./agent-store.js";
|
|
15
16
|
import { openPiAdapter } from "./pi-adapter.js";
|
|
@@ -47,12 +48,7 @@ const resultText = (result) => result.content
|
|
|
47
48
|
const deliveryFor = (chat, source) => isCliChat(chat)
|
|
48
49
|
? null
|
|
49
50
|
: { bindingId: chat.bindingId, chatId: chat.chatId, source };
|
|
50
|
-
const parseModelArgument = (argument, current) => {
|
|
51
|
-
const slash = argument.indexOf("/");
|
|
52
|
-
return slash === -1
|
|
53
|
-
? { id: argument, provider: current.provider }
|
|
54
|
-
: { id: argument.slice(slash + 1), provider: argument.slice(0, slash) };
|
|
55
|
-
};
|
|
51
|
+
const parseModelArgument = (argument, current) => parseModelRef(argument) ?? { id: argument, provider: current.provider };
|
|
56
52
|
/**
|
|
57
53
|
* One running Agent: its `agent.sqlite`, its pi-durable Harness over `harness.sqlite`, its extensions, and its Runs
|
|
58
54
|
* (ADR 0001, ADR 0003). Agents share nothing except the Deployment's model access, so one Agent's failure leaves the
|
|
@@ -225,8 +221,8 @@ export class Agent {
|
|
|
225
221
|
});
|
|
226
222
|
};
|
|
227
223
|
/**
|
|
228
|
-
* Runs a built-in command for `chat` (ADR 0007). Resolves `false` if the command cannot run, for example `/
|
|
229
|
-
* without an argument or `/stop` without an active Run.
|
|
224
|
+
* Runs a built-in command for `chat` (ADR 0007). Resolves `false` if the command cannot run, for example `/goal`
|
|
225
|
+
* without an argument or `/stop` without an active Run. `/model` without an argument lists the available models.
|
|
230
226
|
*
|
|
231
227
|
* Each call sends exactly one command reply to the Chat before it resolves, also when the command cannot run, so a
|
|
232
228
|
* Frontend shows only the reply and adds no message of its own. The exception is `/goal` with an objective, which
|
|
@@ -263,6 +259,16 @@ export class Agent {
|
|
|
263
259
|
}
|
|
264
260
|
}
|
|
265
261
|
};
|
|
262
|
+
/** The available models and the model of the Chat's current Conversation, for `/model` and `models.list`. */
|
|
263
|
+
modelPicker = async (chat) => {
|
|
264
|
+
const conversationId = await this.#chatConversation(chat);
|
|
265
|
+
const [models, model] = await Promise.all([
|
|
266
|
+
availableModels(this.#options.models),
|
|
267
|
+
this.#requirePi().modelOf(conversationId),
|
|
268
|
+
]);
|
|
269
|
+
const current = model === undefined ? undefined : parseModelRef(model);
|
|
270
|
+
return current === undefined ? { models } : { current, models };
|
|
271
|
+
};
|
|
266
272
|
/** Messages of the Chat's current Conversation, oldest first, before `before`. */
|
|
267
273
|
history = async (chat, before, limit) => {
|
|
268
274
|
const conversationId = await this.#chatConversation(chat);
|
|
@@ -720,8 +726,11 @@ export class Agent {
|
|
|
720
726
|
this.#options.events.emit("chat.message", { agent: this.name, message });
|
|
721
727
|
}
|
|
722
728
|
};
|
|
723
|
-
/**
|
|
724
|
-
|
|
729
|
+
/**
|
|
730
|
+
* Sends a command reply to the Chat: an event for the CLI Chat, or an outbox delivery for any other Chat. Only the
|
|
731
|
+
* outbox delivery carries `modelPicker`. CLI Chat clients call `models.list` instead.
|
|
732
|
+
*/
|
|
733
|
+
#reply = async (chat, text, modelPicker) => {
|
|
725
734
|
const conversationId = await this.#chatConversation(chat);
|
|
726
735
|
if (isCliChat(chat)) {
|
|
727
736
|
this.#recordMessage(chat, conversationId, {
|
|
@@ -736,7 +745,7 @@ export class Agent {
|
|
|
736
745
|
await this.#options.outbox?.enqueue({
|
|
737
746
|
bindingId: chat.bindingId,
|
|
738
747
|
chatId: chat.chatId,
|
|
739
|
-
delivery: { kind: "message", source: "command", text },
|
|
748
|
+
delivery: { kind: "message", modelPicker, source: "command", text },
|
|
740
749
|
});
|
|
741
750
|
};
|
|
742
751
|
#resumeRuns = () => {
|
|
@@ -905,7 +914,9 @@ export class Agent {
|
|
|
905
914
|
};
|
|
906
915
|
#changeModel = async (chat, args) => {
|
|
907
916
|
if (args === undefined) {
|
|
908
|
-
|
|
917
|
+
const picker = await this.modelPicker(chat);
|
|
918
|
+
await this.#reply(chat, modelPickerText(picker), picker);
|
|
919
|
+
return true;
|
|
909
920
|
}
|
|
910
921
|
const model = parseModelArgument(args, this.#options.config.model);
|
|
911
922
|
if (this.#options.models.getModel(model.provider, model.id) === undefined) {
|
|
@@ -16,12 +16,17 @@ export const CONFIG_FILE_NAME = "config.yaml";
|
|
|
16
16
|
export const SECRETS_FILE_NAME = "secrets.yaml";
|
|
17
17
|
/** Returns the revision of `config.yaml` text: its SHA-256 hash in hex. */
|
|
18
18
|
export const configRevision = (raw) => createHash("sha256").update(raw).digest("hex");
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
/**
|
|
20
|
+
* The error for invalid `config.yaml` text. `file` is the path that holds the text, so a reader can show the source.
|
|
21
|
+
* Omit it for text that is not on disk yet, such as a rejected save.
|
|
22
|
+
*/
|
|
23
|
+
const invalidConfig = (issues, file) => {
|
|
24
|
+
const list = issues.map(({ message, path: issuePath }) => ({
|
|
21
25
|
message,
|
|
22
26
|
path: issuePath,
|
|
23
|
-
}))
|
|
24
|
-
});
|
|
27
|
+
}));
|
|
28
|
+
return new SeamError("config_invalid", "config.yaml is invalid", file === undefined ? { issues: list } : { file, issues: list });
|
|
29
|
+
};
|
|
25
30
|
/** A config as plain JSON. */
|
|
26
31
|
const configJson = (config) => {
|
|
27
32
|
// A JSON round trip drops fields whose value is `undefined`, which a structured clone would keep.
|
|
@@ -85,7 +90,7 @@ export class FileConfigStore {
|
|
|
85
90
|
const raw = await this.#readRaw();
|
|
86
91
|
const parsed = parseConfigText(raw);
|
|
87
92
|
if (!parsed.ok) {
|
|
88
|
-
throw invalidConfig(parsed.issues);
|
|
93
|
+
throw invalidConfig(parsed.issues, this.#file);
|
|
89
94
|
}
|
|
90
95
|
return this.#snapshot(raw, parsed.config);
|
|
91
96
|
};
|
|
@@ -103,7 +108,7 @@ export class FileConfigStore {
|
|
|
103
108
|
const current = await this.#readRaw();
|
|
104
109
|
const parsed = parseConfigText(current);
|
|
105
110
|
if (!parsed.ok) {
|
|
106
|
-
throw invalidConfig(parsed.issues);
|
|
111
|
+
throw invalidConfig(parsed.issues, this.#file);
|
|
107
112
|
}
|
|
108
113
|
const agentConfig = parsed.config.agents[agent];
|
|
109
114
|
if (agentConfig === undefined) {
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { styleText } from "node:util";
|
|
2
|
+
import { codeFrameColumns } from "@babel/code-frame";
|
|
3
|
+
import { isMap, isNode, isScalar, isSeq, LineCounter, parseDocument, } from "yaml";
|
|
4
|
+
const LINE_BREAK = /\r?\n/u;
|
|
5
|
+
const INDEX_SEGMENT = /^\d+$/u;
|
|
6
|
+
const TRAILING_LINE_BREAK = /\r?\n$/u;
|
|
7
|
+
/** The source lines that the code frame shows above and below the line of the span. */
|
|
8
|
+
const CONTEXT_LINES = 1;
|
|
9
|
+
/** Decodes a JSON Pointer such as `/agents/home/model` into its segments. */
|
|
10
|
+
const pointerSegments = (pointer) => pointer === "/" || pointer === ""
|
|
11
|
+
? []
|
|
12
|
+
: pointer
|
|
13
|
+
.slice(1)
|
|
14
|
+
.split("/")
|
|
15
|
+
.map((segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~"));
|
|
16
|
+
const nodeSpan = (node) => {
|
|
17
|
+
const [start, valueEnd] = node.range ?? [0, 0];
|
|
18
|
+
return [start, valueEnd];
|
|
19
|
+
};
|
|
20
|
+
/** True for a value that starts on the line after its key, such as a block map or a block sequence. */
|
|
21
|
+
const isBlockCollection = (node) => (isMap(node) || isSeq(node)) && node.flow !== true;
|
|
22
|
+
/** The span of a map entry: the key and a value on the same line, or only the key for a block collection value. */
|
|
23
|
+
const pairSpan = (pair) => {
|
|
24
|
+
const [start, keyEnd] = nodeSpan(pair.key);
|
|
25
|
+
if (!isNode(pair.value) || isBlockCollection(pair.value)) {
|
|
26
|
+
return [start, keyEnd];
|
|
27
|
+
}
|
|
28
|
+
return [start, Math.max(keyEnd, nodeSpan(pair.value)[1])];
|
|
29
|
+
};
|
|
30
|
+
const findPair = (items, segment) => items.find((pair) => isScalar(pair.key) && String(pair.key.value) === segment);
|
|
31
|
+
/**
|
|
32
|
+
* Resolves a JSON Pointer against the YAML AST. If a segment does not exist, for example a missing required field, the
|
|
33
|
+
* span is the deepest entry that exists: the parent key, sequence item, or the start of the document.
|
|
34
|
+
*/
|
|
35
|
+
const pointerSpan = (doc, pointer) => {
|
|
36
|
+
let node = doc.contents;
|
|
37
|
+
let span = isNode(node) ? nodeSpan(node) : [0, 0];
|
|
38
|
+
for (const segment of pointerSegments(pointer)) {
|
|
39
|
+
if (isMap(node)) {
|
|
40
|
+
const pair = findPair(node.items, segment);
|
|
41
|
+
if (pair === undefined) {
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
span = pairSpan(pair);
|
|
45
|
+
node = pair.value;
|
|
46
|
+
}
|
|
47
|
+
else if (isSeq(node) && INDEX_SEGMENT.test(segment)) {
|
|
48
|
+
const item = node.items[Number(segment)];
|
|
49
|
+
if (!isNode(item)) {
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
span = nodeSpan(item);
|
|
53
|
+
node = item;
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return span;
|
|
60
|
+
};
|
|
61
|
+
const syntaxDiagnostics = (doc) => doc.errors.map((error) => ({
|
|
62
|
+
headline: "invalid YAML syntax",
|
|
63
|
+
label: error.message,
|
|
64
|
+
span: error.pos,
|
|
65
|
+
}));
|
|
66
|
+
const issueDiagnostics = (doc, issues) => issues.map((issue) => ({
|
|
67
|
+
headline: `invalid value at ${issue.path}`,
|
|
68
|
+
label: issue.message,
|
|
69
|
+
span: pointerSpan(doc, issue.path),
|
|
70
|
+
}));
|
|
71
|
+
/** Moves an offset at the end of the text back onto the last line, so that it points after its last character. */
|
|
72
|
+
const clampOffset = (source, offset) => {
|
|
73
|
+
const last = source.endsWith("\n") ? source.length - 1 : source.length;
|
|
74
|
+
return Math.max(0, Math.min(offset, last));
|
|
75
|
+
};
|
|
76
|
+
/** Applies a `styleText` format if `color` is true. */
|
|
77
|
+
const paint = (color, format, text) => color ? styleText(format, text, { validateStream: false }) : text;
|
|
78
|
+
const renderDiagnostic = (diagnostic, input, counter, lines) => {
|
|
79
|
+
const start = clampOffset(input.source, diagnostic.span[0]);
|
|
80
|
+
const { line, col } = counter.linePos(start);
|
|
81
|
+
const lineEnd = start - (col - 1) + (lines[line - 1] ?? "").trimEnd().length;
|
|
82
|
+
const width = Math.max(0, Math.min(diagnostic.span[1], lineEnd) - start);
|
|
83
|
+
// `codeFrameColumns` takes 0-based columns and colors only with `forceColor`, so the caller decides on color.
|
|
84
|
+
const frame = codeFrameColumns(input.source.replace(TRAILING_LINE_BREAK, ""), {
|
|
85
|
+
end: { column: col - 1 + width, line },
|
|
86
|
+
start: { column: col - 1, line },
|
|
87
|
+
}, {
|
|
88
|
+
forceColor: input.color,
|
|
89
|
+
linesAbove: CONTEXT_LINES,
|
|
90
|
+
linesBelow: CONTEXT_LINES,
|
|
91
|
+
message: diagnostic.label,
|
|
92
|
+
});
|
|
93
|
+
const gutterWidth = String(Math.min(line + CONTEXT_LINES, lines.length)).length;
|
|
94
|
+
return [
|
|
95
|
+
`${paint(input.color, ["red", "bold"], "error")}${paint(input.color, "bold", `: ${diagnostic.headline}`)}`,
|
|
96
|
+
`${" ".repeat(gutterWidth + 1)}${paint(input.color, "gray", "-->")} ${input.file}:${line}:${col}`,
|
|
97
|
+
frame,
|
|
98
|
+
].join("\n");
|
|
99
|
+
};
|
|
100
|
+
/**
|
|
101
|
+
* Renders validation issues of a YAML config file as rustc-style diagnostics: a headline, the `file:line:column`
|
|
102
|
+
* location, and a code frame with carets under the offending entry. If the text has YAML syntax errors, they replace
|
|
103
|
+
* `issues`, because their positions come from the parser. Each issue path is a JSON Pointer into the YAML document.
|
|
104
|
+
*/
|
|
105
|
+
export const renderConfigDiagnostics = (input) => {
|
|
106
|
+
const counter = new LineCounter();
|
|
107
|
+
const doc = parseDocument(input.source, {
|
|
108
|
+
lineCounter: counter,
|
|
109
|
+
prettyErrors: false,
|
|
110
|
+
});
|
|
111
|
+
const diagnostics = doc.errors.length > 0
|
|
112
|
+
? syntaxDiagnostics(doc)
|
|
113
|
+
: issueDiagnostics(doc, input.issues);
|
|
114
|
+
const lines = input.source.replace(TRAILING_LINE_BREAK, "").split(LINE_BREAK);
|
|
115
|
+
return `${diagnostics.map((diagnostic) => renderDiagnostic(diagnostic, input, counter, lines)).join("\n\n")}\n`;
|
|
116
|
+
};
|
|
@@ -7,21 +7,25 @@ const SECRET_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
|
|
|
7
7
|
const MIN_REDACTED_LENGTH = 4;
|
|
8
8
|
const REDACTED = "[redacted]";
|
|
9
9
|
const isText = (value) => typeof value === "string";
|
|
10
|
-
const invalid = (issues) => new SeamError("config_invalid", "secrets.yaml is invalid", {
|
|
10
|
+
const invalid = (file, issues) => new SeamError("config_invalid", "secrets.yaml is invalid", {
|
|
11
|
+
file,
|
|
11
12
|
issues: issues.map(({ message, path }) => ({ message, path })),
|
|
12
13
|
});
|
|
13
|
-
/**
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Parses `secrets.yaml`: a map of secret names to string values. An empty or missing file has no secrets. `file` is the
|
|
16
|
+
* path that holds `raw`, for the error details.
|
|
17
|
+
*/
|
|
18
|
+
const parseSecrets = (file, raw) => {
|
|
15
19
|
const doc = parseDocument(raw, { prettyErrors: false });
|
|
16
20
|
if (doc.errors.length > 0) {
|
|
17
|
-
throw invalid(doc.errors.map((error) => ({ message: error.message, path: "/" })));
|
|
21
|
+
throw invalid(file, doc.errors.map((error) => ({ message: error.message, path: "/" })));
|
|
18
22
|
}
|
|
19
23
|
const values = new Map();
|
|
20
24
|
if (doc.contents === null) {
|
|
21
25
|
return { doc, values };
|
|
22
26
|
}
|
|
23
27
|
if (!isMap(doc.contents)) {
|
|
24
|
-
throw invalid([
|
|
28
|
+
throw invalid(file, [
|
|
25
29
|
{ message: "secrets.yaml must be a map of names to values", path: "/" },
|
|
26
30
|
]);
|
|
27
31
|
}
|
|
@@ -46,7 +50,7 @@ const parseSecrets = (raw) => {
|
|
|
46
50
|
}
|
|
47
51
|
}
|
|
48
52
|
if (issues.length > 0) {
|
|
49
|
-
throw invalid(issues);
|
|
53
|
+
throw invalid(file, issues);
|
|
50
54
|
}
|
|
51
55
|
return { doc, values };
|
|
52
56
|
};
|
|
@@ -65,7 +69,7 @@ export class FileSecretStore {
|
|
|
65
69
|
/** Loads `secrets.yaml`. Throws `SeamError("config_invalid")` for a file that is not a map of string values. */
|
|
66
70
|
static async open(options) {
|
|
67
71
|
const raw = (await readTextIfExists(options.file)) ?? "";
|
|
68
|
-
return new FileSecretStore(options, parseSecrets(raw).values);
|
|
72
|
+
return new FileSecretStore(options, parseSecrets(options.file, raw).values);
|
|
69
73
|
}
|
|
70
74
|
get = (name) => this.#options.env[name] ?? this.#values.get(name);
|
|
71
75
|
list = async () => {
|
|
@@ -128,12 +132,12 @@ export class FileSecretStore {
|
|
|
128
132
|
#change = async (edit) => {
|
|
129
133
|
await this.#queue.run(async () => {
|
|
130
134
|
const raw = (await readTextIfExists(this.#options.file)) ?? "";
|
|
131
|
-
const { doc } = parseSecrets(raw);
|
|
135
|
+
const { doc } = parseSecrets(this.#options.file, raw);
|
|
132
136
|
doc.contents ??= doc.createNode({});
|
|
133
137
|
edit(doc);
|
|
134
138
|
const text = doc.toString();
|
|
135
139
|
await writeFileAtomic(this.#options.file, text, SECRETS_FILE_MODE);
|
|
136
|
-
this.#values = parseSecrets(text).values;
|
|
140
|
+
this.#values = parseSecrets(this.#options.file, text).values;
|
|
137
141
|
});
|
|
138
142
|
};
|
|
139
143
|
#sourceOf = (name) => {
|
package/dist/core/deployment.js
CHANGED
|
@@ -3,7 +3,7 @@ import path from "node:path";
|
|
|
3
3
|
import { PROTOCOL_VERSION } from "@wheatley-ai/protocol";
|
|
4
4
|
import { SeamError } from "../contracts/errors.js";
|
|
5
5
|
import { systemClock } from "../contracts/module.js";
|
|
6
|
-
import { Agent } from "./agent/agent.js";
|
|
6
|
+
import { Agent, CLI_CHAT } from "./agent/agent.js";
|
|
7
7
|
import { gatedModels } from "./agent/gated-models.js";
|
|
8
8
|
import { builtinOnlyCatalog } from "./builtin-catalog.js";
|
|
9
9
|
import { ConcurrencyGate, DEFAULT_PROVIDER_CONCURRENCY, } from "./concurrency-gate.js";
|
|
@@ -11,6 +11,7 @@ import { FileConfigStore } from "./config/config-store.js";
|
|
|
11
11
|
import { pendingRestarts } from "./config/pending-restart.js";
|
|
12
12
|
import { EventBus } from "./events.js";
|
|
13
13
|
import { LogStore } from "./logger.js";
|
|
14
|
+
import { availableModels } from "./model-catalog.js";
|
|
14
15
|
import { createProviderModels } from "./models.js";
|
|
15
16
|
import { defaultSetTimer, Supervisor } from "./supervisor.js";
|
|
16
17
|
/** The folder of the Agents inside the Deployment home. */
|
|
@@ -192,6 +193,23 @@ export class Deployment {
|
|
|
192
193
|
version: this.#options.version,
|
|
193
194
|
};
|
|
194
195
|
};
|
|
196
|
+
/**
|
|
197
|
+
* `models.list`: the available models of the current config. With a running `agent`, also the model of its CLI Chat
|
|
198
|
+
* Conversation. Errors: throws `agent_not_found` for an unknown Agent.
|
|
199
|
+
*/
|
|
200
|
+
listModels = async (agent) => {
|
|
201
|
+
if (agent !== undefined) {
|
|
202
|
+
this.#requireKnown(agent);
|
|
203
|
+
const instance = this.#supervisor.get(agent)?.instance;
|
|
204
|
+
if (instance !== undefined) {
|
|
205
|
+
const picker = await instance.modelPicker(CLI_CHAT);
|
|
206
|
+
return { ...picker, models: [...picker.models] };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const createModels = this.#options.models ?? createProviderModels;
|
|
210
|
+
const models = await createModels(this.#current, this.config.secrets);
|
|
211
|
+
return { models: await availableModels(models) };
|
|
212
|
+
};
|
|
195
213
|
startAgent = async (name) => {
|
|
196
214
|
this.#requireConfigured(name);
|
|
197
215
|
return await this.#supervisor.start(name);
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Marked } from "marked";
|
|
2
|
+
/**
|
|
3
|
+
* GitHub Flavored Markdown, with `breaks` so a single newline in a reply stays a line break. The instance is private,
|
|
4
|
+
* so no other code can change its options or extensions.
|
|
5
|
+
*/
|
|
6
|
+
const parser = new Marked({ breaks: true, gfm: true });
|
|
7
|
+
const INLINE_TYPES = [
|
|
8
|
+
"br",
|
|
9
|
+
"codespan",
|
|
10
|
+
"del",
|
|
11
|
+
"em",
|
|
12
|
+
"escape",
|
|
13
|
+
"html",
|
|
14
|
+
"image",
|
|
15
|
+
"link",
|
|
16
|
+
"strong",
|
|
17
|
+
"text",
|
|
18
|
+
];
|
|
19
|
+
const BLOCK_TYPES = [
|
|
20
|
+
"blockquote",
|
|
21
|
+
"checkbox",
|
|
22
|
+
"code",
|
|
23
|
+
"def",
|
|
24
|
+
"heading",
|
|
25
|
+
"hr",
|
|
26
|
+
"html",
|
|
27
|
+
"list",
|
|
28
|
+
"list_item",
|
|
29
|
+
"paragraph",
|
|
30
|
+
"space",
|
|
31
|
+
"table",
|
|
32
|
+
"text",
|
|
33
|
+
];
|
|
34
|
+
const INLINE_SET = new Set(INLINE_TYPES);
|
|
35
|
+
const BLOCK_SET = new Set(BLOCK_TYPES);
|
|
36
|
+
// Without extensions, the lexer emits only built-in tokens. The guards also drop the generic token type of extensions.
|
|
37
|
+
const isInline = (token) => INLINE_SET.has(token.type);
|
|
38
|
+
const isBlock = (token) => BLOCK_SET.has(token.type);
|
|
39
|
+
/** The inline tokens of a token list. */
|
|
40
|
+
export const inlineTokens = (tokens) => (tokens ?? []).filter(isInline);
|
|
41
|
+
/** The block tokens of a token list. */
|
|
42
|
+
export const blockTokens = (tokens) => tokens.filter(isBlock);
|
|
43
|
+
/** Calls `visit` for each inline token inside `tokens`, at any depth. */
|
|
44
|
+
export const walkInlineTokens = (tokens, visit) => {
|
|
45
|
+
// The callback is synchronous, so the returned values hold no promises.
|
|
46
|
+
void parser.walkTokens([...tokens], (token) => {
|
|
47
|
+
if (isInline(token)) {
|
|
48
|
+
visit(token);
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
/** Splits Markdown into its top-level block tokens. The `raw` texts of the tokens join to the input, with `\n` line ends. */
|
|
53
|
+
export const lexMarkdown = (markdown) => blockTokens(parser.lexer(markdown));
|
|
54
|
+
/** The box text of a task list item, such as `- [x] done`, or an empty string for another list item. */
|
|
55
|
+
export const taskBox = (item, boxes) => {
|
|
56
|
+
if (!item.task) {
|
|
57
|
+
return "";
|
|
58
|
+
}
|
|
59
|
+
return item.checked === true ? boxes.checked : boxes.unchecked;
|
|
60
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
const compareText = (left, right) => left.localeCompare(right, "en");
|
|
2
|
+
const byProviderThenId = (left, right) => compareText(left.provider, right.provider) || compareText(left.id, right.id);
|
|
3
|
+
/** The chat models of every provider with a configured credential, sorted by provider, then by model ID. */
|
|
4
|
+
export const availableModels = async (models) => {
|
|
5
|
+
const available = await models.getAvailable();
|
|
6
|
+
return available
|
|
7
|
+
.map((model) => ({
|
|
8
|
+
id: model.id,
|
|
9
|
+
name: model.name,
|
|
10
|
+
provider: model.provider,
|
|
11
|
+
}))
|
|
12
|
+
.toSorted(byProviderThenId);
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Parses `<provider>/<id>`. The model ID can contain more slashes, for example `openrouter/anthropic/claude`. Returns
|
|
16
|
+
* `undefined` for text without a slash.
|
|
17
|
+
*/
|
|
18
|
+
export const parseModelRef = (text) => {
|
|
19
|
+
const slash = text.indexOf("/");
|
|
20
|
+
return slash === -1
|
|
21
|
+
? undefined
|
|
22
|
+
: { id: text.slice(slash + 1), provider: text.slice(0, slash) };
|
|
23
|
+
};
|
|
24
|
+
const isSameModel = (left, right) => left?.provider === right.provider && left.id === right.id;
|
|
25
|
+
/** The Markdown fallback of a `/model` reply without an argument: the current model, the list, and a switch hint. */
|
|
26
|
+
export const modelPickerText = (picker) => {
|
|
27
|
+
const { current, models } = picker;
|
|
28
|
+
const header = current === undefined
|
|
29
|
+
? []
|
|
30
|
+
: [`Current model: ${current.provider}/${current.id}`];
|
|
31
|
+
if (models.length === 0) {
|
|
32
|
+
return [...header, "No providers have credentials configured."].join("\n\n");
|
|
33
|
+
}
|
|
34
|
+
const sections = [];
|
|
35
|
+
let provider;
|
|
36
|
+
let lines = [];
|
|
37
|
+
for (const model of models) {
|
|
38
|
+
if (model.provider !== provider) {
|
|
39
|
+
if (provider !== undefined) {
|
|
40
|
+
sections.push(lines.join("\n"));
|
|
41
|
+
}
|
|
42
|
+
({ provider } = model);
|
|
43
|
+
lines = [`**${model.provider}**`];
|
|
44
|
+
}
|
|
45
|
+
const marker = isSameModel(current, model) ? " (current)" : "";
|
|
46
|
+
lines.push(`- ${model.id}${marker}`);
|
|
47
|
+
}
|
|
48
|
+
sections.push(lines.join("\n"));
|
|
49
|
+
return [
|
|
50
|
+
...header,
|
|
51
|
+
...sections,
|
|
52
|
+
"Use /model <id> or /model <provider>/<id> to switch.",
|
|
53
|
+
].join("\n\n");
|
|
54
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** The default number of records that `logs.tail` returns. */
|
|
2
2
|
export const DEFAULT_LOG_TAIL = 200;
|
|
3
3
|
/**
|
|
4
|
-
* The Deployment-wide JSON-RPC handlers: Agent lifecycle (`agents.*`), config (`config.*`), secrets (`secrets.*`),
|
|
4
|
+
* The Deployment-wide JSON-RPC handlers: Agent lifecycle (`agents.*`), config (`config.*`), models (`models.list`), secrets (`secrets.*`),
|
|
5
5
|
* `system.status`, and `logs.tail`. The Control Server handles `system.hello` and `events.*` per connection.
|
|
6
6
|
*/
|
|
7
7
|
export const createDeploymentRpc = (deployment) => ({
|
|
@@ -44,6 +44,7 @@ export const createDeploymentRpc = (deployment) => ({
|
|
|
44
44
|
}),
|
|
45
45
|
};
|
|
46
46
|
},
|
|
47
|
+
"models.list": async (params) => await deployment.listModels(params.agent),
|
|
47
48
|
"secrets.delete": async (params) => ({
|
|
48
49
|
deleted: await deployment.config.secrets.delete(params.name),
|
|
49
50
|
}),
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import { once } from "node:events";
|
|
2
2
|
import { chmod, rm } from "node:fs/promises";
|
|
3
|
-
import { createServer } from "node:http";
|
|
4
3
|
import { isIPv4 } from "node:net";
|
|
4
|
+
import { Hono } from "hono";
|
|
5
5
|
import { WebSocketServer } from "ws";
|
|
6
6
|
import { errorMessage } from "../error-message.js";
|
|
7
7
|
import { Connection } from "./connection.js";
|
|
8
|
-
import {
|
|
8
|
+
import { createHttpServer } from "./http-server.js";
|
|
9
|
+
import { mountStaticFiles } from "./static-files.js";
|
|
9
10
|
/** The WebSocket path of the JSON-RPC protocol (ADR 0005). */
|
|
10
11
|
export const WS_PATH = "/ws";
|
|
11
12
|
/** The file mode of the Unix socket: the owner only (ADR 0002). */
|
|
12
13
|
export const SOCKET_FILE_MODE = 0o600;
|
|
14
|
+
const PLAIN_TEXT = { "content-type": "text/plain; charset=utf-8" };
|
|
13
15
|
/** Hosts whose origins count as the listener's own. */
|
|
14
16
|
const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
|
|
15
17
|
/** True for a host name or address that only the local machine can reach: `localhost`, `127.0.0.0/8`, or `::1`. */
|
|
@@ -31,9 +33,11 @@ export class ControlServer {
|
|
|
31
33
|
#wss = new WebSocketServer({ noServer: true });
|
|
32
34
|
#servers = [];
|
|
33
35
|
#connections = new Map();
|
|
36
|
+
#app;
|
|
34
37
|
#port = 0;
|
|
35
38
|
constructor(options) {
|
|
36
39
|
this.#options = options;
|
|
40
|
+
this.#app = this.#createApp();
|
|
37
41
|
}
|
|
38
42
|
/** Starts to listen. Rejects if the port or the socket path is not available. */
|
|
39
43
|
static async listen(options) {
|
|
@@ -82,35 +86,29 @@ export class ControlServer {
|
|
|
82
86
|
}
|
|
83
87
|
};
|
|
84
88
|
#createHttpServer = (checkOrigin) => {
|
|
85
|
-
const server =
|
|
86
|
-
void this.#serveHttp(request, response);
|
|
87
|
-
});
|
|
89
|
+
const server = createHttpServer(this.#app.fetch, "Control Server");
|
|
88
90
|
server.on("upgrade", (request, socket, head) => {
|
|
89
91
|
this.#upgrade(request, socket, head, checkOrigin);
|
|
90
92
|
});
|
|
91
93
|
this.#servers.push(server);
|
|
92
94
|
return server;
|
|
93
95
|
};
|
|
94
|
-
#
|
|
96
|
+
#createApp = () => {
|
|
97
|
+
const app = new Hono();
|
|
95
98
|
const { staticDir } = this.#options;
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
(await serveStaticFile(staticDir, request, response))) {
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
99
|
+
if (staticDir !== undefined) {
|
|
100
|
+
mountStaticFiles(app, staticDir);
|
|
101
101
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
102
|
+
app.get("/", (c) => c.body(`Wheatley daemon. Connect with JSON-RPC over WebSocket at ${WS_PATH}.\n`, 200, PLAIN_TEXT));
|
|
103
|
+
app.notFound((c) => c.body("Not found\n", 404, PLAIN_TEXT));
|
|
104
|
+
app.onError((failure, c) => {
|
|
105
|
+
this.#options.log.warn("A Control Server HTTP request failed", {
|
|
106
|
+
error: errorMessage(failure),
|
|
107
|
+
path: c.req.path,
|
|
105
108
|
});
|
|
106
|
-
|
|
107
|
-
const status = request.method === "GET" && request.url === "/" ? 200 : 404;
|
|
108
|
-
response.writeHead(status, {
|
|
109
|
-
"content-type": "text/plain; charset=utf-8",
|
|
109
|
+
return c.body("Not found\n", 404, PLAIN_TEXT);
|
|
110
110
|
});
|
|
111
|
-
|
|
112
|
-
? `Wheatley daemon. Connect with JSON-RPC over WebSocket at ${WS_PATH}.\n`
|
|
113
|
-
: "Not found\n");
|
|
111
|
+
return app;
|
|
114
112
|
};
|
|
115
113
|
#allowedOrigin = (origin) => {
|
|
116
114
|
const own = [this.#options.host, ...LOOPBACK_HOSTS].map((host) => {
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { Server } from "node:http";
|
|
2
|
+
import { createAdaptorServer } from "@hono/node-server";
|
|
3
|
+
/**
|
|
4
|
+
* Creates a `node:http` server that answers with `fetch`. It does not listen yet. `name` names the listener in the
|
|
5
|
+
* error that a server of another HTTP version causes.
|
|
6
|
+
*/
|
|
7
|
+
export const createHttpServer = (fetch, name) => {
|
|
8
|
+
const server = createAdaptorServer({
|
|
9
|
+
fetch,
|
|
10
|
+
// The default replaces the global `Request` and `Response` for the whole process.
|
|
11
|
+
overrideGlobalObjects: false,
|
|
12
|
+
});
|
|
13
|
+
if (!(server instanceof Server)) {
|
|
14
|
+
throw new TypeError(`The ${name} listener is not an HTTP/1.1 server`);
|
|
15
|
+
}
|
|
16
|
+
return server;
|
|
17
|
+
};
|