rax-flow-core 0.1.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.
Files changed (132) hide show
  1. package/dist/cache/semantic-cache.d.ts +10 -0
  2. package/dist/cache/semantic-cache.d.ts.map +1 -0
  3. package/dist/cache/semantic-cache.js +50 -0
  4. package/dist/cache/semantic-cache.js.map +1 -0
  5. package/dist/governance/policies/pii-policy.d.ts +37 -0
  6. package/dist/governance/policies/pii-policy.d.ts.map +1 -0
  7. package/dist/governance/policies/pii-policy.js +177 -0
  8. package/dist/governance/policies/pii-policy.js.map +1 -0
  9. package/dist/graph/workflow-graph.d.ts +5 -0
  10. package/dist/graph/workflow-graph.d.ts.map +1 -0
  11. package/dist/graph/workflow-graph.js +38 -0
  12. package/dist/graph/workflow-graph.js.map +1 -0
  13. package/dist/index.d.ts +25 -0
  14. package/dist/index.d.ts.map +1 -0
  15. package/dist/index.js +25 -0
  16. package/dist/index.js.map +1 -0
  17. package/dist/memory/graph-memory.d.ts +46 -0
  18. package/dist/memory/graph-memory.d.ts.map +1 -0
  19. package/dist/memory/graph-memory.js +122 -0
  20. package/dist/memory/graph-memory.js.map +1 -0
  21. package/dist/memory/local-vector-store.d.ts +36 -0
  22. package/dist/memory/local-vector-store.d.ts.map +1 -0
  23. package/dist/memory/local-vector-store.js +125 -0
  24. package/dist/memory/local-vector-store.js.map +1 -0
  25. package/dist/memory/memory-manager.d.ts +42 -0
  26. package/dist/memory/memory-manager.d.ts.map +1 -0
  27. package/dist/memory/memory-manager.js +98 -0
  28. package/dist/memory/memory-manager.js.map +1 -0
  29. package/dist/metrics/metrics-engine.d.ts +13 -0
  30. package/dist/metrics/metrics-engine.d.ts.map +1 -0
  31. package/dist/metrics/metrics-engine.js +27 -0
  32. package/dist/metrics/metrics-engine.js.map +1 -0
  33. package/dist/orchestrator/blueprint-committer.d.ts +69 -0
  34. package/dist/orchestrator/blueprint-committer.d.ts.map +1 -0
  35. package/dist/orchestrator/blueprint-committer.js +305 -0
  36. package/dist/orchestrator/blueprint-committer.js.map +1 -0
  37. package/dist/orchestrator/core-orchestrator.d.ts +168 -0
  38. package/dist/orchestrator/core-orchestrator.d.ts.map +1 -0
  39. package/dist/orchestrator/core-orchestrator.js +451 -0
  40. package/dist/orchestrator/core-orchestrator.js.map +1 -0
  41. package/dist/orchestrator/decomposition-engine.d.ts +41 -0
  42. package/dist/orchestrator/decomposition-engine.d.ts.map +1 -0
  43. package/dist/orchestrator/decomposition-engine.js +133 -0
  44. package/dist/orchestrator/decomposition-engine.js.map +1 -0
  45. package/dist/orchestrator/decomposition.d.ts +10 -0
  46. package/dist/orchestrator/decomposition.d.ts.map +1 -0
  47. package/dist/orchestrator/decomposition.js +15 -0
  48. package/dist/orchestrator/decomposition.js.map +1 -0
  49. package/dist/orchestrator/default-workflow.d.ts +59 -0
  50. package/dist/orchestrator/default-workflow.d.ts.map +1 -0
  51. package/dist/orchestrator/default-workflow.js +221 -0
  52. package/dist/orchestrator/default-workflow.js.map +1 -0
  53. package/dist/orchestrator/dynamic-planner.d.ts +46 -0
  54. package/dist/orchestrator/dynamic-planner.d.ts.map +1 -0
  55. package/dist/orchestrator/dynamic-planner.js +232 -0
  56. package/dist/orchestrator/dynamic-planner.js.map +1 -0
  57. package/dist/orchestrator/kernel-bridge.d.ts +57 -0
  58. package/dist/orchestrator/kernel-bridge.d.ts.map +1 -0
  59. package/dist/orchestrator/kernel-bridge.js +211 -0
  60. package/dist/orchestrator/kernel-bridge.js.map +1 -0
  61. package/dist/orchestrator/mutation-applier.d.ts +47 -0
  62. package/dist/orchestrator/mutation-applier.d.ts.map +1 -0
  63. package/dist/orchestrator/mutation-applier.js +253 -0
  64. package/dist/orchestrator/mutation-applier.js.map +1 -0
  65. package/dist/orchestrator/routing.d.ts +4 -0
  66. package/dist/orchestrator/routing.d.ts.map +1 -0
  67. package/dist/orchestrator/routing.js +41 -0
  68. package/dist/orchestrator/routing.js.map +1 -0
  69. package/dist/orchestrator/verify-fix.d.ts +79 -0
  70. package/dist/orchestrator/verify-fix.d.ts.map +1 -0
  71. package/dist/orchestrator/verify-fix.js +153 -0
  72. package/dist/orchestrator/verify-fix.js.map +1 -0
  73. package/dist/plugins/governance-plugin.d.ts +43 -0
  74. package/dist/plugins/governance-plugin.d.ts.map +1 -0
  75. package/dist/plugins/governance-plugin.js +88 -0
  76. package/dist/plugins/governance-plugin.js.map +1 -0
  77. package/dist/plugins/long-term-memory-plugin.d.ts +31 -0
  78. package/dist/plugins/long-term-memory-plugin.d.ts.map +1 -0
  79. package/dist/plugins/long-term-memory-plugin.js +67 -0
  80. package/dist/plugins/long-term-memory-plugin.js.map +1 -0
  81. package/dist/plugins/plugin-system.d.ts +29 -0
  82. package/dist/plugins/plugin-system.d.ts.map +1 -0
  83. package/dist/plugins/plugin-system.js +22 -0
  84. package/dist/plugins/plugin-system.js.map +1 -0
  85. package/dist/recovery/error-recovery.d.ts +15 -0
  86. package/dist/recovery/error-recovery.d.ts.map +1 -0
  87. package/dist/recovery/error-recovery.js +12 -0
  88. package/dist/recovery/error-recovery.js.map +1 -0
  89. package/dist/runtime/concurrency-scheduler.d.ts +2 -0
  90. package/dist/runtime/concurrency-scheduler.d.ts.map +1 -0
  91. package/dist/runtime/concurrency-scheduler.js +18 -0
  92. package/dist/runtime/concurrency-scheduler.js.map +1 -0
  93. package/dist/runtime/runtime-events.d.ts +59 -0
  94. package/dist/runtime/runtime-events.d.ts.map +1 -0
  95. package/dist/runtime/runtime-events.js +12 -0
  96. package/dist/runtime/runtime-events.js.map +1 -0
  97. package/dist/types/contracts.d.ts +127 -0
  98. package/dist/types/contracts.d.ts.map +1 -0
  99. package/dist/types/contracts.js +2 -0
  100. package/dist/types/contracts.js.map +1 -0
  101. package/dist/validator/structured-output-validator.d.ts +10 -0
  102. package/dist/validator/structured-output-validator.d.ts.map +1 -0
  103. package/dist/validator/structured-output-validator.js +19 -0
  104. package/dist/validator/structured-output-validator.js.map +1 -0
  105. package/package.json +18 -0
  106. package/src/cache/semantic-cache.ts +64 -0
  107. package/src/governance/policies/pii-policy.ts +213 -0
  108. package/src/graph/workflow-graph.ts +41 -0
  109. package/src/index.ts +25 -0
  110. package/src/memory/graph-memory.ts +150 -0
  111. package/src/memory/local-vector-store.ts +129 -0
  112. package/src/memory/memory-manager.ts +126 -0
  113. package/src/metrics/metrics-engine.ts +39 -0
  114. package/src/orchestrator/blueprint-committer.ts +351 -0
  115. package/src/orchestrator/core-orchestrator.ts +582 -0
  116. package/src/orchestrator/decomposition-engine.ts +165 -0
  117. package/src/orchestrator/decomposition.ts +25 -0
  118. package/src/orchestrator/default-workflow.ts +269 -0
  119. package/src/orchestrator/dynamic-planner.ts +277 -0
  120. package/src/orchestrator/kernel-bridge.ts +251 -0
  121. package/src/orchestrator/mutation-applier.ts +279 -0
  122. package/src/orchestrator/routing.ts +44 -0
  123. package/src/orchestrator/verify-fix.ts +218 -0
  124. package/src/plugins/governance-plugin.ts +106 -0
  125. package/src/plugins/long-term-memory-plugin.ts +72 -0
  126. package/src/plugins/plugin-system.ts +34 -0
  127. package/src/recovery/error-recovery.ts +23 -0
  128. package/src/runtime/concurrency-scheduler.ts +18 -0
  129. package/src/runtime/runtime-events.ts +27 -0
  130. package/src/types/contracts.ts +159 -0
  131. package/src/validator/structured-output-validator.ts +20 -0
  132. package/tsconfig.json +17 -0
