@nylorun/core 0.2.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.
@@ -2,6 +2,8 @@ import { HarnessError } from "../errors.js";
2
2
  import { assembleAgent } from "./assemble.js";
3
3
  import { schemaFromJSON } from "./schema-json.js";
4
4
  import { copyJsonObject, deepFreeze } from "../utils/immutable.js";
5
+ import { HOOK_POINTS, hasHook, hookListIssue } from "./hooks.js";
6
+ import { delegateFromManifest, delegateOf } from "./delegate.js";
5
7
  /** Rebuild an agent from manifest JSON + in-process implementations (T28). */
6
8
  export function agentFrom(json, implementations, options) {
7
9
  const manifest = normalizeManifest(json);
@@ -20,15 +22,14 @@ export function agentFrom(json, implementations, options) {
20
22
  throw new HarnessError("agent.build-failed", `Missing session tool implementation '${item.name}' for capability '${capability.id}'`);
21
23
  return live;
22
24
  });
23
- if (capability.beforeModelCall && !impl.beforeModelCall)
24
- throw new HarnessError("agent.build-failed", `Missing beforeModelCall implementation for capability '${capability.id}'`);
25
- if (capability.afterModelCall && !impl.afterModelCall)
26
- throw new HarnessError("agent.build-failed", `Missing afterModelCall implementation for capability '${capability.id}'`);
25
+ assertHookImplementations(capability, impl);
27
26
  const handle = impl.middleware ??
28
27
  (async (request, next) => {
29
28
  const advertised = [...tools, ...session];
30
29
  if (advertised.length)
31
- 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));
32
33
  if (capability.instructions)
33
34
  request.configuration.instructions.set(capability.id, capability.instructions);
34
35
  return next();
@@ -43,7 +44,7 @@ export function agentFrom(json, implementations, options) {
43
44
  hasMiddleware: impl.middleware !== undefined,
44
45
  tools: capability.tools !== undefined
45
46
  ? tools.map((tool) => {
46
- const live = impl.tools?.[tool.name];
47
+ const live = delegateOf(tool) ? tool : impl.tools?.[tool.name];
47
48
  if (!live)
48
49
  throw new HarnessError("agent.build-failed", `Missing tool implementation '${tool.name}' for capability '${capability.id}'`);
49
50
  return live;
@@ -65,8 +66,7 @@ export function agentFrom(json, implementations, options) {
65
66
  }
66
67
  : {}),
67
68
  }),
68
- ...(capability.beforeModelCall ? { beforeModelCall: true } : {}),
69
- ...(capability.afterModelCall ? { afterModelCall: true } : {}),
69
+ ...(capability.hooks === undefined ? {} : { hooks: capability.hooks }),
70
70
  manifestType: capability.type,
71
71
  ...(capability.metadata === undefined
72
72
  ? {}
@@ -74,17 +74,16 @@ export function agentFrom(json, implementations, options) {
74
74
  ...(capability.mcpServers === undefined
75
75
  ? {}
76
76
  : { mcpServers: capability.mcpServers }),
77
+ ...(capability.sandbox === undefined
78
+ ? {}
79
+ : { sandbox: capability.sandbox }),
77
80
  ...(capability.skills === undefined
78
81
  ? {}
79
82
  : { skills: capability.skills }),
80
83
  }));
81
84
  dynamics.set(capability.id, {
82
- ...(impl.beforeModelCall
83
- ? { beforeModelCall: impl.beforeModelCall }
84
- : {}),
85
- ...(impl.afterModelCall
86
- ? { afterModelCall: impl.afterModelCall }
87
- : {}),
85
+ ...(impl.before ? { before: impl.before } : {}),
86
+ ...(impl.after ? { after: impl.after } : {}),
88
87
  ...(impl.middleware ? { middleware: impl.middleware } : {}),
89
88
  });
90
89
  }
