@looprun-ai/mastra 0.1.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 +202 -0
- package/dist/agent.d.ts +100 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +348 -0
- package/dist/agent.js.map +1 -0
- package/dist/compile.d.ts +28 -0
- package/dist/compile.d.ts.map +1 -0
- package/dist/compile.js +66 -0
- package/dist/compile.js.map +1 -0
- package/dist/hooks.d.ts +21 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +49 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/json-schema-zod.d.ts +7 -0
- package/dist/json-schema-zod.d.ts.map +1 -0
- package/dist/json-schema-zod.js +37 -0
- package/dist/json-schema-zod.js.map +1 -0
- package/dist/run-conversation.d.ts +21 -0
- package/dist/run-conversation.d.ts.map +1 -0
- package/dist/run-conversation.js +181 -0
- package/dist/run-conversation.js.map +1 -0
- package/dist/session.d.ts +23 -0
- package/dist/session.d.ts.map +1 -0
- package/dist/session.js +53 -0
- package/dist/session.js.map +1 -0
- package/dist/tools.d.ts +8 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +67 -0
- package/dist/tools.js.map +1 -0
- package/dist/world-adapters.d.ts +24 -0
- package/dist/world-adapters.d.ts.map +1 -0
- package/dist/world-adapters.js +24 -0
- package/dist/world-adapters.js.map +1 -0
- package/package.json +60 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/dist/agent.d.ts
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { Agent } from '@mastra/core/agent';
|
|
2
|
+
import type { AgentSpec, AgentWorld, ObservedCall, ToolDef, TrunkTheme } from '@looprun-ai/core';
|
|
3
|
+
import type { LoopRunSession, WorldFactory } from './session.js';
|
|
4
|
+
import type { StateView } from './world-adapters.js';
|
|
5
|
+
export interface LoopRunAgentConfig<W extends AgentWorld = AgentWorld> {
|
|
6
|
+
/** The governed AgentSpec (id/persona/tools/guards/controls/behavior). */
|
|
7
|
+
spec: AgentSpec;
|
|
8
|
+
/** Domain theme override; defaults to `spec.theme`. */
|
|
9
|
+
theme?: TrunkTheme;
|
|
10
|
+
/**
|
|
11
|
+
* The world seam — a deterministic instance (single conversation) or a factory
|
|
12
|
+
* `(sessionId) => world` for multi-session hosts. Omit it in native-tools mode (`tools`).
|
|
13
|
+
*/
|
|
14
|
+
world?: W | WorldFactory<W>;
|
|
15
|
+
/**
|
|
16
|
+
* NATIVE-TOOLS mode (Path B, incl. MCP): pass Mastra tools (e.g. `await mcp.getTools()`).
|
|
17
|
+
* They execute themselves; guards still enforce through the agent hooks. Mutually exclusive
|
|
18
|
+
* with `world`+`toolDefs`. Stateful guards + theme.stateBlock read `stateView`.
|
|
19
|
+
*/
|
|
20
|
+
tools?: Record<string, any>;
|
|
21
|
+
/** Domain state reads for native-tools mode (see world-adapters.ts). */
|
|
22
|
+
stateView?: StateView;
|
|
23
|
+
/** Tool defs (JSON-schema) executed via `world.exec` — the certified path. */
|
|
24
|
+
toolDefs?: ToolDef[];
|
|
25
|
+
/** Mastra model router string ('openai/gpt-5.5') or an AI-SDK model object. */
|
|
26
|
+
model: any;
|
|
27
|
+
/** Options spread into every internal generate (providerOptions / modelSettings / …). */
|
|
28
|
+
modelParams?: Record<string, unknown>;
|
|
29
|
+
/** The certified turn shape (terminal tools + toolChoice:'required'). Default true. */
|
|
30
|
+
terminalProtocol?: boolean;
|
|
31
|
+
maxSteps?: number;
|
|
32
|
+
redrives?: number;
|
|
33
|
+
/** Throw on validateSpec warnings instead of console.warn. */
|
|
34
|
+
strict?: boolean;
|
|
35
|
+
/** Agent id/name override; defaults to the spec id. */
|
|
36
|
+
id?: string;
|
|
37
|
+
name?: string;
|
|
38
|
+
/** Any further @mastra/core Agent option (memory, description, processors, …) passes through. */
|
|
39
|
+
[agentOption: string]: any;
|
|
40
|
+
}
|
|
41
|
+
export interface LoopRunResultMeta {
|
|
42
|
+
sessionId: string;
|
|
43
|
+
turnIndex: number;
|
|
44
|
+
/** Guard activity this turn: veto kinds, 'forced-terminal', 'redrive:*', 'exhaustion-terminal'. */
|
|
45
|
+
corrections: string[];
|
|
46
|
+
exhausted: boolean;
|
|
47
|
+
violations: string[];
|
|
48
|
+
/** This turn's slice of the observed ledger. */
|
|
49
|
+
observed: ObservedCall[];
|
|
50
|
+
}
|
|
51
|
+
export interface LoopRunOptions {
|
|
52
|
+
loopRun?: {
|
|
53
|
+
/** Conversation key; defaults to the memory thread id, else 'default'. */
|
|
54
|
+
sessionId?: string;
|
|
55
|
+
/** Attachment URLs ingested into the world this turn. */
|
|
56
|
+
attachments?: string[];
|
|
57
|
+
};
|
|
58
|
+
[generateOption: string]: any;
|
|
59
|
+
}
|
|
60
|
+
export declare class LoopRunAgent<W extends AgentWorld = AgentWorld> extends Agent {
|
|
61
|
+
readonly spec: AgentSpec;
|
|
62
|
+
readonly theme?: TrunkTheme;
|
|
63
|
+
readonly terminalProtocolOn: boolean;
|
|
64
|
+
private readonly sessions;
|
|
65
|
+
private readonly nativeToolsMode;
|
|
66
|
+
private readonly nativeToolNames;
|
|
67
|
+
private readonly surface;
|
|
68
|
+
private readonly modelParams;
|
|
69
|
+
private readonly maxStepsResolved;
|
|
70
|
+
private readonly redrivesResolved;
|
|
71
|
+
private readonly guardHooks;
|
|
72
|
+
private readonly inputProcessorsResolved;
|
|
73
|
+
/** Per-turn session context: tools/hooks resolve the CURRENT turn's session through this —
|
|
74
|
+
* AsyncLocalStorage, so concurrent turns on different sessions can never cross-execute. */
|
|
75
|
+
private readonly turnContext;
|
|
76
|
+
private readonly renderPrompt;
|
|
77
|
+
constructor(config: LoopRunAgentConfig<W>);
|
|
78
|
+
/** Read a session's state (world/ledger/turnIndex) — hosts and tests. */
|
|
79
|
+
getSession(id?: string): LoopRunSession<W>;
|
|
80
|
+
/** Dispose a conversation's state. */
|
|
81
|
+
endSession(id?: string): void;
|
|
82
|
+
private resolveSessionId;
|
|
83
|
+
/**
|
|
84
|
+
* One governed turn. Pass the user's message as a string (recommended); the volatile world
|
|
85
|
+
* state rides the message tail, the reply comes back as the result's `.text` with `.looprun`
|
|
86
|
+
* metadata attached.
|
|
87
|
+
*/
|
|
88
|
+
generate(messages: any, options?: LoopRunOptions): Promise<any>;
|
|
89
|
+
private governedTurn;
|
|
90
|
+
/**
|
|
91
|
+
* Streaming: tool-level governance (guard hooks + terminal protocol + activeTools + per-turn
|
|
92
|
+
* instructions). Reply finalization (mutators/redrive/exhaustion) needs generate() — with the
|
|
93
|
+
* terminal protocol ON the user text arrives via the terminal tool call, so nothing ungoverned
|
|
94
|
+
* streams as text.
|
|
95
|
+
*/
|
|
96
|
+
stream(messages: any, options?: LoopRunOptions): Promise<any>;
|
|
97
|
+
}
|
|
98
|
+
/** Factory form (composition-friendly alias of `new LoopRunAgent(config)`). */
|
|
99
|
+
export declare function createLoopRunAgent<W extends AgentWorld = AgentWorld>(config: LoopRunAgentConfig<W>): LoopRunAgent<W>;
|
|
100
|
+
//# sourceMappingURL=agent.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agent.d.ts","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"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"}
|
package/dist/agent.js
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @looprun-ai/mastra — LoopRunAgent: a GENUINE @mastra/core Agent compiled from an AgentSpec.
|
|
3
|
+
*
|
|
4
|
+
* DX mirrors `new Agent({...})`:
|
|
5
|
+
*
|
|
6
|
+
* export const booksAgent = new LoopRunAgent({
|
|
7
|
+
* spec: bookkeepingSpec, // carries its domain theme reference
|
|
8
|
+
* world, // instance (single conversation) or factory (sessionId) => world
|
|
9
|
+
* model: 'openai/gpt-5.5', // Mastra router string OR AI-SDK model object
|
|
10
|
+
* })
|
|
11
|
+
*
|
|
12
|
+
* Because it IS an Agent, it registers in a Mastra instance and shows up in Mastra Studio with
|
|
13
|
+
* the guards enforcing live (agent-level hooks apply to every tool source, including MCP).
|
|
14
|
+
*
|
|
15
|
+
* Governance per turn (generate): session resolve → advanceTurn + ledger reset → byte-stable
|
|
16
|
+
* trunk (+ terminal protocol) as per-call `instructions` → volatile state on the USER-message
|
|
17
|
+
* tail → generate with toolChoice:'required' + stopWhen(terminalCalled) → forced-terminal
|
|
18
|
+
* fallback → mutators → onReply checks with bounded NO-TOOLS redrive (never a processor
|
|
19
|
+
* abort/retry — that re-runs side-effecting tools, measured ~100× slower) → deterministic
|
|
20
|
+
* honest-abstain closure. The result's `.text` is the governed reply; `.looprun` carries the meta.
|
|
21
|
+
*
|
|
22
|
+
* stream(): tool-level governance only (guard hooks + terminal protocol + activeTools). Reply
|
|
23
|
+
* finalization (mutators/redrive/exhaustion) requires generate() — documented degraded mode.
|
|
24
|
+
*/
|
|
25
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
26
|
+
import { stepCountIs } from 'ai';
|
|
27
|
+
import { Agent } from '@mastra/core/agent';
|
|
28
|
+
import { beginTurn, finalizeReply, forcedTerminalPrompt, isTerminal, renderScopedSpecTrunk, terminalProtocol, validateSpec, } from '@looprun-ai/core';
|
|
29
|
+
import { SessionStore } from './session.js';
|
|
30
|
+
import { buildWorldTools, buildTerminalTools } from './tools.js';
|
|
31
|
+
import { makeGuardHooks, makeInputProcessors } from './hooks.js';
|
|
32
|
+
import { worldFromTools } from './world-adapters.js';
|
|
33
|
+
import { DEFAULT_MAX_STEPS, DEFAULT_REDRIVES } from './run-conversation.js';
|
|
34
|
+
const LOOPRUN_KEYS = new Set([
|
|
35
|
+
'spec', 'theme', 'world', 'tools', 'stateView', 'toolDefs', 'model', 'modelParams',
|
|
36
|
+
'terminalProtocol', 'maxSteps', 'redrives', 'strict', 'id', 'name',
|
|
37
|
+
]);
|
|
38
|
+
export class LoopRunAgent extends Agent {
|
|
39
|
+
spec;
|
|
40
|
+
theme;
|
|
41
|
+
terminalProtocolOn;
|
|
42
|
+
sessions;
|
|
43
|
+
nativeToolsMode;
|
|
44
|
+
nativeToolNames;
|
|
45
|
+
surface;
|
|
46
|
+
modelParams;
|
|
47
|
+
maxStepsResolved;
|
|
48
|
+
redrivesResolved;
|
|
49
|
+
guardHooks;
|
|
50
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
51
|
+
inputProcessorsResolved;
|
|
52
|
+
/** Per-turn session context: tools/hooks resolve the CURRENT turn's session through this —
|
|
53
|
+
* AsyncLocalStorage, so concurrent turns on different sessions can never cross-execute. */
|
|
54
|
+
turnContext = new AsyncLocalStorage();
|
|
55
|
+
renderPrompt;
|
|
56
|
+
constructor(config) {
|
|
57
|
+
const { spec } = config;
|
|
58
|
+
const theme = config.theme ?? spec.theme;
|
|
59
|
+
if (!theme && !spec.surface.systemPrompt) {
|
|
60
|
+
throw new Error(`LoopRunAgent "${spec.id}": no theme — pass config.theme or set spec.theme.`);
|
|
61
|
+
}
|
|
62
|
+
if (config.tools && (config.world || config.toolDefs)) {
|
|
63
|
+
throw new Error(`LoopRunAgent "${spec.id}": pass EITHER native tools (tools[+stateView]) OR world+toolDefs — not both.`);
|
|
64
|
+
}
|
|
65
|
+
if (!config.tools && !config.world) {
|
|
66
|
+
throw new Error(`LoopRunAgent "${spec.id}": a world (or native tools) is required.`);
|
|
67
|
+
}
|
|
68
|
+
const warnings = validateSpec(spec);
|
|
69
|
+
if (warnings.length) {
|
|
70
|
+
if (config.strict)
|
|
71
|
+
throw new Error(`LoopRunAgent "${spec.id}": ${warnings.map((w) => w.message).join(' | ')}`);
|
|
72
|
+
for (const w of warnings)
|
|
73
|
+
console.warn(`[looprun] ${w.message}`);
|
|
74
|
+
}
|
|
75
|
+
const nativeToolsMode = !!config.tools;
|
|
76
|
+
const world = nativeToolsMode
|
|
77
|
+
? worldFromTools({ stateView: config.stateView })
|
|
78
|
+
: config.world;
|
|
79
|
+
const sessions = new SessionStore(world);
|
|
80
|
+
const getSession = () => {
|
|
81
|
+
const s = this.turnContext.getStore();
|
|
82
|
+
if (!s)
|
|
83
|
+
throw new Error('looprun: tool executed outside a governed turn');
|
|
84
|
+
return s;
|
|
85
|
+
};
|
|
86
|
+
const surface = new Set(spec.surface.tools);
|
|
87
|
+
const guardHooks = makeGuardHooks(spec, getSession);
|
|
88
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
89
|
+
let tools;
|
|
90
|
+
if (nativeToolsMode) {
|
|
91
|
+
tools = { ...config.tools, ...buildTerminalTools(getSession) };
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
tools = buildWorldTools(config.toolDefs ?? [], surface, getSession);
|
|
95
|
+
}
|
|
96
|
+
// Static default instructions (Studio/introspection); each governed turn passes the exact
|
|
97
|
+
// per-turn variant via the per-execution `instructions` override.
|
|
98
|
+
const staticWorld = {
|
|
99
|
+
exec: () => ({}), advanceTurn: () => { }, ingestAttachment: (u) => u, toolCalls: [], sseActions: [],
|
|
100
|
+
};
|
|
101
|
+
const renderPrompt = spec.surface.systemPrompt
|
|
102
|
+
? (w, u) => spec.surface.systemPrompt(w, u)
|
|
103
|
+
: (w, u) => renderScopedSpecTrunk(w, spec, u, theme);
|
|
104
|
+
const terminalOn = config.terminalProtocol !== false;
|
|
105
|
+
const staticInstructions = renderPrompt(staticWorld, []) + (terminalOn ? terminalProtocol(false) : '');
|
|
106
|
+
// Pass through any further Agent option (memory, description, processors, …).
|
|
107
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
108
|
+
const passthrough = {};
|
|
109
|
+
for (const [k, v] of Object.entries(config))
|
|
110
|
+
if (!LOOPRUN_KEYS.has(k))
|
|
111
|
+
passthrough[k] = v;
|
|
112
|
+
super({
|
|
113
|
+
id: config.id ?? spec.id,
|
|
114
|
+
name: config.name ?? config.id ?? spec.id,
|
|
115
|
+
instructions: staticInstructions,
|
|
116
|
+
model: config.model,
|
|
117
|
+
tools,
|
|
118
|
+
// Agent-level hooks: defense in depth — guards enforce on EVERY execution path (Studio
|
|
119
|
+
// stream included), not only through the governed generate() below.
|
|
120
|
+
hooks: guardHooks,
|
|
121
|
+
...passthrough,
|
|
122
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
123
|
+
});
|
|
124
|
+
this.spec = spec;
|
|
125
|
+
this.theme = theme;
|
|
126
|
+
this.terminalProtocolOn = terminalOn;
|
|
127
|
+
this.sessions = sessions;
|
|
128
|
+
this.nativeToolsMode = nativeToolsMode;
|
|
129
|
+
this.nativeToolNames = Object.keys(config.tools ?? {});
|
|
130
|
+
this.surface = surface;
|
|
131
|
+
this.modelParams = config.modelParams ?? {};
|
|
132
|
+
this.maxStepsResolved = spec.controls.maxSteps ?? config.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
133
|
+
this.redrivesResolved = spec.controls.redrives ?? config.redrives ?? DEFAULT_REDRIVES;
|
|
134
|
+
this.guardHooks = guardHooks;
|
|
135
|
+
this.inputProcessorsResolved = makeInputProcessors(spec, getSession);
|
|
136
|
+
this.renderPrompt = renderPrompt;
|
|
137
|
+
}
|
|
138
|
+
/** Read a session's state (world/ledger/turnIndex) — hosts and tests. */
|
|
139
|
+
getSession(id = 'default') {
|
|
140
|
+
return this.sessions.get(id);
|
|
141
|
+
}
|
|
142
|
+
/** Dispose a conversation's state. */
|
|
143
|
+
endSession(id = 'default') {
|
|
144
|
+
this.sessions.end(id);
|
|
145
|
+
}
|
|
146
|
+
resolveSessionId(options) {
|
|
147
|
+
const explicit = options?.loopRun?.sessionId;
|
|
148
|
+
if (explicit)
|
|
149
|
+
return explicit;
|
|
150
|
+
const thread = options?.memory?.thread;
|
|
151
|
+
if (typeof thread === 'string')
|
|
152
|
+
return thread;
|
|
153
|
+
if (thread && typeof thread === 'object' && thread.id)
|
|
154
|
+
return String(thread.id);
|
|
155
|
+
return 'default';
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* One governed turn. Pass the user's message as a string (recommended); the volatile world
|
|
159
|
+
* state rides the message tail, the reply comes back as the result's `.text` with `.looprun`
|
|
160
|
+
* metadata attached.
|
|
161
|
+
*/
|
|
162
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
163
|
+
async generate(messages, options) {
|
|
164
|
+
const session = this.sessions.get(this.resolveSessionId(options));
|
|
165
|
+
return this.sessions.run(session, () => this.turnContext.run(session, () => this.governedTurn(session, messages, options)));
|
|
166
|
+
}
|
|
167
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
168
|
+
async governedTurn(session, input, options) {
|
|
169
|
+
const { spec, theme } = this;
|
|
170
|
+
const { world, ledger } = session;
|
|
171
|
+
const useMemory = !!options?.memory;
|
|
172
|
+
if (session.turnIndex > 0)
|
|
173
|
+
world.advanceTurn();
|
|
174
|
+
beginTurn(ledger, session.turnIndex);
|
|
175
|
+
const attUrls = options?.loopRun?.attachments ?? [];
|
|
176
|
+
const attLabels = attUrls.map((u) => world.ingestAttachment(u));
|
|
177
|
+
ledger.attachments = attLabels;
|
|
178
|
+
const attDisplay = attLabels.map((l, k) => {
|
|
179
|
+
const base = attUrls[k]?.split('/').pop();
|
|
180
|
+
return base ? `${l} (${base})` : l;
|
|
181
|
+
});
|
|
182
|
+
const userText = typeof input === 'string' ? input : null;
|
|
183
|
+
if (userText === null && !Array.isArray(input)) {
|
|
184
|
+
throw new Error('LoopRunAgent.generate: pass the user message as a string (or a messages array).');
|
|
185
|
+
}
|
|
186
|
+
const replyOnly = spec.controls.terminal ? spec.controls.terminal(world) === true : false;
|
|
187
|
+
const activeTools = this.nativeToolsMode
|
|
188
|
+
? [...this.nativeToolNames, ...(replyOnly ? ['replyToUser'] : ['replyToUser', 'askUser'])]
|
|
189
|
+
: (replyOnly ? [...this.surface, 'replyToUser'] : [...this.surface, 'replyToUser', 'askUser']);
|
|
190
|
+
const instructions = this.renderPrompt(world, attLabels) + (this.terminalProtocolOn ? terminalProtocol(replyOnly) : '');
|
|
191
|
+
// State-in-tail: volatile state + uploads ride the user message, after the stable prefix.
|
|
192
|
+
const stateBlock = theme ? theme.stateBlock(world) : '';
|
|
193
|
+
const tailParts = [];
|
|
194
|
+
if (stateBlock && stateBlock.trim())
|
|
195
|
+
tailParts.push(`## Account state\n${stateBlock}`);
|
|
196
|
+
if (attLabels.length)
|
|
197
|
+
tailParts.push(`[Uploads this turn: ${attDisplay.join(', ')}]`);
|
|
198
|
+
if (userText !== null)
|
|
199
|
+
tailParts.push(userText);
|
|
200
|
+
const userContent = tailParts.join('\n\n');
|
|
201
|
+
// Conversation history: Mastra memory owns it when configured; otherwise the session keeps it.
|
|
202
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
203
|
+
let msgs;
|
|
204
|
+
if (userText !== null) {
|
|
205
|
+
if (useMemory) {
|
|
206
|
+
msgs = userContent;
|
|
207
|
+
}
|
|
208
|
+
else {
|
|
209
|
+
session.messages.push({ role: 'user', content: userContent });
|
|
210
|
+
msgs = session.messages;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else {
|
|
214
|
+
msgs = input; // caller-managed messages array — used as-is
|
|
215
|
+
}
|
|
216
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
217
|
+
const passOpts = {};
|
|
218
|
+
for (const [k, v] of Object.entries(options ?? {}))
|
|
219
|
+
if (k !== 'loopRun')
|
|
220
|
+
passOpts[k] = v;
|
|
221
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
222
|
+
const terminalCalled = ({ steps }) => {
|
|
223
|
+
const last = steps?.[steps.length - 1];
|
|
224
|
+
for (const tc of (last?.toolCalls ?? []))
|
|
225
|
+
if (isTerminal(tc.toolName ?? tc.name ?? ''))
|
|
226
|
+
return true;
|
|
227
|
+
return false;
|
|
228
|
+
};
|
|
229
|
+
const protocolOpts = this.terminalProtocolOn
|
|
230
|
+
? { toolChoice: 'required', stopWhen: [stepCountIs(this.maxStepsResolved), terminalCalled] }
|
|
231
|
+
: { stopWhen: [stepCountIs(this.maxStepsResolved)] };
|
|
232
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
233
|
+
const full = await Agent.prototype.generate.call(this, msgs, {
|
|
234
|
+
instructions,
|
|
235
|
+
activeTools,
|
|
236
|
+
...protocolOpts,
|
|
237
|
+
hooks: this.guardHooks,
|
|
238
|
+
...(this.inputProcessorsResolved ? { inputProcessors: this.inputProcessorsResolved } : {}),
|
|
239
|
+
...this.modelParams,
|
|
240
|
+
...passOpts,
|
|
241
|
+
});
|
|
242
|
+
if (!useMemory && userText !== null && full.response?.messages)
|
|
243
|
+
session.messages.push(...full.response.messages);
|
|
244
|
+
// Forced-terminal fallback (terminal protocol only).
|
|
245
|
+
if (this.terminalProtocolOn && !ledger.terminalReply.trim()) {
|
|
246
|
+
const fbTools = replyOnly ? ['replyToUser'] : ['replyToUser', 'askUser'];
|
|
247
|
+
const fbMsgs = useMemory || userText === null
|
|
248
|
+
? forcedTerminalPrompt(replyOnly)
|
|
249
|
+
: [...session.messages, { role: 'user', content: forcedTerminalPrompt(replyOnly) }];
|
|
250
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
251
|
+
const fb = await Agent.prototype.generate.call(this, fbMsgs, {
|
|
252
|
+
instructions,
|
|
253
|
+
activeTools: fbTools,
|
|
254
|
+
toolChoice: 'required',
|
|
255
|
+
stopWhen: [stepCountIs(2), terminalCalled],
|
|
256
|
+
hooks: this.guardHooks,
|
|
257
|
+
...this.modelParams,
|
|
258
|
+
...(useMemory ? { memory: passOpts.memory } : {}),
|
|
259
|
+
});
|
|
260
|
+
if (!useMemory && userText !== null && fb.response?.messages)
|
|
261
|
+
session.messages.push(...fb.response.messages);
|
|
262
|
+
ledger.turnCorrections.push('forced-terminal');
|
|
263
|
+
}
|
|
264
|
+
// The terminal reply wins even with the protocol OFF — the terminal tools stay registered, and
|
|
265
|
+
// a model that used one produced a real answer that `full.text` won't carry.
|
|
266
|
+
const initialText = full?.tripwire
|
|
267
|
+
? String(full.tripwireReason ?? full.reason ?? '')
|
|
268
|
+
: (ledger.terminalReply || full.text || '');
|
|
269
|
+
const finalized = await finalizeReply(spec, theme, world, ledger, initialText, async (message) => {
|
|
270
|
+
const reMsgs = useMemory || userText === null
|
|
271
|
+
? message
|
|
272
|
+
: [...session.messages, { role: 'user', content: message }];
|
|
273
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
274
|
+
const re = await Agent.prototype.generate.call(this, reMsgs, {
|
|
275
|
+
instructions,
|
|
276
|
+
toolChoice: 'none',
|
|
277
|
+
activeTools: [],
|
|
278
|
+
...this.modelParams,
|
|
279
|
+
...(useMemory ? { memory: passOpts.memory } : {}),
|
|
280
|
+
});
|
|
281
|
+
// Candidates are NOT persisted here — a rejected draft must never enter the history.
|
|
282
|
+
return re.text ?? '';
|
|
283
|
+
}, this.redrivesResolved);
|
|
284
|
+
// History reconciliation: when the pipeline changed the outgoing text (mutator / redrive /
|
|
285
|
+
// exhaustion), append the reply the user ACTUALLY received — the model must never see a draft
|
|
286
|
+
// it "said" but the user never got.
|
|
287
|
+
if (!useMemory && userText !== null && finalized.text && finalized.text !== initialText) {
|
|
288
|
+
session.messages.push({ role: 'assistant', content: finalized.text });
|
|
289
|
+
}
|
|
290
|
+
const meta = {
|
|
291
|
+
sessionId: session.id,
|
|
292
|
+
turnIndex: session.turnIndex,
|
|
293
|
+
corrections: ledger.turnCorrections.slice(),
|
|
294
|
+
exhausted: finalized.exhausted,
|
|
295
|
+
violations: finalized.violations,
|
|
296
|
+
observed: ledger.observed.filter((o) => o.turnIndex === session.turnIndex),
|
|
297
|
+
};
|
|
298
|
+
session.turnIndex += 1;
|
|
299
|
+
// Return the LAST Mastra result object with the governed text + looprun meta attached.
|
|
300
|
+
full.text = finalized.text;
|
|
301
|
+
full.looprun = meta;
|
|
302
|
+
return full;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Streaming: tool-level governance (guard hooks + terminal protocol + activeTools + per-turn
|
|
306
|
+
* instructions). Reply finalization (mutators/redrive/exhaustion) needs generate() — with the
|
|
307
|
+
* terminal protocol ON the user text arrives via the terminal tool call, so nothing ungoverned
|
|
308
|
+
* streams as text.
|
|
309
|
+
*/
|
|
310
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
311
|
+
async stream(messages, options) {
|
|
312
|
+
const session = this.sessions.get(this.resolveSessionId(options));
|
|
313
|
+
// The whole stream (including tool executions that happen while the consumer iterates) runs
|
|
314
|
+
// inside the session's AsyncLocalStorage context — no shared mutable pointer, no cross-session
|
|
315
|
+
// execution.
|
|
316
|
+
return this.turnContext.run(session, async () => {
|
|
317
|
+
const { world, ledger } = session;
|
|
318
|
+
if (session.turnIndex > 0)
|
|
319
|
+
world.advanceTurn();
|
|
320
|
+
beginTurn(ledger, session.turnIndex);
|
|
321
|
+
session.turnIndex += 1;
|
|
322
|
+
const replyOnly = this.spec.controls.terminal ? this.spec.controls.terminal(world) === true : false;
|
|
323
|
+
const instructions = this.renderPrompt(world, []) + (this.terminalProtocolOn ? terminalProtocol(replyOnly) : '');
|
|
324
|
+
const activeTools = this.nativeToolsMode
|
|
325
|
+
? undefined
|
|
326
|
+
: (replyOnly ? [...this.surface, 'replyToUser'] : [...this.surface, 'replyToUser', 'askUser']);
|
|
327
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
328
|
+
const passOpts = {};
|
|
329
|
+
for (const [k, v] of Object.entries(options ?? {}))
|
|
330
|
+
if (k !== 'loopRun')
|
|
331
|
+
passOpts[k] = v;
|
|
332
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
333
|
+
return Agent.prototype.stream.call(this, messages, {
|
|
334
|
+
instructions,
|
|
335
|
+
...(activeTools ? { activeTools } : {}),
|
|
336
|
+
hooks: this.guardHooks,
|
|
337
|
+
...(this.inputProcessorsResolved ? { inputProcessors: this.inputProcessorsResolved } : {}),
|
|
338
|
+
...this.modelParams,
|
|
339
|
+
...passOpts,
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
/** Factory form (composition-friendly alias of `new LoopRunAgent(config)`). */
|
|
345
|
+
export function createLoopRunAgent(config) {
|
|
346
|
+
return new LoopRunAgent(config);
|
|
347
|
+
}
|
|
348
|
+
//# sourceMappingURL=agent.js.map
|