@@ -0,0 +1,72 @@
1
+ import { MemoryManager } from "../memory/memory-manager.js";
2
+ import { IEmbeddingProvider, MemoryDocument, AgentInput, AgentOutput, WorkflowNode } from "../types/contracts.js";
3
+ import { RaxPlugin } from "./plugin-system.js";
4
+
5
+ /**
6
+ * LongTermMemoryPlugin enables QSGM (Quantum Semantic Graph Memory) by
7
+ * retrieving relevant past execution data using hybrid graph/vector navigation.
8
+ */
9
+ export class LongTermMemoryPlugin implements RaxPlugin {
10
+ public name = "long-term-memory";
11
+
12
+ constructor(
13
+ private memoryManager: MemoryManager,
14
+ private embeddingProvider: IEmbeddingProvider
15
+ ) { }
16
+
17
+ /**
18
+ * Called before an agent executes.
19
+ * Uses Quantum Semantic Graph Memory to retrieve deep context.
20
+ */
21
+ async beforeNode({ input }: { node: WorkflowNode; input: AgentInput }): Promise<void> {
22
+ try {
23
+ const { vectors } = await this.embeddingProvider.embed([input.userPrompt]);
24
+ if (!vectors || vectors.length === 0) return;
25
+
26
+ const memoryText = await this.memoryManager.getQuantumContext(vectors[0], 3);
27
+
28
+ if (memoryText) {
29
+ // Inject the retrieved knowledge into artifacts for the agent to pick up
30
+ input.artifacts = {
31
+ ...(input.artifacts || {}),
32
+ _longTermMemory: memoryText,
33
+ };
34
+ }
35
+ } catch (err) {
36
+ console.warn("[LongTermMemoryPlugin] Retrieval failed:", err);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Called after an agent finishes.
42
+ * Persists results into both Vector and Graph stores.
43
+ */
44
+ async afterNode({ node, input, output }: { node: WorkflowNode; input: AgentInput; output: AgentOutput }): Promise<void> {
45
+ if (output.success && output.data && Object.keys(output.data).length > 0) {
46
+ try {
47
+ const textToEmbed = `Context: ${input.userPrompt}\nAction: ${node.id} (${node.agent})\nKnowledge: ${JSON.stringify(output.data)}`;
48
+ const { vectors } = await this.embeddingProvider.embed([textToEmbed]);
49
+
50
+ if (!vectors || vectors.length === 0) return;
51
+
52
+ const doc: MemoryDocument = {
53
+ id: `mem_${Date.now()}_${Math.random().toString(36).substring(7)}`,
54
+ text: textToEmbed,
55
+ metadata: {
56
+ taskId: input.taskId,
57
+ nodeId: node.id,
58
+ agent: node.agent,
59
+ timestamp: new Date().toISOString()
60
+ },
61
+ timestamp: Date.now()
62
+ };
63
+
64
+ // In a workflow, we can link nodes if we track the previous node execution.
65
+ // For simplicity, we just add it to the manager.
66
+ await this.memoryManager.remember(doc, vectors[0]);
67
+ } catch (err) {
68
+ console.warn("[LongTermMemoryPlugin] Memorization failed:", err);
69
+ }
70
+ }
71
+ }
72
+ }
@@ -0,0 +1,34 @@
1
+ import { AgentInput, AgentOutput, WorkflowNode } from "../types/contracts.js";
2
+
3
+ export interface RaxPlugin {
4
+ name: string;
5
+ setup?(): Promise<void> | void;
6
+ beforeNode?(params: { node: WorkflowNode; input: AgentInput }): Promise<void> | void;
7
+ afterNode?(params: { node: WorkflowNode; input: AgentInput; output: AgentOutput }): Promise<void> | void;
8
+ }
9
+
10
+ export class PluginSystem {
11
+ private readonly plugins: RaxPlugin[] = [];
12
+
13
+ register(plugin: RaxPlugin): void {
14
+ this.plugins.push(plugin);
15
+ }
16
+
17
+ async initialize(): Promise<void> {
18
+ for (const plugin of this.plugins) {
19
+ await plugin.setup?.();
20
+ }
21
+ }
22
+
23
+ async runBeforeNode(params: { node: WorkflowNode; input: AgentInput }): Promise<void> {
24
+ for (const plugin of this.plugins) {
25
+ await plugin.beforeNode?.(params);
26
+ }
27
+ }
28
+
29
+ async runAfterNode(params: { node: WorkflowNode; input: AgentInput; output: AgentOutput }): Promise<void> {
30
+ for (const plugin of this.plugins) {
31
+ await plugin.afterNode?.(params);
32
+ }
33
+ }
34
+ }
@@ -0,0 +1,23 @@
1
+ export interface RecoveryDecision {
2
+ retry: boolean;
3
+ escalate: boolean;
4
+ reason: string;
5
+ }
6
+
7
+ export class ErrorRecoverySystem {
8
+ decide(params: {
9
+ retries: number;
10
+ maxRetries: number;
11
+ confidence: number;
12
+ minConfidence: number;
13
+ schemaErrors: string[];
14
+ }): RecoveryDecision {
15
+ if (params.schemaErrors.length > 0 && params.retries < params.maxRetries) {
16
+ return { retry: true, escalate: false, reason: "schema_invalid_retry" };
17
+ }
18
+ if (params.confidence < params.minConfidence) {
19
+ return { retry: false, escalate: true, reason: "low_confidence_escalate" };
20
+ }
21
+ return { retry: false, escalate: false, reason: "accept" };
22
+ }
23
+ }
@@ -0,0 +1,18 @@
1
+ export async function runWithConcurrency<T>(tasks: Array<() => Promise<T>>, maxParallel: number): Promise<T[]> {
2
+ if (tasks.length === 0) return [];
3
+ const limit = Math.max(1, maxParallel);
4
+ const results: T[] = new Array(tasks.length);
5
+ let nextIndex = 0;
6
+
7
+ async function worker(): Promise<void> {
8
+ while (nextIndex < tasks.length) {
9
+ const current = nextIndex;
10
+ nextIndex += 1;
11
+ results[current] = await tasks[current]();
12
+ }
13
+ }
14
+
15
+ const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => worker());
16
+ await Promise.all(workers);
17
+ return results;
18
+ }
@@ -0,0 +1,27 @@
1
+ import { EventEmitter } from "node:events";
2
+ import { ExecutionMetrics, WorkflowGraph } from "../types/contracts.js";
3
+
4
+ export type RuntimeEvent =
5
+ | { type: "run_start"; taskId: string; workflow?: WorkflowGraph }
6
+ | { type: "graph_ready"; taskId: string; workflow: WorkflowGraph }
7
+ | { type: "node_start"; nodeId: string; agent: string; retry: number }
8
+ | { type: "node_awaiting_approval"; taskId: string; nodeId: string; agent: string; data: any }
9
+
10
+ | { type: "node_end"; nodeId: string; agent: string; success: boolean; confidence: number; retry: number; costUsd?: number; usage?: { promptTokens: number; completionTokens: number; totalTokens: number } }
11
+ | { type: "node_error"; nodeId: string; agent: string; message: string; retry: number }
12
+ | { type: "audit_record"; taskId: string; nodeId?: string; action?: string; allowed?: boolean; violations?: any[]; score?: any; mutation?: any }
13
+ | { type: "run_end"; taskId: string; metrics: ExecutionMetrics };
14
+
15
+
16
+ export class RuntimeEventBus {
17
+ private readonly emitter = new EventEmitter();
18
+
19
+ emit(event: RuntimeEvent): void {
20
+ this.emitter.emit("event", event);
21
+ }
22
+
23
+ onEvent(handler: (event: RuntimeEvent) => void): () => void {
24
+ this.emitter.on("event", handler);
25
+ return () => this.emitter.off("event", handler);
26
+ }
27
+ }
@@ -0,0 +1,159 @@
1
+ export type Intent =
2
+ | "brainstorm"
3
+ | "spec"
4
+ | "architecture"
5
+ | "plan"
6
+ | "generate_code"
7
+ | "test"
8
+ | "fix"
9
+ | "optimize"
10
+ | "document"
11
+ | "benchmark";
12
+
13
+ export type RiskFlag = "schema_drift" | "hallucination" | "high_cost" | "security" | "latency";
14
+
15
+ export interface AgentInput {
16
+ taskId: string;
17
+ userPrompt: string;
18
+ context?: Record<string, unknown>;
19
+ artifacts?: Record<string, unknown>;
20
+ }
21
+
22
+ export interface AgentOutput<TData = Record<string, unknown>> {
23
+ agent: string;
24
+ success: boolean;
25
+ confidence: number;
26
+ risks: RiskFlag[];
27
+ logs: string[];
28
+ data: TData;
29
+ usage?: {
30
+ promptTokens: number;
31
+ completionTokens: number;
32
+ totalTokens: number;
33
+ };
34
+ costUsd?: number;
35
+ }
36
+
37
+ export interface RoutedPlan {
38
+ intent: Intent;
39
+ workflowId: string;
40
+ parallelizable: boolean;
41
+ escalationPolicy: {
42
+ maxFixLoops: number;
43
+ lowConfidenceThreshold: number;
44
+ escalateTo: string[];
45
+ };
46
+ }
47
+
48
+ export interface ProviderCallOptions {
49
+ model?: string;
50
+ temperature?: number;
51
+ maxTokens?: number;
52
+ metadata?: Record<string, string>;
53
+ }
54
+
55
+ export interface ModelResponse<T = unknown> {
56
+ provider: string;
57
+ model: string;
58
+ latencyMs: number;
59
+ costUsd?: number;
60
+ usage?: {
61
+ promptTokens: number;
62
+ completionTokens: number;
63
+ totalTokens: number;
64
+ };
65
+ output: T;
66
+ raw?: unknown;
67
+ }
68
+
69
+ export interface IModelProvider {
70
+ callModel(prompt: string, options?: ProviderCallOptions): Promise<ModelResponse<string>>;
71
+ callStructured<T>(prompt: string, schema: object, options?: ProviderCallOptions): Promise<ModelResponse<T>>;
72
+ healthCheck(): Promise<boolean>;
73
+ }
74
+
75
+ export interface AgentDefinition {
76
+ name: string;
77
+ role: string;
78
+ activationWhen: string;
79
+ inputSchema: object;
80
+ outputSchema: object;
81
+ run(input: AgentInput): Promise<AgentOutput>;
82
+ }
83
+
84
+ export interface WorkflowNode {
85
+ id: string;
86
+ agent: string;
87
+ dependsOn: string[];
88
+ requireApproval?: boolean;
89
+ }
90
+
91
+
92
+ export interface WorkflowGraph {
93
+ id: string;
94
+ nodes: WorkflowNode[];
95
+ }
96
+
97
+ export interface ExecutionMetrics {
98
+ taskId: string;
99
+ intent: Intent;
100
+ confidence: number;
101
+ retries: number;
102
+ escalations: number;
103
+ totalLatencyMs: number;
104
+ totalCostUsd: number;
105
+ humanInterventionRequired: boolean;
106
+ }
107
+
108
+ // --- Memory & RAG ---
109
+
110
+ export interface EmbeddingResponse {
111
+ vectors: number[][];
112
+ model: string;
113
+ usage: { totalTokens: number };
114
+ }
115
+
116
+ export interface IEmbeddingProvider {
117
+ embed(texts: string[]): Promise<EmbeddingResponse>;
118
+ }
119
+
120
+ export interface MemoryDocument {
121
+ id: string;
122
+ text: string;
123
+ metadata: Record<string, unknown>;
124
+ timestamp: number;
125
+ }
126
+
127
+ export interface SearchResult extends MemoryDocument {
128
+ score: number;
129
+ }
130
+
131
+ export interface IVectorStore {
132
+ add(documents: MemoryDocument[], vectors: number[][]): Promise<void>;
133
+ search(queryVector: number[], limit?: number): Promise<SearchResult[]>;
134
+ clear(): Promise<void>;
135
+ delete?(docIds: string[]): Promise<void>;
136
+ }
137
+
138
+ // --- Governance & Audit ---
139
+
140
+ export interface PolicyViolation {
141
+ policy: string;
142
+ severity: "low" | "medium" | "high" | "critical";
143
+ message: string;
144
+ }
145
+
146
+ export interface PolicyDecision {
147
+ allowed: boolean;
148
+ violations: PolicyViolation[];
149
+ }
150
+
151
+ export interface AuditRecord {
152
+ timestamp: number;
153
+ taskId: string;
154
+ nodeId?: string;
155
+ action: string;
156
+ decision: PolicyDecision;
157
+ metadata: Record<string, unknown>;
158
+ }
159
+
@@ -0,0 +1,20 @@
1
+ import Ajv, { ErrorObject } from "ajv";
2
+
3
+ export class StructuredOutputValidator {
4
+ private readonly ajv: any = new (Ajv as any)({ allErrors: true, strict: false });
5
+
6
+ validate<T>(schema: object, payload: unknown): { ok: boolean; isValid: boolean; value?: T; errors: string[] } {
7
+ const validateFn = this.ajv.compile(schema);
8
+ const ok = validateFn(payload);
9
+ return {
10
+ ok: Boolean(ok),
11
+ isValid: Boolean(ok),
12
+ value: ok ? (payload as T) : undefined,
13
+ errors: (validateFn.errors ?? []).map((e: ErrorObject) => {
14
+ const path = e.instancePath || "/";
15
+ const field = path.split("/").pop() || path;
16
+ return `${field} ${e.message || "invalid"}`;
17
+ })
18
+ };
19
+ }
20
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,17 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": "src",
5
+ "outDir": "dist",
6
+ "composite": true,
7
+ "declaration": true,
8
+ "declarationMap": true
9
+ },
10
+ "include": [
11
+ "src/**/*.ts"
12
+ ],
13
+ "exclude": [
14
+ "src/**/*.test.ts",
15
+ "tests/**/*"
16
+ ]
17
+ }