@wheatley-ai/cli 0.0.0-stage → 0.0.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/LICENSE +15 -0
- package/bin/wheatley.js +2 -0
- package/dist/approvals/gate.js +278 -0
- package/dist/approvals/module.js +21 -0
- package/dist/approvals/policy.js +30 -0
- package/dist/approvals/preview.js +17 -0
- package/dist/approvals/prompt.js +98 -0
- package/dist/approvals/rpc.js +16 -0
- package/dist/approvals/store.js +159 -0
- package/dist/cli/ask.js +94 -0
- package/dist/cli/chat.js +180 -0
- package/dist/cli/client.js +104 -0
- package/dist/cli/daemon.js +35 -0
- package/dist/cli/init.js +72 -0
- package/dist/cli/io.js +45 -0
- package/dist/cli/main.js +204 -0
- package/dist/cli/session.js +87 -0
- package/dist/cli/status.js +46 -0
- package/dist/contracts/approval-gate.js +1 -0
- package/dist/contracts/config-store.js +1 -0
- package/dist/contracts/delivery-outbox.js +1 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/extension-catalog.js +1 -0
- package/dist/contracts/maintenance-runner.js +1 -0
- package/dist/contracts/memory-store.js +1 -0
- package/dist/contracts/module.js +7 -0
- package/dist/contracts/tool-names.js +43 -0
- package/dist/contracts/trigger-runtime.js +1 -0
- package/dist/contracts/webhook-ingress.js +2 -0
- package/dist/core/agent/agent-store.js +300 -0
- package/dist/core/agent/agent.js +1020 -0
- package/dist/core/agent/gated-models.js +89 -0
- package/dist/core/agent/pi-adapter.js +401 -0
- package/dist/core/agent/policy-gate.js +44 -0
- package/dist/core/builtin-catalog.js +20 -0
- package/dist/core/concurrency-gate.js +87 -0
- package/dist/core/config/atomic-file.js +61 -0
- package/dist/core/config/config-store.js +138 -0
- package/dist/core/config/pending-restart.js +53 -0
- package/dist/core/config/secret-references.js +69 -0
- package/dist/core/config/secret-store.js +147 -0
- package/dist/core/config/validate.js +55 -0
- package/dist/core/config/yaml-patch.js +57 -0
- package/dist/core/daemon.js +88 -0
- package/dist/core/deployment.js +347 -0
- package/dist/core/error-message.js +4 -0
- package/dist/core/events.js +25 -0
- package/dist/core/logger.js +81 -0
- package/dist/core/models.js +27 -0
- package/dist/core/module.js +42 -0
- package/dist/core/rpc/agent-handlers.js +82 -0
- package/dist/core/rpc/deployment-handlers.js +63 -0
- package/dist/core/rpc/router.js +95 -0
- package/dist/core/server/connection.js +170 -0
- package/dist/core/server/control-server.js +152 -0
- package/dist/core/server/static-files.js +79 -0
- package/dist/core/supervisor.js +206 -0
- package/dist/core/tool-routing.js +41 -0
- package/dist/dashboard/assets/index-3COz_MZq.css +2 -0
- package/dist/dashboard/assets/index-RnxedkKh.js +11 -0
- package/dist/dashboard/assets/sheet-presentation-U1UUymXc.js +1 -0
- package/dist/dashboard/index.html +13 -0
- package/dist/db/database.js +16 -0
- package/dist/db/migrations.js +184 -0
- package/dist/frontends/discord/approvals.js +199 -0
- package/dist/frontends/discord/attachments.js +115 -0
- package/dist/frontends/discord/binding.js +489 -0
- package/dist/frontends/discord/config.js +107 -0
- package/dist/frontends/discord/discord-runtime.js +52 -0
- package/dist/frontends/discord/errors.js +61 -0
- package/dist/frontends/discord/live-runs.js +189 -0
- package/dist/frontends/discord/module.js +39 -0
- package/dist/frontends/discord/recent-ids.js +20 -0
- package/dist/frontends/slack/approval-blocks.js +98 -0
- package/dist/frontends/slack/attachments.js +102 -0
- package/dist/frontends/slack/background-tasks.js +20 -0
- package/dist/frontends/slack/binding.js +405 -0
- package/dist/frontends/slack/bounded.js +9 -0
- package/dist/frontends/slack/chat-id.js +17 -0
- package/dist/frontends/slack/config.js +80 -0
- package/dist/frontends/slack/delivery-errors.js +81 -0
- package/dist/frontends/slack/inbound.js +76 -0
- package/dist/frontends/slack/live-progress.js +190 -0
- package/dist/frontends/slack/manifest.js +66 -0
- package/dist/frontends/slack/outbound.js +160 -0
- package/dist/frontends/slack/schemas.js +99 -0
- package/dist/frontends/slack/signature.js +30 -0
- package/dist/frontends/slack/slack-client.js +60 -0
- package/dist/frontends/slack/slack-frontend.js +38 -0
- package/dist/frontends/slack/state-store.js +112 -0
- package/dist/frontends/telegram/approvals.js +134 -0
- package/dist/frontends/telegram/attachments.js +126 -0
- package/dist/frontends/telegram/binding.js +144 -0
- package/dist/frontends/telegram/chat-key.js +43 -0
- package/dist/frontends/telegram/client.js +88 -0
- package/dist/frontends/telegram/config.js +93 -0
- package/dist/frontends/telegram/delivery.js +215 -0
- package/dist/frontends/telegram/frontend.js +42 -0
- package/dist/frontends/telegram/grammy-client.js +122 -0
- package/dist/frontends/telegram/http-status.js +6 -0
- package/dist/frontends/telegram/inbound.js +149 -0
- package/dist/frontends/telegram/live.js +182 -0
- package/dist/frontends/telegram/markdown.js +103 -0
- package/dist/frontends/telegram/recent-set.js +18 -0
- package/dist/frontends/telegram/serial-queue.js +23 -0
- package/dist/index.js +7 -0
- package/dist/mcp/content.js +61 -0
- package/dist/mcp/mcp-module.js +35 -0
- package/dist/mcp/mcp-tool-provider.js +93 -0
- package/dist/mcp/server-connection.js +297 -0
- package/dist/memory/consolidation.js +260 -0
- package/dist/memory/format.js +5 -0
- package/dist/memory/migrations.js +76 -0
- package/dist/memory/module.js +69 -0
- package/dist/memory/names.js +20 -0
- package/dist/memory/rows.js +22 -0
- package/dist/memory/rpc.js +49 -0
- package/dist/memory/snapshots.js +12 -0
- package/dist/memory/store.js +281 -0
- package/dist/memory/tools.js +158 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.d.ts +252 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/config.js +110 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +512 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +441 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.d.ts +8 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/duration.js +28 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.d.ts +234 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/events.js +124 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.d.ts +81 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json-rpc.js +157 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.d.ts +14 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/json.js +23 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.d.ts +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/limits.js +17 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +1107 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +201 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.d.ts +45 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/rpc-error.js +44 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.d.ts +20 -0
- package/dist/node_modules/@wheatley-ai/protocol/dist/validation.js +11 -0
- package/dist/node_modules/@wheatley-ai/protocol/package.json +14 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.d.ts +11 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/chunk.js +162 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +39 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.d.ts +29 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/delivery-error.js +27 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +236 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +10 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/index.js +7 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.d.ts +9 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/json.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.d.ts +18 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/logger.js +2 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.d.ts +48 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/plugin.js +5 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/schema.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.d.ts +69 -0
- package/dist/node_modules/@wheatley-ai/sdk/dist/tool.js +3 -0
- package/dist/node_modules/@wheatley-ai/sdk/package.json +11 -0
- package/dist/ops/backup.js +185 -0
- package/dist/ops/cli.js +195 -0
- package/dist/ops/command-runner.js +34 -0
- package/dist/ops/dashboard-assets.js +37 -0
- package/dist/ops/migrate.js +63 -0
- package/dist/ops/module.js +47 -0
- package/dist/ops/paths.js +55 -0
- package/dist/ops/service.js +376 -0
- package/dist/ops/update.js +145 -0
- package/dist/plugins/contributions.js +89 -0
- package/dist/plugins/guards.js +111 -0
- package/dist/plugins/load.js +76 -0
- package/dist/plugins/module.js +31 -0
- package/dist/plugins/provider.js +349 -0
- package/dist/plugins/schema.js +69 -0
- package/dist/skills/disclosure.js +142 -0
- package/dist/skills/discovery.js +120 -0
- package/dist/skills/fs-errors.js +8 -0
- package/dist/skills/read-skill-tool.js +3 -0
- package/dist/skills/skill-file.js +90 -0
- package/dist/skills/skills.js +140 -0
- package/dist/tools/builtin-tools.js +61 -0
- package/dist/tools/input.js +45 -0
- package/dist/tools/paths.js +6 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/shell.js +156 -0
- package/dist/tools/write-file.js +58 -0
- package/dist/triggers/delivery-codec.js +99 -0
- package/dist/triggers/delivery-outbox.js +313 -0
- package/dist/triggers/due-timer.js +14 -0
- package/dist/triggers/errors.js +2 -0
- package/dist/triggers/migrations.js +91 -0
- package/dist/triggers/module.js +104 -0
- package/dist/triggers/rpc.js +35 -0
- package/dist/triggers/schedule.js +52 -0
- package/dist/triggers/sql-row.js +59 -0
- package/dist/triggers/trigger-runtime.js +445 -0
- package/dist/triggers/trigger-tools.js +207 -0
- package/dist/triggers/webhook-ingress.js +216 -0
- package/dist/wiring/agent-services.js +144 -0
- package/dist/wiring/catalog.js +81 -0
- package/dist/wiring/daemon.js +83 -0
- package/dist/wiring/frontend-host.js +268 -0
- package/package.json +50 -3
- package/README.md +0 -3
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { SerialQueue } from "./serial-queue.js";
|
|
2
|
+
/** Telegram shows a typing indicator for about five seconds, so the Frontend repeats it before then. */
|
|
3
|
+
const TYPING_REPEAT_MS = 4000;
|
|
4
|
+
/** How long a finished Run keeps its draft for the final `message` delivery. */
|
|
5
|
+
const DRAFT_RETENTION_MS = 600_000;
|
|
6
|
+
/** The Bot API limit for the text of one message. */
|
|
7
|
+
const MAX_DRAFT_LENGTH = 4096;
|
|
8
|
+
const ELLIPSIS = "…";
|
|
9
|
+
const draftText = (text) => text.length <= MAX_DRAFT_LENGTH
|
|
10
|
+
? text
|
|
11
|
+
: `${text.slice(0, MAX_DRAFT_LENGTH - ELLIPSIS.length)}${ELLIPSIS}`;
|
|
12
|
+
const clearTimers = (state) => {
|
|
13
|
+
clearInterval(state.typing);
|
|
14
|
+
clearTimeout(state.flush);
|
|
15
|
+
clearTimeout(state.expiry);
|
|
16
|
+
state.typing = undefined;
|
|
17
|
+
state.flush = undefined;
|
|
18
|
+
state.expiry = undefined;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Shows live Run progress in Telegram: a repeated typing indicator between `run_started` and `run_finished`, and in
|
|
22
|
+
* `draft` mode a plain-text draft message that receives at most one edit per `draftIntervalMs` (ADR 0012).
|
|
23
|
+
*
|
|
24
|
+
* Invariants: draft API calls of one Run run in order, one at a time. API failures are logged and never reach the
|
|
25
|
+
* caller, because `FrontendBinding.onEvent` must not throw.
|
|
26
|
+
*/
|
|
27
|
+
export class LiveRuns {
|
|
28
|
+
#client;
|
|
29
|
+
#log;
|
|
30
|
+
#options;
|
|
31
|
+
#runs = new Map();
|
|
32
|
+
constructor(client, log, options) {
|
|
33
|
+
this.#client = client;
|
|
34
|
+
this.#log = log;
|
|
35
|
+
this.#options = options;
|
|
36
|
+
}
|
|
37
|
+
/** Applies one Run event for a Chat at `target`. Never throws. */
|
|
38
|
+
onEvent = (event, target) => {
|
|
39
|
+
switch (event.kind) {
|
|
40
|
+
case "run_started": {
|
|
41
|
+
this.#stateOf(event.runId, target);
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
case "text_delta": {
|
|
45
|
+
const state = this.#stateOf(event.runId, target);
|
|
46
|
+
state.text += event.delta;
|
|
47
|
+
if (this.#options.streaming === "draft") {
|
|
48
|
+
this.#scheduleFlush(state);
|
|
49
|
+
}
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
case "run_finished": {
|
|
53
|
+
this.#finish(event.runId);
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
case "tool_started":
|
|
57
|
+
case "tool_finished": {
|
|
58
|
+
// Tool progress shows no extra output: the typing indicator already runs.
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
default: {
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Ends live output of a Run and returns its draft message, if one was sent. Waits for draft calls in flight, so the
|
|
68
|
+
* caller can edit the draft without a race. Returns `undefined` for an unknown Run.
|
|
69
|
+
*/
|
|
70
|
+
takeDraft = async (runId) => {
|
|
71
|
+
const state = this.#runs.get(runId);
|
|
72
|
+
if (state === undefined) {
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
state.closed = true;
|
|
76
|
+
clearTimers(state);
|
|
77
|
+
this.#runs.delete(runId);
|
|
78
|
+
await state.calls.idle();
|
|
79
|
+
return state.messageId === undefined
|
|
80
|
+
? undefined
|
|
81
|
+
: { messageId: state.messageId, target: state.target };
|
|
82
|
+
};
|
|
83
|
+
/** Stops every timer. Later events still work, so `stop` is safe to call before the last event. */
|
|
84
|
+
stop = () => {
|
|
85
|
+
for (const state of this.#runs.values()) {
|
|
86
|
+
state.closed = true;
|
|
87
|
+
clearTimers(state);
|
|
88
|
+
}
|
|
89
|
+
this.#runs.clear();
|
|
90
|
+
};
|
|
91
|
+
#stateOf = (runId, target) => {
|
|
92
|
+
const existing = this.#runs.get(runId);
|
|
93
|
+
if (existing !== undefined) {
|
|
94
|
+
return existing;
|
|
95
|
+
}
|
|
96
|
+
const state = {
|
|
97
|
+
calls: new SerialQueue(),
|
|
98
|
+
closed: false,
|
|
99
|
+
expiry: undefined,
|
|
100
|
+
flush: undefined,
|
|
101
|
+
lastFlushAt: undefined,
|
|
102
|
+
messageId: undefined,
|
|
103
|
+
shown: "",
|
|
104
|
+
target,
|
|
105
|
+
text: "",
|
|
106
|
+
typing: undefined,
|
|
107
|
+
};
|
|
108
|
+
this.#runs.set(runId, state);
|
|
109
|
+
void this.#sendTyping(state);
|
|
110
|
+
state.typing = setInterval(() => {
|
|
111
|
+
void this.#sendTyping(state);
|
|
112
|
+
}, TYPING_REPEAT_MS);
|
|
113
|
+
return state;
|
|
114
|
+
};
|
|
115
|
+
#sendTyping = async (state) => {
|
|
116
|
+
try {
|
|
117
|
+
await this.#client.sendTyping(state.target);
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
this.#log.debug("Telegram typing indicator failed", {
|
|
121
|
+
error: String(error),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
#finish = (runId) => {
|
|
126
|
+
const state = this.#runs.get(runId);
|
|
127
|
+
if (state === undefined) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
clearInterval(state.typing);
|
|
131
|
+
state.typing = undefined;
|
|
132
|
+
if (state.expiry === undefined) {
|
|
133
|
+
// A failed or stopped Run can end without a final `message` delivery that takes the draft.
|
|
134
|
+
state.expiry = setTimeout(() => {
|
|
135
|
+
if (this.#runs.get(runId) === state) {
|
|
136
|
+
state.closed = true;
|
|
137
|
+
clearTimers(state);
|
|
138
|
+
this.#runs.delete(runId);
|
|
139
|
+
}
|
|
140
|
+
}, DRAFT_RETENTION_MS);
|
|
141
|
+
state.expiry.unref();
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
#scheduleFlush = (state) => {
|
|
145
|
+
if (state.flush !== undefined || state.closed) {
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const interval = this.#options.draftIntervalMs;
|
|
149
|
+
const wait = state.lastFlushAt === undefined
|
|
150
|
+
? interval
|
|
151
|
+
: Math.max(0, state.lastFlushAt + interval - Date.now());
|
|
152
|
+
state.flush = setTimeout(() => {
|
|
153
|
+
state.flush = undefined;
|
|
154
|
+
// `#flush` never rejects.
|
|
155
|
+
void state.calls.run(async () => {
|
|
156
|
+
await this.#flush(state);
|
|
157
|
+
});
|
|
158
|
+
}, wait);
|
|
159
|
+
};
|
|
160
|
+
#flush = async (state) => {
|
|
161
|
+
if (state.closed) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const text = draftText(state.text);
|
|
165
|
+
state.lastFlushAt = Date.now();
|
|
166
|
+
try {
|
|
167
|
+
if (state.messageId === undefined) {
|
|
168
|
+
state.messageId = await this.#client.sendMessage(state.target, text);
|
|
169
|
+
}
|
|
170
|
+
else if (text !== state.shown) {
|
|
171
|
+
await this.#client.editMessageText(state.target.chatId, state.messageId, text);
|
|
172
|
+
}
|
|
173
|
+
state.shown = text;
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
this.#log.debug("Telegram draft update failed", { error: String(error) });
|
|
177
|
+
}
|
|
178
|
+
if (draftText(state.text) !== state.shown) {
|
|
179
|
+
this.#scheduleFlush(state);
|
|
180
|
+
}
|
|
181
|
+
};
|
|
182
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Converts the Markdown of Agent replies to the HTML subset of the Telegram Bot API (`parse_mode: "HTML"`). Telegram
|
|
3
|
+
* rejects unbalanced tags, so the converter only emits tags in matched pairs and escapes all other text.
|
|
4
|
+
*/
|
|
5
|
+
const FENCE_OPEN = /^ {0,3}(?<marker>`{3,}|~{3,})\s*(?<info>[^\s`]*)/u;
|
|
6
|
+
const HEADING = /^ {0,3}#{1,6}\s+(?<text>.*?)\s*#*\s*$/u;
|
|
7
|
+
const QUOTE = /^ {0,3}>\s?(?<text>.*)$/u;
|
|
8
|
+
const BULLET = /^(?<indent>\s*)[-*+]\s+(?<text>.*)$/u;
|
|
9
|
+
const INLINE_CODE = /(?<ticks>`+)(?<code>.+?)\k<ticks>/gu;
|
|
10
|
+
const LINK = /\[(?<label>[^\]]+)\]\((?<url>(?:https?|tg|mailto):[^)\s]+)\)/gu;
|
|
11
|
+
const BOLD = /(?:\*\*|__)(?=\S)(?<text>.+?)(?<=\S)(?:\*\*|__)/gu;
|
|
12
|
+
const ITALIC_STAR = /(?<![\w*])\*(?=\S)(?<text>[^*]+?)(?<=\S)\*(?![\w*])/gu;
|
|
13
|
+
const ITALIC_UNDERSCORE = /(?<![\w_])_(?=\S)(?<text>[^_]+?)(?<=\S)_(?![\w_])/gu;
|
|
14
|
+
const STRIKE = /~~(?=\S)(?<text>.+?)(?<=\S)~~/gu;
|
|
15
|
+
const PLACEHOLDER = /\uE000(?<index>\d+)\uE001/gu;
|
|
16
|
+
/** Escapes the three characters that Telegram HTML requires escaped, plus `"` for attribute values. */
|
|
17
|
+
export const escapeHtml = (text) => text
|
|
18
|
+
.replaceAll("&", "&")
|
|
19
|
+
.replaceAll("<", "<")
|
|
20
|
+
.replaceAll(">", ">")
|
|
21
|
+
.replaceAll('"', """);
|
|
22
|
+
/** Formats the inline Markdown of one line. Code spans and links become placeholders so later rules skip them. */
|
|
23
|
+
const formatInline = (line) => {
|
|
24
|
+
const protectedParts = [];
|
|
25
|
+
const protect = (html) => {
|
|
26
|
+
protectedParts.push(html);
|
|
27
|
+
return `\uE000${protectedParts.length - 1}\uE001`;
|
|
28
|
+
};
|
|
29
|
+
let text = line.replaceAll(INLINE_CODE, (_match, _ticks, code) => protect(`<code>${escapeHtml(code)}</code>`));
|
|
30
|
+
text = text.replaceAll(LINK, (_match, label, url) => protect(`<a href="${escapeHtml(url)}">${escapeHtml(label)}</a>`));
|
|
31
|
+
text = escapeHtml(text)
|
|
32
|
+
.replaceAll(BOLD, "<b>$<text></b>")
|
|
33
|
+
.replaceAll(STRIKE, "<s>$<text></s>")
|
|
34
|
+
.replaceAll(ITALIC_STAR, "<i>$<text></i>")
|
|
35
|
+
.replaceAll(ITALIC_UNDERSCORE, "<i>$<text></i>");
|
|
36
|
+
return text.replaceAll(PLACEHOLDER, (_match, index) => protectedParts[Number(index)] ?? "");
|
|
37
|
+
};
|
|
38
|
+
const formatLine = (line) => {
|
|
39
|
+
const heading = HEADING.exec(line)?.groups?.text;
|
|
40
|
+
if (heading !== undefined) {
|
|
41
|
+
return `<b>${formatInline(heading)}</b>`;
|
|
42
|
+
}
|
|
43
|
+
const bullet = BULLET.exec(line)?.groups;
|
|
44
|
+
if (bullet?.text !== undefined) {
|
|
45
|
+
return `${bullet.indent ?? ""}• ${formatInline(bullet.text)}`;
|
|
46
|
+
}
|
|
47
|
+
return formatInline(line);
|
|
48
|
+
};
|
|
49
|
+
const isFenceClose = (line, marker) => {
|
|
50
|
+
const trimmed = line.trim();
|
|
51
|
+
return (trimmed.length >= marker.length &&
|
|
52
|
+
trimmed.replaceAll(marker.charAt(0), "") === "");
|
|
53
|
+
};
|
|
54
|
+
const codeBlock = (info, lines) => {
|
|
55
|
+
const language = info === "" ? "" : ` class="language-${escapeHtml(info)}"`;
|
|
56
|
+
return `<pre><code${language}>${escapeHtml(lines.join("\n"))}</code></pre>`;
|
|
57
|
+
};
|
|
58
|
+
/**
|
|
59
|
+
* Converts Markdown to Telegram HTML.
|
|
60
|
+
*
|
|
61
|
+
* Supports fenced code blocks, inline code, links, bold, italic, strikethrough, headings (as bold), bullet lists, and
|
|
62
|
+
* block quotes. Leaves other Markdown as escaped text. The visible text is never longer than the Markdown input, so a
|
|
63
|
+
* chunk that fits the 4096-character limit as Markdown also fits as HTML.
|
|
64
|
+
*/
|
|
65
|
+
export const markdownToTelegramHtml = (markdown) => {
|
|
66
|
+
const lines = markdown.split("\n");
|
|
67
|
+
const output = [];
|
|
68
|
+
let quote = [];
|
|
69
|
+
let index = 0;
|
|
70
|
+
const endQuote = () => {
|
|
71
|
+
if (quote.length > 0) {
|
|
72
|
+
output.push(`<blockquote>${quote.join("\n")}</blockquote>`);
|
|
73
|
+
quote = [];
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
while (index < lines.length) {
|
|
77
|
+
const line = lines[index] ?? "";
|
|
78
|
+
const fence = FENCE_OPEN.exec(line)?.groups;
|
|
79
|
+
index += 1;
|
|
80
|
+
if (fence?.marker !== undefined) {
|
|
81
|
+
endQuote();
|
|
82
|
+
const body = [];
|
|
83
|
+
while (index < lines.length &&
|
|
84
|
+
!isFenceClose(lines[index] ?? "", fence.marker)) {
|
|
85
|
+
body.push(lines[index] ?? "");
|
|
86
|
+
index += 1;
|
|
87
|
+
}
|
|
88
|
+
index += 1;
|
|
89
|
+
output.push(codeBlock(fence.info ?? "", body));
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
const quoted = QUOTE.exec(line)?.groups?.text;
|
|
93
|
+
if (quoted === undefined) {
|
|
94
|
+
endQuote();
|
|
95
|
+
output.push(formatLine(line));
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
quote.push(formatLine(quoted));
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
endQuote();
|
|
102
|
+
return output.join("\n");
|
|
103
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** A set that forgets its oldest entries beyond `capacity`. */
|
|
2
|
+
export class RecentSet {
|
|
3
|
+
#items = new Set();
|
|
4
|
+
#capacity;
|
|
5
|
+
constructor(capacity) {
|
|
6
|
+
this.#capacity = capacity;
|
|
7
|
+
}
|
|
8
|
+
has = (item) => this.#items.has(item);
|
|
9
|
+
add = (item) => {
|
|
10
|
+
this.#items.add(item);
|
|
11
|
+
for (const oldest of this.#items) {
|
|
12
|
+
if (this.#items.size <= this.#capacity) {
|
|
13
|
+
break;
|
|
14
|
+
}
|
|
15
|
+
this.#items.delete(oldest);
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs async tasks one at a time, in the order of `run` calls.
|
|
3
|
+
*
|
|
4
|
+
* Invariant: a task starts only after every earlier task settles. A rejected task rejects only for its own caller and
|
|
5
|
+
* does not stop later tasks.
|
|
6
|
+
*/
|
|
7
|
+
export class SerialQueue {
|
|
8
|
+
#tail = Promise.resolve();
|
|
9
|
+
/** Queues `task` and resolves or rejects with its result. */
|
|
10
|
+
run = async (task) => {
|
|
11
|
+
const previous = this.#tail;
|
|
12
|
+
const current = (async () => {
|
|
13
|
+
await Promise.allSettled([previous]);
|
|
14
|
+
return await task();
|
|
15
|
+
})();
|
|
16
|
+
this.#tail = current;
|
|
17
|
+
return await current;
|
|
18
|
+
};
|
|
19
|
+
/** Resolves after every task queued so far settles. Never rejects. */
|
|
20
|
+
idle = async () => {
|
|
21
|
+
await Promise.allSettled([this.#tail]);
|
|
22
|
+
};
|
|
23
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The `wheatley` executable: `bin/wheatley.js` imports the compiled form of this file.
|
|
2
|
+
import { processIo } from "./cli/io.js";
|
|
3
|
+
import { runCli } from "./cli/main.js";
|
|
4
|
+
const io = processIo();
|
|
5
|
+
process.exitCode = await runCli(process.argv.slice(2), io);
|
|
6
|
+
// Standard input keeps the event loop alive after a command that reads no input, so the CLI exits explicitly.
|
|
7
|
+
process.exit();
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** A Tool result that reports `text` to the model as an error. */
|
|
2
|
+
export const errorResult = (text) => ({
|
|
3
|
+
content: [{ text, type: "text" }],
|
|
4
|
+
isError: true,
|
|
5
|
+
});
|
|
6
|
+
const base64Bytes = (data) => Buffer.byteLength(data, "base64");
|
|
7
|
+
/** Converts one MCP content block. `text` and `image` pass through, and every other block becomes `text`. */
|
|
8
|
+
const toToolContent = (block) => {
|
|
9
|
+
switch (block.type) {
|
|
10
|
+
case "text": {
|
|
11
|
+
return { text: block.text, type: "text" };
|
|
12
|
+
}
|
|
13
|
+
case "image": {
|
|
14
|
+
return { data: block.data, mimeType: block.mimeType, type: "image" };
|
|
15
|
+
}
|
|
16
|
+
case "audio": {
|
|
17
|
+
return {
|
|
18
|
+
text: `[audio ${block.mimeType}, ${base64Bytes(block.data)} bytes]`,
|
|
19
|
+
type: "text",
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
case "resource_link": {
|
|
23
|
+
const mimeType = block.mimeType === undefined ? "" : ` (${block.mimeType})`;
|
|
24
|
+
return {
|
|
25
|
+
text: `[resource link ${block.name}: ${block.uri}${mimeType}]`,
|
|
26
|
+
type: "text",
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
case "resource": {
|
|
30
|
+
const { resource } = block;
|
|
31
|
+
if ("text" in resource) {
|
|
32
|
+
return { text: resource.text, type: "text" };
|
|
33
|
+
}
|
|
34
|
+
const mimeType = resource.mimeType === undefined ? "" : ` ${resource.mimeType}`;
|
|
35
|
+
return {
|
|
36
|
+
text: `[resource ${resource.uri}${mimeType}, ${base64Bytes(resource.blob)} bytes]`,
|
|
37
|
+
type: "text",
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
default: {
|
|
41
|
+
return { text: JSON.stringify(block), type: "text" };
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Converts an MCP `CallToolResult` into a Tool result for the model.
|
|
47
|
+
*
|
|
48
|
+
* `structuredContent` becomes a JSON `text` block only if `content` has no `text` block. The MCP specification asks
|
|
49
|
+
* servers to repeat structured output as text, so this rule prevents a second copy.
|
|
50
|
+
*/
|
|
51
|
+
export const toToolResult = (result) => {
|
|
52
|
+
const content = result.content.map((block) => toToolContent(block));
|
|
53
|
+
const hasText = content.some((block) => block.type === "text");
|
|
54
|
+
if (result.structuredContent !== undefined && !hasText) {
|
|
55
|
+
content.push({
|
|
56
|
+
text: JSON.stringify(result.structuredContent),
|
|
57
|
+
type: "text",
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
return result.isError === true ? { content, isError: true } : { content };
|
|
61
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { McpToolProvider } from "./mcp-tool-provider.js";
|
|
2
|
+
/** The MCP module stores nothing in `agent.sqlite`. */
|
|
3
|
+
export const mcpMigrations = [];
|
|
4
|
+
/** The MCP module handles no JSON-RPC method. `extensions.list` reads its status through `ToolProvider.health`. */
|
|
5
|
+
export const mcpRpcHandlers = {};
|
|
6
|
+
/**
|
|
7
|
+
* The MCP Server client manager of one Agent (ADR 0006). Its API is the MCP `ToolProvider`.
|
|
8
|
+
*
|
|
9
|
+
* `start` connects every enabled server and resolves after each one is `ready` or `failed`. It never rejects, so one
|
|
10
|
+
* broken server never stops the Agent. `stop` aborts open connects, closes every client, and ends stdio processes.
|
|
11
|
+
*/
|
|
12
|
+
export const mcpModule = {
|
|
13
|
+
create: (ctx, deps) => {
|
|
14
|
+
const provider = new McpToolProvider({
|
|
15
|
+
agentDir: ctx.agentDir,
|
|
16
|
+
agentName: ctx.agentName,
|
|
17
|
+
config: deps.config,
|
|
18
|
+
log: ctx.log,
|
|
19
|
+
secrets: deps.secrets,
|
|
20
|
+
}, deps.timeouts);
|
|
21
|
+
return {
|
|
22
|
+
api: provider,
|
|
23
|
+
rpc: mcpRpcHandlers,
|
|
24
|
+
start: async () => {
|
|
25
|
+
await provider.connect();
|
|
26
|
+
},
|
|
27
|
+
stop: async () => {
|
|
28
|
+
await provider.close();
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
},
|
|
32
|
+
migrations: mcpMigrations,
|
|
33
|
+
name: "mcp",
|
|
34
|
+
scope: "agent",
|
|
35
|
+
};
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { errorResult } from "./content.js";
|
|
2
|
+
import { McpServerConnection } from "./server-connection.js";
|
|
3
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 30_000;
|
|
4
|
+
const DEFAULT_CALL_TIMEOUT_MS = 3_600_000;
|
|
5
|
+
/** The default MCP time limits. */
|
|
6
|
+
export const DEFAULT_MCP_TIMEOUTS = {
|
|
7
|
+
callMs: DEFAULT_CALL_TIMEOUT_MS,
|
|
8
|
+
connectMs: DEFAULT_CONNECT_TIMEOUT_MS,
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* The `ToolProvider` of the MCP Servers of one Agent (ADR 0006).
|
|
12
|
+
*
|
|
13
|
+
* It offers each Tool as `mcp:<server>:<tool>` with the default action `ask`, so the Permission Policy governs every
|
|
14
|
+
* call. A server that fails to connect, or that disconnects later, contributes no Tools and reports `failed` in
|
|
15
|
+
* `health`. The other servers keep working.
|
|
16
|
+
*/
|
|
17
|
+
export class McpToolProvider {
|
|
18
|
+
#connections;
|
|
19
|
+
#stop = new AbortController();
|
|
20
|
+
#connecting;
|
|
21
|
+
#closing;
|
|
22
|
+
constructor(input, timeouts = DEFAULT_MCP_TIMEOUTS) {
|
|
23
|
+
this.#connections = Object.entries(input.config.mcpServers ?? {}).map(([name, config]) => new McpServerConnection({
|
|
24
|
+
agentDir: input.agentDir,
|
|
25
|
+
config,
|
|
26
|
+
log: input.log,
|
|
27
|
+
name,
|
|
28
|
+
secrets: input.secrets,
|
|
29
|
+
timeouts,
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Connects every enabled MCP Server in parallel.
|
|
34
|
+
*
|
|
35
|
+
* Resolves after each server is `ready` or `failed`. Never rejects. Later calls return the first call's promise.
|
|
36
|
+
* `signal`, or a `close` call, aborts the connects that are still open, and those servers fail.
|
|
37
|
+
*/
|
|
38
|
+
connect = async (signal) => {
|
|
39
|
+
this.#connecting ??= this.#connectAll(signal);
|
|
40
|
+
await this.#connecting;
|
|
41
|
+
};
|
|
42
|
+
/** The Tools of every `ready` server. A `failed`, `stopped`, or `disabled` server contributes none. */
|
|
43
|
+
tools = () => this.#connections.flatMap((connection) => connection.tools());
|
|
44
|
+
/**
|
|
45
|
+
* Runs a Tool on the server that owns `name`, with the semantics of `ToolProvider.execute`.
|
|
46
|
+
*
|
|
47
|
+
* Resolves `{ isError: true }` with `Unknown Tool` if no server owns `name`. Never rejects.
|
|
48
|
+
*/
|
|
49
|
+
execute = async (name, input, ctx) => {
|
|
50
|
+
const connection = this.#connections.find((candidate) => candidate.owns(name));
|
|
51
|
+
if (connection === undefined) {
|
|
52
|
+
return errorResult(`Unknown Tool: ${name}`);
|
|
53
|
+
}
|
|
54
|
+
return await connection.execute(name, input, ctx.signal);
|
|
55
|
+
};
|
|
56
|
+
/** One status per configured MCP Server, in config order, disabled servers included. */
|
|
57
|
+
health = () => this.#connections.map((connection) => connection.status());
|
|
58
|
+
/**
|
|
59
|
+
* Aborts open connects, waits for them to settle, then closes every connection. Stdio server processes end.
|
|
60
|
+
*
|
|
61
|
+
* Every server reports `stopped`, except a disabled one. Never rejects. Later calls return the first call's promise.
|
|
62
|
+
*/
|
|
63
|
+
close = async () => {
|
|
64
|
+
this.#closing ??= this.#closeAll();
|
|
65
|
+
await this.#closing;
|
|
66
|
+
};
|
|
67
|
+
#connectAll = async (signal) => {
|
|
68
|
+
const combined = signal === undefined
|
|
69
|
+
? this.#stop.signal
|
|
70
|
+
: AbortSignal.any([signal, this.#stop.signal]);
|
|
71
|
+
await Promise.all(this.#connections.map(async (connection) => {
|
|
72
|
+
await connection.connect(combined);
|
|
73
|
+
}));
|
|
74
|
+
};
|
|
75
|
+
#closeAll = async () => {
|
|
76
|
+
this.#stop.abort(new Error("MCP provider closed"));
|
|
77
|
+
await this.#connecting;
|
|
78
|
+
await Promise.all(this.#connections.map(async (connection) => {
|
|
79
|
+
await connection.close();
|
|
80
|
+
}));
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Creates the MCP `ToolProvider` of one Agent for the `ExtensionCatalog` and connects its servers.
|
|
85
|
+
*
|
|
86
|
+
* Resolves after every enabled server is `ready` or `failed`. Never rejects because of one MCP Server.
|
|
87
|
+
* `input.signal` aborts the connects that are still open.
|
|
88
|
+
*/
|
|
89
|
+
export const createMcpToolProvider = async (input, timeouts = DEFAULT_MCP_TIMEOUTS) => {
|
|
90
|
+
const provider = new McpToolProvider(input, timeouts);
|
|
91
|
+
await provider.connect(input.signal);
|
|
92
|
+
return provider;
|
|
93
|
+
};
|