@nylorun/core 0.3.0-beta → 0.4.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # @nylorun/core
2
2
 
3
+ ## 0.4.0-beta
4
+
5
+ ### Minor Changes
6
+
7
+ - 1cd7dc7: Add subagents: put an agent in another agent's `tools` (`Agent({ tools: [lookupOrder, researcher] })` or `.use({ tools: [researcher] })`) and the model can delegate to it. The tool is named after the agent's id, takes `{ task: string }`, and its description is the agent's `description`, which is now required for an agent used as a tool. The engine runs the child inside the parent's turn as a durable branch: fresh context, its own tools and hooks served by the root agent's executor, its own MCP servers, the session's sandbox, and only its final output (or `outputSchema` result) returned. Empty output, failures (with partial output marked as evidence), and requests for input or approval inside a child reach the parent as failed tool results. Parallel delegation calls run concurrently, completed child work is never re-run on replay, and cancelling the session cancels every child.
8
+
9
+ v1 is one level deep and non-interactive. Nested delegation, child tools that declare `approval`, and differing sandboxes across the tree fail the build with a named diagnostic. The manifest adds an optional `agent` body on a tool (schema version unchanged), actions and effects carry `agent: { id, path, delegationId }`, tool context gains `ctx.agent`, the durable host resolves a new `delegation` effect kind, and the Runtime emits `delegation.started` / `delegation.completed` events and filters history with `?agent=` (`session.history({ agent })`). Studio shows delegations, labels child actions with their agent, and filters events by agent.
10
+
3
11
  ## 0.3.0-beta
4
12
 
5
13
  ### Minor Changes
@@ -276,6 +276,12 @@ export declare const RejectedResponseSchema: z.ZodObject<{
276
276
  requestId: z.ZodOptional<z.ZodString>;
277
277
  }, z.core.$strip>;
278
278
  export type RejectedResponse = z.infer<typeof RejectedResponseSchema>;
279
+ /** The agent a call belongs to. Set on work for an agent used as a tool; absent for the root. */
280
+ export declare const AgentRefSchema: z.ZodObject<{
281
+ id: z.ZodString;
282
+ path: z.ZodString;
283
+ delegationId: z.ZodOptional<z.ZodString>;
284
+ }, z.core.$strict>;
279
285
  /** The hook point an action runs, and the capabilities that registered it (manifest order). */
