@msm-core/mini 0.5.2 → 0.9.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/dist/adapters/index.d.ts +4 -0
- package/dist/adapters/index.js +2 -0
- package/dist/adapters/memory-store.d.ts +38 -0
- package/dist/adapters/memory-store.js +73 -0
- package/dist/adapters/redis-memory.d.ts +13 -8
- package/dist/adapters/redis-memory.js +5 -0
- package/dist/brain/anthropic.js +50 -17
- package/dist/brain/gemini.js +50 -17
- package/dist/brain/ollama.js +68 -19
- package/dist/brain/openai.js +57 -23
- package/dist/brain/streaming.d.ts +315 -0
- package/dist/brain/streaming.js +439 -0
- package/dist/brain/tool-context.d.ts +50 -2
- package/dist/brain/tool-context.js +88 -0
- package/dist/bridge/pipeline.js +11 -8
- package/dist/core/context-builder.d.ts +11 -0
- package/dist/core/context-builder.js +11 -1
- package/dist/core/hooks.d.ts +10 -0
- package/dist/core/hooks.js +14 -0
- package/dist/core/loop.d.ts +43 -1
- package/dist/core/loop.js +749 -98
- package/dist/core/types.d.ts +261 -1
- package/dist/core/types.js +40 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +4 -0
- package/dist/tools/delegate.d.ts +134 -0
- package/dist/tools/delegate.js +223 -0
- package/package.json +11 -11
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delegation — one agent asks another, as an ORDINARY TOOL (ر٢).
|
|
3
|
+
*
|
|
4
|
+
* ── Why a tool and not a loop action ────────────────────────────────────────
|
|
5
|
+
*
|
|
6
|
+
* `BrainOrchestration.action` used to carry a fifth member for routing work to
|
|
7
|
+
* another agent. It was declared at the beginning, dispatched on by nothing,
|
|
8
|
+
* and used by nobody — measured, not assumed: zero occurrences in the live
|
|
9
|
+
* consumer. Meanwhile that same consumer HAS been delegating in production for
|
|
10
|
+
* months, and it does it the other way round: a `call_agent` tool over an
|
|
11
|
+
* injected handle. The measurement settled the design argument, so the action
|
|
12
|
+
* was buried (`core/types.ts`) and this is the thing that replaces it.
|
|
13
|
+
*
|
|
14
|
+
* The consequence is the point of the whole exercise: **there is not one line
|
|
15
|
+
* of loop code here.** A delegation is a tool call, so it already goes through
|
|
16
|
+
* the parameter validation, the `onBeforeTool` approval gate, the dedup cache,
|
|
17
|
+
* the control-bus disable, the per-call `tool_call`/`tool_result` pair in the
|
|
18
|
+
* session log, the tool-call budget and the consecutive-failure counter —
|
|
19
|
+
* every one of them, for free, because it is not special. An action in the loop
|
|
20
|
+
* would have had to re-earn each of those, one `if` at a time, in the file
|
|
21
|
+
* every agent rides on.
|
|
22
|
+
*
|
|
23
|
+
* ── What this improves on the lifted original ───────────────────────────────
|
|
24
|
+
*
|
|
25
|
+
* Three things, each of them a rule this repo already pays for elsewhere:
|
|
26
|
+
*
|
|
27
|
+
* 1. **The child's session id is DERIVED, not random.** `parent.d.child`,
|
|
28
|
+
* built from the parent's own id. The original minted a fresh UUID per
|
|
29
|
+
* delegation, which is exactly the thing س٥ named the enemy of replay: an
|
|
30
|
+
* arbitrary identifier kills every comparison that crosses a run — a tape
|
|
31
|
+
* fingerprint, a golden log, a diff of two sessions that should be
|
|
32
|
+
* identical. Derived, the same delegation twice is the same id twice, the
|
|
33
|
+
* log reads `s-42.d.researcher` and says what it is, and the depth is
|
|
34
|
+
* legible in the id instead of held in a side channel.
|
|
35
|
+
*
|
|
36
|
+
* 2. **The agent name is an `enum`, so the model cannot invent one.** The
|
|
37
|
+
* brains forward `enum` into the provider schema (`toolParamsToJsonSchema`),
|
|
38
|
+
* so this is a real constraint at the provider and not a hint. It is still
|
|
39
|
+
* checked at execution — `validateParams` enforces presence and type, never
|
|
40
|
+
* membership — and an unknown name is a NAMED failure the model can read
|
|
41
|
+
* and correct, not a crash.
|
|
42
|
+
*
|
|
43
|
+
* 3. **The cost is visible.** The original returned the child's text and threw
|
|
44
|
+
* the rest away, so a delegating agent's real spend was invisible to
|
|
45
|
+
* everything that watched it. `totalCostUsd` rides back in the result.
|
|
46
|
+
*
|
|
47
|
+
* ── What is deliberately NOT here ───────────────────────────────────────────
|
|
48
|
+
*
|
|
49
|
+
* • **The child's cost is not added to the parent's `totalCostUsd`.** It is
|
|
50
|
+
* reported and left there. Both agents run their own budgets, and a number
|
|
51
|
+
* counted in two places is worse than a number counted in one: it would
|
|
52
|
+
* make the parent's cost cap fire on spend the child already paid for, and
|
|
53
|
+
* the pair would then disagree about what the run cost. Raised for
|
|
54
|
+
* management, not decided here.
|
|
55
|
+
*
|
|
56
|
+
* • **No parent context is forwarded.** The child gets the message and its
|
|
57
|
+
* tenant, and assembles its own persona, memories and tools. Handing it the
|
|
58
|
+
* parent's `AgentContext` would make it a continuation of the parent rather
|
|
59
|
+
* than a second agent — and `ToolMeta` does not carry one anyway.
|
|
60
|
+
*/
|
|
61
|
+
/**
|
|
62
|
+
* The tool's name, exported because consumers dispatch on it.
|
|
63
|
+
*
|
|
64
|
+
* An approval hook, an audit trail or a UI badge all need to recognise a
|
|
65
|
+
* delegation by name, and a hand-typed string in each of them is the drift س١
|
|
66
|
+
* was paid for. It is `call_agent` and not something new so that the consumer
|
|
67
|
+
* already running this pattern in production can swap its hand-rolled tool for
|
|
68
|
+
* this factory without changing a prompt, a manifest, or an approval rule.
|
|
69
|
+
*/
|
|
70
|
+
export const DELEGATE_TOOL_NAME = "call_agent";
|
|
71
|
+
/**
|
|
72
|
+
* The marker that makes a delegated session id readable and countable.
|
|
73
|
+
*
|
|
74
|
+
* `parent.d.child` — one segment per hop, so the depth is `.d.` counted. It is
|
|
75
|
+
* `.d.` and not a bare `.` because a session id may legitimately contain dots,
|
|
76
|
+
* and a separator that ordinary ids collide with would count hops that never
|
|
77
|
+
* happened.
|
|
78
|
+
*/
|
|
79
|
+
const DEPTH_MARKER = ".d.";
|
|
80
|
+
/** Delegation hops already taken to reach this session. A plain session is 0. */
|
|
81
|
+
function delegationDepth(sessionId) {
|
|
82
|
+
return sessionId.split(DEPTH_MARKER).length - 1;
|
|
83
|
+
}
|
|
84
|
+
/** The child's session id: derived from the parent's, one hop deeper. */
|
|
85
|
+
function childSessionId(parentSessionId, agentName) {
|
|
86
|
+
return `${parentSessionId}${DEPTH_MARKER}${agentName}`;
|
|
87
|
+
}
|
|
88
|
+
/** `maxDepth`, coerced. Non-finite or negative garbage falls back to the default. */
|
|
89
|
+
function resolveMaxDepth(value) {
|
|
90
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0)
|
|
91
|
+
return 1;
|
|
92
|
+
return Math.floor(value);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Build the delegation tool for a set of named agents.
|
|
96
|
+
*
|
|
97
|
+
* ```ts
|
|
98
|
+
* const agent = createAgent({
|
|
99
|
+
* definition, brain, redis,
|
|
100
|
+
* tools: [searchTool, createDelegateTool({ researcher, drafter })],
|
|
101
|
+
* });
|
|
102
|
+
* ```
|
|
103
|
+
*
|
|
104
|
+
* The delegates are `mini` agents themselves — whatever `createAgent` returned,
|
|
105
|
+
* or anything else satisfying `Agent`. Nothing is constructed here and no
|
|
106
|
+
* connection is opened: this is a port like every other in the package, handed
|
|
107
|
+
* in at composition time.
|
|
108
|
+
*
|
|
109
|
+
* @param delegates agents this tool may call, by the name the model will use.
|
|
110
|
+
* @param opts depth cap and the approval/metadata stamp.
|
|
111
|
+
*/
|
|
112
|
+
export function createDelegateTool(delegates, opts = {}) {
|
|
113
|
+
const names = Object.keys(delegates);
|
|
114
|
+
const maxDepth = resolveMaxDepth(opts.maxDepth);
|
|
115
|
+
const fail = (error) => ({
|
|
116
|
+
tool: DELEGATE_TOOL_NAME,
|
|
117
|
+
status: "failed",
|
|
118
|
+
error,
|
|
119
|
+
});
|
|
120
|
+
return {
|
|
121
|
+
name: DELEGATE_TOOL_NAME,
|
|
122
|
+
description: `Hand a subtask to another agent and get its answer back. ` +
|
|
123
|
+
`Available agents: ${names.join(", ") || "(none)"}.`,
|
|
124
|
+
parameters: {
|
|
125
|
+
agent: {
|
|
126
|
+
type: "string",
|
|
127
|
+
description: `Which agent to ask. One of: ${names.join(", ") || "(none)"}.`,
|
|
128
|
+
required: true,
|
|
129
|
+
// The list the provider itself enforces. It is also re-checked below:
|
|
130
|
+
// `validateParams` checks presence and type, never membership.
|
|
131
|
+
enum: names,
|
|
132
|
+
},
|
|
133
|
+
message: {
|
|
134
|
+
type: "string",
|
|
135
|
+
description: "The task to hand over, stated in full — the other agent sees none of this conversation.",
|
|
136
|
+
required: true,
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
...(opts.requiresApproval !== undefined
|
|
140
|
+
? { requiresApproval: opts.requiresApproval }
|
|
141
|
+
: {}),
|
|
142
|
+
...(opts.destructive !== undefined ? { destructive: opts.destructive } : {}),
|
|
143
|
+
...(opts.category !== undefined ? { category: opts.category } : {}),
|
|
144
|
+
async execute(args, meta) {
|
|
145
|
+
const agentName = String(args["agent"] ?? "");
|
|
146
|
+
const message = String(args["message"] ?? "");
|
|
147
|
+
// ── The depth cap, and it fails CLOSED ───────────────────────────────
|
|
148
|
+
//
|
|
149
|
+
// Checked before the name is even resolved, because the cheapest place to
|
|
150
|
+
// stop a runaway recursion is before it can name its next victim. The
|
|
151
|
+
// answer is a named `failed` result and not a thrown exception: a throw
|
|
152
|
+
// ends the step, while a result is something the model reads, understands
|
|
153
|
+
// and can act on — the same reasoning that makes an MCP `isError` a
|
|
154
|
+
// failed result rather than a throw.
|
|
155
|
+
//
|
|
156
|
+
// Two ways the count can read HIGH — an app whose own session ids contain
|
|
157
|
+
// `.d.`, or a delegate registered under a name containing it — and both
|
|
158
|
+
// err toward refusing to delegate. There is no input that makes it read
|
|
159
|
+
// low, which is the only direction that would matter.
|
|
160
|
+
const depth = delegationDepth(meta.sessionId);
|
|
161
|
+
if (depth >= maxDepth) {
|
|
162
|
+
return fail(`delegation depth exceeded: "${meta.sessionId}" is already ${depth} ` +
|
|
163
|
+
`hop(s) deep and maxDepth is ${maxDepth}`);
|
|
164
|
+
}
|
|
165
|
+
// ── The name, re-checked here and not only in the schema ─────────────
|
|
166
|
+
const child = Object.prototype.hasOwnProperty.call(delegates, agentName)
|
|
167
|
+
? delegates[agentName]
|
|
168
|
+
: undefined;
|
|
169
|
+
if (!child) {
|
|
170
|
+
return fail(`unknown agent "${agentName}" — available: ${names.join(", ") || "(none)"}`);
|
|
171
|
+
}
|
|
172
|
+
const sessionId = childSessionId(meta.sessionId, agentName);
|
|
173
|
+
// ── The child's event ────────────────────────────────────────────────
|
|
174
|
+
//
|
|
175
|
+
// The tenant rides across unchanged. "Whoever injects a store injects its
|
|
176
|
+
// isolation with it" (س١'s ruling) has a corollary here: a delegation
|
|
177
|
+
// that dropped the tenant would run the child UNSCOPED — writing to the
|
|
178
|
+
// bare prefix — and the isolation covenant would be broken by a tool
|
|
179
|
+
// rather than by a store. It is passed through exactly as received; this
|
|
180
|
+
// tool neither invents a tenant nor widens one.
|
|
181
|
+
const childEvent = {
|
|
182
|
+
sessionId,
|
|
183
|
+
message,
|
|
184
|
+
...(meta.tenantContext ? { tenantContext: meta.tenantContext } : {}),
|
|
185
|
+
};
|
|
186
|
+
try {
|
|
187
|
+
const outcome = await child.handle(childEvent);
|
|
188
|
+
// `error` is the only outcome type that is a FAILURE of the delegation.
|
|
189
|
+
// `clarify`, `escalate` and a suppressed answer are all things the child
|
|
190
|
+
// successfully decided, and the model needs to see which one it got —
|
|
191
|
+
// hence `outcome` in the payload rather than a flattened string.
|
|
192
|
+
const failed = outcome.type === "error";
|
|
193
|
+
const result = {
|
|
194
|
+
agent: agentName,
|
|
195
|
+
sessionId,
|
|
196
|
+
outcome: outcome.type,
|
|
197
|
+
text: outcome.text ?? "",
|
|
198
|
+
// Reported, never folded into the parent's total. See the header.
|
|
199
|
+
totalCostUsd: outcome.metrics.totalCostUsd,
|
|
200
|
+
};
|
|
201
|
+
return {
|
|
202
|
+
tool: DELEGATE_TOOL_NAME,
|
|
203
|
+
status: failed ? "failed" : "ok",
|
|
204
|
+
result,
|
|
205
|
+
...(failed
|
|
206
|
+
? {
|
|
207
|
+
error: outcome.error ??
|
|
208
|
+
outcome.text ??
|
|
209
|
+
`agent "${agentName}" failed`,
|
|
210
|
+
}
|
|
211
|
+
: {}),
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
catch (err) {
|
|
215
|
+
// `handle` does its own catching and normally returns an error outcome
|
|
216
|
+
// rather than throwing — but it can still throw before its try block
|
|
217
|
+
// (resolving Redis, acquiring the session lock). One agent failing to
|
|
218
|
+
// start is this tool's failure, not the parent step's.
|
|
219
|
+
return fail(`agent "${agentName}" threw: ${err instanceof Error ? err.message : String(err)}`);
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
};
|
|
223
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@msm-core/mini",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Portable AI agent execution loop — brain-agnostic, zero embedded databases",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -31,13 +31,6 @@
|
|
|
31
31
|
"publishConfig": {
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
|
-
"scripts": {
|
|
35
|
-
"build": "tsc",
|
|
36
|
-
"test": "vitest run",
|
|
37
|
-
"test:watch": "vitest",
|
|
38
|
-
"clean": "rm -rf dist",
|
|
39
|
-
"prepublishOnly": "npm run build && npm test"
|
|
40
|
-
},
|
|
41
34
|
"peerDependencies": {
|
|
42
35
|
"openai": ">=4.0.0",
|
|
43
36
|
"@anthropic-ai/sdk": ">=0.20.0",
|
|
@@ -55,7 +48,8 @@
|
|
|
55
48
|
}
|
|
56
49
|
},
|
|
57
50
|
"dependencies": {
|
|
58
|
-
"ioredis": "^5.3.2"
|
|
51
|
+
"ioredis": "^5.3.2",
|
|
52
|
+
"@msm-core/session": "^0.2.0"
|
|
59
53
|
},
|
|
60
54
|
"devDependencies": {
|
|
61
55
|
"@types/node": "^20.0.0",
|
|
@@ -71,5 +65,11 @@
|
|
|
71
65
|
"portable"
|
|
72
66
|
],
|
|
73
67
|
"author": "Emad Jumaah",
|
|
74
|
-
"license": "UNLICENSED"
|
|
75
|
-
|
|
68
|
+
"license": "UNLICENSED",
|
|
69
|
+
"scripts": {
|
|
70
|
+
"build": "tsc",
|
|
71
|
+
"test": "vitest run",
|
|
72
|
+
"test:watch": "vitest",
|
|
73
|
+
"clean": "rm -rf dist"
|
|
74
|
+
}
|
|
75
|
+
}
|