@aidy-dev/spec 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.
@@ -0,0 +1,243 @@
1
+ import { Effect, OPERATION_NAME } from "./catalog.js";
2
+ import { SearchHit } from "./search.js";
3
+ import * as z from "zod";
4
+ // src/protocol.ts
5
+ /**
6
+ * aidy's AG-UI 1.0 profile: interrupts, forms, tool metadata and custom events.
7
+ * See spec/protocol.md.
8
+ */
9
+ const PROTOCOL_VERSION = "aidy/0";
10
+ const API_PREFIX = "/aidy/v0";
11
+ /** Key under which aidy's data sits in AG-UI `metadata`. */
12
+ const METADATA_KEY = "aidy";
13
+ /** `metadata.aidy` on every event. `seq` increases per thread and is the SSE id. */
14
+ const EventMeta = z.strictObject({ seq: z.int().positive() });
15
+ const InterruptReason = {
16
+ approval: "aidy:approval",
17
+ input: "aidy:input",
18
+ task: "aidy:task"
19
+ };
20
+ const APPROVAL_TTL_SECONDS = 900;
21
+ const RunErrorCode = z.enum([
22
+ "model_unavailable",
23
+ "max_steps",
24
+ "open_interrupts",
25
+ "history_conflict",
26
+ "invalid_interaction",
27
+ "internal"
28
+ ]);
29
+ const ToolErrorCode = z.string().regex(/^(invalid_arguments|unresolved_reference|repeated_call|already_attempted|not_executed|credential_expired|timeout|http_\d{3})$/);
30
+ const operationName = z.string().regex(OPERATION_NAME);
31
+ /**
32
+ * `TOOL_CALL_START.metadata.aidy`: the call's operation, beside the event's `seq` (which a
33
+ * reader may have taken out already). Built-in tools (`search`, `request_input`) use their own
34
+ * name as op.
35
+ */
36
+ const ToolCallMeta = EventMeta.partial().extend({
37
+ op: operationName,
38
+ title: z.string().min(1),
39
+ effect: Effect
40
+ });
41
+ /** `TOOL_CALL_RESULT.metadata.aidy`: the call's outcome, beside the event's `seq`. */
42
+ const ToolResultMeta = EventMeta.partial().extend({
43
+ status: z.enum(["succeeded", "failed"]),
44
+ error: z.strictObject({
45
+ code: ToolErrorCode,
46
+ message: z.string()
47
+ }).optional(),
48
+ deduplicated: z.boolean().optional()
49
+ });
50
+ const ApprovalImpact = z.strictObject({
51
+ title: z.string().min(1),
52
+ target: z.string().nullable(),
53
+ effect: Effect,
54
+ risk: z.enum([
55
+ "low",
56
+ "medium",
57
+ "high"
58
+ ]).nullable(),
59
+ costHint: z.string().nullable(),
60
+ changes: z.array(z.string())
61
+ });
62
+ /** `Interrupt.metadata.aidy` for `aidy:approval`. */
63
+ const ApprovalInterruptMeta = z.strictObject({
64
+ op: operationName,
65
+ arguments: z.record(z.string(), z.unknown()),
66
+ argsHash: z.string().min(43),
67
+ impact: ApprovalImpact
68
+ }).meta({
69
+ id: "approval-interrupt",
70
+ title: "Approval interrupt metadata"
71
+ });
72
+ const ApprovalPayload = z.strictObject({ approved: z.boolean() });
73
+ /** `ResumeEntry.metadata.aidy` answering an approval: the hash the user saw. */
74
+ const ApprovalResumeMeta = z.strictObject({ argsHash: z.string().min(43) });
75
+ const APPROVAL_RESPONSE_SCHEMA = {
76
+ type: "object",
77
+ properties: { approved: { type: "boolean" } },
78
+ required: ["approved"],
79
+ additionalProperties: false
80
+ };
81
+ const FormOption = z.strictObject({
82
+ id: z.string().min(1),
83
+ label: z.string().min(1),
84
+ description: z.string().optional(),
85
+ recommended: z.boolean().optional()
86
+ });
87
+ const FormQuestion = z.discriminatedUnion("kind", [z.strictObject({
88
+ id: z.string().min(1),
89
+ prompt: z.string().min(1),
90
+ kind: z.literal("text"),
91
+ required: z.boolean(),
92
+ placeholder: z.string().optional(),
93
+ default: z.string().optional()
94
+ }), z.strictObject({
95
+ id: z.string().min(1),
96
+ prompt: z.string().min(1),
97
+ kind: z.literal("choice"),
98
+ required: z.boolean(),
99
+ options: z.array(FormOption).min(1),
100
+ multiple: z.boolean().optional(),
101
+ allowCustom: z.boolean().optional(),
102
+ default: z.union([z.string(), z.array(z.string())]).optional()
103
+ })]);
104
+ const MAX_FORM_QUESTIONS = 24;
105
+ const Form = z.strictObject({
106
+ prompt: z.string().min(1),
107
+ questions: z.array(FormQuestion).min(1).max(24)
108
+ }).refine((form) => new Set(form.questions.map((question) => question.id)).size === form.questions.length, "question ids must be unique").meta({
109
+ id: "form",
110
+ title: "Form"
111
+ });
112
+ const ChoiceAnswer = z.strictObject({
113
+ selected: z.array(z.string()),
114
+ custom: z.string().optional()
115
+ });
116
+ const FormAnswers = z.strictObject({ answers: z.record(z.string(), z.union([z.string(), ChoiceAnswer])) }).meta({
117
+ id: "form-answers",
118
+ title: "Form resume payload"
119
+ });
120
+ /** `Interrupt.metadata.aidy` for `aidy:input`. */
121
+ const InputInterruptMeta = z.strictObject({ form: Form });
122
+ /** `Interrupt.metadata.aidy` for `aidy:task`. */
123
+ const TaskInterruptMeta = z.strictObject({
124
+ taskId: z.string().min(1),
125
+ op: operationName
126
+ });
127
+ /** The AG-UI `responseSchema` of a form interrupt. */
128
+ function formResponseSchema(form) {
129
+ const properties = {};
130
+ for (const question of form.questions) properties[question.id] = question.kind === "text" ? { type: "string" } : {
131
+ type: "object",
132
+ properties: {
133
+ selected: {
134
+ type: "array",
135
+ items: { enum: question.options.map((option) => option.id) }
136
+ },
137
+ ...question.allowCustom ? { custom: { type: "string" } } : {}
138
+ },
139
+ required: ["selected"],
140
+ additionalProperties: false
141
+ };
142
+ return {
143
+ type: "object",
144
+ properties: { answers: {
145
+ type: "object",
146
+ properties,
147
+ required: form.questions.filter((q) => q.required).map((q) => q.id),
148
+ additionalProperties: false
149
+ } },
150
+ required: ["answers"],
151
+ additionalProperties: false
152
+ };
153
+ }
154
+ /** Validates a form answer. An empty list means it is acceptable. */
155
+ function checkAnswers(form, answers) {
156
+ const issues = [];
157
+ const questions = new Map(form.questions.map((question) => [question.id, question]));
158
+ for (const id of Object.keys(answers)) if (!questions.has(id)) issues.push({
159
+ question: id,
160
+ message: "unknown question"
161
+ });
162
+ for (const question of form.questions) {
163
+ const answer = answers[question.id];
164
+ if (question.kind === "text") {
165
+ if (answer !== void 0 && typeof answer !== "string") issues.push({
166
+ question: question.id,
167
+ message: "expected text"
168
+ });
169
+ else if (question.required && !answer?.trim()) issues.push({
170
+ question: question.id,
171
+ message: "required"
172
+ });
173
+ continue;
174
+ }
175
+ if (answer === void 0) {
176
+ if (question.required) issues.push({
177
+ question: question.id,
178
+ message: "required"
179
+ });
180
+ continue;
181
+ }
182
+ if (typeof answer === "string") {
183
+ issues.push({
184
+ question: question.id,
185
+ message: "expected a choice"
186
+ });
187
+ continue;
188
+ }
189
+ const known = new Set(question.options.map((option) => option.id));
190
+ const unknown = answer.selected.filter((id) => !known.has(id));
191
+ if (unknown.length > 0) issues.push({
192
+ question: question.id,
193
+ message: `unknown options: ${unknown.join(", ")}`
194
+ });
195
+ const custom = answer.custom?.trim();
196
+ if (custom && !question.allowCustom) issues.push({
197
+ question: question.id,
198
+ message: "custom answers are not allowed"
199
+ });
200
+ const count = answer.selected.length + (custom ? 1 : 0);
201
+ if (count === 0 && question.required) issues.push({
202
+ question: question.id,
203
+ message: "required"
204
+ });
205
+ else if (count > 1 && !question.multiple) issues.push({
206
+ question: question.id,
207
+ message: "only one answer is allowed"
208
+ });
209
+ }
210
+ return issues;
211
+ }
212
+ const CustomEvents = {
213
+ "aidy.ui.open": z.strictObject({ path: z.string().regex(/^\/(?!\/)/) }),
214
+ "aidy.citation": z.strictObject({
215
+ messageId: z.string().min(1),
216
+ hits: z.array(SearchHit).min(1)
217
+ }),
218
+ "aidy.context": z.strictObject({
219
+ usedTokens: z.int().nonnegative(),
220
+ budgetTokens: z.int().positive(),
221
+ source: z.enum(["estimated", "provider"])
222
+ }),
223
+ "aidy.model.retry": z.strictObject({
224
+ step: z.int().positive(),
225
+ attempt: z.int().positive(),
226
+ maxAttempts: z.int().positive(),
227
+ reason: z.string().min(1)
228
+ }),
229
+ "aidy.message.discard": z.strictObject({ messageId: z.string().min(1) }),
230
+ "aidy.task": z.strictObject({
231
+ taskId: z.string().min(1),
232
+ status: z.enum([
233
+ "running",
234
+ "succeeded",
235
+ "failed",
236
+ "cancelled"
237
+ ]),
238
+ message: z.string().optional()
239
+ })
240
+ };
241
+ const PROGRESS_ACTIVITY = "aidy.progress";
242
+ const ProgressContent = z.strictObject({ message: z.string().min(1) });
243
+ export { API_PREFIX, APPROVAL_RESPONSE_SCHEMA, APPROVAL_TTL_SECONDS, ApprovalImpact, ApprovalInterruptMeta, ApprovalPayload, ApprovalResumeMeta, ChoiceAnswer, CustomEvents, EventMeta, Form, FormAnswers, FormOption, FormQuestion, InputInterruptMeta, InterruptReason, MAX_FORM_QUESTIONS, METADATA_KEY, PROGRESS_ACTIVITY, PROTOCOL_VERSION, ProgressContent, RunErrorCode, TaskInterruptMeta, ToolCallMeta, ToolErrorCode, ToolResultMeta, checkAnswers, formResponseSchema };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Search: the source contract and federation. See spec/search.md.
3
+ */
4
+ import * as z from "zod";
5
+ export declare const SearchHit: z.ZodObject<{
6
+ type: z.ZodString;
7
+ id: z.ZodString;
8
+ title: z.ZodString;
9
+ excerpt: z.ZodOptional<z.ZodString>;
10
+ url: z.ZodString;
11
+ updatedAt: z.ZodOptional<z.ZodISODateTime>;
12
+ }, z.core.$strict>;
13
+ export type SearchHit = z.infer<typeof SearchHit>;
14
+ export declare const MAX_SEARCH_LIMIT = 50;
15
+ export declare const DEFAULT_SEARCH_LIMIT = 10;
16
+ export declare const SearchResponse: z.ZodObject<{
17
+ hits: z.ZodArray<z.ZodObject<{
18
+ type: z.ZodString;
19
+ id: z.ZodString;
20
+ title: z.ZodString;
21
+ excerpt: z.ZodOptional<z.ZodString>;
22
+ url: z.ZodString;
23
+ updatedAt: z.ZodOptional<z.ZodISODateTime>;
24
+ }, z.core.$strict>>;
25
+ }, z.core.$strict>;
26
+ export type SearchResponse = z.infer<typeof SearchResponse>;
27
+ /** The knowledge index's source name; host sources are named after their operation. */
28
+ export declare const KNOWLEDGE_SOURCE = "knowledge";
29
+ export declare const FederatedHit: z.ZodObject<{
30
+ type: z.ZodString;
31
+ id: z.ZodString;
32
+ title: z.ZodString;
33
+ excerpt: z.ZodOptional<z.ZodString>;
34
+ url: z.ZodString;
35
+ updatedAt: z.ZodOptional<z.ZodISODateTime>;
36
+ source: z.ZodString;
37
+ }, z.core.$strict>;
38
+ export type FederatedHit = z.infer<typeof FederatedHit>;
39
+ export declare const SearchFailure: z.ZodObject<{
40
+ source: z.ZodString;
41
+ code: z.ZodString;
42
+ }, z.core.$strict>;
43
+ export type SearchFailure = z.infer<typeof SearchFailure>;
44
+ export declare const FederatedSearchResponse: z.ZodObject<{
45
+ hits: z.ZodArray<z.ZodObject<{
46
+ type: z.ZodString;
47
+ id: z.ZodString;
48
+ title: z.ZodString;
49
+ excerpt: z.ZodOptional<z.ZodString>;
50
+ url: z.ZodString;
51
+ updatedAt: z.ZodOptional<z.ZodISODateTime>;
52
+ source: z.ZodString;
53
+ }, z.core.$strict>>;
54
+ failed: z.ZodArray<z.ZodObject<{
55
+ source: z.ZodString;
56
+ code: z.ZodString;
57
+ }, z.core.$strict>>;
58
+ }, z.core.$strict>;
59
+ export type FederatedSearchResponse = z.infer<typeof FederatedSearchResponse>;
60
+ export interface SourceHits {
61
+ readonly source: string;
62
+ readonly hits: readonly SearchHit[];
63
+ }
64
+ /**
65
+ * Merges ranked hits from several sources by reciprocal rank fusion. A hit that
66
+ * several sources return (same type and id) keeps its first appearance and
67
+ * sums its scores.
68
+ */
69
+ export declare function fuse(sources: readonly SourceHits[], limit: number): FederatedHit[];
package/dist/search.js ADDED
@@ -0,0 +1,63 @@
1
+ import { OPERATION_NAME } from "./catalog.js";
2
+ import * as z from "zod";
3
+ // src/search.ts
4
+ /**
5
+ * Search: the source contract and federation. See spec/search.md.
6
+ */
7
+ const SearchHit = z.strictObject({
8
+ type: z.string().regex(/^[a-z][a-z0-9_.-]{0,31}$/),
9
+ id: z.string().min(1),
10
+ title: z.string().min(1),
11
+ excerpt: z.string().max(300).optional(),
12
+ url: z.string().regex(/^(\/(?!\/)|https?:\/\/)/, "must be a product path or an http(s) URL"),
13
+ updatedAt: z.iso.datetime({ offset: true }).optional()
14
+ }).meta({
15
+ id: "search-hit",
16
+ title: "SearchHit"
17
+ });
18
+ const MAX_SEARCH_LIMIT = 50;
19
+ const DEFAULT_SEARCH_LIMIT = 10;
20
+ const SearchResponse = z.strictObject({ hits: z.array(SearchHit).max(50) }).meta({
21
+ id: "search-response",
22
+ title: "Search source response"
23
+ });
24
+ /** The knowledge index's source name; host sources are named after their operation. */
25
+ const KNOWLEDGE_SOURCE = "knowledge";
26
+ const FederatedHit = SearchHit.extend({ source: z.string().regex(OPERATION_NAME) });
27
+ const SearchFailure = z.strictObject({
28
+ source: z.string().regex(OPERATION_NAME),
29
+ code: z.string().regex(/^(timeout|invalid_response|http_\d{3})$/)
30
+ });
31
+ const FederatedSearchResponse = z.strictObject({
32
+ hits: z.array(FederatedHit),
33
+ failed: z.array(SearchFailure)
34
+ }).meta({
35
+ id: "federated-search-response",
36
+ title: "Federated search response"
37
+ });
38
+ const RRF_K = 60;
39
+ /**
40
+ * Merges ranked hits from several sources by reciprocal rank fusion. A hit that
41
+ * several sources return (same type and id) keeps its first appearance and
42
+ * sums its scores.
43
+ */
44
+ function fuse(sources, limit) {
45
+ const merged = /* @__PURE__ */ new Map();
46
+ let order = 0;
47
+ for (const { source, hits } of sources) hits.forEach((hit, rank) => {
48
+ const key = `${hit.type}\u0000${hit.id}`;
49
+ const score = 1 / (RRF_K + rank + 1);
50
+ const existing = merged.get(key);
51
+ if (existing) existing.score += score;
52
+ else merged.set(key, {
53
+ hit: {
54
+ ...hit,
55
+ source
56
+ },
57
+ score,
58
+ order: order++
59
+ });
60
+ });
61
+ return [...merged.values()].sort((a, b) => b.score - a.score || a.order - b.order).slice(0, limit).map((entry) => entry.hit);
62
+ }
63
+ export { DEFAULT_SEARCH_LIMIT, FederatedHit, FederatedSearchResponse, KNOWLEDGE_SOURCE, MAX_SEARCH_LIMIT, SearchFailure, SearchHit, SearchResponse, fuse };
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@aidy-dev/spec",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "aidy's language-neutral contract: the x-aidy catalog, delegation assertions, search and the AG-UI profile.",
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/spec"
11
+ },
12
+ "type": "module",
13
+ "sideEffects": false,
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "exports": {
18
+ "./catalog": {
19
+ "@aidy-dev/source": "./src/catalog.ts",
20
+ "default": "./dist/catalog.js"
21
+ },
22
+ "./delegation": {
23
+ "@aidy-dev/source": "./src/delegation.ts",
24
+ "default": "./dist/delegation.js"
25
+ },
26
+ "./protocol": {
27
+ "@aidy-dev/source": "./src/protocol.ts",
28
+ "default": "./dist/protocol.js"
29
+ },
30
+ "./search": {
31
+ "@aidy-dev/source": "./src/search.ts",
32
+ "default": "./dist/search.js"
33
+ },
34
+ "./package.json": "./package.json"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "dependencies": {
40
+ "zod": "^4.6.7"
41
+ },
42
+ "devDependencies": {
43
+ "@ag-ui/core": "^1.0.5"
44
+ },
45
+ "scripts": {
46
+ "build": "tsdown",
47
+ "typecheck": "tsc -p .",
48
+ "test": "vitest run",
49
+ "schemas": "node scripts/schemas.ts"
50
+ }
6
51
  }