@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.
Files changed (43) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +127 -2
  3. package/README.npm.md +128 -0
  4. package/dist/bin.js +28734 -0
  5. package/dist/liate.js +39468 -0
  6. package/dist/runtime/hono.js +28061 -0
  7. package/dist/runtime/index.js +28061 -0
  8. package/hub/agents/docgyan-agent/agent.json +27 -0
  9. package/hub/agents/docgyan-agent/agent.ts +39 -0
  10. package/hub/agents/gnani-agent/agent.json +17 -0
  11. package/hub/agents/neon-agent/agent.json +18 -0
  12. package/hub/agents/prism-agent/agent.json +17 -0
  13. package/hub/agents/sarvam-agent/agent.json +17 -0
  14. package/package.json +71 -4
  15. package/src/cli/index.ts +346 -0
  16. package/src/cli/resolver.ts +153 -0
  17. package/src/core/aum.ts +137 -0
  18. package/src/core/om.ts +159 -0
  19. package/src/core/spec.ts +112 -0
  20. package/src/core/uuid.ts +8 -0
  21. package/src/core/version.ts +2 -0
  22. package/src/layers/agent/harness.ts +118 -0
  23. package/src/layers/agent/loop.ts +203 -0
  24. package/src/layers/agent/skills.ts +302 -0
  25. package/src/layers/agent/types.ts +66 -0
  26. package/src/layers/environment/sandbox.ts +107 -0
  27. package/src/layers/environment/types.ts +23 -0
  28. package/src/layers/integration/knowledge.ts +187 -0
  29. package/src/layers/integration/lib.ts +167 -0
  30. package/src/layers/integration/memory.ts +135 -0
  31. package/src/layers/integration/repo.ts +273 -0
  32. package/src/layers/integration/types.ts +60 -0
  33. package/src/layers/llm/model.ts +916 -0
  34. package/src/layers/llm/types.ts +64 -0
  35. package/src/layers/tools/mcp.ts +236 -0
  36. package/src/layers/tools/registry.ts +307 -0
  37. package/src/layers/tools/server.ts +69 -0
  38. package/src/layers/tools/types.ts +38 -0
  39. package/src/liate.ts +65 -0
  40. package/src/routes/skills.ts +73 -0
  41. package/src/runtime/hono.ts +346 -0
  42. package/src/runtime/wasm.ts +23 -0
  43. package/src/scaffold/project.ts +188 -0
