@wheatley-ai/cli 0.2.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.
Files changed (67) hide show
  1. package/README.md +37 -3
  2. package/dist/cli/ask.js +8 -4
  3. package/dist/cli/chat.js +8 -4
  4. package/dist/cli/daemon.js +45 -0
  5. package/dist/cli/io.js +1 -0
  6. package/dist/cli/main.js +145 -157
  7. package/dist/cli/session.js +59 -3
  8. package/dist/cli/status.js +4 -4
  9. package/dist/cli/tui/app.js +14 -2
  10. package/dist/cli/tui/controller.js +80 -19
  11. package/dist/cli/tui/markdown.js +229 -104
  12. package/dist/cli/tui/model-picker.js +76 -0
  13. package/dist/cli/tui/picker-panel.js +39 -0
  14. package/dist/core/agent/agent.js +23 -12
  15. package/dist/core/config/config-store.js +11 -6
  16. package/dist/core/config/diagnostics.js +116 -0
  17. package/dist/core/config/secret-store.js +13 -9
  18. package/dist/core/deployment.js +19 -1
  19. package/dist/core/markdown-tokens.js +60 -0
  20. package/dist/core/model-catalog.js +54 -0
  21. package/dist/core/rpc/deployment-handlers.js +2 -1
  22. package/dist/core/server/control-server.js +19 -21
  23. package/dist/core/server/http-server.js +17 -0
  24. package/dist/core/server/static-files.js +40 -66
  25. package/dist/dashboard/assets/index-DGa2Ps9u.js +12 -0
  26. package/dist/dashboard/assets/index-DeERxJOJ.css +2 -0
  27. package/dist/dashboard/assets/{sheet-presentation-DMljN0LW.js → sheet-presentation-CZ1dO2kr.js} +1 -1
  28. package/dist/dashboard/index.html +2 -2
  29. package/dist/frontends/discord/approvals.js +8 -43
  30. package/dist/frontends/discord/binding.js +81 -8
  31. package/dist/frontends/discord/json-file.js +57 -0
  32. package/dist/frontends/discord/model-picker.js +276 -0
  33. package/dist/frontends/slack/binding.js +33 -3
  34. package/dist/frontends/slack/inbound.js +21 -12
  35. package/dist/frontends/slack/model-picker-blocks.js +147 -0
  36. package/dist/frontends/slack/outbound.js +27 -2
  37. package/dist/frontends/slack/schemas.js +9 -2
  38. package/dist/frontends/telegram/approvals.js +13 -48
  39. package/dist/frontends/telegram/binding.js +5 -0
  40. package/dist/frontends/telegram/client.js +7 -0
  41. package/dist/frontends/telegram/delivery.js +19 -6
  42. package/dist/frontends/telegram/inbound.js +64 -8
  43. package/dist/frontends/telegram/markdown.js +120 -83
  44. package/dist/frontends/telegram/model-picker.js +160 -0
  45. package/dist/frontends/telegram/token-store.js +73 -0
  46. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.d.ts +13 -0
  47. package/dist/node_modules/@wheatley-ai/protocol/dist/domain.js +11 -0
  48. package/dist/node_modules/@wheatley-ai/protocol/dist/index.d.ts +1 -1
  49. package/dist/node_modules/@wheatley-ai/protocol/dist/index.js +1 -1
  50. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.d.ts +20 -0
  51. package/dist/node_modules/@wheatley-ai/protocol/dist/methods.js +9 -1
  52. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.d.ts +2 -2
  53. package/dist/node_modules/@wheatley-ai/sdk/dist/commands.js +2 -2
  54. package/dist/node_modules/@wheatley-ai/sdk/dist/frontend.d.ts +23 -0
  55. package/dist/node_modules/@wheatley-ai/sdk/dist/index.d.ts +1 -1
  56. package/dist/node_modules/@wheatley-ai/sdk/package.json +1 -1
  57. package/dist/ops/cli.js +127 -114
  58. package/dist/ops/command-runner.js +1 -0
  59. package/dist/ops/install-method.js +189 -0
  60. package/dist/ops/registry.js +35 -0
  61. package/dist/ops/service.js +6 -1
  62. package/dist/ops/update.js +109 -88
  63. package/dist/triggers/delivery-codec.js +13 -0
  64. package/dist/triggers/webhook-ingress.js +89 -82
  65. package/package.json +11 -4
  66. package/dist/dashboard/assets/index-C9Rul5vE.css +0 -2
  67. package/dist/dashboard/assets/index-DXzGGAxQ.js +0 -11
