@framers/agentos 0.12.13 → 0.12.14
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/README.md +1 -1
- package/dist/api/agent.d.ts +35 -1
- package/dist/api/agent.d.ts.map +1 -1
- package/dist/api/agent.js +8 -0
- package/dist/api/agent.js.map +1 -1
- package/dist/api/gmi.d.ts +21 -0
- package/dist/api/gmi.d.ts.map +1 -0
- package/dist/api/gmi.js +527 -0
- package/dist/api/gmi.js.map +1 -0
- package/dist/api/runtime/agentCognitiveMemory.d.ts +82 -0
- package/dist/api/runtime/agentCognitiveMemory.d.ts.map +1 -0
- package/dist/api/runtime/agentCognitiveMemory.js +277 -0
- package/dist/api/runtime/agentCognitiveMemory.js.map +1 -0
- package/dist/api/runtime/capabilityContract.d.ts +21 -1
- package/dist/api/runtime/capabilityContract.d.ts.map +1 -1
- package/dist/api/runtime/capabilityContract.js +15 -15
- package/dist/api/runtime/capabilityContract.js.map +1 -1
- package/dist/api/runtime/gmiCognition.d.ts +66 -0
- package/dist/api/runtime/gmiCognition.d.ts.map +1 -0
- package/dist/api/runtime/gmiCognition.js +58 -0
- package/dist/api/runtime/gmiCognition.js.map +1 -0
- package/dist/api/runtime/gmiPersona.d.ts +16 -0
- package/dist/api/runtime/gmiPersona.d.ts.map +1 -0
- package/dist/api/runtime/gmiPersona.js +91 -0
- package/dist/api/runtime/gmiPersona.js.map +1 -0
- package/dist/api/runtime/gmiResults.d.ts +98 -0
- package/dist/api/runtime/gmiResults.d.ts.map +1 -0
- package/dist/api/runtime/gmiResults.js +333 -0
- package/dist/api/runtime/gmiResults.js.map +1 -0
- package/dist/api/runtime/gmiSession.d.ts +85 -0
- package/dist/api/runtime/gmiSession.d.ts.map +1 -0
- package/dist/api/runtime/gmiSession.js +285 -0
- package/dist/api/runtime/gmiSession.js.map +1 -0
- package/dist/api/runtime/gmiTranscript.d.ts +48 -0
- package/dist/api/runtime/gmiTranscript.d.ts.map +1 -0
- package/dist/api/runtime/gmiTranscript.js +110 -0
- package/dist/api/runtime/gmiTranscript.js.map +1 -0
- package/dist/api/runtime/lightweightAgentDiagnostics.d.ts +6 -1
- package/dist/api/runtime/lightweightAgentDiagnostics.d.ts.map +1 -1
- package/dist/api/runtime/lightweightAgentDiagnostics.js +9 -2
- package/dist/api/runtime/lightweightAgentDiagnostics.js.map +1 -1
- package/dist/api/sessionHistory.d.ts +43 -1
- package/dist/api/sessionHistory.d.ts.map +1 -1
- package/dist/api/sessionHistory.js +56 -1
- package/dist/api/sessionHistory.js.map +1 -1
- package/dist/api/sessionTranscript.d.ts +8 -0
- package/dist/api/sessionTranscript.d.ts.map +1 -1
- package/dist/api/sessionTranscript.js.map +1 -1
- package/dist/api/transferStyle.d.ts +8 -0
- package/dist/api/transferStyle.d.ts.map +1 -1
- package/dist/api/transferStyle.js +4 -1
- package/dist/api/transferStyle.js.map +1 -1
- package/dist/api/types.d.ts +11 -0
- package/dist/api/types.d.ts.map +1 -1
- package/dist/api/types.js.map +1 -1
- package/dist/cognition/substrate/GMI.d.ts.map +1 -1
- package/dist/cognition/substrate/GMI.js +54 -2
- package/dist/cognition/substrate/GMI.js.map +1 -1
- package/dist/cognition/substrate/IGMI.d.ts +23 -1
- package/dist/cognition/substrate/IGMI.d.ts.map +1 -1
- package/dist/cognition/substrate/IGMI.js.map +1 -1
- package/dist/io/vision/VisionPipeline.d.ts +5 -0
- package/dist/io/vision/VisionPipeline.d.ts.map +1 -1
- package/dist/io/vision/VisionPipeline.js +28 -13
- package/dist/io/vision/VisionPipeline.js.map +1 -1
- package/dist/io/vision/index.d.ts.map +1 -1
- package/dist/io/vision/index.js +2 -0
- package/dist/io/vision/index.js.map +1 -1
- package/dist/io/vision/types.d.ts +11 -0
- package/dist/io/vision/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/api/gmi.js
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file gmi.ts
|
|
3
|
+
* gmi(): an agent whose sessions are Generalized Mind Instances, built
|
|
4
|
+
* in-process from agent options (spec D5-D12). `agent({ runtime: 'gmi' })`
|
|
5
|
+
* returns the same handle.
|
|
6
|
+
*
|
|
7
|
+
* Construction checks what needs no environment: options the GMI path cannot
|
|
8
|
+
* honour, the cognition profile, and the `memory.embedding` settings that name
|
|
9
|
+
* their provider. The persona (with the provider and model it resolves), the
|
|
10
|
+
* prompt engine, utility AI and tool orchestrator the sessions share, and the
|
|
11
|
+
* cognitive memory are built on first use, so an agent made before its keys are
|
|
12
|
+
* set resolves them on its first call; a build that fails is not kept, and the
|
|
13
|
+
* next call builds again.
|
|
14
|
+
*/
|
|
15
|
+
import { randomUUID } from 'node:crypto';
|
|
16
|
+
import { GMI } from '../cognition/substrate/GMI.js';
|
|
17
|
+
import { InMemoryWorkingMemory } from '../cognition/substrate/memory/InMemoryWorkingMemory.js';
|
|
18
|
+
import { StatisticalUtilityAI } from '../cognition/nlp/ai_utilities/StatisticalUtilityAI.js';
|
|
19
|
+
import { PromptEngine } from '../core/llm/PromptEngine.js';
|
|
20
|
+
import { ToolPermissionManager } from '../core/tools/permissions/ToolPermissionManager.js';
|
|
21
|
+
import { ToolExecutor } from '../core/tools/ToolExecutor.js';
|
|
22
|
+
import { ToolOrchestrator } from '../core/tools/ToolOrchestrator.js';
|
|
23
|
+
import { ExtensionRegistry } from '../extensions/ExtensionRegistry.js';
|
|
24
|
+
import { EXTENSION_KIND_TOOL } from '../extensions/types.js';
|
|
25
|
+
import { createCompletionGateway } from './runtime/completionGateway.js';
|
|
26
|
+
import { GatewayProviderManager } from './runtime/gatewayProviderManager.js';
|
|
27
|
+
import { adaptTools } from './runtime/toolAdapter.js';
|
|
28
|
+
import { resolveCognition } from './runtime/gmiCognition.js';
|
|
29
|
+
import { personaFromAgentOptions } from './runtime/gmiPersona.js';
|
|
30
|
+
import { assertEmbeddingConfig, createAgentCognitiveMemory } from './runtime/agentCognitiveMemory.js';
|
|
31
|
+
import { sendGmiTurn, streamGmiTurn, TurnLock } from './runtime/gmiSession.js';
|
|
32
|
+
import { transcriptToConversation } from './runtime/gmiTranscript.js';
|
|
33
|
+
import { SessionHistoryBuffer, SESSION_HISTORY_DEFAULTS } from './sessionHistory.js';
|
|
34
|
+
import { accumulateUsage, createEmptyUsageAggregate, mergeAggregates } from './runtime/usageAccumulator.js';
|
|
35
|
+
import { exportAgentConfig, exportAgentConfigJSON } from './agentExportCore.js';
|
|
36
|
+
import { getDeferredCapabilities } from './runtime/lightweightAgentDiagnostics.js';
|
|
37
|
+
/** Options with no GMI-path implementation yet; set, they throw at construction. */
|
|
38
|
+
const UNSUPPORTED_ON_GMI = ['voice', 'avatar', 'channels'];
|
|
39
|
+
/** Per-call overrides generate() and stream() accept on the GMI path (spec D10). */
|
|
40
|
+
const ALLOWED_CALL_OVERRIDES = new Set(['temperature', 'maxTokens', 'topP', 'responseFormat', 'model', 'provider', 'maxSteps', 'usageLedger']);
|
|
41
|
+
/** Per-call overrides that pick the route, the step limit or the ledger rather than a completion option. */
|
|
42
|
+
const ROUTE_OVERRIDES = new Set(['model', 'provider', 'maxSteps', 'usageLedger']);
|
|
43
|
+
/** `agent()`'s step limit. */
|
|
44
|
+
const DEFAULT_MAX_STEPS = 5;
|
|
45
|
+
const GMI_PROMPT_ENGINE_CONFIG = {
|
|
46
|
+
defaultTemplateName: 'openai_chat',
|
|
47
|
+
availableTemplates: {},
|
|
48
|
+
tokenCounting: { strategy: 'estimated', estimationModel: 'gpt-3.5-turbo' },
|
|
49
|
+
// Truncation only: no utility AI is passed, and no summary is made by a model call.
|
|
50
|
+
historyManagement: { defaultMaxMessages: 100000, maxTokensForHistory: 120000, summarizationTriggerRatio: 0, preserveImportantMessages: true },
|
|
51
|
+
contextManagement: { maxRAGContextTokens: 1500, summarizationQualityTier: 'balanced', preserveSourceAttributionInSummary: true },
|
|
52
|
+
contextualElementSelection: { maxElementsPerType: {}, defaultMaxElementsPerType: 3, priorityResolutionStrategy: 'highest_first', conflictResolutionStrategy: 'skip_conflicting' },
|
|
53
|
+
performance: { enableCaching: false, cacheTimeoutSeconds: 60 },
|
|
54
|
+
};
|
|
55
|
+
function isSet(value) {
|
|
56
|
+
if (value == null || value === false)
|
|
57
|
+
return false;
|
|
58
|
+
if (typeof value === 'object')
|
|
59
|
+
return Object.keys(value).length > 0;
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* A memoised async build that is not kept when it fails: the next call after a
|
|
64
|
+
* rejection builds again, so one transient failure does not fail every later
|
|
65
|
+
* call. `reset()` drops a kept result.
|
|
66
|
+
*/
|
|
67
|
+
function retryingOnce(build) {
|
|
68
|
+
let pending;
|
|
69
|
+
return {
|
|
70
|
+
get() {
|
|
71
|
+
if (!pending) {
|
|
72
|
+
const attempt = build();
|
|
73
|
+
pending = attempt;
|
|
74
|
+
attempt.catch(() => {
|
|
75
|
+
if (pending === attempt)
|
|
76
|
+
pending = undefined;
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return pending;
|
|
80
|
+
},
|
|
81
|
+
peek: () => pending,
|
|
82
|
+
reset() {
|
|
83
|
+
pending = undefined;
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/** `target` with some members replaced; every other method runs on `target` itself. */
|
|
88
|
+
function withMembers(target, members) {
|
|
89
|
+
return new Proxy(target, {
|
|
90
|
+
get(t, prop) {
|
|
91
|
+
if (Object.prototype.hasOwnProperty.call(members, prop))
|
|
92
|
+
return members[prop];
|
|
93
|
+
const value = Reflect.get(t, prop, t);
|
|
94
|
+
return typeof value === 'function' ? value.bind(t) : value;
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* The agent's memory manager as one GMI sees it. `GMI.shutdown()` shuts down
|
|
100
|
+
* the cognitive memory it was given; the agent's sessions share one manager, so
|
|
101
|
+
* a session's shutdown must leave it to the others, and `agent.close()` closes it.
|
|
102
|
+
*/
|
|
103
|
+
function sharedMemoryView(manager) {
|
|
104
|
+
return withMembers(manager, { shutdown: async () => undefined });
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* A tool registry that leaves out the tools ToolExecutor registers from its own
|
|
108
|
+
* constructor (the built-in getCurrentDateTime), so a tool-less agent offers the
|
|
109
|
+
* model no tools (spec D4j) and an agent tool of the same name is the only one.
|
|
110
|
+
* The constructor starts that registration without waiting for it; skipping it
|
|
111
|
+
* here needs no wait, and no later registration can be overtaken by it.
|
|
112
|
+
*/
|
|
113
|
+
class AgentToolRegistry extends ExtensionRegistry {
|
|
114
|
+
constructor() {
|
|
115
|
+
super(...arguments);
|
|
116
|
+
/** False while the executor's constructor registers its built-ins. */
|
|
117
|
+
this.acceptsRegistrations = false;
|
|
118
|
+
}
|
|
119
|
+
async register(...args) {
|
|
120
|
+
if (!this.acceptsRegistrations)
|
|
121
|
+
return;
|
|
122
|
+
return super.register(...args);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function toolExecutorWithoutBuiltIns() {
|
|
126
|
+
const registry = new AgentToolRegistry(EXTENSION_KIND_TOOL);
|
|
127
|
+
const executor = new ToolExecutor(undefined, undefined, registry);
|
|
128
|
+
registry.acceptsRegistrations = true;
|
|
129
|
+
return executor;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The agent's `onBeforeToolExecution` around the shared orchestrator, for one
|
|
133
|
+
* GMI: `null` skips the tool as `generateText` skips it, returned arguments
|
|
134
|
+
* replace the call's, and a hook that throws is warned about and the tool runs.
|
|
135
|
+
*/
|
|
136
|
+
function hookTools(base, hook, step) {
|
|
137
|
+
if (!hook)
|
|
138
|
+
return base;
|
|
139
|
+
const processToolCall = async (details) => {
|
|
140
|
+
const req = details.toolCallRequest;
|
|
141
|
+
let info = {
|
|
142
|
+
name: req.name,
|
|
143
|
+
args: (req.arguments ?? {}),
|
|
144
|
+
id: req.id,
|
|
145
|
+
step: step.index,
|
|
146
|
+
};
|
|
147
|
+
try {
|
|
148
|
+
info = await hook(info);
|
|
149
|
+
}
|
|
150
|
+
catch (hookError) {
|
|
151
|
+
console.warn('[agentos] onBeforeToolExecution hook error:', hookError);
|
|
152
|
+
}
|
|
153
|
+
if (info === null) {
|
|
154
|
+
return {
|
|
155
|
+
toolCallId: req.id,
|
|
156
|
+
toolName: req.name,
|
|
157
|
+
output: { skipped: true },
|
|
158
|
+
isError: true,
|
|
159
|
+
errorDetails: { message: 'Skipped by onBeforeToolExecution hook' },
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
return base.processToolCall({ ...details, toolCallRequest: { ...req, arguments: info.args } });
|
|
163
|
+
};
|
|
164
|
+
return withMembers(base, { processToolCall });
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The agent's completion gateway. The GMI's route carries its own `onFallback`
|
|
168
|
+
* (a trace entry), which replaces a gateway default, so the agent's
|
|
169
|
+
* `onFallback` is called beside it, as `onFallback(error, provider)`; a
|
|
170
|
+
* listener that throws is warned about and never fails the hop.
|
|
171
|
+
*/
|
|
172
|
+
function gatewayFor(opts) {
|
|
173
|
+
const base = createCompletionGateway({
|
|
174
|
+
apiKey: opts.apiKey,
|
|
175
|
+
baseUrl: opts.baseUrl,
|
|
176
|
+
fallbackProviders: opts.fallbackProviders,
|
|
177
|
+
policyTier: opts.policyTier,
|
|
178
|
+
router: opts.router,
|
|
179
|
+
routerParams: opts.routerParams,
|
|
180
|
+
hostPolicy: opts.hostPolicy,
|
|
181
|
+
});
|
|
182
|
+
const listener = opts.onFallback;
|
|
183
|
+
if (!listener)
|
|
184
|
+
return base;
|
|
185
|
+
return {
|
|
186
|
+
stream: base.stream,
|
|
187
|
+
resolve: (route, after) => base.resolve({
|
|
188
|
+
...route,
|
|
189
|
+
onFallback: (info) => {
|
|
190
|
+
route.onFallback?.(info);
|
|
191
|
+
try {
|
|
192
|
+
listener(info.error, info.to);
|
|
193
|
+
}
|
|
194
|
+
catch (listenerError) {
|
|
195
|
+
console.warn('[agentos] onFallback listener error:', listenerError);
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
}, after),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function mergeLedger(...parts) {
|
|
202
|
+
const merged = Object.assign({}, ...parts.filter(Boolean));
|
|
203
|
+
return Object.keys(merged).length > 0 ? merged : undefined;
|
|
204
|
+
}
|
|
205
|
+
async function recordedUsage(ledger, sessionId) {
|
|
206
|
+
// Imported on use, as agent() imports it: the ledger reads files.
|
|
207
|
+
const { getRecordedAgentOSUsage } = await import('./runtime/usageLedger.js');
|
|
208
|
+
return getRecordedAgentOSUsage({ enabled: ledger?.enabled, path: ledger?.path, sessionId });
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* An agent whose sessions are GMIs (docs/GMI.md, "GMIs from agent()").
|
|
212
|
+
*
|
|
213
|
+
* @param opts - The options of `agent()`. `voice`, `avatar` and `channels` throw.
|
|
214
|
+
* @returns The `Agent` surface: `generate`, `stream`, `session`, `usage`, `close`, `export`.
|
|
215
|
+
* @throws {Error} At construction, naming the option: an option the GMI path
|
|
216
|
+
* cannot honour, an unknown cognition profile or metaprompt preset, or a
|
|
217
|
+
* `memory.embedding` that names a provider without embeddings, a model that
|
|
218
|
+
* does not resolve, or a dimension that is not a positive integer or not known.
|
|
219
|
+
* No environment is read here: the provider and model resolve on the first
|
|
220
|
+
* call, which rejects with the error `agent()` gives when nothing resolves.
|
|
221
|
+
*/
|
|
222
|
+
export function gmi(opts) {
|
|
223
|
+
for (const key of UNSUPPORTED_ON_GMI) {
|
|
224
|
+
if (isSet(opts[key])) {
|
|
225
|
+
throw new Error(`gmi(): '${key}' is not available on the GMI path; remove it or use runtime: 'legacy'.`);
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
const deferred = getDeferredCapabilities(opts, 'gmi');
|
|
229
|
+
if (deferred.length > 0) {
|
|
230
|
+
console.warn(`[AgentOS] gmi() accepted config it does not enforce yet: ${deferred.join(', ')}.`);
|
|
231
|
+
}
|
|
232
|
+
const cognition = resolveCognition(opts);
|
|
233
|
+
const lightCognition = resolveCognition({ cognition: 'light' });
|
|
234
|
+
if (cognition.memory)
|
|
235
|
+
assertEmbeddingConfig(cognition.memory);
|
|
236
|
+
if (cognition.memory && opts.memoryProvider?.getContext) {
|
|
237
|
+
console.warn('[agentos] gmi(): cognitive memory supplies the memory context; memoryProvider.getContext is skipped (observe still runs).');
|
|
238
|
+
}
|
|
239
|
+
const tools = adaptTools(opts.tools);
|
|
240
|
+
const ledger = mergeLedger(opts.observability?.usageLedger ?? opts.usageLedger);
|
|
241
|
+
const maxSteps = opts.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
242
|
+
const gateway = gatewayFor(opts);
|
|
243
|
+
const shared = retryingOnce(async () => {
|
|
244
|
+
// Throws, as generateText throws, when no provider or model resolves.
|
|
245
|
+
const persona = personaFromAgentOptions(opts, cognition, tools);
|
|
246
|
+
const lightPersona = personaFromAgentOptions(opts, lightCognition, tools);
|
|
247
|
+
const promptEngine = new PromptEngine();
|
|
248
|
+
await promptEngine.initialize(GMI_PROMPT_ENGINE_CONFIG);
|
|
249
|
+
const utilityAI = new StatisticalUtilityAI(`gmi-utility-${persona.id}`);
|
|
250
|
+
await utilityAI.initialize({ utilityId: `gmi-utility-${persona.id}` });
|
|
251
|
+
const permissions = new ToolPermissionManager();
|
|
252
|
+
await permissions.initialize({ strictCapabilityChecking: false, logToolCalls: false, toolToSubscriptionFeatures: {} });
|
|
253
|
+
const orchestrator = new ToolOrchestrator();
|
|
254
|
+
await orchestrator.initialize({ orchestratorId: `gmi-tools-${persona.id}`, defaultToolCallTimeoutMs: 30000, maxConcurrentToolCalls: 10, logToolCalls: false, globalDisabledTools: [] }, permissions, toolExecutorWithoutBuiltIns(), tools);
|
|
255
|
+
return { persona, lightPersona, promptEngine, utilityAI, tools: orchestrator };
|
|
256
|
+
});
|
|
257
|
+
const memory = retryingOnce(async () => {
|
|
258
|
+
if (!cognition.memory)
|
|
259
|
+
return undefined;
|
|
260
|
+
const { persona } = await shared.get();
|
|
261
|
+
// Reads the environment for the embedding provider when memory.embedding names none.
|
|
262
|
+
return createAgentCognitiveMemory({ persona, memory: cognition.memory, mechanisms: cognition.mechanisms });
|
|
263
|
+
});
|
|
264
|
+
async function buildGmi(id, persona, mem, steps) {
|
|
265
|
+
const s = await shared.get();
|
|
266
|
+
const step = { index: 0 };
|
|
267
|
+
let turn = { prompt: undefined, memoryContext: undefined };
|
|
268
|
+
const instance = new GMI(id);
|
|
269
|
+
const config = {
|
|
270
|
+
workingMemory: new InMemoryWorkingMemory(),
|
|
271
|
+
promptEngine: s.promptEngine,
|
|
272
|
+
llmProviderManager: new GatewayProviderManager().asProviderManager(),
|
|
273
|
+
utilityAI: s.utilityAI,
|
|
274
|
+
toolOrchestrator: hookTools(s.tools, opts.onBeforeToolExecution, step),
|
|
275
|
+
...(mem ? { cognitiveMemory: sharedMemoryView(mem.manager) } : {}),
|
|
276
|
+
completionGateway: gateway,
|
|
277
|
+
maxToolLoopIterations: steps,
|
|
278
|
+
defaultLlmProviderId: persona.defaultProviderId,
|
|
279
|
+
defaultLlmModelId: persona.defaultModelId,
|
|
280
|
+
// Every model call: the memoryProvider block after the leading system
|
|
281
|
+
// messages (where the legacy path puts it), then onBeforeGeneration.
|
|
282
|
+
beforeModelCall: async (ctx) => {
|
|
283
|
+
step.index = ctx.stepIndex;
|
|
284
|
+
let messages = ctx.messages;
|
|
285
|
+
let changed = false;
|
|
286
|
+
if (turn.memoryContext) {
|
|
287
|
+
let insertAt = 0;
|
|
288
|
+
while (insertAt < messages.length && messages[insertAt].role === 'system')
|
|
289
|
+
insertAt += 1;
|
|
290
|
+
messages = [...messages.slice(0, insertAt), { role: 'system', content: turn.memoryContext }, ...messages.slice(insertAt)];
|
|
291
|
+
changed = true;
|
|
292
|
+
}
|
|
293
|
+
if (opts.onBeforeGeneration) {
|
|
294
|
+
try {
|
|
295
|
+
const modified = await opts.onBeforeGeneration({
|
|
296
|
+
messages: messages,
|
|
297
|
+
system: typeof persona.baseSystemPrompt === 'string' ? persona.baseSystemPrompt : undefined,
|
|
298
|
+
tools,
|
|
299
|
+
model: ctx.modelId,
|
|
300
|
+
provider: ctx.providerId,
|
|
301
|
+
step: ctx.stepIndex,
|
|
302
|
+
prompt: turn.prompt,
|
|
303
|
+
});
|
|
304
|
+
if (modified?.messages) {
|
|
305
|
+
messages = modified.messages;
|
|
306
|
+
changed = true;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
catch (hookError) {
|
|
310
|
+
console.warn('[agentos] onBeforeGeneration hook error:', hookError);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
return changed ? messages : undefined;
|
|
314
|
+
},
|
|
315
|
+
};
|
|
316
|
+
await instance.initialize(persona, config);
|
|
317
|
+
return {
|
|
318
|
+
gmi: instance,
|
|
319
|
+
prepare: (context) => {
|
|
320
|
+
turn = context;
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
/** A GMI for one turn only, shut down once the turn ends. */
|
|
325
|
+
function forOneTurn(built) {
|
|
326
|
+
return { ...built, release: () => built.gmi.shutdown() };
|
|
327
|
+
}
|
|
328
|
+
const sessions = new Map();
|
|
329
|
+
const sessionTallies = new Map();
|
|
330
|
+
const agentTally = createEmptyUsageAggregate();
|
|
331
|
+
/** The per-call overrides as completion options; throws naming an override the GMI path does not take. */
|
|
332
|
+
function overridesOf(extra) {
|
|
333
|
+
const out = {};
|
|
334
|
+
for (const [k, v] of Object.entries(extra ?? {})) {
|
|
335
|
+
if (v === undefined)
|
|
336
|
+
continue;
|
|
337
|
+
if (!ALLOWED_CALL_OVERRIDES.has(k))
|
|
338
|
+
throw new Error(`gmi(): the per-call option '${k}' is not supported on the GMI path.`);
|
|
339
|
+
if (!ROUTE_OVERRIDES.has(k))
|
|
340
|
+
out[k] = v;
|
|
341
|
+
}
|
|
342
|
+
return out;
|
|
343
|
+
}
|
|
344
|
+
function oneShotDeps(source, extra) {
|
|
345
|
+
const callId = `${source === 'agent.generate' ? 'generate' : 'stream'}-${randomUUID()}`;
|
|
346
|
+
return {
|
|
347
|
+
sessionId: callId,
|
|
348
|
+
opts,
|
|
349
|
+
userId: callId,
|
|
350
|
+
useMemoryProviderContext: true,
|
|
351
|
+
history: null,
|
|
352
|
+
ledger: mergeLedger(ledger, extra?.usageLedger, { source: extra?.usageLedger?.source ?? source }),
|
|
353
|
+
onUsage: (u) => accumulateUsage(agentTally, u),
|
|
354
|
+
lock: new TurnLock(),
|
|
355
|
+
// generate() and stream() keep no history and run the light profile whatever the agent's (spec D10).
|
|
356
|
+
gmiFor: async () => {
|
|
357
|
+
const s = await shared.get();
|
|
358
|
+
const persona = extra && (extra.model || extra.provider)
|
|
359
|
+
? personaFromAgentOptions({ ...opts, model: extra.model ?? opts.model, provider: extra.provider ?? opts.provider }, lightCognition, tools)
|
|
360
|
+
: s.lightPersona;
|
|
361
|
+
return forOneTurn(await buildGmi(`gmi-${persona.id}-${callId}`, persona, undefined, extra?.maxSteps ?? maxSteps));
|
|
362
|
+
},
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
const handle = {
|
|
366
|
+
async generate(prompt, extra) {
|
|
367
|
+
const options = overridesOf(extra);
|
|
368
|
+
return sendGmiTurn(oneShotDeps('agent.generate', extra), prompt, { options });
|
|
369
|
+
},
|
|
370
|
+
stream(prompt, extra) {
|
|
371
|
+
const options = overridesOf(extra);
|
|
372
|
+
return streamGmiTurn(oneShotDeps('agent.stream', extra), prompt, { options });
|
|
373
|
+
},
|
|
374
|
+
session(id, sessionOptions) {
|
|
375
|
+
const sessionId = id ?? randomUUID();
|
|
376
|
+
const existing = sessions.get(sessionId);
|
|
377
|
+
if (existing) {
|
|
378
|
+
if (sessionOptions?.userId !== undefined && sessionOptions.userId !== existing.userId) {
|
|
379
|
+
throw new Error(`gmi(): session '${sessionId}' already runs as user '${existing.userId}'; close it to open it for another user.`);
|
|
380
|
+
}
|
|
381
|
+
return existing.session;
|
|
382
|
+
}
|
|
383
|
+
// Each session's memory scope is its own unless the caller names the user:
|
|
384
|
+
// sessions are often different people, and one person's facts must not
|
|
385
|
+
// reach another's replies.
|
|
386
|
+
const userId = sessionOptions?.userId ?? sessionId;
|
|
387
|
+
const history = opts.history === false ? null : new SessionHistoryBuffer({ ...SESSION_HISTORY_DEFAULTS, ...(opts.history ?? {}) });
|
|
388
|
+
if (!sessionTallies.has(sessionId))
|
|
389
|
+
sessionTallies.set(sessionId, createEmptyUsageAggregate(sessionId));
|
|
390
|
+
const tally = sessionTallies.get(sessionId);
|
|
391
|
+
const lock = new TurnLock();
|
|
392
|
+
let closing;
|
|
393
|
+
const buildSessionGmi = async (gmiId) => {
|
|
394
|
+
const { persona } = await shared.get();
|
|
395
|
+
return buildGmi(gmiId, persona, await memory.get(), maxSteps);
|
|
396
|
+
};
|
|
397
|
+
// The session's own GMI, when it keeps history; a GMI per turn otherwise.
|
|
398
|
+
const own = retryingOnce(() => buildSessionGmi(`gmi-${sessionId}`));
|
|
399
|
+
let ownBuilt;
|
|
400
|
+
// A send made after close() fails; one made before it runs, and close() waits for it.
|
|
401
|
+
const gmiFor = (closedAtCall) => async () => {
|
|
402
|
+
if (closedAtCall)
|
|
403
|
+
throw new Error(`gmi(): session '${sessionId}' is closed; agent.session('${sessionId}') opens a new one.`);
|
|
404
|
+
if (!history)
|
|
405
|
+
return forOneTurn(await buildSessionGmi(`gmi-${sessionId}-${randomUUID()}`));
|
|
406
|
+
ownBuilt = await own.get();
|
|
407
|
+
return ownBuilt;
|
|
408
|
+
};
|
|
409
|
+
/** Brings the session GMI's own history in line with the store once the running turn ends, so a cleared fact never reaches its sentiment tracker or metaprompts. */
|
|
410
|
+
const syncGmiHistory = () => {
|
|
411
|
+
void lock
|
|
412
|
+
.acquire()
|
|
413
|
+
.then((release) => {
|
|
414
|
+
try {
|
|
415
|
+
ownBuilt?.gmi.replaceHistory?.(transcriptToConversation(history?.messages() ?? []));
|
|
416
|
+
}
|
|
417
|
+
finally {
|
|
418
|
+
release();
|
|
419
|
+
}
|
|
420
|
+
})
|
|
421
|
+
.catch((error) => console.warn('[agentos] gmi(): could not clear the session GMI history:', error));
|
|
422
|
+
};
|
|
423
|
+
const deps = (source) => ({
|
|
424
|
+
sessionId,
|
|
425
|
+
opts,
|
|
426
|
+
userId,
|
|
427
|
+
history,
|
|
428
|
+
lock,
|
|
429
|
+
ledger: mergeLedger(ledger, { sessionId, source }),
|
|
430
|
+
useMemoryProviderContext: !cognition.memory,
|
|
431
|
+
gmiFor: gmiFor(closing !== undefined),
|
|
432
|
+
onUsage: (u) => {
|
|
433
|
+
accumulateUsage(tally, u);
|
|
434
|
+
accumulateUsage(agentTally, u);
|
|
435
|
+
},
|
|
436
|
+
});
|
|
437
|
+
const session = {
|
|
438
|
+
id: sessionId,
|
|
439
|
+
send: (input, sendOpts) => {
|
|
440
|
+
const options = Object.fromEntries(Object.entries({
|
|
441
|
+
toolChoice: sendOpts?.toolChoice,
|
|
442
|
+
requestTimeout: sendOpts?.requestTimeout,
|
|
443
|
+
cacheDiagnostics: sendOpts?.cacheDiagnostics,
|
|
444
|
+
cache: sendOpts?.cache,
|
|
445
|
+
maxTokens: sendOpts?.maxTokens,
|
|
446
|
+
}).filter(([, v]) => v !== undefined));
|
|
447
|
+
return sendGmiTurn(deps('agent.session.send'), input, {
|
|
448
|
+
options,
|
|
449
|
+
responseSchema: sendOpts?.responseSchema,
|
|
450
|
+
schemaName: sendOpts?.schemaName,
|
|
451
|
+
blockLabel: sendOpts?.blockLabel,
|
|
452
|
+
});
|
|
453
|
+
},
|
|
454
|
+
stream: (input) => streamGmiTurn(deps('agent.session.stream'), input, {}),
|
|
455
|
+
messages: () => history?.messages() ?? [],
|
|
456
|
+
reseed: (snapshot) => {
|
|
457
|
+
if (!history)
|
|
458
|
+
throw new Error('reseed requires session history (history: false is set on this agent)');
|
|
459
|
+
history.reseed(snapshot);
|
|
460
|
+
syncGmiHistory();
|
|
461
|
+
},
|
|
462
|
+
drainHistoryEvents: () => history?.drainHistoryEvents() ?? [],
|
|
463
|
+
usage: async () => {
|
|
464
|
+
const persisted = await recordedUsage(ledger, sessionId);
|
|
465
|
+
return ledger?.enabled ? persisted : mergeAggregates(tally, persisted);
|
|
466
|
+
},
|
|
467
|
+
clear: () => {
|
|
468
|
+
history?.reseed([]);
|
|
469
|
+
syncGmiHistory();
|
|
470
|
+
},
|
|
471
|
+
// A turn still running ends first and is returned to its caller, but the
|
|
472
|
+
// reseed keeps it out of the history; then the session's GMI is shut down.
|
|
473
|
+
close: () => (closing ?? (closing = (async () => {
|
|
474
|
+
if (sessions.get(sessionId) === entry)
|
|
475
|
+
sessions.delete(sessionId);
|
|
476
|
+
history?.reseed([]);
|
|
477
|
+
const release = await lock.acquire();
|
|
478
|
+
try {
|
|
479
|
+
const built = await own.peek()?.catch(() => undefined);
|
|
480
|
+
await built?.gmi.shutdown();
|
|
481
|
+
}
|
|
482
|
+
finally {
|
|
483
|
+
release();
|
|
484
|
+
}
|
|
485
|
+
})())),
|
|
486
|
+
};
|
|
487
|
+
const entry = { session, userId };
|
|
488
|
+
sessions.set(sessionId, entry);
|
|
489
|
+
return session;
|
|
490
|
+
},
|
|
491
|
+
async usage(sessionId) {
|
|
492
|
+
const persisted = await recordedUsage(ledger, sessionId);
|
|
493
|
+
const inMemory = sessionId ? sessionTallies.get(sessionId) ?? createEmptyUsageAggregate(sessionId) : agentTally;
|
|
494
|
+
return ledger?.enabled ? persisted : mergeAggregates(inMemory, persisted);
|
|
495
|
+
},
|
|
496
|
+
/**
|
|
497
|
+
* Closes every session (each after its running turn), then the cognitive
|
|
498
|
+
* memory; a session opened from now on builds a new one. The tools stay as
|
|
499
|
+
* the caller passed them: the orchestrator is not shut down, because
|
|
500
|
+
* shutting it down would shut down the caller's tools.
|
|
501
|
+
*/
|
|
502
|
+
async close() {
|
|
503
|
+
const pending = memory.peek();
|
|
504
|
+
memory.reset();
|
|
505
|
+
await Promise.all([...sessions.values()].map(({ session }) => session.close()));
|
|
506
|
+
const mem = await pending?.catch(() => undefined);
|
|
507
|
+
await mem?.close();
|
|
508
|
+
},
|
|
509
|
+
export(metadata, options) {
|
|
510
|
+
return exportAgentConfig(handle, metadata, options);
|
|
511
|
+
},
|
|
512
|
+
exportJSON(metadata, options) {
|
|
513
|
+
return exportAgentConfigJSON(handle, metadata, options);
|
|
514
|
+
},
|
|
515
|
+
getAvatarBindings() {
|
|
516
|
+
return {};
|
|
517
|
+
},
|
|
518
|
+
setAvatarBindingOverrides() {
|
|
519
|
+
// avatar is not available on the GMI path
|
|
520
|
+
},
|
|
521
|
+
};
|
|
522
|
+
Object.defineProperty(handle, '__config', { value: opts, enumerable: false, configurable: true });
|
|
523
|
+
return handle;
|
|
524
|
+
}
|
|
525
|
+
/** Alias of {@link gmi}. */
|
|
526
|
+
export const createGmi = gmi;
|
|
527
|
+
//# sourceMappingURL=gmi.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gmi.js","sourceRoot":"","sources":["../../src/api/gmi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,OAAO,EAAE,GAAG,EAAE,MAAM,+BAA+B,CAAC;AAIpD,OAAO,EAAE,qBAAqB,EAAE,MAAM,wDAAwD,CAAC;AAC/F,OAAO,EAAE,oBAAoB,EAAE,MAAM,uDAAuD,CAAC;AAC7F,OAAO,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAG3D,OAAO,EAAE,qBAAqB,EAAE,MAAM,oDAAoD,CAAC;AAC3F,OAAO,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,mCAAmC,CAAC;AAGrE,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AA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@file agentCognitiveMemory.ts
|
|
3
|
+
* Cognitive memory for GMIs built from agent options (`agent({ runtime: 'gmi' })`,
|
|
4
|
+
* spec D7): a {@link CognitiveMemoryManager} over an in-memory vector store, the
|
|
5
|
+
* in-memory knowledge graph, an embedding manager for `memory.embedding`, a
|
|
6
|
+
* working memory of its own and the persona's HEXACO traits.
|
|
7
|
+
*
|
|
8
|
+
* One manager serves every session of an agent. Each GMI's memory bridge passes
|
|
9
|
+
* the session's mood on every encode, retrieve and assemble call and scopes
|
|
10
|
+
* recall to the session's user and conversation, so the manager's own mood
|
|
11
|
+
* callback is neutral. The memory graph runs on the `'knowledge-graph'` backend
|
|
12
|
+
* over the same in-memory knowledge graph, because the `'graphology'` backend
|
|
13
|
+
* needs graphology, an optional peer dependency. Consolidation runs only when
|
|
14
|
+
* `memory.consolidation.enabled` is true. The build embeds one test text through
|
|
15
|
+
* the embedding model it sets up, so a model that cannot answer, or answers with
|
|
16
|
+
* another size than memory expects, fails the build instead of leaving memory empty.
|
|
17
|
+
*/
|
|
18
|
+
import { CognitiveMemoryManager } from '../../cognition/memory/CognitiveMemoryManager.js';
|
|
19
|
+
import type { CognitiveMechanismsConfig } from '../../cognition/memory/mechanisms/types.js';
|
|
20
|
+
import type { IPersonaDefinition } from '../../cognition/substrate/personas/IPersonaDefinition.js';
|
|
21
|
+
import type { IEmbeddingManager } from '../../core/embeddings/IEmbeddingManager.js';
|
|
22
|
+
import type { MemoryConfig } from '../types.js';
|
|
23
|
+
type Env = Readonly<Record<string, string | undefined>>;
|
|
24
|
+
/**
|
|
25
|
+
* Checks, when the agent is built, that cognitive memory has an embedding model
|
|
26
|
+
* it can use, so a missing or unusable one fails before the first send. Reads
|
|
27
|
+
* the environment only to pick the provider when `memory.embedding` is unset;
|
|
28
|
+
* credentials are read when the memory is built.
|
|
29
|
+
*
|
|
30
|
+
* @param memory - The agent's memory config.
|
|
31
|
+
* @param env - The environment to read OPENAI_API_KEY and OLLAMA_BASE_URL from (defaults to `process.env`).
|
|
32
|
+
* @throws {Error} Naming `memory.embedding` when no provider is set or detected, when the
|
|
33
|
+
* provider has no embeddings (Anthropic, Groq, xAI, the Claude Code and Gemini CLIs), when the
|
|
34
|
+
* model does not resolve, or when the model's output size is unknown and
|
|
35
|
+
* `memory.embedding.dimension` is unset or not a positive integer.
|
|
36
|
+
*/
|
|
37
|
+
export declare function assertEmbeddingAvailable(memory: MemoryConfig, env?: Env): void;
|
|
38
|
+
/**
|
|
39
|
+
* The checks on `memory.embedding` that read no environment, for `gmi()` to run
|
|
40
|
+
* when the agent is built: with a provider set, that it has embeddings, that the
|
|
41
|
+
* model resolves on it, that a declared dimension is a positive integer, and that
|
|
42
|
+
* the model's output size is known or declared. With no provider set, the
|
|
43
|
+
* provider is picked from the environment when the memory is first built, and
|
|
44
|
+
* only a declared dimension is checked here.
|
|
45
|
+
*
|
|
46
|
+
* @param memory - The agent's memory config.
|
|
47
|
+
* @throws {Error} Naming `memory.embedding`, as {@link assertEmbeddingAvailable} does.
|
|
48
|
+
*/
|
|
49
|
+
export declare function assertEmbeddingConfig(memory: MemoryConfig): void;
|
|
50
|
+
export interface AgentCognitiveMemoryOptions {
|
|
51
|
+
/** The agent's persona: its id is the memory's owner (`agentId`), its traits shape encoding. */
|
|
52
|
+
persona: IPersonaDefinition;
|
|
53
|
+
memory: MemoryConfig;
|
|
54
|
+
/** The memory mechanisms to run; none when undefined. */
|
|
55
|
+
mechanisms?: CognitiveMechanismsConfig;
|
|
56
|
+
/**
|
|
57
|
+
* An embedding manager to use instead of one built from `memory.embedding`
|
|
58
|
+
* (tests, and hosts that own one). The caller keeps ownership: `close()` does not shut it down.
|
|
59
|
+
*/
|
|
60
|
+
embeddingManager?: IEmbeddingManager;
|
|
61
|
+
}
|
|
62
|
+
export interface AgentCognitiveMemory {
|
|
63
|
+
manager: CognitiveMemoryManager;
|
|
64
|
+
/**
|
|
65
|
+
* Shuts the manager down and releases the vector store and the embedding
|
|
66
|
+
* manager this builder created. Later calls return the first call's promise.
|
|
67
|
+
*/
|
|
68
|
+
close(): Promise<void>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Builds and initialises the cognitive memory manager an agent's GMIs share.
|
|
72
|
+
*
|
|
73
|
+
* @param opts - The persona, the memory config, the mechanisms and an optional embedding manager.
|
|
74
|
+
* @returns The manager and a `close()` that releases it.
|
|
75
|
+
* @throws {Error} When the embedding model is missing or unusable (see {@link assertEmbeddingAvailable}),
|
|
76
|
+
* when its provider has no credentials or fails to start, when a test embedding through it
|
|
77
|
+
* fails or returns another size than memory expects (skipped for an embedding manager the
|
|
78
|
+
* caller passes), or when the manager fails to initialise.
|
|
79
|
+
*/
|
|
80
|
+
export declare function createAgentCognitiveMemory(opts: AgentCognitiveMemoryOptions): Promise<AgentCognitiveMemory>;
|
|
81
|
+
export {};
|
|
82
|
+
//# sourceMappingURL=agentCognitiveMemory.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agentCognitiveMemory.d.ts","sourceRoot":"","sources":["../../../src/api/runtime/agentCognitiveMemory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,sBAAsB,EAAE,MAAM,kDAAkD,CAAC;AAE1F,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,4CAA4C,CAAC;AAM5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0DAA0D,CAAC;AAEnG,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAGpF,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AA+BhD,KAAK,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;AA4ExD;;;;;;;;;;;;GAYG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,GAAE,GAAiB,GAAG,IAAI,CAE3F;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI,CAMhE;AAED,MAAM,WAAW,2BAA2B;IAC1C,gGAAgG;IAChG,OAAO,EAAE,kBAAkB,CAAC;IAC5B,MAAM,EAAE,YAAY,CAAC;IACrB,yDAAyD;IACzD,UAAU,CAAC,EAAE,yBAAyB,CAAC;IACvC;;;OAGG;IACH,gBAAgB,CAAC,EAAE,iBAAiB,CAAC;CACtC;AAED,MAAM,WAAW,oBAAoB;IACnC,OAAO,EAAE,sBAAsB,CAAC;IAChC;;;OAGG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAgFD;;;;;;;;;GASG;AACH,wBAAsB,0BAA0B,CAAC,IAAI,EAAE,2BAA2B,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAgEjH"}
|