@almadar/agent 2.0.5 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Builder Tools
3
+ *
4
+ * Creates the safe subset of agent tools for web/builder use.
5
+ * No filesystem, git, design-system, or deploy tools.
6
+ *
7
+ * Included:
8
+ * - validate: Validate a schema string
9
+ * - generate_orbital: Generate a single orbital via LLM subagent
10
+ * - combine_orbitals: Deterministic merge of orbitals into schema
11
+ * - query_structure: Introspect a schema's orbital/entity/trait layout
12
+ * - neural_generate: Run GFlowNet pipeline (if PythonExecutor provided)
13
+ * - auto_fix: LLM-based validation error repair
14
+ *
15
+ * Excluded:
16
+ * - compile, verify, lint, scaffold, git, filesystem,
17
+ * design-system, deploy, screenshot, console
18
+ */
19
+ import type { BuilderConfig, BuilderToolDefinition } from './types.js';
20
+ /**
21
+ * Create the builder-mode tool set.
22
+ *
23
+ * @param config - Builder configuration with injectable executors
24
+ * @returns Array of tool definitions ready for use with createSkillAgent
25
+ */
26
+ export declare function createBuilderTools(config: BuilderConfig): BuilderToolDefinition[];
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Builder Module
3
+ *
4
+ * Convenience exports for builder-mode consumers (server, web).
5
+ * Pre-configured for schema generation without workspace/git/filesystem.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ export { createBuilderTools } from './builder-tools.js';
10
+ export type { BuilderConfig, BuilderToolDefinition, CommandExecutor, PythonExecutor } from './types.js';
@@ -0,0 +1,424 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/neural/masar-client.ts
12
+ var masar_client_exports = {};
13
+ __export(masar_client_exports, {
14
+ MasarClient: () => MasarClient
15
+ });
16
+ function toNeuralPipelineResult(data) {
17
+ return {
18
+ success: data.success,
19
+ validationPass: data.validation_pass,
20
+ compilationPass: false,
21
+ goalMatch: data.goal_match ?? 0,
22
+ totalSteps: data.total_steps ?? 0,
23
+ fixRounds: data.fix_rounds ?? 0,
24
+ llmCalls: data.llm_calls ?? 0,
25
+ durationMs: data.duration_ms ?? 0,
26
+ schema: data.schema ?? null,
27
+ schemaPath: null,
28
+ actions: data.actions ?? [],
29
+ validationErrors: data.validation_errors ?? [],
30
+ compilationErrors: [],
31
+ error: data.error ?? null
32
+ };
33
+ }
34
+ function makeErrorResult(error) {
35
+ return {
36
+ success: false,
37
+ validationPass: false,
38
+ compilationPass: false,
39
+ goalMatch: 0,
40
+ totalSteps: 0,
41
+ fixRounds: 0,
42
+ llmCalls: 0,
43
+ durationMs: 0,
44
+ schema: null,
45
+ schemaPath: null,
46
+ actions: [],
47
+ validationErrors: [],
48
+ compilationErrors: [],
49
+ error
50
+ };
51
+ }
52
+ var MasarClient;
53
+ var init_masar_client = __esm({
54
+ "src/neural/masar-client.ts"() {
55
+ MasarClient = class {
56
+ constructor(options) {
57
+ this.baseUrl = (options?.baseUrl ?? process.env["MASAR_URL"] ?? "https://masar-345008351456.europe-west4.run.app").replace(/\/$/, "");
58
+ this.timeoutMs = options?.timeoutMs ?? 12e4;
59
+ this.onProgress = options?.onProgress ?? null;
60
+ }
61
+ /**
62
+ * Generate an .orb schema from a natural language prompt.
63
+ *
64
+ * Sends the prompt to the Masar server which runs the full neural pipeline
65
+ * (goal parsing, GFlowNet generation, validation, LLM fix loop) and returns
66
+ * the result.
67
+ */
68
+ async generate(prompt) {
69
+ this.onProgress?.("request", `Sending prompt to Masar at ${this.baseUrl}`);
70
+ const url = `${this.baseUrl}/generate`;
71
+ const controller = new AbortController();
72
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
73
+ try {
74
+ const response = await fetch(url, {
75
+ method: "POST",
76
+ headers: { "Content-Type": "application/json" },
77
+ body: JSON.stringify({ prompt }),
78
+ signal: controller.signal
79
+ });
80
+ if (!response.ok) {
81
+ const body = await response.text().catch(() => "");
82
+ return makeErrorResult(
83
+ `Masar server returned ${response.status} ${response.statusText}${body ? `: ${body}` : ""}`
84
+ );
85
+ }
86
+ const data = await response.json();
87
+ this.onProgress?.("response", data.success ? "Generation succeeded" : `Generation failed: ${data.error ?? "unknown"}`);
88
+ return toNeuralPipelineResult(data);
89
+ } catch (err) {
90
+ if (err instanceof DOMException && err.name === "AbortError") {
91
+ return makeErrorResult(`Masar request timed out after ${this.timeoutMs}ms`);
92
+ }
93
+ const message = err instanceof Error ? err.message : String(err);
94
+ return makeErrorResult(`Masar request failed: ${message}`);
95
+ } finally {
96
+ clearTimeout(timeout);
97
+ }
98
+ }
99
+ };
100
+ }
101
+ });
102
+
103
+ // src/builder/builder-tools.ts
104
+ function createBuilderTools(config) {
105
+ const tools = [
106
+ createValidateBuilderTool(config),
107
+ createGenerateOrbitalBuilderTool(),
108
+ createCombineOrbitalsBuilderTool(),
109
+ createQueryStructureBuilderTool(),
110
+ createAutoFixBuilderTool(config)
111
+ ];
112
+ if (config.pythonExecutor) {
113
+ tools.push(createNeuralGenerateBuilderTool());
114
+ }
115
+ return tools;
116
+ }
117
+ function createValidateBuilderTool(config) {
118
+ return {
119
+ name: "validate",
120
+ description: "Validate an .orb schema. Returns errors and warnings.",
121
+ parameters: {
122
+ type: "object",
123
+ properties: {
124
+ schema: { type: "string", description: "The .orb schema JSON string to validate" }
125
+ },
126
+ required: ["schema"]
127
+ },
128
+ async execute(args) {
129
+ const schema = args.schema;
130
+ return config.executor.validateSchema(schema);
131
+ }
132
+ };
133
+ }
134
+ function createGenerateOrbitalBuilderTool() {
135
+ return {
136
+ name: "generate_orbital",
137
+ description: "Generate a single orbital definition from a spec using an LLM subagent.",
138
+ parameters: {
139
+ type: "object",
140
+ properties: {
141
+ name: { type: "string", description: "Orbital name" },
142
+ entityName: { type: "string", description: "Entity name (PascalCase)" },
143
+ traitNames: { type: "array", description: "List of trait names" },
144
+ fields: { type: "array", description: "Optional field definitions [{name, type, required?}]" },
145
+ description: { type: "string", description: "Optional entity description" },
146
+ provider: { type: "string", description: "LLM provider (deepseek, anthropic, openrouter)" },
147
+ model: { type: "string", description: "LLM model name" }
148
+ },
149
+ required: ["name", "entityName", "traitNames"]
150
+ },
151
+ async execute(args) {
152
+ const { getSubagentSystemPrompt } = await import('@almadar/skills');
153
+ const { LLMClient } = await import('@almadar/llm');
154
+ const systemPrompt = getSubagentSystemPrompt();
155
+ const provider = args.provider ?? "deepseek";
156
+ const model = args.model ?? "deepseek-chat";
157
+ const fields = args.fields;
158
+ const fieldsList = fields?.length ? fields.map((f) => ` - ${f.name}: ${f.type}${f.required ? " (required)" : ""}`).join("\n") : " (infer appropriate fields from the entity name and description)";
159
+ const userPrompt = `Generate a complete FullOrbitalUnit for this orbital:
160
+
161
+ Name: ${args.name}
162
+ Entity: ${args.entityName}
163
+ Traits: ${args.traitNames.join(", ")}
164
+ ${args.description ? `Description: ${args.description}` : ""}
165
+
166
+ Fields:
167
+ ${fieldsList}
168
+
169
+ Return ONLY valid JSON matching the FullOrbitalUnit schema. No markdown fences, no explanation text.`;
170
+ const client = new LLMClient({
171
+ provider,
172
+ model
173
+ });
174
+ const text = await client.callRaw({
175
+ systemPrompt,
176
+ userPrompt,
177
+ maxTokens: 8192
178
+ });
179
+ const orbital = extractJson(text);
180
+ if (!orbital) {
181
+ return { success: false, error: "Failed to parse orbital JSON from LLM response" };
182
+ }
183
+ const obj = orbital;
184
+ if (!obj.name || !obj.entity || !obj.traits) {
185
+ return { success: false, error: "Generated orbital missing required fields (name, entity, traits)" };
186
+ }
187
+ return { success: true, orbital };
188
+ }
189
+ };
190
+ }
191
+ function createCombineOrbitalsBuilderTool() {
192
+ return {
193
+ name: "combine_orbitals",
194
+ description: "Combine multiple orbital definitions into a single .orb schema JSON string.",
195
+ parameters: {
196
+ type: "object",
197
+ properties: {
198
+ appName: { type: "string", description: "Application name" },
199
+ orbitals: { type: "array", description: "Array of orbital definition objects" }
200
+ },
201
+ required: ["appName", "orbitals"]
202
+ },
203
+ async execute(args) {
204
+ const orbitals = args.orbitals;
205
+ const appName = args.appName;
206
+ if (!orbitals.length) {
207
+ return { success: false, error: "No orbitals provided" };
208
+ }
209
+ const schema = {
210
+ name: appName,
211
+ version: "1.0.0",
212
+ orbitals
213
+ };
214
+ return {
215
+ success: true,
216
+ schema: JSON.stringify(schema, null, 2),
217
+ orbitalCount: orbitals.length
218
+ };
219
+ }
220
+ };
221
+ }
222
+ function createQueryStructureBuilderTool() {
223
+ return {
224
+ name: "query_structure",
225
+ description: "Get a lightweight map of a schema (orbital names, entities, traits, field counts).",
226
+ parameters: {
227
+ type: "object",
228
+ properties: {
229
+ schema: { type: "string", description: "The .orb schema JSON string" }
230
+ },
231
+ required: ["schema"]
232
+ },
233
+ async execute(args) {
234
+ try {
235
+ const parsed = JSON.parse(args.schema);
236
+ const orbitals = parsed.orbitals ?? [];
237
+ return {
238
+ name: parsed.name,
239
+ orbitals: orbitals.map((o) => ({
240
+ name: o.name,
241
+ entityName: getEntityName(o.entity),
242
+ traits: getTraitNames(o.traits ?? []),
243
+ totalFields: countFields(o.entity),
244
+ totalStates: countStates(o.traits ?? [])
245
+ }))
246
+ };
247
+ } catch (err) {
248
+ return { error: `Failed to parse schema: ${err instanceof Error ? err.message : String(err)}` };
249
+ }
250
+ }
251
+ };
252
+ }
253
+ function createAutoFixBuilderTool(config) {
254
+ return {
255
+ name: "auto_fix",
256
+ description: "Attempt to fix validation errors in a schema using LLM repair.",
257
+ parameters: {
258
+ type: "object",
259
+ properties: {
260
+ schema: { type: "string", description: "The .orb schema JSON string with errors" },
261
+ errors: { type: "array", description: "Validation errors to fix [{code, message}]" },
262
+ warnings: { type: "array", description: "Validation warnings to fix [{code, message}]" },
263
+ provider: { type: "string", description: "LLM provider" },
264
+ model: { type: "string", description: "LLM model" }
265
+ },
266
+ required: ["schema", "errors"]
267
+ },
268
+ async execute(args) {
269
+ const { getSubagentSystemPrompt } = await import('@almadar/skills');
270
+ const { LLMClient } = await import('@almadar/llm');
271
+ const orbitalKnowledge = getSubagentSystemPrompt();
272
+ const provider = args.provider ?? "deepseek";
273
+ const model = args.model ?? "deepseek-chat";
274
+ const errors = args.errors;
275
+ const warnings = args.warnings ?? [];
276
+ const issues = [
277
+ ...errors.map((e) => `ERROR [${e.code}]: ${e.message}`),
278
+ ...warnings.map((w) => `WARNING [${w.code}]: ${w.message}`)
279
+ ].join("\n");
280
+ const client = new LLMClient({
281
+ provider,
282
+ model
283
+ });
284
+ const text = await client.callRaw({
285
+ systemPrompt: `You are a schema repair tool for .orb orbital schemas.
286
+
287
+ ${orbitalKnowledge}
288
+
289
+ Return ONLY valid JSON.`,
290
+ userPrompt: `Fix ALL validation errors and warnings in this schema.
291
+
292
+ ISSUES:
293
+ ${issues}
294
+
295
+ SCHEMA:
296
+ ${args.schema}
297
+
298
+ Return the COMPLETE corrected schema as valid JSON.`,
299
+ maxTokens: 8192
300
+ });
301
+ const fixed = extractJson(text);
302
+ if (!fixed) {
303
+ return { success: false, error: "Failed to parse fixed schema from LLM response" };
304
+ }
305
+ const fixedStr = JSON.stringify(fixed, null, 2);
306
+ const valResult = await config.executor.validateSchema(fixedStr);
307
+ return {
308
+ success: valResult.success,
309
+ schema: fixedStr,
310
+ remainingErrors: valResult.errors.length,
311
+ remainingWarnings: valResult.warnings.length
312
+ };
313
+ }
314
+ };
315
+ }
316
+ function createNeuralGenerateBuilderTool(config) {
317
+ return {
318
+ name: "neural_generate",
319
+ description: "Generate a schema using the GFlowNet neural pipeline. Fast (2-10s) but best for simple apps (1-2 entities).",
320
+ parameters: {
321
+ type: "object",
322
+ properties: {
323
+ prompt: { type: "string", description: "Natural language description of the app to build" },
324
+ provider: { type: "string", description: "LLM provider for goal parsing and auto-fix" },
325
+ model: { type: "string", description: "LLM model" },
326
+ samples: { type: "number", description: "Number of GFlowNet samples (default: 5)" },
327
+ temperature: { type: "number", description: "Sampling temperature (default: 0.8)" }
328
+ },
329
+ required: ["prompt"]
330
+ },
331
+ async execute(args) {
332
+ const { MasarClient: MasarClient2 } = await Promise.resolve().then(() => (init_masar_client(), masar_client_exports));
333
+ const client = new MasarClient2({
334
+ timeoutMs: 12e4
335
+ });
336
+ const result = await client.generate(args.prompt);
337
+ return result;
338
+ }
339
+ };
340
+ }
341
+ function getEntityName(entity) {
342
+ if (!entity) return "Unknown";
343
+ if (typeof entity === "string") return entity.replace(".entity", "");
344
+ if (typeof entity === "object" && entity !== null && "name" in entity) {
345
+ return entity.name;
346
+ }
347
+ return "Unknown";
348
+ }
349
+ function getTraitNames(traits) {
350
+ const names = [];
351
+ for (const t of traits) {
352
+ if (typeof t === "object" && t !== null) {
353
+ if ("ref" in t) names.push(t.ref);
354
+ else if ("name" in t) names.push(t.name);
355
+ }
356
+ }
357
+ return names;
358
+ }
359
+ function countFields(entity) {
360
+ if (!entity || typeof entity !== "object") return 0;
361
+ const e = entity;
362
+ return Array.isArray(e.fields) ? e.fields.length : 0;
363
+ }
364
+ function countStates(traits) {
365
+ let total = 0;
366
+ for (const t of traits) {
367
+ if (typeof t === "object" && t !== null && "stateMachine" in t) {
368
+ const sm = t.stateMachine;
369
+ if (sm?.states) total += sm.states.length;
370
+ }
371
+ }
372
+ return total;
373
+ }
374
+ function extractJson(text) {
375
+ try {
376
+ return JSON.parse(text.trim());
377
+ } catch {
378
+ }
379
+ const fenceMatch = /```(?:json)?\s*\n?([\s\S]*?)\n?```/.exec(text);
380
+ if (fenceMatch) {
381
+ try {
382
+ return JSON.parse(fenceMatch[1].trim());
383
+ } catch {
384
+ }
385
+ }
386
+ const braceStart = text.indexOf("{");
387
+ if (braceStart >= 0) {
388
+ let depth = 0;
389
+ let inString = false;
390
+ let escape = false;
391
+ for (let i = braceStart; i < text.length; i++) {
392
+ const ch = text[i];
393
+ if (escape) {
394
+ escape = false;
395
+ continue;
396
+ }
397
+ if (ch === "\\" && inString) {
398
+ escape = true;
399
+ continue;
400
+ }
401
+ if (ch === '"') {
402
+ inString = !inString;
403
+ continue;
404
+ }
405
+ if (inString) continue;
406
+ if (ch === "{") depth++;
407
+ if (ch === "}") {
408
+ depth--;
409
+ if (depth === 0) {
410
+ try {
411
+ return JSON.parse(text.slice(braceStart, i + 1));
412
+ } catch {
413
+ }
414
+ break;
415
+ }
416
+ }
417
+ }
418
+ }
419
+ return null;
420
+ }
421
+
422
+ export { createBuilderTools };
423
+ //# sourceMappingURL=index.js.map
424
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/neural/masar-client.ts","../../src/builder/builder-tools.ts"],"names":["MasarClient"],"mappings":";;;;;;;;;;;AAAA,IAAA,oBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,oBAAA,EAAA;AAAA,EAAA,WAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AA0GA,SAAS,uBAAuB,IAAA,EAAmD;AACjF,EAAA,OAAO;AAAA,IACL,SAAS,IAAA,CAAK,OAAA;AAAA,IACd,gBAAgB,IAAA,CAAK,eAAA;AAAA,IACrB,eAAA,EAAiB,KAAA;AAAA,IACjB,SAAA,EAAW,KAAK,UAAA,IAAc,CAAA;AAAA,IAC9B,UAAA,EAAY,KAAK,WAAA,IAAe,CAAA;AAAA,IAChC,SAAA,EAAW,KAAK,UAAA,IAAc,CAAA;AAAA,IAC9B,QAAA,EAAU,KAAK,SAAA,IAAa,CAAA;AAAA,IAC5B,UAAA,EAAY,KAAK,WAAA,IAAe,CAAA;AAAA,IAChC,MAAA,EAAQ,KAAK,MAAA,IAAU,IAAA;AAAA,IACvB,UAAA,EAAY,IAAA;AAAA,IACZ,OAAA,EAAS,IAAA,CAAK,OAAA,IAAW,EAAC;AAAA,IAC1B,gBAAA,EAAkB,IAAA,CAAK,iBAAA,IAAqB,EAAC;AAAA,IAC7C,mBAAmB,EAAC;AAAA,IACpB,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,MAAA,MAAM,EAAA,GAAK,KAAK,CAAC,CAAA;AACjB,MAAA,IAAI,MAAA,EAAQ;AAAE,QAAA,MAAA,GAAS,KAAA;AAAO,QAAA;AAAA,MAAU;AACxC,MAAA,IAAI,EAAA,KAAO,QAAQ,QAAA,EAAU;AAAE,QAAA,MAAA,GAAS,IAAA;AAAM,QAAA;AAAA,MAAU;AACxD,MAAA,IAAI,OAAO,GAAA,EAAK;AAAE,QAAA,QAAA,GAAW,CAAC,QAAA;AAAU,QAAA;AAAA,MAAU;AAClD,MAAA,IAAI,QAAA,EAAU;AACd,MAAA,IAAI,OAAO,GAAA,EAAK,KAAA,EAAA;AAChB,MAAA,IAAI,OAAO,GAAA,EAAK;AACd,QAAA,KAAA,EAAA;AACA,QAAA,IAAI,UAAU,CAAA,EAAG;AACf,UAAA,IAAI;AAAE,YAAA,OAAO,KAAK,KAAA,CAAM,IAAA,CAAK,MAAM,UAAA,EAAY,CAAA,GAAI,CAAC,CAAC,CAAA;AAAA,UAAG,CAAA,CAAA,MAAQ;AAAA,UAAa;AAC7E,UAAA;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,EAAA,OAAO,IAAA;AACT","file":"index.js","sourcesContent":["/**\n * Masar HTTP Client\n *\n * Calls the Masar server's /generate endpoint via HTTP instead of\n * orchestrating the neural pipeline (GFlowNet + LLM fix loop) directly.\n *\n * The Masar server runs the full pipeline server-side and returns\n * a NeuralPipelineResult-compatible response.\n */\n\nimport type { NeuralPipelineResult } from './types.js';\n\n/** Response shape returned by the Masar /generate endpoint (snake_case from Python). */\ninterface MasarGenerateResponse {\n success: boolean;\n schema: string | null;\n validation_pass: boolean;\n goal_match: number;\n total_steps: number;\n fix_rounds: number;\n llm_calls: number;\n duration_ms: number;\n actions: string[];\n validation_errors: string[];\n error: string | null;\n}\n\n/** Options for constructing a MasarClient. */\nexport interface MasarClientOptions {\n /** Base URL of the Masar server. Defaults to MASAR_URL env var or http://localhost:8080 */\n baseUrl?: string;\n /** Request timeout in milliseconds. Defaults to 120000 (2 minutes). */\n timeoutMs?: number;\n /** Optional callback for progress updates. */\n onProgress?: (phase: string, detail: string) => void;\n}\n\n/**\n * HTTP client for the Masar schema generation server.\n *\n * Usage:\n * ```ts\n * const client = new MasarClient();\n * const result = await client.generate('Build a todo app with projects and tasks');\n * ```\n */\nexport class MasarClient {\n private readonly baseUrl: string;\n private readonly timeoutMs: number;\n private readonly onProgress: ((phase: string, detail: string) => void) | null;\n\n constructor(options?: MasarClientOptions) {\n this.baseUrl = (options?.baseUrl ?? process.env['MASAR_URL'] ?? 'https://masar-345008351456.europe-west4.run.app').replace(/\\/$/, '');\n this.timeoutMs = options?.timeoutMs ?? 120_000;\n this.onProgress = options?.onProgress ?? null;\n }\n\n /**\n * Generate an .orb schema from a natural language prompt.\n *\n * Sends the prompt to the Masar server which runs the full neural pipeline\n * (goal parsing, GFlowNet generation, validation, LLM fix loop) and returns\n * the result.\n */\n async generate(prompt: string): Promise<NeuralPipelineResult> {\n this.onProgress?.('request', `Sending prompt to Masar at ${this.baseUrl}`);\n\n const url = `${this.baseUrl}/generate`;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ prompt }),\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n return makeErrorResult(\n `Masar server returned ${response.status} ${response.statusText}${body ? `: ${body}` : ''}`,\n );\n }\n\n const data: MasarGenerateResponse = await response.json() as MasarGenerateResponse;\n this.onProgress?.('response', data.success ? 'Generation succeeded' : `Generation failed: ${data.error ?? 'unknown'}`);\n\n return toNeuralPipelineResult(data);\n } catch (err: unknown) {\n if (err instanceof DOMException && err.name === 'AbortError') {\n return makeErrorResult(`Masar request timed out after ${this.timeoutMs}ms`);\n }\n const message = err instanceof Error ? err.message : String(err);\n return makeErrorResult(`Masar request failed: ${message}`);\n } finally {\n clearTimeout(timeout);\n }\n }\n}\n\n/**\n * Map the Masar server response to a NeuralPipelineResult.\n * Provides defaults for any missing fields so the result always satisfies the full interface.\n */\nfunction toNeuralPipelineResult(data: MasarGenerateResponse): NeuralPipelineResult {\n return {\n success: data.success,\n validationPass: data.validation_pass,\n compilationPass: false,\n goalMatch: data.goal_match ?? 0,\n totalSteps: data.total_steps ?? 0,\n fixRounds: data.fix_rounds ?? 0,\n llmCalls: data.llm_calls ?? 0,\n durationMs: data.duration_ms ?? 0,\n schema: data.schema ?? null,\n schemaPath: null,\n actions: data.actions ?? [],\n validationErrors: data.validation_errors ?? [],\n compilationErrors: [],\n error: data.error ?? null,\n };\n}\n\nfunction makeErrorResult(error: string): NeuralPipelineResult {\n return {\n success: false,\n validationPass: false,\n compilationPass: false,\n goalMatch: 0,\n totalSteps: 0,\n fixRounds: 0,\n llmCalls: 0,\n durationMs: 0,\n schema: null,\n schemaPath: null,\n actions: [],\n validationErrors: [],\n compilationErrors: [],\n error,\n };\n}\n","/**\n * Builder Tools\n *\n * Creates the safe subset of agent tools for web/builder use.\n * No filesystem, git, design-system, or deploy tools.\n *\n * Included:\n * - validate: Validate a schema string\n * - generate_orbital: Generate a single orbital via LLM subagent\n * - combine_orbitals: Deterministic merge of orbitals into schema\n * - query_structure: Introspect a schema's orbital/entity/trait layout\n * - neural_generate: Run GFlowNet pipeline (if PythonExecutor provided)\n * - auto_fix: LLM-based validation error repair\n *\n * Excluded:\n * - compile, verify, lint, scaffold, git, filesystem,\n * design-system, deploy, screenshot, console\n */\n\nimport type { BuilderConfig, BuilderToolDefinition } from './types.js';\nimport type { ValidationResult } from '../neural/types.js';\n\n/**\n * Create the builder-mode tool set.\n *\n * @param config - Builder configuration with injectable executors\n * @returns Array of tool definitions ready for use with createSkillAgent\n */\nexport function createBuilderTools(config: BuilderConfig): BuilderToolDefinition[] {\n const tools: BuilderToolDefinition[] = [\n createValidateBuilderTool(config),\n createGenerateOrbitalBuilderTool(),\n createCombineOrbitalsBuilderTool(),\n createQueryStructureBuilderTool(),\n createAutoFixBuilderTool(config),\n ];\n\n if (config.pythonExecutor) {\n tools.push(createNeuralGenerateBuilderTool(config));\n }\n\n return tools;\n}\n\n// ============================================================================\n// Tool Implementations\n// ============================================================================\n\nfunction createValidateBuilderTool(config: BuilderConfig): BuilderToolDefinition {\n return {\n name: 'validate',\n description: 'Validate an .orb schema. Returns errors and warnings.',\n parameters: {\n type: 'object',\n properties: {\n schema: { type: 'string', description: 'The .orb schema JSON string to validate' },\n },\n required: ['schema'],\n },\n async execute(args) {\n const schema = args.schema as string;\n return config.executor.validateSchema(schema);\n },\n };\n}\n\nfunction createGenerateOrbitalBuilderTool(): BuilderToolDefinition {\n return {\n name: 'generate_orbital',\n description: 'Generate a single orbital definition from a spec using an LLM subagent.',\n parameters: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Orbital name' },\n entityName: { type: 'string', description: 'Entity name (PascalCase)' },\n traitNames: { type: 'array', description: 'List of trait names' },\n fields: { type: 'array', description: 'Optional field definitions [{name, type, required?}]' },\n description: { type: 'string', description: 'Optional entity description' },\n provider: { type: 'string', description: 'LLM provider (deepseek, anthropic, openrouter)' },\n model: { type: 'string', description: 'LLM model name' },\n },\n required: ['name', 'entityName', 'traitNames'],\n },\n async execute(args) {\n const { getSubagentSystemPrompt } = await import('@almadar/skills');\n const { LLMClient } = await import('@almadar/llm');\n\n const systemPrompt = getSubagentSystemPrompt();\n const provider = (args.provider as string) ?? 'deepseek';\n const model = (args.model as string) ?? 'deepseek-chat';\n\n const fields = args.fields as Array<{ name: string; type: string; required?: boolean }> | undefined;\n const fieldsList = fields?.length\n ? fields.map((f) => ` - ${f.name}: ${f.type}${f.required ? ' (required)' : ''}`).join('\\n')\n : ' (infer appropriate fields from the entity name and description)';\n\n const userPrompt = `Generate a complete FullOrbitalUnit for this orbital:\n\nName: ${args.name}\nEntity: ${args.entityName}\nTraits: ${(args.traitNames as string[]).join(', ')}\n${args.description ? `Description: ${args.description}` : ''}\n\nFields:\n${fieldsList}\n\nReturn ONLY valid JSON matching the FullOrbitalUnit schema. No markdown fences, no explanation text.`;\n\n const client = new LLMClient({\n provider: provider as 'anthropic' | 'deepseek' | 'openrouter',\n model,\n });\n\n const text = await client.callRaw({\n systemPrompt,\n userPrompt,\n maxTokens: 8192,\n });\n\n const orbital = extractJson(text);\n if (!orbital) {\n return { success: false, error: 'Failed to parse orbital JSON from LLM response' };\n }\n\n const obj = orbital as Record<string, unknown>;\n if (!obj.name || !obj.entity || !obj.traits) {\n return { success: false, error: 'Generated orbital missing required fields (name, entity, traits)' };\n }\n\n return { success: true, orbital };\n },\n };\n}\n\nfunction createCombineOrbitalsBuilderTool(): BuilderToolDefinition {\n return {\n name: 'combine_orbitals',\n description: 'Combine multiple orbital definitions into a single .orb schema JSON string.',\n parameters: {\n type: 'object',\n properties: {\n appName: { type: 'string', description: 'Application name' },\n orbitals: { type: 'array', description: 'Array of orbital definition objects' },\n },\n required: ['appName', 'orbitals'],\n },\n async execute(args) {\n const orbitals = args.orbitals as unknown[];\n const appName = args.appName as string;\n\n if (!orbitals.length) {\n return { success: false, error: 'No orbitals provided' };\n }\n\n const schema = {\n name: appName,\n version: '1.0.0',\n orbitals,\n };\n\n return {\n success: true,\n schema: JSON.stringify(schema, null, 2),\n orbitalCount: orbitals.length,\n };\n },\n };\n}\n\nfunction createQueryStructureBuilderTool(): BuilderToolDefinition {\n return {\n name: 'query_structure',\n description: 'Get a lightweight map of a schema (orbital names, entities, traits, field counts).',\n parameters: {\n type: 'object',\n properties: {\n schema: { type: 'string', description: 'The .orb schema JSON string' },\n },\n required: ['schema'],\n },\n async execute(args) {\n try {\n const parsed = JSON.parse(args.schema as string);\n const orbitals = (parsed.orbitals ?? []) as Array<Record<string, unknown>>;\n\n return {\n name: parsed.name,\n orbitals: orbitals.map((o) => ({\n name: o.name,\n entityName: getEntityName(o.entity),\n traits: getTraitNames(o.traits as unknown[] ?? []),\n totalFields: countFields(o.entity),\n totalStates: countStates(o.traits as unknown[] ?? []),\n })),\n };\n } catch (err) {\n return { error: `Failed to parse schema: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n };\n}\n\nfunction createAutoFixBuilderTool(config: BuilderConfig): BuilderToolDefinition {\n return {\n name: 'auto_fix',\n description: 'Attempt to fix validation errors in a schema using LLM repair.',\n parameters: {\n type: 'object',\n properties: {\n schema: { type: 'string', description: 'The .orb schema JSON string with errors' },\n errors: { type: 'array', description: 'Validation errors to fix [{code, message}]' },\n warnings: { type: 'array', description: 'Validation warnings to fix [{code, message}]' },\n provider: { type: 'string', description: 'LLM provider' },\n model: { type: 'string', description: 'LLM model' },\n },\n required: ['schema', 'errors'],\n },\n async execute(args) {\n const { getSubagentSystemPrompt } = await import('@almadar/skills');\n const { LLMClient } = await import('@almadar/llm');\n\n const orbitalKnowledge = getSubagentSystemPrompt();\n const provider = (args.provider as string) ?? 'deepseek';\n const model = (args.model as string) ?? 'deepseek-chat';\n\n const errors = args.errors as Array<{ code: string; message: string }>;\n const warnings = (args.warnings as Array<{ code: string; message: string }>) ?? [];\n\n const issues = [\n ...errors.map((e) => `ERROR [${e.code}]: ${e.message}`),\n ...warnings.map((w) => `WARNING [${w.code}]: ${w.message}`),\n ].join('\\n');\n\n const client = new LLMClient({\n provider: provider as 'anthropic' | 'deepseek' | 'openrouter',\n model,\n });\n\n const text = await client.callRaw({\n systemPrompt: `You are a schema repair tool for .orb orbital schemas.\\n\\n${orbitalKnowledge}\\n\\nReturn ONLY valid JSON.`,\n userPrompt: `Fix ALL validation errors and warnings in this schema.\\n\\nISSUES:\\n${issues}\\n\\nSCHEMA:\\n${args.schema}\\n\\nReturn the COMPLETE corrected schema as valid JSON.`,\n maxTokens: 8192,\n });\n\n const fixed = extractJson(text);\n if (!fixed) {\n return { success: false, error: 'Failed to parse fixed schema from LLM response' };\n }\n\n // Validate the fix\n const fixedStr = JSON.stringify(fixed, null, 2);\n const valResult = await config.executor.validateSchema(fixedStr);\n\n return {\n success: valResult.success,\n schema: fixedStr,\n remainingErrors: valResult.errors.length,\n remainingWarnings: valResult.warnings.length,\n };\n },\n };\n}\n\nfunction createNeuralGenerateBuilderTool(config: BuilderConfig): BuilderToolDefinition {\n return {\n name: 'neural_generate',\n description: 'Generate a schema using the GFlowNet neural pipeline. Fast (2-10s) but best for simple apps (1-2 entities).',\n parameters: {\n type: 'object',\n properties: {\n prompt: { type: 'string', description: 'Natural language description of the app to build' },\n provider: { type: 'string', description: 'LLM provider for goal parsing and auto-fix' },\n model: { type: 'string', description: 'LLM model' },\n samples: { type: 'number', description: 'Number of GFlowNet samples (default: 5)' },\n temperature: { type: 'number', description: 'Sampling temperature (default: 0.8)' },\n },\n required: ['prompt'],\n },\n async execute(args) {\n const { MasarClient } = await import('../neural/masar-client.js');\n\n const client = new MasarClient({\n timeoutMs: 120_000,\n });\n\n const result = await client.generate(args.prompt as string);\n return result;\n },\n };\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction getEntityName(entity: unknown): string {\n if (!entity) return 'Unknown';\n if (typeof entity === 'string') return entity.replace('.entity', '');\n if (typeof entity === 'object' && entity !== null && 'name' in entity) {\n return (entity as { name: string }).name;\n }\n return 'Unknown';\n}\n\nfunction getTraitNames(traits: unknown[]): string[] {\n const names: string[] = [];\n for (const t of traits) {\n if (typeof t === 'object' && t !== null) {\n if ('ref' in t) names.push((t as { ref: string }).ref);\n else if ('name' in t) names.push((t as { name: string }).name);\n }\n }\n return names;\n}\n\nfunction countFields(entity: unknown): number {\n if (!entity || typeof entity !== 'object') return 0;\n const e = entity as { fields?: unknown[] };\n return Array.isArray(e.fields) ? e.fields.length : 0;\n}\n\nfunction countStates(traits: unknown[]): number {\n let total = 0;\n for (const t of traits) {\n if (typeof t === 'object' && t !== null && 'stateMachine' in t) {\n const sm = (t as { stateMachine?: { states?: unknown[] } }).stateMachine;\n if (sm?.states) total += sm.states.length;\n }\n }\n return total;\n}\n\nfunction extractJson(text: string): unknown | null {\n try {\n return JSON.parse(text.trim());\n } catch {\n // noop\n }\n\n const fenceMatch = /```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```/.exec(text);\n if (fenceMatch) {\n try {\n return JSON.parse(fenceMatch[1].trim());\n } catch {\n // noop\n }\n }\n\n const braceStart = text.indexOf('{');\n if (braceStart >= 0) {\n let depth = 0;\n let inString = false;\n let escape = false;\n for (let i = braceStart; i < text.length; i++) {\n const ch = text[i];\n if (escape) { escape = false; continue; }\n if (ch === '\\\\' && inString) { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === '{') depth++;\n if (ch === '}') {\n depth--;\n if (depth === 0) {\n try { return JSON.parse(text.slice(braceStart, i + 1)); } catch { /* noop */ }\n break;\n }\n }\n }\n }\n\n return null;\n}\n"]}
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Builder Module Types
3
+ *
4
+ * Types for the builder-mode subset of the agent framework.
5
+ * Builder mode provides schema generation without workspace/git/filesystem.
6
+ */
7
+ import type { CommandExecutor, PythonExecutor } from '../neural/types.js';
8
+ export type { CommandExecutor, PythonExecutor };
9
+ export interface BuilderConfig {
10
+ /** How to run `orbital validate` */
11
+ executor: CommandExecutor;
12
+ /** How to run GFlowNet inference (optional, enables neural mode) */
13
+ pythonExecutor?: PythonExecutor;
14
+ }
15
+ export interface BuilderToolDefinition {
16
+ name: string;
17
+ description: string;
18
+ parameters: Record<string, unknown>;
19
+ execute: (args: Record<string, unknown>) => Promise<unknown>;
20
+ }
package/dist/index.d.ts CHANGED
@@ -58,3 +58,7 @@ export type { SandboxOptions, SandboxResult } from './tools/sandbox-executor.js'
58
58
  export { classifyCommand, TOOL_GATES, CRITICAL_COMMAND_PATTERNS } from './agent/interrupt-config.js';
59
59
  export type { ActionGate } from './agent/interrupt-config.js';
60
60
  export type { SessionActions, SessionServiceContract, MemoryActions, MemoryServiceContract, AgentActions, AgentServiceContract, AgentServiceContracts, } from './contracts.js';
61
+ export { MasarClient } from './neural/index.js';
62
+ export type { GoalSpec, NeuralGenerateResult, NeuralPipelineResult, NeuralPipelineOptions, MasarClientOptions, CommandExecutor, PythonExecutor, InferOptions, InferResult, } from './neural/index.js';
63
+ export { createBuilderTools } from './builder/index.js';
64
+ export type { BuilderConfig, BuilderToolDefinition } from './builder/index.js';