@@ -1,36 +1,25 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
+ import semver from "semver";
3
4
  import { Type } from "typebox";
4
5
  import { Value } from "typebox/value";
5
6
  import { describeFailure } from "./command-runner.js";
6
- import { isDocker } from "./paths.js";
7
- /** The npm package name of the daemon and CLI. */
8
- export const PACKAGE_NAME = "@wheatley-ai/cli";
7
+ import { fetchPublishedVersions, PACKAGE_NAME } from "./registry.js";
9
8
  /** The commands that update a Docker Compose Deployment. Run them in the folder of `docker-compose.yml`. */
10
9
  export const DOCKER_UPDATE_COMMANDS = [
11
10
  "docker compose pull",
12
11
  "docker compose up -d",
13
12
  ];
14
- const VERSION = /^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?<prerelease>-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u;
15
- const parseVersion = (text) => {
16
- const groups = VERSION.exec(text)?.groups;
17
- if (groups === undefined) {
18
- return undefined;
19
- }
20
- return {
21
- major: Number(groups.major),
22
- minor: Number(groups.minor),
23
- patch: Number(groups.patch),
24
- prerelease: groups.prerelease !== undefined,
25
- text,
26
- };
27
- };
28
- /** Orders by major, minor, and patch. A release sorts after a prerelease of the same numbers. */
29
- const compareVersions = (a, b) => a.major - b.major ||
30
- a.minor - b.minor ||
31
- a.patch - b.patch ||
32
- Number(b.prerelease) - Number(a.prerelease);
33
- const newest = (versions) => versions.toSorted(compareVersions).at(-1);
13
+ /** The `curl` installer. Run again with `--version`, it replaces the app in its XDG folder. */
14
+ export const INSTALLER_URL = "https://raw.githubusercontent.com/SphericalKat/wheatley/main/scripts/install.sh";
15
+ const BUILD_METADATA = /\+.*$/u;
16
+ /**
17
+ * Accepts only canonical semantic versions. `semver.valid` also accepts a `v` prefix and white space, and drops build
18
+ * metadata from its result, so the text without build metadata must equal the normalized version.
19
+ */
20
+ const isVersion = (text) => semver.valid(text) === text.replace(BUILD_METADATA, "");
21
+ const isStable = (text) => semver.prerelease(text) === null;
22
+ const newest = (versions) => versions.toSorted(semver.rcompare).at(0);
34
23
  /**
35
24
  * Applies the major-version guard: picks the newest stable release with the same major version as `current` that is
36
25
  * newer than `current`. It ignores prereleases and text that is not a version.
@@ -38,100 +27,107 @@ const newest = (versions) => versions.toSorted(compareVersions).at(-1);
38
27
  * Errors: throws if `current` is not a semantic version.
39
28
  */
