@orkestrel/tool 0.0.1
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/LICENSE +21 -0
- package/README.md +50 -0
- package/dist/src/core/index.cjs +1240 -0
- package/dist/src/core/index.cjs.map +1 -0
- package/dist/src/core/index.d.cts +1180 -0
- package/dist/src/core/index.d.ts +1180 -0
- package/dist/src/core/index.js +1199 -0
- package/dist/src/core/index.js.map +1 -0
- package/package.json +84 -0
|
@@ -0,0 +1,1199 @@
|
|
|
1
|
+
import { arrayShape, booleanShape, createContract, integerShape, literalShape, objectShape, optionalShape, schemaToParameters, stringShape, unionShape } from "@orkestrel/contract";
|
|
2
|
+
import { WorkspaceError, createTool, createWorkspaceManager, isText, rangeOf } from "@orkestrel/agent";
|
|
3
|
+
import { WorkflowError, createWorkflowContract } from "@orkestrel/workflow";
|
|
4
|
+
//#region src/core/constants.ts
|
|
5
|
+
/**
|
|
6
|
+
* The name {@link import('./factories.js').createAgentTool} advertises by default — the key a
|
|
7
|
+
* model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
|
|
8
|
+
*/
|
|
9
|
+
var AGENT_TOOL_NAME = "agent";
|
|
10
|
+
/**
|
|
11
|
+
* The maximum nesting depth a delegation chain (agent tool → sub-agent → agent tool → …) may
|
|
12
|
+
* reach — the bound {@link import('./factories.js').createAgentTool}'s depth/cycle guard
|
|
13
|
+
* enforces.
|
|
14
|
+
*
|
|
15
|
+
* @remarks
|
|
16
|
+
* Deliberately a SEPARATE constant from {@link MAX_WORKFLOW_DEPTH} (rather than the two guards
|
|
17
|
+
* sharing one reference): the two guards bound DIFFERENT chains (workflow nesting vs. agent
|
|
18
|
+
* delegation) that happen to share a value today, and keeping this bound decoupled means a
|
|
19
|
+
* future change to one never silently shifts the other. Same numeric value by convention, not
|
|
20
|
+
* by shared reference.
|
|
21
|
+
*/
|
|
22
|
+
var AGENT_TOOL_DEPTH = 8;
|
|
23
|
+
/**
|
|
24
|
+
* The DESCRIPTION {@link import('./factories.js').createAgentTool} advertises — a short guide
|
|
25
|
+
* that teaches a model how to delegate a task to a sub-agent.
|
|
26
|
+
*
|
|
27
|
+
* @remarks
|
|
28
|
+
* Mirrors {@link WORKFLOW_TOOL_DESCRIPTION} / `WORKSPACE_TOOL_DESCRIPTION`'s teaching style: names
|
|
29
|
+
* the required `task` field, and documents the optional per-call `provider` / `tools` /
|
|
30
|
+
* `system` overrides.
|
|
31
|
+
*/
|
|
32
|
+
/**
|
|
33
|
+
* The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createAgentTool}
|
|
34
|
+
* advertises in place of {@link AGENT_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
|
|
35
|
+
* (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
|
|
36
|
+
* for the full teaching description; the full text stays retrievable via
|
|
37
|
+
* {@link import('./factories.js').createDescribeTool}.
|
|
38
|
+
*/
|
|
39
|
+
var AGENT_TOOL_SUMMARY = "Delegate a task to a sub-agent and return its result; each call runs one sub-agent turn to completion. Call describe('agent') for the optional provider/tools/system overrides.";
|
|
40
|
+
var AGENT_TOOL_DESCRIPTION = [
|
|
41
|
+
"Delegate a task to a sub-agent and return its result. Every call runs ONE sub-agent turn to completion.",
|
|
42
|
+
"",
|
|
43
|
+
"Required:",
|
|
44
|
+
" task - the instructions the sub-agent should carry out.",
|
|
45
|
+
"Optional overrides (default to the values this tool was configured with):",
|
|
46
|
+
" provider - the registry key of the model/provider the sub-agent runs against.",
|
|
47
|
+
" tools - registry keys of the tools loaded into the sub-agent (replaces the default list, not merged).",
|
|
48
|
+
" system - a system prompt seeding the sub-agent's context (replaces the default).",
|
|
49
|
+
"Example:",
|
|
50
|
+
JSON.stringify({ task: "Summarize the attached notes in three bullet points." })
|
|
51
|
+
].join("\n");
|
|
52
|
+
/**
|
|
53
|
+
* The maximum nesting depth a workflow → agent → workflow chain may reach — the bound
|
|
54
|
+
* {@link import('./factories.js').createAgentFunction} and
|
|
55
|
+
* {@link import('./factories.js').createWorkflowTool}'s depth/cycle guards enforce.
|
|
56
|
+
*
|
|
57
|
+
* @remarks
|
|
58
|
+
* OWNED here now (ported from `@orkestrel/workflow`, whose engine no longer uses it — only the
|
|
59
|
+
* tool-authoring guards this package now owns consume it). The limit lives in ONE place: an
|
|
60
|
+
* agent-function-wrapped agent running at this depth can no longer author + run a NESTED
|
|
61
|
+
* workflow through its bound workflow tool (that would be depth `MAX_WORKFLOW_DEPTH + 1`), so
|
|
62
|
+
* the over-deep invocation is REJECTED (a typed `DEPTH` `WorkflowError` throw, `@orkestrel/workflow`).
|
|
63
|
+
*/
|
|
64
|
+
var MAX_WORKFLOW_DEPTH = 8;
|
|
65
|
+
/**
|
|
66
|
+
* The name {@link import('./factories.js').createWorkflowTool} advertises by default — the key a
|
|
67
|
+
* model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under, and the name
|
|
68
|
+
* {@link import('./factories.js').createAgentFunction} binds the depth/cycle-aware workflow tool
|
|
69
|
+
* under onto a wrapped agent's `context.tools`.
|
|
70
|
+
*
|
|
71
|
+
* @remarks
|
|
72
|
+
* OWNED here now (ported from `@orkestrel/workflow`). The propagation seam's well-known key: when
|
|
73
|
+
* `createAgentFunction`'s `runner` option is supplied, it adds a `createWorkflowTool`-built tool
|
|
74
|
+
* under this name to the agent's `context.tools`, so it can author + run a NESTED workflow
|
|
75
|
+
* (bounded by {@link MAX_WORKFLOW_DEPTH}).
|
|
76
|
+
*/
|
|
77
|
+
var WORKFLOW_TOOL_NAME = "workflow";
|
|
78
|
+
/**
|
|
79
|
+
* A complete FLAT authoring example — the PRIMARY way a small model authors a workflow through
|
|
80
|
+
* {@link import('./factories.js').createWorkflowTool}: `{ name, steps: [{ name }] }`.
|
|
81
|
+
*
|
|
82
|
+
* @remarks
|
|
83
|
+
* OWNED here now (ported from `@orkestrel/workflow`). Each step becomes a one-task phase, in
|
|
84
|
+
* order; a step's `name` is a REGISTERED behavior name (not a label) — the registry key its
|
|
85
|
+
* task's `run` resolves against. The tool expands this
|
|
86
|
+
* ({@link import('./helpers.js').expandSteps}) into a valid `WorkflowDefinition`
|
|
87
|
+
* (`@orkestrel/workflow`). It is embedded VERBATIM in {@link WORKFLOW_TOOL_DESCRIPTION}.
|
|
88
|
+
*/
|
|
89
|
+
var WORKFLOW_TOOL_FLAT_EXAMPLE = Object.freeze({
|
|
90
|
+
name: "release",
|
|
91
|
+
steps: Object.freeze([Object.freeze({ name: "compile" }), Object.freeze({ name: "publish" })])
|
|
92
|
+
});
|
|
93
|
+
/**
|
|
94
|
+
* A minimal NESTED authoring example — the ADVANCED escape-hatch form a model may use instead of
|
|
95
|
+
* the flat shape: a full `WorkflowDefinition` (`@orkestrel/workflow`).
|
|
96
|
+
*
|
|
97
|
+
* @remarks
|
|
98
|
+
* OWNED here now (ported from `@orkestrel/workflow`). The full four-level form, documented in
|
|
99
|
+
* {@link WORKFLOW_TOOL_DESCRIPTION} as the advanced alternative. It is embedded VERBATIM.
|
|
100
|
+
*/
|
|
101
|
+
var WORKFLOW_TOOL_NESTED_EXAMPLE = Object.freeze({
|
|
102
|
+
id: "release",
|
|
103
|
+
name: "Release",
|
|
104
|
+
phases: Object.freeze([Object.freeze({
|
|
105
|
+
id: "build",
|
|
106
|
+
name: "Build",
|
|
107
|
+
tasks: Object.freeze([Object.freeze({
|
|
108
|
+
id: "compile",
|
|
109
|
+
name: "Compile",
|
|
110
|
+
run: "compile"
|
|
111
|
+
})])
|
|
112
|
+
})])
|
|
113
|
+
});
|
|
114
|
+
/**
|
|
115
|
+
* The DESCRIPTION {@link import('./factories.js').createWorkflowTool} advertises — a multi-line
|
|
116
|
+
* guide that teaches a small model how to author a complete workflow tree.
|
|
117
|
+
*
|
|
118
|
+
* @remarks
|
|
119
|
+
* OWNED here now (ported from `@orkestrel/workflow`). Presents the SIMPLE flat shape
|
|
120
|
+
* (`{ name, steps: [{ name }] }`) as the PRIMARY way with one complete worked example
|
|
121
|
+
* ({@link WORKFLOW_TOOL_FLAT_EXAMPLE}), names that a step's `name` is a REGISTERED name (not a
|
|
122
|
+
* human label), and documents the full nested `WorkflowDefinition` as the ADVANCED form with a
|
|
123
|
+
* minimal example ({@link WORKFLOW_TOOL_NESTED_EXAMPLE}). The `parameters` the tool advertises
|
|
124
|
+
* are the FLAT shape's schema; the nested form is the documented escape-hatch (the tool accepts
|
|
125
|
+
* both).
|
|
126
|
+
*/
|
|
127
|
+
/**
|
|
128
|
+
* The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createWorkflowTool}
|
|
129
|
+
* advertises in place of {@link WORKFLOW_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
|
|
130
|
+
* (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
|
|
131
|
+
* for the full teaching description; the full text stays retrievable via
|
|
132
|
+
* {@link import('./factories.js').createDescribeTool}.
|
|
133
|
+
*/
|
|
134
|
+
var WORKFLOW_TOOL_SUMMARY = "Author and run a multi-phase workflow in one call — phases run in sequence, tasks within a phase run concurrently. Call describe('workflow') for the full authoring schema and examples.";
|
|
135
|
+
var WORKFLOW_TOOL_DESCRIPTION = [
|
|
136
|
+
"Author and run a workflow (phases run sequentially, the tasks within a phase run concurrently) in one call.",
|
|
137
|
+
"",
|
|
138
|
+
"SIMPLEST way — a flat list of steps. Each step runs one registered behavior; steps run one after another:",
|
|
139
|
+
" { \"name\": \"<workflow name>\", \"steps\": [ { \"name\": \"<registered name>\" }, ... ] }",
|
|
140
|
+
"- a step's \"name\" is a REGISTERED behavior name (a registry key), NOT a human label.",
|
|
141
|
+
"- the top-level \"name\" (the workflow name) is optional. Ids are filled in for you.",
|
|
142
|
+
"Example:",
|
|
143
|
+
JSON.stringify(WORKFLOW_TOOL_FLAT_EXAMPLE),
|
|
144
|
+
"",
|
|
145
|
+
"ADVANCED — the full nested form, for multi-task phases or explicit ids. A workflow has phases; a phase has tasks; a task has a \"run\" (a registered behavior name):",
|
|
146
|
+
JSON.stringify(WORKFLOW_TOOL_NESTED_EXAMPLE),
|
|
147
|
+
"In the nested form you may omit any \"id\"/\"name\" and they are filled in positionally; a provided one is kept."
|
|
148
|
+
].join("\n");
|
|
149
|
+
/**
|
|
150
|
+
* The name {@link import('./factories.js').createWorkspaceTool} advertises by default — the key a
|
|
151
|
+
* model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
|
|
152
|
+
*
|
|
153
|
+
* @remarks
|
|
154
|
+
* OWNED here now (ported from `@orkestrel/agent`).
|
|
155
|
+
*/
|
|
156
|
+
var WORKSPACE_TOOL_NAME = "workspace";
|
|
157
|
+
/**
|
|
158
|
+
* A valid `WorkspaceOperation` (`@orkestrel/agent`) object — the canonical example embedded
|
|
159
|
+
* VERBATIM in {@link WORKSPACE_TOOL_DESCRIPTION}.
|
|
160
|
+
*
|
|
161
|
+
* @remarks
|
|
162
|
+
* OWNED here now (ported from `@orkestrel/agent`). A `'write'` op (the most common authoring
|
|
163
|
+
* action): create or overwrite `notes.txt` with `hello`. Frozen so it cannot be mutated in
|
|
164
|
+
* place.
|
|
165
|
+
*/
|
|
166
|
+
var WORKSPACE_TOOL_EXAMPLE = Object.freeze({
|
|
167
|
+
operation: "write",
|
|
168
|
+
path: "notes.txt",
|
|
169
|
+
content: "hello"
|
|
170
|
+
});
|
|
171
|
+
/**
|
|
172
|
+
* The DESCRIPTION {@link import('./factories.js').createWorkspaceTool} advertises — a multi-line
|
|
173
|
+
* guide that teaches a small model how to drive a workspace through the single
|
|
174
|
+
* `operation`-keyed tool.
|
|
175
|
+
*
|
|
176
|
+
* @remarks
|
|
177
|
+
* OWNED here now (ported from `@orkestrel/agent`). Mirrors {@link WORKFLOW_TOOL_DESCRIPTION}'s
|
|
178
|
+
* teaching style: names the `operation` discriminant field, enumerates all 13 operations with
|
|
179
|
+
* their FLAT fields, gives a worked example for the common ones, and embeds
|
|
180
|
+
* {@link WORKSPACE_TOOL_EXAMPLE} verbatim.
|
|
181
|
+
*/
|
|
182
|
+
/**
|
|
183
|
+
* The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createWorkspaceTool}
|
|
184
|
+
* advertises in place of {@link WORKSPACE_TOOL_DESCRIPTION} — a `ToolManagerInterface.definitions()`
|
|
185
|
+
* (`@orkestrel/agent`) advertises `summary ?? description`, so this one-sentence text stands in
|
|
186
|
+
* for the full teaching description; the full text stays retrievable via
|
|
187
|
+
* {@link import('./factories.js').createDescribeTool}.
|
|
188
|
+
*/
|
|
189
|
+
var WORKSPACE_TOOL_SUMMARY = "Read and edit files in a workspace — one operation per call (read, write, list, search, replace, splice, move, remove, plus workspace switching), chosen by the 'operation' field. Call describe('workspace') for the full operation list and fields.";
|
|
190
|
+
var WORKSPACE_TOOL_DESCRIPTION = [
|
|
191
|
+
"Read and edit files in a workspace. Every call is ONE operation, chosen by the \"operation\" field.",
|
|
192
|
+
"All file operations act on the ACTIVE workspace; use \"workspaces\" then \"switch\" to move between workspaces.",
|
|
193
|
+
"",
|
|
194
|
+
"Operations (each takes the fields listed):",
|
|
195
|
+
"- read { \"operation\": \"read\", \"path\": \"<file>\" } — return the file's text.",
|
|
196
|
+
"- list { \"operation\": \"list\" } — list every file in the active workspace (path, state, size, lines, kind).",
|
|
197
|
+
"- has { \"operation\": \"has\", \"path\": \"<file>\" } — whether the file exists.",
|
|
198
|
+
"- search { \"operation\": \"search\", \"query\": \"<text>\", \"regex\"?: bool, \"exact\"?: bool, \"limit\"?: int } — find lines matching the query across all files.",
|
|
199
|
+
"- replace { \"operation\": \"replace\", \"query\": \"<text>\", \"replacement\": \"<text>\", \"regex\"?: bool, \"exact\"?: bool, \"limit\"?: int } — replace matches across all files.",
|
|
200
|
+
"- write { \"operation\": \"write\", \"path\": \"<file>\", \"content\": \"<text>\" } — create or overwrite the whole file.",
|
|
201
|
+
"- splice { \"operation\": \"splice\", \"path\": \"<file>\", \"content\": \"<text>\", \"fromLine\": int, \"fromColumn\": int, \"toLine\": int, \"toColumn\": int } — replace a 1-based range (from inclusive, to exclusive) with content.",
|
|
202
|
+
"- prepend { \"operation\": \"prepend\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the start of the file.",
|
|
203
|
+
"- append { \"operation\": \"append\", \"path\": \"<file>\", \"content\": \"<text>\" } — add content to the end of the file.",
|
|
204
|
+
"- move { \"operation\": \"move\", \"from\": \"<file>\", \"to\": \"<file>\" } — rename / move a file.",
|
|
205
|
+
"- remove { \"operation\": \"remove\", \"path\": \"<file>\" } — delete a file.",
|
|
206
|
+
"- workspaces { \"operation\": \"workspaces\" } — list the workspaces you can switch between (each id, file count, active).",
|
|
207
|
+
"- switch { \"operation\": \"switch\", \"id\": \"<id>\" } — make the workspace with that id active (ids come from \"workspaces\").",
|
|
208
|
+
"",
|
|
209
|
+
"Notes: lines and columns are 1-based (column 1 is the first character). \"regex\" defaults to false (a literal substring), \"exact\" defaults to true (case-sensitive). \"search\"/\"replace\"/\"splice\" act only on text files. Editing with no active workspace auto-creates one.",
|
|
210
|
+
"",
|
|
211
|
+
"Example — write a file:",
|
|
212
|
+
JSON.stringify(WORKSPACE_TOOL_EXAMPLE)
|
|
213
|
+
].join("\n");
|
|
214
|
+
/**
|
|
215
|
+
* The name {@link import('./factories.js').createDescribeTool} advertises by default — the key a
|
|
216
|
+
* model calls and the `ToolManagerInterface` (`@orkestrel/agent`) registers under.
|
|
217
|
+
*
|
|
218
|
+
* @remarks
|
|
219
|
+
* Net-new: pairs with the other three tools' lean {@link AGENT_TOOL_SUMMARY} /
|
|
220
|
+
* {@link WORKFLOW_TOOL_SUMMARY} / {@link WORKSPACE_TOOL_SUMMARY} — a model that reads only the
|
|
221
|
+
* advertised summary can call `describe` with that tool's registered name to get its full
|
|
222
|
+
* teaching description back.
|
|
223
|
+
*/
|
|
224
|
+
var DESCRIBE_TOOL_NAME = "describe";
|
|
225
|
+
/**
|
|
226
|
+
* The lean {@link import('@orkestrel/agent').ToolInterface.summary} {@link import('./factories.js').createDescribeTool}
|
|
227
|
+
* advertises — this tool needs no teaching of its own, so its summary and description are both
|
|
228
|
+
* short.
|
|
229
|
+
*/
|
|
230
|
+
var DESCRIBE_TOOL_SUMMARY = "Return the full description of a named registered tool.";
|
|
231
|
+
/**
|
|
232
|
+
* The DESCRIPTION {@link import('./factories.js').createDescribeTool} advertises.
|
|
233
|
+
*
|
|
234
|
+
* @remarks
|
|
235
|
+
* Deliberately short — unlike the workflow / workspace / agent tools, this one has no authoring
|
|
236
|
+
* schema or multi-step protocol to teach.
|
|
237
|
+
*/
|
|
238
|
+
var DESCRIBE_TOOL_DESCRIPTION = "Return the full description of a registered tool by its name. Required: name - the registered tool name (see another tool listing for available names).";
|
|
239
|
+
//#endregion
|
|
240
|
+
//#region src/core/errors.ts
|
|
241
|
+
/**
|
|
242
|
+
* Thrown by {@link import('./factories.js').createAgentTool}'s and
|
|
243
|
+
* {@link import('./factories.js').createDescribeTool}'s handlers on every failure path — a
|
|
244
|
+
* malformed / unresolvable call or an unknown tool name (`TOOL`), or a delegation that would
|
|
245
|
+
* exceed the configured depth bound or re-enter an ancestor (`DEPTH`).
|
|
246
|
+
*
|
|
247
|
+
* @remarks
|
|
248
|
+
* Carries a machine-readable `code` (see {@link import('./types.js').AgentToolErrorCode}) and
|
|
249
|
+
* an optional `context` bag for structured diagnostics. The `ToolManagerInterface`
|
|
250
|
+
* (`@orkestrel/agent`) isolates every throw into the canonical tool result's top-level `error`
|
|
251
|
+
* (AGENTS §14) — nothing escapes the run.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* ```ts
|
|
255
|
+
* import { AgentToolError, isAgentToolError } from '@src/core'
|
|
256
|
+
*
|
|
257
|
+
* try {
|
|
258
|
+
* throw new AgentToolError('TOOL', 'task is required')
|
|
259
|
+
* } catch (error) {
|
|
260
|
+
* if (isAgentToolError(error)) console.log(error.code) // 'TOOL'
|
|
261
|
+
* }
|
|
262
|
+
* ```
|
|
263
|
+
*/
|
|
264
|
+
var AgentToolError = class extends Error {
|
|
265
|
+
code;
|
|
266
|
+
context;
|
|
267
|
+
constructor(code, message, context) {
|
|
268
|
+
super(message);
|
|
269
|
+
this.name = "AgentToolError";
|
|
270
|
+
this.code = code;
|
|
271
|
+
this.context = context;
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
/**
|
|
275
|
+
* Type guard narrowing an unknown caught value to an {@link AgentToolError}.
|
|
276
|
+
*
|
|
277
|
+
* @param value - The value to test (typically a `catch` binding)
|
|
278
|
+
* @returns `true` when `value` is an {@link AgentToolError}
|
|
279
|
+
*
|
|
280
|
+
* @example
|
|
281
|
+
* ```ts
|
|
282
|
+
* import { isAgentToolError } from '@src/core'
|
|
283
|
+
*
|
|
284
|
+
* try {
|
|
285
|
+
* // ...
|
|
286
|
+
* } catch (error) {
|
|
287
|
+
* if (isAgentToolError(error)) console.log(error.code)
|
|
288
|
+
* }
|
|
289
|
+
* ```
|
|
290
|
+
*/
|
|
291
|
+
function isAgentToolError(value) {
|
|
292
|
+
return value instanceof AgentToolError;
|
|
293
|
+
}
|
|
294
|
+
//#endregion
|
|
295
|
+
//#region src/core/shapers.ts
|
|
296
|
+
/**
|
|
297
|
+
* The shape of {@link import('./types.js').AgentToolArguments} —
|
|
298
|
+
* {@link import('./factories.js').createAgentTool}'s advertised `parameters`.
|
|
299
|
+
*
|
|
300
|
+
* @remarks
|
|
301
|
+
* `task` is the only required field (a non-empty string); `provider` / `tools` / `system`
|
|
302
|
+
* are per-call overrides of the tool's own configured defaults.
|
|
303
|
+
*/
|
|
304
|
+
var agentToolShape = objectShape({
|
|
305
|
+
task: stringShape({
|
|
306
|
+
min: 1,
|
|
307
|
+
description: "The instructions the sub-agent should carry out."
|
|
308
|
+
}),
|
|
309
|
+
provider: optionalShape(stringShape({
|
|
310
|
+
min: 1,
|
|
311
|
+
description: "Registry key of the provider to run the sub-agent against (overrides the default)."
|
|
312
|
+
})),
|
|
313
|
+
tools: optionalShape(arrayShape(stringShape({ min: 1 }), { description: "Registry keys of the tools loaded into the sub-agent (replaces the default list)." })),
|
|
314
|
+
system: optionalShape(stringShape({ description: "A system prompt seeding the sub-agent's context (overrides the default)." }))
|
|
315
|
+
});
|
|
316
|
+
/**
|
|
317
|
+
* The shape of {@link import('./types.js').DescribeToolArguments} —
|
|
318
|
+
* {@link import('./factories.js').createDescribeTool}'s advertised `parameters`.
|
|
319
|
+
*
|
|
320
|
+
* @remarks
|
|
321
|
+
* `name` is the only field (a non-empty string) — the registered tool name to look up.
|
|
322
|
+
*/
|
|
323
|
+
var describeToolShape = objectShape({ name: stringShape({
|
|
324
|
+
min: 1,
|
|
325
|
+
description: "The registered name of the tool whose full description to return."
|
|
326
|
+
}) });
|
|
327
|
+
/**
|
|
328
|
+
* The shape of a {@link import('./types.js').TaskDraft} — identical to a strict task shape
|
|
329
|
+
* EXCEPT `id` and `name` are OPTIONAL.
|
|
330
|
+
*/
|
|
331
|
+
var taskDraftShape = objectShape({
|
|
332
|
+
id: optionalShape(stringShape({
|
|
333
|
+
min: 1,
|
|
334
|
+
description: "Task id; auto-filled when omitted."
|
|
335
|
+
})),
|
|
336
|
+
name: optionalShape(stringShape({
|
|
337
|
+
min: 1,
|
|
338
|
+
description: "Task name; defaults to the id when omitted."
|
|
339
|
+
})),
|
|
340
|
+
description: optionalShape(stringShape({ description: "Optional task description." })),
|
|
341
|
+
run: optionalShape(stringShape({
|
|
342
|
+
min: 1,
|
|
343
|
+
description: "The registered behavior name to invoke (a registry key, not a label); omitted has no handler."
|
|
344
|
+
})),
|
|
345
|
+
retries: optionalShape(integerShape({
|
|
346
|
+
min: 0,
|
|
347
|
+
description: "Extra attempts after the first on failure; overrides the phase default. Omitted means none."
|
|
348
|
+
})),
|
|
349
|
+
timeout: optionalShape(integerShape({
|
|
350
|
+
min: 0,
|
|
351
|
+
description: "Per-attempt deadline in milliseconds; overrides the phase default. Omitted means no deadline."
|
|
352
|
+
}))
|
|
353
|
+
});
|
|
354
|
+
/**
|
|
355
|
+
* The shape of a PHASE in a draft workflow — identical to a strict phase shape EXCEPT `id` and
|
|
356
|
+
* `name` are OPTIONAL, and its tasks are {@link taskDraftShape}s.
|
|
357
|
+
*/
|
|
358
|
+
var phaseDraftShape = objectShape({
|
|
359
|
+
id: optionalShape(stringShape({
|
|
360
|
+
min: 1,
|
|
361
|
+
description: "Phase id; auto-filled when omitted."
|
|
362
|
+
})),
|
|
363
|
+
name: optionalShape(stringShape({
|
|
364
|
+
min: 1,
|
|
365
|
+
description: "Phase name; defaults to the id when omitted."
|
|
366
|
+
})),
|
|
367
|
+
description: optionalShape(stringShape({ description: "Optional phase description." })),
|
|
368
|
+
tasks: arrayShape(taskDraftShape, { description: "The phase tasks; they run CONCURRENTLY." }),
|
|
369
|
+
concurrency: optionalShape(integerShape({
|
|
370
|
+
min: 1,
|
|
371
|
+
description: "Max tasks in flight at once (a resource throttle); omitted means unbounded."
|
|
372
|
+
})),
|
|
373
|
+
bail: optionalShape(literalShape([true, false], { description: "Per-phase failure-policy override; omitted inherits the workflow bail." }))
|
|
374
|
+
});
|
|
375
|
+
/**
|
|
376
|
+
* The shape of a DRAFT workflow — identical to a strict workflow shape EXCEPT `id` and `name`
|
|
377
|
+
* are OPTIONAL at all three levels (workflow / phase / task), so a small model can omit the six
|
|
378
|
+
* identity strings and let the tool synthesize them positionally.
|
|
379
|
+
*
|
|
380
|
+
* @remarks
|
|
381
|
+
* The lenient counterpart {@link import('./factories.js').createWorkflowDraftContract} compiles.
|
|
382
|
+
* `run` stays required on the strict form; a provided `id` / `name` still has `minLength: 1` (so
|
|
383
|
+
* an explicitly-empty `id: ''` is REJECTED, not auto-filled). After
|
|
384
|
+
* {@link import('./helpers.js').completeDraft} fills the missing ids/names, the result is
|
|
385
|
+
* validated against the STRICT `createWorkflowContract` (`@orkestrel/workflow`) gate before
|
|
386
|
+
* running.
|
|
387
|
+
*/
|
|
388
|
+
var workflowDraftShape = objectShape({
|
|
389
|
+
id: optionalShape(stringShape({
|
|
390
|
+
min: 1,
|
|
391
|
+
description: "Workflow id; auto-filled when omitted."
|
|
392
|
+
})),
|
|
393
|
+
name: optionalShape(stringShape({
|
|
394
|
+
min: 1,
|
|
395
|
+
description: "Workflow name; defaults to the id when omitted."
|
|
396
|
+
})),
|
|
397
|
+
description: optionalShape(stringShape({ description: "Optional workflow description." })),
|
|
398
|
+
phases: arrayShape(phaseDraftShape, { description: "The workflow phases; they run SEQUENTIALLY, in order." }),
|
|
399
|
+
bail: optionalShape(literalShape([true, false], { description: "Failure policy: false (default) continues gracefully, true halts on the first failure." }))
|
|
400
|
+
});
|
|
401
|
+
/**
|
|
402
|
+
* The shape of ONE flat step — `{ name }` — the building block of {@link workflowStepsShape}.
|
|
403
|
+
*
|
|
404
|
+
* @remarks
|
|
405
|
+
* `name` is the REGISTERED behavior name the step runs (it becomes the task's `run`). The tool
|
|
406
|
+
* expands each step into a one-task phase, in order ({@link import('./helpers.js').expandSteps}).
|
|
407
|
+
*/
|
|
408
|
+
var stepShape = objectShape({ name: stringShape({
|
|
409
|
+
min: 1,
|
|
410
|
+
description: "The registered behavior name this step runs (becomes the task run)."
|
|
411
|
+
}) });
|
|
412
|
+
/**
|
|
413
|
+
* The FLAT authoring shape {@link import('./factories.js').createWorkflowTool} advertises as its
|
|
414
|
+
* `parameters` — the simplest surface a small model can fill: `{ name?, steps: [{ name }] }`.
|
|
415
|
+
*
|
|
416
|
+
* @remarks
|
|
417
|
+
* A deliberately-reduced surface: a flat ordered list of steps, each a `{ name }`. The tool
|
|
418
|
+
* EXPANDS it ({@link import('./helpers.js').expandSteps}) into a full
|
|
419
|
+
* {@link import('./types.js').WorkflowDefinition} — one one-task phase per step, in order —
|
|
420
|
+
* then validates against the STRICT `createWorkflowContract` (`@orkestrel/workflow`) gate. The
|
|
421
|
+
* full nested form is STILL accepted by the tool (it branches on the args' shape) and is
|
|
422
|
+
* documented as the advanced escape-hatch in the tool's description — but THIS is what
|
|
423
|
+
* `parameters` advertises.
|
|
424
|
+
*/
|
|
425
|
+
var workflowStepsShape = objectShape({
|
|
426
|
+
name: optionalShape(stringShape({
|
|
427
|
+
min: 1,
|
|
428
|
+
description: "Optional workflow name."
|
|
429
|
+
})),
|
|
430
|
+
steps: arrayShape(stepShape, { description: "The ordered steps to run, one after another (each becomes a one-task phase)." })
|
|
431
|
+
});
|
|
432
|
+
/**
|
|
433
|
+
* The shape of a {@link import('./types.js').WorkspaceOperation} — a descriptive tagged union
|
|
434
|
+
* over the 13 workspace edit / read / navigation operations, discriminated by the `operation`
|
|
435
|
+
* literal (never a bare `kind`; AGENTS §4.4). Each variant leads with its `operation`
|
|
436
|
+
* discriminant then its FLAT fields, every field via `stringShape` / `optionalShape` /
|
|
437
|
+
* `integerShape({ min: 1 })` / `booleanShape`, each carrying a strong field-level `description`.
|
|
438
|
+
*
|
|
439
|
+
* @remarks
|
|
440
|
+
* The union compiles to an `anyOf` JSON Schema + a `unionOf` guard + a first-match parser
|
|
441
|
+
* automatically ({@link import('./factories.js').createWorkspaceTool} types the result to the
|
|
442
|
+
* hand-written {@link import('./types.js').WorkspaceOperation}). `limit` and the four `'splice'`
|
|
443
|
+
* caret components are POSITIVE integers (`integerShape({ min: 1 })`); `regex` / `exact` are
|
|
444
|
+
* `optionalShape(booleanShape(...))`. The two REGISTRY arms — `workspaces` (list the workspaces
|
|
445
|
+
* the model can move between) and `switch` (re-point the active one by `id`) — let a model
|
|
446
|
+
* DISCOVER then CHOOSE which workspace the edit / read arms target.
|
|
447
|
+
*/
|
|
448
|
+
var workspaceToolShape = unionShape(objectShape({
|
|
449
|
+
operation: literalShape(["read"], { description: "Read a whole text file's text by path." }),
|
|
450
|
+
path: stringShape({ description: "The path of the file to read." })
|
|
451
|
+
}), objectShape({ operation: literalShape(["list"], { description: "List every file in the workspace." }) }), objectShape({
|
|
452
|
+
operation: literalShape(["has"], { description: "Check whether a file exists at the path." }),
|
|
453
|
+
path: stringShape({ description: "The path to check for." })
|
|
454
|
+
}), objectShape({
|
|
455
|
+
operation: literalShape(["search"], { description: "Search every text file for a query, returning each hit." }),
|
|
456
|
+
query: stringShape({ description: "The text (or regular-expression source) to search for." }),
|
|
457
|
+
regex: optionalShape(booleanShape({ description: "Treat the query as a regular expression. Defaults to false (a literal substring)." })),
|
|
458
|
+
exact: optionalShape(booleanShape({ description: "Match case-sensitively. Defaults to true (set false for case-insensitive)." })),
|
|
459
|
+
limit: optionalShape(integerShape({
|
|
460
|
+
min: 1,
|
|
461
|
+
description: "Stop after this many matches across all files. Omitted means unlimited."
|
|
462
|
+
}))
|
|
463
|
+
}), objectShape({
|
|
464
|
+
operation: literalShape(["replace"], { description: "Replace a query with a replacement across every text file." }),
|
|
465
|
+
query: stringShape({ description: "The text (or regular-expression source) to replace." }),
|
|
466
|
+
replacement: stringShape({ description: "The text to substitute for each match." }),
|
|
467
|
+
regex: optionalShape(booleanShape({ description: "Treat the query as a regular expression. Defaults to false (a literal substring)." })),
|
|
468
|
+
exact: optionalShape(booleanShape({ description: "Match case-sensitively. Defaults to true (set false for case-insensitive)." })),
|
|
469
|
+
limit: optionalShape(integerShape({
|
|
470
|
+
min: 1,
|
|
471
|
+
description: "Stop after this many replacements across all files. Omitted means unlimited."
|
|
472
|
+
}))
|
|
473
|
+
}), objectShape({
|
|
474
|
+
operation: literalShape(["write"], { description: "Create or overwrite a whole file with content." }),
|
|
475
|
+
path: stringShape({ description: "The path of the file to write." }),
|
|
476
|
+
content: stringShape({ description: "The full new contents of the file." })
|
|
477
|
+
}), objectShape({
|
|
478
|
+
operation: literalShape(["splice"], { description: "Replace a 1-based range of an existing text file (from inclusive, to exclusive) with content." }),
|
|
479
|
+
path: stringShape({ description: "The path of the text file to edit." }),
|
|
480
|
+
content: stringShape({ description: "The text to splice in place of the range." }),
|
|
481
|
+
fromLine: integerShape({
|
|
482
|
+
min: 1,
|
|
483
|
+
description: "The 1-based start line of the range (inclusive)."
|
|
484
|
+
}),
|
|
485
|
+
fromColumn: integerShape({
|
|
486
|
+
min: 1,
|
|
487
|
+
description: "The 1-based start column of the range (inclusive; column 1 is the first character)."
|
|
488
|
+
}),
|
|
489
|
+
toLine: integerShape({
|
|
490
|
+
min: 1,
|
|
491
|
+
description: "The 1-based end line of the range (exclusive)."
|
|
492
|
+
}),
|
|
493
|
+
toColumn: integerShape({
|
|
494
|
+
min: 1,
|
|
495
|
+
description: "The 1-based end column of the range (exclusive)."
|
|
496
|
+
})
|
|
497
|
+
}), objectShape({
|
|
498
|
+
operation: literalShape(["prepend"], { description: "Add content to the start of a file (creating it when absent)." }),
|
|
499
|
+
path: stringShape({ description: "The path of the file to prepend to." }),
|
|
500
|
+
content: stringShape({ description: "The text to add at the start of the file." })
|
|
501
|
+
}), objectShape({
|
|
502
|
+
operation: literalShape(["append"], { description: "Add content to the end of a file (creating it when absent)." }),
|
|
503
|
+
path: stringShape({ description: "The path of the file to append to." }),
|
|
504
|
+
content: stringShape({ description: "The text to add at the end of the file." })
|
|
505
|
+
}), objectShape({
|
|
506
|
+
operation: literalShape(["move"], { description: "Rename or move a file (overwriting an occupied target)." }),
|
|
507
|
+
from: stringShape({ description: "The current path of the file." }),
|
|
508
|
+
to: stringShape({ description: "The new path for the file." })
|
|
509
|
+
}), objectShape({
|
|
510
|
+
operation: literalShape(["remove"], { description: "Delete a file from the workspace." }),
|
|
511
|
+
path: stringShape({ description: "The path of the file to remove." })
|
|
512
|
+
}), objectShape({ operation: literalShape(["workspaces"], { description: "List the workspaces you can move between (each id, file count, and whether it is active), so you can pick an id to switch to." }) }), objectShape({
|
|
513
|
+
operation: literalShape(["switch"], { description: "Switch the active workspace to the one with this id (get ids from the \"workspaces\" operation). Edit and read operations then target it." }),
|
|
514
|
+
id: stringShape({ description: "The id of the workspace to make active (from the \"workspaces\" listing)." })
|
|
515
|
+
}));
|
|
516
|
+
//#endregion
|
|
517
|
+
//#region src/core/helpers.ts
|
|
518
|
+
/**
|
|
519
|
+
* The ancestry identifier of a workflow in a run chain — `workflow:<id>`.
|
|
520
|
+
*
|
|
521
|
+
* @remarks
|
|
522
|
+
* Namespacing keeps a workflow id and an {@link agentTag} agent name in ONE set without
|
|
523
|
+
* collision, so re-entering a workflow OR an agent already in the chain is a single `includes`
|
|
524
|
+
* check.
|
|
525
|
+
*
|
|
526
|
+
* @param id - The workflow definition's `id`
|
|
527
|
+
* @returns The namespaced ancestry tag (`workflow:<id>`)
|
|
528
|
+
*/
|
|
529
|
+
function workflowTag(id) {
|
|
530
|
+
return `workflow:${id}`;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* The ancestry identifier of an agent in a run chain — `agent:<name>`.
|
|
534
|
+
*
|
|
535
|
+
* @remarks
|
|
536
|
+
* The agent counterpart of {@link workflowTag}: {@link import('./factories.js').createAgentFunction}
|
|
537
|
+
* / {@link import('./factories.js').createWorkflowTool} guard against re-entering an agent or
|
|
538
|
+
* workflow already in the chain (a typed `DEPTH` `WorkflowError`, `@orkestrel/workflow`). The
|
|
539
|
+
* `agent:` namespace keeps it distinct from a same-string workflow id.
|
|
540
|
+
*
|
|
541
|
+
* @param name - The agent's identifier / registry name
|
|
542
|
+
* @returns The namespaced ancestry tag (`agent:<name>`)
|
|
543
|
+
*/
|
|
544
|
+
function agentTag(name) {
|
|
545
|
+
return `agent:${name}`;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Build the plain success summary {@link import('./factories.js').createWorkflowTool} returns on
|
|
549
|
+
* a completed run — the universal tool-handler contract (AGENTS §14): return a plain value on
|
|
550
|
+
* success, appearing identically over BOTH the agent loop and MCP.
|
|
551
|
+
*
|
|
552
|
+
* @remarks
|
|
553
|
+
* The summary is LEAN: the workflow's terminal `status` and the COUNT of settled task results —
|
|
554
|
+
* enough for a caller / model to react without serializing the whole live tree. (It carries no
|
|
555
|
+
* synthetic `id` / `name`: a tool handler has no call id; the `ToolManagerInterface`
|
|
556
|
+
* (`@orkestrel/agent`) supplies the canonical envelope's identity.)
|
|
557
|
+
*
|
|
558
|
+
* @param result - The terminal `WorkflowResult` (`@orkestrel/workflow`) the run produced
|
|
559
|
+
* @returns The plain success summary — `{ status, count }`
|
|
560
|
+
*/
|
|
561
|
+
function workflowToolSummary(result) {
|
|
562
|
+
return {
|
|
563
|
+
status: result.status,
|
|
564
|
+
count: result.results.length
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* Complete a {@link WorkflowDraft} into a strict {@link WorkflowDefinition} — synthesize any
|
|
569
|
+
* MISSING `id` deterministically + positionally, and default any MISSING `name` to its
|
|
570
|
+
* (now-resolved) `id`.
|
|
571
|
+
*
|
|
572
|
+
* @remarks
|
|
573
|
+
* The positional id scheme is stable and human-legible: the workflow is `wf`, phase `i` is
|
|
574
|
+
* `phase-<i>`, and task `j` of that phase is `<phaseId>-task-<j>` (so a provided phase id flows
|
|
575
|
+
* into its tasks' synthesized ids). A PROVIDED `id` / `name` at any level is kept VERBATIM —
|
|
576
|
+
* synthesis touches only the omitted ones. A missing `name` defaults to the resolved `id` (never
|
|
577
|
+
* the other way round), so the result always has both. `run`, `description`, the per-phase
|
|
578
|
+
* `concurrency` / `bail`, the per-task `retries` / `timeout`, and the workflow `bail` carry over
|
|
579
|
+
* unchanged. The result is a complete {@link WorkflowDefinition}; the caller still validates it
|
|
580
|
+
* against the STRICT contract.
|
|
581
|
+
*
|
|
582
|
+
* @param draft - The draft workflow (id/name optional at all three levels)
|
|
583
|
+
* @returns A complete {@link WorkflowDefinition} with every id/name filled
|
|
584
|
+
*/
|
|
585
|
+
function completeDraft(draft) {
|
|
586
|
+
const id = draft.id ?? "wf";
|
|
587
|
+
return {
|
|
588
|
+
id,
|
|
589
|
+
name: draft.name ?? id,
|
|
590
|
+
...draft.description === void 0 ? {} : { description: draft.description },
|
|
591
|
+
phases: draft.phases.map((phase, index) => completePhaseDraft(phase, index)),
|
|
592
|
+
...draft.bail === void 0 ? {} : { bail: draft.bail }
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Complete one {@link PhaseDraft} into a strict phase definition — the per-phase step of
|
|
597
|
+
* {@link completeDraft} (phase `index` → `phase-<index>` when its id is omitted).
|
|
598
|
+
*
|
|
599
|
+
* @param phase - The draft phase
|
|
600
|
+
* @param index - The phase's positional index in the workflow
|
|
601
|
+
* @returns A complete phase definition
|
|
602
|
+
*/
|
|
603
|
+
function completePhaseDraft(phase, index) {
|
|
604
|
+
const id = phase.id ?? `phase-${index}`;
|
|
605
|
+
return {
|
|
606
|
+
id,
|
|
607
|
+
name: phase.name ?? id,
|
|
608
|
+
...phase.description === void 0 ? {} : { description: phase.description },
|
|
609
|
+
tasks: phase.tasks.map((task, taskIndex) => completeTaskDraft(task, id, taskIndex)),
|
|
610
|
+
...phase.concurrency === void 0 ? {} : { concurrency: phase.concurrency },
|
|
611
|
+
...phase.bail === void 0 ? {} : { bail: phase.bail }
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Complete one {@link TaskDraft} into a strict task definition — the per-task leaf step of
|
|
616
|
+
* {@link completeDraft} (task `index` of phase `<phaseId>` → `<phaseId>-task-<index>` when its id
|
|
617
|
+
* is omitted).
|
|
618
|
+
*
|
|
619
|
+
* @param task - The draft task
|
|
620
|
+
* @param phaseId - The (resolved) parent phase id, so the synthesized task id nests under it
|
|
621
|
+
* @param index - The task's positional index within its phase
|
|
622
|
+
* @returns A complete task definition
|
|
623
|
+
*/
|
|
624
|
+
function completeTaskDraft(task, phaseId, index) {
|
|
625
|
+
const id = task.id ?? `${phaseId}-task-${index}`;
|
|
626
|
+
return {
|
|
627
|
+
id,
|
|
628
|
+
name: task.name ?? id,
|
|
629
|
+
...task.description === void 0 ? {} : { description: task.description },
|
|
630
|
+
...task.run === void 0 ? {} : { run: task.run },
|
|
631
|
+
...task.retries === void 0 ? {} : { retries: task.retries },
|
|
632
|
+
...task.timeout === void 0 ? {} : { timeout: task.timeout }
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
/**
|
|
636
|
+
* Expand a flat {@link WorkflowSteps} blob into a strict {@link WorkflowDefinition} — each step
|
|
637
|
+
* becomes a one-task phase, IN ORDER.
|
|
638
|
+
*
|
|
639
|
+
* @remarks
|
|
640
|
+
* The expansion of the tool's ADVERTISED surface: the deliberately-reduced flat form. Each
|
|
641
|
+
* {@link import('./types.js').WorkflowStep} maps to a phase holding exactly one task: the step's
|
|
642
|
+
* `name` becomes the task's `run` (the behavior-registry key). Ids/names are auto-filled
|
|
643
|
+
* positionally — it builds an ids-omitted {@link WorkflowDraft} and delegates to
|
|
644
|
+
* {@link completeDraft}, so the two lenient surfaces share ONE synthesis path (step `i` → phase
|
|
645
|
+
* `phase-<i>`, its task `phase-<i>-task-0`). The optional `name` becomes the workflow's `name`.
|
|
646
|
+
* The result is a complete definition the caller validates against the STRICT contract before
|
|
647
|
+
* running.
|
|
648
|
+
*
|
|
649
|
+
* @param flat - The flat steps blob (`{ name?, steps: [{ name }] }`)
|
|
650
|
+
* @returns A complete {@link WorkflowDefinition} (one one-task phase per step)
|
|
651
|
+
*/
|
|
652
|
+
function expandSteps(flat) {
|
|
653
|
+
return completeDraft({
|
|
654
|
+
...flat.name === void 0 ? {} : { name: flat.name },
|
|
655
|
+
phases: flat.steps.map((step) => ({ tasks: [{ run: step.name }] }))
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
//#endregion
|
|
659
|
+
//#region src/core/factories.ts
|
|
660
|
+
/**
|
|
661
|
+
* Wrap a registered tool as a {@link WorkflowFunction} (`@orkestrel/workflow`) — the OPT-IN
|
|
662
|
+
* adapter that lets a `function`-form task run a `@orkestrel/agent` tool BY NAME.
|
|
663
|
+
*
|
|
664
|
+
* @remarks
|
|
665
|
+
* OWNED here now (ported from `@orkestrel/workflow`). Composes into a caller's
|
|
666
|
+
* `WorkflowOptions.functions` registry like any other behavior
|
|
667
|
+
* (`{ publish: createToolFunction(tools, 'publish') }`); the pure workflow runner has no
|
|
668
|
+
* knowledge of tools itself. The returned function executes `name` against `tools` with the
|
|
669
|
+
* task's `controller.input` as the call arguments, id-correlated to the task's own id. A
|
|
670
|
+
* `ToolManagerInterface.execute` (`@orkestrel/agent`) NEVER throws (a handler throw is isolated
|
|
671
|
+
* into `result.error`), so a failing tool is surfaced here as a THROWN `Error` carrying the
|
|
672
|
+
* original message as `cause` — the leaf `fail`s, honouring `bail`. An UNREGISTERED tool name is
|
|
673
|
+
* a programmer error (an explicit binding to a name that doesn't exist) — unlike the engine's
|
|
674
|
+
* own silent auto-complete of an unresolved task handler, this THROWS a typed `TOOL`
|
|
675
|
+
* `WorkflowError` (`@orkestrel/workflow`).
|
|
676
|
+
*
|
|
677
|
+
* @param tools - The `ToolManagerInterface` (`@orkestrel/agent`) the named tool is registered on
|
|
678
|
+
* @param name - The registered tool's name
|
|
679
|
+
* @returns A {@link WorkflowFunction} that runs the named tool
|
|
680
|
+
*
|
|
681
|
+
* @example
|
|
682
|
+
* ```ts
|
|
683
|
+
* import { createToolFunction } from '@src/core'
|
|
684
|
+
* import { createToolManager } from '@orkestrel/agent'
|
|
685
|
+
* import { createWorkflowRunner } from '@orkestrel/workflow'
|
|
686
|
+
*
|
|
687
|
+
* const tools = createToolManager()
|
|
688
|
+
* tools.add(myPublishTool)
|
|
689
|
+
* const runner = createWorkflowRunner()
|
|
690
|
+
* await runner.execute(definition, { functions: { publish: createToolFunction(tools, 'publish') } })
|
|
691
|
+
* ```
|
|
692
|
+
*/
|
|
693
|
+
function createToolFunction(tools, name) {
|
|
694
|
+
return async (controller) => {
|
|
695
|
+
if (tools.tool(name) === void 0) throw new WorkflowError("TOOL", `tool '${name}' is not registered`, { tool: name });
|
|
696
|
+
const result = await tools.execute({
|
|
697
|
+
id: controller.task.id,
|
|
698
|
+
name,
|
|
699
|
+
arguments: controller.input
|
|
700
|
+
});
|
|
701
|
+
if (result.error !== void 0) throw new Error(result.error, { cause: result.error });
|
|
702
|
+
return result.value;
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
/**
|
|
706
|
+
* Wrap a live `AgentInterface` (`@orkestrel/agent`) as a {@link WorkflowFunction}
|
|
707
|
+
* (`@orkestrel/workflow`) — the OPT-IN adapter that runs the agent to a settled result, folding
|
|
708
|
+
* a nested workflow-authoring depth / cycle guard into its own closure.
|
|
709
|
+
*
|
|
710
|
+
* @remarks
|
|
711
|
+
* OWNED here now (ported from `@orkestrel/workflow`). Composes into a caller's
|
|
712
|
+
* `WorkflowOptions.functions` registry like any other behavior; the pure workflow runner has no
|
|
713
|
+
* knowledge of agents itself. Before running the agent, the depth/cycle guard REJECTS the call
|
|
714
|
+
* (a THROWN typed `DEPTH` `WorkflowError`, which the leaf `fail`s) when running it would push a
|
|
715
|
+
* nested chain past {@link import('./constants.js').MAX_WORKFLOW_DEPTH}, OR when this agent is
|
|
716
|
+
* already an ancestor (a cycle). When {@link import('./types.js').AgentFunctionOptions.runner}
|
|
717
|
+
* is supplied, the adapter BINDS a depth/cycle-aware {@link createWorkflowTool} onto the agent's
|
|
718
|
+
* `context.tools` (the propagation seam) — closed over `depth` and the extended ancestry (the
|
|
719
|
+
* tool itself computes `depth + 1` internally) — so the agent can author + run a NESTED workflow
|
|
720
|
+
* through it; the wrapped default is the CURRENT task's own workflow id (used only on a no-args
|
|
721
|
+
* tool call). The task's cancellation folds into the agent run: an already-aborted
|
|
722
|
+
* `controller.signal` cancels the agent up front; otherwise a one-shot listener fires
|
|
723
|
+
* `agent.abort(reason)` when the task cancels, removed in `finally`. `agent.generate()` resolves
|
|
724
|
+
* a partial `AgentResult` on a cancel (never rejects), returned as the task's completed value.
|
|
725
|
+
*
|
|
726
|
+
* A bound agent is effectively SINGLE-RUN: `context.tools.add` binds one `ToolInterface` under
|
|
727
|
+
* the fixed {@link import('./constants.js').WORKFLOW_TOOL_NAME}, and `agent.generate()` /
|
|
728
|
+
* `agent.abort()` are per-agent state. Two CONCURRENT tasks sharing the SAME `agent` instance
|
|
729
|
+
* race on that one tool binding (last-write-wins) and on generate/abort — give each concurrent
|
|
730
|
+
* task its OWN agent instance.
|
|
731
|
+
*
|
|
732
|
+
* @param agent - The live `AgentInterface` to run
|
|
733
|
+
* @param options - The nested-workflow binding + depth/cycle bookkeeping (see {@link import('./types.js').AgentFunctionOptions})
|
|
734
|
+
* @returns A {@link WorkflowFunction} that runs `agent` to its settled result
|
|
735
|
+
*
|
|
736
|
+
* @example
|
|
737
|
+
* ```ts
|
|
738
|
+
* import { createAgentFunction } from '@src/core'
|
|
739
|
+
* import { createWorkflowRunner } from '@orkestrel/workflow'
|
|
740
|
+
*
|
|
741
|
+
* const runner = createWorkflowRunner()
|
|
742
|
+
* const review = createAgentFunction(myAgent, { runner })
|
|
743
|
+
* await runner.execute(definition, { functions: { review } })
|
|
744
|
+
* ```
|
|
745
|
+
*/
|
|
746
|
+
function createAgentFunction(agent, options) {
|
|
747
|
+
return async (controller) => {
|
|
748
|
+
const depth = options?.depth ?? 0;
|
|
749
|
+
const ancestry = options?.ancestry ?? [];
|
|
750
|
+
if (depth + 1 > 8) throw new WorkflowError("DEPTH", `agent '${agent.id}' exceeds max workflow depth`, {
|
|
751
|
+
agent: agent.id,
|
|
752
|
+
depth,
|
|
753
|
+
max: 8
|
|
754
|
+
});
|
|
755
|
+
const tag = agentTag(agent.id);
|
|
756
|
+
if (ancestry.includes(tag)) throw new WorkflowError("DEPTH", `agent '${agent.id}' is already an ancestor (cycle)`, {
|
|
757
|
+
agent: agent.id,
|
|
758
|
+
ancestry: [...ancestry]
|
|
759
|
+
});
|
|
760
|
+
const runner = options?.runner;
|
|
761
|
+
if (runner !== void 0) {
|
|
762
|
+
const workflowId = controller.task.phase.workflow.id;
|
|
763
|
+
const wrapped = {
|
|
764
|
+
id: workflowId,
|
|
765
|
+
name: workflowId,
|
|
766
|
+
phases: []
|
|
767
|
+
};
|
|
768
|
+
agent.context.tools.add(createWorkflowTool(wrapped, runner, {
|
|
769
|
+
depth,
|
|
770
|
+
ancestry: [...ancestry, tag]
|
|
771
|
+
}));
|
|
772
|
+
}
|
|
773
|
+
const signal = controller.signal;
|
|
774
|
+
const onAbort = () => agent.abort(signal.reason);
|
|
775
|
+
if (signal.aborted) agent.abort(signal.reason);
|
|
776
|
+
else signal.addEventListener("abort", onAbort, { once: true });
|
|
777
|
+
try {
|
|
778
|
+
return await agent.generate();
|
|
779
|
+
} finally {
|
|
780
|
+
signal.removeEventListener("abort", onAbort);
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
/**
|
|
785
|
+
* Compile the LENIENT workflow DRAFT contract — identical to `createWorkflowContract`
|
|
786
|
+
* (`@orkestrel/workflow`) EXCEPT `id` and `name` are OPTIONAL at all three levels (workflow /
|
|
787
|
+
* phase / task), so a small model can omit the six identity strings.
|
|
788
|
+
*
|
|
789
|
+
* @remarks
|
|
790
|
+
* The widened authoring surface {@link createWorkflowTool} parses an authored blob through
|
|
791
|
+
* before {@link import('./helpers.js').completeDraft} fills the missing ids/names. It does NOT
|
|
792
|
+
* relax the canonical contract — `createWorkflowContract` (`@orkestrel/workflow`) stays
|
|
793
|
+
* byte-for-byte unchanged and STRICT, and the completed draft is re-validated against THAT
|
|
794
|
+
* strict gate before running (soundness preserved). A PROVIDED `id` / `name` still carries
|
|
795
|
+
* `minLength: 1`, so an explicitly-empty `id: ''` is REJECTED (parses to `undefined`), never
|
|
796
|
+
* auto-filled — keeping "garbage" distinct from "omitted". `run` stays optional (a plain name
|
|
797
|
+
* string).
|
|
798
|
+
*
|
|
799
|
+
* @returns The compiled {@link import('./types.js').WorkflowDraft} contract
|
|
800
|
+
*
|
|
801
|
+
* @example
|
|
802
|
+
* ```ts
|
|
803
|
+
* import { createWorkflowDraftContract, completeDraft } from '@src/core'
|
|
804
|
+
*
|
|
805
|
+
* const draft = createWorkflowDraftContract()
|
|
806
|
+
* const parsed = draft.parse({ phases: [{ tasks: [{ run: 'compile' }] }] })
|
|
807
|
+
* const definition = parsed && completeDraft(parsed) // ids/names filled positionally
|
|
808
|
+
* draft.parse({ id: '', phases: [] }) // undefined — an explicit empty id is rejected
|
|
809
|
+
* ```
|
|
810
|
+
*/
|
|
811
|
+
function createWorkflowDraftContract() {
|
|
812
|
+
return createContract(workflowDraftShape);
|
|
813
|
+
}
|
|
814
|
+
/**
|
|
815
|
+
* Wrap a {@link WorkflowDefinition} as an LLM-callable tool — it ADVERTISES the SIMPLE flat
|
|
816
|
+
* authoring shape (`{ name?, steps: [{ name }] }`) as its `parameters` so even a small model can
|
|
817
|
+
* author a complete tree, and its handler EXPANDS / COMPLETES the authored blob, validates it
|
|
818
|
+
* against the STRICT contract, runs it through `runner`, and, when
|
|
819
|
+
* {@link import('./types.js').WorkflowToolOptions.store} is supplied, PERSISTS each executed
|
|
820
|
+
* workflow's final snapshot after the run settles.
|
|
821
|
+
*
|
|
822
|
+
* @remarks
|
|
823
|
+
* A plain `ToolManagerInterface`-compatible tool (`@orkestrel/agent`), reproducing
|
|
824
|
+
* `@orkestrel/workflow`'s former call contract exactly (flat / draft / full authoring forms, the
|
|
825
|
+
* strict soundness gate, the depth/cycle guard). It is ALSO the propagation carrier
|
|
826
|
+
* {@link createAgentFunction} binds onto a wrapped agent's `context.tools`: because a tool
|
|
827
|
+
* handler receives ONLY the model-supplied `args` (no ambient context, no signal), the run's
|
|
828
|
+
* depth + ancestry are CLOSED OVER at bind time via {@link import('./types.js').WorkflowToolOptions},
|
|
829
|
+
* and the handler enforces the SAME depth / cycle guard itself before running the nested
|
|
830
|
+
* workflow at `depth + 1` with the extended ancestry.
|
|
831
|
+
*
|
|
832
|
+
* **Widened authoring surface (additive — the canonical contract + runner stay STRICT and
|
|
833
|
+
* unchanged).** A 2B model reliably CALLS the tool but cannot reliably emit the full four-level
|
|
834
|
+
* nested {@link WorkflowDefinition} (six required `id`/`name` strings, an all-or-nothing tree).
|
|
835
|
+
* So the tool ACCEPTS three authoring forms and converges them on the SAME strict
|
|
836
|
+
* `createWorkflowContract` gate before running (soundness preserved):
|
|
837
|
+
* - the FLAT shape `{ name?, steps: [{ name }] }` — the ADVERTISED `parameters` (the simplest
|
|
838
|
+
* form, {@link import('./helpers.js').expandSteps}'d into one one-task phase per step);
|
|
839
|
+
* - a nested DRAFT with any `id`/`name` OMITTED — {@link createWorkflowDraftContract}-parsed then
|
|
840
|
+
* {@link import('./helpers.js').completeDraft}'d (missing ids synthesized positionally);
|
|
841
|
+
* - the full nested {@link WorkflowDefinition} — the advanced escape-hatch, accepted as the draft
|
|
842
|
+
* super-set.
|
|
843
|
+
*
|
|
844
|
+
* The universal tool-handler contract (AGENTS §14): returns the plain run summary
|
|
845
|
+
* (`{ status, count }`) on success, THROWS a typed `WorkflowError` (`@orkestrel/workflow`) on
|
|
846
|
+
* every failure path — malformed authored args (`TOOL`), or an over-deep / cyclic nested run
|
|
847
|
+
* (`DEPTH`). The `ToolManagerInterface` isolates every throw into the canonical tool result's
|
|
848
|
+
* top-level `error`, so nothing escapes the run. `options.depth` / `options.ancestry` are the
|
|
849
|
+
* propagation carrier across a workflow → agent → workflow chain; `options.store` is this
|
|
850
|
+
* package's ADDITION — the persisted snapshot is retrievable via the store afterwards (a caller
|
|
851
|
+
* restores it through `@orkestrel/workflow`'s own `Workflow.restore` / store-backed factories).
|
|
852
|
+
*
|
|
853
|
+
* @param definition - The workflow the tool runs when called with no authored args
|
|
854
|
+
* @param runner - The `WorkflowRunnerInterface` (`@orkestrel/workflow`) that executes the (nested) workflow
|
|
855
|
+
* @param options - Depth/ancestry bookkeeping plus the optional durable store (see {@link import('./types.js').WorkflowToolOptions})
|
|
856
|
+
* @returns A `ToolInterface` (named {@link import('./constants.js').WORKFLOW_TOOL_NAME}) whose
|
|
857
|
+
* `parameters` advertise the flat authoring schema
|
|
858
|
+
*
|
|
859
|
+
* @example
|
|
860
|
+
* ```ts
|
|
861
|
+
* import { createWorkflowTool } from '@src/core'
|
|
862
|
+
* import { createWorkflowRunner, createMemoryWorkflowStore } from '@orkestrel/workflow'
|
|
863
|
+
* import { createToolManager } from '@orkestrel/agent'
|
|
864
|
+
*
|
|
865
|
+
* const runner = createWorkflowRunner()
|
|
866
|
+
* const store = createMemoryWorkflowStore()
|
|
867
|
+
* const tool = createWorkflowTool(definition, runner, { store })
|
|
868
|
+
* const tools = createToolManager()
|
|
869
|
+
* tools.add(tool) // authored runs are now persisted to `store` on settle
|
|
870
|
+
* ```
|
|
871
|
+
*/
|
|
872
|
+
function createWorkflowTool(definition, runner, options) {
|
|
873
|
+
const strict = createWorkflowContract();
|
|
874
|
+
const draft = createWorkflowDraftContract();
|
|
875
|
+
const steps = createContract(workflowStepsShape);
|
|
876
|
+
const depth = options?.depth ?? 0;
|
|
877
|
+
const ancestry = options?.ancestry ?? [];
|
|
878
|
+
const store = options?.store;
|
|
879
|
+
return createTool({
|
|
880
|
+
name: WORKFLOW_TOOL_NAME,
|
|
881
|
+
description: WORKFLOW_TOOL_DESCRIPTION,
|
|
882
|
+
summary: WORKFLOW_TOOL_SUMMARY,
|
|
883
|
+
parameters: schemaToParameters(steps.schema),
|
|
884
|
+
execute: async (args) => {
|
|
885
|
+
let target;
|
|
886
|
+
if (Object.keys(args).length === 0) target = definition;
|
|
887
|
+
else if (Array.isArray(args.steps)) {
|
|
888
|
+
const flat = steps.parse(args);
|
|
889
|
+
target = flat === void 0 ? void 0 : expandSteps(flat);
|
|
890
|
+
} else {
|
|
891
|
+
const parsed = draft.parse(args);
|
|
892
|
+
target = parsed === void 0 ? void 0 : completeDraft(parsed);
|
|
893
|
+
}
|
|
894
|
+
if (target === void 0 || !strict.is(target)) throw new WorkflowError("TOOL", "malformed workflow definition", { workflow: definition.id });
|
|
895
|
+
if (depth + 1 > 8) throw new WorkflowError("DEPTH", `nested workflow exceeds max depth 8`, {
|
|
896
|
+
workflow: target.id,
|
|
897
|
+
depth,
|
|
898
|
+
max: 8
|
|
899
|
+
});
|
|
900
|
+
const tag = workflowTag(target.id);
|
|
901
|
+
if (ancestry.includes(tag)) throw new WorkflowError("DEPTH", `workflow '${target.id}' is already an ancestor (cycle)`, {
|
|
902
|
+
workflow: target.id,
|
|
903
|
+
ancestry: [...ancestry]
|
|
904
|
+
});
|
|
905
|
+
const result = await runner.execute(target);
|
|
906
|
+
if (store !== void 0) await store.set(result.workflow.snapshot());
|
|
907
|
+
return workflowToolSummary(result);
|
|
908
|
+
}
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
/**
|
|
912
|
+
* Build an LLM-callable workspace-editing tool — it ADVERTISES the `operation`-discriminated
|
|
913
|
+
* 13-op union ({@link import('./shapers.js').workspaceToolShape}) as its `parameters`, and its
|
|
914
|
+
* handler PARSES the model-supplied args against that contract and DISPATCHES the matched
|
|
915
|
+
* operation against the manager's ACTIVE workspace (the registry ops drive the manager itself),
|
|
916
|
+
* returning the plain result (throwing a typed `WorkspaceError`, `@orkestrel/agent`, on
|
|
917
|
+
* failure). EITHER drives a caller-supplied {@link WorkspaceToolOptions.manager} directly, OR
|
|
918
|
+
* constructs a fresh `WorkspaceManagerInterface` (`@orkestrel/agent`) over
|
|
919
|
+
* {@link import('./types.js').WorkspaceToolOptions.store} (via `@orkestrel/agent`'s
|
|
920
|
+
* `createWorkspaceManager`); neither given constructs a manager backed by `@orkestrel/agent`'s
|
|
921
|
+
* in-memory store default.
|
|
922
|
+
*
|
|
923
|
+
* @remarks
|
|
924
|
+
* MANAGER-DRIVEN: every edit / read op (read / list / has / search / replace / write / splice /
|
|
925
|
+
* prepend / append / move / remove) targets `manager.active`, so the model edits whichever
|
|
926
|
+
* workspace is active and a host can re-point it (`WorkspaceManagerInterface.switch`) between
|
|
927
|
+
* turns. Two REGISTRY ops make the model self-sufficient: `workspaces` LISTS the registered
|
|
928
|
+
* workspaces (each `{ id, files, active }`) so it can discover an id, and `switch` re-points the
|
|
929
|
+
* active workspace by id (lenient — an unknown id is a no-op reporting `switched: false`, never a
|
|
930
|
+
* throw).
|
|
931
|
+
*
|
|
932
|
+
* NO-ACTIVE RULE (the ergonomic seam): a WRITING op (write / splice / prepend / append / move /
|
|
933
|
+
* remove / replace) run when `manager.active` is `undefined` AUTO-CREATES + activates a default
|
|
934
|
+
* workspace (`manager.add()`) so the model can just start writing; a pure-READ op (read / list /
|
|
935
|
+
* has / search) against no active workspace returns the EMPTY result (`undefined` / `[]` /
|
|
936
|
+
* `false`), never creating one and never throwing.
|
|
937
|
+
*
|
|
938
|
+
* The handler conforms to the universal tool-handler contract (AGENTS §14): it `contract.parse`s
|
|
939
|
+
* the args, THROWS a `TOOL` `WorkspaceError` when no operation arm matched (a malformed / unknown
|
|
940
|
+
* operation), else `switch`es on `op.operation` and RETURNS the plain result — letting a
|
|
941
|
+
* `WorkspaceError` raised by the live workspace (`MODALITY` / `PATTERN` / `RANGE`) PROPAGATE
|
|
942
|
+
* uncaught. The range edit is the FLAT `'splice'` op: its four flat caret integers are
|
|
943
|
+
* reassembled into a `Range` (`@orkestrel/agent`) by `rangeOf` and fed to the workspace's ranged
|
|
944
|
+
* `write`.
|
|
945
|
+
*
|
|
946
|
+
* @param options - `manager` (drive directly) OR `store` (build a manager over it); neither ⇒
|
|
947
|
+
* an in-memory-backed manager (see {@link import('./types.js').WorkspaceToolOptions})
|
|
948
|
+
* @returns A `ToolInterface` (named {@link import('./constants.js').WORKSPACE_TOOL_NAME} by default)
|
|
949
|
+
*
|
|
950
|
+
* @example
|
|
951
|
+
* ```ts
|
|
952
|
+
* import { createWorkspaceTool } from '@src/core'
|
|
953
|
+
* import { createToolManager } from '@orkestrel/agent'
|
|
954
|
+
*
|
|
955
|
+
* const tool = createWorkspaceTool() // in-memory workspace, no persistence
|
|
956
|
+
* const tools = createToolManager()
|
|
957
|
+
* tools.add(tool)
|
|
958
|
+
* ```
|
|
959
|
+
*/
|
|
960
|
+
function createWorkspaceTool(options) {
|
|
961
|
+
const manager = options?.manager ?? createWorkspaceManager(options?.store === void 0 ? void 0 : { store: options.store });
|
|
962
|
+
const contract = createContract(workspaceToolShape);
|
|
963
|
+
const parameters = schemaToParameters(contract.schema);
|
|
964
|
+
return createTool({
|
|
965
|
+
name: options?.name ?? "workspace",
|
|
966
|
+
description: options?.description ?? WORKSPACE_TOOL_DESCRIPTION,
|
|
967
|
+
summary: WORKSPACE_TOOL_SUMMARY,
|
|
968
|
+
parameters,
|
|
969
|
+
execute: (args) => {
|
|
970
|
+
const op = contract.parse(args);
|
|
971
|
+
if (op === void 0) throw new WorkspaceError("TOOL", `unknown or malformed operation`, { args });
|
|
972
|
+
if (op.operation === "workspaces") {
|
|
973
|
+
const activeId = manager.active?.id;
|
|
974
|
+
return manager.workspaces().map((workspace) => ({
|
|
975
|
+
id: workspace.id,
|
|
976
|
+
files: workspace.count,
|
|
977
|
+
active: workspace.id === activeId
|
|
978
|
+
}));
|
|
979
|
+
}
|
|
980
|
+
if (op.operation === "switch") {
|
|
981
|
+
const switched = manager.switch(op.id);
|
|
982
|
+
return switched === void 0 ? {
|
|
983
|
+
id: op.id,
|
|
984
|
+
switched: false
|
|
985
|
+
} : {
|
|
986
|
+
id: switched.id,
|
|
987
|
+
switched: true,
|
|
988
|
+
files: switched.count
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
const active = manager.active;
|
|
992
|
+
switch (op.operation) {
|
|
993
|
+
case "read": return active?.read(op.path);
|
|
994
|
+
case "list": return (active?.files() ?? []).map((file) => ({
|
|
995
|
+
path: file.path,
|
|
996
|
+
state: file.state,
|
|
997
|
+
size: file.size,
|
|
998
|
+
lines: file.lines,
|
|
999
|
+
kind: isText(file.content) ? "text" : "binary"
|
|
1000
|
+
}));
|
|
1001
|
+
case "has": return active?.has(op.path) ?? false;
|
|
1002
|
+
case "search": return active?.search(op.query, {
|
|
1003
|
+
regex: op.regex,
|
|
1004
|
+
exact: op.exact,
|
|
1005
|
+
limit: op.limit
|
|
1006
|
+
}) ?? [];
|
|
1007
|
+
case "replace": return (active ?? manager.add()).replace(op.query, op.replacement, {
|
|
1008
|
+
regex: op.regex,
|
|
1009
|
+
exact: op.exact,
|
|
1010
|
+
limit: op.limit
|
|
1011
|
+
});
|
|
1012
|
+
case "write": {
|
|
1013
|
+
const workspace = active ?? manager.add();
|
|
1014
|
+
workspace.write(op.path, op.content);
|
|
1015
|
+
return {
|
|
1016
|
+
path: op.path,
|
|
1017
|
+
state: workspace.file(op.path)?.state
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
case "splice": {
|
|
1021
|
+
const workspace = active ?? manager.add();
|
|
1022
|
+
workspace.write(op.path, op.content, rangeOf(op.fromLine, op.fromColumn, op.toLine, op.toColumn));
|
|
1023
|
+
return {
|
|
1024
|
+
path: op.path,
|
|
1025
|
+
state: workspace.file(op.path)?.state
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
case "prepend": {
|
|
1029
|
+
const workspace = active ?? manager.add();
|
|
1030
|
+
workspace.prepend(op.path, op.content);
|
|
1031
|
+
return {
|
|
1032
|
+
path: op.path,
|
|
1033
|
+
state: workspace.file(op.path)?.state
|
|
1034
|
+
};
|
|
1035
|
+
}
|
|
1036
|
+
case "append": {
|
|
1037
|
+
const workspace = active ?? manager.add();
|
|
1038
|
+
workspace.append(op.path, op.content);
|
|
1039
|
+
return {
|
|
1040
|
+
path: op.path,
|
|
1041
|
+
state: workspace.file(op.path)?.state
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
case "move": {
|
|
1045
|
+
const workspace = active ?? manager.add();
|
|
1046
|
+
return {
|
|
1047
|
+
from: op.from,
|
|
1048
|
+
to: op.to,
|
|
1049
|
+
moved: workspace.move(op.from, op.to)
|
|
1050
|
+
};
|
|
1051
|
+
}
|
|
1052
|
+
case "remove": {
|
|
1053
|
+
const workspace = active ?? manager.add();
|
|
1054
|
+
return {
|
|
1055
|
+
path: op.path,
|
|
1056
|
+
removed: workspace.remove(op.path)
|
|
1057
|
+
};
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Build an LLM-callable sub-agent delegation tool — resolves a live, seeded `AgentInterface`
|
|
1065
|
+
* from `registry` and runs it to completion for ONE delegated `task`.
|
|
1066
|
+
*
|
|
1067
|
+
* @remarks
|
|
1068
|
+
* The universal tool-handler contract (AGENTS §14): validates the call args against
|
|
1069
|
+
* {@link import('./shapers.js').agentToolShape}, assembles an `AgentJobInput` (`task` seeds the
|
|
1070
|
+
* sub-agent's conversation as a single `user` message; `provider` / `tools` / `system` fall
|
|
1071
|
+
* back to the tool's own {@link import('./types.js').AgentToolOptions} defaults), rehydrates the sub-agent via
|
|
1072
|
+
* `registry.build`, runs it with `agent.generate()`, and returns the settled
|
|
1073
|
+
* `AgentResult.content` string (the sub-agent's final text). A missing / unresolvable `provider`, or a malformed call, THROWS a typed `TOOL`
|
|
1074
|
+
* {@link import('./errors.js').AgentToolError}; a delegation that would exceed
|
|
1075
|
+
* {@link import('./constants.js').AGENT_TOOL_DEPTH}, or re-enter an already-delegated agent (a
|
|
1076
|
+
* cycle), THROWS a typed `DEPTH` {@link import('./errors.js').AgentToolError} — both isolated
|
|
1077
|
+
* by the `ToolManagerInterface` into the canonical tool result's top-level `error`.
|
|
1078
|
+
*
|
|
1079
|
+
* `AgentInterface` (`@orkestrel/agent`) exposes no teardown method — a bound sub-agent's
|
|
1080
|
+
* lifetime is the single `generate()` call this handler awaits; there is nothing to release
|
|
1081
|
+
* afterwards (unlike a store-backed resource, its state lives entirely in the resolved
|
|
1082
|
+
* `AgentContextInterface`, owned by the caller's registry).
|
|
1083
|
+
*
|
|
1084
|
+
* @param registry - The `AgentRegistryInterface` a delegated job resolves against (providers,
|
|
1085
|
+
* tools, authorities, schedulers, and the `build` rehydration seam)
|
|
1086
|
+
* @param options - Delegation defaults, depth/ancestry bookkeeping, and advertised overrides
|
|
1087
|
+
* (see {@link import('./types.js').AgentToolOptions})
|
|
1088
|
+
* @returns A `ToolInterface` (named {@link import('./constants.js').AGENT_TOOL_NAME} by default)
|
|
1089
|
+
*
|
|
1090
|
+
* @example
|
|
1091
|
+
* ```ts
|
|
1092
|
+
* import { createAgentTool } from '@src/core'
|
|
1093
|
+
* import { createAgentRegistry, createToolManager } from '@orkestrel/agent'
|
|
1094
|
+
*
|
|
1095
|
+
* const registry = createAgentRegistry({ providers: { openai: myProvider } })
|
|
1096
|
+
* const tool = createAgentTool(registry, { provider: 'openai' })
|
|
1097
|
+
* const tools = createToolManager()
|
|
1098
|
+
* tools.add(tool) // a model can now delegate a task to a sub-agent
|
|
1099
|
+
* ```
|
|
1100
|
+
*/
|
|
1101
|
+
function createAgentTool(registry, options) {
|
|
1102
|
+
const contract = createContract(agentToolShape);
|
|
1103
|
+
const parameters = schemaToParameters(contract.schema);
|
|
1104
|
+
const depth = options?.depth ?? 0;
|
|
1105
|
+
const ancestry = options?.ancestry ?? [];
|
|
1106
|
+
return createTool({
|
|
1107
|
+
name: options?.name ?? "agent",
|
|
1108
|
+
description: options?.description ?? AGENT_TOOL_DESCRIPTION,
|
|
1109
|
+
summary: AGENT_TOOL_SUMMARY,
|
|
1110
|
+
parameters,
|
|
1111
|
+
execute: async (args) => {
|
|
1112
|
+
const call = contract.parse(args);
|
|
1113
|
+
if (call === void 0) throw new AgentToolError("TOOL", "malformed agent-delegation call", { args });
|
|
1114
|
+
const provider = call.provider ?? options?.provider;
|
|
1115
|
+
if (provider === void 0) throw new AgentToolError("TOOL", "no provider resolved for the delegated agent", { task: call.task });
|
|
1116
|
+
if (depth + 1 > 8) throw new AgentToolError("DEPTH", `delegation exceeds max agent depth 8`, {
|
|
1117
|
+
provider,
|
|
1118
|
+
depth,
|
|
1119
|
+
max: 8
|
|
1120
|
+
});
|
|
1121
|
+
const tag = agentTag(provider);
|
|
1122
|
+
if (ancestry.includes(tag)) throw new AgentToolError("DEPTH", `agent '${provider}' is already an ancestor (cycle)`, {
|
|
1123
|
+
provider,
|
|
1124
|
+
ancestry: [...ancestry]
|
|
1125
|
+
});
|
|
1126
|
+
const tools = call.tools ?? options?.tools;
|
|
1127
|
+
const system = call.system ?? options?.system;
|
|
1128
|
+
const agent = registry.build({
|
|
1129
|
+
provider,
|
|
1130
|
+
messages: [{
|
|
1131
|
+
role: "user",
|
|
1132
|
+
content: call.task
|
|
1133
|
+
}],
|
|
1134
|
+
...system === void 0 ? {} : { system },
|
|
1135
|
+
...tools === void 0 ? {} : { tools }
|
|
1136
|
+
});
|
|
1137
|
+
const result = await agent.generate();
|
|
1138
|
+
if (options?.store !== void 0) {
|
|
1139
|
+
const active = agent.context.conversations.active;
|
|
1140
|
+
if (active !== void 0) await options.store.set(active.snapshot());
|
|
1141
|
+
}
|
|
1142
|
+
return result.content;
|
|
1143
|
+
}
|
|
1144
|
+
});
|
|
1145
|
+
}
|
|
1146
|
+
/**
|
|
1147
|
+
* Build an LLM-callable tool that returns the FULL `description` of another registered tool by
|
|
1148
|
+
* name — the counterpart to the lean `summary` the other tools in this package advertise
|
|
1149
|
+
* (`AGENT_TOOL_SUMMARY` / `WORKFLOW_TOOL_SUMMARY` / `WORKSPACE_TOOL_SUMMARY`).
|
|
1150
|
+
*
|
|
1151
|
+
* @remarks
|
|
1152
|
+
* `ToolManagerInterface.definitions()` (`@orkestrel/agent`) advertises `tool.summary ??
|
|
1153
|
+
* tool.description` — a lean one-sentence summary stands in for a tool's full teaching
|
|
1154
|
+
* description when `summary` is set, keeping the advertised tool list compact for a small model.
|
|
1155
|
+
* This tool is the on-demand expansion seam: given a registered tool's `name`, it looks the tool
|
|
1156
|
+
* up via `tools.tool(name)` and returns its full `description` (falling back to `summary` when a
|
|
1157
|
+
* tool has no `description` of its own, then a placeholder when it has neither).
|
|
1158
|
+
*
|
|
1159
|
+
* The universal tool-handler contract (AGENTS §14): validates the call args against
|
|
1160
|
+
* {@link import('./shapers.js').describeToolShape}, RETURNS the plain description string on
|
|
1161
|
+
* success, THROWS a typed `TOOL` {@link import('./errors.js').AgentToolError} on a malformed call
|
|
1162
|
+
* or an unknown tool name.
|
|
1163
|
+
*
|
|
1164
|
+
* @param tools - The `ToolManagerInterface` (`@orkestrel/agent`) whose registered tools this
|
|
1165
|
+
* tool can describe
|
|
1166
|
+
* @returns A `ToolInterface` (named {@link import('./constants.js').DESCRIBE_TOOL_NAME})
|
|
1167
|
+
*
|
|
1168
|
+
* @example
|
|
1169
|
+
* ```ts
|
|
1170
|
+
* import { createDescribeTool, createWorkflowTool } from '@src/core'
|
|
1171
|
+
* import { createToolManager } from '@orkestrel/agent'
|
|
1172
|
+
*
|
|
1173
|
+
* const tools = createToolManager()
|
|
1174
|
+
* tools.add(createWorkflowTool(definition, runner))
|
|
1175
|
+
* tools.add(createDescribeTool(tools))
|
|
1176
|
+
* const full = await tools.execute({ id: '1', name: 'describe', arguments: { name: 'workflow' } })
|
|
1177
|
+
* full.value // the workflow tool's full teaching description
|
|
1178
|
+
* ```
|
|
1179
|
+
*/
|
|
1180
|
+
function createDescribeTool(tools) {
|
|
1181
|
+
const contract = createContract(describeToolShape);
|
|
1182
|
+
return createTool({
|
|
1183
|
+
name: DESCRIBE_TOOL_NAME,
|
|
1184
|
+
description: DESCRIBE_TOOL_DESCRIPTION,
|
|
1185
|
+
summary: DESCRIBE_TOOL_SUMMARY,
|
|
1186
|
+
parameters: schemaToParameters(contract.schema),
|
|
1187
|
+
execute: async (args) => {
|
|
1188
|
+
const call = contract.parse(args);
|
|
1189
|
+
if (call === void 0) throw new AgentToolError("TOOL", "malformed describe call", { args });
|
|
1190
|
+
const tool = tools.tool(call.name);
|
|
1191
|
+
if (tool === void 0) throw new AgentToolError("TOOL", `unknown tool '${call.name}'`, { name: call.name });
|
|
1192
|
+
return tool.description ?? tool.summary ?? "<no description>";
|
|
1193
|
+
}
|
|
1194
|
+
});
|
|
1195
|
+
}
|
|
1196
|
+
//#endregion
|
|
1197
|
+
export { AGENT_TOOL_DEPTH, AGENT_TOOL_DESCRIPTION, AGENT_TOOL_NAME, AGENT_TOOL_SUMMARY, AgentToolError, DESCRIBE_TOOL_DESCRIPTION, DESCRIBE_TOOL_NAME, DESCRIBE_TOOL_SUMMARY, MAX_WORKFLOW_DEPTH, WORKFLOW_TOOL_DESCRIPTION, WORKFLOW_TOOL_FLAT_EXAMPLE, WORKFLOW_TOOL_NAME, WORKFLOW_TOOL_NESTED_EXAMPLE, WORKFLOW_TOOL_SUMMARY, WORKSPACE_TOOL_DESCRIPTION, WORKSPACE_TOOL_EXAMPLE, WORKSPACE_TOOL_NAME, WORKSPACE_TOOL_SUMMARY, agentTag, agentToolShape, completeDraft, completePhaseDraft, completeTaskDraft, createAgentFunction, createAgentTool, createDescribeTool, createToolFunction, createWorkflowDraftContract, createWorkflowTool, createWorkspaceTool, describeToolShape, expandSteps, isAgentToolError, phaseDraftShape, stepShape, taskDraftShape, workflowDraftShape, workflowStepsShape, workflowTag, workflowToolSummary, workspaceToolShape };
|
|
1198
|
+
|
|
1199
|
+
//# sourceMappingURL=index.js.map
|