@@ -0,0 +1,203 @@
1
+ import type {
2
+ AgentTool,
3
+ AgentContext,
4
+ AgentStep,
5
+ AgentRunResult,
6
+ AgentExecutionOptions,
7
+ ToolCall,
8
+ ToolResult
9
+ } from "@/layers/agent/types";
10
+ import type { MemoryProvider } from "@/layers/integration/types";
11
+ import type { LlmMessage, LlmChatResponse } from "@/layers/llm/model";
12
+
13
+ export interface LLMFunctionCaller {
14
+ chat(messages: LlmMessage[], options?: any): Promise<LlmChatResponse & { toolCalls?: ToolCall[] }>;
15
+ }
16
+
17
+ /**
18
+ * Layer [A] Autonomous ReAct Reasoning Loop
19
+ * Orchestrates: User Query -> Reason -> Tool Action -> Observation -> Final Answer
20
+ */
21
+ export class ReActLoop {
22
+ public static async execute(
23
+ userInput: string,
24
+ llm: LLMFunctionCaller,
25
+ memory: MemoryProvider,
26
+ tools: AgentTool[] = [],
27
+ context: AgentContext,
28
+ options: AgentExecutionOptions = {}
29
+ ): Promise<AgentRunResult> {
30
+ const startTime = Date.now();
31
+ const maxSteps = options.maxSteps ?? 10;
32
+ const steps: AgentStep[] = [];
33
+ const toolMap = new Map<string, AgentTool>(tools.map((t) => [t.name, t]));
34
+
35
+ const formattedTools = tools.length > 0 ? tools.map((t) => ({
36
+ type: "function",
37
+ function: {
38
+ name: t.name,
39
+ description: t.description,
40
+ parameters: t.parameters || { type: "object", properties: {} }
41
+ }
42
+ })) : undefined;
43
+
44
+ // 1. Append user input to session memory
45
+ await memory.append({
46
+ role: "user",
47
+ content: userInput,
48
+ timestamp: startTime
49
+ });
50
+
51
+ let currentStep = 1;
52
+ let finalOutput = "";
53
+ let finalThought: string | undefined = undefined;
54
+ let finalAudioBase64: string | undefined = undefined;
55
+ let finishReason: "stop" | "max_steps_reached" | "error" = "max_steps_reached";
56
+ let usedModel = options.model || "unknown";
57
+
58
+ // 2. Build system instruction from Intent & Name (Intent IS the system prompt)
59
+ const systemInstruction = options.systemPrompt ??
60
+ `You are ${context.agentName}.
61
+ Your intent: ${context.intent || "Autonomous AI Agent"}.
62
+ Follow the ReAct methodology: Reason carefully, invoke tools when needed, observe results, and provide a clear final answer.`;
63
+
64
+ // 3. ReAct Step Loop
65
+ while (currentStep <= maxSteps) {
66
+ const stepStartTime = Date.now();
67
+
68
+ // Retrieve full accumulated conversation history from Layer [I]
69
+ const conversationHistory: LlmMessage[] = memory.getMessages().map((m) => {
70
+ const item: LlmMessage = {
71
+ role: m.role as "system" | "user" | "assistant" | "tool",
72
+ content: m.content
73
+ };
74
+ if (m.name) item.name = m.name;
75
+ if (m.toolCallId) item.tool_call_id = m.toolCallId;
76
+ if (m.toolCalls && m.toolCalls.length > 0) {
77
+ item.tool_calls = m.toolCalls.map((tc) => ({
78
+ id: tc.id,
79
+ type: "function",
80
+ function: {
81
+ name: tc.name,
82
+ arguments: JSON.stringify(tc.arguments)
83
+ }
84
+ }));
85
+ }
86
+ return item;
87
+ });
88
+
89
+ const messages: LlmMessage[] = [
90
+ { role: "system", content: systemInstruction },
91
+ ...conversationHistory
92
+ ];
93
+
94
+ // Query Layer [L] Model
95
+ const response = await llm.chat(messages, {
96
+ ...(options as any),
97
+ model: options.model,
98
+ maxTokens: options.maxTokens,
99
+ temperature: options.temperature ?? 0.2,
100
+ tools: formattedTools,
101
+ apiKey: options.apiKey
102
+ });
103
+
104
+ usedModel = response.model || usedModel;
105
+ if (response.audioBase64) {
106
+ finalAudioBase64 = response.audioBase64;
107
+ }
108
+ const thought = response.reasoningContent;
109
+ if (thought) {
110
+ finalThought = thought;
111
+ }
112
+
113
+ const requestedToolCalls: ToolCall[] = response.toolCalls || [];
114
+
115
+ // Case A: Model requested tool execution
116
+ if (requestedToolCalls.length > 0) {
117
+ await memory.append({
118
+ role: "assistant",
119
+ content: response.text || "",
120
+ reasoningContent: thought,
121
+ toolCalls: requestedToolCalls,
122
+ timestamp: stepStartTime
123
+ });
124
+
125
+ const stepResults: ToolResult[] = [];
126
+
127
+ for (const tc of requestedToolCalls) {
128
+ const tool = toolMap.get(tc.name);
129
+ let resultStr: string;
130
+
131
+ if (!tool) {
132
+ resultStr = `Error: Tool '${tc.name}' not found. Available: ${Array.from(toolMap.keys()).join(", ")}`;
133
+ } else {
134
+ try {
135
+ const res = await tool.execute(tc.arguments, context);
136
+ resultStr = typeof res === "string" ? res : JSON.stringify(res);
137
+ } catch (err: any) {
138
+ resultStr = `Error executing tool '${tc.name}': ${err.message}`;
139
+ }
140
+ }
141
+
142
+ stepResults.push({
143
+ toolCallId: tc.id,
144
+ toolName: tc.name,
145
+ result: resultStr
146
+ });
147
+
148
+ // Append tool observation to Layer [I] session memory
149
+ await memory.append({
150
+ role: "tool",
151
+ name: tc.name,
152
+ toolCallId: tc.id,
153
+ content: resultStr,
154
+ timestamp: Date.now()
155
+ });
156
+ }
157
+
158
+ steps.push({
159
+ step: currentStep,
160
+ thought,
161
+ toolCalls: requestedToolCalls,
162
+ toolResults: stepResults,
163
+ timestamp: stepStartTime
164
+ });
165
+
166
+ currentStep++;
167
+ } else {
168
+ // Case B: Final text answer produced
169
+ finalOutput = response.text;
170
+ finishReason = "stop";
171
+
172
+ steps.push({
173
+ step: currentStep,
174
+ thought,
175
+ output: finalOutput,
176
+ timestamp: stepStartTime
177
+ });
178
+
179
+ // Append final assistant reply to Layer [I] session memory
180
+ await memory.append({
181
+ role: "assistant",
182
+ content: finalOutput,
183
+ reasoningContent: thought,
184
+ timestamp: Date.now()
185
+ });
186
+
187
+ break;
188
+ }
189
+ }
190
+
191
+ return {
192
+ text: finalOutput,
193
+ thought: finalThought,
194
+ steps,
195
+ totalSteps: steps.length,
196
+ model: usedModel,
197
+ durationMs: Date.now() - startTime,
198
+ finishReason,
199
+ audioBase64: finalAudioBase64
200
+ };
201
+ }
202
+ }
203
+
@@ -0,0 +1,302 @@
1
+ // src/layers/agent/skills.ts
2
+ // Layer [A] Dynamic Skill Resolver (skills.sh 1.26M+ skills, GitHub, HTTPS & Local SKILL.md)
3
+
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, resolve as resolvePath } from "node:path";
6
+
7
+ export interface SkillSearchResult {
8
+ id: string;
9
+ source: string;
10
+ skillId: string;
11
+ name: string;
12
+ installs?: number;
13
+ }
14
+
15
+ export interface ResolvedSkill {
16
+ name: string;
17
+ slug: string;
18
+ instructions: string;
19
+ source: "skills.sh" | "github" | "local" | "inline";
20
+ cachedAt?: number;
21
+ }
22
+
23
+ export type EdgeSkill = ResolvedSkill;
24
+
25
+ const skillMemoryCache = new Map<string, ResolvedSkill>();
26
+
27
+ export class SkillResolver {
28
+ /**
29
+ * Dynamically fetch and resolve a skills.sh slug, GitHub reference, HTTPS URL, or local SKILL.md path.
30
+ */
31
+ public static async resolve(slugOrUrl: string): Promise<ResolvedSkill> {
32
+ const cleanSlug = slugOrUrl.trim();
33
+
34
+ if (skillMemoryCache.has(cleanSlug)) {
35
+ return skillMemoryCache.get(cleanSlug)!;
36
+ }
37
+
38
+ // 1. Local file path fallback
39
+ if (
40
+ cleanSlug.startsWith("./") ||
41
+ cleanSlug.startsWith("../") ||
42
+ cleanSlug.startsWith("/") ||
43
+ cleanSlug.endsWith(".md")
44
+ ) {
45
+ const fullPath = resolvePath(process.cwd(), cleanSlug);
46
+ if (existsSync(fullPath)) {
47
+ const text = readFileSync(fullPath, "utf-8");
48
+ const skill: ResolvedSkill = {
49
+ name: cleanSlug.split(/[\\/]/).pop()?.replace(/\.md$/i, "") || "local-skill",
50
+ slug: cleanSlug,
51
+ instructions: text,
52
+ source: "local",
53
+ cachedAt: Date.now(),
54
+ };
55
+ skillMemoryCache.set(cleanSlug, skill);
56
+ return skill;
57
+ }
58
+ }
59
+
60
+ // 2. Direct HTTPS URL
61
+ if (cleanSlug.startsWith("http://") || cleanSlug.startsWith("https://")) {
62
+ try {
63
+ const res = await fetch(cleanSlug, { signal: AbortSignal.timeout(6000) });
64
+ if (res.ok) {
65
+ const text = await res.text();
66
+ const skill: ResolvedSkill = {
67
+ name: cleanSlug.split("/").pop()?.replace(/\.md$/i, "") || "remote-skill",
68
+ slug: cleanSlug,
69
+ instructions: text,
70
+ source: "skills.sh",
71
+ cachedAt: Date.now(),
72
+ };
73
+ skillMemoryCache.set(cleanSlug, skill);
74
+ return skill;
75
+ }
76
+ } catch {
77
+ // Continue to fallback
78
+ }
79
+ }
80
+
81
+ // 3. skills.sh / GitHub slug (e.g. "vercel-labs/find-skills" or "skills.sh/vercel-labs/find-skills")
82
+ const id = cleanSlug.replace(/^skills\.sh\//, "").replace(/^github:/, "");
83
+ const idParts = id.split("/").filter(Boolean);
84
+
85
+ if (idParts.length >= 2) {
86
+ // 3a. skills.sh API
87
+ try {
88
+ const apiUrl = `https://skills.sh/api/v1/skills/${id}`;
89
+ const res = await fetch(apiUrl, { signal: AbortSignal.timeout(6000) });
90
+ if (res.ok) {
91
+ const data: any = await res.json();
92
+ const skillFile =
93
+ data.files?.find((f: any) => f.path === "SKILL.md" || f.path?.endsWith(".md")) ||
94
+ data.files?.[0];
95
+ const contents = skillFile?.contents || data.instructions || data.content;
96
+ if (contents) {
97
+ const skill: ResolvedSkill = {
98
+ name: idParts.slice(1).join("-"),
99
+ slug: id,
100
+ instructions: contents,
101
+ source: "skills.sh",
102
+ cachedAt: Date.now(),
103
+ };
104
+ skillMemoryCache.set(cleanSlug, skill);
105
+ return skill;
106
+ }
107
+ }
108
+ } catch {
109
+ // Fallback to GitHub raw
110
+ }
111
+
112
+ // 3b. GitHub Raw common paths
113
+ const owner = idParts[0];
114
+ const repo = idParts[1];
115
+ const targetSkill = idParts.slice(2).join("/") || repo;
116
+
117
+ const candidateUrls = [
118
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/${targetSkill}/SKILL.md`,
119
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/${targetSkill}/SKILL.md`,
120
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/productivity/${targetSkill}/SKILL.md`,
121
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/engineering/${targetSkill}/SKILL.md`,
122
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/design/${targetSkill}/SKILL.md`,
123
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/skills/${repo}/SKILL.md`,
124
+ `https://raw.githubusercontent.com/${owner}/${repo}/main/SKILL.md`,
125
+ `https://raw.githubusercontent.com/${owner}/${repo}/master/SKILL.md`,
126
+ ];
127
+
128
+ for (const url of candidateUrls) {
129
+ try {
130
+ const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
131
+ if (res.ok) {
132
+ const text = await res.text();
133
+ if (text && !text.includes("404: Not Found")) {
134
+ const skill: ResolvedSkill = {
135
+ name: targetSkill || `${owner}/${repo}`,
136
+ slug: id,
137
+ instructions: text,
138
+ source: "github",
139
+ cachedAt: Date.now(),
140
+ };
141
+ skillMemoryCache.set(cleanSlug, skill);
142
+ return skill;
143
+ }
144
+ }
145
+ } catch {
146
+ // Try next candidate
147
+ }
148
+ }
149
+
150
+ // 3c. Dynamic GitHub Tree discovery
151
+ try {
152
+ const treeRes = await fetch(
153
+ `https://api.github.com/repos/${owner}/${repo}/git/trees/main?recursive=1`,
154
+ {
155
+ headers: { "User-Agent": "OpenLiate" },
156
+ signal: AbortSignal.timeout(6000),
157
+ }
158
+ );
159
+ if (treeRes.ok) {
160
+ const treeData: any = await treeRes.json();
161
+ const shortTarget = targetSkill.replace(/^[a-z0-9]+-/i, "").toLowerCase();
162
+ const matchedPath = treeData.tree?.find((item: any) => {
163
+ const p = String(item.path || "").toLowerCase();
164
+ const isSkill = p.endsWith("skill.md") || p.endsWith("skill");
165
+ return (
166
+ isSkill &&
167
+ (p.includes(targetSkill.toLowerCase()) ||
168
+ (shortTarget.length > 4 && p.includes(shortTarget)))
169
+ );
170
+ })?.path;
171
+
172
+ if (matchedPath) {
173
+ const rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/main/${matchedPath}`;
174
+ const fileRes = await fetch(rawUrl, { signal: AbortSignal.timeout(5000) });
175
+ if (fileRes.ok) {
176
+ const text = await fileRes.text();
177
+ const skill: ResolvedSkill = {
178
+ name: targetSkill || `${owner}/${repo}`,
179
+ slug: id,
180
+ instructions: text,
181
+ source: "github",
182
+ cachedAt: Date.now(),
183
+ };
184
+ skillMemoryCache.set(cleanSlug, skill);
185
+ return skill;
186
+ }
187
+ }
188
+ }
189
+ } catch {
190
+ // Fallback to inline slug
191
+ }
192
+ }
193
+
194
+ const resolvedName =
195
+ idParts[idParts.length - 1] || cleanSlug.split("/").pop()?.replace(/\.md$/i, "") || "skill";
196
+ return {
197
+ name: resolvedName,
198
+ slug: cleanSlug,
199
+ instructions: cleanSlug,
200
+ source: "inline",
201
+ cachedAt: Date.now(),
202
+ };
203
+ }
204
+
205
+ public static async resolveAll(skills: string[]): Promise<ResolvedSkill[]> {
206
+ if (!skills || skills.length === 0) return [];
207
+ return Promise.all(skills.map((s) => this.resolve(s)));
208
+ }
209
+
210
+ public static formatSystemPrompt(skills: ResolvedSkill[]): string {
211
+ if (!skills || skills.length === 0) return "";
212
+ const blocks = skills.map(
213
+ (s) => `### Skill: ${s.name} (${s.source}: ${s.slug})\n${s.instructions.trim()}`
214
+ );
215
+ return `\n\n<skills>\n${blocks.join("\n\n")}\n</skills>`;
216
+ }
217
+
218
+ /**
219
+ * Search the public skills.sh registry (Algolia-backed, no auth required).
220
+ */
221
+ public static async search(query: string, limit = 10): Promise<SkillSearchResult[]> {
222
+ const q = query.trim();
223
+ if (!q) return [];
224
+ const url = `https://skills.sh/api/search?q=${encodeURIComponent(q)}&limit=${Math.min(Math.max(limit, 1), 25)}`;
225
+ const res = await fetch(url, { signal: AbortSignal.timeout(6000) });
226
+ if (!res.ok) {
227
+ throw new Error(`skills.sh search failed (${res.status})`);
228
+ }
229
+ const data = (await res.json()) as { skills?: SkillSearchResult[] };
230
+ return (data.skills || []).slice(0, limit);
231
+ }
232
+
233
+ /**
234
+ * Resolve a skill from skills.sh/GitHub, save SKILL.md to .liate/skills/, and add to agent.json A.skills.
235
+ */
236
+ public static async add(
237
+ slugOrUrl: string,
238
+ options: { cwd?: string; agentFile?: string } = {}
239
+ ): Promise<{ skill: ResolvedSkill; savedPath: string; updatedAgentJson: boolean }> {
240
+ const cwd = options.cwd || process.cwd();
241
+ const skill = await this.resolve(slugOrUrl);
242
+ if (skill.source === "inline") {
243
+ throw new Error(`Could not fetch SKILL.md for '${slugOrUrl}' from skills.sh or GitHub.`);
244
+ }
245
+
246
+ const safeSlug = skill.slug.replace(/[^a-zA-Z0-9_/-]/g, "-").replace(/^\/+|\/+$/g, "");
247
+ const savedPath = resolvePath(cwd, ".liate", "skills", safeSlug, "SKILL.md");
248
+ mkdirSync(dirname(savedPath), { recursive: true });
249
+ writeFileSync(savedPath, skill.instructions, "utf-8");
250
+
251
+ let updatedAgentJson = false;
252
+ const agentPath = resolvePath(cwd, options.agentFile || "agent.json");
253
+ if (existsSync(agentPath)) {
254
+ const raw = JSON.parse(readFileSync(agentPath, "utf-8"));
255
+ const aKey = raw.A ? "A" : raw.Agent ? "Agent" : raw.agent ? "agent" : "A";
256
+ raw[aKey] = typeof raw[aKey] === "object" && raw[aKey] ? raw[aKey] : { name: String(raw[aKey] || "agent") };
257
+ const existing: string[] = Array.isArray(raw[aKey].skills) ? raw[aKey].skills : [];
258
+ if (!existing.includes(slugOrUrl)) {
259
+ raw[aKey].skills = [...existing, slugOrUrl];
260
+ writeFileSync(agentPath, JSON.stringify(raw, null, 2) + "\n", "utf-8");
261
+ updatedAgentJson = true;
262
+ }
263
+ }
264
+
265
+ return { skill, savedPath, updatedAgentJson };
266
+ }
267
+
268
+ /**
269
+ * Refresh all skills listed in agent.json from upstream GitHub / HTTPS sources.
270
+ */
271
+ public static async update(
272
+ options: { cwd?: string; agentFile?: string } = {}
273
+ ): Promise<{ updated: { slug: string; source: string; bytes: number }[] }> {
274
+ const cwd = options.cwd || process.cwd();
275
+ const agentPath = resolvePath(cwd, options.agentFile || "agent.json");
276
+ if (!existsSync(agentPath)) {
277
+ return { updated: [] };
278
+ }
279
+ const raw = JSON.parse(readFileSync(agentPath, "utf-8"));
280
+ const aObj = raw.A || raw.Agent || raw.agent || {};
281
+ const slugs: string[] = Array.isArray(aObj.skills) ? aObj.skills : [];
282
+
283
+ this.clearCache();
284
+ const updated: { slug: string; source: string; bytes: number }[] = [];
285
+ for (const slug of slugs) {
286
+ const { skill } = await this.add(slug, { cwd, agentFile: options.agentFile });
287
+ updated.push({ slug, source: skill.source, bytes: skill.instructions.length });
288
+ }
289
+ return { updated };
290
+ }
291
+
292
+ public static listCached(): ResolvedSkill[] {
293
+ return Array.from(skillMemoryCache.values());
294
+ }
295
+
296
+ public static clearCache(): void {
297
+ skillMemoryCache.clear();
298
+ }
299
+ }
300
+
301
+ export const EdgeSkillResolver = SkillResolver;
302
+
@@ -0,0 +1,66 @@
1
+ export interface ToolCall {
2
+ id: string;
3
+ name: string;
4
+ arguments: Record<string, any>;
5
+ }
6
+
7
+ export interface ToolResult {
8
+ toolCallId: string;
9
+ toolName: string;
10
+ result: string;
11
+ }
12
+
13
+ export interface AgentTool {
14
+ name: string;
15
+ description: string;
16
+ parameters?: Record<string, any>;
17
+ execute: (args: Record<string, any>, context?: AgentContext) => Promise<string | Record<string, any>>;
18
+ }
19
+
20
+ export interface AgentContext {
21
+ agentName: string;
22
+ intent: string;
23
+ sessionId?: string;
24
+ state: Record<string, any>;
25
+ }
26
+
27
+ export interface AgentStep {
28
+ step: number;
29
+ thought?: string;
30
+ toolCalls?: ToolCall[];
31
+ toolResults?: ToolResult[];
32
+ output?: string;
33
+ timestamp: number;
34
+ }
35
+
36
+ export interface AgentRunResult {
37
+ text: string;
38
+ thought?: string;
39
+ steps: AgentStep[];
40
+ totalSteps: number;
41
+ model: string;
42
+ durationMs: number;
43
+ finishReason: "stop" | "max_steps_reached" | "error";
44
+ audioBase64?: string;
45
+ }
46
+
47
+ export interface AgentExecutionOptions {
48
+ model?: string;
49
+ maxTokens?: number;
50
+ maxSteps?: number;
51
+ systemPrompt?: string;
52
+ temperature?: number;
53
+ tools?: AgentTool[];
54
+ skills?: string[];
55
+ apiKey?: string;
56
+ }
57
+
58
+ export interface AgentConfig {
59
+ name: string;
60
+ intent?: string;
61
+ model?: string;
62
+ maxSteps?: number;
63
+ tools?: AgentTool[];
64
+ skills?: string[];
65
+ }
66
+
@@ -0,0 +1,107 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import os from "os";
4
+ import type { SandboxConfig } from "@/layers/environment/types";
5
+
6
+ export class EnvironmentResolver {
7
+ /**
8
+ * Automatically loads .env and .env.local files from cwd, module dir, parent dirs, and home dir
9
+ */
10
+ public static loadEnv(targetPath?: string): void {
11
+ // 1. Load keys from ~/.liate/config.json if available
12
+ try {
13
+ const configPath = path.resolve(os.homedir(), ".liate", "config.json");
14
+ if (fs.existsSync(configPath)) {
15
+ const raw = fs.readFileSync(configPath, "utf-8");
16
+ const parsed = JSON.parse(raw);
17
+ if (parsed.keys && typeof parsed.keys === "object") {
18
+ for (const [k, v] of Object.entries(parsed.keys)) {
19
+ if (!process.env[k]) {
20
+ process.env[k] = String(v);
21
+ }
22
+ }
23
+ }
24
+ }
25
+ } catch {}
26
+
27
+ // 2. Load .env files from candidate locations
28
+ const candidates = [
29
+ path.resolve(process.cwd(), ".env"),
30
+ path.resolve(process.cwd(), ".env.local"),
31
+ path.resolve(process.cwd(), ".liate", ".env"),
32
+ path.resolve(process.cwd(), "..", ".env"),
33
+ path.resolve(process.cwd(), "..", ".env.local"),
34
+ targetPath ? path.resolve(path.dirname(targetPath), ".env") : "",
35
+ targetPath ? path.resolve(path.dirname(targetPath), ".env.local") : "",
36
+ path.resolve(os.homedir(), ".liate", ".env"),
37
+ path.resolve(os.homedir(), ".liate", "config.env"),
38
+ path.resolve(os.homedir(), ".env")
39
+ ].filter(Boolean);
40
+
41
+ for (const file of candidates) {
42
+ if (fs.existsSync(file)) {
43
+ try {
44
+ const content = fs.readFileSync(file, "utf-8");
45
+ for (const line of content.split("\n")) {
46
+ const trimmed = line.trim();
47
+ if (!trimmed || trimmed.startsWith("#")) continue;
48
+ const [k, ...v] = trimmed.split("=");
49
+ if (k && !process.env[k.trim()]) {
50
+ process.env[k.trim()] = v.join("=").trim().replace(/^["']|["']$/g, "");
51
+ }
52
+ }
53
+ } catch {}
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Expands variable references (e.g. "$API_KEY" -> process.env.API_KEY)
60
+ */
61
+ public static resolve(
62
+ declaredEnv: Record<string, string | undefined>,
63
+ systemEnv: Record<string, string | undefined> = process.env
64
+ ): Record<string, string> {
65
+ const resolved: Record<string, string> = {};
66
+
67
+ for (const [key, val] of Object.entries(declaredEnv)) {
68
+ if (typeof val === "string" && val.startsWith("$")) {
69
+ const varName = val.slice(1);
70
+ resolved[key] = systemEnv[varName] || "";
71
+ } else {
72
+ resolved[key] = String(val ?? "");
73
+ }
74
+ }
75
+
76
+ return resolved;
77
+ }
78
+
79
+ /**
80
+ * Masks sensitive credentials in logs (e.g. sk_live_1234... -> sk_l***5678)
81
+ */
82
+ public static maskSecret(value: string): string {
83
+ if (!value || value.length <= 8) {
84
+ return "******";
85
+ }
86
+ const prefix = value.slice(0, 4);
87
+ const suffix = value.slice(-4);
88
+ return `${prefix}***${suffix}`;
89
+ }
90
+
91
+ /**
92
+ * Constructs an isolated sandbox configuration
93
+ */
94
+ public static createSandbox(
95
+ env: Record<string, string | undefined>,
96
+ options: Partial<SandboxConfig> = {}
97
+ ): SandboxConfig {
98
+ const resolvedEnv = this.resolve(env);
99
+
100
+ return {
101
+ allowedDomains: options.allowedDomains || [],
102
+ denyNetwork: options.denyNetwork ?? false,
103
+ timeoutMs: options.timeoutMs ?? 30000,
104
+ env: resolvedEnv
105
+ };
106
+ }
107
+ }
@@ -0,0 +1,23 @@
1
+ export interface EnvironmentSecrets {
2
+ [key: string]: string | undefined;
3
+ }
4
+
5
+ export interface SandboxGuardrails {
6
+ maxExecutionTimeMs?: number;
7
+ allowedDomains?: string[];
8
+ blockNetwork?: boolean;
9
+ }
10
+
11
+ export interface ResolvedEnvironment {
12
+ secrets: Record<string, string>;
13
+ guardrails: SandboxGuardrails;
14
+ }
15
+
16
+ export interface SandboxConfig {
17
+ allowedDomains: string[];
18
+ denyNetwork: boolean;
19
+ timeoutMs?: number;
20
+ maxExecutionTimeMs?: number;
21
+ env: Record<string, string>;
22
+ }
23
+