@openliate/liate 0.0.0-stage → 0.1.5
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 +21 -0
- package/README.md +127 -2
- package/README.npm.md +128 -0
- package/dist/bin.js +28734 -0
- package/dist/liate.js +39468 -0
- package/dist/runtime/hono.js +28061 -0
- package/dist/runtime/index.js +28061 -0
- package/hub/agents/docgyan-agent/agent.json +27 -0
- package/hub/agents/docgyan-agent/agent.ts +39 -0
- package/hub/agents/gnani-agent/agent.json +17 -0
- package/hub/agents/neon-agent/agent.json +18 -0
- package/hub/agents/prism-agent/agent.json +17 -0
- package/hub/agents/sarvam-agent/agent.json +17 -0
- package/package.json +71 -4
- package/src/cli/index.ts +346 -0
- package/src/cli/resolver.ts +153 -0
- package/src/core/aum.ts +137 -0
- package/src/core/om.ts +159 -0
- package/src/core/spec.ts +112 -0
- package/src/core/uuid.ts +8 -0
- package/src/core/version.ts +2 -0
- package/src/layers/agent/harness.ts +118 -0
- package/src/layers/agent/loop.ts +203 -0
- package/src/layers/agent/skills.ts +302 -0
- package/src/layers/agent/types.ts +66 -0
- package/src/layers/environment/sandbox.ts +107 -0
- package/src/layers/environment/types.ts +23 -0
- package/src/layers/integration/knowledge.ts +187 -0
- package/src/layers/integration/lib.ts +167 -0
- package/src/layers/integration/memory.ts +135 -0
- package/src/layers/integration/repo.ts +273 -0
- package/src/layers/integration/types.ts +60 -0
- package/src/layers/llm/model.ts +916 -0
- package/src/layers/llm/types.ts +64 -0
- package/src/layers/tools/mcp.ts +236 -0
- package/src/layers/tools/registry.ts +307 -0
- package/src/layers/tools/server.ts +69 -0
- package/src/layers/tools/types.ts +38 -0
- package/src/liate.ts +65 -0
- package/src/routes/skills.ts +73 -0
- package/src/runtime/hono.ts +346 -0
- package/src/runtime/wasm.ts +23 -0
- package/src/scaffold/project.ts +188 -0
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type { AgentTool, IntegrationConfig, KnowledgeContext, KnowledgeDoc, MemoryProvider } from "@/layers/integration/types";
|
|
4
|
+
import { Session } from "@/layers/integration/memory";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Layer [I] Knowledge Manager
|
|
8
|
+
* Resolves local documents, files, and inline facts into structured context for the agent.
|
|
9
|
+
*/
|
|
10
|
+
export class Knowledge {
|
|
11
|
+
/**
|
|
12
|
+
* Resolves Layer [I] Knowledge specifications from file paths, directories, or inline texts.
|
|
13
|
+
*/
|
|
14
|
+
public static async resolve(
|
|
15
|
+
spec: string | string[] | Record<string, any>,
|
|
16
|
+
baseDir: string = process.cwd()
|
|
17
|
+
): Promise<KnowledgeContext> {
|
|
18
|
+
const documents: KnowledgeDoc[] = [];
|
|
19
|
+
const sources: string[] = [];
|
|
20
|
+
|
|
21
|
+
const processItem = (item: string) => {
|
|
22
|
+
sources.push(item);
|
|
23
|
+
const resolved = path.isAbsolute(item) ? item : path.resolve(baseDir, item);
|
|
24
|
+
|
|
25
|
+
if (fs.existsSync(resolved)) {
|
|
26
|
+
const stats = fs.statSync(resolved);
|
|
27
|
+
if (stats.isDirectory()) {
|
|
28
|
+
const files = this.scanDir(resolved);
|
|
29
|
+
for (const file of files.slice(0, 50)) {
|
|
30
|
+
try {
|
|
31
|
+
const content = fs.readFileSync(file, "utf-8").slice(0, 50000);
|
|
32
|
+
const rel = path.relative(baseDir, file);
|
|
33
|
+
documents.push({
|
|
34
|
+
id: rel,
|
|
35
|
+
source: rel,
|
|
36
|
+
title: path.basename(file),
|
|
37
|
+
content
|
|
38
|
+
});
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
} else if (stats.isFile()) {
|
|
42
|
+
try {
|
|
43
|
+
const content = fs.readFileSync(resolved, "utf-8").slice(0, 50000);
|
|
44
|
+
documents.push({
|
|
45
|
+
id: item,
|
|
46
|
+
source: item,
|
|
47
|
+
title: path.basename(resolved),
|
|
48
|
+
content
|
|
49
|
+
});
|
|
50
|
+
} catch {}
|
|
51
|
+
}
|
|
52
|
+
} else {
|
|
53
|
+
// Treat as inline knowledge snippet / factual string
|
|
54
|
+
documents.push({
|
|
55
|
+
id: `inline-${documents.length + 1}`,
|
|
56
|
+
source: "inline",
|
|
57
|
+
content: item
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
if (Array.isArray(spec)) {
|
|
63
|
+
for (const item of spec) {
|
|
64
|
+
if (typeof item === "string") processItem(item);
|
|
65
|
+
}
|
|
66
|
+
} else if (typeof spec === "string") {
|
|
67
|
+
processItem(spec);
|
|
68
|
+
} else if (typeof spec === "object" && spec !== null) {
|
|
69
|
+
if (Array.isArray(spec.files)) {
|
|
70
|
+
for (const f of spec.files) processItem(f);
|
|
71
|
+
}
|
|
72
|
+
if (typeof spec.path === "string" || typeof spec.dir === "string") {
|
|
73
|
+
processItem(spec.path || spec.dir);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const totalChars = documents.reduce((acc, d) => acc + d.content.length, 0);
|
|
78
|
+
return {
|
|
79
|
+
sources,
|
|
80
|
+
documents,
|
|
81
|
+
totalChars
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Synthesizes an executable AgentTool for the agent to query and search its knowledge base.
|
|
87
|
+
*/
|
|
88
|
+
public static asTool(context: KnowledgeContext): AgentTool {
|
|
89
|
+
return {
|
|
90
|
+
name: "search_knowledge",
|
|
91
|
+
description: "Search documents and reference knowledge configured in Layer [I] Knowledge.",
|
|
92
|
+
parameters: {
|
|
93
|
+
type: "object",
|
|
94
|
+
properties: {
|
|
95
|
+
query: { type: "string", description: "Search query, topic, or keyword to retrieve from knowledge base." }
|
|
96
|
+
},
|
|
97
|
+
required: ["query"]
|
|
98
|
+
},
|
|
99
|
+
execute: async (args: any) => {
|
|
100
|
+
const query = (args.query || "").toLowerCase().trim();
|
|
101
|
+
if (!query) return "Empty query. Provide a search term.";
|
|
102
|
+
|
|
103
|
+
const matches = context.documents
|
|
104
|
+
.map((doc) => {
|
|
105
|
+
const contentLower = doc.content.toLowerCase();
|
|
106
|
+
const queryWords = query.split(/\s+/).filter(Boolean);
|
|
107
|
+
const score = queryWords.reduce((acc: number, w: string) => acc + (contentLower.includes(w) ? 1 : 0), 0);
|
|
108
|
+
return { doc, score };
|
|
109
|
+
})
|
|
110
|
+
.filter((m) => m.score > 0)
|
|
111
|
+
.sort((a, b) => b.score - a.score)
|
|
112
|
+
.slice(0, 3);
|
|
113
|
+
|
|
114
|
+
if (matches.length === 0) {
|
|
115
|
+
return `No direct matches found in knowledge base (${context.documents.length} docs available).`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return matches
|
|
119
|
+
.map((m) => `[Source: ${m.doc.source}]\n${m.doc.content.slice(0, 1500)}`)
|
|
120
|
+
.join("\n\n---\n\n");
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
private static scanDir(dir: string): string[] {
|
|
126
|
+
const results: string[] = [];
|
|
127
|
+
try {
|
|
128
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
129
|
+
for (const entry of entries) {
|
|
130
|
+
const full = path.join(dir, entry.name);
|
|
131
|
+
if (entry.isDirectory()) {
|
|
132
|
+
if (!entry.name.startsWith(".") && entry.name !== "node_modules") {
|
|
133
|
+
results.push(...this.scanDir(full));
|
|
134
|
+
}
|
|
135
|
+
} else if (entry.isFile()) {
|
|
136
|
+
const ext = path.extname(entry.name).toLowerCase();
|
|
137
|
+
if ([".md", ".txt", ".json", ".csv", ".yaml", ".yml"].includes(ext)) {
|
|
138
|
+
results.push(full);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
} catch {}
|
|
143
|
+
return results;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Universal Integration Resolver for Layer [I]
|
|
149
|
+
*/
|
|
150
|
+
export class IntegrationResolver {
|
|
151
|
+
public static resolveMemory(
|
|
152
|
+
config?: string | IntegrationConfig | MemoryProvider,
|
|
153
|
+
metadata?: Record<string, any>,
|
|
154
|
+
sessionId?: string
|
|
155
|
+
): MemoryProvider {
|
|
156
|
+
if (!config) {
|
|
157
|
+
return new Session(sessionId || "ephemeral", metadata);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (typeof config === "object" && "append" in config && "getMessages" in config) {
|
|
161
|
+
return config as MemoryProvider;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const memoryTarget = typeof config === "string" ? config : (config.memory || config.type);
|
|
165
|
+
return new Session(memoryTarget, metadata);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
public static async resolveKnowledge(
|
|
169
|
+
config?: string | string[] | IntegrationConfig,
|
|
170
|
+
baseDir?: string
|
|
171
|
+
): Promise<KnowledgeContext | undefined> {
|
|
172
|
+
if (!config) return undefined;
|
|
173
|
+
const spec = typeof config === "object" && !Array.isArray(config) ? config.knowledge : config;
|
|
174
|
+
if (!spec) return undefined;
|
|
175
|
+
return Knowledge.resolve(spec, baseDir);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
public static async resolveKnowledgeTool(
|
|
179
|
+
config?: string | string[] | IntegrationConfig,
|
|
180
|
+
baseDir?: string
|
|
181
|
+
): Promise<AgentTool | undefined> {
|
|
182
|
+
const context = await this.resolveKnowledge(config, baseDir);
|
|
183
|
+
if (!context || context.documents.length === 0) return undefined;
|
|
184
|
+
return Knowledge.asTool(context);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// src/layers/integration/lib.ts
|
|
2
|
+
// Layer [I] Dynamic Library & Module Resolver (exposes npm/local/builtin exports as AgentTools)
|
|
3
|
+
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import type { AgentTool } from "@/layers/agent/types";
|
|
6
|
+
|
|
7
|
+
export interface LoadedLib {
|
|
8
|
+
name: string;
|
|
9
|
+
module: any;
|
|
10
|
+
exports: string[];
|
|
11
|
+
type: "npm" | "local" | "builtin";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export class Lib {
|
|
15
|
+
private static cache = new Map<string, LoadedLib>();
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Dynamically imports any npm library, local file, or Node.js/Bun builtin module.
|
|
19
|
+
*/
|
|
20
|
+
public static async import(nameOrPath: string): Promise<LoadedLib> {
|
|
21
|
+
if (this.cache.has(nameOrPath)) {
|
|
22
|
+
return this.cache.get(nameOrPath)!;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let mod: any;
|
|
26
|
+
let type: "npm" | "local" | "builtin" = "npm";
|
|
27
|
+
|
|
28
|
+
const isLocalPath =
|
|
29
|
+
nameOrPath.startsWith("./") ||
|
|
30
|
+
nameOrPath.startsWith("../") ||
|
|
31
|
+
path.isAbsolute(nameOrPath);
|
|
32
|
+
|
|
33
|
+
if (isLocalPath) {
|
|
34
|
+
type = "local";
|
|
35
|
+
const resolvedPath = path.resolve(process.cwd(), nameOrPath);
|
|
36
|
+
try {
|
|
37
|
+
mod = await import(resolvedPath);
|
|
38
|
+
} catch (err: any) {
|
|
39
|
+
throw new Error(`Layer [I] failed to import local module '${nameOrPath}': ${err.message}`);
|
|
40
|
+
}
|
|
41
|
+
} else {
|
|
42
|
+
try {
|
|
43
|
+
mod = await import(nameOrPath);
|
|
44
|
+
} catch (err: any) {
|
|
45
|
+
try {
|
|
46
|
+
const localNodeModules = path.resolve(process.cwd(), "node_modules", nameOrPath);
|
|
47
|
+
mod = await import(localNodeModules);
|
|
48
|
+
} catch {
|
|
49
|
+
throw new Error(
|
|
50
|
+
`Layer [I] failed to load library '${nameOrPath}'. Ensure it is installed: ${err.message}`
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const exports = Object.keys(mod || {});
|
|
57
|
+
const loaded: LoadedLib = {
|
|
58
|
+
name: nameOrPath,
|
|
59
|
+
module: mod,
|
|
60
|
+
exports,
|
|
61
|
+
type,
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
this.cache.set(nameOrPath, loaded);
|
|
65
|
+
return loaded;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Resolves multiple libraries declared in Layer [I]
|
|
70
|
+
*/
|
|
71
|
+
public static async resolveLibs(
|
|
72
|
+
libs: string[] | Record<string, string>
|
|
73
|
+
): Promise<Map<string, LoadedLib>> {
|
|
74
|
+
const results = new Map<string, LoadedLib>();
|
|
75
|
+
|
|
76
|
+
if (Array.isArray(libs)) {
|
|
77
|
+
for (const libName of libs) {
|
|
78
|
+
if (!libName || typeof libName !== "string") continue;
|
|
79
|
+
try {
|
|
80
|
+
const loaded = await this.import(libName);
|
|
81
|
+
results.set(libName, loaded);
|
|
82
|
+
} catch (err: any) {
|
|
83
|
+
console.warn(`[Liate Layer I] Could not resolve '${libName}': ${err.message}`);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
} else if (typeof libs === "object" && libs !== null) {
|
|
87
|
+
for (const [alias, spec] of Object.entries(libs)) {
|
|
88
|
+
if (!spec || typeof spec !== "string") continue;
|
|
89
|
+
try {
|
|
90
|
+
const loaded = await this.import(spec);
|
|
91
|
+
results.set(alias, loaded);
|
|
92
|
+
} catch (err: any) {
|
|
93
|
+
console.warn(`[Liate Layer I] Could not resolve '${alias}' (${spec}): ${err.message}`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return results;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Exposes callable functions from loaded libraries as native AgentTools.
|
|
103
|
+
*/
|
|
104
|
+
public static asTools(loadedMap: Map<string, LoadedLib>): AgentTool[] {
|
|
105
|
+
const tools: AgentTool[] = [];
|
|
106
|
+
|
|
107
|
+
for (const [libKey, loaded] of loadedMap.entries()) {
|
|
108
|
+
const mod = loaded.module?.default || loaded.module;
|
|
109
|
+
if (!mod) continue;
|
|
110
|
+
|
|
111
|
+
if (typeof mod === "function") {
|
|
112
|
+
const safeName = `lib_${libKey.replace(/[^a-zA-Z0-9_]/g, "_")}`;
|
|
113
|
+
tools.push({
|
|
114
|
+
name: safeName,
|
|
115
|
+
description: `Execute function from Layer [I] library '${libKey}'.`,
|
|
116
|
+
parameters: {
|
|
117
|
+
type: "object",
|
|
118
|
+
properties: {
|
|
119
|
+
input: {
|
|
120
|
+
type: "string",
|
|
121
|
+
description: "Input parameter or JSON payload for the library function.",
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
execute: async (args: any) => {
|
|
126
|
+
let parsed = args.input;
|
|
127
|
+
try {
|
|
128
|
+
parsed = JSON.parse(args.input);
|
|
129
|
+
} catch {}
|
|
130
|
+
return await mod(parsed);
|
|
131
|
+
},
|
|
132
|
+
});
|
|
133
|
+
} else if (typeof mod === "object") {
|
|
134
|
+
for (const [fnName, fnVal] of Object.entries(mod)) {
|
|
135
|
+
if (typeof fnVal === "function" && !fnName.startsWith("_") && tools.length < 20) {
|
|
136
|
+
const toolName = `lib_${libKey.replace(/[^a-zA-Z0-9_]/g, "_")}_${fnName}`;
|
|
137
|
+
tools.push({
|
|
138
|
+
name: toolName,
|
|
139
|
+
description: `Execute '${fnName}' from Layer [I] library '${libKey}'.`,
|
|
140
|
+
parameters: {
|
|
141
|
+
type: "object",
|
|
142
|
+
properties: {
|
|
143
|
+
args: {
|
|
144
|
+
type: "array",
|
|
145
|
+
description: "Arguments array to pass to the function.",
|
|
146
|
+
items: { type: "string" },
|
|
147
|
+
},
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
execute: async (args: any) => {
|
|
151
|
+
const callArgs = Array.isArray(args.args) ? args.args : [args.args];
|
|
152
|
+
return await (fnVal as any)(...callArgs);
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return tools;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
public static clearCache(): void {
|
|
164
|
+
this.cache.clear();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import fs from "fs/promises";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import type { AgentMessage, MemoryProvider, SessionData } from "@/layers/integration/types";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Unified Session Manager for Layer [I]
|
|
7
|
+
* Operates in-memory by default, or auto-persists to .liate/sessions/<name>.json if a path is specified.
|
|
8
|
+
*/
|
|
9
|
+
export class Session implements MemoryProvider {
|
|
10
|
+
public readonly sessionId: string;
|
|
11
|
+
public readonly filePath?: string;
|
|
12
|
+
private data: SessionData;
|
|
13
|
+
private loaded: boolean = false;
|
|
14
|
+
|
|
15
|
+
constructor(target?: string, metadata?: Record<string, any>) {
|
|
16
|
+
const isMemory = !target || target === ":memory:" || target === "memory" || target === "in-memory";
|
|
17
|
+
|
|
18
|
+
if (isMemory) {
|
|
19
|
+
this.sessionId = (target && target !== ":memory:" && target !== "memory" && target !== "in-memory")
|
|
20
|
+
? target
|
|
21
|
+
: "ephemeral";
|
|
22
|
+
this.filePath = undefined;
|
|
23
|
+
} else {
|
|
24
|
+
let normalized = target.endsWith(".json") ? target : `${target}.json`;
|
|
25
|
+
if (!path.isAbsolute(normalized)) {
|
|
26
|
+
if (normalized.startsWith("sessions/") || normalized.startsWith("sessions\\")) {
|
|
27
|
+
normalized = path.join(".liate", normalized);
|
|
28
|
+
} else if (!normalized.startsWith(".liate")) {
|
|
29
|
+
normalized = path.join(".liate", "sessions", normalized);
|
|
30
|
+
}
|
|
31
|
+
this.filePath = path.resolve(process.cwd(), normalized);
|
|
32
|
+
} else {
|
|
33
|
+
this.filePath = normalized;
|
|
34
|
+
}
|
|
35
|
+
this.sessionId = path.basename(this.filePath, ".json");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const now = new Date().toISOString();
|
|
39
|
+
this.data = {
|
|
40
|
+
sessionId: this.sessionId,
|
|
41
|
+
createdAt: now,
|
|
42
|
+
updatedAt: now,
|
|
43
|
+
metadata: metadata || {},
|
|
44
|
+
messages: [],
|
|
45
|
+
state: {}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
if (isMemory) {
|
|
49
|
+
this.loaded = true;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
public async load(): Promise<SessionData> {
|
|
54
|
+
if (!this.filePath) {
|
|
55
|
+
return this.data;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
const content = await fs.readFile(this.filePath, "utf-8");
|
|
60
|
+
const parsed = JSON.parse(content);
|
|
61
|
+
this.data = {
|
|
62
|
+
sessionId: parsed.sessionId || this.sessionId,
|
|
63
|
+
createdAt: parsed.createdAt || this.data.createdAt,
|
|
64
|
+
updatedAt: parsed.updatedAt || new Date().toISOString(),
|
|
65
|
+
metadata: { ...(this.data.metadata || {}), ...(parsed.metadata || {}) },
|
|
66
|
+
messages: Array.isArray(parsed.messages) ? parsed.messages : [],
|
|
67
|
+
state: parsed.state && typeof parsed.state === "object" ? parsed.state : {}
|
|
68
|
+
};
|
|
69
|
+
this.loaded = true;
|
|
70
|
+
} catch (err: any) {
|
|
71
|
+
if (err.code !== "ENOENT") {
|
|
72
|
+
throw new Error(`Failed to load session memory from ${this.filePath}: ${err.message}`);
|
|
73
|
+
}
|
|
74
|
+
await this.save();
|
|
75
|
+
this.loaded = true;
|
|
76
|
+
}
|
|
77
|
+
return this.data;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
public async save(): Promise<void> {
|
|
81
|
+
this.data.updatedAt = new Date().toISOString();
|
|
82
|
+
if (!this.filePath) {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
const dir = path.dirname(this.filePath);
|
|
88
|
+
await fs.mkdir(dir, { recursive: true });
|
|
89
|
+
await fs.writeFile(this.filePath, JSON.stringify(this.data, null, 2), "utf-8");
|
|
90
|
+
} catch {
|
|
91
|
+
// In read-only or restricted environments, gracefully persist in memory
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
public getMessages(): AgentMessage[] {
|
|
96
|
+
return [...this.data.messages];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
public async append(message: AgentMessage | AgentMessage[]): Promise<void> {
|
|
100
|
+
if (!this.loaded && this.filePath) {
|
|
101
|
+
await this.load();
|
|
102
|
+
}
|
|
103
|
+
const list = Array.isArray(message) ? message : [message];
|
|
104
|
+
for (const msg of list) {
|
|
105
|
+
this.data.messages.push({
|
|
106
|
+
...msg,
|
|
107
|
+
timestamp: msg.timestamp ?? Date.now()
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
await this.save();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
public getState(key: string): any {
|
|
114
|
+
return this.data.state[key];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
public async setState(key: string, value: any): Promise<void> {
|
|
118
|
+
if (!this.loaded && this.filePath) {
|
|
119
|
+
await this.load();
|
|
120
|
+
}
|
|
121
|
+
this.data.state[key] = value;
|
|
122
|
+
await this.save();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
public async clear(): Promise<void> {
|
|
126
|
+
this.data.messages = [];
|
|
127
|
+
this.data.state = {};
|
|
128
|
+
await this.save();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Clean Aliases
|
|
133
|
+
export const InMemorySession = Session;
|
|
134
|
+
export const FileSessionMemory = Session;
|
|
135
|
+
|