@nylorun/core 0.0.0-bootstrap → 0.2.0-beta

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 (72) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +192 -0
  3. package/README.md +16 -0
  4. package/dist/compatibility.d.ts +3 -0
  5. package/dist/compatibility.js +3 -0
  6. package/dist/contracts.d.ts +330 -0
  7. package/dist/contracts.js +366 -0
  8. package/dist/define.d.ts +32 -0
  9. package/dist/define.js +15 -0
  10. package/dist/definition/assemble.d.ts +29 -0
  11. package/dist/definition/assemble.js +120 -0
  12. package/dist/definition/bind-agent.d.ts +8 -0
  13. package/dist/definition/bind-agent.js +62 -0
  14. package/dist/definition/bind-tool.d.ts +4 -0
  15. package/dist/definition/bind-tool.js +25 -0
  16. package/dist/definition/binding.d.ts +15 -0
  17. package/dist/definition/binding.js +9 -0
  18. package/dist/definition/bound.d.ts +34 -0
  19. package/dist/definition/bound.js +1 -0
  20. package/dist/definition/builder.d.ts +66 -0
  21. package/dist/definition/builder.js +218 -0
  22. package/dist/definition/declaration.d.ts +10 -0
  23. package/dist/definition/declaration.js +93 -0
  24. package/dist/definition/from.d.ts +13 -0
  25. package/dist/definition/from.js +294 -0
  26. package/dist/definition/helpers.d.ts +23 -0
  27. package/dist/definition/helpers.js +33 -0
  28. package/dist/definition/implementations.d.ts +16 -0
  29. package/dist/definition/implementations.js +3 -0
  30. package/dist/definition/manifest.d.ts +13 -0
  31. package/dist/definition/manifest.js +60 -0
  32. package/dist/definition/output-contract.d.ts +6 -0
  33. package/dist/definition/output-contract.js +12 -0
  34. package/dist/definition/schema-json.d.ts +3 -0
  35. package/dist/definition/schema-json.js +22 -0
  36. package/dist/definition/schema.d.ts +16 -0
  37. package/dist/definition/schema.js +284 -0
  38. package/dist/definition/skill-tools.d.ts +3 -0
  39. package/dist/definition/skill-tools.js +56 -0
  40. package/dist/definition/tool-error.d.ts +9 -0
  41. package/dist/definition/tool-error.js +20 -0
  42. package/dist/errors.d.ts +17 -0
  43. package/dist/errors.js +22 -0
  44. package/dist/index.d.ts +10 -0
  45. package/dist/index.js +1 -0
  46. package/dist/types/agent.d.ts +10 -0
  47. package/dist/types/agent.js +1 -0
  48. package/dist/types/dynamics.d.ts +53 -0
  49. package/dist/types/dynamics.js +1 -0
  50. package/dist/types/manifest.d.ts +57 -0
  51. package/dist/types/manifest.js +1 -0
  52. package/dist/types/middleware.d.ts +92 -0
  53. package/dist/types/middleware.js +1 -0
  54. package/dist/types/model.d.ts +184 -0
  55. package/dist/types/model.js +1 -0
  56. package/dist/types/observe.d.ts +180 -0
  57. package/dist/types/observe.js +1 -0
  58. package/dist/types/shared.d.ts +25 -0
  59. package/dist/types/shared.js +1 -0
  60. package/dist/types/tool.d.ts +194 -0
  61. package/dist/types/tool.js +1 -0
  62. package/dist/types/transcript.d.ts +65 -0
  63. package/dist/types/transcript.js +1 -0
  64. package/dist/utils/canonical.d.ts +1 -0
  65. package/dist/utils/canonical.js +10 -0
  66. package/dist/utils/hash.d.ts +3 -0
  67. package/dist/utils/hash.js +7 -0
  68. package/dist/utils/immutable.d.ts +6 -0
  69. package/dist/utils/immutable.js +76 -0
  70. package/package.json +57 -7
  71. package/index.js +0 -1
  72. package/publish.out +0 -0
