@nylorun/core 0.7.0-beta → 0.9.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 (61) hide show
  1. package/CHANGELOG.md +249 -0
  2. package/dist/compatibility.d.ts +42 -4
  3. package/dist/compatibility.js +65 -3
  4. package/dist/contracts.d.ts +2165 -328
  5. package/dist/contracts.js +1246 -100
  6. package/dist/define.d.ts +13 -5
  7. package/dist/define.js +7 -2
  8. package/dist/definition/assemble.js +16 -14
  9. package/dist/definition/bind-tool.js +1 -0
  10. package/dist/definition/bound.d.ts +2 -0
  11. package/dist/definition/builder.d.ts +116 -16
  12. package/dist/definition/builder.js +330 -53
  13. package/dist/definition/capability.d.ts +55 -0
  14. package/dist/definition/capability.js +104 -0
  15. package/dist/definition/declaration.js +6 -2
  16. package/dist/definition/delegate.d.ts +25 -4
  17. package/dist/definition/delegate.js +34 -6
  18. package/dist/definition/flow/compile.d.ts +23 -0
  19. package/dist/definition/flow/compile.js +274 -0
  20. package/dist/definition/flow/from.d.ts +11 -0
  21. package/dist/definition/flow/from.js +78 -0
  22. package/dist/definition/flow/index.d.ts +11 -0
  23. package/dist/definition/flow/index.js +11 -0
  24. package/dist/definition/flow/paths.d.ts +60 -0
  25. package/dist/definition/flow/paths.js +90 -0
  26. package/dist/definition/flow/spec.d.ts +66 -0
  27. package/dist/definition/flow/spec.js +130 -0
  28. package/dist/definition/flow/types.d.ts +157 -0
  29. package/dist/definition/flow/types.js +1 -0
  30. package/dist/definition/from.js +5 -1
  31. package/dist/definition/helpers.d.ts +1 -16
  32. package/dist/definition/helpers.js +1 -30
  33. package/dist/definition/mcp.d.ts +37 -0
  34. package/dist/definition/mcp.js +81 -0
  35. package/dist/definition/model-failure.d.ts +4 -0
  36. package/dist/definition/model-failure.js +22 -0
  37. package/dist/definition/sandbox-capability.d.ts +12 -0
  38. package/dist/definition/sandbox-capability.js +33 -0
  39. package/dist/definition/schema.js +3 -0
  40. package/dist/definition/workflow/build.d.ts +3 -13
  41. package/dist/definition/workflow/build.js +3 -25
  42. package/dist/definition/workflow/chain.js +0 -1
  43. package/dist/definition/workflow/loop.js +2 -4
  44. package/dist/definition/workflow/map.js +0 -1
  45. package/dist/definition/workflow/parallel.js +0 -1
  46. package/dist/definition/workflow/runnable.d.ts +13 -5
  47. package/dist/definition/workflow/runnable.js +11 -41
  48. package/dist/definition/workflow/switch.js +0 -2
  49. package/dist/errors.d.ts +3 -1
  50. package/dist/types/manifest.d.ts +4 -2
  51. package/dist/types/middleware.d.ts +1 -3
  52. package/dist/types/model.d.ts +32 -1
  53. package/dist/types/observe.d.ts +7 -1
  54. package/dist/types/tool.d.ts +6 -0
  55. package/dist/types/transcript.d.ts +14 -1
  56. package/dist/types/workflow.d.ts +72 -3
  57. package/dist/utils/deprecate.d.ts +3 -0
  58. package/dist/utils/deprecate.js +25 -0
  59. package/dist/utils/sandbox.d.ts +0 -4
  60. package/dist/utils/sandbox.js +0 -16
  61. package/package.json +1 -1
@@ -3,6 +3,15 @@ import { assembleAgent } from "./assemble.js";
3
3
  import { compileDeclaration } from "./declaration.js";
4
4
  import { agentFrom } from "./from.js";
5
5
  import { hooksFrom } from "./hooks.js";
