@aidy-dev/server 0.0.0-stage → 0.2.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 +18 -0
- package/README.md +60 -2
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +45 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +1 -0
- package/dist/serve-Mv2At2zq.js +218 -0
- package/package.json +42 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
Copyright 2026 Aidy Contributors
|
|
6
|
+
|
|
7
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
8
|
+
you may not use this file except in compliance with the License.
|
|
9
|
+
You may obtain a copy of the License at
|
|
10
|
+
|
|
11
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
12
|
+
|
|
13
|
+
Unless required by applicable law or agreed to in writing, software
|
|
14
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
15
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
16
|
+
See the License for the specific language governing permissions and
|
|
17
|
+
limitations under the License.
|
|
18
|
+
|
package/README.md
CHANGED
|
@@ -1,3 +1,61 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aidy-dev/server
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Run aidy beside a host written in any language: Python, Go, Java. The server reads its
|
|
4
|
+
configuration from the environment, serves aidy over HTTP, and calls your API as the user
|
|
5
|
+
(see [delegation](../../spec/delegation.md)). It runs as one binary (`aidy-server`) or as the
|
|
6
|
+
Docker image `ghcr.io/aidy-dev/aidy-server`.
|
|
7
|
+
|
|
8
|
+
JavaScript hosts can embed `@aidy-dev/core` instead. Under Express, mount `nodeHandler(aidy)`
|
|
9
|
+
from this package.
|
|
10
|
+
|
|
11
|
+
## Quickstart
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npx @aidy-dev/server keys aidy-1 # prints signingKey (for aidy) and publicKey (for your host)
|
|
15
|
+
|
|
16
|
+
AIDY_URL=https://console.example.com/aidy \
|
|
17
|
+
AIDY_HOST_ORIGIN=https://console.example.com \
|
|
18
|
+
AIDY_HOST_BASE_URL=http://api.internal:8000 \
|
|
19
|
+
AIDY_SIGNING_KEY='{"kty":"OKP","crv":"Ed25519","d":"…","x":"…","kid":"aidy-1"}' \
|
|
20
|
+
AIDY_SECRET="$(openssl rand -base64 48)" \
|
|
21
|
+
AIDY_DATABASE_URL=postgres://aidy:…@db/aidy \
|
|
22
|
+
AIDY_MODELS='[{"id":"qwen","provider":"openai-compatible","model":"qwen-flash","baseURL":"https://dashscope.aliyuncs.com/compatible-mode/v1","apiKey":"…"}]' \
|
|
23
|
+
npx @aidy-dev/server serve
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Then route `/aidy/`, `/mcp`, `/skill.md`, `/llms.txt` and `/.well-known/aidy-keys.json` on your
|
|
27
|
+
public origin to the server, and pin the public key in your host kit.
|
|
28
|
+
|
|
29
|
+
## Environment
|
|
30
|
+
|
|
31
|
+
| Variable | Required | Meaning |
|
|
32
|
+
| --- | --- | --- |
|
|
33
|
+
| `AIDY_URL` | yes | Public URL of aidy; the assertion `iss`. |
|
|
34
|
+
| `AIDY_HOST_ORIGIN` | yes | Your product's public origin; the assertion `aud`. |
|
|
35
|
+
| `AIDY_HOST_BASE_URL` | | Where aidy reaches your API, when that differs from the origin (an internal service URL). |
|
|
36
|
+
| `AIDY_HOST_OPENAPI` | | Path or URL of your OpenAPI 3.1 document. Default `/api/openapi.json`. |
|
|
37
|
+
| `AIDY_SIGNING_KEY` | yes | Private Ed25519 JWK with `kid` (`aidy-server keys`). |
|
|
38
|
+
| `AIDY_HOST_KEYS` | | JSON array of public JWKs your host signs `Aidy-Host-Assertion`s with (deferred-task completions and `POST /aidy/v0/generate`). |
|
|
39
|
+
| `AIDY_SECRET` | yes | 32+ bytes; seals stored model API keys. |
|
|
40
|
+
| `AIDY_PREVIOUS_SECRET` | | The secret before a rotation: it still unseals saved settings, which are sealed again with `AIDY_SECRET` on first read. Remove it afterwards. |
|
|
41
|
+
| `AIDY_DATABASE_URL` | yes | `postgres://…` or `sqlite:<path>`. aidy creates its own `aidy_*` tables; give it its own database or schema. |
|
|
42
|
+
| `AIDY_MODELS` | | JSON model chain (`id`, `provider` = `openai-compatible`/`openai`/`anthropic`, `model`, `baseURL`, `apiKey`, `vision`, `temperature`, `maxOutputTokens`, `cooldownSeconds` = `{quota, rateLimit, error}`, `providerOptions`). Admins can change it in the app. |
|
|
43
|
+
| `AIDY_NAME` | | The assistant's name. Default `Aidy`. |
|
|
44
|
+
| `AIDY_INSTRUCTIONS` | | System instructions, or `@path` to a file. |
|
|
45
|
+
| `AIDY_SKILL_GUIDE` | | Hand-written guide placed first in `/skill.md`, or `@path`. |
|
|
46
|
+
| `AIDY_SKILL_NAME` | | The `/skill.md` frontmatter `name` (a slug). Default: the product's slug, else the first label of the host's hostname. |
|
|
47
|
+
| `AIDY_CLI_COMMAND`, `AIDY_CLI_PACKAGE`, `AIDY_CLI_INSTALL` | | The CLI `/skill.md` and `/llms.txt` name, and how to install it: its npm package, or a free-form install line (which wins), e.g. `curl -fsSL https://tm.example.com/install.sh \| sh`. Default `aidy` from `@aidy-dev/cli`. |
|
|
48
|
+
| `AIDY_KNOWLEDGE_DIR`, `AIDY_KNOWLEDGE_BASE_URL` | | A directory of Markdown docs indexed for search and answers, and the URL their pages live under. |
|
|
49
|
+
| `AIDY_MCP_AUTHORIZATION_SERVERS` | | Comma-separated OAuth issuers for MCP clients. |
|
|
50
|
+
| `AIDY_BASE_PATH` | | Prefix of every route when aidy is served below a path. |
|
|
51
|
+
| `AIDY_MAX_STEPS` | | Model steps per run. Default 16. |
|
|
52
|
+
| `PORT` | | Default 8080. `GET /healthz` answers `ok`. |
|
|
53
|
+
|
|
54
|
+
## Docker
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
docker run -p 8080:8080 --env-file aidy.env ghcr.io/aidy-dev/aidy-server:v0.2.0
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
To build on your own base image (an internal registry, say), pass
|
|
61
|
+
`--build-arg BASE_IMAGE=… --build-arg AIDY_VERSION=0.2.0` to this package's `Dockerfile`.
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {}
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { r as ConfigError, t as serve } from "./serve-Mv2At2zq.js";
|
|
3
|
+
import { generateKeyPair, portableJwk } from "@aidy-dev/spec/delegation";
|
|
4
|
+
// src/cli.ts
|
|
5
|
+
/** The `aidy-server` command. */
|
|
6
|
+
const USAGE = `usage:
|
|
7
|
+
aidy-server serve run aidy, configured from the environment (see README)
|
|
8
|
+
aidy-server keys <kid> print a new Ed25519 key pair: AIDY_SIGNING_KEY and the host's public key`;
|
|
9
|
+
async function main(command, args) {
|
|
10
|
+
switch (command) {
|
|
11
|
+
case "serve": {
|
|
12
|
+
const server = await serve({ env: process.env });
|
|
13
|
+
const stop = async () => {
|
|
14
|
+
await server.close();
|
|
15
|
+
process.exit(0);
|
|
16
|
+
};
|
|
17
|
+
process.once("SIGTERM", stop);
|
|
18
|
+
process.once("SIGINT", stop);
|
|
19
|
+
return -1;
|
|
20
|
+
}
|
|
21
|
+
case "keys": {
|
|
22
|
+
const kid = args[0];
|
|
23
|
+
if (!kid) break;
|
|
24
|
+
const pair = await generateKeyPair(kid);
|
|
25
|
+
const privateJwk = await crypto.subtle.exportKey("jwk", pair.signing.privateKey);
|
|
26
|
+
process.stdout.write(`${JSON.stringify({
|
|
27
|
+
signingKey: {
|
|
28
|
+
...portableJwk(privateJwk),
|
|
29
|
+
kid
|
|
30
|
+
},
|
|
31
|
+
publicKey: pair.publicJwk
|
|
32
|
+
}, null, 2)}\n`);
|
|
33
|
+
return 0;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
process.stderr.write(`${USAGE}\n`);
|
|
37
|
+
return 2;
|
|
38
|
+
}
|
|
39
|
+
main(process.argv[2], process.argv.slice(3)).then((code) => {
|
|
40
|
+
if (code >= 0) process.exit(code);
|
|
41
|
+
}, (error) => {
|
|
42
|
+
process.stderr.write(`${error instanceof ConfigError ? error.message : error instanceof Error ? error.stack : String(error)}\n`);
|
|
43
|
+
process.exit(error instanceof ConfigError ? 2 : 1);
|
|
44
|
+
});
|
|
45
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { Aidy, AidyConfig } from "@aidy-dev/core";
|
|
3
|
+
import { KnowledgeDocument } from "@aidy-dev/knowledge";
|
|
4
|
+
/**
|
|
5
|
+
* Every `.md`/`.mdx` file under `dir`. A document's url is `baseUrl` plus its path without the
|
|
6
|
+
* extension (`index` maps to its directory); its title is the frontmatter title, else the first
|
|
7
|
+
* heading, else the file name.
|
|
8
|
+
*/
|
|
9
|
+
export declare function loadDocuments(dir: string, baseUrl: string): Promise<KnowledgeDocument[]>;
|
|
10
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
11
|
+
export declare class ConfigError extends Error {
|
|
12
|
+
constructor(message: string);
|
|
13
|
+
}
|
|
14
|
+
interface ServerSettings {
|
|
15
|
+
readonly port: number;
|
|
16
|
+
readonly databaseUrl: string;
|
|
17
|
+
/** Markdown documents ingested into the knowledge source at start. */
|
|
18
|
+
readonly knowledge?: {
|
|
19
|
+
readonly dir: string;
|
|
20
|
+
readonly baseUrl: string;
|
|
21
|
+
};
|
|
22
|
+
readonly aidy: Omit<AidyConfig, 'store' | 'sources'>;
|
|
23
|
+
}
|
|
24
|
+
export declare function readSettings(env: Env): Promise<ServerSettings>;
|
|
25
|
+
/**
|
|
26
|
+
* A Node request listener for aidy. Under Express, mount it at the path aidy's `basePath`
|
|
27
|
+
* names: it reads `originalUrl`, so aidy sees the full path.
|
|
28
|
+
*/
|
|
29
|
+
export declare function nodeHandler(aidy: Aidy): (req: IncomingMessage & {
|
|
30
|
+
originalUrl?: string;
|
|
31
|
+
}, res: ServerResponse) => Promise<void>;
|
|
32
|
+
interface ServeOptions {
|
|
33
|
+
readonly env: Env;
|
|
34
|
+
readonly log?: (line: string) => void;
|
|
35
|
+
}
|
|
36
|
+
interface Server {
|
|
37
|
+
readonly port: number;
|
|
38
|
+
close(): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
export declare function serve(options: ServeOptions): Promise<Server>;
|
|
41
|
+
export type { ServeOptions, Server, ServerSettings };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { r as ConfigError, a as loadDocuments, n as nodeHandler, i as readSettings, t as serve } from "./serve-Mv2At2zq.js";
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { readFile, readdir } from "node:fs/promises";
|
|
2
|
+
import { join, relative, sep } from "node:path";
|
|
3
|
+
import { importPublicKeys, importSigningKey } from "@aidy-dev/spec/delegation";
|
|
4
|
+
import { getRequestListener } from "@hono/node-server";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { SqlStore, createAidy } from "@aidy-dev/core";
|
|
7
|
+
import { createKnowledge } from "@aidy-dev/knowledge";
|
|
8
|
+
import { postgresDriver } from "@aidy-dev/sql/postgres";
|
|
9
|
+
import { sqliteDriver } from "@aidy-dev/sql/sqlite";
|
|
10
|
+
// src/docs.ts
|
|
11
|
+
/** Loads a directory of Markdown documents for the knowledge index. */
|
|
12
|
+
const MARKDOWN = /\.mdx?$/;
|
|
13
|
+
async function files(dir) {
|
|
14
|
+
const entries = await readdir(dir, { withFileTypes: true });
|
|
15
|
+
return (await Promise.all(entries.map((entry) => {
|
|
16
|
+
const path = join(dir, entry.name);
|
|
17
|
+
if (entry.isDirectory()) return files(path);
|
|
18
|
+
return MARKDOWN.test(entry.name) ? [path] : [];
|
|
19
|
+
}))).flat().sort();
|
|
20
|
+
}
|
|
21
|
+
function frontmatter(markdown) {
|
|
22
|
+
const match = /^---\n([\s\S]*?)\n---\n?/.exec(markdown);
|
|
23
|
+
if (!match) return { body: markdown };
|
|
24
|
+
const title = /^title:\s*["']?(.+?)["']?\s*$/m.exec(match[1])?.[1];
|
|
25
|
+
return {
|
|
26
|
+
...title ? { title } : {},
|
|
27
|
+
body: markdown.slice(match[0].length)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Every `.md`/`.mdx` file under `dir`. A document's url is `baseUrl` plus its path without the
|
|
32
|
+
* extension (`index` maps to its directory); its title is the frontmatter title, else the first
|
|
33
|
+
* heading, else the file name.
|
|
34
|
+
*/
|
|
35
|
+
async function loadDocuments(dir, baseUrl) {
|
|
36
|
+
const base = baseUrl.replace(/\/+$/, "");
|
|
37
|
+
return Promise.all((await files(dir)).map(async (path) => {
|
|
38
|
+
const id = relative(dir, path).split(sep).join("/").replace(MARKDOWN, "");
|
|
39
|
+
const { title, body } = frontmatter(await readFile(path, "utf8"));
|
|
40
|
+
const heading = /^#\s+(.+)$/m.exec(body)?.[1]?.trim();
|
|
41
|
+
const slug = id === "index" ? "" : id.replace(/(^|\/)index$/, "");
|
|
42
|
+
return {
|
|
43
|
+
id,
|
|
44
|
+
title: title ?? heading ?? id,
|
|
45
|
+
url: slug ? `${base}/${slug}` : base || "/",
|
|
46
|
+
markdown: body
|
|
47
|
+
};
|
|
48
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
// src/env.ts
|
|
51
|
+
/**
|
|
52
|
+
* Reads an aidy server's configuration from the environment, so one image serves any host.
|
|
53
|
+
* Every variable is listed in README.md.
|
|
54
|
+
*/
|
|
55
|
+
var ConfigError = class extends Error {
|
|
56
|
+
constructor(message) {
|
|
57
|
+
super(message);
|
|
58
|
+
this.name = "ConfigError";
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
function required(env, name) {
|
|
62
|
+
const value = env[name]?.trim();
|
|
63
|
+
if (!value) throw new ConfigError(`${name} is required`);
|
|
64
|
+
return value;
|
|
65
|
+
}
|
|
66
|
+
function json(env, name, fallback) {
|
|
67
|
+
const raw = env[name]?.trim();
|
|
68
|
+
if (!raw) {
|
|
69
|
+
if (fallback === void 0) throw new ConfigError(`${name} is required`);
|
|
70
|
+
return fallback;
|
|
71
|
+
}
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(raw);
|
|
74
|
+
} catch {
|
|
75
|
+
throw new ConfigError(`${name} is not valid JSON`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** A value, or the contents of a file when it starts with `@`. */
|
|
79
|
+
async function text(env, name) {
|
|
80
|
+
const raw = env[name];
|
|
81
|
+
if (!raw) return void 0;
|
|
82
|
+
return raw.startsWith("@") ? readFile(raw.slice(1), "utf8") : raw;
|
|
83
|
+
}
|
|
84
|
+
async function signingKey(env) {
|
|
85
|
+
const jwk = json(env, "AIDY_SIGNING_KEY");
|
|
86
|
+
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.d || !jwk.kid) throw new ConfigError("AIDY_SIGNING_KEY must be a private Ed25519 JWK with a kid");
|
|
87
|
+
return importSigningKey({
|
|
88
|
+
...jwk,
|
|
89
|
+
kid: jwk.kid
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
function models(env) {
|
|
93
|
+
const chain = json(env, "AIDY_MODELS", []);
|
|
94
|
+
if (!Array.isArray(chain)) throw new ConfigError("AIDY_MODELS must be a JSON array");
|
|
95
|
+
chain.forEach((entry, index) => {
|
|
96
|
+
if (!entry.id || !entry.provider || !entry.model) throw new ConfigError(`AIDY_MODELS[${index}] needs id, provider and model`);
|
|
97
|
+
});
|
|
98
|
+
return chain;
|
|
99
|
+
}
|
|
100
|
+
async function readSettings(env) {
|
|
101
|
+
const secret = required(env, "AIDY_SECRET");
|
|
102
|
+
if (new TextEncoder().encode(secret).length < 32) throw new ConfigError("AIDY_SECRET must be at least 32 bytes");
|
|
103
|
+
const previous = env.AIDY_PREVIOUS_SECRET?.trim();
|
|
104
|
+
if (previous && new TextEncoder().encode(previous).length < 32) throw new ConfigError("AIDY_PREVIOUS_SECRET must be at least 32 bytes");
|
|
105
|
+
const hostKeys = json(env, "AIDY_HOST_KEYS", []);
|
|
106
|
+
const instructions = await text(env, "AIDY_INSTRUCTIONS");
|
|
107
|
+
const guide = await text(env, "AIDY_SKILL_GUIDE");
|
|
108
|
+
const cliCommand = env.AIDY_CLI_COMMAND?.trim();
|
|
109
|
+
const cliPackage = env.AIDY_CLI_PACKAGE?.trim();
|
|
110
|
+
const cliInstall = env.AIDY_CLI_INSTALL?.trim();
|
|
111
|
+
if ((cliPackage || cliInstall) && !cliCommand) throw new ConfigError("AIDY_CLI_PACKAGE and AIDY_CLI_INSTALL need AIDY_CLI_COMMAND");
|
|
112
|
+
const skillName = env.AIDY_SKILL_NAME?.trim();
|
|
113
|
+
const skill = {
|
|
114
|
+
...skillName ? { name: skillName } : {},
|
|
115
|
+
...guide ? { guide } : {},
|
|
116
|
+
...cliCommand ? { cli: {
|
|
117
|
+
command: cliCommand,
|
|
118
|
+
...cliPackage ? { package: cliPackage } : {},
|
|
119
|
+
...cliInstall ? { install: cliInstall } : {}
|
|
120
|
+
} } : {}
|
|
121
|
+
};
|
|
122
|
+
const authorizationServers = env.AIDY_MCP_AUTHORIZATION_SERVERS?.split(",").map((server) => server.trim()).filter(Boolean);
|
|
123
|
+
const maxSteps = env.AIDY_MAX_STEPS ? Number(env.AIDY_MAX_STEPS) : void 0;
|
|
124
|
+
if (maxSteps !== void 0 && !(Number.isInteger(maxSteps) && maxSteps > 0)) throw new ConfigError("AIDY_MAX_STEPS must be a positive integer");
|
|
125
|
+
const knowledgeDir = env.AIDY_KNOWLEDGE_DIR?.trim();
|
|
126
|
+
return {
|
|
127
|
+
port: Number(env.PORT ?? 8080),
|
|
128
|
+
databaseUrl: required(env, "AIDY_DATABASE_URL"),
|
|
129
|
+
...knowledgeDir ? { knowledge: {
|
|
130
|
+
dir: knowledgeDir,
|
|
131
|
+
baseUrl: required(env, "AIDY_KNOWLEDGE_BASE_URL")
|
|
132
|
+
} } : {},
|
|
133
|
+
aidy: {
|
|
134
|
+
url: required(env, "AIDY_URL"),
|
|
135
|
+
...env.AIDY_NAME ? { name: env.AIDY_NAME } : {},
|
|
136
|
+
...env.AIDY_BASE_PATH ? { basePath: env.AIDY_BASE_PATH } : {},
|
|
137
|
+
host: {
|
|
138
|
+
origin: required(env, "AIDY_HOST_ORIGIN"),
|
|
139
|
+
...env.AIDY_HOST_BASE_URL ? { baseUrl: env.AIDY_HOST_BASE_URL } : {},
|
|
140
|
+
openapi: env.AIDY_HOST_OPENAPI ?? "/api/openapi.json"
|
|
141
|
+
},
|
|
142
|
+
signingKey: await signingKey(env),
|
|
143
|
+
...hostKeys.length > 0 ? { hostKeys: await importPublicKeys(hostKeys) } : {},
|
|
144
|
+
secret: previous ? [secret, previous] : secret,
|
|
145
|
+
models: { chain: models(env) },
|
|
146
|
+
...instructions ? { instructions } : {},
|
|
147
|
+
...Object.keys(skill).length > 0 ? { skill } : {},
|
|
148
|
+
...maxSteps ? { limits: { maxSteps } } : {},
|
|
149
|
+
...authorizationServers?.length ? { mcp: { authorizationServers } } : {}
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
// src/node.ts
|
|
154
|
+
/**
|
|
155
|
+
* A Node request listener for aidy. Under Express, mount it at the path aidy's `basePath`
|
|
156
|
+
* names: it reads `originalUrl`, so aidy sees the full path.
|
|
157
|
+
*/
|
|
158
|
+
function nodeHandler(aidy) {
|
|
159
|
+
const listener = getRequestListener((request) => aidy.fetch(request));
|
|
160
|
+
return async (req, res) => {
|
|
161
|
+
if (req.originalUrl) req.url = req.originalUrl;
|
|
162
|
+
await listener(req, res);
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
// src/serve.ts
|
|
166
|
+
/** `aidy-server serve`: one aidy instance, configured from the environment, on Node. */
|
|
167
|
+
function driverFor(url) {
|
|
168
|
+
if (/^postgres(ql)?:\/\//.test(url)) return postgresDriver(url);
|
|
169
|
+
if (url.startsWith("sqlite:")) return sqliteDriver(url.slice(7));
|
|
170
|
+
throw new ConfigError("AIDY_DATABASE_URL must be postgres://… or sqlite:<path>");
|
|
171
|
+
}
|
|
172
|
+
async function serve(options) {
|
|
173
|
+
const log = options.log ?? ((line) => console.log(line));
|
|
174
|
+
const settings = await readSettings(options.env);
|
|
175
|
+
const driver = driverFor(settings.databaseUrl);
|
|
176
|
+
const store = new SqlStore(driver);
|
|
177
|
+
const sources = [];
|
|
178
|
+
if (settings.knowledge) {
|
|
179
|
+
const knowledge = createKnowledge({ driver });
|
|
180
|
+
await knowledge.migrate();
|
|
181
|
+
const documents = await loadDocuments(settings.knowledge.dir, settings.knowledge.baseUrl);
|
|
182
|
+
const { updated, unchanged } = await knowledge.ingest("docs", documents);
|
|
183
|
+
log(`knowledge: ${updated} updated, ${unchanged} unchanged`);
|
|
184
|
+
sources.push(knowledge.source({ collections: () => ["docs"] }));
|
|
185
|
+
}
|
|
186
|
+
const aidy = createAidy({
|
|
187
|
+
...settings.aidy,
|
|
188
|
+
store,
|
|
189
|
+
sources
|
|
190
|
+
});
|
|
191
|
+
await aidy.migrate();
|
|
192
|
+
const handle = nodeHandler(aidy);
|
|
193
|
+
const server = createServer((req, res) => {
|
|
194
|
+
if (req.url === "/healthz") {
|
|
195
|
+
res.writeHead(200, { "content-type": "text/plain" }).end("ok");
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
handle(req, res).catch((error) => {
|
|
199
|
+
log(`request failed: ${error instanceof Error ? error.stack : String(error)}`);
|
|
200
|
+
if (!res.headersSent) res.writeHead(500).end();
|
|
201
|
+
else res.end();
|
|
202
|
+
});
|
|
203
|
+
});
|
|
204
|
+
server.requestTimeout = 0;
|
|
205
|
+
await new Promise((resolve) => server.listen(settings.port, "0.0.0.0", resolve));
|
|
206
|
+
const port = server.address().port;
|
|
207
|
+
log(`aidy serving ${settings.aidy.url} for ${settings.aidy.host.origin} on :${port}`);
|
|
208
|
+
return {
|
|
209
|
+
port,
|
|
210
|
+
async close() {
|
|
211
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
212
|
+
server.closeAllConnections();
|
|
213
|
+
await aidy.close();
|
|
214
|
+
await driver.close();
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
export { loadDocuments as a, readSettings as i, nodeHandler as n, ConfigError as r, serve as t };
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aidy-dev/server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Run aidy beside a host in any language: `aidy-server`, a Node handler, and the Docker image.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://aidy.lpythu.workers.dev",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/aidy-dev/aidy.git",
|
|
10
|
+
"directory": "packages/server"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"files": [
|
|
14
|
+
"dist"
|
|
15
|
+
],
|
|
16
|
+
"bin": {
|
|
17
|
+
"aidy-server": "./dist/cli.js"
|
|
18
|
+
},
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"@aidy-dev/source": "./src/index.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./package.json": "./package.json"
|
|
25
|
+
},
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@hono/node-server": "^2.1.9",
|
|
31
|
+
"postgres": "^4.1.1",
|
|
32
|
+
"@aidy-dev/core": "0.2.0",
|
|
33
|
+
"@aidy-dev/spec": "0.2.0",
|
|
34
|
+
"@aidy-dev/sql": "0.2.0",
|
|
35
|
+
"@aidy-dev/knowledge": "0.2.0"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@aidy-dev/conformance": "0.1.0"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsdown",
|
|
42
|
+
"typecheck": "tsc -p .",
|
|
43
|
+
"test": "vitest run"
|
|
44
|
+
}
|
|
6
45
|
}
|