40
29
  export const selectUpdate = (current, available) => {
41
- const installed = parseVersion(current);
42
- if (installed === undefined) {
30
+ if (!isVersion(current)) {
43
31
  throw new Error(`The installed version is not a semantic version: ${current}`);
44
32
  }
45
- const releases = available
46
- .flatMap((text) => parseVersion(text) ?? [])
47
- .filter((version) => !version.prerelease && compareVersions(version, installed) > 0);
33
+ const installedMajor = semver.major(current);
34
+ const releases = available.filter((text) => isVersion(text) && isStable(text) && semver.gt(text, current));
48
35
  return {
49
- newerMajor: newest(releases.filter((version) => version.major > installed.major))?.text,
50
- target: newest(releases.filter((version) => version.major === installed.major))?.text,
36
+ newerMajor: newest(releases.filter((text) => semver.major(text) > installedMajor)),
37
+ target: newest(releases.filter((text) => semver.major(text) === installedMajor)),
51
38
  };
52
39
  };
53
- const segment = (...names) => `${path.sep}${names.join(path.sep)}${path.sep}`;
40
+ const command = (verify, ...parts) => ({ command: parts, kind: "command", verify });
41
+ const notice = (...lines) => ({
42
+ kind: "notice",
43
+ lines,
44
+ });
54
45
  /**
55
- * Detects the install method from the environment and the real path of the installed package folder.
46
+ * Returns what updates `installation` to `version`.
56
47
  *
57
- * pnpm keeps global packages in a `pnpm/global/` folder and its store in `.pnpm/`. Any other `node_modules/` folder is
58
- * an npm install. A folder outside `node_modules/` is a source checkout.
48
+ * Errors: throws for a Docker install or a source checkout, which `planUpdate` handles before the registry query.
59
49
  */
60
- export const detectInstallMethod = (env, packageDir) => {
61
- if (isDocker(env)) {
62
- return "docker";
63
- }
64
- const dir = `${packageDir}${path.sep}`;
65
- if (dir.includes(segment("pnpm", "global")) ||
66
- dir.includes(segment(".pnpm"))) {
67
- return "pnpm";
50
+ export const upgradeAction = (installation, version) => {
51
+ const spec = `${PACKAGE_NAME}@${version}`;
52
+ switch (installation.method) {
53
+ case "npm": {
54
+ const prefix = installation.prefix === undefined
55
+ ? []
56
+ : ["--prefix", installation.prefix];
57
+ return command(true, ...installation.npm, "install", "--global", ...prefix, spec);
58
+ }
59
+ case "pnpm": {
60
+ return command(false, "pnpm", "add", "--global", spec);
61
+ }
62
+ case "yarn": {
63
+ return command(true, "yarn", "global", "add", spec);
64
+ }
65
+ case "bun": {
66
+ return command(true, "bun", "install", "--global", spec);
67
+ }
68
+ case "brew": {
69
+ return command(false, "brew", "upgrade", installation.formula);
70
+ }
71
+ case "curl": {
72
+ // The script is downloaded before it runs, so that a failed download fails the command. A pipe from `curl` to
73
+ // `sh` would exit 0. The URL and version are arguments, not shell text.
74
+ return command(false, "sh", "-c", 'script="$(curl -fsSL "$0")" && printf "%s\\n" "$script" | sh -s -- --version "$1" --no-modify-path', INSTALLER_URL, version);
75
+ }
76
+ case "volta": {
77
+ return notice("Volta manages this Wheatley. To update it, run:", ` volta install ${spec}`);
78
+ }
79
+ case "mise": {
80
+ return notice("mise manages this Wheatley. To update it, run:", ` mise use -g npm:${spec}`);
81
+ }
82
+ case "aur": {
83
+ return notice("This Wheatley is the AUR package wheatley-cli. Update it with your AUR helper, for example:", " paru -Syu", " yay -Syu");
84
+ }
85
+ case "docker":
86
+ case "source": {
87
+ throw new Error(`wheatley update cannot update a ${installation.method} install`);
88
+ }
89
+ default: {
90
+ const unknown = installation;
91
+ throw new Error(`Unknown installation: ${JSON.stringify(unknown)}`);
92
+ }
68
93
  }
69
- return dir.includes(segment("node_modules")) ? "npm" : "source";
70
94
  };
71
- /** The global install command that updates Wheatley to `version`. */
72
- export const installCommand = (manager, version) => manager === "pnpm"
73
- ? ["pnpm", "add", "--global", `${PACKAGE_NAME}@${version}`]
74
- : ["npm", "install", "--global", `${PACKAGE_NAME}@${version}`];
75
- /** `npm view <package> versions --json` prints a string for one version and an array for more. */
76
- const VersionListSchema = Type.Union([
77
- Type.String(),
78
- Type.Array(Type.String()),
79
- ]);
80
95
  const PackageJsonSchema = Type.Object({ version: Type.String() });
81
- /** Lists the published versions of the package with `npm view`, which works for npm and pnpm installs. */
82
- const publishedVersions = async (runner) => {
83
- const args = ["view", PACKAGE_NAME, "versions", "--json"];
84
- const result = await runner.run("npm", args);
85
- if (result.exitCode !== 0) {
86
- throw new Error(describeFailure("npm", args, result));
87
- }
88
- const parsed = JSON.parse(result.stdout);
89
- if (!Value.Check(VersionListSchema, parsed)) {
90
- throw new Error("npm view returned an unexpected version list");
91
- }
92
- return [parsed].flat();
93
- };
94
96
  /**
95
97
  * Decides what `wheatley update` does. It never installs anything.
96
98
  *
97
99
  * - Docker: returns the Docker Compose commands, without a registry query.
98
- * - npm or pnpm: queries the registry and applies the major-version guard (`selectUpdate`).
100
+ * - Any other install: queries the registry, applies the major-version guard (`selectUpdate`), and returns the
101
+ * `upgradeAction` of the target version.
99
102
  *
100
- * Errors: throws for a source checkout without a `manager` override, if `npm view` fails, or for an invalid current
101
- * version.
103
+ * Errors: throws for a source checkout, if the registry query fails, or for an invalid current version.
102
104
  */
103
105
  export const planUpdate = async (input) => {
104
- if (input.method === "docker") {
106
+ const { installation } = input;
107
+ if (installation.method === "docker") {
105
108
  return { commands: DOCKER_UPDATE_COMMANDS, kind: "docker" };
106
109
  }
107
- const manager = input.manager ?? (input.method === "source" ? undefined : input.method);
108
- if (manager === undefined) {
109
- throw new Error("This Wheatley runs from a source checkout. Update it with git, or pass --manager npm or --manager pnpm.");
110
+ if (installation.method === "source") {
111
+ throw new Error("This Wheatley runs from a source checkout. Update it with git, or pass --method npm|pnpm|yarn|bun|brew|curl.");
110
112
  }
111
- const { newerMajor, target } = selectUpdate(input.current, await publishedVersions(input.runner));
113
+ const { newerMajor, target } = selectUpdate(input.current, await fetchPublishedVersions(input));
114
+ const major = newerMajor === undefined
115
+ ? undefined
116
+ : {
117
+ action: upgradeAction(installation, newerMajor),
118
+ version: newerMajor,
119
+ };
112
120
  if (target === undefined) {
113
- return { current: input.current, kind: "up_to_date", newerMajor };
121
+ return { current: input.current, kind: "up_to_date", newerMajor: major };
114
122
  }
115
123
  return {
116
- command: installCommand(manager, target),
124
+ action: upgradeAction(installation, target),
117
125
  current: input.current,
118
126
  kind: "update",
119
- newerMajor,
127
+ newerMajor: major,
120
128
  target,
121
129
  };
122
130
  };
123
- /**
124
- * Runs the install command of an `update` plan with the standard streams attached.
125
- *
126
- * Errors: rejects if the package manager cannot start or exits with a non-zero code.
127
- */
128
- export const applyUpdate = async (plan, runner) => {
129
- const [command, ...args] = plan.command;
130
- const result = await runner.run(command, args, { inheritStdio: true });
131
- if (result.exitCode !== 0) {
132
- throw new Error(describeFailure(command, args, result));
133
- }
134
- };
135
131
  /** The folder of this package, which holds `package.json`, `bin/`, and `dist/`. */
136
132
  export const packageDir = () => path.resolve(import.meta.dirname, "..", "..");
137
133
  /** Reads the version of the installed package from its `package.json`. */
@@ -143,3 +139,28 @@ export const readPackageVersion = async (dir = packageDir()) => {
143
139
  }
144
140
  return parsed.version;
145
141
  };
142
+ /**
143
+ * Runs an upgrade command with the standard streams attached. If `action.verify` is `true`, it then reads
144
+ * `package.json` in `packageDir` again, because a package manager can exit with code 0 but update another copy.
145
+ *
146
+ * Errors: rejects if the command cannot start, exits with a non-zero code, or leaves the running copy on another
147
+ * version than `target`.
148
+ */
149
+ export const applyUpgrade = async (action, options) => {
150
+ const [program, ...args] = action.command;
151
+ // Corepack shims of pnpm and yarn refuse to run inside a project whose `packageManager` names another manager.
152
+ const result = await options.runner.run(program, args, {
153
+ cwd: options.workDir,
154
+ inheritStdio: true,
155
+ });
156
+ if (result.exitCode !== 0) {
157
+ throw new Error(describeFailure(program, args, result));
158
+ }
159
+ if (!action.verify) {
160
+ return;
161
+ }
162
+ const installed = await readPackageVersion(options.packageDir);
163
+ if (installed !== options.target) {
164
+ throw new Error(`${action.command.join(" ")} finished, but ${options.packageDir} still has Wheatley ${installed}, not ${options.target}. Another copy of Wheatley can be first on PATH, or pass --method to name the package manager that owns this copy.`);
165
+ }
166
+ };
@@ -16,12 +16,25 @@ const StoredAttachmentSchema = Type.Union([
16
16
  sizeBytes: Type.Number(),
17
17
  }),
18
18
  ]);
19
+ const StoredModelRefSchema = Type.Object({
20
+ id: Type.String(),
21
+ provider: Type.String(),
22
+ });
23
+ const StoredModelPickerSchema = Type.Object({
24
+ current: Type.Optional(StoredModelRefSchema),
25
+ models: Type.Array(Type.Object({
26
+ id: Type.String(),
27
+ name: Type.String(),
28
+ provider: Type.String(),
29
+ })),
30
+ });
19
31
  const StoredDeliverySchema = Type.Union([
20
32
  Type.Object({
21
33
  attachments: Type.Optional(Type.Array(StoredAttachmentSchema)),
22
34
  chatId: Type.String(),
23
35
  kind: Type.Literal("message"),
24
36
  messageId: Type.String(),
37
+ modelPicker: Type.Optional(StoredModelPickerSchema),
25
38
  runId: Type.Optional(Type.String()),
26
39
  source: Type.Union([
27
40
  Type.Literal("reply"),
@@ -1,47 +1,59 @@
1
1
  import { timingSafeEqual } from "node:crypto";
2
2
  import { once } from "node:events";
3
- import { createServer } from "node:http";
3
+ import { Hono } from "hono";
4
+ import { bodyLimit } from "hono/body-limit";
5
+ import { HTTPException } from "hono/http-exception";
4
6
  import { SeamError } from "../contracts/errors.js";
5
7
  import { MAX_WEBHOOK_BODY_BYTES } from "../contracts/webhook-ingress.js";
8
+ import { createHttpServer } from "../core/server/http-server.js";
6
9
  import { errorText } from "./errors.js";
7
10
  /** A request must arrive in full within this time. */
8
11
  const REQUEST_TIMEOUT_MS = 30_000;
9
12
  const BEARER = /^Bearer (?<token>\S+)$/u;
10
13
  const SAFE_SUFFIX = /^[A-Za-z0-9._~\-/]+$/u;
14
+ /** The origin of the `Request` that `handle` builds. The Ingress routes on the path only. */
15
+ const INTERNAL_ORIGIN = "http://ingress.invalid";
16
+ const FRONTEND_PREFIX = /^\/frontends\/[^/]+\/[^/]+\//u;
11
17
  const status = (code) => ({ status: code });
12
18
  const tokensMatch = (given, expected) => {
13
19
  const left = Buffer.from(given);
14
20
  const right = Buffer.from(expected);
15
21
  return left.length === right.length && timingSafeEqual(left, right);
16
22
  };
17
- const headersOf = (request) => Object.fromEntries(Object.entries(request.headers).flatMap(([name, value]) => value === undefined
18
- ? []
19
- : [[name, Array.isArray(value) ? value.join(", ") : value]]));
20
- /**
21
- * Reads the body and stops at `MAX_WEBHOOK_BODY_BYTES`. Resolves `undefined` as soon as the declared length or the
22
- * streamed bytes pass the cap, without reading the rest.
23
- */
24
- const readBody = async (request) => {
25
- const declared = Number(request.headers["content-length"] ?? "0");
26
- if (declared > MAX_WEBHOOK_BODY_BYTES) {
27
- return undefined;
28
- }
29
- const chunks = [];
30
- let size = 0;
31
- // The early return must not destroy the socket before the `413` answer.
32
- for await (const chunk of request.iterator({ destroyOnReturn: false })) {
33
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
34
- size += buffer.length;
35
- if (size > MAX_WEBHOOK_BODY_BYTES) {
36
- return undefined;
37
- }
38
- chunks.push(buffer);
39
- }
40
- return new Uint8Array(Buffer.concat(chunks));
23
+ const toResponse = (result) => new Response(result.body instanceof Uint8Array
24
+ ? new Uint8Array(result.body)
25
+ : result.body, { headers: result.headers, status: result.status });
26
+ const fromResponse = async (response) => {
27
+ const body = new Uint8Array(await response.arrayBuffer());
28
+ return {
29
+ status: response.status,
30
+ headers: Object.fromEntries(response.headers),
31
+ ...(body.byteLength > 0 && { body }),
32
+ };
41
33
  };
42
34
  const isAddressInfo = (address) => typeof address === "object" && address !== null;
35
+ const readRequest = (c) => ({
36
+ body: c.get("body"),
37
+ headers: Object.fromEntries(c.req.raw.headers),
38
+ path: new URL(c.req.url).pathname,
39
+ query: c.req.query(),
40
+ });
41
+ const noop = async () => {
42
+ await Promise.resolve();
43
+ };
44
+ /** An error that answers `code` with an empty body and closes the connection. */
45
+ const closingError = (code) => new HTTPException(code, {
46
+ res: new Response(null, { headers: { connection: "close" }, status: code }),
47
+ });
48
+ const limitBody = bodyLimit({
49
+ maxSize: MAX_WEBHOOK_BODY_BYTES,
50
+ onError: () => {
51
+ throw closingError(413);
52
+ },
53
+ });
43
54
  /**
44
- * The Webhook Ingress (ADR 0010, ADR 0012): the routing of `WebhookIngress` and a `node:http` listener for it.
55
+ * The Webhook Ingress (ADR 0010, ADR 0012): the routing of `WebhookIngress` as a Hono app and a `node:http` listener
56
+ * for it.
45
57
  *
46
58
  * The listener answers `413` for a body over 256 KiB as soon as the declared length or the streamed bytes pass the
47
59
  * cap, and closes the connection without reading the rest.
@@ -49,9 +61,11 @@ const isAddressInfo = (address) => typeof address === "object" && address !== nu
49
61
  export class HttpWebhookIngress {
50
62
  #options;
51
63
  #routes = new Map();
64
+ #app;
52
65
  #server;
53
66
  constructor(options) {
54
67
  this.#options = options;
68
+ this.#app = this.#createApp();
55
69
  }
56
70
  registerFrontendRoute = (agent, bindingId, pathSuffix, handler) => {
57
71
  const invalid = pathSuffix === "" ||
@@ -75,29 +89,12 @@ export class HttpWebhookIngress {
75
89
  };
76
90
  };
77
91
  handle = async (request) => {
78
- if (request.method !== "POST") {
79
- return status(405);
80
- }
81
- const [empty, area, agentName = "", target = "", ...rest] = request.path.split("/");
82
- if (empty !== "") {
83
- return status(404);
84
- }
85
- try {
86
- if (area === "webhooks" && rest.length === 0) {
87
- return await this.#trigger(agentName, target, request);
88
- }
89
- if (area === "frontends") {
90
- return await this.#frontend(agentName, rest.join("/"), request);
91
- }
92
- return status(404);
93
- }
94
- catch (error) {
95
- this.#options.log.error("A webhook request failed", {
96
- error: errorText(error),
97
- path: request.path,
98
- });
99
- return status(500);
92
+ const url = new URL(request.path, INTERNAL_ORIGIN);
93
+ for (const [name, value] of Object.entries(request.query)) {
94
+ url.searchParams.set(name, value);
100
95
  }
96
+ const response = await this.#app.fetch(new Request(url, { headers: request.headers, method: request.method }), { body: request.body });
97
+ return await fromResponse(response);
101
98
  };
102
99
  /** The bound address while the listener runs, else `undefined`. */
103
100
  address = () => {
@@ -106,9 +103,7 @@ export class HttpWebhookIngress {
106
103
  };
107
104
  /** Starts the listener on `host` and `port`. Rejects if the port is in use. */
108
105
  listen = async (host, port) => {
109
- const server = createServer((request, response) => {
110
- void this.#serve(request, response);
111
- });
106
+ const server = createHttpServer(this.#app.fetch, "Webhook Ingress");
112
107
  server.requestTimeout = REQUEST_TIMEOUT_MS;
113
108
  server.listen(port, host);
114
109
  await once(server, "listening");
@@ -126,6 +121,49 @@ export class HttpWebhookIngress {
126
121
  server.closeAllConnections();
127
122
  await closed;
128
123
  };
124
+ #createApp = () => {
125
+ const app = new Hono();
126
+ app.post("*", async (c, proceed) => {
127
+ c.set("body", c.env.body ?? (await this.#readBody(c)));
128
+ await proceed();
129
+ });
130
+ app.post("/webhooks/:agent/:triggerId", async (c) => toResponse(await this.#trigger(c.req.param("agent"), c.req.param("triggerId"), readRequest(c))));
131
+ app.post("/frontends/:agent/:bindingId/*", async (c) => {
132
+ const request = readRequest(c);
133
+ return toResponse(await this.#frontend(c.req.param("agent"), request.path.replace(FRONTEND_PREFIX, ""), request));
134
+ });
135
+ app.all("*", (c) => c.body(null, c.req.method === "POST" ? 404 : 405));
136
+ app.onError((failure, c) => {
137
+ if (failure instanceof HTTPException) {
138
+ return failure.getResponse();
139
+ }
140
+ this.#options.log.error("A webhook request failed", {
141
+ error: errorText(failure),
142
+ path: c.req.path,
143
+ });
144
+ return c.body(null, 500);
145
+ });
146
+ return app;
147
+ };
148
+ /**
149
+ * Reads the body of a listener request. Throws an `HTTPException` that answers `413` past the cap, or `400` for a
150
+ * body that cannot be read, for example after the client aborts. Handler failures answer `500` in `onError`.
151
+ */
152
+ #readBody = async (c) => {
153
+ try {
154
+ await limitBody(c, noop);
155
+ return new Uint8Array(await c.req.arrayBuffer());
156
+ }
157
+ catch (error) {
158
+ if (error instanceof HTTPException) {
159
+ throw error;
160
+ }
161
+ this.#options.log.warn("A webhook request was not read", {
162
+ error: errorText(error),
163
+ });
164
+ throw closingError(400);
165
+ }
166
+ };
129
167
  #trigger = async (agentName, triggerId, request) => {
130
168
  const agent = this.#options.agent(agentName);
131
169
  if (agent === undefined) {
@@ -178,35 +216,4 @@ export class HttpWebhookIngress {
178
216
  query: request.query,
179
217
  });
180
218
  };
181
- #serve = async (request, response) => {
182
- const url = new URL(request.url ?? "/", "http://ingress.invalid");
183
- try {
184
- const body = request.method === "POST" ? await readBody(request) : new Uint8Array();
185
- if (body === undefined) {
186
- response.writeHead(413, { connection: "close" });
187
- response.end(() => {
188
- request.destroy();
189
- });
190
- return;
191
- }
192
- const result = await this.handle({
193
- body,
194
- headers: headersOf(request),
195
- method: request.method ?? "",
196
- path: url.pathname,
197
- query: Object.fromEntries(url.searchParams),
198
- });
199
- response.writeHead(result.status, result.headers);
200
- response.end(result.body);
201
- }
202
- catch (error) {
203
- this.#options.log.warn("A webhook request was not read", {
204
- error: errorText(error),
205
- });
206
- if (!response.headersSent) {
207
- response.writeHead(400, { connection: "close" });
208
- }
209
- response.end();
210
- }
211
- };
212
219
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wheatley-ai/cli",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Wheatley daemon and CLI",
5
5
  "license": "ISC",
6
6
  "repository": {
@@ -21,20 +21,26 @@
21
21
  "access": "public"
22
22
  },
23
23
  "dependencies": {
24
+ "@babel/code-frame": "8.0.6",
24
25
  "@earendil-works/chord": "1.6.1",
25
26
  "@earendil-works/pi-ai": "1.6.1",
26
27
  "@earendil-works/pi-durable": "1.6.1",
27
28
  "@earendil-works/pi-schema": "1.6.1",
29
+ "@hono/node-server": "2.1.11",
28
30
  "@modelcontextprotocol/client": "2.4.0",
29
31
  "@slack/socket-mode": "3.2.0",
30
32
  "@slack/web-api": "8.5.0",
33
+ "commander": "15.1.0",
31
34
  "croner": "11.0.1",
32
35
  "discord.js": "14.28.1",
33
36
  "grammy": "1.48.0",
37
+ "hono": "4.13.23",
34
38
  "import-meta-resolve": "4.2.0",
35
39
  "ink": "8.0.0",
40
+ "marked": "18.3.0",
36
41
  "react": "19.3.1",
37
- "string-width": "8.3.0",
42
+ "semver": "7.8.6",
43
+ "string-width": "9.0.0",
38
44
  "typebox": "1.4.7",
39
45
  "wrap-ansi": "10.0.2",
40
46
  "ws": "8.23.0",
@@ -42,11 +48,12 @@
42
48
  },
43
49
  "devDependencies": {
44
50
  "@modelcontextprotocol/server": "2.4.0",
45
- "@types/react": "19.3.1",
51
+ "@types/react": "19.3.3",
52
+ "@types/semver": "7.8.0",
46
53
  "@types/ws": "8.18.2",
47
54
  "@wheatley-ai/dashboard": "0.0.0",
48
55
  "@wheatley-ai/protocol": "0.0.0",
49
- "@wheatley-ai/sdk": "0.2.0",
56
+ "@wheatley-ai/sdk": "0.4.0",
50
57
  "ink-testing-library": "4.0.0"
51
58
  },
52
59
  "engines": {