@aidy-dev/client 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,23 @@
1
- # Temporary Holding Version
1
+ # @aidy-dev/client
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
+ A typed client for aidy's HTTP API, plus a reducer that turns its AG-UI event stream into
4
+ thread state. It runs in the browser and in Node, and has no UI.
5
+
6
+ ```ts
7
+ import { createClient, initialThreadState, reduceThread } from '@aidy-dev/client';
8
+
9
+ const aidy = createClient({ baseUrl: '/aidy/v0' });
10
+ const thread = await aidy.createThread();
11
+ let state = initialThreadState;
12
+ for await (const event of aidy.run(thread.id, { message: 'Stop gpu-train-01' })) {
13
+ state = reduceThread(state, event);
14
+ }
15
+ // state.interrupts holds the approval; answer it:
16
+ // aidy.run(thread.id, { resume: [answerApproval(state.interrupts[0], true)] })
17
+ ```
18
+
19
+ - **Endpoints:** `createThread`, `listThreads`, `getThread`, `renameThread`, `deleteThread`,
20
+ `run`, `follow` (replays, then follows live and reconnects with `Last-Event-ID`), `cancel`,
21
+ `catalog`, `search`, `getSettings`, `putSettings`.
22
+ - **Helpers:** `answerApproval`, `answerForm` and `cancelAll` build resume entries.
23
+ - **State:** `reduceThread` is pure, and a replayed event leaves the state unchanged.
@@ -0,0 +1,213 @@
1
+ import { ApprovalInterruptMeta, CustomEventValue, Form, FormAnswers, ToolCallMeta } from "@aidy-dev/spec/protocol";
2
+ import { Event, Interrupt, Message, ResumeEntry, ResumeEntry as ResumeEntry$1, TokenUsage } from "@ag-ui/core";
3
+ import { Approval, Effect, JsonSchema, Surface } from "@aidy-dev/spec/catalog";
4
+ import { FederatedSearchResponse, SearchHit } from "@aidy-dev/spec/search";
5
+ /** An AG-UI event as aidy sends it: `metadata.aidy.seq` is always present. */
6
+ type AidyEvent = Event & {
7
+ metadata: {
8
+ aidy: {
9
+ seq: number;
10
+ };
11
+ };
12
+ };
13
+ export declare class AidyProtocolError extends Error {
14
+ name: string;
15
+ }
16
+ interface ClientOptions {
17
+ /** Origin (and optional path prefix) that serves `/aidy/v0`. */
18
+ readonly baseUrl: string;
19
+ readonly fetch?: typeof globalThis.fetch;
20
+ /** Called before every request, e.g. to add the user's `Authorization`. */
21
+ readonly headers?: () => HeadersInit | Promise<HeadersInit>;
22
+ }
23
+ interface ThreadSummary {
24
+ readonly id: string;
25
+ readonly title: string | null;
26
+ readonly createdAt: string;
27
+ }
28
+ interface ThreadPage {
29
+ readonly items: ThreadSummary[];
30
+ readonly next?: string;
31
+ }
32
+ interface ThreadDetail extends ThreadSummary {
33
+ readonly messages: Message[];
34
+ readonly interrupts: Interrupt[];
35
+ }
36
+ interface CatalogOperation {
37
+ readonly name: string;
38
+ readonly title: string;
39
+ readonly effect: Effect;
40
+ readonly approval: Approval;
41
+ readonly surfaces: Surface[];
42
+ readonly input: JsonSchema;
43
+ }
44
+ interface ModelEndpointFields {
45
+ readonly provider: 'openai-compatible' | 'openai' | 'anthropic';
46
+ readonly model: string;
47
+ readonly baseURL?: string;
48
+ readonly vision?: boolean;
49
+ readonly providerOptions?: Record<string, unknown>;
50
+ }
51
+ /** A model endpoint as `GET /settings` shows it: the key itself is never returned. */
52
+ interface ModelEndpointSettings extends ModelEndpointFields {
53
+ readonly hasApiKey: boolean;
54
+ }
55
+ /** A model endpoint in `PUT /settings`: an absent `apiKey` keeps the stored one. */
56
+ interface ModelEndpointUpdate extends ModelEndpointFields {
57
+ readonly apiKey?: string;
58
+ }
59
+ interface Settings {
60
+ readonly models: {
61
+ readonly chain: ModelEndpointSettings[];
62
+ };
63
+ }
64
+ interface SettingsUpdate {
65
+ readonly models: {
66
+ readonly chain: ModelEndpointUpdate[];
67
+ };
68
+ }
69
+ interface RunRequest {
70
+ /** A new user message. */
71
+ readonly message?: string;
72
+ /** Answers to the thread's open interrupts. */
73
+ readonly resume?: ResumeEntry$1[];
74
+ }
75
+ /** A run's events. The request is sent when iteration starts. */
76
+ interface RunStream extends AsyncIterable<AidyEvent> {
77
+ readonly runId: string;
78
+ /** The id given to `RunRequest.message`. */
79
+ readonly messageId?: string;
80
+ }
81
+ interface SearchOptions {
82
+ readonly limit?: number;
83
+ readonly types?: readonly string[];
84
+ readonly signal?: AbortSignal;
85
+ }
86
+ export declare class AidyRequestError extends Error {
87
+ readonly status: number;
88
+ readonly body: unknown;
89
+ name: string;
90
+ constructor(status: number, body: unknown);
91
+ }
92
+ export declare function createClient(options: ClientOptions): {
93
+ createThread(): Promise<ThreadSummary>;
94
+ listThreads(cursor?: string): Promise<ThreadPage>;
95
+ getThread(id: string): Promise<ThreadDetail>;
96
+ renameThread(id: string, title: string): Promise<void>;
97
+ deleteThread(id: string): Promise<void>;
98
+ /** Starts a run. Leaving the iteration early detaches from it; the run goes on. */
99
+ run(threadId: string, input: RunRequest, init?: {
100
+ signal?: AbortSignal;
101
+ }): RunStream;
102
+ /**
103
+ * Replays the thread's events after `after`, then follows them live. It reconnects with
104
+ * `Last-Event-ID` and exponential backoff until `signal` aborts, never yielding a seq twice.
105
+ */
106
+ follow(threadId: string, init: {
107
+ after: number;
108
+ signal?: AbortSignal;
109
+ }): AsyncGenerator<AidyEvent>;
110
+ cancel(runId: string): Promise<void>;
111
+ catalog(): Promise<CatalogOperation[]>;
112
+ search(query: string, init?: SearchOptions): Promise<FederatedSearchResponse>;
113
+ getSettings(): Promise<Settings>;
114
+ putSettings(settings: SettingsUpdate): Promise<Settings>;
115
+ };
116
+ type AidyClient = ReturnType<typeof createClient>;
117
+ interface UserItem {
118
+ readonly kind: 'user';
119
+ readonly id: string;
120
+ readonly text: string;
121
+ }
122
+ interface AssistantItem {
123
+ readonly kind: 'assistant';
124
+ readonly id: string;
125
+ readonly text: string;
126
+ readonly streaming: boolean;
127
+ }
128
+ interface ToolItem {
129
+ readonly kind: 'tool';
130
+ /** The tool call id. */
131
+ readonly id: string;
132
+ readonly name: string;
133
+ /** From `TOOL_CALL_START.metadata.aidy`; null when the runtime sent none. */
134
+ readonly meta: ToolCallMeta | null;
135
+ /** The redacted arguments, once they arrived and parse as a JSON object. */
136
+ readonly arguments: Record<string, unknown> | null;
137
+ readonly status: 'running' | 'succeeded' | 'failed';
138
+ readonly error: {
139
+ readonly code: string;
140
+ readonly message: string;
141
+ } | null;
142
+ readonly deduplicated: boolean;
143
+ /** The redacted JSON result. */
144
+ readonly result: string | null;
145
+ }
146
+ interface ProgressItem {
147
+ readonly kind: 'progress';
148
+ readonly id: string;
149
+ readonly message: string;
150
+ }
151
+ type ThreadItem = UserItem | AssistantItem | ToolItem | ProgressItem;
152
+ interface InterruptBase {
153
+ readonly id: string;
154
+ readonly interrupt: Interrupt;
155
+ }
156
+ interface ApprovalInterrupt extends InterruptBase {
157
+ readonly kind: 'approval';
158
+ readonly meta: ApprovalInterruptMeta;
159
+ }
160
+ interface InputInterrupt extends InterruptBase {
161
+ readonly kind: 'input';
162
+ readonly form: Form;
163
+ }
164
+ interface TaskInterrupt extends InterruptBase {
165
+ readonly kind: 'task';
166
+ readonly taskId: string;
167
+ readonly op: string;
168
+ /** The latest `aidy.task` progress. */
169
+ readonly progress: CustomEventValue<'aidy.task'> | null;
170
+ }
171
+ /** An interrupt aidy's profile does not describe; it can only be cancelled. */
172
+ interface OtherInterrupt extends InterruptBase {
173
+ readonly kind: 'other';
174
+ }
175
+ type OpenInterrupt = ApprovalInterrupt | InputInterrupt | TaskInterrupt | OtherInterrupt;
176
+ type RunStatus = 'idle' | 'running' | 'interrupted' | 'succeeded' | 'cancelled' | 'failed';
177
+ interface ThreadState {
178
+ /** The highest seq applied; events at or below it are ignored. */
179
+ readonly lastSeq: number;
180
+ readonly status: RunStatus;
181
+ readonly runId: string | null;
182
+ readonly items: readonly ThreadItem[];
183
+ readonly interrupts: readonly OpenInterrupt[];
184
+ /** Hits each assistant message cites, by message id, in `[n]` order. */
185
+ readonly citations: Readonly<Record<string, readonly SearchHit[]>>;
186
+ /** Product pages the runs asked to show (`aidy.ui.open`), with the seq that asked. */
187
+ readonly opens: readonly {
188
+ readonly seq: number;
189
+ readonly path: string;
190
+ }[];
191
+ readonly context: CustomEventValue<'aidy.context'> | null;
192
+ /** The model retry in progress, cleared when text arrives or the run ends. */
193
+ readonly retry: CustomEventValue<'aidy.model.retry'> | null;
194
+ readonly error: {
195
+ readonly code: string | null;
196
+ readonly message: string;
197
+ } | null;
198
+ readonly usage: readonly TokenUsage[];
199
+ }
200
+ export declare const initialThreadState: ThreadState;
201
+ /** Reads an AG-UI interrupt as one of aidy's three kinds. */
202
+ export declare function openInterrupt(interrupt: Interrupt): OpenInterrupt;
203
+ /** Applies one event. Pure; an event at or below `lastSeq` (a replay) changes nothing. */
204
+ export declare function reduceThread(state: ThreadState, event: AidyEvent): ThreadState;
205
+ /** Shows a message the user just sent before the run echoes it; the echo is then ignored. */
206
+ export declare function appendUserMessage(state: ThreadState, message: UserItem): ThreadState;
207
+ /** Answers an approval, echoing the `argsHash` the user saw so aidy runs exactly those arguments. */
208
+ export declare function answerApproval(interrupt: ApprovalInterrupt, approved: boolean): ResumeEntry$1;
209
+ /** Answers a form. Throws when the answers fail `checkAnswers`. */
210
+ export declare function answerForm(interrupt: InputInterrupt, answers: FormAnswers['answers']): ResumeEntry$1;
211
+ /** Cancels every open interrupt, as a new user message must. */
212
+ export declare function cancelAll(interrupts: readonly OpenInterrupt[]): ResumeEntry$1[];
213
+ export type { AidyClient, AidyEvent, ApprovalInterrupt, AssistantItem, CatalogOperation, ClientOptions, InputInterrupt, ModelEndpointSettings, ModelEndpointUpdate, OpenInterrupt, OtherInterrupt, ProgressItem, ResumeEntry, RunRequest, RunStatus, RunStream, SearchOptions, Settings, SettingsUpdate, TaskInterrupt, ThreadDetail, ThreadItem, ThreadPage, ThreadState, ThreadSummary, ToolItem, UserItem };
package/dist/index.js ADDED
@@ -0,0 +1,561 @@
1
+ import { API_PREFIX, ApprovalInterruptMeta, CustomEvents, InputInterruptMeta, InterruptReason, METADATA_KEY, PROGRESS_ACTIVITY, ProgressContent, TaskInterruptMeta, ToolCallMeta, ToolResultMeta, checkAnswers } from "@aidy-dev/spec/protocol";
2
+ import { EventType } from "@ag-ui/core";
3
+ // src/sse.ts
4
+ var AidyProtocolError = class extends Error {
5
+ name = "AidyProtocolError";
6
+ };
7
+ /** Splits a byte stream into server-sent-event frames (WHATWG event-stream format). */
8
+ async function* readSse(body) {
9
+ const reader = body.getReader();
10
+ const decoder = new TextDecoder();
11
+ let buffer = "";
12
+ let data = [];
13
+ let id;
14
+ let retry;
15
+ try {
16
+ while (true) {
17
+ const { value, done } = await reader.read();
18
+ if (done) return;
19
+ buffer += decoder.decode(value, { stream: true });
20
+ let newline = buffer.search(/\r\n|\r|\n/);
21
+ while (newline !== -1 && !(newline === buffer.length - 1 && buffer.endsWith("\r"))) {
22
+ const line = buffer.slice(0, newline);
23
+ buffer = buffer.slice(newline + (buffer.startsWith("\r\n", newline) ? 2 : 1));
24
+ if (line === "") {
25
+ if (data.length > 0 || retry !== void 0) yield {
26
+ data: data.join("\n"),
27
+ ...id === void 0 ? {} : { id },
28
+ ...retry === void 0 ? {} : { retry }
29
+ };
30
+ data = [];
31
+ id = void 0;
32
+ retry = void 0;
33
+ } else if (!line.startsWith(":")) {
34
+ const colon = line.indexOf(":");
35
+ const field = colon === -1 ? line : line.slice(0, colon);
36
+ let text = colon === -1 ? "" : line.slice(colon + 1);
37
+ if (text.startsWith(" ")) text = text.slice(1);
38
+ if (field === "data") data.push(text);
39
+ else if (field === "id") id = text;
40
+ else if (field === "retry" && /^\d+$/.test(text)) retry = Number(text);
41
+ }
42
+ newline = buffer.search(/\r\n|\r|\n/);
43
+ }
44
+ }
45
+ } finally {
46
+ await reader.cancel().catch(() => {});
47
+ }
48
+ }
49
+ /** Parses a frame's data as an aidy event, checking `metadata.aidy.seq` against the SSE id. */
50
+ function parseEvent(frame) {
51
+ let event;
52
+ try {
53
+ event = JSON.parse(frame.data);
54
+ } catch {
55
+ throw new AidyProtocolError("event data is not JSON");
56
+ }
57
+ if (typeof event !== "object" || event === null || typeof event.type !== "string") throw new AidyProtocolError("event has no type");
58
+ const seq = event.metadata?.aidy?.seq;
59
+ if (typeof seq !== "number" || !Number.isInteger(seq) || seq < 1) throw new AidyProtocolError(`${event.type} has no metadata.aidy.seq`);
60
+ if (frame.id !== void 0 && frame.id !== String(seq)) throw new AidyProtocolError(`SSE id ${frame.id} does not match seq ${seq}`);
61
+ return event;
62
+ }
63
+ function seqOf(event) {
64
+ return event.metadata.aidy.seq;
65
+ }
66
+ // src/client.ts
67
+ var AidyRequestError = class extends Error {
68
+ status;
69
+ body;
70
+ name = "AidyRequestError";
71
+ constructor(status, body) {
72
+ super(`aidy request failed (${status})`);
73
+ this.status = status;
74
+ this.body = body;
75
+ }
76
+ };
77
+ const DEFAULT_RETRY_MS = 1e3;
78
+ const MAX_RETRY_MS = 3e4;
79
+ function sleep(ms, signal) {
80
+ return new Promise((resolve, reject) => {
81
+ if (signal?.aborted) return reject(signal.reason);
82
+ const timer = setTimeout(() => {
83
+ signal?.removeEventListener("abort", abort);
84
+ resolve();
85
+ }, ms);
86
+ const abort = () => {
87
+ clearTimeout(timer);
88
+ reject(signal?.reason);
89
+ };
90
+ signal?.addEventListener("abort", abort, { once: true });
91
+ });
92
+ }
93
+ /** Whether a failed `follow` request is worth retrying. */
94
+ function transient(error) {
95
+ return !(error instanceof AidyRequestError) || error.status === 408 || error.status === 429 || error.status >= 500;
96
+ }
97
+ function createClient(options) {
98
+ const base = `${options.baseUrl.replace(/\/$/, "")}${API_PREFIX}`;
99
+ const fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
100
+ async function request(path, init = {}) {
101
+ const headers = new Headers(await options.headers?.());
102
+ if (init.body !== void 0) headers.set("Content-Type", "application/json");
103
+ new Headers(init.headers).forEach((value, key) => {
104
+ headers.set(key, value);
105
+ });
106
+ const response = await fetcher(`${base}${path}`, {
107
+ ...init,
108
+ headers
109
+ });
110
+ if (!response.ok) {
111
+ const text = await response.text().catch(() => "");
112
+ let body = text;
113
+ try {
114
+ body = JSON.parse(text);
115
+ } catch {}
116
+ throw new AidyRequestError(response.status, body);
117
+ }
118
+ return response;
119
+ }
120
+ async function json(path, init) {
121
+ return (await request(path, init)).json();
122
+ }
123
+ async function* events(response) {
124
+ if (!response.body) throw new AidyRequestError(response.status, "no response body");
125
+ for await (const frame of readSse(response.body)) if (frame.data !== "") yield parseEvent(frame);
126
+ }
127
+ const thread = (id) => `/threads/${encodeURIComponent(id)}`;
128
+ return {
129
+ createThread() {
130
+ return json("/threads", {
131
+ method: "POST",
132
+ body: "{}"
133
+ });
134
+ },
135
+ listThreads(cursor) {
136
+ return json(cursor ? `/threads?cursor=${encodeURIComponent(cursor)}` : "/threads");
137
+ },
138
+ getThread(id) {
139
+ return json(thread(id));
140
+ },
141
+ async renameThread(id, title) {
142
+ await request(thread(id), {
143
+ method: "PATCH",
144
+ body: JSON.stringify({ title })
145
+ });
146
+ },
147
+ async deleteThread(id) {
148
+ await request(thread(id), { method: "DELETE" });
149
+ },
150
+ /** Starts a run. Leaving the iteration early detaches from it; the run goes on. */
151
+ run(threadId, input, init = {}) {
152
+ const runId = crypto.randomUUID();
153
+ const messageId = input.message === void 0 ? void 0 : crypto.randomUUID();
154
+ const body = {
155
+ threadId,
156
+ runId,
157
+ messages: messageId === void 0 || input.message === void 0 ? [] : [{
158
+ id: messageId,
159
+ role: "user",
160
+ content: input.message
161
+ }],
162
+ tools: [],
163
+ context: [],
164
+ ...input.resume ? { resume: input.resume } : {}
165
+ };
166
+ return {
167
+ runId,
168
+ ...messageId === void 0 ? {} : { messageId },
169
+ async *[Symbol.asyncIterator]() {
170
+ yield* events(await request(`${thread(threadId)}/runs`, {
171
+ method: "POST",
172
+ body: JSON.stringify(body),
173
+ headers: { Accept: "text/event-stream" },
174
+ ...init.signal ? { signal: init.signal } : {}
175
+ }));
176
+ }
177
+ };
178
+ },
179
+ /**
180
+ * Replays the thread's events after `after`, then follows them live. It reconnects with
181
+ * `Last-Event-ID` and exponential backoff until `signal` aborts, never yielding a seq twice.
182
+ */
183
+ async *follow(threadId, init) {
184
+ let last = init.after;
185
+ let retryMs = DEFAULT_RETRY_MS;
186
+ let failures = 0;
187
+ while (!init.signal?.aborted) {
188
+ try {
189
+ const response = await request(`${thread(threadId)}/events?after=${last}`, {
190
+ headers: {
191
+ Accept: "text/event-stream",
192
+ "Last-Event-ID": String(last)
193
+ },
194
+ ...init.signal ? { signal: init.signal } : {}
195
+ });
196
+ if (!response.body) throw new AidyRequestError(response.status, "no response body");
197
+ for await (const frame of readSse(response.body)) {
198
+ if (frame.retry !== void 0) retryMs = frame.retry;
199
+ if (frame.data === "") continue;
200
+ const event = parseEvent(frame);
201
+ failures = 0;
202
+ if (seqOf(event) <= last) continue;
203
+ last = seqOf(event);
204
+ yield event;
205
+ }
206
+ } catch (error) {
207
+ if (init.signal?.aborted) return;
208
+ if (error instanceof AidyProtocolError || !transient(error)) throw error;
209
+ }
210
+ if (init.signal?.aborted) return;
211
+ await sleep(Math.min(retryMs * 2 ** failures, MAX_RETRY_MS), init.signal).catch(() => {});
212
+ failures += 1;
213
+ }
214
+ },
215
+ async cancel(runId) {
216
+ await request(`/runs/${encodeURIComponent(runId)}/cancel`, { method: "POST" });
217
+ },
218
+ async catalog() {
219
+ return (await json("/catalog")).operations;
220
+ },
221
+ search(query, init = {}) {
222
+ const params = new URLSearchParams({ q: query });
223
+ if (init.limit !== void 0) params.set("limit", String(init.limit));
224
+ if (init.types?.length) params.set("types", init.types.join(","));
225
+ return json(`/search?${params}`, init.signal ? { signal: init.signal } : {});
226
+ },
227
+ getSettings() {
228
+ return json("/settings");
229
+ },
230
+ putSettings(settings) {
231
+ return json("/settings", {
232
+ method: "PUT",
233
+ body: JSON.stringify(settings)
234
+ });
235
+ }
236
+ };
237
+ }
238
+ // src/reducer.ts
239
+ const initialThreadState = {
240
+ lastSeq: 0,
241
+ status: "idle",
242
+ runId: null,
243
+ items: [],
244
+ interrupts: [],
245
+ citations: {},
246
+ opens: [],
247
+ context: null,
248
+ retry: null,
249
+ error: null,
250
+ usage: []
251
+ };
252
+ function aidyMeta(metadata) {
253
+ return metadata?.[METADATA_KEY];
254
+ }
255
+ /** An event's `metadata.aidy` without the `seq` every event carries. */
256
+ function eventMeta(event) {
257
+ const { seq: _, ...meta } = event.metadata.aidy;
258
+ return meta;
259
+ }
260
+ function text(content) {
261
+ return typeof content === "string" ? content : content.map((part) => part.type === "text" ? part.text : "").join("");
262
+ }
263
+ function upsert(items, id, kind, update) {
264
+ const index = items.findIndex((item) => item.id === id && item.kind === kind);
265
+ if (index === -1) return [...items, update(void 0)];
266
+ const next = [...items];
267
+ next[index] = update(items[index]);
268
+ return next;
269
+ }
270
+ function toolItem(id, name) {
271
+ return {
272
+ kind: "tool",
273
+ id,
274
+ name,
275
+ meta: null,
276
+ arguments: null,
277
+ status: "running",
278
+ error: null,
279
+ deduplicated: false,
280
+ result: null
281
+ };
282
+ }
283
+ function parseArguments(json) {
284
+ try {
285
+ const value = JSON.parse(json);
286
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
287
+ } catch {
288
+ return null;
289
+ }
290
+ }
291
+ /** Reads an AG-UI interrupt as one of aidy's three kinds. */
292
+ function openInterrupt(interrupt) {
293
+ const base = {
294
+ id: interrupt.id,
295
+ interrupt
296
+ };
297
+ const meta = aidyMeta(interrupt.metadata);
298
+ if (interrupt.reason === InterruptReason.approval) {
299
+ const parsed = ApprovalInterruptMeta.safeParse(meta);
300
+ if (parsed.success) return {
301
+ ...base,
302
+ kind: "approval",
303
+ meta: parsed.data
304
+ };
305
+ } else if (interrupt.reason === InterruptReason.input) {
306
+ const parsed = InputInterruptMeta.safeParse(meta);
307
+ if (parsed.success) return {
308
+ ...base,
309
+ kind: "input",
310
+ form: parsed.data.form
311
+ };
312
+ } else if (interrupt.reason === InterruptReason.task) {
313
+ const parsed = TaskInterruptMeta.safeParse(meta);
314
+ if (parsed.success) return {
315
+ ...base,
316
+ kind: "task",
317
+ ...parsed.data,
318
+ progress: null
319
+ };
320
+ }
321
+ return {
322
+ ...base,
323
+ kind: "other"
324
+ };
325
+ }
326
+ function addUserMessages(state, input) {
327
+ let items = state.items;
328
+ for (const message of input?.messages ?? []) if (message.role === "user" && !items.some((item) => item.id === message.id)) items = [...items, {
329
+ kind: "user",
330
+ id: message.id,
331
+ text: text(message.content)
332
+ }];
333
+ const answered = new Set(input?.resume?.map((entry) => entry.interruptId));
334
+ return {
335
+ ...state,
336
+ items,
337
+ interrupts: state.interrupts.filter((open) => !answered.has(open.id))
338
+ };
339
+ }
340
+ function endStreaming(items) {
341
+ return items.some((item) => item.kind === "assistant" && item.streaming) ? items.map((item) => item.kind === "assistant" && item.streaming ? {
342
+ ...item,
343
+ streaming: false
344
+ } : item) : items;
345
+ }
346
+ function applyCustom(state, name, value, seq) {
347
+ if (!(name in CustomEvents)) return state;
348
+ const parsed = CustomEvents[name].safeParse(value);
349
+ if (!parsed.success) return state;
350
+ const data = parsed.data;
351
+ switch (name) {
352
+ case "aidy.ui.open": return {
353
+ ...state,
354
+ opens: [...state.opens, {
355
+ seq,
356
+ path: data.path
357
+ }]
358
+ };
359
+ case "aidy.citation": {
360
+ const { messageId, hits } = data;
361
+ return {
362
+ ...state,
363
+ citations: {
364
+ ...state.citations,
365
+ [messageId]: hits
366
+ }
367
+ };
368
+ }
369
+ case "aidy.context": return {
370
+ ...state,
371
+ context: data
372
+ };
373
+ case "aidy.model.retry": return {
374
+ ...state,
375
+ retry: data
376
+ };
377
+ case "aidy.message.discard": {
378
+ const { messageId } = data;
379
+ return {
380
+ ...state,
381
+ items: state.items.filter((item) => item.id !== messageId)
382
+ };
383
+ }
384
+ case "aidy.task": {
385
+ const progress = data;
386
+ return {
387
+ ...state,
388
+ interrupts: state.interrupts.map((open) => open.kind === "task" && open.taskId === progress.taskId ? {
389
+ ...open,
390
+ progress
391
+ } : open)
392
+ };
393
+ }
394
+ default: return state;
395
+ }
396
+ }
397
+ function apply(state, event) {
398
+ switch (event.type) {
399
+ case EventType.RUN_STARTED: return addUserMessages({
400
+ ...state,
401
+ status: "running",
402
+ runId: event.runId,
403
+ error: null,
404
+ retry: null
405
+ }, event.input);
406
+ case EventType.RUN_FINISHED: {
407
+ const outcome = event.outcome ?? { type: "success" };
408
+ return {
409
+ ...state,
410
+ status: outcome.type === "interrupt" ? "interrupted" : outcome.type === "cancelled" ? "cancelled" : "succeeded",
411
+ interrupts: outcome.type === "interrupt" ? outcome.interrupts.map(openInterrupt) : [],
412
+ items: endStreaming(state.items),
413
+ retry: null,
414
+ usage: event.usage ?? []
415
+ };
416
+ }
417
+ case EventType.RUN_ERROR: return {
418
+ ...state,
419
+ status: "failed",
420
+ error: {
421
+ code: event.code ?? null,
422
+ message: event.message
423
+ },
424
+ items: endStreaming(state.items),
425
+ retry: null,
426
+ usage: event.usage ?? []
427
+ };
428
+ case EventType.TEXT_MESSAGE_START:
429
+ if (event.role === "user") return {
430
+ ...state,
431
+ items: upsert(state.items, event.messageId, "user", (current) => ({
432
+ kind: "user",
433
+ id: event.messageId,
434
+ text: current?.text ?? ""
435
+ }))
436
+ };
437
+ return {
438
+ ...state,
439
+ retry: null,
440
+ items: upsert(state.items, event.messageId, "assistant", (current) => ({
441
+ kind: "assistant",
442
+ id: event.messageId,
443
+ text: current?.text ?? "",
444
+ streaming: true
445
+ }))
446
+ };
447
+ case EventType.TEXT_MESSAGE_CONTENT: {
448
+ const user = state.items.find((item) => item.id === event.messageId)?.kind === "user";
449
+ return {
450
+ ...state,
451
+ retry: null,
452
+ items: user ? upsert(state.items, event.messageId, "user", (current) => ({
453
+ kind: "user",
454
+ id: event.messageId,
455
+ text: (current?.text ?? "") + event.delta
456
+ })) : upsert(state.items, event.messageId, "assistant", (current) => ({
457
+ kind: "assistant",
458
+ id: event.messageId,
459
+ text: (current?.text ?? "") + event.delta,
460
+ streaming: true
461
+ }))
462
+ };
463
+ }
464
+ case EventType.TEXT_MESSAGE_END: return {
465
+ ...state,
466
+ items: state.items.map((item) => item.id === event.messageId && item.kind === "assistant" ? {
467
+ ...item,
468
+ streaming: false
469
+ } : item)
470
+ };
471
+ case EventType.TOOL_CALL_START: {
472
+ const meta = ToolCallMeta.safeParse(eventMeta(event));
473
+ return {
474
+ ...state,
475
+ items: upsert(state.items, event.toolCallId, "tool", (current) => ({
476
+ ...current ?? toolItem(event.toolCallId, event.toolCallName),
477
+ name: event.toolCallName,
478
+ meta: meta.success ? meta.data : null
479
+ }))
480
+ };
481
+ }
482
+ case EventType.TOOL_CALL_ARGS: return {
483
+ ...state,
484
+ items: upsert(state.items, event.toolCallId, "tool", (current) => ({
485
+ ...current ?? toolItem(event.toolCallId, ""),
486
+ arguments: parseArguments(event.delta)
487
+ }))
488
+ };
489
+ case EventType.TOOL_CALL_RESULT: {
490
+ const meta = ToolResultMeta.safeParse(eventMeta(event));
491
+ return {
492
+ ...state,
493
+ items: upsert(state.items, event.toolCallId, "tool", (current) => ({
494
+ ...current ?? toolItem(event.toolCallId, ""),
495
+ status: meta.success ? meta.data.status : "succeeded",
496
+ error: meta.success ? meta.data.error ?? null : null,
497
+ deduplicated: meta.success && meta.data.deduplicated === true,
498
+ result: text(event.content)
499
+ }))
500
+ };
501
+ }
502
+ case EventType.ACTIVITY_SNAPSHOT: {
503
+ const content = ProgressContent.safeParse(event.content);
504
+ if (event.activityType !== PROGRESS_ACTIVITY || !content.success) return state;
505
+ return {
506
+ ...state,
507
+ items: upsert(state.items, event.messageId, "progress", () => ({
508
+ kind: "progress",
509
+ id: event.messageId,
510
+ message: content.data.message
511
+ }))
512
+ };
513
+ }
514
+ case EventType.CUSTOM: return applyCustom(state, event.name, event.value, event.metadata.aidy.seq);
515
+ default: return state;
516
+ }
517
+ }
518
+ /** Applies one event. Pure; an event at or below `lastSeq` (a replay) changes nothing. */
519
+ function reduceThread(state, event) {
520
+ const seq = event.metadata.aidy.seq;
521
+ if (seq <= state.lastSeq) return state;
522
+ return {
523
+ ...apply(state, event),
524
+ lastSeq: seq
525
+ };
526
+ }
527
+ /** Shows a message the user just sent before the run echoes it; the echo is then ignored. */
528
+ function appendUserMessage(state, message) {
529
+ return state.items.some((item) => item.id === message.id) ? state : {
530
+ ...state,
531
+ items: [...state.items, message]
532
+ };
533
+ }
534
+ // src/resume.ts
535
+ /** Answers an approval, echoing the `argsHash` the user saw so aidy runs exactly those arguments. */
536
+ function answerApproval(interrupt, approved) {
537
+ return {
538
+ interruptId: interrupt.id,
539
+ status: "resolved",
540
+ payload: { approved },
541
+ metadata: { [METADATA_KEY]: { argsHash: interrupt.meta.argsHash } }
542
+ };
543
+ }
544
+ /** Answers a form. Throws when the answers fail `checkAnswers`. */
545
+ function answerForm(interrupt, answers) {
546
+ const issues = checkAnswers(interrupt.form, answers);
547
+ if (issues.length > 0) throw new Error(`invalid answers: ${issues.map((issue) => `${issue.question}: ${issue.message}`).join("; ")}`);
548
+ return {
549
+ interruptId: interrupt.id,
550
+ status: "resolved",
551
+ payload: { answers }
552
+ };
553
+ }
554
+ /** Cancels every open interrupt, as a new user message must. */
555
+ function cancelAll(interrupts) {
556
+ return interrupts.map((open) => ({
557
+ interruptId: open.id,
558
+ status: "cancelled"
559
+ }));
560
+ }
561
+ export { AidyProtocolError, AidyRequestError, answerApproval, answerForm, appendUserMessage, cancelAll, createClient, initialThreadState, openInterrupt, reduceThread };
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@aidy-dev/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Typed client of the aidy HTTP API and a reducer from its AG-UI events to thread state.",
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/client"
11
+ },
12
+ "type": "module",
13
+ "sideEffects": false,
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "exports": {
18
+ ".": {
19
+ "@aidy-dev/source": "./src/index.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "dependencies": {
28
+ "@ag-ui/core": "^1.0.5",
29
+ "@aidy-dev/spec": "0.1.0"
30
+ },
31
+ "scripts": {
32
+ "build": "tsdown",
33
+ "typecheck": "tsc -p .",
34
+ "test": "vitest run"
35
+ }
6
36
  }