managed-deepagents 0.10.2-dev.20 → 0.10.2-dev.21
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/cached-agent.d.ts +68 -0
- package/dist/cached-agent.d.ts.map +1 -0
- package/dist/cached-agent.js +74 -0
- package/dist/cached-agent.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/memory/instructions-middleware.d.ts.map +1 -1
- package/dist/memory/instructions-middleware.js +24 -3
- package/dist/memory/instructions-middleware.js.map +1 -1
- package/dist/runtime/backend.d.ts.map +1 -1
- package/dist/runtime/backend.js +14 -7
- package/dist/runtime/backend.js.map +1 -1
- package/dist/runtime/cached-graphs.d.ts +69 -0
- package/dist/runtime/cached-graphs.d.ts.map +1 -0
- package/dist/runtime/cached-graphs.js +192 -0
- package/dist/runtime/cached-graphs.js.map +1 -0
- package/dist/runtime/graph-build-timing.d.ts +5 -0
- package/dist/runtime/graph-build-timing.d.ts.map +1 -1
- package/dist/runtime/graph-build-timing.js +13 -4
- package/dist/runtime/graph-build-timing.js.map +1 -1
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +167 -44
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/memory/user-memory.d.ts +3 -2
- package/dist/runtime/memory/user-memory.d.ts.map +1 -1
- package/dist/runtime/memory/user-memory.js +22 -5
- package/dist/runtime/memory/user-memory.js.map +1 -1
- package/dist/runtime/run-input.d.ts +1 -1
- package/dist/runtime/run-input.d.ts.map +1 -1
- package/dist/runtime/run-input.js +17 -4
- package/dist/runtime/run-input.js.map +1 -1
- package/dist/runtime/run-local.d.ts +34 -0
- package/dist/runtime/run-local.d.ts.map +1 -0
- package/dist/runtime/run-local.js +79 -0
- package/dist/runtime/run-local.js.map +1 -0
- package/dist/runtime/run-scoped-backend.d.ts +33 -0
- package/dist/runtime/run-scoped-backend.d.ts.map +1 -0
- package/dist/runtime/run-scoped-backend.js +65 -0
- package/dist/runtime/run-scoped-backend.js.map +1 -0
- package/dist/runtime/sandbox-manager.d.ts +2 -0
- package/dist/runtime/sandbox-manager.d.ts.map +1 -1
- package/dist/runtime/sandbox-manager.js +4 -0
- package/dist/runtime/sandbox-manager.js.map +1 -1
- package/package.json +7 -7
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { defineDeepAgent } from "../define-deep-agent.js";
|
|
2
|
+
import { assertDynamicMemorySelection } from "../managed-composition.js";
|
|
3
|
+
import { cachedAgentParts } from "../cached-agent.js";
|
|
4
|
+
// Maximum entries in each of the definition and graph caches, per process. When
|
|
5
|
+
// full, the least recently used entry is dropped.
|
|
6
|
+
export const CACHED_GRAPHS_KEPT = 32;
|
|
7
|
+
/** A least-recently-used map: reading or writing a key makes it the newest. */
|
|
8
|
+
class LruMap {
|
|
9
|
+
entries = new Map();
|
|
10
|
+
get(key) {
|
|
11
|
+
const value = this.entries.get(key);
|
|
12
|
+
if (value !== undefined) {
|
|
13
|
+
this.entries.delete(key);
|
|
14
|
+
this.entries.set(key, value);
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
set(key, value) {
|
|
19
|
+
this.entries.delete(key);
|
|
20
|
+
this.entries.set(key, value);
|
|
21
|
+
while (this.entries.size > CACHED_GRAPHS_KEPT) {
|
|
22
|
+
const oldest = this.entries.keys().next().value;
|
|
23
|
+
this.entries.delete(oldest);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
clear() {
|
|
27
|
+
this.entries.clear();
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
// Each cached agent gets its own definition cache, keyed by params digest. A
|
|
31
|
+
// WeakMap lets an agent's definitions go away with the agent.
|
|
32
|
+
const definitions = new WeakMap();
|
|
33
|
+
// Compiled graphs, keyed by entry, graph role, params digest and compile options.
|
|
34
|
+
// Only static definitions' and cached agents' graphs are cached. Their definitions
|
|
35
|
+
// don't depend on the run, so they hold nothing specific to one run, thread or caller.
|
|
36
|
+
const graphs = new LruMap();
|
|
37
|
+
/**
|
|
38
|
+
* Return the definition and params digest for this access of a cached agent.
|
|
39
|
+
*
|
|
40
|
+
* Calls the agent's `keyedBy` every time, and its `build` only on a cache miss.
|
|
41
|
+
* `build` only sees its params, so the same params always produce the same
|
|
42
|
+
* definition, and `build` runs once per key.
|
|
43
|
+
*/
|
|
44
|
+
export async function resolveCachedDefinition(entry, runtime) {
|
|
45
|
+
const parts = cachedAgentParts(entry);
|
|
46
|
+
if (!parts) {
|
|
47
|
+
throw new TypeError("agent export is not a cached agent");
|
|
48
|
+
}
|
|
49
|
+
let resolved;
|
|
50
|
+
try {
|
|
51
|
+
resolved = await parts.resolve(runtime);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
throw new Error("agent factory failed");
|
|
55
|
+
}
|
|
56
|
+
let kept = definitions.get(entry);
|
|
57
|
+
if (!kept) {
|
|
58
|
+
kept = new LruMap();
|
|
59
|
+
definitions.set(entry, kept);
|
|
60
|
+
}
|
|
61
|
+
let definition = kept.get(resolved.digest);
|
|
62
|
+
if (!definition) {
|
|
63
|
+
let selected;
|
|
64
|
+
try {
|
|
65
|
+
selected = parts.build(resolved);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
throw new Error("agent factory failed");
|
|
69
|
+
}
|
|
70
|
+
if (selected?.kind !== "deep-agent" ||
|
|
71
|
+
typeof selected.config !== "object") {
|
|
72
|
+
throw new TypeError("agent factory must return defineDeepAgent(...)");
|
|
73
|
+
}
|
|
74
|
+
// Reapply authoring validation, as for any factory's result, and take a fresh
|
|
75
|
+
// snapshot so later mutation cannot alter the cached definition.
|
|
76
|
+
try {
|
|
77
|
+
definition = defineDeepAgent(selected.config);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
throw new TypeError("agent factory returned an invalid definition");
|
|
81
|
+
}
|
|
82
|
+
if (definition.config.memory !== undefined &&
|
|
83
|
+
definition.config.memory !== null) {
|
|
84
|
+
assertDynamicMemorySelection(definition.config.memory);
|
|
85
|
+
}
|
|
86
|
+
kept.set(resolved.digest, definition);
|
|
87
|
+
}
|
|
88
|
+
return { definition, digest: resolved.digest };
|
|
89
|
+
}
|
|
90
|
+
// A number per object, so graph keys can name the entry and options they were
|
|
91
|
+
// compiled from. WeakMap, so an entry that goes away takes its number with it.
|
|
92
|
+
const objectIds = new WeakMap();
|
|
93
|
+
let nextObjectId = 0;
|
|
94
|
+
function objectId(value) {
|
|
95
|
+
let id = objectIds.get(value);
|
|
96
|
+
if (id === undefined) {
|
|
97
|
+
id = nextObjectId++;
|
|
98
|
+
objectIds.set(value, id);
|
|
99
|
+
}
|
|
100
|
+
return id;
|
|
101
|
+
}
|
|
102
|
+
/** A key part: strings, numbers, booleans and nullish by value, objects by identity. */
|
|
103
|
+
function identityPart(value) {
|
|
104
|
+
if (value === null || value === undefined)
|
|
105
|
+
return null;
|
|
106
|
+
if (Array.isArray(value))
|
|
107
|
+
return value.map(identityPart);
|
|
108
|
+
if (typeof value === "object" || typeof value === "function") {
|
|
109
|
+
return { id: objectId(value) };
|
|
110
|
+
}
|
|
111
|
+
return value;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Cache key for a static definition's or cached agent's compiled graph.
|
|
115
|
+
*
|
|
116
|
+
* - `entry`: the definition or cached agent itself, so two entries with equal params
|
|
117
|
+
* (or none) never share a graph.
|
|
118
|
+
* - `graph`: which graph is being built, "lead" or "subagent:<name>". One entry
|
|
119
|
+
* can produce several graphs, so the params alone aren't enough.
|
|
120
|
+
* - `digest`: the SHA-256 digest of the cached agent's params JSON (a constant for a
|
|
121
|
+
* static definition).
|
|
122
|
+
* - `options`: the compile options, each compared by identity. The generated entry
|
|
123
|
+
* passes the same declarations on every access; other in-process callers may
|
|
124
|
+
* not, and must not share a graph.
|
|
125
|
+
*/
|
|
126
|
+
export function cachedGraphKey(entry, graph, digest, options) {
|
|
127
|
+
const optionParts = Object.entries(options ?? {})
|
|
128
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
129
|
+
.map(([name, value]) => [name, identityPart(value)]);
|
|
130
|
+
return JSON.stringify([objectId(entry), graph, digest, optionParts]);
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Return the cached graph for `key`, or undefined on a miss.
|
|
134
|
+
*
|
|
135
|
+
* A read (`policy` undefined) accepts any cached graph. A run only accepts one
|
|
136
|
+
* compiled with the same memory access `policy`.
|
|
137
|
+
*/
|
|
138
|
+
export function cachedGraph(key, policy) {
|
|
139
|
+
const built = graphs.get(key);
|
|
140
|
+
if (!built)
|
|
141
|
+
return undefined;
|
|
142
|
+
if (policy && !samePolicy(built.policy, policy))
|
|
143
|
+
return undefined;
|
|
144
|
+
return built;
|
|
145
|
+
}
|
|
146
|
+
export function keepCachedGraph(key, built) {
|
|
147
|
+
// Don't let a read's graph replace a cached one: a run's graph serves both runs
|
|
148
|
+
// and reads, while a read's graph can't serve runs.
|
|
149
|
+
if (!built.policy && graphs.get(key))
|
|
150
|
+
return;
|
|
151
|
+
graphs.set(key, built);
|
|
152
|
+
}
|
|
153
|
+
function samePolicy(kept, wanted) {
|
|
154
|
+
return (kept !== undefined &&
|
|
155
|
+
kept.allowAgent === wanted.allowAgent &&
|
|
156
|
+
kept.userMemory === wanted.userMemory);
|
|
157
|
+
}
|
|
158
|
+
// Compiles in progress, so concurrent misses on one key share one compile.
|
|
159
|
+
const pending = new Map();
|
|
160
|
+
/**
|
|
161
|
+
* Compile and keep the graph for `key`, or wait for a compile already running.
|
|
162
|
+
*
|
|
163
|
+
* Returns the graph and whether this call compiled it. A failed compile is not
|
|
164
|
+
* kept, so the next access tries again.
|
|
165
|
+
*/
|
|
166
|
+
export async function compileOnce(key, policy, compile) {
|
|
167
|
+
const pendingKey = JSON.stringify([key, policy ?? null]);
|
|
168
|
+
const running = pending.get(pendingKey);
|
|
169
|
+
if (running) {
|
|
170
|
+
return {
|
|
171
|
+
built: (await running),
|
|
172
|
+
compiledHere: false,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const compiling = compile().then((built) => {
|
|
176
|
+
keepCachedGraph(key, built);
|
|
177
|
+
return built;
|
|
178
|
+
});
|
|
179
|
+
pending.set(pendingKey, compiling);
|
|
180
|
+
try {
|
|
181
|
+
return { built: await compiling, compiledHere: true };
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
pending.delete(pendingKey);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/** Empty the graph cache. Definition caches go away with their factories. */
|
|
188
|
+
export function clearCachedGraphsForTests() {
|
|
189
|
+
graphs.clear();
|
|
190
|
+
pending.clear();
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=cached-graphs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cached-graphs.js","sourceRoot":"","sources":["../../src/runtime/cached-graphs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,EAAE,4BAA4B,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAMtD,gFAAgF;AAChF,kDAAkD;AAClD,MAAM,CAAC,MAAM,kBAAkB,GAAG,EAAE,CAAC;AA2BrC,+EAA+E;AAC/E,MAAM,MAAM;IACO,OAAO,GAAG,IAAI,GAAG,EAAa,CAAC;IAEhD,GAAG,CAAC,GAAW;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QACpC,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;YACzB,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC/B,CAAC;Q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GAAG,CAAC,UAAU,CAAC,CAAC;IACxC,IAAI,OAAO,EAAE,CAAC;QACZ,OAAO;YACL,KAAK,EAAE,CAAC,MAAM,OAAO,CAAuB;YAC5C,YAAY,EAAE,KAAK;SACpB,CAAC;IACJ,CAAC;IACD,MAAM,SAAS,GAAG,OAAO,EAAE,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE;QACzC,eAAe,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;QAC5B,OAAO,KAAK,CAAC;IACf,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,SAAyC,CAAC,CAAC;IACnE,IAAI,CAAC;QACH,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC;IACxD,CAAC;YAAS,CAAC;QACT,OAAO,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;IAC7B,CAAC;AACH,CAAC;AAED,6EAA6E;AAC7E,MAAM,UAAU,yBAAyB;IACvC,MAAM,CAAC,KAAK,EAAE,CAAC;IACf,OAAO,CAAC,KAAK,EAAE,CAAC;AAClB,CAAC"}
|
|
@@ -7,6 +7,8 @@ export type GraphBuildSizes = {
|
|
|
7
7
|
subagents: number;
|
|
8
8
|
};
|
|
9
9
|
/** Wall time of each managed phase, from construction to {@link log}. */
|
|
10
|
+
/** Whether a graph came from the cache; `off` when the entry is not cacheable. */
|
|
11
|
+
export type GraphCacheState = "hit" | "miss" | "off";
|
|
10
12
|
export declare class GraphBuildTiming {
|
|
11
13
|
private readonly clock;
|
|
12
14
|
private readonly started;
|
|
@@ -21,6 +23,9 @@ export declare class GraphBuildTiming {
|
|
|
21
23
|
phase<T>(name: GraphBuildPhase, run: () => T | Promise<T>): Promise<T>;
|
|
22
24
|
/** Record what the agent graph is built from. */
|
|
23
25
|
setSizes(sizes: GraphBuildSizes): void;
|
|
26
|
+
private cache;
|
|
27
|
+
/** Record whether the graph came from the cache: hit, miss, or off (not cacheable). */
|
|
28
|
+
setCache(state: GraphCacheState): void;
|
|
24
29
|
/** Write the total, each phase in the order it first finished, and the sizes. */
|
|
25
30
|
log({ kind, runId, }: {
|
|
26
31
|
kind: GraphBuildKind;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-build-timing.d.ts","sourceRoot":"","sources":["../../src/runtime/graph-build-timing.ts"],"names":[],"mappings":"AAaA,MAAM,MAAM,eAAe,GACvB,SAAS,GACT,SAAS,GACT,QAAQ,GACR,cAAc,GACd,YAAY,GACZ,mBAAmB,CAAC;AACxB,MAAM,MAAM,cAAc,GAAG,KAAK,GAAG,MAAM,CAAC;AAC5C,0CAA0C;AAC1C,MAAM,MAAM,eAAe,GAAG;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,yEAAyE;AACzE,qBAAa,gBAAgB;IAKf,OAAO,CAAC,QAAQ,CAAC,KAAK;IAJlC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsC;IAC7D,OAAO,CAAC,KAAK,CAA8B;IAE3C,YAA6B,KAAK,GAAE,MAAM,MAAgC,EAEzE;IAED;;;;OAIG;IACG,KAAK,CAAC,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,GAAG,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAU3E;IAED,iDAAiD;IACjD,QAAQ,CAAC,KAAK,EAAE,eAAe,GAAG,IAAI,CAErC;IAED,iFAAiF;IACjF,GAAG,CAAC,EACF,IAAI,EACJ,KAAK,GACN,EAAE;QACD,IAAI,EAAE,cAAc,CAAC;QACrB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;KAC3B,GAAG,IAAI,
|
|
1
|
+
{"version":3,"file":"graph-build-timing.d.ts","sourceRoot":"","s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/** Wall time of each managed phase, from construction to {@link log}. */
|
|
3
2
|
export class GraphBuildTiming {
|
|
4
3
|
clock;
|
|
5
4
|
started;
|
|
@@ -27,12 +26,19 @@ export class GraphBuildTiming {
|
|
|
27
26
|
setSizes(sizes) {
|
|
28
27
|
this.sizes = sizes;
|
|
29
28
|
}
|
|
29
|
+
cache;
|
|
30
|
+
/** Record whether the graph came from the cache: hit, miss, or off (not cacheable). */
|
|
31
|
+
setCache(state) {
|
|
32
|
+
this.cache = state;
|
|
33
|
+
}
|
|
30
34
|
/** Write the total, each phase in the order it first finished, and the sizes. */
|
|
31
35
|
log({ kind, runId, }) {
|
|
32
36
|
const totalMs = Math.round(this.clock() - this.started);
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
37
|
+
let scope = `kind=${kind}`;
|
|
38
|
+
if (this.cache !== undefined)
|
|
39
|
+
scope += `, cache=${this.cache}`;
|
|
40
|
+
if (runId !== undefined)
|
|
41
|
+
scope += `, run_id=${logger.logIdentifier(runId)}`;
|
|
36
42
|
const parts = [
|
|
37
43
|
...[...this.phases].map(([name, ms]) => `${name}=${Math.round(ms)}ms`),
|
|
38
44
|
...Object.entries(this.sizes ?? {}).map(([name, count]) => `${name}=${count}`),
|
|
@@ -40,6 +46,9 @@ export class GraphBuildTiming {
|
|
|
40
46
|
const attributes = {
|
|
41
47
|
"mda.graph_build.kind": kind,
|
|
42
48
|
"mda.graph_build.total_ms": totalMs,
|
|
49
|
+
...(this.cache !== undefined
|
|
50
|
+
? { "mda.graph_build.cache": this.cache }
|
|
51
|
+
: {}),
|
|
43
52
|
};
|
|
44
53
|
for (const [name, ms] of this.phases) {
|
|
45
54
|
attributes[`mda.graph_build.${name}_ms`] = Math.round(ms);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph-build-timing.js","sourceRoot":"","sources":["../../src/runtime/graph-build-timing.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;
|
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|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/runtime/index.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAuFpD,OAAO,KAAK,EACV,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,EACrB,MAAM,YAAY,CAAC;AAepB,YAAY,EACV,mBAAmB,EACnB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAAE,gCAAgC,EAAE,MAAM,sBAAsB,CAAC;AAExE,OAAO,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAIzD,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,oBAAoB,EACpB,WAAW,EACX,kBAAkB,EAClB,0BAA0B,EAC1B,wBAAwB,GACzB,MAAM,gBAAgB,CAAC;AACxB,YAAY,EACV,SAAS,EACT,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,EACjB,yBAAyB,EACzB,aAAa,EACb,WAAW,EACX,aAAa,EACb,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,mBAAmB,EACnB,WAAW,GACZ,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACL,aAAa,EACb,eAAe,EACf,SAAS,EACT,wBAAwB,GACzB,MAAM,cAAc,CAAC;AACtB,YAAY,EACV,OAAO,EACP,oBAAoB,EACpB,mBAAmB,EACnB,uBAAuB,GACxB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAE7C;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB,aAAa,CAAC;AAG9C,eAAO,MAAM,+BAA+B,QAGnB,CAAC;AAmB1B;;;GAGG;AACH,wBAAsB,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BAG1C;AAED;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CACvC,KAAK,EAAE,UAAU,EACjB,MAAM,CAAC,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE,mBAAmB,EAC7B,OAAO,CAAC,EAAE,oBAAoB,gBA6E/B;AAsvBD,MAAM,WAAW,kBAAmB,SAAQ,IAAI,CAC9C,mBAAmB,EACnB,aAAa,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,CACjD;IACC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,0BAA0B,CAC9C,KAAK,EAAE,UAAU,EACjB,MAAM,CAAC,EAAE,gBAAgB,EACzB,OAAO,CAAC,EAAE,kBAAkB,gBA+C7B"}
|
package/dist/runtime/index.js
CHANGED
|
@@ -5,7 +5,11 @@ import { snapshotMemorySelection, snapshotMcpSelection, snapshotSandboxSelection
|
|
|
5
5
|
import { LazyManagedSandboxBackend } from "./backend.js";
|
|
6
6
|
import { inheritSetupRecipe, sandboxSelection, } from "./sandbox-manager.js";
|
|
7
7
|
import { resolveAgentDefinition } from "./agent-entry.js";
|
|
8
|
+
import { cachedAgentParts } from "../cached-agent.js";
|
|
9
|
+
import { cachedGraph, compileOnce, resolveCachedDefinition, cachedGraphKey, } from "./cached-graphs.js";
|
|
8
10
|
import { GraphBuildTiming } from "./graph-build-timing.js";
|
|
11
|
+
// The params digest of a static definition: it has no params, so one graph per entry.
|
|
12
|
+
const STATIC_DIGEST = "static";
|
|
9
13
|
import { GENERAL_PURPOSE, SUBAGENT_SKILLS_KEY, asyncSubagentDefinition, routeAsyncSubagents, withAsyncGeneralPurpose, } from "./async-subagents.js";
|
|
10
14
|
import { threadSource, verifiedLeadThread, } from "./parent-run.js";
|
|
11
15
|
import { loadToolsByConnector } from "./connector.js";
|
|
@@ -30,6 +34,7 @@ import { createEvalTrialFilesystemBackend } from "./eval-filesystem.js";
|
|
|
30
34
|
import { adaptChannelExecution, executionContext, isChannelExecution, isRunExecution, resolveRunId, threadIdOf, } from "./run-input.js";
|
|
31
35
|
import { managedChannelContextSchema } from "../run-context.js";
|
|
32
36
|
import { resolveRunThread } from "./managed-thread.js";
|
|
37
|
+
import { RunScopedBackend } from "./run-scoped-backend.js";
|
|
33
38
|
import { registerChannelMessaging } from "../channels/messaging-registry.js";
|
|
34
39
|
import { nonblankString } from "../values.js";
|
|
35
40
|
export { assertStaticAgentDefinition } from "./static-entry.js";
|
|
@@ -107,8 +112,22 @@ export async function compileManagedAgent(entry, config, options, runtime) {
|
|
|
107
112
|
: { ...nativeRuntime, ...extras };
|
|
108
113
|
const factoryEntry = typeof entry === "function";
|
|
109
114
|
const skipFactoryInspectionTools = factoryEntry && !isRun;
|
|
110
|
-
const
|
|
111
|
-
|
|
115
|
+
const cached = cachedAgentParts(entry) ? entry : undefined;
|
|
116
|
+
// Static definitions and cached agents are cached; plain factories compile
|
|
117
|
+
// on every access. A static definition has no params, so a constant digest.
|
|
118
|
+
let digest = factoryEntry ? undefined : STATIC_DIGEST;
|
|
119
|
+
const definition = withAsyncSubagents(await timing.phase("factory", async () => {
|
|
120
|
+
if (!cached)
|
|
121
|
+
return resolveAgentDefinition(entry, factoryRuntime);
|
|
122
|
+
const resolved = await resolveCachedDefinition(cached, factoryRuntime);
|
|
123
|
+
digest = resolved.digest;
|
|
124
|
+
return resolved.definition;
|
|
125
|
+
}), options);
|
|
126
|
+
const agent = await compileResolvedManagedAgent(definition, runConfig, { ...options, leadThread }, isRun, skipFactoryInspectionTools, factoryEntry, timing, digest === undefined || (factoryEntry && !cached)
|
|
127
|
+
? undefined
|
|
128
|
+
: cachedGraphKey(entry, options?.asyncSubagent === undefined
|
|
129
|
+
? "lead"
|
|
130
|
+
: `subagent:${options.asyncSubagent}`, digest, options));
|
|
112
131
|
timing.log({ kind: isRun ? "run" : "read", runId: resolveRunId(config) });
|
|
113
132
|
return agent;
|
|
114
133
|
}
|
|
@@ -133,7 +152,8 @@ function internalServerRuntime(context, isRun) {
|
|
|
133
152
|
}
|
|
134
153
|
: { accessContext: "assistants.read", executionRuntime: null };
|
|
135
154
|
}
|
|
136
|
-
async function compileResolvedManagedAgent(definition, config, options, isRun, skipFactoryInspectionTools, factoryEntry, timing) {
|
|
155
|
+
async function compileResolvedManagedAgent(definition, config, options, isRun, skipFactoryInspectionTools, factoryEntry, timing, cacheKey) {
|
|
156
|
+
const startedMonotonicMs = performance.now();
|
|
137
157
|
const connectors = selectRunConnectors(definition.config, options?.connectors);
|
|
138
158
|
const selected = options?.trialRootDir
|
|
139
159
|
? undefined
|
|
@@ -154,7 +174,48 @@ async function compileResolvedManagedAgent(definition, config, options, isRun, s
|
|
|
154
174
|
}
|
|
155
175
|
: options;
|
|
156
176
|
registerChannelMessaging(options?.channels ?? []);
|
|
157
|
-
|
|
177
|
+
const compileOptions = {
|
|
178
|
+
...runOptions,
|
|
179
|
+
browser: selectRunBrowser(definition.config, options),
|
|
180
|
+
};
|
|
181
|
+
// Resolved before the compile: it is part of a cached graph's key, and each
|
|
182
|
+
// call needs the run's approved user (see forCall).
|
|
183
|
+
const memoryAccess = await runMemoryAccess(definition, config, compileOptions, isRun, skipFactoryInspectionTools);
|
|
184
|
+
if (cacheKey === undefined) {
|
|
185
|
+
timing.setCache("off");
|
|
186
|
+
return forCall(await compileManagedAgentGraph(definition, config, { ...compileOptions, memoryAccess }, isRun, skipFactoryInspectionTools, timing), config, options, isRun, startedMonotonicMs, memoryAccess);
|
|
187
|
+
}
|
|
188
|
+
// A static definition's or cached agent's graph is cached in cached-graphs.ts
|
|
189
|
+
// and reused by later runs and reads, from any thread or caller.
|
|
190
|
+
//
|
|
191
|
+
// A run's graph bakes in which memory layers are mounted, so a cached graph is
|
|
192
|
+
// reused by a run only if it was built with the same layers allowed. Which user
|
|
193
|
+
// the user layer reads is not part of it (see MemoryPolicy). Reads have no
|
|
194
|
+
// caller, so their policy is undefined and they can reuse any cached graph.
|
|
195
|
+
const policy = isRun
|
|
196
|
+
? {
|
|
197
|
+
allowAgent: memoryAccess?.allowAgent ?? false,
|
|
198
|
+
userMemory: memoryAccess?.userAccess.userId !== undefined,
|
|
199
|
+
}
|
|
200
|
+
: undefined;
|
|
201
|
+
let built = cachedGraph(cacheKey, policy);
|
|
202
|
+
if (built) {
|
|
203
|
+
timing.setCache("hit");
|
|
204
|
+
}
|
|
205
|
+
else {
|
|
206
|
+
const compiled = await compileOnce(cacheKey, policy, async () => ({
|
|
207
|
+
...(await compileManagedAgentGraph(definition,
|
|
208
|
+
// A cached graph is reused across runs, so it must not be compiled with
|
|
209
|
+
// this run's config or lead thread. Per-run values, such as the thread
|
|
210
|
+
// whose sandbox to use, are read from the run in progress when each call
|
|
211
|
+
// executes.
|
|
212
|
+
undefined, { ...compileOptions, leadThread: undefined, memoryAccess }, isRun, skipFactoryInspectionTools, timing)),
|
|
213
|
+
policy,
|
|
214
|
+
}));
|
|
215
|
+
built = compiled.built;
|
|
216
|
+
timing.setCache(compiled.compiledHere ? "miss" : "hit");
|
|
217
|
+
}
|
|
218
|
+
return forCall(built, config, options, isRun, startedMonotonicMs, memoryAccess);
|
|
158
219
|
}
|
|
159
220
|
/** Replace or disable the discovered sandbox for this run. */
|
|
160
221
|
function selectRunSandbox(config, discovered) {
|
|
@@ -182,18 +243,12 @@ async function compileManagedAgentGraph(definition, config, options, isRun, skip
|
|
|
182
243
|
identity,
|
|
183
244
|
// The autodiscovered root memory declaration. An explicit dynamic
|
|
184
245
|
// selection below replaces it for this run.
|
|
185
|
-
memory: discoveredMemory, trialRootDir,
|
|
186
|
-
const
|
|
187
|
-
const { metadata, instructions: authoredInstructions, memory: authoredMemory, skills: skillSelection, [SUBAGENT_SKILLS_KEY]: subagentSkills, ...agentConfig } = definition.config;
|
|
246
|
+
memory: discoveredMemory, trialRootDir, browser, } = options ?? {};
|
|
247
|
+
const { metadata, instructions: authoredInstructions, memory: _selectedMemory, skills: skillSelection, [SUBAGENT_SKILLS_KEY]: subagentSkills, ...agentConfig } = definition.config;
|
|
188
248
|
delete agentConfig.mcp;
|
|
189
249
|
delete agentConfig.sandbox;
|
|
190
250
|
delete agentConfig.browser;
|
|
191
|
-
const memorySelectedByDynamicResolver =
|
|
192
|
-
const memory = memorySelectedByDynamicResolver
|
|
193
|
-
? authoredMemory === null
|
|
194
|
-
? undefined
|
|
195
|
-
: snapshotMemorySelection(authoredMemory)
|
|
196
|
-
: discoveredMemory;
|
|
251
|
+
const { memory, memorySelectedByDynamicResolver } = selectRunMemory(definition, discoveredMemory);
|
|
197
252
|
/** Layers mounted for this run, also used to state their objective policy. */
|
|
198
253
|
let mountedMemory = [];
|
|
199
254
|
/** Layers the project declared, whether or not this run was allowed them. */
|
|
@@ -242,22 +297,17 @@ async function compileManagedAgentGraph(definition, config, options, isRun, skip
|
|
|
242
297
|
// The agent's own files; deepagents' default StateBackend when unset.
|
|
243
298
|
let backend;
|
|
244
299
|
if (contextBackend) {
|
|
300
|
+
// Memory mounts read the repo while the run executes, so each run gets its
|
|
301
|
+
// own Context Hub backend (see RunScopedBackend). The local filesystem mock
|
|
302
|
+
// reads disk on every call, so it needs no wrapper.
|
|
303
|
+
const liveContextBackend = contextBackend.kind === "hub" && contextRepo
|
|
304
|
+
? new RunScopedBackend(contextBackend.backend, () => new ContextHubBackend(contextRepo))
|
|
305
|
+
: contextBackend.backend;
|
|
245
306
|
// Memory is opt-in: only the root `memory` declaration enables a layer, so a
|
|
246
307
|
// project that declares nothing mounts nothing regardless of identity.
|
|
247
|
-
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
const policyConfig = policyRunConfig(config);
|
|
251
|
-
const allowAgent = await resolveAgentMemoryAccess(agentLayer, policyConfig, isChannelExecution(config)
|
|
252
|
-
? managedChannelContextSchema
|
|
253
|
-
: agentConfig.contextSchema, isRun);
|
|
254
|
-
const userAccess = !userLayer
|
|
255
|
-
? { deniedReason: null }
|
|
256
|
-
: isRun
|
|
257
|
-
? await resolveUserMemoryAccess(userLayer, policyConfig, isChannelExecution(config)
|
|
258
|
-
? managedChannelContextSchema
|
|
259
|
-
: agentConfig.contextSchema, memorySelectedByDynamicResolver)
|
|
260
|
-
: { deniedReason: "no_context" };
|
|
308
|
+
// Usually resolved ahead of the compile (see runMemoryAccess).
|
|
309
|
+
const { allowAgent, userAccess } = options?.memoryAccess ??
|
|
310
|
+
(await resolveMemoryAccess(declaredMemory, config, agentConfig.contextSchema, isRun, memorySelectedByDynamicResolver));
|
|
261
311
|
const allowedUserId = userAccess.userId;
|
|
262
312
|
userDeniedReason = userAccess.deniedReason;
|
|
263
313
|
const memoryLayers = declaredMemory.filter((layer) => layer.type === "agent" ? allowAgent : allowedUserId !== undefined);
|
|
@@ -269,13 +319,12 @@ async function compileManagedAgentGraph(definition, config, options, isRun, skip
|
|
|
269
319
|
? contextBackend.rootDir
|
|
270
320
|
: undefined,
|
|
271
321
|
runConfig: config,
|
|
272
|
-
allowedUserId,
|
|
273
322
|
})
|
|
274
323
|
: undefined;
|
|
275
324
|
if (userMemoryBackend) {
|
|
276
325
|
loadUserMemory = () => downloadContextFile(userMemoryBackend, "/AGENTS.md");
|
|
277
326
|
}
|
|
278
|
-
backend = managedContextBackend(
|
|
327
|
+
backend = managedContextBackend(liveContextBackend, sandboxBackend, hasAgentMemoryLayer(memoryLayers), userMemoryBackend, selectedSkills?.backend);
|
|
279
328
|
// Sandbox + FilesystemPermission cannot coexist at execute() time: deepagents
|
|
280
329
|
// adapts CompositeBackend and drops routePrefixes, so any permission rule
|
|
281
330
|
// disables shell. Rely on read-only Context Hub mounts instead.
|
|
@@ -283,7 +332,7 @@ async function compileManagedAgentGraph(definition, config, options, isRun, skip
|
|
|
283
332
|
? []
|
|
284
333
|
: managedContextPermissions(params.permissions);
|
|
285
334
|
if (allowAgent) {
|
|
286
|
-
loadAgentMemory = () => downloadContextFile(
|
|
335
|
+
loadAgentMemory = () => downloadContextFile(liveContextBackend, "/memories/agent/AGENTS.md");
|
|
287
336
|
}
|
|
288
337
|
}
|
|
289
338
|
else {
|
|
@@ -408,17 +457,10 @@ async function compileManagedAgentGraph(definition, config, options, isRun, skip
|
|
|
408
457
|
const compiled = metadata && Object.keys(metadata).length > 0
|
|
409
458
|
? agent.withConfig({ metadata })
|
|
410
459
|
: agent;
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
const origin = ingressRunOrigin(config?.metadata);
|
|
415
|
-
const pending = startRun({
|
|
416
|
-
identity: await detectRunIdentity({
|
|
417
|
-
caller: buildRuntimeIdentity(resolveRuntimeConfigurable(config)),
|
|
418
|
-
isRun,
|
|
419
|
-
}),
|
|
460
|
+
const built = {
|
|
461
|
+
policy: undefined,
|
|
462
|
+
agent: compiled,
|
|
420
463
|
configuration: {
|
|
421
|
-
channel: detectRunChannel(config),
|
|
422
464
|
sandboxDeclared: sandbox !== undefined,
|
|
423
465
|
identityDeclared: identity !== undefined,
|
|
424
466
|
skillsDeclared: effectiveHasSkills,
|
|
@@ -437,19 +479,100 @@ async function compileManagedAgentGraph(definition, config, options, isRun, skip
|
|
|
437
479
|
layers_mounted: mountedMemory.map((layer) => layer.type),
|
|
438
480
|
user_denied_reason: userDeniedReason,
|
|
439
481
|
},
|
|
440
|
-
providerEventType: origin.providerEventType,
|
|
441
|
-
userResolution: origin.userResolution,
|
|
442
482
|
subagentRole: options?.asyncSubagent === undefined ? "lead" : "async_subagent",
|
|
443
483
|
browserDeclared: browser !== undefined,
|
|
444
484
|
},
|
|
485
|
+
};
|
|
486
|
+
return built;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Prepare a compiled graph for this call: telemetry, then the channel adapter.
|
|
490
|
+
*
|
|
491
|
+
* Both are applied to a copy returned by `withConfig`, so the graph in `built` is
|
|
492
|
+
* never modified and stays safe to share across runs. The adapter also records
|
|
493
|
+
* this run's verified lead thread on that copy.
|
|
494
|
+
*/
|
|
495
|
+
async function forCall(built, config, options, isRun, startedMonotonicMs,
|
|
496
|
+
// This run's memory access. Graphs serve many users, so the user memory denial
|
|
497
|
+
// the graph was compiled with may not be this run's.
|
|
498
|
+
memoryAccess) {
|
|
499
|
+
// The user this run may reach user memory as: from the run's resolved access,
|
|
500
|
+
// never from anything the caller sends.
|
|
501
|
+
const approvedUser = isRun ? memoryAccess?.userAccess.userId : undefined;
|
|
502
|
+
if (options?.reportTelemetry === false) {
|
|
503
|
+
return adaptChannelExecution(built.agent.withConfig({}), options?.leadThread, approvedUser);
|
|
504
|
+
}
|
|
505
|
+
const origin = ingressRunOrigin(config?.metadata);
|
|
506
|
+
const pending = startRun({
|
|
507
|
+
identity: await detectRunIdentity({
|
|
508
|
+
caller: buildRuntimeIdentity(resolveRuntimeConfigurable(config)),
|
|
509
|
+
isRun,
|
|
510
|
+
}),
|
|
511
|
+
configuration: {
|
|
512
|
+
...built.configuration,
|
|
513
|
+
...(memoryAccess === undefined
|
|
514
|
+
? {}
|
|
515
|
+
: {
|
|
516
|
+
memory: {
|
|
517
|
+
...built.configuration.memory,
|
|
518
|
+
user_denied_reason: memoryAccess.userAccess.deniedReason,
|
|
519
|
+
},
|
|
520
|
+
}),
|
|
521
|
+
channel: detectRunChannel(config),
|
|
522
|
+
providerEventType: origin.providerEventType,
|
|
523
|
+
userResolution: origin.userResolution,
|
|
524
|
+
},
|
|
445
525
|
// Absent on a direct invoke, where `startRun` mints one.
|
|
446
526
|
runId: resolveRunId(config),
|
|
447
527
|
threadId: threadIdOf(config),
|
|
448
528
|
startedMonotonicMs,
|
|
449
529
|
});
|
|
450
|
-
return
|
|
530
|
+
return adaptChannelExecution(built.agent.withConfig({
|
|
451
531
|
callbacks: [new RunTelemetryListener(pending)],
|
|
452
|
-
});
|
|
532
|
+
}), options?.leadThread, approvedUser);
|
|
533
|
+
}
|
|
534
|
+
/** The memory this run uses: the factory's explicit selection, or the discovered one. */
|
|
535
|
+
function selectRunMemory(definition, discovered) {
|
|
536
|
+
const authored = definition.config.memory;
|
|
537
|
+
const memorySelectedByDynamicResolver = Object.hasOwn(definition.config, "memory") && authored !== undefined;
|
|
538
|
+
const memory = memorySelectedByDynamicResolver
|
|
539
|
+
? authored === null
|
|
540
|
+
? undefined
|
|
541
|
+
: snapshotMemorySelection(authored)
|
|
542
|
+
: discovered;
|
|
543
|
+
return { memory, memorySelectedByDynamicResolver };
|
|
544
|
+
}
|
|
545
|
+
/** Resolve which declared memory layers this run may mount. */
|
|
546
|
+
async function resolveMemoryAccess(declaredMemory, config, contextSchema, isRun, memorySelectedByDynamicResolver) {
|
|
547
|
+
const agentLayer = declaredMemory.find((layer) => layer.type === "agent");
|
|
548
|
+
const userLayer = userMemoryLayer(declaredMemory);
|
|
549
|
+
// Memory policies keep their public channel field after routing normalization.
|
|
550
|
+
const policyConfig = policyRunConfig(config);
|
|
551
|
+
const schema = isChannelExecution(config)
|
|
552
|
+
? managedChannelContextSchema
|
|
553
|
+
: contextSchema;
|
|
554
|
+
const allowAgent = await resolveAgentMemoryAccess(agentLayer, policyConfig, schema, isRun);
|
|
555
|
+
const userAccess = !userLayer
|
|
556
|
+
? { deniedReason: null }
|
|
557
|
+
: isRun
|
|
558
|
+
? await resolveUserMemoryAccess(userLayer, policyConfig, schema, memorySelectedByDynamicResolver)
|
|
559
|
+
: { deniedReason: "no_context" };
|
|
560
|
+
return { allowAgent, userAccess };
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Resolve the run's memory access before the compile: it is part of a cached
|
|
564
|
+
* graph's key, and each call carries the run's approved user.
|
|
565
|
+
*
|
|
566
|
+
* Returns undefined when the compile would mount no Context Hub backend, and so no
|
|
567
|
+
* memory: a read of a factory entry, or a project with no context repo or root.
|
|
568
|
+
*/
|
|
569
|
+
async function runMemoryAccess(definition, config, options, isRun, skipFactoryInspectionTools) {
|
|
570
|
+
if (skipFactoryInspectionTools ||
|
|
571
|
+
(!options.contextRepo && !options.contextRoot)) {
|
|
572
|
+
return undefined;
|
|
573
|
+
}
|
|
574
|
+
const { memory, memorySelectedByDynamicResolver } = selectRunMemory(definition, options.memory);
|
|
575
|
+
return resolveMemoryAccess(memory?.config.scope ?? [], config, definition.config.contextSchema, isRun, memorySelectedByDynamicResolver);
|
|
453
576
|
}
|
|
454
577
|
function policyRunConfig(config) {
|
|
455
578
|
const context = config?.context;
|