6
+ import { isAgentItem } from "./delegate.js";
7
+ import { normalizeMcpServers } from "./mcp.js";
8
+ import { deprecate } from "../utils/deprecate.js";
9
+ import { WorkflowBuildError } from "./workflow/diagnostics.js";
10
+ import { flowFrom } from "./flow/from.js";
11
+ import { isBuiltWorkflow } from "./workflow/types.js";
12
+ import { compileAgentFlow } from "./flow/compile.js";
13
+ import { loopStage, mapStage, named, parallelStage, stepStage, switchStage, } from "./flow/spec.js";
14
+ import { isCapabilityBuilder } from "./capability.js";
6
15
  export class AgentBuildError extends HarnessError {
7
16
  diagnostics;
8
17
  constructor(diagnostics) {
@@ -21,7 +30,9 @@ export function Agent(options) {
21
30
  return AgentBuilder.create(options);
22
31
  }
23
32
  (function (Agent) {
24
- function from(json, implementations) {
33
+ function from(json, implementations = {}) {
34
+ if (json.kind === "workflow")
35
+ return flowFrom(json, implementations);
25
36
  return agentFrom(json, implementations);
26
37
  }
27
38
  Agent.from = from;
@@ -30,6 +41,7 @@ const SNAPSHOT = Symbol("AgentBuilder.snapshot");
30
41
  export class AgentBuilder {
31
42
  #snapshot;
32
43
  #agent;
44
+ #workflow;
33
45
  #error;
34
46
  getBinding() {
35
47
  return this.build().getBinding();
@@ -43,8 +55,14 @@ export class AgentBuilder {
43
55
  static create(options) {
44
56
  return new AgentBuilder(options);
45
57
  }
46
- static withSnapshot(snapshot) {
47
- return new AgentBuilder(snapshot, SNAPSHOT);
58
+ /** @internal True for an agent whose body is a flow. */
59
+ static isFlowAgent(value) {
60
+ return value instanceof AgentBuilder && value.#snapshot.body === "flow";
61
+ }
62
+ /** A new builder of the same class (subclasses survive chaining). */
63
+ spawn(snapshot) {
64
+ const Ctor = this.constructor;
65
+ return new Ctor(snapshot, SNAPSHOT);
48
66
  }
49
67
  /** Compose-time identity — available before `.build()`. */
50
68
  get id() {
@@ -56,10 +74,102 @@ export class AgentBuilder {
56
74
  get manifest() {
57
75
  return this.ensure().manifest;
58
76
  }
77
+ /** A flow agent's input and output schemas (local; not on the v1 wire). */
78
+ get inputSchema() {
79
+ return this.#snapshot.body === "flow" ? this.#snapshot.inputSchema : undefined;
80
+ }
81
+ get outputSchema() {
82
+ return this.#snapshot.body === "flow" ? this.#snapshot.outputSchema : undefined;
83
+ }
59
84
  toJSON() {
60
85
  return this.ensure().toJSON();
61
86
  }
87
+ // ── ReAct: the model decides ───────────────────────────────────────────────
88
+ /** Add instructions. Repeated calls add more. */
89
+ instructions(...text) {
90
+ for (const item of text)
91
+ if (typeof item !== "string")
92
+ throw new HarnessError("configuration.invalid", ".instructions() takes strings");
93
+ return this.withAgentItems("instructions()", { instructions: text });
94
+ }
95
+ /** Add tools. Repeated calls add more. Agents belong in `.subagents()`. */
96
+ tools(...tools) {
97
+ return this.withAgentItems("tools()", { tools });
98
+ }
99
+ /** Add agents the model may delegate a self-contained task to. */
100
+ subagents(...agents) {
101
+ for (const agent of agents)
102
+ if (!isAgentItem(agent))
103
+ throw new HarnessError("configuration.invalid", ".subagents() takes agents; tools belong in .tools()");
104
+ return this.withAgentItems("subagents()", { tools: agents });
105
+ }
106
+ /** Declare MCP servers. A server's `name` defaults to its key; calls merge. */
107
+ mcp(servers) {
108
+ const snapshot = this.#snapshot;
109
+ const body = this.bodyFor("react", "mcp()");
110
+ const added = normalizeMcpServers(servers, ".mcp()");
111
+ const merged = { ...(snapshot.mcpServers ?? {}) };
112
+ const diagnostics = [];
113
+ for (const [key, server] of Object.entries(added)) {
114
+ if (merged[key] !== undefined)
115
+ diagnostics.push(Object.freeze({
116
+ code: "mcp.duplicate-server",
117
+ message: `MCP server '${key}' is declared twice on '${snapshot.id}'`,
118
+ }));
119
+ merged[key] = server;
120
+ }
121
+ const compiled = compileDeclaration({ id: "mcp", mcpServers: Object.freeze(merged) });
122
+ return this.spawn({
123
+ ...snapshot,
124
+ ...body,
125
+ mcpServers: Object.freeze(merged),
126
+ entries: replaceOrAppend(snapshot.entries, compiled.bound),
127
+ dynamics: withDynamics(snapshot.dynamics, "mcp", {}),
128
+ diagnostics: addDiagnostics(body.diagnostics ?? snapshot.diagnostics, diagnostics),
129
+ });
130
+ }
131
+ /** Attach a reusable bundle made with `capability({ id })`. */
132
+ capability(bundle) {
133
+ const declaration = isCapabilityBuilder(bundle)
134
+ ? bundle.toDeclaration()
135
+ : bundle;
136
+ return this.addDeclaration(declaration, "capability()");
137
+ }
138
+ /** Run `fn` before each turn. */
139
+ beforeTurn(fn) {
140
+ return this.addAgentHook("before", "turn", fn);
141
+ }
142
+ /** Run `fn` before every model call. */
143
+ beforeModel(fn) {
144
+ return this.addAgentHook("before", "step", fn);
145
+ }
146
+ /** Run `fn` after every model call. */
147
+ afterModel(fn) {
148
+ return this.addAgentHook("after", "step", fn);
149
+ }
150
+ /** Run `fn` after the turn's final answer. */
151
+ afterTurn(fn) {
152
+ return this.addAgentHook("after", "turn", fn);
153
+ }
154
+ /** The structured output. Set once. */
155
+ output(schema) {
156
+ const snapshot = this.#snapshot;
157
+ if (snapshot.outputSchema !== undefined)
158
+ return this.spawn({
159
+ ...snapshot,
160
+ diagnostics: addDiagnostics(snapshot.diagnostics, [singleValue(snapshot.id, "output schema")]),
161
+ });
162
+ return this.spawn({ ...snapshot, outputSchema: schema });
163
+ }
62
164
  use(idOrMiddleware, middleware) {
165
+ if (typeof idOrMiddleware === "object") {
166
+ deprecate("NYLORUN_DEP_USE", ".use(capability) is deprecated. Use .capability(), .mcp(), .skills() or .plugin().");
167
+ const declaration = isCapabilityBuilder(idOrMiddleware)
168
+ ? idOrMiddleware.toDeclaration()
169
+ : idOrMiddleware;
170
+ return this.addDeclaration(declaration, "use()");
171
+ }
172
+ const body = this.bodyFor("react", "use()");
63
173
  let compiled;
64
174
  if (typeof idOrMiddleware === "function") {
65
175
  compiled = {
@@ -71,9 +181,6 @@ export class AgentBuilder {
71
181
  middleware: idOrMiddleware,
72
182
  };
73
183
  }
74
- else if (typeof idOrMiddleware === "object") {
75
- compiled = compileDeclaration(idOrMiddleware);
76
- }
77
184
  else {
78
185
  compiled = {
79
186
  bound: {
@@ -84,44 +191,193 @@ export class AgentBuilder {
84
191
  middleware: middleware,
85
192
  };
86
193
  }
87
- const dynamics = new Map(this.#snapshot.dynamics);
88
- dynamics.set(compiled.bound.id, {
89
- ...(compiled.before ? { before: compiled.before } : {}),
90
- ...(compiled.after ? { after: compiled.after } : {}),
91
- ...(compiled.middleware ? { middleware: compiled.middleware } : {}),
92
- });
93
- return AgentBuilder.withSnapshot({
94
- ...this.#snapshot,
95
- entries: Object.freeze([...this.#snapshot.entries, compiled.bound]),
96
- dynamics,
97
- });
194
+ return this.appendCompiled(compiled, body);
98
195
  }
99
196
  /**
197
+ * @deprecated Use `.beforeTurn()` or `.beforeModel()`.
100
198
  * Run `fn` before each turn (`"turn"`) or before every model call (`"step"`).
101
- * The returned Patch applies to the whole turn or to that one model call.
102
199
  */
103
200
  before(scope, fn) {
201
+ deprecate("NYLORUN_DEP_HOOKS", '.before()/.after() are deprecated. Use .beforeTurn(), .beforeModel(), .afterModel() or .afterTurn().');
104
202
  return this.addAgentHook("before", scope, fn);
105
203
  }
106
204
  /**
205
+ * @deprecated Use `.afterModel()` or `.afterTurn()`.
107
206
  * Run `fn` after every model call (`"step"`) or after the turn's final answer (`"turn"`).
108
207
  */
109
208
  after(scope, fn) {
209
+ deprecate("NYLORUN_DEP_HOOKS", '.before()/.after() are deprecated. Use .beforeTurn(), .beforeModel(), .afterModel() or .afterTurn().');
110
210
  return this.addAgentHook("after", scope, fn);
111
211
  }
212
+ // ── Flow: code decides ─────────────────────────────────────────────────────
213
+ /** The flow agent's input. Set once. */
214
+ input(schema) {
215
+ const snapshot = this.#snapshot;
216
+ const body = this.bodyFor("flow", "input()");
217
+ if (snapshot.inputSchema !== undefined)
218
+ return this.spawn({
219
+ ...snapshot,
220
+ ...body,
221
+ diagnostics: addDiagnostics(body.diagnostics ?? snapshot.diagnostics, [singleValue(snapshot.id, "input schema")]),
222
+ });
223
+ return this.spawn({ ...snapshot, ...body, inputSchema: schema });
224
+ }
225
+ step(child, options) {
226
+ return this.addStage(stepStage(child, options), "step()");
227
+ }
228
+ switch(cases, options) {
229
+ return this.addStage(switchStage(cases, options), "switch()");
230
+ }
231
+ parallel(branches, options) {
232
+ return this.addStage(parallelStage(branches, options), "parallel()");
233
+ }
234
+ map(each, options) {
235
+ return this.addStage(mapStage(each, options), "map()");
236
+ }
237
+ loop(body, options) {
238
+ return this.addStage(loopStage(body, options), "loop()");
239
+ }
240
+ /** Give this agent a new step id where there is no options object. */
241
+ withId(id) {
242
+ return named(this, id);
243
+ }
244
+ // ── Build ─────────────────────────────────────────────────────────────────
245
+ /** Optional no-op: returns the assembled agent facade (a workflow for flow agents). */
246
+ build() {
247
+ return this.ensure();
248
+ }
249
+ ensure() {
250
+ if (this.#agent)
251
+ return this.#agent;
252
+ if (this.#workflow)
253
+ return this.#workflow;
254
+ if (this.#error)
255
+ throw this.#error;
256
+ const snapshot = this.#snapshot;
257
+ if (snapshot.diagnostics?.length) {
258
+ this.#error = new AgentBuildError(snapshot.diagnostics);
259
+ throw this.#error;
260
+ }
261
+ if (snapshot.body === "flow") {
262
+ try {
263
+ this.#workflow = compileAgentFlow({
264
+ id: snapshot.id,
265
+ ...(snapshot.name === undefined ? {} : { name: snapshot.name }),
266
+ ...(snapshot.description === undefined ? {} : { description: snapshot.description }),
267
+ ...(snapshot.metadata === undefined ? {} : { metadata: snapshot.metadata }),
268
+ stages: snapshot.stages,
269
+ ...(snapshot.inputSchema === undefined ? {} : { inputSchema: snapshot.inputSchema }),
270
+ ...(snapshot.outputSchema === undefined ? {} : { outputSchema: snapshot.outputSchema }),
271
+ });
272
+ }
273
+ catch (error) {
274
+ if (error instanceof WorkflowBuildError) {
275
+ this.#error = new AgentBuildError(error.diagnostics);
276
+ throw this.#error;
277
+ }
278
+ throw error;
279
+ }
280
+ return this.#workflow;
281
+ }
282
+ const result = assembleAgent(snapshot.entries, {
283
+ id: snapshot.id,
284
+ name: snapshot.name,
285
+ description: snapshot.description,
286
+ metadata: snapshot.metadata,
287
+ outputSchema: snapshot.outputSchema,
288
+ }, snapshot.dynamics);
289
+ if (!result.ok) {
290
+ this.#error = new AgentBuildError(result.diagnostics);
291
+ throw this.#error;
292
+ }
293
+ this.#agent = result.agent;
294
+ return this.#agent;
295
+ }
296
+ // ── Internals ─────────────────────────────────────────────────────────────
297
+ /** Record which body a method belongs to; mixing bodies is a build error. */
298
+ bodyFor(kind, method) {
299
+ const snapshot = this.#snapshot;
300
+ if (snapshot.body === "none" || snapshot.body === kind)
301
+ return { body: kind };
302
+ const diagnostic = kind === "react"
303
+ ? Object.freeze({
304
+ code: "flow.no-model",
305
+ message: `'${snapshot.id}' is a flow agent, which runs no model. Move .${method} to an agent passed to .step().`,
306
+ })
307
+ : Object.freeze({
308
+ code: "agent.mixed-body",
309
+ message: `'${snapshot.id}' is a ReAct agent. An agent is either a ReAct loop or a flow: put the ReAct part in its own Agent and add it with .step().`,
310
+ });
311
+ return { body: snapshot.body, diagnostics: addDiagnostics(snapshot.diagnostics, [diagnostic]) };
312
+ }
313
+ addStage(stage, method) {
314
+ const snapshot = this.#snapshot;
315
+ const body = this.bodyFor("flow", method);
316
+ return this.spawn({ ...snapshot, ...body, stages: Object.freeze([...snapshot.stages, stage]) });
317
+ }
318
+ withAgentItems(method, items) {
319
+ const snapshot = this.#snapshot;
320
+ const body = this.bodyFor("react", method);
321
+ const flows = (items.tools ?? []).filter((item) => isFlowItem(item));
322
+ const part = {
323
+ ...(snapshot.agentPart?.instructions !== undefined || items.instructions !== undefined
324
+ ? { instructions: Object.freeze([...(snapshot.agentPart?.instructions ?? []), ...(items.instructions ?? [])]) }
325
+ : {}),
326
+ ...(snapshot.agentPart?.tools !== undefined || items.tools !== undefined
327
+ ? { tools: Object.freeze([...(snapshot.agentPart?.tools ?? []), ...(items.tools ?? []).filter((item) => !isFlowItem(item))]) }
328
+ : {}),
329
+ };
330
+ const diagnostics = flows.map((item) => Object.freeze({
331
+ code: "delegation.flow-unsupported",
332
+ message: `'${item.id ?? "workflow"}' was built with Chain, Switch, Parallel, Map or Loop and cannot be a subagent. Write it as a flow agent, Agent({ id }).step(…), which can.`,
333
+ }));
334
+ const compiled = compileDeclaration({ id: "agent", ...part });
335
+ const dynamics = snapshot.dynamics.get("agent") ?? {};
336
+ const hooks = hooksFrom(dynamics.before, dynamics.after);
337
+ const bound = hooks === undefined ? compiled.bound : Object.freeze({ ...compiled.bound, hooks });
338
+ return this.spawn({
339
+ ...snapshot,
340
+ ...body,
341
+ agentPart: Object.freeze(part),
342
+ entries: replaceOrAppend(snapshot.entries, bound),
343
+ dynamics: withDynamics(snapshot.dynamics, "agent", dynamics),
344
+ diagnostics: addDiagnostics(body.diagnostics ?? snapshot.diagnostics, diagnostics),
345
+ });
346
+ }
347
+ addDeclaration(declaration, method) {
348
+ const body = this.bodyFor("react", method);
349
+ return this.appendCompiled(compileDeclaration(declaration), body);
350
+ }
351
+ appendCompiled(compiled, body) {
352
+ const snapshot = this.#snapshot;
353
+ const dynamics = new Map(snapshot.dynamics);
354
+ dynamics.set(compiled.bound.id, {
355
+ ...(compiled.before ? { before: compiled.before } : {}),
356
+ ...(compiled.after ? { after: compiled.after } : {}),
357
+ ...(compiled.middleware ? { middleware: compiled.middleware } : {}),
358
+ });
359
+ return this.spawn({
360
+ ...snapshot,
361
+ ...body,
362
+ entries: Object.freeze([...snapshot.entries, compiled.bound]),
363
+ dynamics,
364
+ });
365
+ }
112
366
  addAgentHook(at, scope, fn) {
113
367
  if (typeof fn !== "function")
114
368
  throw new HarnessError("configuration.invalid", `${at}("${scope}") requires a function`);
115
369
  if (scope !== "turn" && scope !== "step")
116
370
  throw new HarnessError("configuration.invalid", `Unknown hook scope '${String(scope)}'; use "turn" or "step"`);
117
- const dynamics = new Map(this.#snapshot.dynamics);
371
+ const snapshot = this.#snapshot;
372
+ const body = this.bodyFor("react", hookMethod(at, scope));
373
+ const dynamics = new Map(snapshot.dynamics);
118
374
  const existing = dynamics.get("agent") ?? {};
119
375
  const current = existing[at];
120
376
  if (current?.[scope] !== undefined)
121
- return AgentBuilder.withSnapshot({
122
- ...this.#snapshot,
123
- diagnostics: Object.freeze([
124
- ...(this.#snapshot.diagnostics ?? []),
377
+ return this.spawn({
378
+ ...snapshot,
379
+ ...body,
380
+ diagnostics: addDiagnostics(body.diagnostics ?? snapshot.diagnostics, [
125
381
  Object.freeze({
126
382
  code: "hook.duplicate",
127
383
  message: `Agent hook ${at}("${scope}") is registered more than once`,
@@ -133,39 +389,13 @@ export class AgentBuilder {
133
389
  [at]: Object.freeze({ ...current, [scope]: fn }),
134
390
  };
135
391
  dynamics.set("agent", next);
136
- return AgentBuilder.withSnapshot({
137
- ...this.#snapshot,
138
- entries: withAgentHooks(this.#snapshot.entries, next),
392
+ return this.spawn({
393
+ ...snapshot,
394
+ ...body,
395
+ entries: withAgentHooks(snapshot.entries, next),
139
396
  dynamics,
140
397
  });
141
398
  }
142
- /** Optional no-op: returns the assembled agent facade. */
143
- build() {
144
- return this.ensure();
145
- }
146
- ensure() {
147
- if (this.#agent)
148
- return this.#agent;
149
- if (this.#error)
150
- throw this.#error;
151
- if (this.#snapshot.diagnostics?.length) {
152
- this.#error = new AgentBuildError(this.#snapshot.diagnostics);
153
- throw this.#error;
154
- }
155
- const result = assembleAgent(this.#snapshot.entries, {
156
- id: this.#snapshot.id,
157
- name: this.#snapshot.name,
158
- description: this.#snapshot.description,
159
- metadata: this.#snapshot.metadata,
160
- outputSchema: this.#snapshot.outputSchema,
161
- }, this.#snapshot.dynamics);
162
- if (!result.ok) {
163
- this.#error = new AgentBuildError(result.diagnostics);
164
- throw this.#error;
165
- }
166
- this.#agent = result.agent;
167
- return this.#agent;
168
- }
169
399
  }
170
400
  function createSnapshot(options) {
171
401
  const entries = [];
@@ -175,6 +405,8 @@ function createSnapshot(options) {
175
405
  : typeof options.instructions === "string"
176
406
  ? [options.instructions]
177
407
  : options.instructions;
408
+ if (instructions !== undefined || options.tools !== undefined || options.outputSchema !== undefined)
409
+ deprecate("NYLORUN_DEP_AGENT_OPTIONS", "Agent({ instructions, tools, outputSchema }) is deprecated. Use .instructions(), .tools(), .subagents() and .output().");
178
410
  if (instructions !== undefined || options.tools !== undefined) {
179
411
  const compiled = compileDeclaration({
180
412
  id: "agent",
@@ -194,8 +426,53 @@ function createSnapshot(options) {
194
426
  outputSchema: options.outputSchema,
195
427
  entries: Object.freeze(entries),
196
428
  dynamics,
429
+ body: instructions !== undefined || options.tools !== undefined ? "react" : "none",
430
+ ...(instructions === undefined && options.tools === undefined
431
+ ? {}
432
+ : {
433
+ agentPart: Object.freeze({
434
+ ...(instructions === undefined ? {} : { instructions: Object.freeze([...instructions]) }),
435
+ ...(options.tools === undefined ? {} : { tools: Object.freeze([...options.tools]) }),
436
+ }),
437
+ }),
438
+ stages: Object.freeze([]),
197
439
  };
198
440
  }
441
+ function hookMethod(at, scope) {
442
+ return `${at}${scope === "turn" ? "Turn" : "Model"}()`;
443
+ }
444
+ function singleValue(id, what) {
445
+ return Object.freeze({
446
+ code: "agent.single-value",
447
+ message: `'${id}' already has an ${what}; set it once`,
448
+ });
449
+ }
450
+ function addDiagnostics(current, added) {
451
+ if (added.length === 0)
452
+ return current;
453
+ return Object.freeze([...(current ?? []), ...added]);
454
+ }
455
+ function withDynamics(dynamics, id, value) {
456
+ const next = new Map(dynamics);
457
+ next.set(id, value);
458
+ return next;
459
+ }
460
+ /** Replace the entry with the same id in place, or append it. */
461
+ function replaceOrAppend(entries, bound) {
462
+ const index = entries.findIndex((item) => item.id === bound.id);
463
+ if (index < 0)
464
+ return Object.freeze([...entries, bound]);
465
+ return Object.freeze([...entries.slice(0, index), bound, ...entries.slice(index + 1)]);
466
+ }
467
+ /**
468
+ * A workflow built with the v1 primitives, placed where a subagent is expected. Flow
469
+ * agents are subagents like any agent: they run in their own linked session.
470
+ */
471
+ function isFlowItem(value) {
472
+ if (!value || typeof value !== "object" || value instanceof AgentBuilder)
473
+ return false;
474
+ return isBuiltWorkflow(value) && value.manifest.workflowSchemaVersion === 1;
475
+ }
199
476
  function nextMiddlewareId(entries) {
200
477
  const taken = new Set(entries.map((item) => item.id));
201
478
  let seq = 0;
@@ -0,0 +1,55 @@
1
+ import type { StepMiddleware, CapabilityDeclaration } from "../types/middleware.js";
2
+ import type { ToolDefinition } from "../types/tool.js";
3
+ import type { AgentTool } from "../types/agent.js";
4
+ import type { AfterHook, AfterHooks, BeforeHook, BeforeHooks } from "../types/dynamics.js";
5
+ import type { ModelDirective } from "../types/model.js";
6
+ export interface CapabilityIdentity {
7
+ readonly id: string;
8
+ readonly name?: string;
9
+ readonly description?: string;
10
+ }
11
+ /** The options form of `capability()`. Deprecated: use the builder methods. */
12
+ export interface CapabilityOptions<Info = unknown> extends CapabilityIdentity {
13
+ readonly tools?: readonly (ToolDefinition<any, Info, any> | AgentTool)[];
14
+ readonly instructions?: string | readonly string[];
15
+ /** Run before each turn or before every model call (step). */
16
+ readonly before?: BeforeHooks<Info>;
17
+ /** Run after every model call (step) or after the turn's final answer. */
18
+ readonly after?: AfterHooks<Info>;
19
+ /** @deprecated Prefer before / after hooks. */
20
+ readonly middleware?: StepMiddleware<Info>;
21
+ /** @deprecated Model resolution is Runtime-owned; not projected into the manifest. */
22
+ readonly model?: ModelDirective;
23
+ }
24
+ type Parts<Info> = {
25
+ readonly instructions?: readonly string[];
26
+ readonly tools?: readonly (ToolDefinition<any, Info, any> | AgentTool)[];
27
+ readonly before?: BeforeHooks<Info>;
28
+ readonly after?: AfterHooks<Info>;
29
+ };
30
+ /**
31
+ * A reusable bundle of instructions, tools and hooks, attached with `.capability()`.
32
+ * It has the same methods as a ReAct agent.
33
+ */
34
+ export declare class CapabilityBuilder<Info = unknown> {
35
+ #private;
36
+ constructor(identity: CapabilityIdentity, parts?: Parts<Info>);
37
+ get id(): string;
38
+ instructions(...text: readonly string[]): CapabilityBuilder<Info>;
39
+ tools(...tools: readonly ToolDefinition<any, Info, any>[]): CapabilityBuilder<Info>;
40
+ subagents(...agents: readonly AgentTool[]): CapabilityBuilder<Info>;
41
+ beforeTurn(fn: BeforeHook<"turn", Info>): CapabilityBuilder<Info>;
42
+ beforeModel(fn: BeforeHook<"step", Info>): CapabilityBuilder<Info>;
43
+ afterModel(fn: AfterHook<"step", Info>): CapabilityBuilder<Info>;
44
+ afterTurn(fn: AfterHook<"turn", Info>): CapabilityBuilder<Info>;
45
+ /** @internal The declaration `.capability()` attaches. */
46
+ toDeclaration(): CapabilityDeclaration<Info>;
47
+ private with;
48
+ private hook;
49
+ }
50
+ export declare function isCapabilityBuilder(value: unknown): value is CapabilityBuilder<any>;
51
+ /** Compose a reusable capability bundle: `capability({ id }).instructions(…).tools(…)`. */
52
+ export declare function capability<Info = unknown>(identity: CapabilityIdentity): CapabilityBuilder<Info>;
53
+ /** @deprecated Use `capability({ id }).instructions(…).tools(…).beforeTurn(…)`. */
54
+ export declare function capability<Info = unknown>(declaration: CapabilityOptions<Info>): CapabilityDeclaration<Info>;
55
+ export {};
@@ -0,0 +1,104 @@
1
+ import { HarnessError } from "../errors.js";
2
+ import { delegateTool, isAgentItem } from "./delegate.js";
3
+ import { deprecate } from "../utils/deprecate.js";
4
+ const CAPABILITY = Symbol.for("nylorun.capability");
5
+ /**
6
+ * A reusable bundle of instructions, tools and hooks, attached with `.capability()`.
7
+ * It has the same methods as a ReAct agent.
8
+ */
9
+ export class CapabilityBuilder {
10
+ #identity;
11
+ #parts;
12
+ constructor(identity, parts = {}) {
13
+ if (!identity || typeof identity.id !== "string" || identity.id.length === 0)
14
+ throw new HarnessError("configuration.invalid", "capability() requires a non-empty id");
15
+ this.#identity = Object.freeze({ ...identity });
16
+ this.#parts = Object.freeze({ ...parts });
17
+ Object.defineProperty(this, CAPABILITY, { value: true });
18
+ }
19
+ get id() {
20
+ return this.#identity.id;
21
+ }
22
+ instructions(...text) {
23
+ return this.with({ instructions: [...(this.#parts.instructions ?? []), ...text] });
24
+ }
25
+ tools(...tools) {
26
+ return this.with({ tools: [...(this.#parts.tools ?? []), ...tools] });
27
+ }
28
+ subagents(...agents) {
29
+ for (const agent of agents)
30
+ if (!isAgentItem(agent))
31
+ throw new HarnessError("configuration.invalid", ".subagents() takes agents; tools belong in .tools()");
32
+ return this.with({ tools: [...(this.#parts.tools ?? []), ...agents] });
33
+ }
34
+ beforeTurn(fn) {
35
+ return this.hook("before", "turn", fn);
36
+ }
37
+ beforeModel(fn) {
38
+ return this.hook("before", "step", fn);
39
+ }
40
+ afterModel(fn) {
41
+ return this.hook("after", "step", fn);
42
+ }
43
+ afterTurn(fn) {
44
+ return this.hook("after", "turn", fn);
45
+ }
46
+ /** @internal The declaration `.capability()` attaches. */
47
+ toDeclaration() {
48
+ return declarationOf({ ...this.#identity, ...this.#parts });
49
+ }
50
+ with(parts) {
51
+ return new CapabilityBuilder(this.#identity, { ...this.#parts, ...parts });
52
+ }
53
+ hook(at, scope, fn) {
54
+ if (typeof fn !== "function")
55
+ throw new HarnessError("configuration.invalid", `${at}${scope === "turn" ? "Turn" : "Model"}() requires a function`);
56
+ const current = (this.#parts[at] ?? {});
57
+ if (current[scope] !== undefined)
58
+ throw new HarnessError("configuration.invalid", `Capability '${this.#identity.id}' already has a ${at}${scope === "turn" ? "Turn" : "Model"}() hook`);
59
+ return this.with({ [at]: Object.freeze({ ...current, [scope]: fn }) });
60
+ }
61
+ }
62
+ export function isCapabilityBuilder(value) {
63
+ return !!value && typeof value === "object" && value[CAPABILITY] === true;
64
+ }
65
+ const LEGACY_FIELDS = ["tools", "instructions", "before", "after", "middleware", "model"];
66
+ export function capability(declaration) {
67
+ const legacy = LEGACY_FIELDS.some((key) => declaration[key] !== undefined);
68
+ if (!legacy)
69
+ return new CapabilityBuilder({
70
+ id: declaration.id,
71
+ ...(declaration.name === undefined ? {} : { name: declaration.name }),
72
+ ...(declaration.description === undefined ? {} : { description: declaration.description }),
73
+ });
74
+ deprecate("NYLORUN_DEP_CAPABILITY_OPTIONS", "capability({ tools, instructions, before, after }) is deprecated. Use capability({ id }).instructions(…).tools(…).beforeTurn(…).");
75
+ return declarationOf(declaration);
76
+ }
77
+ function declarationOf(declaration) {
78
+ const instructions = declaration.instructions === undefined
79
+ ? undefined
80
+ : typeof declaration.instructions === "string"
81
+ ? [declaration.instructions]
82
+ : declaration.instructions;
83
+ return {
84
+ id: declaration.id,
85
+ ...(declaration.name === undefined ? {} : { name: declaration.name }),
86
+ ...(declaration.description === undefined
87
+ ? {}
88
+ : { description: declaration.description }),
89
+ ...(declaration.tools === undefined
90
+ ? {}
91
+ : {
92
+ tools: declaration.tools.map((item) => isAgentItem(item)
93
+ ? delegateTool(item)
94
+ : item),
95
+ }),
96
+ ...(instructions === undefined ? {} : { instructions }),
97
+ ...(declaration.before === undefined ? {} : { before: declaration.before }),
98
+ ...(declaration.after === undefined ? {} : { after: declaration.after }),
99
+ ...(declaration.middleware === undefined
100
+ ? {}
101
+ : { middleware: declaration.middleware }),
102
+ ...(declaration.model === undefined ? {} : { model: declaration.model }),
103
+ };
104
+ }
@@ -45,9 +45,10 @@ export function compileDeclaration(declaration) {
45
45
  Object.keys(declaration.mcpServers).length === 0
46
46
  ? {}
47
47
  : { mcpServers: declaration.mcpServers }),
48
- ...(declaration.sandbox === undefined
48
+ // Definitions declare no sandbox; carry one through so the build can refuse it by name.
49
+ ...(sandboxOf(declaration) === undefined
49
50
  ? {}
50
- : { sandbox: declaration.sandbox }),
51
+ : { sandbox: sandboxOf(declaration) }),
51
52
  ...(declaration.pluginRoot === undefined
52
53
  ? {}
53
54
  : { pluginRoot: declaration.pluginRoot }),
@@ -103,3 +104,6 @@ function asTools(value) {
103
104
  items: Object.freeze(value.items.map((item) => (isAgentItem(item) ? delegateTool(item) : item))),
104
105
  });
105
106
  }
107
+ function sandboxOf(declaration) {
108
+ return declaration.sandbox;
109
+ }