280
286
  export declare const ActionHookSchema: z.ZodObject<{
281
287
  at: z.ZodEnum<{
@@ -308,6 +314,11 @@ export declare const ActionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
308
314
  generation: z.ZodNumber;
309
315
  claimId: z.ZodNullable<z.ZodString>;
310
316
  leaseExpiresAt: z.ZodNullable<z.ZodString>;
317
+ agent: z.ZodOptional<z.ZodObject<{
318
+ id: z.ZodString;
319
+ path: z.ZodString;
320
+ delegationId: z.ZodOptional<z.ZodString>;
321
+ }, z.core.$strict>>;
311
322
  kind: z.ZodLiteral<"tool">;
312
323
  capabilityId: z.ZodString;
313
324
  toolName: z.ZodString;
@@ -332,6 +343,11 @@ export declare const ActionSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
332
343
  generation: z.ZodNumber;
333
344
  claimId: z.ZodNullable<z.ZodString>;
334
345
  leaseExpiresAt: z.ZodNullable<z.ZodString>;
346
+ agent: z.ZodOptional<z.ZodObject<{
347
+ id: z.ZodString;
348
+ path: z.ZodString;
349
+ delegationId: z.ZodOptional<z.ZodString>;
350
+ }, z.core.$strict>>;
335
351
  kind: z.ZodLiteral<"hook">;
336
352
  hook: z.ZodObject<{
337
353
  at: z.ZodEnum<{
@@ -375,6 +391,11 @@ export declare const ActionClaimResponseSchema: z.ZodObject<{
375
391
  generation: z.ZodNumber;
376
392
  claimId: z.ZodNullable<z.ZodString>;
377
393
  leaseExpiresAt: z.ZodNullable<z.ZodString>;
394
+ agent: z.ZodOptional<z.ZodObject<{
395
+ id: z.ZodString;
396
+ path: z.ZodString;
397
+ delegationId: z.ZodOptional<z.ZodString>;
398
+ }, z.core.$strict>>;
378
399
  kind: z.ZodLiteral<"tool">;
379
400
  capabilityId: z.ZodString;
380
401
  toolName: z.ZodString;
@@ -399,6 +420,11 @@ export declare const ActionClaimResponseSchema: z.ZodObject<{
399
420
  generation: z.ZodNumber;
400
421
  claimId: z.ZodNullable<z.ZodString>;
401
422
  leaseExpiresAt: z.ZodNullable<z.ZodString>;
423
+ agent: z.ZodOptional<z.ZodObject<{
424
+ id: z.ZodString;
425
+ path: z.ZodString;
426
+ delegationId: z.ZodOptional<z.ZodString>;
427
+ }, z.core.$strict>>;
402
428
  kind: z.ZodLiteral<"hook">;
403
429
  hook: z.ZodObject<{
404
430
  at: z.ZodEnum<{
package/dist/contracts.js CHANGED
@@ -2,6 +2,8 @@
2
2
  import { z } from "zod";
3
3
  import { SANDBOX_NETWORK_PRESETS, SANDBOX_TOOL_NAMES, isSandboxHostPattern, parseSandboxDuration, parseSandboxSize, } from "./utils/sandbox.js";
4
4
  import { hookListIssue } from "./definition/hooks.js";
5
+ import { DELEGATE_INPUT_SCHEMA } from "./definition/delegate.js";
6
+ import { canonical } from "./utils/canonical.js";
5
7
  export const PROTOCOL_VERSION = 1;
6
8
  export const RequestIdSchema = z.string().min(1);
7
9
  export const IdempotencyKeySchema = z.string().min(1).max(256);
@@ -80,6 +82,7 @@ const toolManifestSchema = z
80
82
  description: z.string().optional(),
81
83
  inputSchema: jsonObject,
82
84
  outputSchema: jsonObject.optional(),
85
+ agent: z.lazy(() => AgentManifestSchema).optional(),
83
86
  })
84
87
  .strict();
85
88
  const hookPointSchema = z
@@ -122,6 +125,7 @@ export const AgentManifestSchema = z
122
125
  })
123
126
  .strict()
124
127
  .superRefine((manifest, ctx) => {
128
+ delegationIssues(manifest, (message) => ctx.addIssue({ code: "custom", message }));
125
129
  const ids = new Set();
126
130
  const names = new Set();
127
131
  const servers = new Set();
@@ -192,6 +196,36 @@ export const AgentManifestSchema = z
192
196
  }
193
197
  }
194
198
  });
199
+ /** Agents used as tools: one level deep, `{ task }` input, one shared sandbox spec. */
200
+ function delegationIssues(manifest, issue) {
201
+ const sandboxes = new Set();
202
+ const addSandboxes = (agent) => {
203
+ for (const capability of agent.capabilities)
204
+ if (capability.sandbox)
205
+ sandboxes.add(canonical(capability.sandbox));
206
+ };
207
+ addSandboxes(manifest);
208
+ for (const capability of manifest.capabilities)
209
+ for (const tool of capability.tools ?? []) {
210
+ const child = tool.agent;
211
+ if (!child)
212
+ continue;
213
+ if (tool.name !== child.id)
214
+ issue(`Tool '${tool.name}' must be named after the agent it runs ('${child.id}')`);
215
+ if (!child.description?.trim() || tool.description !== child.description)
216
+ issue(`Agent tool '${tool.name}' must carry the agent's non-empty description`);
217
+ if (canonical(tool.inputSchema) !== canonical(DELEGATE_INPUT_SCHEMA))
218
+ issue(`Agent tool '${tool.name}' must take the standard { task } input`);
219
+ if (tool.outputSchema !== undefined)
220
+ issue(`Agent tool '${tool.name}' must not declare outputSchema; the agent's outputSchema applies`);
221
+ for (const inner of child.capabilities)
222
+ if (inner.tools?.some((item) => item.agent !== undefined))
223
+ issue(`'${child.id}' delegates to another agent; nested delegation is not supported yet`);
224
+ addSandboxes(child);
225
+ }
226
+ if (sandboxes.size > 1)
227
+ issue("An agent and the agents it uses as tools must declare identical sandboxes");
228
+ }
195
229
  const absolutePath = z.string().min(1).refine((value) => value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value), { message: "plugin root must be an absolute path" });
196
230
  export const PutAgentRequestSchema = z
197
231
  .object({
@@ -412,6 +446,14 @@ export const RejectedResponseSchema = z.object({
412
446
  activeTurnId: z.string().optional(),
413
447
  requestId: z.string().optional(),
414
448
  });
449
+ /** The agent a call belongs to. Set on work for an agent used as a tool; absent for the root. */
450
+ export const AgentRefSchema = z
451
+ .object({
452
+ id: z.string().min(1),
453
+ path: z.string().min(1),
454
+ delegationId: z.string().min(1).optional(),
455
+ })
456
+ .strict();
415
457
  const actionBase = {
416
458
  actionId: z.string(),
417
459
  sessionId: z.string(),
@@ -425,6 +467,7 @@ const actionBase = {
425
467
  generation: z.number().int().nonnegative(),
426
468
  claimId: z.string().nullable(),
427
469
  leaseExpiresAt: z.string().nullable(),
470
+ agent: AgentRefSchema.optional(),
428
471
  };
429
472
  /** The hook point an action runs, and the capabilities that registered it (manifest order). */
430
473
  export const ActionHookSchema = z
package/dist/define.d.ts CHANGED
@@ -2,7 +2,9 @@ export { Agent, AgentBuilder, AgentBuildError, AgentLifecycleError, } from "./de
2
2
  export type { AgentOptions } from "./definition/builder.js";
3
3
  export { HarnessError, isHarnessError } from "./errors.js";
4
4
  export type { HarnessErrorCode, HarnessErrorDetails, HarnessErrorOptions, } from "./errors.js";
5
- export type { BuiltAgent } from "./types/agent.js";
5
+ export type { AgentTool, BuiltAgent } from "./types/agent.js";
6
+ export { DELEGATE_INPUT_SCHEMA, delegateManifest, delegateOf, delegatesOf, } from "./definition/delegate.js";
7
+ export type { Delegate } from "./definition/delegate.js";
6
8
  export { capability, middleware, model, tool } from "./definition/helpers.js";
7
9
  export { ToolError, isToolError } from "./definition/tool-error.js";
8
10
  export { defineSchema } from "./definition/schema.js";
@@ -12,14 +14,14 @@ export { SANDBOX_DEFERRED_FIELDS, SANDBOX_FIELDS, SANDBOX_NETWORK_PRESETS, SANDB
12
14
  export type { SandboxToolName } from "./utils/sandbox.js";
13
15
  export type { Implementations } from "./definition/implementations.js";
14
16
  export type { AgentManifest, CapabilityManifest, McpServerManifest, RuntimeManifest, SandboxManifest, SandboxNetworkPreset, SkillManifest, ToolManifest, ManifestSchemaVersion, } from "./types/manifest.js";
15
- export type { CapabilityDeclaration, CapabilityItems, MiddlewareContributions, SkillRecord, StepMiddleware, StepRequest, StepResponse, } from "./types/middleware.js";
17
+ export type { CapabilityDeclaration, CapabilityInput, CapabilityItems, MiddlewareContributions, SkillRecord, StepMiddleware, StepRequest, StepResponse, } from "./types/middleware.js";
16
18
  export type { Patch, Decision, TurnDecision, HookAt, HookScope, HookManifest, HookState, HookToolCall, BeforeHook, AfterHook, BeforeHooks, AfterHooks, BeforeTurnArgs, BeforeStepArgs, AfterStepArgs, AfterTurnArgs, } from "./types/dynamics.js";
17
19
  export { HOOK_POINTS, hasHook, hookListIssue, hooksFrom, runHookPoint, } from "./definition/hooks.js";
18
20
  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";
19
21
  export type { BuildDiagnostic, ContextItem, DeferredOutcome, JsonObject, JsonPrimitive, JsonValue, Tripwire, } from "./types/shared.js";
20
22
  export type { ObserveEvent, ObserveModelConfigurationSnapshot, ObserveModelRequested, ObserveSealedCall, ObserveToolSnapshot, Observer, } from "./types/observe.js";
21
23
  export type { InputEvent, MessageInput, InteractionReply, TranscriptEntry, UserContentPart, } from "./types/transcript.js";
22
- 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";
24
+ export type { Interaction, RequiredInteraction, ToolContent, ToolDefinition, ToolDescriptor, ToolExecutionContext, AgentRef, ToolExecutionResume, ToolInputSchema, ToolOutputSchema, ToolSchema, ToolSchemaSource, StandardToolSchema, StandardSchemaIssue, SchemaIssue, SchemaValidation, SchemaOutput, ToolOwner, ToolOutcome, ToolResult, ToolValidationFailureDetails, ToolEffects, ToolApproval, ToolRunResult, SessionStateBag, } from "./types/tool.js";
23
25
  export { normalizeToolDefinition, normalizedSchemasFor, } from "./definition/schema.js";
24
26
  export { implementationsFor, bindingFromAgent } from "./definition/binding.js";
25
27
  export type { AgentBinding } from "./definition/binding.js";
package/dist/define.js CHANGED
@@ -1,5 +1,6 @@
1
1
  export { Agent, AgentBuilder, AgentBuildError, AgentLifecycleError, } from "./definition/builder.js";
2
2
  export { HarnessError, isHarnessError } from "./errors.js";
3
+ export { DELEGATE_INPUT_SCHEMA, delegateManifest, delegateOf, delegatesOf, } from "./definition/delegate.js";
3
4
  export { capability, middleware, model, tool } from "./definition/helpers.js";
4
5
  export { ToolError, isToolError } from "./definition/tool-error.js";
5
6
  export { defineSchema } from "./definition/schema.js";
@@ -1,6 +1,8 @@
1
1
  import { bindAgent } from "./bind-agent.js";
2
2
  import { createManifest } from "./manifest.js";
3
3
  import { createSkillTools } from "./skill-tools.js";
4
+ import { DELEGATE_NAME_PATTERN, delegateOf, delegatesOf } from "./delegate.js";
5
+ import { canonical } from "../utils/canonical.js";
4
6
  const diagnostic = (code, message, extra = {}) => Object.freeze({ code, message, ...extra });
5
7
  export function assembleAgent(middleware, identity, dynamics = new Map()) {
6
8
  const diagnostics = [];
@@ -72,6 +74,7 @@ export function assembleAgent(middleware, identity, dynamics = new Map()) {
72
74
  else
73
75
  toolOwners.set(entry.name, item.id);
74
76
  }
77
+ diagnostics.push(...delegationDiagnostics(skilled.items));
75
78
  if (diagnostics.length)
76
79
  return Object.freeze({
77
80
  ok: false,
@@ -90,6 +93,38 @@ export function assembleAgent(middleware, identity, dynamics = new Map()) {
90
93
  const agent = bindAgent(frozenMiddleware, manifest, identity, dynamics);
91
94
  return Object.freeze({ ok: true, agent, manifest });
92
95
  }
96
+ /** v1 delegation is one level deep and non-interactive; anything else fails the build by name. */
97
+ function delegationDiagnostics(items) {
98
+ const found = [];
99
+ const sandboxes = new Set();
100
+ for (const item of items)
101
+ if (item.sandbox)
102
+ sandboxes.add(canonical(item.sandbox));
103
+ for (const item of items)
104
+ for (const tool of item.tools ?? []) {
105
+ const delegate = delegateOf(tool);
106
+ if (!delegate)
107
+ continue;
108
+ const child = delegate.manifest;
109
+ const extra = { toolName: tool.name };
110
+ if (!DELEGATE_NAME_PATTERN.test(child.id))
111
+ found.push(diagnostic("delegation.invalid-name", `Agent '${child.id}' is used as a tool, so its id must be 1-64 letters, digits, '_' or '-'`, extra));
112
+ if (!child.description?.trim())
113
+ found.push(diagnostic("delegation.description-required", `Agent '${child.id}' is used as a tool by capability '${item.id}' and needs a description: the parent's model reads it to decide when to delegate`, extra));
114
+ const nested = delegatesOf(child)[0];
115
+ if (nested)
116
+ found.push(diagnostic("delegation.nested", `'${child.id}' delegates to '${nested.manifest.id}'; nested delegation is not supported yet`, extra));
117
+ for (const childTool of delegate.agent?.getBinding().tools ?? [])
118
+ if (childTool.approval)
119
+ found.push(diagnostic("delegation.approval-unsupported", `'${childTool.name}' in '${child.id}' needs approval; agents used as tools can't ask for it yet, so keep it on the parent`, extra));
120
+ for (const capability of child.capabilities)
121
+ if (capability.sandbox)
122
+ sandboxes.add(canonical(capability.sandbox));
123
+ }
124
+ if (sandboxes.size > 1)
125
+ found.push(diagnostic("sandbox.mismatch", "An agent and the agents it uses as tools share one sandbox, so every sandbox they declare must be identical"));
126
+ return found;
127
+ }
93
128
  const SKILL_TOOL_NAMES = new Set(["load_skill", "read_skill_resource"]);
94
129
  function attachSkillTools(items) {
95
130
  const skills = new Map();
@@ -1,5 +1,6 @@
1
1
  import { HarnessError } from "../errors.js";
2
2
  import { normalizeToolDefinition, normalizedSchemasFor } from "./schema.js";
3
+ import { delegateOf } from "./delegate.js";
3
4
  /** Prepares an executable Tool and records its middleware slot provenance. */
4
5
  export function bindTool(item, owner) {
5
6
  const prepared = normalizeToolDefinition(item);
@@ -8,6 +9,7 @@ export function bindTool(item, owner) {
8
9
  if (typeof prepared.execute !== "function")
9
10
  throw new HarnessError("tool.invalid", `Tool '${prepared.name}' must provide execute()`);
10
11
  const schemas = normalizedSchemasFor(prepared);
12
+ const delegate = delegateOf(item);
11
13
  return Object.freeze({
12
14
  // Keep the original object identity so ToolRegistry WeakMap lookups succeed.
13
15
  source: item,
@@ -21,5 +23,6 @@ export function bindTool(item, owner) {
21
23
  ...(prepared.approval === undefined ? {} : { approval: prepared.approval }),
22
24
  ...(prepared.effects === undefined ? {} : { effects: prepared.effects }),
23
25
  owner: Object.freeze({ ...owner }),
26
+ ...(delegate === undefined ? {} : { delegate }),
24
27
  });
25
28
  }
@@ -2,6 +2,7 @@ import type { JsonObject } from "../types/shared.js";
2
2
  import type { McpServerManifest, SandboxManifest, SkillManifest } from "../types/manifest.js";
3
3
  import type { SkillRecord } from "../types/middleware.js";
4
4
  import type { HookManifest } from "../types/dynamics.js";
5
+ import type { Delegate } from "./delegate.js";
5
6
  import type { MiddlewareContributions, StepMiddleware } from "../types/middleware.js";
6
7
  import type { ToolApproval, ToolDefinition, ToolEffects, ToolExecutionContext, ToolInputSchema, ToolOutputSchema, ToolOwner, ToolRunResult, ToolSchema } from "../types/tool.js";
7
8
  export interface BoundToolDefinition<Info = unknown> extends Omit<ToolDefinition<ToolInputSchema, Info, ToolOutputSchema | undefined>, "inputSchema" | "outputSchema" | "execute" | "run" | "input" | "output"> {
@@ -12,6 +13,8 @@ export interface BoundToolDefinition<Info = unknown> extends Omit<ToolDefinition
12
13
  readonly effects?: ToolEffects;
13
14
  readonly owner: ToolOwner;
14
15
  readonly source: ToolDefinition<any, any, any>;
16
+ /** Set when this tool is an agent used as a tool; the engine runs it. */
17
+ readonly delegate?: Delegate;
15
18
  }
16
19
  export interface BoundMiddleware {
17
20
  readonly id: string;
@@ -1,9 +1,9 @@
1
1
  import type { BoundMiddleware } from "./bound.js";
2
- import type { CapabilityDeclaration, StepMiddleware } from "../types/middleware.js";
2
+ import type { CapabilityInput, StepMiddleware } from "../types/middleware.js";
3
3
  import type { BuildDiagnostic, JsonObject } from "../types/shared.js";
4
4
  import { HarnessError } from "../errors.js";
5
5
  import type { ToolDefinition, ToolSchemaSource, SchemaOutput } from "../types/tool.js";
6
- import type { BuiltAgent } from "../types/agent.js";
6
+ import type { AgentTool, BuiltAgent } from "../types/agent.js";
7
7
  import type { AgentManifest } from "../types/manifest.js";
8
8
  import type { AfterHook, BeforeHook, HookScope } from "../types/dynamics.js";
9
9
  import type { Implementations } from "./implementations.js";
@@ -15,8 +15,8 @@ export interface AgentOptions<Schema extends ToolSchemaSource | undefined = unde
15
15
  readonly description?: string;
16
16
  readonly metadata?: JsonObject;
17
17
  readonly instructions?: string | readonly string[];
18
- /** Top-level tools (H2). Composed as capability id `"agent"`. */
19
- readonly tools?: readonly ToolDefinition<any, any, any>[];
18
+ /** Top-level tools (H2), and agents used as tools. Composed as capability id `"agent"`. */
19
+ readonly tools?: readonly (ToolDefinition<any, any, any> | AgentTool)[];
20
20
  }
21
21
  interface BuilderSnapshot {
22
22
  readonly id: string;
@@ -56,7 +56,7 @@ export declare class AgentBuilder<Info = unknown, Schema extends ToolSchemaSourc
56
56
  toJSON(): AgentManifest;
57
57
  use(middleware: StepMiddleware<Info>): AgentBuilder<Info, Schema>;
58
58
  use(id: string, middleware: StepMiddleware<Info>): AgentBuilder<Info, Schema>;
59
- use(declaration: CapabilityDeclaration<Info>): AgentBuilder<Info, Schema>;
59
+ use(declaration: CapabilityInput<Info>): AgentBuilder<Info, Schema>;
60
60
  /**
61
61
  * Run `fn` before each turn (`"turn"`) or before every model call (`"step"`).
62
62
  * The returned Patch applies to the whole turn or to that one model call.
@@ -1,5 +1,5 @@
1
1
  import type { BoundMiddleware } from "./bound.js";
2
- import type { CapabilityDeclaration, StepMiddleware } from "../types/middleware.js";
2
+ import type { CapabilityInput, StepMiddleware } from "../types/middleware.js";
3
3
  import type { AfterHooks, BeforeHooks } from "../types/dynamics.js";
4
4
  export interface CompiledCapability {
5
5
  readonly bound: BoundMiddleware;
@@ -7,4 +7,4 @@ export interface CompiledCapability {
7
7
  readonly after?: AfterHooks<any>;
8
8
  readonly middleware?: StepMiddleware<any>;
9
9
  }
10
- export declare function compileDeclaration<State>(declaration: CapabilityDeclaration<State>): CompiledCapability;
10
+ export declare function compileDeclaration<State>(declaration: CapabilityInput<State>): CompiledCapability;
@@ -1,6 +1,7 @@
1
1
  import { hooksFrom } from "./hooks.js";
2
+ import { delegateTool, isAgentItem } from "./delegate.js";
2
3
  export function compileDeclaration(declaration) {
3
- const tools = copyItems(declaration.tools, declaration.id);
4
+ const tools = asTools(copyItems(declaration.tools, declaration.id));
4
5
  const instructions = copyItems(declaration.instructions, declaration.id);
5
6
  const model = declaration.model;
6
7
  const hooks = hooksFrom(declaration.before, declaration.after);
@@ -91,3 +92,14 @@ function copyItems(value, defaultSlot) {
91
92
  items: Object.freeze([...value.items]),
92
93
  });
93
94
  }
95
+ /** Agents placed in `tools` become the tools that delegate to them. */
96
+ function asTools(value) {
97
+ if (value === undefined)
98
+ return undefined;
99
+ if (!value.items.some(isAgentItem))
100
+ return value;
101
+ return Object.freeze({
102
+ slot: value.slot,
103
+ items: Object.freeze(value.items.map((item) => (isAgentItem(item) ? delegateTool(item) : item))),
104
+ });
105
+ }
@@ -0,0 +1,35 @@
1
+ import type { BuiltAgent } from "../types/agent.js";
2
+ import type { AgentManifest } from "../types/manifest.js";
3
+ import type { JsonObject } from "../types/shared.js";
4
+ import type { ToolDefinition } from "../types/tool.js";
5
+ /** An agent used as another agent's tool. The engine runs it; customer code never does. */
6
+ export interface Delegate {
7
+ /** The child's manifest, inlined into the parent's tool. */
8
+ readonly manifest: AgentManifest;
9
+ /** The authored child, when available locally. Absent when rebuilt from a manifest. */
10
+ readonly agent?: BuiltAgent;
11
+ }
12
+ /** Model-facing tool names: what every supported provider accepts. */
13
+ export declare const DELEGATE_NAME_PATTERN: RegExp;
14
+ /** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
15
+ export declare const DELEGATE_INPUT_SCHEMA: JsonObject;
16
+ /** A built agent or an agent builder; both expose getBinding() and manifest. */
17
+ export declare function isAgentItem(value: unknown): value is Pick<BuiltAgent, "id" | "manifest" | "getBinding"> & {
18
+ build?: () => BuiltAgent;
19
+ };
20
+ /** Turn an agent placed in `tools` into the tool that delegates to it. */
21
+ export declare function delegateTool(item: unknown): ToolDefinition;
22
+ /** Rebuild the delegating tool from a manifest's `agent` body. */
23
+ export declare function delegateFromManifest(manifest: AgentManifest, tool: {
24
+ readonly description?: string;
25
+ readonly inputSchema: JsonObject;
26
+ }): ToolDefinition;
27
+ /** The delegate behind a tool definition, or behind the bound snapshot of one. */
28
+ export declare function delegateOf(tool: unknown): Delegate | undefined;
29
+ /** The agents a manifest delegates to, with the capability and tool that declare each. */
30
+ export declare function delegatesOf(manifest: AgentManifest): readonly {
31
+ readonly capabilityId: string;
32
+ readonly manifest: AgentManifest;
33
+ }[];
34
+ /** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
35
+ export declare function delegateManifest(manifest: AgentManifest, id: string): AgentManifest | undefined;
@@ -0,0 +1,72 @@
1
+ import { z } from "zod";
2
+ import { ToolError } from "./tool-error.js";
3
+ import { normalizeSchema } from "./schema.js";
4
+ import { schemaFromJSON } from "./schema-json.js";
5
+ /** Survives duplicate installed copies of core, like the error brands. */
6
+ const DELEGATE = Symbol.for("@nylorun/core/delegate");
7
+ /** Model-facing tool names: what every supported provider accepts. */
8
+ export const DELEGATE_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
9
+ const taskSchema = z
10
+ .object({
11
+ task: z
12
+ .string()
13
+ .min(1)
14
+ .describe("A complete, self-contained task. The agent sees nothing else."),
15
+ })
16
+ .strict();
17
+ /** The input every agent used as a tool accepts. Part of the hashed manifest; change deliberately. */
18
+ export const DELEGATE_INPUT_SCHEMA = normalizeSchema(taskSchema, "input").jsonSchema;
19
+ async function engineOnly() {
20
+ throw new ToolError("delegation.engine-only", "Agents used as tools are run by the Nylorun engine, not by an executor");
21
+ }
22
+ /** A built agent or an agent builder; both expose getBinding() and manifest. */
23
+ export function isAgentItem(value) {
24
+ if (value === null || typeof value !== "object")
25
+ return false;
26
+ const item = value;
27
+ return (typeof item.getBinding === "function" &&
28
+ typeof item.execute !== "function" &&
29
+ typeof item.run !== "function");
30
+ }
31
+ /** Turn an agent placed in `tools` into the tool that delegates to it. */
32
+ export function delegateTool(item) {
33
+ const candidate = item;
34
+ const agent = typeof candidate.build === "function" ? candidate.build() : candidate;
35
+ return withDelegate(agent.manifest, agent);
36
+ }
37
+ /** Rebuild the delegating tool from a manifest's `agent` body. */
38
+ export function delegateFromManifest(manifest, tool) {
39
+ return withDelegate(manifest, undefined, tool);
40
+ }
41
+ function withDelegate(manifest, agent, declared) {
42
+ const description = declared ? declared.description : manifest.description;
43
+ const definition = {
44
+ name: manifest.id,
45
+ ...(description === undefined ? {} : { description }),
46
+ inputSchema: declared ? schemaFromJSON(declared.inputSchema) : taskSchema,
47
+ execute: engineOnly,
48
+ };
49
+ const delegate = Object.freeze({ manifest, ...(agent ? { agent } : {}) });
50
+ Object.defineProperty(definition, DELEGATE, { value: delegate, enumerable: false });
51
+ return Object.freeze(definition);
52
+ }
53
+ /** The delegate behind a tool definition, or behind the bound snapshot of one. */
54
+ export function delegateOf(tool) {
55
+ if (tool === null || typeof tool !== "object")
56
+ return undefined;
57
+ const value = tool;
58
+ return value[DELEGATE] ?? (value.source === tool ? undefined : delegateOf(value.source));
59
+ }
60
+ /** The agents a manifest delegates to, with the capability and tool that declare each. */
61
+ export function delegatesOf(manifest) {
62
+ const found = [];
63
+ for (const capability of manifest.capabilities)
64
+ for (const tool of capability.tools ?? [])
65
+ if (tool.agent)
66
+ found.push({ capabilityId: capability.id, manifest: tool.agent });
67
+ return found;
68
+ }
69
+ /** The manifest of the delegated agent `id`, or undefined. One level deep by construction. */
70
+ export function delegateManifest(manifest, id) {
71
+ return delegatesOf(manifest).find((item) => item.manifest.id === id)?.manifest;
72
+ }
@@ -3,6 +3,7 @@ import { assembleAgent } from "./assemble.js";
3
3
  import { schemaFromJSON } from "./schema-json.js";
4
4
  import { copyJsonObject, deepFreeze } from "../utils/immutable.js";
5
5
  import { HOOK_POINTS, hasHook, hookListIssue } from "./hooks.js";
6
+ import { delegateFromManifest, delegateOf } from "./delegate.js";
6
7
  /** Rebuild an agent from manifest JSON + in-process implementations (T28). */
7
8
  export function agentFrom(json, implementations, options) {
8
9
  const manifest = normalizeManifest(json);
@@ -26,7 +27,9 @@ export function agentFrom(json, implementations, options) {
26
27
  (async (request, next) => {
27
28
  const advertised = [...tools, ...session];
28
29
  if (advertised.length)
29
- request.configuration.tools.set(capability.id, advertised.map((tool) => implementations[capability.id]?.tools?.[tool.name] ?? tool));
30
+ request.configuration.tools.set(capability.id, advertised.map((tool) => (delegateOf(tool)
31
+ ? tool
32
+ : implementations[capability.id]?.tools?.[tool.name]) ?? tool));
30
33
  if (capability.instructions)
31
34
  request.configuration.instructions.set(capability.id, capability.instructions);
32
35
  return next();
@@ -41,7 +44,7 @@ export function agentFrom(json, implementations, options) {
41
44
  hasMiddleware: impl.middleware !== undefined,
42
45
  tools: capability.tools !== undefined
43
46
  ? tools.map((tool) => {
44
- const live = impl.tools?.[tool.name];
47
+ const live = delegateOf(tool) ? tool : impl.tools?.[tool.name];
45
48
  if (!live)
46
49
  throw new HarnessError("agent.build-failed", `Missing tool implementation '${tool.name}' for capability '${capability.id}'`);
47
50
  return live;
@@ -117,6 +120,13 @@ function resolveTools(capability, tools) {
117
120
  return [];
118
121
  return capability.tools.flatMap((declared) => {
119
122
  const live = tools?.[declared.name];
123
+ // The engine runs agents used as tools; an authored delegate keeps its local child.
124
+ if (declared.agent)
125
+ return [
126
+ live && delegateOf(live)?.manifest.id === declared.agent.id
127
+ ? live
128
+ : delegateFromManifest(declared.agent, declared),
129
+ ];
120
130
  if (live)
121
131
  return [live];
122
132
  if ((declared.name === "load_skill" || declared.name === "read_skill_resource") &&
@@ -314,5 +324,8 @@ function normalizeTool(tool) {
314
324
  ...(tool.outputSchema === undefined
315
325
  ? {}
316
326
  : { outputSchema: tool.outputSchema }),
327
+ ...(tool.agent === undefined
328
+ ? {}
329
+ : { agent: normalizeManifest(tool.agent) }),
317
330
  });
318
331
  }
@@ -11,7 +11,7 @@ export declare function capability<Info = unknown>(declaration: {
11
11
  readonly id: string;
12
12
  readonly name?: string;
13
13
  readonly description?: string;
14
- readonly tools?: readonly ToolDefinition<any, Info, any>[];
14
+ readonly tools?: readonly (ToolDefinition<any, Info, any> | import("../types/agent.js").AgentTool)[];
15
15
  readonly instructions?: string | readonly string[];
16
16
  /** Run before each turn or before every model call (step). */
17
17
  readonly before?: import("../types/dynamics.js").BeforeHooks<Info>;
@@ -1,4 +1,5 @@
1
1
  import { prepareTool } from "./schema.js";
2
+ import { delegateTool, isAgentItem } from "./delegate.js";
2
3
  export const tool = (value) => prepareTool(value);
3
4
  /** @deprecated Prefer Runtime model resolution. Capability-disguised `.use({ model })` is not the taught path. */
4
5
  export const model = (value) => value;
@@ -17,7 +18,13 @@ export function capability(declaration) {
17
18
  ...(declaration.description === undefined
18
19
  ? {}
19
20
  : { description: declaration.description }),
20
- ...(declaration.tools === undefined ? {} : { tools: declaration.tools }),
21
+ ...(declaration.tools === undefined
22
+ ? {}
23
+ : {
24
+ tools: declaration.tools.map((item) => isAgentItem(item)
25
+ ? delegateTool(item)
26
+ : item),
27
+ }),
21
28
  ...(instructions === undefined ? {} : { instructions }),
22
29
  ...(declaration.before === undefined ? {} : { before: declaration.before }),
23
30
  ...(declaration.after === undefined ? {} : { after: declaration.after }),
@@ -1,5 +1,6 @@
1
1
  import { bindOutputContract } from "./output-contract.js";
2
2
  import { normalizedSchemasFor } from "./schema.js";
3
+ import { delegateOf } from "./delegate.js";
3
4
  import { copyJsonObject, deepFreeze } from "../utils/immutable.js";
4
5
  export function createManifest(input) {
5
6
  const capabilities = input.middleware.map((item) => projectCapability(item));
@@ -51,6 +52,7 @@ function projectCapability(item) {
51
52
  }
52
53
  function projectTool(tool) {
53
54
  const schemas = normalizedSchemasFor(tool);
55
+ const delegate = delegateOf(tool);
54
56
  return {
55
57
  name: tool.name,
56
58
  ...(tool.description === undefined
@@ -60,5 +62,6 @@ function projectTool(tool) {
60
62
  ...(schemas.outputSchema === undefined
61
63
  ? {}
62
64
  : { outputSchema: schemas.outputSchema.jsonSchema }),
65
+ ...(delegate === undefined ? {} : { agent: delegate.manifest }),
63
66
  };
64
67
  }
@@ -8,3 +8,8 @@ export interface BuiltAgent<Info = unknown, Output = string> {
8
8
  toJSON(): AgentManifest;
9
9
  getBinding(): AgentBinding;
10
10
  }
11
+ /**
12
+ * An agent placed in another agent's `tools`: a built agent or an `Agent(...)` builder.
13
+ * It becomes a tool named after the agent's id that takes `{ task: string }`.
14
+ */
15
+ export type AgentTool = Pick<BuiltAgent<any, any>, "id" | "manifest" | "getBinding">;
@@ -7,6 +7,11 @@ export interface ToolManifest {
7
7
  readonly description?: string;
8
8
  readonly inputSchema: JsonObject;
9
9
  readonly outputSchema?: JsonObject;
10
+ /**
11
+ * Present when this tool is another agent. The engine runs it with a fresh context and
12
+ * returns its final output; its input is always `{ task: string }`. One level deep.
13
+ */
14
+ readonly agent?: AgentManifest;
10
15
  }
11
16
  export interface SkillManifest {
12
17
  readonly name: string;
@@ -1,5 +1,6 @@
1
1
  import type { ContextMutationOptions, ModelCandidate, ModelDirective, ModelToolCall, ModelConfigurationMutationOptions } from "./model.js";
2
2
  import type { InputEvent, TranscriptEntry } from "./transcript.js";
3
+ import type { AgentTool } from "./agent.js";
3
4
  import type { McpServerManifest, SandboxManifest, SkillManifest } from "./manifest.js";
4
5
  /** Skill files held on the developer binding. Not a manifest field. */
5
6
  export interface SkillRecord {
@@ -85,6 +86,10 @@ export interface CapabilityDeclaration<Info = unknown> {
85
86
  /** Run after each model call (step) or after the turn's final answer. */
86
87
  readonly after?: AfterHooks<Info>;
87
88
  }
89
+ /** What `.use()` accepts: a capability whose `tools` may also hold agents used as tools. */
90
+ export type CapabilityInput<Info = unknown> = Omit<CapabilityDeclaration<Info>, "tools"> & {
91
+ readonly tools?: CapabilityItems<ToolDefinition<any, Info, any> | AgentTool>;
92
+ };
88
93
  export interface MiddlewareContributions {
89
94
  readonly instructions?: readonly string[];
90
95
  readonly tools?: readonly {
@@ -1,7 +1,7 @@
1
1
  import type { ContextSnapshot, ModelCandidate, ModelCall, ModelConfigurationSnapshot } from "./model.js";
2
2
  import type { JsonObject, JsonValue } from "./shared.js";
3
3
  import type { InputEvent, TranscriptEntry } from "./transcript.js";
4
- import type { RequiredInteraction, ToolDescriptor, ToolResult } from "./tool.js";
4
+ import type { AgentRef, RequiredInteraction, ToolDescriptor, ToolResult } from "./tool.js";
5
5
  export type ObserveToolSnapshot = ToolDescriptor;
6
6
  /** JSON-only model-configuration view suitable for an observation stream. */
7
7
  export interface ObserveModelConfigurationSnapshot extends Omit<ModelConfigurationSnapshot, "tools"> {
@@ -144,6 +144,28 @@ export type ObserveEvent = {
144
144
  readonly attributes: {
145
145
  readonly token?: JsonValue;
146
146
  };
147
+ } | {
148
+ readonly type: "delegation.started";
149
+ readonly turnId: string;
150
+ readonly stepId: string;
151
+ readonly callId: string;
152
+ readonly invocationId: string;
153
+ readonly toolName: string;
154
+ readonly agent: AgentRef;
155
+ readonly attributes: {
156
+ readonly task: string;
157
+ };
158
+ } | {
159
+ readonly type: "delegation.completed";
160
+ readonly turnId: string;
161
+ readonly stepId: string;
162
+ readonly callId: string;
163
+ readonly invocationId: string;
164
+ readonly toolName: string;
165
+ readonly agent: AgentRef;
166
+ /** The agent's own end state: completed, failed, cancelled or paused. */
167
+ readonly status: string;
168
+ readonly attributes: ToolResult;
147
169
  } | {
148
170
  readonly type: "turn.completed";
149
171
  readonly turnId: string;
@@ -102,6 +102,15 @@ export interface ToolExecutionResume {
102
102
  readonly value?: JsonValue;
103
103
  readonly token?: JsonValue;
104
104
  }
105
+ /**
106
+ * The agent a call belongs to. `path` is `"<root>"` or `"<root>/<child>"`; `delegationId`
107
+ * identifies one run of an agent used as a tool and is absent for the root agent.
108
+ */
109
+ export interface AgentRef {
110
+ readonly id: string;
111
+ readonly path: string;
112
+ readonly delegationId?: string;
113
+ }
105
114
  interface ToolExecutionContextBase {
106
115
  readonly executionId: string;
107
116
  readonly turnId: string;
@@ -122,6 +131,8 @@ interface ToolExecutionContextBase {
122
131
  readonly session: {
123
132
  readonly id: string;
124
133
  };
134
+ /** The agent this call belongs to: the root agent, or an agent used as a tool. */
135
+ readonly agent?: AgentRef;
125
136
  /** Live progress stub — emits an observation when a listener is present. */
126
137
  progress(message: string, data?: JsonObject): void;
127
138
  /** Durable wait: park for a human/app response. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nylorun/core",
3
- "version": "0.3.0-beta",
3
+ "version": "0.4.0-beta",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "Shared agent definitions and wire contracts",