@@ -0,0 +1,366 @@
1
+ /** Public wire contracts only. Never import checkpoint or engine modules here. */
2
+ import { z } from "zod";
3
+ export const PROTOCOL_VERSION = 1;
4
+ export const RequestIdSchema = z.string().min(1);
5
+ export const IdempotencyKeySchema = z.string().min(1).max(256);
6
+ const jsonObject = z.record(z.string(), z.unknown());
7
+ const mcpServerSchema = z.discriminatedUnion("type", [
8
+ z
9
+ .object({
10
+ name: z.string().min(1),
11
+ type: z.literal("stdio"),
12
+ command: z.string().min(1),
13
+ args: z.array(z.string()).optional(),
14
+ env: z.record(z.string(), z.string()).optional(),
15
+ cwd: z.string().optional(),
16
+ })
17
+ .strict(),
18
+ z
19
+ .object({
20
+ name: z.string().min(1),
21
+ type: z.literal("streamable-http"),
22
+ url: z.string().min(1),
23
+ headers: z.record(z.string(), z.string()).optional(),
24
+ })
25
+ .strict(),
26
+ z
27
+ .object({
28
+ name: z.string().min(1),
29
+ type: z.literal("sse"),
30
+ url: z.string().min(1),
31
+ headers: z.record(z.string(), z.string()).optional(),
32
+ })
33
+ .strict(),
34
+ ]);
35
+ const skillManifestSchema = z
36
+ .object({
37
+ name: z.string().min(1),
38
+ description: z.string().min(1),
39
+ })
40
+ .strict();
41
+ const toolManifestSchema = z
42
+ .object({
43
+ name: z.string().min(1),
44
+ description: z.string().optional(),
45
+ inputSchema: jsonObject,
46
+ outputSchema: jsonObject.optional(),
47
+ })
48
+ .strict();
49
+ export const AgentManifestSchema = z
50
+ .object({
51
+ manifestSchemaVersion: z.literal(3),
52
+ id: z.string().min(1),
53
+ name: z.string().min(1).optional(),
54
+ description: z.string().optional(),
55
+ metadata: jsonObject.optional(),
56
+ outputSchema: jsonObject.optional(),
57
+ capabilities: z.array(z
58
+ .object({
59
+ id: z.string().min(1),
60
+ type: z.enum(["agent", "agent-plugin"]),
61
+ name: z.string().min(1).optional(),
62
+ description: z.string().optional(),
63
+ metadata: jsonObject.optional(),
64
+ instructions: z.array(z.string()).optional(),
65
+ skills: z.record(z.string(), skillManifestSchema).optional(),
66
+ tools: z.array(toolManifestSchema).optional(),
67
+ mcpServers: z.record(z.string(), mcpServerSchema).optional(),
68
+ beforeModelCall: z.boolean().optional(),
69
+ afterModelCall: z.boolean().optional(),
70
+ })
71
+ .strict()),
72
+ runtime: z.object({}).strict().optional(),
73
+ })
74
+ .strict()
75
+ .superRefine((manifest, ctx) => {
76
+ const ids = new Set();
77
+ const names = new Set();
78
+ const servers = new Set();
79
+ const skills = new Set();
80
+ for (const capability of manifest.capabilities) {
81
+ if (ids.has(capability.id))
82
+ ctx.addIssue({ code: "custom", message: "Duplicate capability id" });
83
+ ids.add(capability.id);
84
+ for (const tool of capability.tools ?? []) {
85
+ if (names.has(tool.name))
86
+ ctx.addIssue({
87
+ code: "custom",
88
+ message: "Tool names must be unique",
89
+ });
90
+ names.add(tool.name);
91
+ }
92
+ if (capability.skills && Object.keys(capability.skills).length === 0)
93
+ ctx.addIssue({
94
+ code: "custom",
95
+ message: "skills must be omitted when a capability declares no skills",
96
+ });
97
+ for (const [key, skill] of Object.entries(capability.skills ?? {})) {
98
+ if (key !== skill.name)
99
+ ctx.addIssue({
100
+ code: "custom",
101
+ message: `skills key '${key}' must equal the skill name`,
102
+ });
103
+ if (skills.has(skill.name))
104
+ ctx.addIssue({
105
+ code: "custom",
106
+ message: `Duplicate skill '${skill.name}'`,
107
+ });
108
+ skills.add(skill.name);
109
+ }
110
+ if (capability.mcpServers && Object.keys(capability.mcpServers).length === 0)
111
+ ctx.addIssue({
112
+ code: "custom",
113
+ message: "mcpServers must be omitted when a capability declares no servers",
114
+ });
115
+ for (const [key, server] of Object.entries(capability.mcpServers ?? {})) {
116
+ if (key !== server.name)
117
+ ctx.addIssue({
118
+ code: "custom",
119
+ message: `mcpServers key '${key}' must equal the server name`,
120
+ });
121
+ if (servers.has(server.name))
122
+ ctx.addIssue({
123
+ code: "custom",
124
+ message: `Duplicate MCP server '${server.name}'`,
125
+ });
126
+ servers.add(server.name);
127
+ }
128
+ }
129
+ });
130
+ const absolutePath = z.string().min(1).refine((value) => value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value), { message: "plugin root must be an absolute path" });
131
+ export const PutAgentRequestSchema = z
132
+ .object({
133
+ requestId: RequestIdSchema,
134
+ manifest: AgentManifestSchema,
135
+ implementationVersion: z.string().min(1),
136
+ pluginRoots: z.record(z.string(), absolutePath).optional(),
137
+ })
138
+ .strict();
139
+ export const CredentialSelectionSchema = z
140
+ .object({
141
+ serverName: z.string().min(1),
142
+ credentialId: z.string().min(1),
143
+ })
144
+ .strict();
145
+ export const PutSessionRequestSchema = z
146
+ .object({
147
+ requestId: RequestIdSchema,
148
+ agentId: z.string().min(1),
149
+ ownerUserId: z.string().min(1),
150
+ info: jsonObject.optional(),
151
+ vaultIds: z.array(z.string().min(1)).optional(),
152
+ credentialSelections: z.array(CredentialSelectionSchema).optional(),
153
+ })
154
+ .strict();
155
+ const vaultWriteBase = {
156
+ requestId: RequestIdSchema,
157
+ idempotencyKey: IdempotencyKeySchema,
158
+ };
159
+ const tokenEndpointAuthSchema = z.discriminatedUnion("type", [
160
+ z.object({ type: z.literal("none") }).strict(),
161
+ z
162
+ .object({
163
+ type: z.literal("client_secret_basic"),
164
+ clientSecret: z.string().min(1),
165
+ })
166
+ .strict(),
167
+ z
168
+ .object({
169
+ type: z.literal("client_secret_post"),
170
+ clientSecret: z.string().min(1),
171
+ })
172
+ .strict(),
173
+ ]);
174
+ const oauthRefreshSchema = z
175
+ .object({
176
+ tokenEndpoint: z.string().min(1),
177
+ clientId: z.string().min(1),
178
+ refreshToken: z.string().min(1),
179
+ tokenEndpointAuth: tokenEndpointAuthSchema,
180
+ })
181
+ .strict();
182
+ export const CreateVaultRequestSchema = z
183
+ .object({
184
+ ...vaultWriteBase,
185
+ name: z.string().min(1),
186
+ ownerUserId: z.string().min(1),
187
+ metadata: z.record(z.string(), z.string()).optional(),
188
+ })
189
+ .strict();
190
+ export const CreateCredentialRequestSchema = z
191
+ .object({
192
+ ...vaultWriteBase,
193
+ name: z.string().min(1),
194
+ auth: z.discriminatedUnion("type", [
195
+ z
196
+ .object({
197
+ type: z.literal("bearer"),
198
+ url: z.string().min(1),
199
+ token: z.string().min(1),
200
+ })
201
+ .strict(),
202
+ z
203
+ .object({
204
+ type: z.literal("oauth"),
205
+ url: z.string().min(1),
206
+ accessToken: z.string().min(1),
207
+ expiresAt: z.string().min(1).nullable().optional(),
208
+ refresh: oauthRefreshSchema.optional(),
209
+ })
210
+ .strict(),
211
+ ]),
212
+ })
213
+ .strict();
214
+ export const RotateCredentialRequestSchema = z
215
+ .object({
216
+ ...vaultWriteBase,
217
+ auth: z.discriminatedUnion("type", [
218
+ z
219
+ .object({
220
+ type: z.literal("bearer"),
221
+ token: z.string().min(1),
222
+ })
223
+ .strict(),
224
+ z
225
+ .object({
226
+ type: z.literal("oauth"),
227
+ accessToken: z.string().min(1),
228
+ expiresAt: z.string().min(1).nullable().optional(),
229
+ })
230
+ .strict(),
231
+ ]),
232
+ })
233
+ .strict();
234
+ const commandBase = {
235
+ requestId: RequestIdSchema,
236
+ idempotencyKey: IdempotencyKeySchema,
237
+ };
238
+ export const MessageEventBodySchema = z
239
+ .object({
240
+ ...commandBase,
241
+ type: z.literal("message"),
242
+ content: z.string().min(1),
243
+ })
244
+ .strict();
245
+ export const ActionOutcomeSchema = z
246
+ .object({
247
+ value: z.unknown(),
248
+ statePatch: jsonObject.optional(),
249
+ })
250
+ .strict();
251
+ export const ActionResultCommandSchema = z
252
+ .object({
253
+ ...commandBase,
254
+ type: z.literal("action_result"),
255
+ actionId: z.string().min(1),
256
+ claimId: z.string().min(1),
257
+ generation: z.number().int().positive(),
258
+ outcome: ActionOutcomeSchema,
259
+ })
260
+ .strict();
261
+ export const SessionCommandSchema = z.discriminatedUnion("type", [
262
+ MessageEventBodySchema,
263
+ z
264
+ .object({
265
+ ...commandBase,
266
+ type: z.literal("approve"),
267
+ interactionId: z.string().min(1),
268
+ approved: z.boolean(),
269
+ })
270
+ .strict(),
271
+ z
272
+ .object({
273
+ ...commandBase,
274
+ type: z.literal("respond"),
275
+ interactionId: z.string().min(1),
276
+ value: z.unknown(),
277
+ })
278
+ .strict(),
279
+ z
280
+ .object({
281
+ ...commandBase,
282
+ type: z.literal("cancel"),
283
+ reason: z.string().optional(),
284
+ })
285
+ .strict(),
286
+ ActionResultCommandSchema,
287
+ ]);
288
+ export const SessionEventBodySchema = SessionCommandSchema;
289
+ export const LiveEventSchema = z
290
+ .object({
291
+ eventId: z.string(),
292
+ sessionId: z.string(),
293
+ turnId: z.string().nullable(),
294
+ cursor: z.string(),
295
+ createdAt: z.string(),
296
+ type: z.string(),
297
+ payload: z.unknown(),
298
+ })
299
+ .strict();
300
+ export const SessionItemsResponseSchema = z.object({
301
+ items: z.array(LiveEventSchema),
302
+ cursor: z.string().nullable(),
303
+ });
304
+ export const AcceptedResponseSchema = z.object({
305
+ status: z.literal("accepted"),
306
+ turnId: z.string().nullable(),
307
+ cursor: z.string().nullable(),
308
+ requestId: z.string(),
309
+ });
310
+ export const RejectedResponseSchema = z.object({
311
+ status: z.literal("rejected"),
312
+ code: z.string(),
313
+ message: z.string(),
314
+ activeTurnId: z.string().optional(),
315
+ requestId: z.string().optional(),
316
+ });
317
+ export const ActionSchema = z.object({
318
+ actionId: z.string(),
319
+ sessionId: z.string(),
320
+ turnId: z.string(),
321
+ agentId: z.string(),
322
+ manifestHash: z.string(),
323
+ implementationVersion: z.string(),
324
+ kind: z.enum(["tool", "beforeModelCall", "afterModelCall"]),
325
+ capabilityId: z.string(),
326
+ toolName: z.string().optional(),
327
+ inputSchema: jsonObject.optional(),
328
+ outputSchema: jsonObject.optional(),
329
+ input: z.unknown(),
330
+ context: jsonObject,
331
+ status: z.enum(["pending", "claimed", "completed", "uncertain", "cancelled"]),
332
+ generation: z.number().int().nonnegative(),
333
+ claimId: z.string().nullable(),
334
+ leaseExpiresAt: z.string().nullable(),
335
+ });
336
+ export const ActionClaimRequestSchema = z
337
+ .object({
338
+ requestId: RequestIdSchema,
339
+ implementationVersion: z.string().min(1),
340
+ })
341
+ .strict();
342
+ export const ActionHeartbeatRequestSchema = z
343
+ .object({
344
+ requestId: RequestIdSchema,
345
+ claimId: z.string().min(1),
346
+ generation: z.number().int().positive(),
347
+ })
348
+ .strict();
349
+ export const ActionClaimResponseSchema = z.object({
350
+ action: ActionSchema,
351
+ claimId: z.string(),
352
+ generation: z.number().int().positive(),
353
+ leaseExpiresAt: z.string(),
354
+ });
355
+ export const ExecutorNotificationSchema = z.object({
356
+ type: z.literal("work_available"),
357
+ });
358
+ export const HealthResponseSchema = z.object({
359
+ status: z.literal("ok"),
360
+ service: z.string(),
361
+ });
362
+ export const ReadyResponseSchema = z.object({
363
+ status: z.enum(["ready", "not_ready"]),
364
+ service: z.string(),
365
+ checks: z.record(z.string(), z.boolean()),
366
+ });
@@ -0,0 +1,32 @@
1
+ export { Agent, AgentBuilder, AgentBuildError, AgentLifecycleError, } from "./definition/builder.js";
2
+ export type { AgentOptions } from "./definition/builder.js";
3
+ export { HarnessError, isHarnessError } from "./errors.js";
4
+ export type { HarnessErrorCode, HarnessErrorDetails, HarnessErrorOptions, } from "./errors.js";
5
+ export type { BuiltAgent } from "./types/agent.js";
6
+ export { capability, middleware, model, tool } from "./definition/helpers.js";
7
+ export { ToolError, isToolError } from "./definition/tool-error.js";
8
+ export { defineSchema } from "./definition/schema.js";
9
+ export { hashManifest } from "./utils/hash.js";
10
+ export type { Implementations } from "./definition/implementations.js";
11
+ export type { AgentManifest, CapabilityManifest, McpServerManifest, RuntimeManifest, SkillManifest, ToolManifest, ManifestSchemaVersion, } from "./types/manifest.js";
12
+ export type { CapabilityDeclaration, CapabilityItems, MiddlewareContributions, SkillRecord, StepMiddleware, StepRequest, StepResponse, } from "./types/middleware.js";
13
+ export type { Patch, Decision, BeforeModelCallFn, AfterModelCallFn, } from "./types/dynamics.js";
14
+ export type { ModelCandidate, ModelControls, ModelDirective, ModelEvidence, ModelFinishReason, ModelAdapter, ModelAdapterContext, ModelPreparedCall, ContextContributor, ContextMutationOptions, ContextSnapshot, ModelCall, ModelCallTool, ModelOutputBlock, PromptContentPart, PromptItem, ModelConfigurationContributor, ModelConfigurationInstruction, ModelConfigurationMutationOptions, ModelConfigurationSnapshot, ModelConfigurationTool, ModelRequest, ModelToolCall, ModelUsage, } from "./types/model.js";
15
+ export type { BuildDiagnostic, ContextItem, DeferredOutcome, JsonObject, JsonPrimitive, JsonValue, Tripwire, } from "./types/shared.js";
16
+ export type { ObserveEvent, ObserveModelConfigurationSnapshot, ObserveModelRequested, ObserveSealedCall, ObserveToolSnapshot, Observer, } from "./types/observe.js";
17
+ export type { InputEvent, MessageInput, InteractionReply, TranscriptEntry, UserContentPart, } from "./types/transcript.js";
18
+ export type { Interaction, RequiredInteraction, ToolContent, ToolDefinition, ToolDescriptor, ToolExecutionContext, ToolExecutionResume, ToolInputSchema, ToolOutputSchema, ToolSchema, ToolSchemaSource, StandardToolSchema, StandardSchemaIssue, SchemaIssue, SchemaValidation, SchemaOutput, ToolOwner, ToolOutcome, ToolResult, ToolValidationFailureDetails, ToolEffects, ToolApproval, ToolRunResult, SessionStateBag, } from "./types/tool.js";
19
+ export { normalizeToolDefinition, normalizedSchemasFor, } from "./definition/schema.js";
20
+ export { implementationsFor, bindingFromAgent } from "./definition/binding.js";
21
+ export type { AgentBinding } from "./definition/binding.js";
22
+ export type { BoundMiddleware, BoundToolDefinition, } from "./definition/bound.js";
23
+ export { bindTool } from "./definition/bind-tool.js";
24
+ export { bindOutputContract } from "./definition/output-contract.js";
25
+ export type { TurnOutputContract } from "./definition/output-contract.js";
26
+ export { agentFrom } from "./definition/from.js";
27
+ export type { SessionToolRef } from "./definition/from.js";
28
+ export { schemaFromJSON } from "./definition/schema-json.js";
29
+ export { normalizeSchema } from "./definition/schema.js";
30
+ export * from "./utils/immutable.js";
31
+ export * from "./utils/canonical.js";
32
+ export type { TranscriptToolsEntry } from "./types/transcript.js";
package/dist/define.js ADDED
@@ -0,0 +1,15 @@
1
+ export { Agent, AgentBuilder, AgentBuildError, AgentLifecycleError, } from "./definition/builder.js";
2
+ export { HarnessError, isHarnessError } from "./errors.js";
3
+ export { capability, middleware, model, tool } from "./definition/helpers.js";
4
+ export { ToolError, isToolError } from "./definition/tool-error.js";
5
+ export { defineSchema } from "./definition/schema.js";
6
+ export { hashManifest } from "./utils/hash.js";
7
+ export { normalizeToolDefinition, normalizedSchemasFor, } from "./definition/schema.js";
8
+ export { implementationsFor, bindingFromAgent } from "./definition/binding.js";
9
+ export { bindTool } from "./definition/bind-tool.js";
10
+ export { bindOutputContract } from "./definition/output-contract.js";
11
+ export { agentFrom } from "./definition/from.js";
12
+ export { schemaFromJSON } from "./definition/schema-json.js";
13
+ export { normalizeSchema } from "./definition/schema.js";
14
+ export * from "./utils/immutable.js";
15
+ export * from "./utils/canonical.js";
@@ -0,0 +1,29 @@
1
+ import type { BoundMiddleware } from "./bound.js";
2
+ import type { BuiltAgent } from "../types/agent.js";
3
+ import type { AgentManifest, RuntimeManifest } from "../types/manifest.js";
4
+ import type { BuildDiagnostic, JsonObject } from "../types/shared.js";
5
+ import type { ToolSchemaSource } from "../types/tool.js";
6
+ import type { AfterModelCallFn, BeforeModelCallFn } from "../types/dynamics.js";
7
+ import type { StepMiddleware } from "../types/middleware.js";
8
+ type BuildResult<Agent> = {
9
+ readonly ok: true;
10
+ readonly agent: Agent;
11
+ readonly manifest: AgentManifest;
12
+ } | {
13
+ readonly ok: false;
14
+ readonly diagnostics: readonly BuildDiagnostic[];
15
+ };
16
+ export interface CapabilityDynamics {
17
+ readonly beforeModelCall?: BeforeModelCallFn<any>;
18
+ readonly afterModelCall?: AfterModelCallFn<any>;
19
+ readonly middleware?: StepMiddleware<any>;
20
+ }
21
+ export declare function assembleAgent(middleware: readonly BoundMiddleware[], identity: Readonly<{
22
+ id: string;
23
+ name?: string;
24
+ description?: string;
25
+ metadata?: JsonObject;
26
+ outputSchema?: ToolSchemaSource;
27
+ runtime?: RuntimeManifest;
28
+ }>, dynamics?: ReadonlyMap<string, CapabilityDynamics>): BuildResult<BuiltAgent>;
29
+ export {};
@@ -0,0 +1,120 @@
1
+ import { bindAgent } from "./bind-agent.js";
2
+ import { createManifest } from "./manifest.js";
3
+ import { createSkillTools } from "./skill-tools.js";
4
+ const diagnostic = (code, message, extra = {}) => Object.freeze({ code, message, ...extra });
5
+ export function assembleAgent(middleware, identity, dynamics = new Map()) {
6
+ const diagnostics = [];
7
+ if (typeof identity.id !== "string" || identity.id.length === 0) {
8
+ diagnostics.push(diagnostic("agent.invalid-id", "Agent id must be a non-empty string"));
9
+ }
10
+ if (identity.name !== undefined &&
11
+ (typeof identity.name !== "string" || identity.name.length === 0)) {
12
+ diagnostics.push(diagnostic("agent.invalid-name", "Agent name must be a non-empty string"));
13
+ }
14
+ const middlewareIds = new Set();
15
+ const frozen = [];
16
+ for (const item of middleware) {
17
+ if (!item.id)
18
+ diagnostics.push(diagnostic("middleware.invalid-id", "Middleware id must not be empty"));
19
+ else if (middlewareIds.has(item.id))
20
+ diagnostics.push(diagnostic("middleware.duplicate-id", `Duplicate middleware id '${item.id}'`));
21
+ else if (typeof item.handle !== "function")
22
+ diagnostics.push(diagnostic("middleware.invalid", `Middleware '${item.id}' must provide a function`));
23
+ else if (item.name !== undefined && item.name.length === 0)
24
+ diagnostics.push(diagnostic("middleware.invalid", `Capability '${item.id}' name must be a non-empty string`));
25
+ else {
26
+ middlewareIds.add(item.id);
27
+ frozen.push(Object.freeze({
28
+ id: item.id,
29
+ ...(item.name === undefined ? {} : { name: item.name }),
30
+ ...(item.description === undefined
31
+ ? {}
32
+ : { description: item.description }),
33
+ handle: item.handle,
34
+ hasMiddleware: item.hasMiddleware,
35
+ ...(item.tools === undefined ? {} : { tools: item.tools }),
36
+ ...(item.contributions === undefined
37
+ ? {}
38
+ : { contributions: item.contributions }),
39
+ ...(item.beforeModelCall ? { beforeModelCall: true } : {}),
40
+ ...(item.afterModelCall ? { afterModelCall: true } : {}),
41
+ ...(item.manifestType === undefined
42
+ ? {}
43
+ : { manifestType: item.manifestType }),
44
+ ...(item.metadata === undefined ? {} : { metadata: item.metadata }),
45
+ ...(item.mcpServers === undefined
46
+ ? {}
47
+ : { mcpServers: item.mcpServers }),
48
+ ...(item.skills === undefined ? {} : { skills: item.skills }),
49
+ ...(item.skillRecords === undefined
50
+ ? {}
51
+ : { skillRecords: item.skillRecords }),
52
+ ...(item.sessionTools === undefined
53
+ ? {}
54
+ : { sessionTools: item.sessionTools }),
55
+ ...(item.pluginRoot === undefined ? {} : { pluginRoot: item.pluginRoot }),
56
+ }));
57
+ }
58
+ }
59
+ const skilled = attachSkillTools(frozen);
60
+ diagnostics.push(...skilled.diagnostics);
61
+ if (diagnostics.length)
62
+ return Object.freeze({
63
+ ok: false,
64
+ diagnostics: Object.freeze(diagnostics),
65
+ });
66
+ const frozenMiddleware = Object.freeze(skilled.items.map((item) => Object.freeze(item)));
67
+ const manifest = createManifest({
68
+ id: identity.id,
69
+ name: identity.name,
70
+ description: identity.description,
71
+ metadata: identity.metadata,
72
+ outputSchema: identity.outputSchema,
73
+ runtime: identity.runtime,
74
+ middleware: frozenMiddleware,
75
+ });
76
+ const agent = bindAgent(frozenMiddleware, manifest, identity, dynamics);
77
+ return Object.freeze({ ok: true, agent, manifest });
78
+ }
79
+ const SKILL_TOOL_NAMES = new Set(["load_skill", "read_skill_resource"]);
80
+ function attachSkillTools(items) {
81
+ const skills = new Map();
82
+ const diagnostics = [];
83
+ const seen = new Set();
84
+ let ownerId;
85
+ for (const item of items) {
86
+ for (const [key, skill] of Object.entries(item.skills ?? {})) {
87
+ if (key !== skill.name || seen.has(skill.name)) {
88
+ diagnostics.push(diagnostic("skill.duplicate-name", `Duplicate skill '${skill.name}' on capability '${item.id}'`));
89
+ continue;
90
+ }
91
+ seen.add(skill.name);
92
+ }
93
+ for (const [key, skill] of Object.entries(item.skillRecords ?? {})) {
94
+ if (key !== skill.name || skills.has(skill.name)) {
95
+ diagnostics.push(diagnostic("skill.duplicate-name", `Duplicate skill '${skill.name}' on capability '${item.id}'`));
96
+ continue;
97
+ }
98
+ skills.set(skill.name, skill);
99
+ ownerId ??= item.id;
100
+ }
101
+ }
102
+ if (diagnostics.length > 0 || ownerId === undefined)
103
+ return { items: [...items], diagnostics };
104
+ const skillTools = createSkillTools(skills);
105
+ const next = items.map((item) => {
106
+ if (item.id !== ownerId)
107
+ return item;
108
+ const tools = [
109
+ ...(item.tools ?? []).filter((entry) => !SKILL_TOOL_NAMES.has(entry.name)),
110
+ ...skillTools,
111
+ ];
112
+ const advertised = [...tools, ...(item.sessionTools ?? [])];
113
+ const handle = async (request, next) => item.handle(request, async () => {
114
+ request.configuration.tools.set(item.id, advertised);
115
+ return next();
116
+ });
117
+ return { ...item, tools, handle };
118
+ });
119
+ return { items: next, diagnostics };
120
+ }
@@ -0,0 +1,8 @@
1
+ import type { AgentManifest } from "../types/manifest.js";
2
+ import type { BoundMiddleware } from "./bound.js";
3
+ import type { BuiltAgent } from "../types/agent.js";
4
+ import type { ToolSchemaSource } from "../types/tool.js";
5
+ import type { CapabilityDynamics } from "./assemble.js";
6
+ export declare function bindAgent(middleware: readonly BoundMiddleware[], manifest: AgentManifest, options?: {
7
+ outputSchema?: ToolSchemaSource;
8
+ }, dynamics?: ReadonlyMap<string, CapabilityDynamics>): BuiltAgent;
@@ -0,0 +1,62 @@
1
+ import { bindTool } from "./bind-tool.js";
2
+ import { HarnessError } from "../errors.js";
3
+ import { bindOutputContract } from "./output-contract.js";
4
+ export function bindAgent(middleware, manifest, options = {}, dynamics = new Map()) {
5
+ const seen = new Set();
6
+ const keys = new Set();
7
+ const tools = [];
8
+ for (const declaration of middleware)
9
+ for (const tool of [
10
+ ...(declaration.tools ?? []),
11
+ ...(declaration.sessionTools ?? []),
12
+ ]) {
13
+ const key = JSON.stringify([declaration.id, tool.name]);
14
+ if (seen.has(tool) || keys.has(key))
15
+ throw new HarnessError("tool.invalid", `Duplicate registered tool '${tool.name}' in '${declaration.id}'`);
16
+ seen.add(tool);
17
+ keys.add(key);
18
+ tools.push(bindTool(tool, { middlewareId: declaration.id, slot: declaration.id }));
19
+ }
20
+ const implementations = buildImplementations(middleware, dynamics, tools);
21
+ const binding = Object.freeze({
22
+ declarations: middleware,
23
+ tools: Object.freeze(tools),
24
+ ...(options.outputSchema === undefined
25
+ ? {}
26
+ : { outputSchema: options.outputSchema }),
27
+ manifest,
28
+ implementations,
29
+ });
30
+ // Validate the live output schema at authoring time without compiling engine state.
31
+ if (options.outputSchema)
32
+ bindOutputContract(options.outputSchema);
33
+ const agent = {
34
+ id: manifest.id,
35
+ name: manifest.name,
36
+ manifest,
37
+ toJSON: () => manifest,
38
+ };
39
+ Object.defineProperty(agent, "getBinding", {
40
+ value: () => binding,
41
+ enumerable: false,
42
+ });
43
+ return agent;
44
+ }
45
+ function buildImplementations(middleware, dynamics, snapshots) {
46
+ const table = {};
47
+ for (const item of middleware) {
48
+ const tools = {};
49
+ for (const tool of snapshots.filter((tool) => tool.owner.middlewareId === item.id))
50
+ tools[tool.name] = tool;
51
+ const dyn = dynamics.get(item.id);
52
+ table[item.id] = Object.freeze({
53
+ ...(Object.keys(tools).length
54
+ ? { tools: Object.freeze({ ...tools }) }
55
+ : {}),
56
+ ...(dyn?.beforeModelCall ? { beforeModelCall: dyn.beforeModelCall } : {}),
57
+ ...(dyn?.afterModelCall ? { afterModelCall: dyn.afterModelCall } : {}),
58
+ ...(dyn?.middleware ? { middleware: dyn.middleware } : {}),
59
+ });
60
+ }
61
+ return Object.freeze(table);
62
+ }
@@ -0,0 +1,4 @@
1
+ import type { BoundToolDefinition } from "./bound.js";
2
+ import type { ToolDefinition } from "../types/tool.js";
3
+ /** Prepares an executable Tool and records its middleware slot provenance. */
4
+ export declare function bindTool(item: ToolDefinition, owner: BoundToolDefinition["owner"]): BoundToolDefinition;
@@ -0,0 +1,25 @@
1
+ import { HarnessError } from "../errors.js";
2
+ import { normalizeToolDefinition, normalizedSchemasFor } from "./schema.js";
3
+ /** Prepares an executable Tool and records its middleware slot provenance. */
4
+ export function bindTool(item, owner) {
5
+ const prepared = normalizeToolDefinition(item);
6
+ if (!prepared.name)
7
+ throw new HarnessError("tool.invalid-name", "Tool name must not be empty");
8
+ if (typeof prepared.execute !== "function")
9
+ throw new HarnessError("tool.invalid", `Tool '${prepared.name}' must provide execute()`);
10
+ const schemas = normalizedSchemasFor(prepared);
11
+ return Object.freeze({
12
+ // Keep the original object identity so ToolRegistry WeakMap lookups succeed.
13
+ source: item,
14
+ name: prepared.name,
15
+ ...(prepared.description ? { description: prepared.description } : {}),
16
+ inputSchema: schemas.inputSchema,
17
+ ...(schemas.outputSchema === undefined
18
+ ? {}
19
+ : { outputSchema: schemas.outputSchema }),
20
+ execute: prepared.execute.bind(prepared),
21
+ ...(prepared.approval === undefined ? {} : { approval: prepared.approval }),
22
+ ...(prepared.effects === undefined ? {} : { effects: prepared.effects }),
23
+ owner: Object.freeze({ ...owner }),
24
+ });
25
+ }