@sisu-ai/mw-orchestration 0.2.0
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 +201 -0
- package/README.md +85 -0
- package/dist/index.d.ts +153 -0
- package/dist/index.js +573 -0
- package/package.json +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# @sisu-ai/mw-orchestration
|
|
2
|
+
|
|
3
|
+
Orchestration middleware for delegated multi-agent execution in Sisu.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @sisu-ai/mw-orchestration
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## What it does
|
|
12
|
+
|
|
13
|
+
- Constrains orchestrator control actions to `delegateTask` and `finish`
|
|
14
|
+
- Delegates child work using a strict 4-tuple (`instruction`, `context`, `tools`, `model`)
|
|
15
|
+
- Tracks runtime state in `ctx.state.orchestration`
|
|
16
|
+
- Supports pluggable child executors (built-in inline executor included)
|
|
17
|
+
- Emits explicit orchestration events for tracing/observability
|
|
18
|
+
|
|
19
|
+
## Policy hooks and self-correction
|
|
20
|
+
|
|
21
|
+
The middleware supports pluggable policy hooks so behavior can be hardened without example-specific logic:
|
|
22
|
+
|
|
23
|
+
- `normalizeDelegationInput(raw, ctx)`
|
|
24
|
+
- `validateDelegation(input, ctx)`
|
|
25
|
+
- `resolveToolScope(input, ctx)`
|
|
26
|
+
- `modelResolver(modelRef, ctx)`
|
|
27
|
+
|
|
28
|
+
Delegation failures use a structured error contract (`code`, `message`, `hint`, `details`) so models can self-correct on the next `delegateTask` call.
|
|
29
|
+
|
|
30
|
+
## Flow
|
|
31
|
+
|
|
32
|
+
```mermaid
|
|
33
|
+
flowchart TD
|
|
34
|
+
U[User Task] --> O[Orchestrator Middleware]
|
|
35
|
+
O -->|delegateTask| C[Child Executor]
|
|
36
|
+
C --> CC[Scoped Child Context\n instruction + context + tools + model]
|
|
37
|
+
CC --> R[DelegationResult]
|
|
38
|
+
R --> O
|
|
39
|
+
O -->|finish| A[Final Assistant Answer]
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
```mermaid
|
|
43
|
+
sequenceDiagram
|
|
44
|
+
autonumber
|
|
45
|
+
participant P as Parent Orchestrator
|
|
46
|
+
participant M as Parent Model
|
|
47
|
+
participant E as Child Executor
|
|
48
|
+
participant CM as Child Model
|
|
49
|
+
participant T as Scoped Tools
|
|
50
|
+
|
|
51
|
+
P->>M: generate(messages, control tools)
|
|
52
|
+
M-->>P: assistant tool_call(delegateTask)
|
|
53
|
+
P->>E: execute(request 4-tuple)
|
|
54
|
+
E->>CM: generate(child messages, scoped tools)
|
|
55
|
+
CM-->>E: tool_call(s)
|
|
56
|
+
E->>T: invoke allowed tools only
|
|
57
|
+
T-->>E: tool results
|
|
58
|
+
E-->>P: DelegationResult(status, output, telemetry, trace)
|
|
59
|
+
P->>M: continue with tool message(result)
|
|
60
|
+
M-->>P: tool_call(finish)
|
|
61
|
+
P-->>P: append final assistant answer
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Usage
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { Agent } from "@sisu-ai/core";
|
|
68
|
+
import { orchestration } from "@sisu-ai/mw-orchestration";
|
|
69
|
+
|
|
70
|
+
const app = new Agent()
|
|
71
|
+
.use(
|
|
72
|
+
orchestration({
|
|
73
|
+
allowedModels: ["gpt-4o-mini"],
|
|
74
|
+
maxDelegations: 6,
|
|
75
|
+
defaultTimeoutMs: 30_000,
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## Integration notes
|
|
81
|
+
|
|
82
|
+
- Use with `@sisu-ai/mw-register-tools` to expose parent tool registry for child scoping.
|
|
83
|
+
- Child executions are compatible with `@sisu-ai/mw-tool-calling` style tool semantics.
|
|
84
|
+
- Usage rollup can consume metrics written by `@sisu-ai/mw-usage-tracker`.
|
|
85
|
+
- Traces can be viewed with `@sisu-ai/mw-trace-viewer` using parent-child run linkage in orchestration state.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { type Ctx, type LLM, type Middleware, type Usage } from "@sisu-ai/core";
|
|
2
|
+
export type DelegationStatus = "ok" | "error" | "cancelled" | "timeout";
|
|
3
|
+
export type DelegationContext = {
|
|
4
|
+
messages?: Array<{
|
|
5
|
+
role: "system" | "user" | "assistant" | "tool";
|
|
6
|
+
content: string;
|
|
7
|
+
}>;
|
|
8
|
+
memoryKeys?: string[];
|
|
9
|
+
artifacts?: Array<{
|
|
10
|
+
type: string;
|
|
11
|
+
value: string;
|
|
12
|
+
}>;
|
|
13
|
+
};
|
|
14
|
+
export type DelegationToolScope = {
|
|
15
|
+
allow: string[];
|
|
16
|
+
};
|
|
17
|
+
export type DelegationModelRef = {
|
|
18
|
+
name: string;
|
|
19
|
+
provider?: "openai" | "anthropic" | "ollama" | string;
|
|
20
|
+
opts?: Record<string, unknown>;
|
|
21
|
+
};
|
|
22
|
+
export type DelegateTaskInput = {
|
|
23
|
+
instruction: string;
|
|
24
|
+
context: DelegationContext;
|
|
25
|
+
tools: DelegationToolScope;
|
|
26
|
+
model?: DelegationModelRef;
|
|
27
|
+
metadata?: Record<string, unknown>;
|
|
28
|
+
};
|
|
29
|
+
export type DelegateTaskOptions = {
|
|
30
|
+
timeoutMs?: number;
|
|
31
|
+
maxChildTurns?: number;
|
|
32
|
+
idempotencyKey?: string;
|
|
33
|
+
};
|
|
34
|
+
export type ChildExecutionRequest = {
|
|
35
|
+
delegationId: string;
|
|
36
|
+
input: DelegateTaskInput;
|
|
37
|
+
options?: DelegateTaskOptions;
|
|
38
|
+
};
|
|
39
|
+
export interface DelegationResult {
|
|
40
|
+
delegationId: string;
|
|
41
|
+
status: DelegationStatus;
|
|
42
|
+
output?: {
|
|
43
|
+
summary: string;
|
|
44
|
+
answer?: string;
|
|
45
|
+
artifacts?: Array<{
|
|
46
|
+
type: string;
|
|
47
|
+
value: string;
|
|
48
|
+
}>;
|
|
49
|
+
citations?: string[];
|
|
50
|
+
};
|
|
51
|
+
telemetry: {
|
|
52
|
+
startedAt: string;
|
|
53
|
+
endedAt: string;
|
|
54
|
+
durationMs: number;
|
|
55
|
+
model: string;
|
|
56
|
+
toolsAllowed: string[];
|
|
57
|
+
toolsUsed: string[];
|
|
58
|
+
usage?: Usage;
|
|
59
|
+
};
|
|
60
|
+
trace: {
|
|
61
|
+
runId: string;
|
|
62
|
+
parentRunId: string;
|
|
63
|
+
file?: string;
|
|
64
|
+
};
|
|
65
|
+
error?: {
|
|
66
|
+
name: string;
|
|
67
|
+
message: string;
|
|
68
|
+
code?: string;
|
|
69
|
+
retryable?: boolean;
|
|
70
|
+
hint?: string;
|
|
71
|
+
details?: Record<string, unknown>;
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export type DelegationValidationResult = {
|
|
75
|
+
ok: true;
|
|
76
|
+
} | {
|
|
77
|
+
ok: false;
|
|
78
|
+
code: string;
|
|
79
|
+
message: string;
|
|
80
|
+
retryable?: boolean;
|
|
81
|
+
hint?: string;
|
|
82
|
+
details?: Record<string, unknown>;
|
|
83
|
+
};
|
|
84
|
+
export interface OrchestrationState {
|
|
85
|
+
version: 1;
|
|
86
|
+
runId: string;
|
|
87
|
+
depth: number;
|
|
88
|
+
maxDepth: number;
|
|
89
|
+
status: "running" | "finished" | "aborted" | "error";
|
|
90
|
+
steps: Array<{
|
|
91
|
+
stepId: string;
|
|
92
|
+
type: "delegate" | "finish";
|
|
93
|
+
startedAt: string;
|
|
94
|
+
endedAt?: string;
|
|
95
|
+
status: "ok" | "error" | "cancelled" | "timeout";
|
|
96
|
+
delegationId?: string;
|
|
97
|
+
}>;
|
|
98
|
+
children: Record<string, {
|
|
99
|
+
delegationId: string;
|
|
100
|
+
parentRunId: string;
|
|
101
|
+
instruction: string;
|
|
102
|
+
toolScope: string[];
|
|
103
|
+
model: string;
|
|
104
|
+
status: "running" | "ok" | "error" | "cancelled" | "timeout";
|
|
105
|
+
usage?: Usage;
|
|
106
|
+
trace?: {
|
|
107
|
+
runId: string;
|
|
108
|
+
file?: string;
|
|
109
|
+
};
|
|
110
|
+
error?: {
|
|
111
|
+
message: string;
|
|
112
|
+
code?: string;
|
|
113
|
+
retryable?: boolean;
|
|
114
|
+
hint?: string;
|
|
115
|
+
};
|
|
116
|
+
}>;
|
|
117
|
+
totals: {
|
|
118
|
+
delegations: number;
|
|
119
|
+
succeeded: number;
|
|
120
|
+
failed: number;
|
|
121
|
+
durationMs: number;
|
|
122
|
+
promptTokens?: number;
|
|
123
|
+
completionTokens?: number;
|
|
124
|
+
totalTokens?: number;
|
|
125
|
+
costUSD?: number;
|
|
126
|
+
};
|
|
127
|
+
policy: {
|
|
128
|
+
allowParallel: boolean;
|
|
129
|
+
defaultTimeoutMs: number;
|
|
130
|
+
allowedModels: string[];
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
export type ChildExecutor = (request: ChildExecutionRequest, parentCtx: Ctx) => Promise<DelegationResult>;
|
|
134
|
+
export interface OrchestrationOptions {
|
|
135
|
+
allowedModels?: string[];
|
|
136
|
+
maxDepth?: number;
|
|
137
|
+
maxDelegations?: number;
|
|
138
|
+
defaultTimeoutMs?: number;
|
|
139
|
+
maxChildTurns?: number;
|
|
140
|
+
maxCorrectionRetries?: number;
|
|
141
|
+
childExecutor?: ChildExecutor;
|
|
142
|
+
modelResolver?: (modelRef: DelegationModelRef, parentCtx: Ctx) => LLM;
|
|
143
|
+
normalizeDelegationInput?: (rawInput: unknown, ctx: Ctx) => unknown;
|
|
144
|
+
validateDelegation?: (input: DelegateTaskInput, ctx: Ctx) => DelegationValidationResult;
|
|
145
|
+
resolveToolScope?: (input: DelegateTaskInput, ctx: Ctx) => string[];
|
|
146
|
+
}
|
|
147
|
+
export declare const orchestration: (opts?: OrchestrationOptions) => Middleware;
|
|
148
|
+
export declare function createInlineChildExecutor(opts: {
|
|
149
|
+
defaultTimeoutMs: number;
|
|
150
|
+
maxChildTurns: number;
|
|
151
|
+
allowedModels: string[];
|
|
152
|
+
modelResolver?: (modelRef: DelegationModelRef, parentCtx: Ctx) => LLM;
|
|
153
|
+
}): ChildExecutor;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
import { randomUUID } from "crypto";
|
|
2
|
+
import { NullStream, SimpleTools, } from "@sisu-ai/core";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
const delegateTaskSchema = z.object({
|
|
5
|
+
instruction: z.string().min(1),
|
|
6
|
+
context: z
|
|
7
|
+
.object({
|
|
8
|
+
messages: z
|
|
9
|
+
.array(z.object({
|
|
10
|
+
role: z.enum(["system", "user", "assistant", "tool"]),
|
|
11
|
+
content: z.string(),
|
|
12
|
+
}))
|
|
13
|
+
.optional(),
|
|
14
|
+
memoryKeys: z.array(z.string()).optional(),
|
|
15
|
+
artifacts: z
|
|
16
|
+
.array(z.object({ type: z.string(), value: z.string() }))
|
|
17
|
+
.optional(),
|
|
18
|
+
})
|
|
19
|
+
.default({}),
|
|
20
|
+
tools: z.object({ allow: z.array(z.string()).min(1) }),
|
|
21
|
+
model: z.object({
|
|
22
|
+
name: z.string().min(1),
|
|
23
|
+
provider: z.string().optional(),
|
|
24
|
+
opts: z.record(z.string(), z.unknown()).optional(),
|
|
25
|
+
}).optional(),
|
|
26
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
27
|
+
});
|
|
28
|
+
const finishSchema = z.object({
|
|
29
|
+
answer: z.string().min(1),
|
|
30
|
+
confidence: z.number().min(0).max(1).optional(),
|
|
31
|
+
notes: z.string().optional(),
|
|
32
|
+
});
|
|
33
|
+
export const orchestration = (opts = {}) => {
|
|
34
|
+
const maxDepth = opts.maxDepth ?? 1;
|
|
35
|
+
const maxDelegations = opts.maxDelegations ?? 8;
|
|
36
|
+
const defaultTimeoutMs = opts.defaultTimeoutMs ?? 30_000;
|
|
37
|
+
const maxChildTurns = opts.maxChildTurns ?? 8;
|
|
38
|
+
const maxCorrectionRetries = opts.maxCorrectionRetries ?? 2;
|
|
39
|
+
return async (ctx, next) => {
|
|
40
|
+
await next();
|
|
41
|
+
const state = ensureState(ctx, {
|
|
42
|
+
maxDepth,
|
|
43
|
+
defaultTimeoutMs,
|
|
44
|
+
allowedModels: opts.allowedModels ?? [],
|
|
45
|
+
});
|
|
46
|
+
const runStartedAt = Date.now();
|
|
47
|
+
if (state.depth > state.maxDepth) {
|
|
48
|
+
throw new Error(`[orchestration] depth ${state.depth} exceeds maxDepth ${state.maxDepth}`);
|
|
49
|
+
}
|
|
50
|
+
const childExecutor = opts.childExecutor ??
|
|
51
|
+
createInlineChildExecutor({
|
|
52
|
+
defaultTimeoutMs,
|
|
53
|
+
maxChildTurns,
|
|
54
|
+
allowedModels: opts.allowedModels ?? [],
|
|
55
|
+
modelResolver: opts.modelResolver,
|
|
56
|
+
});
|
|
57
|
+
let delegations = 0;
|
|
58
|
+
let correctionRetries = 0;
|
|
59
|
+
while (!ctx.signal.aborted) {
|
|
60
|
+
if (delegations > maxDelegations) {
|
|
61
|
+
throw new Error(`[orchestration] max delegations reached (${maxDelegations})`);
|
|
62
|
+
}
|
|
63
|
+
const out = await ctx.model.generate(ctx.messages, {
|
|
64
|
+
signal: ctx.signal,
|
|
65
|
+
toolChoice: "auto",
|
|
66
|
+
tools: [delegateControlTool, finishControlTool],
|
|
67
|
+
parallelToolCalls: false,
|
|
68
|
+
});
|
|
69
|
+
const msg = out.message;
|
|
70
|
+
const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
|
|
71
|
+
if (calls.length === 0) {
|
|
72
|
+
ctx.messages.push(msg);
|
|
73
|
+
state.status = "finished";
|
|
74
|
+
state.totals.durationMs = Date.now() - runStartedAt;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
ctx.messages.push(msg);
|
|
78
|
+
for (const call of calls) {
|
|
79
|
+
if (call.name === "delegateTask") {
|
|
80
|
+
delegations += 1;
|
|
81
|
+
const stepId = randomUUID();
|
|
82
|
+
const stepStart = new Date().toISOString();
|
|
83
|
+
state.steps.push({
|
|
84
|
+
stepId,
|
|
85
|
+
type: "delegate",
|
|
86
|
+
startedAt: stepStart,
|
|
87
|
+
status: "ok",
|
|
88
|
+
delegationId: call.id,
|
|
89
|
+
});
|
|
90
|
+
ctx.log.info?.("[orchestration] delegate.start", {
|
|
91
|
+
stepId,
|
|
92
|
+
delegationId: call.id,
|
|
93
|
+
});
|
|
94
|
+
const result = await runDelegation(call, ctx, state, childExecutor, defaultTimeoutMs, maxChildTurns, opts);
|
|
95
|
+
const step = state.steps[state.steps.length - 1];
|
|
96
|
+
step.status = result.status;
|
|
97
|
+
step.endedAt = new Date().toISOString();
|
|
98
|
+
if (result.status === "ok") {
|
|
99
|
+
state.totals.succeeded += 1;
|
|
100
|
+
}
|
|
101
|
+
else {
|
|
102
|
+
state.totals.failed += 1;
|
|
103
|
+
}
|
|
104
|
+
state.totals.delegations += 1;
|
|
105
|
+
aggregateUsage(state, result.telemetry.usage);
|
|
106
|
+
state.children[result.delegationId] = {
|
|
107
|
+
delegationId: result.delegationId,
|
|
108
|
+
parentRunId: result.trace.parentRunId,
|
|
109
|
+
instruction: readInstructionFromArgs(call.arguments) ?? "delegated task",
|
|
110
|
+
toolScope: result.telemetry.toolsAllowed,
|
|
111
|
+
model: result.telemetry.model,
|
|
112
|
+
status: result.status,
|
|
113
|
+
usage: result.telemetry.usage,
|
|
114
|
+
trace: { runId: result.trace.runId, file: result.trace.file },
|
|
115
|
+
error: result.error
|
|
116
|
+
? {
|
|
117
|
+
message: result.error.message,
|
|
118
|
+
code: result.error.code,
|
|
119
|
+
retryable: result.error.retryable,
|
|
120
|
+
hint: result.error.hint,
|
|
121
|
+
}
|
|
122
|
+
: undefined,
|
|
123
|
+
};
|
|
124
|
+
if (result.status === "error" && result.error?.retryable) {
|
|
125
|
+
correctionRetries += 1;
|
|
126
|
+
if (correctionRetries > maxCorrectionRetries) {
|
|
127
|
+
throw new Error(`[orchestration] correction retries exceeded (${maxCorrectionRetries})`);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
else {
|
|
131
|
+
correctionRetries = 0;
|
|
132
|
+
}
|
|
133
|
+
ctx.log.info?.("[orchestration] delegate.result", {
|
|
134
|
+
stepId,
|
|
135
|
+
delegationId: result.delegationId,
|
|
136
|
+
status: result.status,
|
|
137
|
+
error: result.error?.message,
|
|
138
|
+
});
|
|
139
|
+
const toolMessage = {
|
|
140
|
+
role: "tool",
|
|
141
|
+
content: JSON.stringify(result),
|
|
142
|
+
...(call.id ? { tool_call_id: call.id } : { name: call.name }),
|
|
143
|
+
};
|
|
144
|
+
ctx.messages.push(toolMessage);
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (call.name === "finish") {
|
|
148
|
+
const parsed = finishSchema.parse(call.arguments);
|
|
149
|
+
const stepId = randomUUID();
|
|
150
|
+
state.steps.push({
|
|
151
|
+
stepId,
|
|
152
|
+
type: "finish",
|
|
153
|
+
startedAt: new Date().toISOString(),
|
|
154
|
+
endedAt: new Date().toISOString(),
|
|
155
|
+
status: "ok",
|
|
156
|
+
});
|
|
157
|
+
ctx.log.info?.("[orchestration] finish", {
|
|
158
|
+
stepId,
|
|
159
|
+
confidence: parsed.confidence,
|
|
160
|
+
});
|
|
161
|
+
ctx.messages.push({ role: "assistant", content: parsed.answer });
|
|
162
|
+
state.status = "finished";
|
|
163
|
+
state.totals.durationMs = Date.now() - runStartedAt;
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
throw new Error(`[orchestration] unsupported control tool call: ${call.name}`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
state.status = "aborted";
|
|
170
|
+
};
|
|
171
|
+
};
|
|
172
|
+
const delegateControlTool = {
|
|
173
|
+
name: "delegateTask",
|
|
174
|
+
description: "Delegate specialized execution with a 4-tuple: instruction, context, tools, model",
|
|
175
|
+
schema: delegateTaskSchema,
|
|
176
|
+
handler: async () => ({ ok: true }),
|
|
177
|
+
};
|
|
178
|
+
const finishControlTool = {
|
|
179
|
+
name: "finish",
|
|
180
|
+
description: "Finish orchestration and return final answer",
|
|
181
|
+
schema: finishSchema,
|
|
182
|
+
handler: async () => ({ ok: true }),
|
|
183
|
+
};
|
|
184
|
+
async function runDelegation(call, ctx, state, childExecutor, defaultTimeoutMs, maxChildTurns, opts) {
|
|
185
|
+
const delegationId = call.id || randomUUID();
|
|
186
|
+
const normalized = (opts.normalizeDelegationInput ?? normalizeDelegationInput)(call.arguments, ctx);
|
|
187
|
+
const parsed = delegateTaskSchema.safeParse(normalized);
|
|
188
|
+
if (!parsed.success) {
|
|
189
|
+
const issues = parsed.error.issues.map((issue) => ({
|
|
190
|
+
path: issue.path.join("."),
|
|
191
|
+
code: issue.code,
|
|
192
|
+
message: issue.message,
|
|
193
|
+
}));
|
|
194
|
+
return buildErrorResult(delegationId, state.runId, {
|
|
195
|
+
name: "DelegationValidationError",
|
|
196
|
+
code: "SCHEMA_INVALID",
|
|
197
|
+
message: parsed.error.message,
|
|
198
|
+
retryable: true,
|
|
199
|
+
hint: "Use delegateTask arguments as { instruction, context?: { messages?: [] }, tools: { allow: string[] }, model?: { name: string } }",
|
|
200
|
+
details: { issues },
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const input = parsed.data;
|
|
204
|
+
if (!input.model) {
|
|
205
|
+
input.model = { name: ctx.model.name };
|
|
206
|
+
}
|
|
207
|
+
input.tools.allow =
|
|
208
|
+
opts.resolveToolScope?.(input, ctx) ?? input.tools.allow;
|
|
209
|
+
const policy = opts.validateDelegation?.(input, ctx) ?? defaultValidateDelegation(input, ctx);
|
|
210
|
+
if (!policy.ok) {
|
|
211
|
+
return buildErrorResult(delegationId, state.runId, {
|
|
212
|
+
name: "DelegationPolicyError",
|
|
213
|
+
code: policy.code,
|
|
214
|
+
message: policy.message,
|
|
215
|
+
retryable: policy.retryable ?? true,
|
|
216
|
+
hint: policy.hint,
|
|
217
|
+
details: policy.details,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
const request = {
|
|
221
|
+
delegationId,
|
|
222
|
+
input,
|
|
223
|
+
options: {
|
|
224
|
+
timeoutMs: defaultTimeoutMs,
|
|
225
|
+
maxChildTurns,
|
|
226
|
+
},
|
|
227
|
+
};
|
|
228
|
+
try {
|
|
229
|
+
return await childExecutor(request, ctx);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
const err = error;
|
|
233
|
+
return buildErrorResult(delegationId, state.runId, {
|
|
234
|
+
name: err.name || "DelegationExecutionError",
|
|
235
|
+
code: "EXECUTOR_FAILED",
|
|
236
|
+
message: err.message,
|
|
237
|
+
retryable: false,
|
|
238
|
+
details: { model: input.model?.name, tools: input.tools.allow },
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
export function createInlineChildExecutor(opts) {
|
|
243
|
+
return async (request, parentCtx) => {
|
|
244
|
+
const startedAt = new Date();
|
|
245
|
+
const parentState = ensureState(parentCtx, {
|
|
246
|
+
maxDepth: 1,
|
|
247
|
+
defaultTimeoutMs: opts.defaultTimeoutMs,
|
|
248
|
+
allowedModels: opts.allowedModels,
|
|
249
|
+
});
|
|
250
|
+
const input = request.input;
|
|
251
|
+
validateScope(parentCtx, input, opts.allowedModels);
|
|
252
|
+
const modelRef = input.model ?? { name: parentCtx.model.name };
|
|
253
|
+
input.model = modelRef;
|
|
254
|
+
const model = opts.modelResolver?.(modelRef, parentCtx) ?? resolveModel(modelRef, parentCtx);
|
|
255
|
+
const childRunId = randomUUID();
|
|
256
|
+
const parentRunId = parentState.runId;
|
|
257
|
+
const timeoutMs = request.options?.timeoutMs ?? opts.defaultTimeoutMs;
|
|
258
|
+
const childSignal = withTimeoutSignal(parentCtx.signal, timeoutMs);
|
|
259
|
+
const childCtx = buildChildCtx(parentCtx, {
|
|
260
|
+
model,
|
|
261
|
+
signal: childSignal,
|
|
262
|
+
runId: childRunId,
|
|
263
|
+
parentRunId,
|
|
264
|
+
input,
|
|
265
|
+
});
|
|
266
|
+
const run = await executeChild(childCtx, request.options?.maxChildTurns ?? opts.maxChildTurns);
|
|
267
|
+
const endedAt = new Date();
|
|
268
|
+
const usage = getUsage(childCtx);
|
|
269
|
+
const durationMs = endedAt.getTime() - startedAt.getTime();
|
|
270
|
+
const abortReason = childSignal.aborted ? String(childSignal.reason ?? "") : "";
|
|
271
|
+
const status = childSignal.aborted
|
|
272
|
+
? abortReason.includes("timed out")
|
|
273
|
+
? "timeout"
|
|
274
|
+
: "cancelled"
|
|
275
|
+
: "ok";
|
|
276
|
+
return {
|
|
277
|
+
delegationId: request.delegationId,
|
|
278
|
+
status,
|
|
279
|
+
output: {
|
|
280
|
+
summary: run.summary,
|
|
281
|
+
answer: run.answer,
|
|
282
|
+
},
|
|
283
|
+
telemetry: {
|
|
284
|
+
startedAt: startedAt.toISOString(),
|
|
285
|
+
endedAt: endedAt.toISOString(),
|
|
286
|
+
durationMs,
|
|
287
|
+
model: model.name,
|
|
288
|
+
toolsAllowed: input.tools.allow,
|
|
289
|
+
toolsUsed: Array.from(run.toolsUsed),
|
|
290
|
+
usage,
|
|
291
|
+
},
|
|
292
|
+
trace: {
|
|
293
|
+
runId: childRunId,
|
|
294
|
+
parentRunId,
|
|
295
|
+
},
|
|
296
|
+
};
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function normalizeDelegationInput(rawInput, _ctx) {
|
|
300
|
+
if (!rawInput || typeof rawInput !== "object")
|
|
301
|
+
return rawInput;
|
|
302
|
+
const input = { ...rawInput };
|
|
303
|
+
if (!input.context || typeof input.context !== "object") {
|
|
304
|
+
input.context = {};
|
|
305
|
+
}
|
|
306
|
+
const tools = input.tools;
|
|
307
|
+
if (typeof tools === "string") {
|
|
308
|
+
input.tools = { allow: [tools] };
|
|
309
|
+
}
|
|
310
|
+
else if (Array.isArray(tools)) {
|
|
311
|
+
input.tools = {
|
|
312
|
+
allow: tools.filter((tool) => typeof tool === "string"),
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
else if (tools && typeof tools === "object") {
|
|
316
|
+
const scope = tools;
|
|
317
|
+
if (typeof scope.allow === "string") {
|
|
318
|
+
input.tools = { allow: [scope.allow] };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
if (typeof input.model === "string") {
|
|
322
|
+
input.model = { name: input.model };
|
|
323
|
+
}
|
|
324
|
+
return input;
|
|
325
|
+
}
|
|
326
|
+
function defaultValidateDelegation(input, ctx) {
|
|
327
|
+
if (!Array.isArray(input.tools.allow) || input.tools.allow.length === 0) {
|
|
328
|
+
return {
|
|
329
|
+
ok: false,
|
|
330
|
+
code: "TOOLS_INVALID",
|
|
331
|
+
message: "Delegation requires at least one allowed tool.",
|
|
332
|
+
retryable: true,
|
|
333
|
+
hint: "Set tools.allow to a non-empty string array.",
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
for (const toolName of input.tools.allow) {
|
|
337
|
+
if (!ctx.tools.get(toolName)) {
|
|
338
|
+
return {
|
|
339
|
+
ok: false,
|
|
340
|
+
code: "TOOLS_NOT_ALLOWED",
|
|
341
|
+
message: `Unknown tool '${toolName}' in delegation scope.`,
|
|
342
|
+
retryable: true,
|
|
343
|
+
hint: "Use only tools registered in the parent context.",
|
|
344
|
+
details: {
|
|
345
|
+
toolName,
|
|
346
|
+
availableTools: ctx.tools.list().map((tool) => tool.name),
|
|
347
|
+
},
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
return { ok: true };
|
|
352
|
+
}
|
|
353
|
+
function buildErrorResult(delegationId, parentRunId, error) {
|
|
354
|
+
return {
|
|
355
|
+
delegationId,
|
|
356
|
+
status: "error",
|
|
357
|
+
telemetry: {
|
|
358
|
+
startedAt: new Date().toISOString(),
|
|
359
|
+
endedAt: new Date().toISOString(),
|
|
360
|
+
durationMs: 0,
|
|
361
|
+
model: "unknown",
|
|
362
|
+
toolsAllowed: [],
|
|
363
|
+
toolsUsed: [],
|
|
364
|
+
},
|
|
365
|
+
trace: {
|
|
366
|
+
runId: randomUUID(),
|
|
367
|
+
parentRunId,
|
|
368
|
+
},
|
|
369
|
+
error,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function ensureState(ctx, defaults) {
|
|
373
|
+
const existing = ctx.state.orchestration;
|
|
374
|
+
if (existing)
|
|
375
|
+
return existing;
|
|
376
|
+
const state = {
|
|
377
|
+
version: 1,
|
|
378
|
+
runId: randomUUID(),
|
|
379
|
+
depth: 0,
|
|
380
|
+
maxDepth: defaults.maxDepth,
|
|
381
|
+
status: "running",
|
|
382
|
+
steps: [],
|
|
383
|
+
children: {},
|
|
384
|
+
totals: {
|
|
385
|
+
delegations: 0,
|
|
386
|
+
succeeded: 0,
|
|
387
|
+
failed: 0,
|
|
388
|
+
durationMs: 0,
|
|
389
|
+
promptTokens: 0,
|
|
390
|
+
completionTokens: 0,
|
|
391
|
+
totalTokens: 0,
|
|
392
|
+
costUSD: 0,
|
|
393
|
+
},
|
|
394
|
+
policy: {
|
|
395
|
+
allowParallel: false,
|
|
396
|
+
defaultTimeoutMs: defaults.defaultTimeoutMs,
|
|
397
|
+
allowedModels: defaults.allowedModels,
|
|
398
|
+
},
|
|
399
|
+
};
|
|
400
|
+
ctx.state.orchestration = state;
|
|
401
|
+
return state;
|
|
402
|
+
}
|
|
403
|
+
function validateScope(parentCtx, input, allowedModels) {
|
|
404
|
+
const modelName = input.model?.name ?? parentCtx.model.name;
|
|
405
|
+
if (allowedModels.length > 0 && !isModelAllowed(modelName, allowedModels)) {
|
|
406
|
+
throw new Error(`[orchestration] model '${modelName}' is not allowed`);
|
|
407
|
+
}
|
|
408
|
+
for (const toolName of input.tools.allow) {
|
|
409
|
+
if (!parentCtx.tools.get(toolName)) {
|
|
410
|
+
throw new Error(`[orchestration] unknown delegated tool '${toolName}'`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function resolveModel(modelRef, parentCtx) {
|
|
415
|
+
if (modelRef.name && parentCtx.model.name !== modelRef.name) {
|
|
416
|
+
throw new Error(`[orchestration] unable to resolve model '${modelRef.name}' without modelResolver`);
|
|
417
|
+
}
|
|
418
|
+
return parentCtx.model;
|
|
419
|
+
}
|
|
420
|
+
function buildChildCtx(parentCtx, opts) {
|
|
421
|
+
const tools = new SimpleTools();
|
|
422
|
+
for (const name of opts.input.tools.allow) {
|
|
423
|
+
const tool = parentCtx.tools.get(name);
|
|
424
|
+
if (tool)
|
|
425
|
+
tools.register(tool);
|
|
426
|
+
}
|
|
427
|
+
const baseMessages = (opts.input.context.messages ?? []).map((m) => ({ role: m.role, content: m.content }));
|
|
428
|
+
baseMessages.push({ role: "user", content: opts.input.instruction });
|
|
429
|
+
const childState = {
|
|
430
|
+
...parentCtx.state,
|
|
431
|
+
orchestration: {
|
|
432
|
+
...parentCtx.state.orchestration,
|
|
433
|
+
runId: opts.runId,
|
|
434
|
+
depth: Number(parentCtx.state.orchestration
|
|
435
|
+
?.depth ?? 0) + 1,
|
|
436
|
+
parentRunId: opts.parentRunId,
|
|
437
|
+
},
|
|
438
|
+
};
|
|
439
|
+
return {
|
|
440
|
+
input: opts.input.instruction,
|
|
441
|
+
messages: baseMessages,
|
|
442
|
+
model: opts.model,
|
|
443
|
+
tools,
|
|
444
|
+
memory: parentCtx.memory,
|
|
445
|
+
stream: new NullStream(),
|
|
446
|
+
state: childState,
|
|
447
|
+
signal: opts.signal,
|
|
448
|
+
log: parentCtx.log,
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
async function executeChild(childCtx, maxChildTurns) {
|
|
452
|
+
const toolsUsed = new Set();
|
|
453
|
+
for (let turn = 0; turn < maxChildTurns; turn++) {
|
|
454
|
+
if (childCtx.signal.aborted)
|
|
455
|
+
break;
|
|
456
|
+
const out = await childCtx.model.generate(childCtx.messages, {
|
|
457
|
+
signal: childCtx.signal,
|
|
458
|
+
toolChoice: "auto",
|
|
459
|
+
tools: childCtx.tools.list(),
|
|
460
|
+
parallelToolCalls: false,
|
|
461
|
+
});
|
|
462
|
+
const msg = out.message;
|
|
463
|
+
const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
|
|
464
|
+
if (calls.length === 0) {
|
|
465
|
+
childCtx.messages.push(msg);
|
|
466
|
+
const answer = typeof msg.content === "string" ? msg.content : "";
|
|
467
|
+
return { answer, summary: answer.slice(0, 400), toolsUsed };
|
|
468
|
+
}
|
|
469
|
+
childCtx.messages.push(msg);
|
|
470
|
+
for (const call of calls) {
|
|
471
|
+
const tool = childCtx.tools.get(call.name);
|
|
472
|
+
if (!tool) {
|
|
473
|
+
throw new Error(`[orchestration] child unknown tool '${call.name}'`);
|
|
474
|
+
}
|
|
475
|
+
toolsUsed.add(call.name);
|
|
476
|
+
const parsedArgs = tool.schema && hasParse(tool.schema)
|
|
477
|
+
? tool.schema.parse(call.arguments)
|
|
478
|
+
: call.arguments;
|
|
479
|
+
const toolCtx = {
|
|
480
|
+
memory: childCtx.memory,
|
|
481
|
+
signal: childCtx.signal,
|
|
482
|
+
log: childCtx.log,
|
|
483
|
+
model: childCtx.model,
|
|
484
|
+
deps: childCtx.state.toolDeps,
|
|
485
|
+
};
|
|
486
|
+
const result = await tool.handler(parsedArgs, toolCtx);
|
|
487
|
+
const toolMessage = {
|
|
488
|
+
role: "tool",
|
|
489
|
+
content: JSON.stringify(result),
|
|
490
|
+
...(call.id ? { tool_call_id: call.id } : { name: call.name }),
|
|
491
|
+
};
|
|
492
|
+
childCtx.messages.push(toolMessage);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
const answer = "";
|
|
496
|
+
return { answer, summary: answer, toolsUsed };
|
|
497
|
+
}
|
|
498
|
+
function hasParse(value) {
|
|
499
|
+
return Boolean(value &&
|
|
500
|
+
typeof value === "object" &&
|
|
501
|
+
"parse" in value &&
|
|
502
|
+
typeof value.parse === "function");
|
|
503
|
+
}
|
|
504
|
+
function getUsage(ctx) {
|
|
505
|
+
const usage = ctx.state.usage;
|
|
506
|
+
if (!usage)
|
|
507
|
+
return undefined;
|
|
508
|
+
return {
|
|
509
|
+
promptTokens: usage.promptTokens,
|
|
510
|
+
completionTokens: usage.completionTokens,
|
|
511
|
+
totalTokens: usage.totalTokens,
|
|
512
|
+
costUSD: usage.costUSD,
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
function aggregateUsage(state, usage) {
|
|
516
|
+
if (!usage)
|
|
517
|
+
return;
|
|
518
|
+
state.totals.promptTokens =
|
|
519
|
+
Number(state.totals.promptTokens ?? 0) + Number(usage.promptTokens ?? 0);
|
|
520
|
+
state.totals.completionTokens =
|
|
521
|
+
Number(state.totals.completionTokens ?? 0) +
|
|
522
|
+
Number(usage.completionTokens ?? 0);
|
|
523
|
+
state.totals.totalTokens =
|
|
524
|
+
Number(state.totals.totalTokens ?? 0) + Number(usage.totalTokens ?? 0);
|
|
525
|
+
state.totals.costUSD =
|
|
526
|
+
Number(state.totals.costUSD ?? 0) + Number(usage.costUSD ?? 0);
|
|
527
|
+
}
|
|
528
|
+
function withTimeoutSignal(signal, timeoutMs) {
|
|
529
|
+
if (timeoutMs <= 0)
|
|
530
|
+
return signal;
|
|
531
|
+
const ac = new AbortController();
|
|
532
|
+
const onParentAbort = () => ac.abort(signal.reason);
|
|
533
|
+
signal.addEventListener("abort", onParentAbort, { once: true });
|
|
534
|
+
const timer = setTimeout(() => {
|
|
535
|
+
ac.abort(new Error("Delegation timed out"));
|
|
536
|
+
}, timeoutMs);
|
|
537
|
+
ac.signal.addEventListener("abort", () => {
|
|
538
|
+
clearTimeout(timer);
|
|
539
|
+
signal.removeEventListener("abort", onParentAbort);
|
|
540
|
+
}, { once: true });
|
|
541
|
+
if (signal.aborted)
|
|
542
|
+
ac.abort(signal.reason);
|
|
543
|
+
return ac.signal;
|
|
544
|
+
}
|
|
545
|
+
function readInstructionFromArgs(args) {
|
|
546
|
+
if (!args || typeof args !== "object")
|
|
547
|
+
return undefined;
|
|
548
|
+
const instruction = args.instruction;
|
|
549
|
+
return typeof instruction === "string" ? instruction : undefined;
|
|
550
|
+
}
|
|
551
|
+
function isModelAllowed(modelName, allowedModels) {
|
|
552
|
+
if (allowedModels.includes(modelName))
|
|
553
|
+
return true;
|
|
554
|
+
const normalizedRequested = normalizeModelName(modelName);
|
|
555
|
+
return allowedModels.some((allowed) => {
|
|
556
|
+
if (allowed === modelName)
|
|
557
|
+
return true;
|
|
558
|
+
const normalizedAllowed = normalizeModelName(allowed);
|
|
559
|
+
return normalizedAllowed === normalizedRequested;
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
function normalizeModelName(modelName) {
|
|
563
|
+
const trimmed = modelName.trim();
|
|
564
|
+
if (!trimmed)
|
|
565
|
+
return trimmed;
|
|
566
|
+
const slashIdx = trimmed.lastIndexOf("/");
|
|
567
|
+
const colonIdx = trimmed.lastIndexOf(":");
|
|
568
|
+
const splitIdx = Math.max(slashIdx, colonIdx);
|
|
569
|
+
if (splitIdx >= 0 && splitIdx < trimmed.length - 1) {
|
|
570
|
+
return trimmed.slice(splitIdx + 1);
|
|
571
|
+
}
|
|
572
|
+
return trimmed;
|
|
573
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sisu-ai/mw-orchestration",
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "https://github.com/finger-gun/sisu",
|
|
17
|
+
"directory": "packages/middleware/orchestration"
|
|
18
|
+
},
|
|
19
|
+
"homepage": "https://github.com/finger-gun/sisu#readme",
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/finger-gun/sisu/issues"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"zod": "^3.23.8"
|
|
25
|
+
},
|
|
26
|
+
"peerDependencies": {
|
|
27
|
+
"@sisu-ai/core": "2.3.1"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^24.3.1",
|
|
31
|
+
"vitest": "^3.2.4",
|
|
32
|
+
"@sisu-ai/core": "2.3.1"
|
|
33
|
+
},
|
|
34
|
+
"keywords": [
|
|
35
|
+
"sisu",
|
|
36
|
+
"ai",
|
|
37
|
+
"ai-agent",
|
|
38
|
+
"agentic",
|
|
39
|
+
"middleware",
|
|
40
|
+
"orchestration"
|
|
41
|
+
],
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "tsc -b",
|
|
44
|
+
"clean": "rm -rf dist",
|
|
45
|
+
"lint": "eslint src --ext .ts,.js",
|
|
46
|
+
"lint:fix": "eslint src --ext .ts,.js --fix",
|
|
47
|
+
"typecheck": "tsc --noEmit"
|
|
48
|
+
}
|
|
49
|
+
}
|