@@ -121,6 +120,13 @@ function resolveTools(capability, tools) {
121
120
  return [];
122
121
  return capability.tools.flatMap((declared) => {
123
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
+ ];
124
130
  if (live)
125
131
  return [live];
126
132
  if ((declared.name === "load_skill" || declared.name === "read_skill_resource") &&
@@ -130,6 +136,16 @@ function resolveTools(capability, tools) {
130
136
  throw new HarnessError("agent.build-failed", `Missing tool implementation '${declared.name}' for capability '${capability.id}'`);
131
137
  });
132
138
  }
139
+ function assertHookImplementations(capability, impl) {
140
+ for (const point of HOOK_POINTS) {
141
+ const declared = hasHook(capability.hooks, point.at, point.scope);
142
+ const live = impl[point.at]?.[point.scope] !== undefined;
143
+ if (declared && !live)
144
+ throw new HarnessError("agent.build-failed", `Missing ${point.at}("${point.scope}") implementation for capability '${capability.id}'`);
145
+ if (live && !declared)
146
+ throw new HarnessError("agent.build-failed", `Capability '${capability.id}' implements ${point.at}("${point.scope}") but the manifest does not declare it`);
147
+ }
148
+ }
133
149
  function normalizeManifest(json) {
134
150
  if (!json || typeof json !== "object" || Array.isArray(json))
135
151
  throw new HarnessError("agent.build-failed", "Agent.from requires a manifest object");
@@ -144,8 +160,10 @@ function normalizeManifest(json) {
144
160
  throw new HarnessError("agent.build-failed", "Manifest capabilities must be an array");
145
161
  if ("schemaVersion" in value && value.schemaVersion !== undefined)
146
162
  throw new HarnessError("agent.build-failed", "Manifest field schemaVersion was renamed to manifestSchemaVersion");
147
- if (value.manifestSchemaVersion !== 3)
148
- throw new HarnessError("agent.build-failed", `Unsupported manifestSchemaVersion ${String(value.manifestSchemaVersion)}`);
163
+ if (value.manifestSchemaVersion !== 4)
164
+ throw new HarnessError("agent.build-failed", value.manifestSchemaVersion === 3
165
+ ? "manifestSchemaVersion 3 is no longer supported; rebuild the agent with before/after hooks (see MIGRATION.md)"
166
+ : `Unsupported manifestSchemaVersion ${String(value.manifestSchemaVersion)}`);
149
167
  // Reject top-level model (Runtime-owned).
150
168
  if ("model" in value && value.model !== undefined)
151
169
  throw new HarnessError("agent.build-failed", "Manifest must not include top-level model; Runtime owns model resolution");
@@ -166,7 +184,7 @@ function normalizeManifest(json) {
166
184
  servers.add(name);
167
185
  }
168
186
  return deepFreeze({
169
- manifestSchemaVersion: 3,
187
+ manifestSchemaVersion: 4,
170
188
  id: value.id,
171
189
  ...(typeof value.name === "string" && value.name ? { name: value.name } : {}),
172
190
  ...(typeof value.description === "string"
@@ -204,6 +222,14 @@ function normalizeCapability(capability) {
204
222
  throw new HarnessError("agent.build-failed", `Capability '${capability.id}' must not include model; Runtime owns model resolution`);
205
223
  if (capability.type !== "agent" && capability.type !== "agent-plugin")
206
224
  throw new HarnessError("agent.build-failed", `Capability '${capability.id}' type must be agent or agent-plugin`);
225
+ for (const legacy of ["beforeModelCall", "afterModelCall"])
226
+ if (legacy in raw)
227
+ throw new HarnessError("agent.build-failed", `Capability '${capability.id}' field ${legacy} was replaced by hooks (see MIGRATION.md)`);
228
+ if (capability.hooks !== undefined) {
229
+ const issue = hookListIssue(capability.hooks);
230
+ if (issue)
231
+ throw new HarnessError("agent.build-failed", `Capability '${capability.id}' ${issue}`);
232
+ }
207
233
  const metadata = capability.metadata === undefined
208
234
  ? undefined
209
235
  : copyJsonObject(capability.metadata, "metadata");
@@ -225,8 +251,16 @@ function normalizeCapability(capability) {
225
251
  : {}),
226
252
  ...(skills === undefined ? {} : { skills }),
227
253
  ...(mcpServers === undefined ? {} : { mcpServers }),
228
- ...(capability.beforeModelCall ? { beforeModelCall: true } : {}),
229
- ...(capability.afterModelCall ? { afterModelCall: true } : {}),
254
+ ...(capability.sandbox === undefined
255
+ ? {}
256
+ : {
257
+ sandbox: deepFreeze(copyJsonObject(capability.sandbox, "sandbox")),
258
+ }),
259
+ ...(capability.hooks === undefined
260
+ ? {}
261
+ : {
262
+ hooks: Object.freeze(capability.hooks.map((hook) => Object.freeze({ at: hook.at, scope: hook.scope }))),
263
+ }),
230
264
  });
231
265
  }
232
266
  function normalizeSkills(capabilityId, skills) {
@@ -290,5 +324,8 @@ function normalizeTool(tool) {
290
324
  ...(tool.outputSchema === undefined
291
325
  ? {}
292
326
  : { outputSchema: tool.outputSchema }),
327
+ ...(tool.agent === undefined
328
+ ? {}
329
+ : { agent: normalizeManifest(tool.agent) }),
293
330
  });
294
331
  }
@@ -4,18 +4,20 @@ import type { ToolDefinition, ToolInputSchema, ToolOutputSchema, ToolSchemaSourc
4
4
  export declare const tool: <InputSchema extends ToolInputSchema, Info = unknown, OutputSchema extends ToolOutputSchema | undefined = undefined>(value: ToolDefinition<InputSchema, Info, OutputSchema>) => ToolDefinition<InputSchema, Info, OutputSchema>;
5
5
  /** @deprecated Prefer Runtime model resolution. Capability-disguised `.use({ model })` is not the taught path. */
6
6
  export declare const model: <T extends ModelAdapter>(value: T) => T;
7
- /** @deprecated Prefer `beforeModelCall` / `afterModelCall`. Kept through 1.0. */
7
+ /** @deprecated Prefer `before` / `after` hooks. Kept through 1.0. */
8
8
  export declare const middleware: <T extends StepMiddleware>(value: T) => T;
9
- /** Compose a reusable capability bundle (tools, instructions, optional dynamics). */
9
+ /** Compose a reusable capability bundle (tools, instructions, optional hooks). */
10
10
  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
- readonly beforeModelCall?: import("../types/dynamics.js").BeforeModelCallFn<Info>;
17
- readonly afterModelCall?: import("../types/dynamics.js").AfterModelCallFn<Info>;
18
- /** @deprecated Prefer beforeModelCall / afterModelCall. */
16
+ /** Run before each turn or before every model call (step). */
17
+ readonly before?: import("../types/dynamics.js").BeforeHooks<Info>;
18
+ /** Run after every model call (step) or after the turn's final answer. */
19
+ readonly after?: import("../types/dynamics.js").AfterHooks<Info>;
20
+ /** @deprecated Prefer before / after hooks. */
19
21
  readonly middleware?: StepMiddleware<Info>;
20
22
  /** @deprecated Model resolution is Runtime-owned; not projected into the manifest. */
21
23
  readonly model?: import("../types/model.js").ModelDirective;
@@ -1,10 +1,11 @@
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;
5
- /** @deprecated Prefer `beforeModelCall` / `afterModelCall`. Kept through 1.0. */
6
+ /** @deprecated Prefer `before` / `after` hooks. Kept through 1.0. */
6
7
  export const middleware = (value) => value;
7
- /** Compose a reusable capability bundle (tools, instructions, optional dynamics). */
8
+ /** Compose a reusable capability bundle (tools, instructions, optional hooks). */
8
9
  export function capability(declaration) {
9
10
  const instructions = declaration.instructions === undefined
10
11
  ? undefined
@@ -17,14 +18,16 @@ export function capability(declaration) {
17
18
  ...(declaration.description === undefined
18
19
  ? {}
19
20
  : { description: declaration.description }),
20
- ...(declaration.tools === undefined ? {} : { tools: declaration.tools }),
21
- ...(instructions === undefined ? {} : { instructions }),
22
- ...(declaration.beforeModelCall === undefined
23
- ? {}
24
- : { beforeModelCall: declaration.beforeModelCall }),
25
- ...(declaration.afterModelCall === undefined
21
+ ...(declaration.tools === undefined
26
22
  ? {}
27
- : { afterModelCall: declaration.afterModelCall }),
23
+ : {
24
+ tools: declaration.tools.map((item) => isAgentItem(item)
25
+ ? delegateTool(item)
26
+ : item),
27
+ }),
28
+ ...(instructions === undefined ? {} : { instructions }),
29
+ ...(declaration.before === undefined ? {} : { before: declaration.before }),
30
+ ...(declaration.after === undefined ? {} : { after: declaration.after }),
28
31
  ...(declaration.middleware === undefined
29
32
  ? {}
30
33
  : { middleware: declaration.middleware }),
@@ -0,0 +1,19 @@
1
+ import type { AfterHooks, BeforeHooks, HookAt, HookManifest, HookScope } from "../types/dynamics.js";
2
+ import type { Implementations } from "./implementations.js";
3
+ /** Every hook point, in the order the loop reaches them and the manifest lists them. */
4
+ export declare const HOOK_POINTS: readonly HookManifest[];
5
+ /** Canonical manifest list for a capability's hooks, or undefined when it has none. */
6
+ export declare function hooksFrom(before: BeforeHooks<any> | undefined, after: AfterHooks<any> | undefined): readonly HookManifest[] | undefined;
7
+ export declare function hasHook(hooks: readonly HookManifest[] | undefined, at: HookAt, scope: HookScope): boolean;
8
+ /** Why a manifest `hooks` value is invalid, or undefined when it is valid. */
9
+ export declare function hookListIssue(value: unknown): string | undefined;
10
+ /**
11
+ * Run one hook point for the listed capabilities, concurrently.
12
+ * Never throws: a missing or failing hook blocks with its message, so a
13
+ * re-delivered hook cannot fail the same way forever.
14
+ */
15
+ export declare function runHookPoint(implementations: Implementations<any>, hook: {
16
+ readonly at: HookAt;
17
+ readonly scope: HookScope;
18
+ readonly capabilityIds: readonly string[];
19
+ }, args: unknown): Promise<Readonly<Record<string, unknown>>>;
@@ -0,0 +1,67 @@
1
+ /** Every hook point, in the order the loop reaches them and the manifest lists them. */
2
+ export const HOOK_POINTS = Object.freeze([
3
+ Object.freeze({ at: "before", scope: "turn" }),
4
+ Object.freeze({ at: "before", scope: "step" }),
5
+ Object.freeze({ at: "after", scope: "step" }),
6
+ Object.freeze({ at: "after", scope: "turn" }),
7
+ ]);
8
+ const pointIndex = (point) => HOOK_POINTS.findIndex((item) => item.at === point.at && item.scope === point.scope);
9
+ /** Canonical manifest list for a capability's hooks, or undefined when it has none. */
10
+ export function hooksFrom(before, after) {
11
+ const hooks = HOOK_POINTS.filter((point) => typeof (point.at === "before" ? before : after)?.[point.scope] ===
12
+ "function");
13
+ return hooks.length ? Object.freeze(hooks) : undefined;
14
+ }
15
+ export function hasHook(hooks, at, scope) {
16
+ return hooks?.some((hook) => hook.at === at && hook.scope === scope) ?? false;
17
+ }
18
+ /** Why a manifest `hooks` value is invalid, or undefined when it is valid. */
19
+ export function hookListIssue(value) {
20
+ if (!Array.isArray(value))
21
+ return "hooks must be an array";
22
+ if (value.length === 0)
23
+ return "hooks must be omitted when empty";
24
+ let previous = -1;
25
+ for (const item of value) {
26
+ if (item === null ||
27
+ typeof item !== "object" ||
28
+ Object.keys(item).some((key) => key !== "at" && key !== "scope"))
29
+ return "each hook must be { at, scope }";
30
+ const index = pointIndex(item);
31
+ if (index < 0)
32
+ return `unknown hook point '${String(item.at)} ${String(item.scope)}'`;
33
+ if (index === previous)
34
+ return `duplicate hook '${item.at} ${item.scope}'`;
35
+ if (index < previous)
36
+ return "hooks must be listed as before turn, before step, after step, after turn";
37
+ previous = index;
38
+ }
39
+ return undefined;
40
+ }
41
+ /**
42
+ * Run one hook point for the listed capabilities, concurrently.
43
+ * Never throws: a missing or failing hook blocks with its message, so a
44
+ * re-delivered hook cannot fail the same way forever.
45
+ */
46
+ export async function runHookPoint(implementations, hook, args) {
47
+ const entries = await Promise.all(hook.capabilityIds.map(async (id) => {
48
+ const fn = implementations[id]?.[hook.at]?.[hook.scope];
49
+ if (typeof fn !== "function")
50
+ return [
51
+ id,
52
+ {
53
+ block: `Missing ${hook.at}("${hook.scope}") implementation for capability '${id}'`,
54
+ },
55
+ ];
56
+ try {
57
+ return [id, (await fn(args)) ?? {}];
58
+ }
59
+ catch (error) {
60
+ return [
61
+ id,
62
+ { block: error instanceof Error ? error.message : String(error) },
63
+ ];
64
+ }
65
+ }));
66
+ return Object.freeze(Object.fromEntries(entries));
67
+ }
@@ -1,4 +1,4 @@
1
- import type { AfterModelCallFn, BeforeModelCallFn } from "../types/dynamics.js";
1
+ import type { AfterHooks, BeforeHooks } from "../types/dynamics.js";
2
2
  import type { ToolDefinition } from "../types/tool.js";
3
3
  import type { StepMiddleware } from "../types/middleware.js";
4
4
  /** In-process implementations table keyed by capability id (never serialized). */
@@ -7,8 +7,8 @@ export interface Implementations<Info = unknown> {
7
7
  readonly tools?: {
8
8
  readonly [toolName: string]: ToolDefinition<any, Info, any>;
9
9
  };
10
- readonly beforeModelCall?: BeforeModelCallFn<Info>;
11
- readonly afterModelCall?: AfterModelCallFn<Info>;
10
+ readonly before?: BeforeHooks<Info>;
11
+ readonly after?: AfterHooks<Info>;
12
12
  /** @deprecated Local engine only through 1.0. */
13
13
  readonly middleware?: StepMiddleware<Info>;
14
14
  };
@@ -1,10 +1,11 @@
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));
6
7
  return deepFreeze({
7
- manifestSchemaVersion: 3,
8
+ manifestSchemaVersion: 4,
8
9
  id: input.id,
9
10
  ...(input.name === undefined ? {} : { name: input.name }),
10
11
  ...(input.description === undefined
@@ -41,12 +42,17 @@ function projectCapability(item) {
41
42
  : { tools: item.tools.map((tool) => projectTool(tool)) }),
42
43
  ...(item.skills === undefined ? {} : { skills: item.skills }),
43
44
  ...(item.mcpServers === undefined ? {} : { mcpServers: item.mcpServers }),
44
- ...(item.beforeModelCall ? { beforeModelCall: true } : {}),
45
- ...(item.afterModelCall ? { afterModelCall: true } : {}),
45
+ ...(item.sandbox === undefined
46
+ ? {}
47
+ : { sandbox: copyJsonObject(item.sandbox, "sandbox") }),
48
+ ...(item.hooks === undefined
49
+ ? {}
50
+ : { hooks: item.hooks.map((hook) => ({ at: hook.at, scope: hook.scope })) }),
46
51
  };
47
52
  }
48
53
  function projectTool(tool) {
49
54
  const schemas = normalizedSchemasFor(tool);
55
+ const delegate = delegateOf(tool);
50
56
  return {
51
57
  name: tool.name,
52
58
  ...(tool.description === undefined
@@ -56,5 +62,6 @@ function projectTool(tool) {
56
62
  ...(schemas.outputSchema === undefined
57
63
  ? {}
58
64
  : { outputSchema: schemas.outputSchema.jsonSchema }),
65
+ ...(delegate === undefined ? {} : { agent: delegate.manifest }),
59
66
  };
60
67
  }
@@ -0,0 +1,5 @@
1
+ import type { ToolDefinition } from "../types/tool.js";
2
+ /** Instructions attached to every sandbox capability. */
3
+ export declare const SANDBOX_INSTRUCTIONS: string;
4
+ /** The six built-in sandbox tools. Schemas are part of the hashed manifest; change them deliberately. */
5
+ export declare function createSandboxTools(): readonly ToolDefinition[];
@@ -0,0 +1,109 @@
1
+ import { z } from "zod";
2
+ import { tool } from "./helpers.js";
3
+ import { ToolError } from "./tool-error.js";
4
+ import { SANDBOX_WORKSPACE } from "../utils/sandbox.js";
5
+ const PATH_NOTE = `Relative paths resolve under ${SANDBOX_WORKSPACE}.`;
6
+ /** Instructions attached to every sandbox capability. */
7
+ export const SANDBOX_INSTRUCTIONS = `You have an isolated Linux sandbox with a persistent working directory at ${SANDBOX_WORKSPACE}. ` +
8
+ "Use bash to run commands, read/write/edit to work with files, and grep/glob to search. " +
9
+ "Network egress is limited by policy; a failed download usually means the host is not allowed.";
10
+ /**
11
+ * Stub implementation for the developer process. The Runtime executes sandbox tools;
12
+ * reaching this means the agent ran without a Nylorun Runtime.
13
+ */
14
+ async function runtimeOnly() {
15
+ throw new ToolError("sandbox.runtime-only", "Sandbox tools run in the Nylorun Runtime. Run the agent with `nylorun dev` or `nylorun serve` to use them.");
16
+ }
17
+ /** The six built-in sandbox tools. Schemas are part of the hashed manifest; change them deliberately. */
18
+ export function createSandboxTools() {
19
+ return Object.freeze([
20
+ tool({
21
+ name: "bash",
22
+ description: `Run a bash command in the sandbox. The working directory is ${SANDBOX_WORKSPACE}. ` +
23
+ "Returns exitCode, stdout and stderr; a non-zero exit code is a normal result, not an error. " +
24
+ "Long output is truncated in the middle.",
25
+ inputSchema: z.object({
26
+ command: z.string().min(1).describe("The command line to run with bash."),
27
+ timeout: z
28
+ .number()
29
+ .int()
30
+ .min(1)
31
+ .max(600)
32
+ .optional()
33
+ .describe("Seconds before the command is killed. Default 120, maximum 600."),
34
+ }),
35
+ effects: "write",
36
+ execute: runtimeOnly,
37
+ }),
38
+ tool({
39
+ name: "read",
40
+ description: `Read a text file from the sandbox. ${PATH_NOTE} Returns numbered lines. ` +
41
+ "Use offset and limit to page through large files.",
42
+ inputSchema: z.object({
43
+ path: z.string().min(1),
44
+ offset: z
45
+ .number()
46
+ .int()
47
+ .min(1)
48
+ .optional()
49
+ .describe("First line to return, 1-based."),
50
+ limit: z
51
+ .number()
52
+ .int()
53
+ .min(1)
54
+ .max(5000)
55
+ .optional()
56
+ .describe("Maximum number of lines. Default 2000."),
57
+ }),
58
+ effects: "read",
59
+ execute: runtimeOnly,
60
+ }),
61
+ tool({
62
+ name: "write",
63
+ description: `Create or overwrite a text file in the sandbox. ${PATH_NOTE} Parent directories are created.`,
64
+ inputSchema: z.object({
65
+ path: z.string().min(1),
66
+ content: z.string(),
67
+ }),
68
+ effects: "write",
69
+ execute: runtimeOnly,
70
+ }),
71
+ tool({
72
+ name: "edit",
73
+ description: `Replace text in a sandbox file. ${PATH_NOTE} old_string must match exactly and be unique ` +
74
+ "unless replace_all is true.",
75
+ inputSchema: z.object({
76
+ path: z.string().min(1),
77
+ old_string: z.string().min(1),
78
+ new_string: z.string(),
79
+ replace_all: z.boolean().optional(),
80
+ }),
81
+ effects: "write",
82
+ execute: runtimeOnly,
83
+ }),
84
+ tool({
85
+ name: "grep",
86
+ description: `Search file contents in the sandbox with an extended regular expression. ${PATH_NOTE} ` +
87
+ "Returns matching lines as path:line:text.",
88
+ inputSchema: z.object({
89
+ pattern: z.string().min(1),
90
+ path: z.string().min(1).optional().describe(`Directory or file to search. Default ${SANDBOX_WORKSPACE}.`),
91
+ glob: z.string().min(1).optional().describe("Only search files whose name matches, e.g. \"*.py\"."),
92
+ ignore_case: z.boolean().optional(),
93
+ max_results: z.number().int().min(1).max(1000).optional().describe("Default 200."),
94
+ }),
95
+ effects: "read",
96
+ execute: runtimeOnly,
97
+ }),
98
+ tool({
99
+ name: "glob",
100
+ description: `Find files in the sandbox by glob pattern, e.g. "**/*.csv". ${PATH_NOTE} Returns matching paths.`,
101
+ inputSchema: z.object({
102
+ pattern: z.string().min(1),
103
+ path: z.string().min(1).optional().describe(`Directory to search. Default ${SANDBOX_WORKSPACE}.`),
104
+ }),
105
+ effects: "read",
106
+ execute: runtimeOnly,
107
+ }),
108
+ ]);
109
+ }
@@ -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,11 +7,11 @@ export type Patch = {
7
7
  readonly capabilities?: Readonly<Record<string, boolean>>;
8
8
  /** Switch tools by name. */
9
9
  readonly tools?: Readonly<Record<string, boolean>>;
10
- /** Extra instructions for this model call only. */
10
+ /** Extra instructions for the model calls this patch covers. */
11
11
  readonly instructions?: readonly string[];
12
12
  /** Write session state keys (merged into durable session state). */
13
13
  readonly state?: Readonly<Record<string, JsonValue>>;
14
- /** Refuse this model call; message returned to the host. */
14
+ /** Refuse the model call; message returned to the host. */
15
15
  readonly block?: string;
16
16
  /**
17
17
  * Capability-level shorthand: toggle only this capability.
@@ -33,21 +33,69 @@ export type Decision = {
33
33
  readonly retry?: string;
34
34
  readonly block?: string;
35
35
  };
36
- export type BeforeModelCallFn<Info = unknown> = (args: {
36
+ /** Decision applied to a turn's final answer before it is returned. */
37
+ export type TurnDecision = {
38
+ /** Replace the final text. Plain-text agents only. */
39
+ readonly text?: string;
40
+ /** Replace the final structured output. Agents with an output schema only. */
41
+ readonly output?: JsonValue;
42
+ /** Ask the model to answer again; the feedback is added as a message. */
43
+ readonly retry?: string;
44
+ readonly block?: string;
45
+ };
46
+ /** When a hook runs: once per turn, or on every model call (step). */
47
+ export type HookScope = "turn" | "step";
48
+ export type HookAt = "before" | "after";
49
+ /** A registered hook point as published in the manifest. */
50
+ export type HookManifest = {
51
+ readonly at: HookAt;
52
+ readonly scope: HookScope;
53
+ };
54
+ export type HookState = Readonly<Record<string, JsonValue>>;
55
+ export type HookToolCall = {
56
+ readonly id: string;
57
+ readonly name: string;
58
+ readonly args: JsonValue;
59
+ };
60
+ export type BeforeTurnArgs<Info = unknown> = {
61
+ /** The user input that started this turn. */
37
62
  readonly input?: MessageInput | string;
38
63
  readonly info?: Info;
39
- readonly state: Readonly<Record<string, JsonValue>>;
64
+ readonly state: HookState;
40
65
  readonly messages: readonly PromptItem[];
66
+ };
67
+ export type BeforeStepArgs<Info = unknown> = BeforeTurnArgs<Info> & {
68
+ /** Zero-based model call index within the turn. */
41
69
  readonly step: number;
42
- }) => Patch | Promise<Patch>;
43
- export type AfterModelCallFn<Info = unknown> = (args: {
70
+ };
71
+ export type AfterStepArgs<Info = unknown> = {
44
72
  readonly text?: string;
45
- readonly toolCalls: readonly {
46
- readonly id: string;
47
- readonly name: string;
48
- readonly args: JsonValue;
49
- }[];
50
- }, ctx: {
73
+ readonly toolCalls: readonly HookToolCall[];
74
+ readonly info?: Info;
75
+ readonly state: HookState;
76
+ readonly step: number;
77
+ /** Retries already requested by `after("step")` hooks in this turn. */
78
+ readonly attempt: number;
79
+ };
80
+ export type AfterTurnArgs<Info = unknown> = {
81
+ /** Final text, for plain-text agents. */
82
+ readonly text?: string;
83
+ /** Final output: the text, or the structured value when an output schema is set. */
84
+ readonly output: JsonValue;
51
85
  readonly info?: Info;
52
- readonly state: Readonly<Record<string, JsonValue>>;
53
- }) => Decision | Promise<Decision>;
86
+ readonly state: HookState;
87
+ /** Retries already requested by `after("turn")` hooks in this turn. */
88
+ readonly attempt: number;
89
+ };
90
+ type Awaitable<T> = T | Promise<T>;
91
+ export type BeforeHook<S extends HookScope, Info = unknown> = (args: S extends "turn" ? BeforeTurnArgs<Info> : BeforeStepArgs<Info>) => Awaitable<Patch>;
92
+ export type AfterHook<S extends HookScope, Info = unknown> = S extends "step" ? (args: AfterStepArgs<Info>) => Awaitable<Decision> : (args: AfterTurnArgs<Info>) => Awaitable<TurnDecision>;
93
+ export type BeforeHooks<Info = unknown> = {
94
+ readonly turn?: BeforeHook<"turn", Info>;
95
+ readonly step?: BeforeHook<"step", Info>;
96
+ };
97
+ export type AfterHooks<Info = unknown> = {
98
+ readonly step?: AfterHook<"step", Info>;
99
+ readonly turn?: AfterHook<"turn", Info>;
100
+ };
101
+ export {};