@aidy-dev/core 0.0.0-stage → 0.1.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 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,122 @@
1
- # Temporary Holding Version
1
+ # @aidy-dev/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The aidy runtime. It reads a product's annotated OpenAPI (`x-aidy`) and serves, from one
4
+ Web-standard `fetch` handler:
5
+
6
+ - the in-app agent over aidy's HTTP API and its AG-UI 1.0 profile (`/aidy/v0/*`),
7
+ - an MCP server (`/mcp`),
8
+ - federated search (`/aidy/v0/search`),
9
+ - generated agent documents (`/skill.md`, `/llms.txt`) and its public keys
10
+ (`/.well-known/aidy-keys.json`).
11
+
12
+ It uses Web-standard APIs only, so it runs on Node, Bun, Deno and Cloudflare Workers. The
13
+ contract it implements is in [`spec/`](../../spec); every behavior is pinned by the
14
+ [conformance cases](../../conformance).
15
+
16
+ ## Quickstart
17
+
18
+ ```ts
19
+ import { createAidy, SqlStore } from '@aidy-dev/core';
20
+ import { sqliteDriver } from '@aidy-dev/sql/sqlite';
21
+
22
+ const signingKey = {
23
+ kid: 'aidy-1',
24
+ // An Ed25519 private JWK from `aidy keys generate`; extractable, so the public key can be served.
25
+ privateKey: await crypto.subtle.importKey('jwk', JSON.parse(process.env.AIDY_PRIVATE_JWK!), 'Ed25519', true, ['sign']),
26
+ };
27
+
28
+ const aidy = createAidy({
29
+ url: 'https://console.example.com',
30
+ host: { origin: 'https://console.example.com', openapi: '/openapi.json' },
31
+ signingKey,
32
+ secret: process.env.AIDY_SECRET!, // 32+ bytes; seals model API keys at rest
33
+ store: new SqlStore(sqliteDriver('aidy.db')),
34
+ models: {
35
+ chain: [
36
+ { id: 'main', provider: 'openai', model: 'gpt-5.1', apiKey: process.env.OPENAI_API_KEY },
37
+ { id: 'backup', provider: 'anthropic', model: 'claude-sonnet-4-5', apiKey: process.env.ANTHROPIC_API_KEY },
38
+ ],
39
+ },
40
+ });
41
+
42
+ // Any server that speaks `fetch`: Hono, Bun.serve, Deno.serve, a Worker.
43
+ Bun.serve({ fetch: (request) => aidy.fetch(request) });
44
+ ```
45
+
46
+ The host keeps serving its own API. aidy calls it as the user: every call carries the user's
47
+ `Authorization` and `Cookie` headers and an `Aidy-Assertion` the host verifies with aidy's
48
+ public key ([delegation](../../spec/delegation.md)).
49
+
50
+ ### Embedded in the host
51
+
52
+ Pass the host's own handler as `host.fetch` to call it in process, and mount aidy under a
53
+ prefix with `basePath`:
54
+
55
+ ```ts
56
+ const app = new Hono();
57
+ // … the product's routes …
58
+ const aidy = createAidy({ ...config, basePath: '/assistant', host: { ...config.host, fetch: app.fetch } });
59
+ app.all('/assistant/*', (c) => aidy.fetch(c.req.raw));
60
+ ```
61
+
62
+ ### Cloudflare Workers
63
+
64
+ `createAidy` does no I/O, so build it per isolate from `env`. Pass the execution context so
65
+ runs that outlive the response are kept alive, and use the D1 driver:
66
+
67
+ ```ts
68
+ import { d1Driver } from '@aidy-dev/sql/d1';
69
+
70
+ export default {
71
+ fetch(request, env, ctx) {
72
+ aidy ??= createAidy({ ...configFrom(env), store: new SqlStore(d1Driver(env.DB)) });
73
+ return aidy.fetch(request, ctx);
74
+ },
75
+ };
76
+ ```
77
+
78
+ Any AI SDK provider model can join the chain, e.g. Workers AI:
79
+ `{ id: 'workers-ai', languageModel: createWorkersAI({ binding: env.AI })('@cf/…'), vision: false }`.
80
+
81
+ ## Configuration
82
+
83
+ | Key | Meaning |
84
+ | --- | --- |
85
+ | `url` | aidy's public URL: the assertion `iss`, and the base of `/mcp` in generated documents. |
86
+ | `basePath` | Prefix of every route. Default `''`. |
87
+ | `host.origin` | The host's public origin: the assertion `aud` and the base of `htu`. |
88
+ | `host.baseUrl` | Where aidy reaches the host's API, if not the origin (an internal address). |
89
+ | `host.openapi` | Path or URL of the OpenAPI 3.1 document, read with each user's credential. |
90
+ | `host.fetch` | In-process fetch for embedded hosts. |
91
+ | `signingKey` | aidy's Ed25519 key for assertions. |
92
+ | `hostKeys` | Host public keys allowed to complete deferred tasks. |
93
+ | `secret` | 32+ bytes; seals settings (model API keys) with AES-GCM. |
94
+ | `store` | `MemoryStore` or `SqlStore(driver)` over any `@aidy-dev/sql` driver. |
95
+ | `models.chain` | Models tried in order; 402 rests a model 6 h, 429 rests it 60 s; turns with images go to `vision` models. Admins replace the chain through `PUT /aidy/v0/settings`. |
96
+ | `instructions` | Extra system instructions, or a function of the user's identity. |
97
+ | `sources` | Extra search sources (`SearchSource`), such as `@aidy-dev/knowledge`. |
98
+ | `skill.guide` | Hand-written Markdown placed at the top of `/skill.md`. |
99
+ | `limits` | `maxSteps` (16), `contextTokens` (128 000), `runTimeoutSeconds` (600). |
100
+ | `mcp.authorizationServers` | Serves OAuth protected-resource metadata for MCP clients. |
101
+
102
+ ## The instance
103
+
104
+ ```ts
105
+ interface Aidy {
106
+ fetch(request: Request, ctx?: { waitUntil(promise: Promise<unknown>): void }): Promise<Response>;
107
+ migrate(): Promise<void>; // otherwise run on the first request
108
+ close(): Promise<void>; // waits for runs in progress, ends MCP sessions
109
+ }
110
+ ```
111
+
112
+ `Store` is the persistence contract; `MemoryStore` keeps everything in process (tests,
113
+ demos), and `SqlStore` keeps it in `aidy_*` tables of Postgres, SQLite or D1, with
114
+ compare-and-set approvals and tasks and a lease per thread, so several workers can share one
115
+ database.
116
+
117
+ ## Development
118
+
119
+ ```sh
120
+ pnpm --filter @aidy-dev/core test # unit tests and every conformance case (memory, sqlite)
121
+ AIDY_TEST_POSTGRES_URL=postgres://… pnpm --filter @aidy-dev/core test # and on Postgres
122
+ ```
@@ -0,0 +1,325 @@
1
+ import "hono";
2
+ import { Identity } from "@aidy-dev/spec/catalog";
3
+ import { SigningKey, VerificationKeys } from "@aidy-dev/spec/delegation";
4
+ import { Form } from "@aidy-dev/spec/protocol";
5
+ import "zod";
6
+ import { SearchHit } from "@aidy-dev/spec/search";
7
+ import { LanguageModelV4, SharedV4ProviderOptions } from "@ai-sdk/provider";
8
+ import { SqlDriver } from "@aidy-dev/sql";
9
+ import { Interrupt, Message } from "@ag-ui/core";
10
+ type Owner = {
11
+ subject: string;
12
+ tenant?: string;
13
+ };
14
+ interface ThreadRecord {
15
+ readonly id: string;
16
+ readonly owner: Owner;
17
+ readonly title: string;
18
+ readonly createdAt: string;
19
+ readonly updatedAt: string;
20
+ }
21
+ /** An AG-UI event as aidy stores and streams it; `metadata.aidy.seq` is set on append. */
22
+ type AidyEvent = {
23
+ type: string;
24
+ [key: string]: unknown;
25
+ };
26
+ interface StoredEvent {
27
+ readonly seq: number;
28
+ readonly runId: string;
29
+ readonly event: AidyEvent;
30
+ }
31
+ type RunStatus = 'running' | 'finished' | 'interrupted' | 'failed' | 'cancelled';
32
+ /** What a run remembers across its steps, and across the runs that resume it. */
33
+ interface RunState {
34
+ /** Digest of the catalog the run works with (see CatalogLoader). */
35
+ catalog: string;
36
+ steps: number;
37
+ /** Guard keys of reads that succeeded since the last write. */
38
+ reads: string[];
39
+ /** Guard key → tool message content of writes that succeeded. */
40
+ writes: Record<string, string>;
41
+ /** Operation → error message of approved writes that failed. */
42
+ failedWrites: Record<string, string>;
43
+ /** The next step is offered no tools: the model must answer from what it has. */
44
+ answerOnly: boolean;
45
+ /** Search hits the model may cite as `[n]`, n = index + 1. */
46
+ hits: CitedHit[];
47
+ }
48
+ interface CitedHit {
49
+ readonly type: string;
50
+ readonly id: string;
51
+ readonly title: string;
52
+ readonly url: string;
53
+ readonly excerpt?: string;
54
+ readonly updatedAt?: string;
55
+ }
56
+ interface RunRecord {
57
+ readonly id: string;
58
+ readonly threadId: string;
59
+ readonly status: RunStatus;
60
+ readonly cancelRequested: boolean;
61
+ readonly state: RunState;
62
+ readonly createdAt: string;
63
+ }
64
+ /** A tool call the model made, as it is kept while it waits. */
65
+ interface PendingToolCall {
66
+ readonly id: string;
67
+ readonly name: string;
68
+ readonly arguments: Record<string, unknown>;
69
+ }
70
+ /** What a paused call needs to go on once its interrupt is answered. */
71
+ type PendingCall = {
72
+ readonly kind: 'approval';
73
+ readonly call: PendingToolCall;
74
+ readonly argsHash: string;
75
+ readonly guardKey: string;
76
+ } | {
77
+ readonly kind: 'form';
78
+ readonly call: PendingToolCall;
79
+ readonly form: Form;
80
+ readonly guardKey: string;
81
+ } | {
82
+ readonly kind: 'input';
83
+ readonly call: PendingToolCall;
84
+ readonly form: Form;
85
+ } | {
86
+ readonly kind: 'task';
87
+ readonly call: PendingToolCall;
88
+ readonly taskId: string;
89
+ readonly guardKey: string;
90
+ };
91
+ type InterruptStatus = 'open' | 'resolved' | 'cancelled';
92
+ interface InterruptRecord {
93
+ readonly id: string;
94
+ readonly threadId: string;
95
+ readonly runId: string;
96
+ readonly status: InterruptStatus;
97
+ readonly interrupt: Interrupt;
98
+ readonly pending: PendingCall;
99
+ readonly createdAt: string;
100
+ }
101
+ type TaskStatus = 'pending' | 'succeeded' | 'failed' | 'cancelled';
102
+ interface TaskRecord {
103
+ readonly id: string;
104
+ readonly threadId: string;
105
+ readonly interruptId: string;
106
+ readonly op: string;
107
+ readonly owner: Owner;
108
+ readonly status: TaskStatus;
109
+ readonly result?: unknown;
110
+ }
111
+ interface Store {
112
+ /** Creates or upgrades the store's tables. */
113
+ migrate(): Promise<void>;
114
+ createThread(thread: ThreadRecord): Promise<void>;
115
+ getThread(id: string, owner: Owner): Promise<ThreadRecord | undefined>;
116
+ /** Newest first. `next` is the cursor of the following page. */
117
+ listThreads(owner: Owner, cursor?: string, limit?: number): Promise<{
118
+ items: ThreadRecord[];
119
+ next?: string;
120
+ }>;
121
+ updateThread(id: string, owner: Owner, patch: {
122
+ title?: string;
123
+ }): Promise<void>;
124
+ /** Deletes the thread with its messages, events, runs, interrupts and tasks. */
125
+ deleteThread(id: string, owner: Owner): Promise<void>;
126
+ listMessages(threadId: string): Promise<Message[]>;
127
+ appendMessages(threadId: string, messages: readonly Message[]): Promise<void>;
128
+ /** Stores the event under the thread's next `seq` and answers it. */
129
+ appendEvent(threadId: string, runId: string, event: AidyEvent): Promise<number>;
130
+ listEvents(threadId: string, after: number, limit?: number): Promise<StoredEvent[]>;
131
+ /** Takes the thread's run lease when it is free, expired, or already this run's. */
132
+ acquireLease(threadId: string, runId: string, until: number, now: number): Promise<boolean>;
133
+ /** Extends the lease; false when the run no longer holds it. */
134
+ renewLease(threadId: string, runId: string, until: number): Promise<boolean>;
135
+ releaseLease(threadId: string, runId: string): Promise<void>;
136
+ createRun(run: RunRecord): Promise<void>;
137
+ getRun(id: string): Promise<RunRecord | undefined>;
138
+ updateRun(id: string, patch: {
139
+ status?: RunStatus;
140
+ state?: RunState;
141
+ cancelRequested?: boolean;
142
+ }): Promise<void>;
143
+ createInterrupt(record: InterruptRecord): Promise<void>;
144
+ listOpenInterrupts(threadId: string): Promise<InterruptRecord[]>;
145
+ /** Closes an open interrupt; false when it was not open (someone else answered it). */
146
+ closeInterrupt(id: string, status: Exclude<InterruptStatus, 'open'>): Promise<boolean>;
147
+ createTask(task: TaskRecord): Promise<void>;
148
+ getTask(id: string): Promise<TaskRecord | undefined>;
149
+ /** Completes a pending task; false when it was not pending. */
150
+ completeTask(id: string, status: Exclude<TaskStatus, 'pending'>, result?: unknown): Promise<boolean>;
151
+ /** The sealed settings document, if any. */
152
+ getSettings(): Promise<string | undefined>;
153
+ putSettings(sealed: string): Promise<void>;
154
+ }
155
+ /** A model aidy builds from an AI SDK provider package. */
156
+ interface ProviderEndpoint {
157
+ /** Stable id: settings keep an entry's API key by it. */
158
+ id: string;
159
+ provider: 'openai-compatible' | 'openai' | 'anthropic';
160
+ model: string;
161
+ baseURL?: string;
162
+ apiKey?: string;
163
+ /** Used for turns with images. */
164
+ vision?: boolean;
165
+ /** Passed to the provider, e.g. `{ "openai-compatible": { enable_thinking: false } }`. */
166
+ providerOptions?: SharedV4ProviderOptions;
167
+ }
168
+ /** Any AI SDK provider model, e.g. Workers AI through `workers-ai-provider`. */
169
+ interface CustomEndpoint {
170
+ /** Stable id, shown in settings. */
171
+ id: string;
172
+ languageModel: LanguageModelV4;
173
+ vision?: boolean;
174
+ }
175
+ type ModelEndpoint = ProviderEndpoint | CustomEndpoint;
176
+ interface ModelSettings {
177
+ /**
178
+ * Tried in order; a model answering 402 rests 6 h, one answering 429 rests 60 s. Turns with
179
+ * images go only to `vision` models.
180
+ */
181
+ chain: ModelEndpoint[];
182
+ }
183
+ interface SearchSource {
184
+ /** Matches OPERATION_NAME, e.g. "knowledge". */
185
+ readonly name: string;
186
+ search(query: string, options: {
187
+ limit: number;
188
+ identity: Identity;
189
+ }): Promise<SearchHit[]>;
190
+ }
191
+ interface AidyConfig {
192
+ /** Display name of the assistant. Default "Aidy". */
193
+ name?: string;
194
+ /** Public URL of this aidy instance (the assertion `iss`), e.g. https://console.example.com/aidy */
195
+ url: string;
196
+ /** Prefix of every route when the host mounts aidy below its root, e.g. `/assistant`. */
197
+ basePath?: string;
198
+ host: {
199
+ /** The host origin (the assertion `aud`). */
200
+ origin: string;
201
+ /** Where aidy reaches the host's API. Default: origin. */
202
+ baseUrl?: string;
203
+ /** Path or absolute URL of the host's OpenAPI 3.1 document, fetched with the user's credential. */
204
+ openapi: string;
205
+ /** In-process fetch for embedded hosts (e.g. Hono `app.fetch`). Default: global fetch. */
206
+ fetch?: (request: Request) => Promise<Response>;
207
+ };
208
+ /** aidy's Ed25519 signing key (assertions). Its private key must be extractable, to publish the public key. */
209
+ signingKey: SigningKey;
210
+ /** Host public keys that may sign `Aidy-Host-Assertion` (deferred-task completion). */
211
+ hostKeys?: VerificationKeys;
212
+ /** 32+ byte secret used to seal settings (model API keys) at rest. */
213
+ secret: string;
214
+ store: Store;
215
+ /** Defaults; admins override them through /aidy/v0/settings. */
216
+ models: ModelSettings;
217
+ instructions?: string | ((identity: Identity) => string);
218
+ /** Extra search sources, e.g. knowledge. */
219
+ sources?: SearchSource[];
220
+ /** Hand-written markdown placed before the generated tool index of /skill.md. */
221
+ skill?: {
222
+ guide: string;
223
+ };
224
+ limits?: {
225
+ maxSteps?: number;
226
+ contextTokens?: number;
227
+ runTimeoutSeconds?: number;
228
+ };
229
+ /** OAuth protected-resource metadata for MCP clients. */
230
+ mcp?: {
231
+ authorizationServers?: string[];
232
+ };
233
+ }
234
+ /** Workers' execution context: runs that outlive the response are registered with it. */
235
+ interface ExecutionContext {
236
+ waitUntil(promise: Promise<unknown>): void;
237
+ }
238
+ interface Aidy {
239
+ /** Handles /aidy/v0/*, /mcp, /skill.md, /llms.txt, /.well-known/aidy-keys.json. */
240
+ fetch(request: Request, ctx?: ExecutionContext): Promise<Response>;
241
+ /** Creates or upgrades the store's tables; otherwise done on the first request. */
242
+ migrate(): Promise<void>;
243
+ /** Waits for the runs in progress and ends MCP sessions. */
244
+ close(): Promise<void>;
245
+ }
246
+ /** Builds an aidy instance. It does no I/O until the first request (Workers build one per isolate). */
247
+ export declare function createAidy(config: AidyConfig): Aidy;
248
+ export declare class MemoryStore implements Store {
249
+ private readonly threads;
250
+ private readonly runs;
251
+ private readonly interrupts;
252
+ private readonly tasks;
253
+ private settings;
254
+ migrate(): Promise<void>;
255
+ createThread(thread: ThreadRecord): Promise<void>;
256
+ getThread(id: string, owner: Owner): Promise<ThreadRecord | undefined>;
257
+ listThreads(owner: Owner, cursor?: string, limit?: number): Promise<{
258
+ items: ThreadRecord[];
259
+ next?: string;
260
+ }>;
261
+ updateThread(id: string, owner: Owner, patch: {
262
+ title?: string;
263
+ }): Promise<void>;
264
+ deleteThread(id: string, owner: Owner): Promise<void>;
265
+ listMessages(threadId: string): Promise<Message[]>;
266
+ appendMessages(threadId: string, messages: readonly Message[]): Promise<void>;
267
+ appendEvent(threadId: string, runId: string, event: AidyEvent): Promise<number>;
268
+ listEvents(threadId: string, after: number, limit?: number): Promise<StoredEvent[]>;
269
+ acquireLease(threadId: string, runId: string, until: number, now: number): Promise<boolean>;
270
+ renewLease(threadId: string, runId: string, until: number): Promise<boolean>;
271
+ releaseLease(threadId: string, runId: string): Promise<void>;
272
+ createRun(run: RunRecord): Promise<void>;
273
+ getRun(id: string): Promise<RunRecord | undefined>;
274
+ updateRun(id: string, patch: {
275
+ status?: RunStatus;
276
+ state?: RunState;
277
+ cancelRequested?: boolean;
278
+ }): Promise<void>;
279
+ createInterrupt(record: InterruptRecord): Promise<void>;
280
+ listOpenInterrupts(threadId: string): Promise<InterruptRecord[]>;
281
+ closeInterrupt(id: string, status: Exclude<InterruptStatus, 'open'>): Promise<boolean>;
282
+ createTask(task: TaskRecord): Promise<void>;
283
+ getTask(id: string): Promise<TaskRecord | undefined>;
284
+ completeTask(id: string, status: Exclude<TaskStatus, 'pending'>, result?: unknown): Promise<boolean>;
285
+ getSettings(): Promise<string | undefined>;
286
+ putSettings(sealed: string): Promise<void>;
287
+ }
288
+ export declare class SqlStore implements Store {
289
+ private readonly db;
290
+ constructor(driver: SqlDriver);
291
+ migrate(): Promise<void>;
292
+ createThread(thread: ThreadRecord): Promise<void>;
293
+ getThread(id: string, owner: Owner): Promise<ThreadRecord | undefined>;
294
+ listThreads(owner: Owner, cursor?: string, limit?: number): Promise<{
295
+ items: ThreadRecord[];
296
+ next?: string;
297
+ }>;
298
+ updateThread(id: string, owner: Owner, patch: {
299
+ title?: string;
300
+ }): Promise<void>;
301
+ deleteThread(id: string, owner: Owner): Promise<void>;
302
+ listMessages(threadId: string): Promise<Message[]>;
303
+ appendMessages(threadId: string, messages: readonly Message[]): Promise<void>;
304
+ appendEvent(threadId: string, runId: string, event: AidyEvent): Promise<number>;
305
+ listEvents(threadId: string, after: number, limit?: number): Promise<StoredEvent[]>;
306
+ acquireLease(threadId: string, runId: string, until: number, now: number): Promise<boolean>;
307
+ renewLease(threadId: string, runId: string, until: number): Promise<boolean>;
308
+ releaseLease(threadId: string, runId: string): Promise<void>;
309
+ createRun(run: RunRecord): Promise<void>;
310
+ getRun(id: string): Promise<RunRecord | undefined>;
311
+ updateRun(id: string, patch: {
312
+ status?: RunStatus;
313
+ state?: RunState;
314
+ cancelRequested?: boolean;
315
+ }): Promise<void>;
316
+ createInterrupt(record: InterruptRecord): Promise<void>;
317
+ listOpenInterrupts(threadId: string): Promise<InterruptRecord[]>;
318
+ closeInterrupt(id: string, status: Exclude<InterruptStatus, 'open'>): Promise<boolean>;
319
+ createTask(task: TaskRecord): Promise<void>;
320
+ getTask(id: string): Promise<TaskRecord | undefined>;
321
+ completeTask(id: string, status: Exclude<TaskStatus, 'pending'>, result?: unknown): Promise<boolean>;
322
+ getSettings(): Promise<string | undefined>;
323
+ putSettings(sealed: string): Promise<void>;
324
+ }
325
+ export type { Aidy, AidyConfig, AidyEvent, CitedHit, CustomEndpoint, ExecutionContext, InterruptRecord, InterruptStatus, ModelEndpoint, ModelSettings, Owner, PendingCall, PendingToolCall, ProviderEndpoint, RunRecord, RunState, RunStatus, SearchSource, Store, StoredEvent, TaskRecord, TaskStatus, ThreadRecord };