@indra.ai/deva 1.64.55 → 1.64.92

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/index.js CHANGED
@@ -12,2301 +12,2311 @@ import config from './_data/index.js';
12
12
  import pkg from './package.json' with {type:'json'};
13
13
 
14
14
  class Deva {
15
- constructor(opts) {
16
- opts = opts || {}; // set opts to provided opts or an empty object.
17
- this._core = pkg; // set the core from the package data.
18
- this._id = opts.id || randomUUID(); // the unique id assigned to the agent at load
19
- this._info = opts.info || false; // the deva information from the package file.
20
- this._config = opts.config || {}; // local Config Object
21
- this._config.hashes = config.hashes; // set hashes array from config for stamping.
22
- this._config.ready_hash = config.ready_hash; // items to hash at ready
23
- this._config.timeout = {...config.timeout, ...this._config.timeout}; // add timeout values to _config.
24
-
25
- this._agent = opts.agent || false; // Agent profile object
26
- this._client = {}; // this will be set on init.
27
- this._active = false; // the active/birth date.
28
- this._license = false; // inherited License features.
29
- this._error = false; // inherited Error features.
30
- this._log = false; // inherited Log features.
31
- this._data = false; // inherited Data features.
32
- this._report = false; // inherited Report features.
33
- this._legal = false; // inherited Legal features.
34
- this._security = false; // inherited Security features.
35
- this._support = false; // inherited Support features.
36
- this._services = false; // inherited Service features.
37
- this._systems = false; // inherited Systems features.
38
-
39
- this.events = opts.events || new EventEmitter({}); // Event Bus
40
- this.lib = new lib({pkg}); // used for loading library functions
41
- this.utils = opts.utils || {}; // parse functions inside the deva
42
- this.devas = opts.devas || {}; // Devas which are loaded
43
- this.vars = opts.vars || {}; // Variables object
44
- this.listeners = opts.listeners || {}; // local Listeners
45
- this.modules = opts.modules || {}; // 3rd Party Modules
46
- this.func = opts.func || {}; // local Functions
47
- this.methods = opts.methods || {}; // local Methods
48
- this.maxListeners = opts.maxListeners || 0; // set the local maxListeners
49
- // prevent overwriting existing functions and variables with same name
50
- for (const opt in opts) {
51
- if (!this[opt] || !this[`_${opt}`]) this[opt] = opts[opt];
52
- }
53
-
54
- this.cmdChr = config.cmdChr; // the trigger for local commands
55
- this.askChr = config.askChr; // the trigger for ask other DEva features
56
- this.container = config.container // set the container object
57
- this.box = config.box // set the box object
58
-
59
- this._inherit = config.inherit; // set inherit from config data.
60
- this._bind = config.bind; // set the bind from the config data.
61
- this._binding = new Map(); // set the binding map
62
-
63
- this._uid = config.uid; // set the uid options
64
-
65
- this._events = config.events; // set the core system events
66
- this._bound = new Map(); // evt -> wrapper registered on the shared bus
67
- this._pending = new Set(); // pending asks: {evt, handler, timer}
68
- this._stateBound = []; // [event, handler] pairs for the state listeners
69
-
70
- this._feature = config.feature; // set the feature from config data.
71
- this._features = config.features; // set the features from config data.
72
-
73
- this._zone = config.zone; // set the current zone from config data.
74
- this._zones = {...config.zones}; // set the zones from config data.
75
- // load any custom zones from the agent file
76
- if (this._agent.zones) {
77
- for (let item in this._agent.zones) {
78
- if (!this._zones[item]) this._zones[item] = this._agent.zones[item];
79
- }
80
- delete this._agent.zones;
81
- }
82
-
83
- this._action = config.action; // set the action from config data.
84
- this._actions = {...config.actions}; // set the actions from config data.
85
- // load any custom actions from the agent file
86
- if (this._agent.actions) {
87
- for (let item in this._agent.actions) {
88
- if (!this._actions[item]) this._actions[item] = this._agent.actions[item];
89
- }
90
- delete this._agent.actions;
91
- }
92
-
93
- this._state = config.state; // set the current state from config data.
94
- this._states = {...config.states}; // set the states from options
95
- // load any custom states from the agent file
96
- if (this._agent.states) {
97
- for (let item in this._agent.states) {
98
- if (!this._states[item]) this._states[item] = this._agent.states[item];
99
- }
100
- delete this._agent.states;
101
- }
102
-
103
- this._intent = config.intent; // set the current intent from config data.
104
- this._intents = {...config.intents}; // set the states from options
105
- // load any custom actions from the agent file
106
- if (this._agent.intents) {
107
- for (let item in this._agent.intents) {
108
- if (!this._intents[item]) this._intents[item] = this._agent.intents[item];
109
- }
110
- delete this._agent.intents;
111
- }
112
-
113
- this._belief = config.belief; // set the current belief from config data.
114
- this._beliefs = {...config.beliefs}; // set the states from options
115
- // load any custom actions from the agent file
116
- if (this._agent.beliefs) {
117
- for (let item in this._agent.beliefs) {
118
- if (!this._beliefs[item]) this._beliefs[item] = this._agent.beliefs[item];
119
- }
120
- delete this._agent.beliefs;
121
- }
122
-
123
- this._context = config.context || false; // set the local context
124
-
125
- this._messages = {...config.messages}; // set the messages from config data.
126
- // load any custom actions from the agent file
127
- if (this._agent.messages) {
128
- for (let item in this._agent.messages) {
129
- if (!this._messages[item]) this._messages[item] = this._agent.messages[item];
130
- }
131
- delete this._agent.messages;
132
- }
133
-
134
- }
135
-
136
- /**************
137
- func: _assignBind
138
- params: none
139
- describe:
140
- The assign bind function will bind the translate functions and parse functions
141
- of the agent and bind their functionality to the state machine.
142
-
143
- ***************/
144
- _assignBind() {
145
- return new Promise((resolve, reject) => {
146
- try {
147
- this._bind.forEach(bind => { // loop over the bind items func, method, listener...
148
- if (this[bind]) for (let x in this[bind]) { // if the root has a bind func, method, listener
149
- // check to make sure the binding is a function.
150
- if (typeof this[bind][x] === 'function') {
151
- // check to make sure object is a function
152
- if (!this._binding.has(bind)) this._binding.set(bind, {});
153
- this._binding.get(bind)[x] = this[bind][x].toString();
154
- this[bind][x] = this[bind][x].bind(this);
155
- }
156
- }
157
- });
158
- return resolve(); // when the configuration is complete then return an empty resolve.
159
- }
160
- catch (e) {
161
- return this.err(e, false, reject); // trigger the this.err for errors
162
- }
163
- });
164
- }
165
-
166
- /**************
167
- func: _assignListeners
168
- params: none
169
- describe:
170
- Assign listeners will take the this.lisners objects and assign the appropriate
171
- lisnter values for the event bus.
172
- ***************/
173
- _assignListeners() {
174
- return new Promise((resolve, reject) => {
175
- try {
176
-
177
- // set the default listeners for the states of the agent.
178
- for (let state in this._states) {
179
- if (typeof this[state] === 'function') {
180
- const evt = `${this._agent.key}:${state}`;
181
- const handler = packet => this[state](packet);
182
- this._stateBound.push([evt, handler]); // keep it so shutdown can remove it
183
- this.events.on(evt, handler);
184
- }
185
- }
186
-
187
- // set the assigned listeners for the agent.
188
- for (let listener in this.listeners) { // loop over the listeners
189
- const handler = packet => this.listeners[listener](packet);
190
- this._bound.set(listener, handler);
191
- this.events.on(listener, handler);
192
- }
193
- return resolve(); // resolve the function after everything is done.
194
- }
195
- catch (e) {
196
- return this.err(e, false, reject); // pass errors to this.err
197
- }
198
- });
199
- }
200
-
201
- /**************
202
- func: _removeListeners
203
- params: none
204
- describe:
205
- Remove listeners will take the this.lisners objects and remove the appropriate
206
- listener values for the event bus.
207
- ***************/
208
- _removeListeners() {
209
- if (!this.events || !this.listeners) return;
210
- for (const evt in this.listeners) {
211
- const handler = this._bound.get(evt);
212
- if (handler) this.ignore(evt, handler); // ignore() already calls events.removeListener
213
- }
214
- this._bound.clear();
215
- for (const [evt, handler] of this._stateBound) this.ignore(evt, handler); // state listeners from _assignListeners
216
- this._stateBound = [];
217
- return this._clearPending(); // pending asks go in the same pass
218
- }
219
-
220
- /**************
221
- func: _clearPending
222
- params: none
223
- describe:
224
- Clears the timer and removes the listener for every pending ask so a
225
- shutdown leaves nothing behind on the shared event bus.
226
- ***************/
227
- _clearPending() {
228
- if (!this._pending) return;
229
- for (const pending of this._pending) {
230
- clearTimeout(pending.timer);
231
- if (this.events) this.ignore(pending.evt, pending.handler);
232
- pending.resolve(this._messages.offline); // the Deva is going offline so answer the waiting caller.
233
- }
234
- this._pending.clear();
235
- }
236
-
237
- // Some elements will inherit the data of the parent. this object will loop over
238
- // any children data that this deva has and assign the inherited information.
239
- /**************
240
- func: _assignInherit
241
- params: none
242
- describe:
243
- The assign inherit will make sure the Devas in the current Deva have all the
244
- inherited properties all setup to collaborate efficiently.
245
- ***************/
246
- _assignInherit() {
247
- return new Promise((resolve, reject) => {
248
- try {
249
- for (let d in this.devas) {
250
- this._inherit.forEach(inherit => {
251
- this.devas[d][inherit] = this[inherit];
252
- });
253
- }
254
- return resolve();
255
- }
256
- catch (e) {
257
- return this.err(e, false, reject);
258
- }
259
- });
260
- }
261
-
262
- // General handler for when a method is NOT found from a user command.
263
- /**************
264
- func: _methodNotFound
265
- params:
266
- - packet: The packet to relay when a method is not found.
267
- describe:
268
- The _methodNotFound function allows for additional security by firing
269
- a specfici program functon every single time a interaction happens wehre a
270
- method is not located. This assits in security and support by identifying
271
- troubls or users who may be attemptng to explit features.
272
-
273
- Then we talk a security event that watches all methods and return the packet.
274
-
275
- This will return a not found text string preventing any furhter processing.
276
- ***************/
277
- _methodNotFound(packet) {
278
- if (!this._active) return this._messages.offline; // check the active status
279
- const id = this.uid();
280
- const agent = this.agent() || false;
281
- const client = this.client() || false;
282
- const {meta, params} = packet.q;
283
- const text = `${this._messages.method_not_found} ${agent.key} ${meta.method}`
284
- const packet_answer = {
285
- id,
286
- agent,
287
- client,
288
- text,
289
- meta: {
290
- key: agent.key,
291
- method: meta.method,
292
- },
293
- created: Date.now(),
294
- };
295
- // set packet into packet.a after stamping it.
296
- packet.a = this._stamp(packet_answer);
297
-
298
- // stamp the packet before return
299
- const packet_stamped = this._stamp(this._unstamp(packet), `methodNotFound:${meta.method}`, packet.id.uid);
300
- this.state('invalid', `${meta.method}:${packet.id.uid}`);
301
- return packet;
302
- }
303
-
304
- /**************
305
- func: _getFeature
306
- params:
307
- - key: the feature key parameter.
308
- - value: the value being passed into the data.
309
- describe:
310
- ***************/
311
- _getFeature(key) {
312
- if (!this._active) return this._messages.offline; // check the active status
313
- if (!this._features[key]) return this._messages.invalidfeature; // return no key if doesn't match.
314
-
315
- this.feature(key); // set the security state
316
- this.zone(key); // set the zone to the key.
317
- this.state('try', key); // set the state to try.
318
- try {
319
- const data = this.lib.copy(this[`_${key}`]);
320
- this.action('return', `_getFeature:${key}`); // set the return action
321
- this.state('valid', `_getFeature:${key}`); // set the valid state
322
- this.intent('good', `_getFeature:${key}`); // set the intent good
323
- return data; // return the data
324
- } catch (err) {
325
- this.state('catch', `_getFeature:${key}`);
326
- this.intent('bad', `_getFeature:${key}`);
327
- return this.err(err);
328
- }
329
- }
330
-
331
- /**************
332
- func: _invoke
333
- params:
334
- - data: the data to pass to the resolve
335
- - resolve: the complete resolve to pass back
336
- describe: The _invoke function is used for the recursion over
337
- init, start, enter, done ready, finish, complete
338
- usage: this.complete(data, resolve)
339
- ***************/
340
- _invoke(opts) {
341
- const {key, data, resolve} = opts;
342
- if (!this._active) return resolve(this._messages.offline);
343
- if (!key) return resolve (this._messages.nokey);
344
- if (!config.invoke[key]) return resolve (this._messages.invalidkey);
345
- if (!data) return resolve (this._messages.nodata);
346
-
347
- const {next_key, onfunc, clear} = config.invoke[key];
348
- this.action('invoke', `${key}:${data.id.uid}`);
349
- this.context(key, data.id.uid);
350
- this.zone(key, data.id.uid);
351
- this.action(key, data.id.uid);
352
- this.state(key, data.id.uid);
353
-
354
- this.state('data', `${key}:date:${data.id.uid}`);
355
- data[key] = Date.now();// set the complete date on the whole data.
356
-
357
- const data_stamped = this._stamp(this._unstamp(data), key, data.id.uid);
358
-
359
- // setup the complete talk veent
360
- this.action('talk', `${this._events[key]}:${data.id.uid}`); // action talk for the event.
361
- this.talk(this._events[key], this.lib.copy(data)); // talk the complete event
362
-
363
- if (clear) {
364
- this.state('loop', `${key}:clear:${data.id.uid}`);
365
- for (let item of clear) {
366
- if (item === 'listeners') this._removeListeners();
367
- this[item] = false;
368
- }
369
- }
370
-
371
- // determine if there is an onComplete function for the entity.
372
- const hasOnFunc = this[onfunc] && typeof this[onfunc] === 'function';
373
- if (hasOnFunc) {
374
- this.action('return', `onfunc:${onfunc}:${data.id.uid}`); // action return
375
- this.state('valid', `onfunc:${onfunc}:${data.id.uid}`); // state valid
376
- this.intent('good', `onfunc:${onfunc}:${data.id.uid}`); // intent good
377
- return this[onfunc](data, resolve);
378
- }
379
-
380
- this.action('return', `${key}:${data.id.uid}`); // return action complete
381
- this.state('valid', `${key}:${data.id.uid}`); // return state valid
382
- this.intent('good', `${key}:${data.id.uid}`); // return intent good
383
- return next_key ? this[next_key](data, resolve) : resolve(data);
384
- }
385
-
386
- /**************
387
- func: _stamp
388
- params:
389
- - data: the data to stamp
390
- - label: the label for the hash action.
391
- describe: the stamp function will take a data object and apply the hashes from the this._config.hashes array.
392
- usage: this._stamp(data, 'value')
393
- ***************/
394
- _stamp(data, label='', uid='') {
395
- for (const algo of this._config.hashes) {
396
- if (label) this.action('hash', `${label}:${algo}:${uid}`);
397
- data[algo] = this.hash(data, algo);
398
- }
399
- return data;
400
- }
401
-
402
- /**************
403
- func: _unstamp
404
- params:
405
- - data: the data to unstamp
406
- describe: the unstamp function will take a data object and remove the hashes over the this._hashes array.
407
- usage: this._unstamp(data)
408
- ***************/
409
- _unstamp(data) {
410
- const id = data.id?.uid || this._messages.noid; // check for proper id in the data.
411
- for (const algo of this._config.hashes) {
412
- this.action('delete', `${algo}:${id}`);
413
- delete data[algo]
414
- };
415
- return data;
416
- }
417
-
418
- /**************
419
- func: Client
420
- params: client - client provided data.
421
- describe:
422
- The Client feature sets up the client variables and removes any unnecessary
423
- keys from the client object that are used in other features.
424
-
425
- usage:
426
- this.Client = {data}
427
- ***************/
428
- Client(client, resolve, reject) {
429
- this.feature('client', `client:${client.id}`);
430
- this.zone('client', `client:${client.id}`);
431
- this.action('client', `client:${client.id}`);
432
- // setup any custom methods for the features
433
- this.state('try', `client:${client.id}`);
434
- try {
435
- this.state('set', `client:methods:${client.id}`);
436
- for (const x in client.features) {
437
- const methods = client.features[x].methods || false;
438
- if (methods) for (const y in methods) {
439
- const isFunc = typeof methods[y] === 'function';
440
- if (isFunc) {
441
- this.methods[y] = methods[y].bind(this);
442
- }
443
- }
444
- }
445
- const _client = this.lib.copy(client); // copy the client parameter
446
- this.state('data', `client:${client.id}`); // set the state to data for client.
447
- this._client = _client; // set local _client to this scope
448
-
449
- this.action('return', `client:${client.id}`); // set the action
450
- this.intent('good', `client:${client.id}`); // set the intent
451
- return resolve(_client); // resolve the client .
452
- } catch (e) {
453
- this.state('catch', `client:${client.id}`);
454
- this.intent('bad', `client:${client.id}`);
455
- return this.err(e, false, reject);
456
- }
457
- }
458
-
459
- /**************
460
- func: Feature
461
- params: client: false
462
- describe:
463
- The Security feature sets the correct variables and necessary rules for the
464
- client presented data.
465
- ***************/
466
- Feature(feature, resolve, reject) {
467
- if (!this._features[feature]) return reject(this._messages.invalidfeature); // reject if there is no feature match.
468
- const _id = this.uid();
469
- this.feature(feature, _id.uid);
470
- this.zone(feature, _id.uid);
471
- try {
472
- if (!this._features[feature]) return resolve(this._messages.invalidfeature); // if no feature resolve invalid feature
473
- else {
474
- const call_str = `Feature:${feature}:${_id.uid}` // call string for action state intent.
475
- this.action('feature', call_str); // set action to feature
476
- this.state('data', call_str); // set state to data
477
- const {id, profile, features} = this.client(); // set the values from the client.
478
- const data = features[feature]; // make a copy of the feature data
479
-
480
- this.state('set', `Feature:this._${feature}:${_id.uid}`); // set the feature state value
481
- this[`_${feature}`] = { // set this feature with data
482
- id: _id, // uid of the feature
483
- client_id: id, // client id for reference
484
- client_name: profile.name, // client name for personalization
485
- concerns: data.concerns, // any concerns for client
486
- global: data.global, // the global policies for client
487
- personal: data.devas[this._agent.key], // Client personal features and rules.
488
- created: Date.now(),
489
- };
490
- this.state('delete', `Feature:client:${feature}:${_id.uid}`); // set the state to delete
491
- delete this._client.features[feature]; // make a copy the clinet data.
492
-
493
- this.action('return', call_str); // set the action to return
494
- this.state('resolve', call_str); // set the state to resolve
495
- this.intent('good', call_str); // set the intent to good.
496
- return resolve(feature); // resolve when done
497
- }
498
- } catch (e) {
499
- this.state('catch', `${feature}:${_id.uid}`); // set the state to catch.
500
- this.intent('bad', `${feature}:catch:${_id.uid}`); // set the intent to bad.
501
- return this.err(e, feature, reject); // run error handling if an error is caught
502
- }
503
- }
504
-
505
- /**************
506
- func: License
507
- params: resolve, reject
508
- describe:
509
- The License feature sets the correct variables and necessary rules for the
510
- client presented data.
511
- ***************/
512
- License(resolve, reject) {
513
- return this.Feature('license', resolve, reject);
514
- }
515
-
516
- /**************
517
- func: Error
518
- params: resolve, reject
519
- describe:
520
- The Error feature sets the correct variables and necessary rules for the
521
- client presented data.
522
- ***************/
523
- Error(resolve, reject) {
524
- return this.Feature('error', resolve, reject);
525
- }
526
-
527
- /**************
528
- func: Log
529
- params: resolve, reject
530
- describe:
531
- The Log feature sets the correct variables and necessary rules for the
532
- client presented data.
533
- ***************/
534
- Log(resolve, reject) {
535
- return this.Feature('log', resolve, reject);
536
- }
537
-
538
- /**************
539
- func: Data
540
- params: resolve, reject
541
- describe:
542
- The Data feature sets the correct variables and necessary rules for the
543
- client presented data.
544
- ***************/
545
- Data(resolve, reject) {
546
- return this.Feature('data', resolve, reject);
547
- }
548
-
549
- /**************
550
- func: Report
551
- params: resolve, reject
552
- describe:
553
- The Report feature sets the correct variables and necessary rules for the
554
- client presented data.
555
- ***************/
556
- Report(resolve, reject) {
557
- return this.Feature('report', resolve, reject);
558
- }
559
-
560
- /**************
561
- func: Legal
562
- params: resolve, reject
563
- describe:
564
- The Legal feature sets the correct variables and necessary rules for the
565
- client presented data.
566
- ***************/
567
- Legal(resolve, reject) {
568
- return this.Feature('legal', resolve, reject);
569
- }
570
-
571
- /**************
572
- func: Security
573
- params: resolve, reject
574
- describe:
575
- The Security feature sets the correct variables and necessary rules for the
576
- client presented data.
577
- ***************/
578
- Security(resolve, reject) {
579
- return this.Feature('security', resolve, reject);
580
- }
581
-
582
- /**************
583
- func: Support
584
- params: resolve, reject
585
- describe:
586
- The Support feature sets the correct variables and necessary rules for the
587
- client presented data.
588
- ***************/
589
- Support(resolve, reject) {
590
- return this.Feature('support', resolve, reject);
591
- }
592
-
593
- /**************
594
- func: Services
595
- params: resolve, reject
596
- describe:
597
- The Services feature sets the correct variables and necessary rules for the
598
- client presented data.
599
- ***************/
600
- Services(resolve, reject) {
601
- return this.Feature('services', resolve, reject);
602
- }
603
-
604
- /**************
605
- func: Systems
606
- params: client: false
607
- describe:
608
- The Systems feature sets the correct variables and necessary rules for the
609
- client presented data.
610
- ***************/
611
- Systems(resolve, reject) {
612
- return this.Feature('systems', resolve, reject);
613
- }
614
-
615
- /**************
616
- func: Done
617
- params: none
618
- describe: The end of the workflow Client Feature Workflow
619
- ***************/
620
- Done(resolve, reject) {
621
- try {
622
- delete this._client.features; // delete the features key when done.
623
- this.state('Done', 'Done'); // set the done state.
624
- return resolve(this._client); // resolve an empty pr
625
- } catch (e) {
626
- this.state('catch', 'Done');
627
- return this.err(e, false, reject);
628
- }
629
- }
630
-
631
- /**************
632
- func: talk
633
- params:
634
- - evt: The event the Deva is speaking to listen back for on a once event.
635
- - resource: The payload resource to send with the talk event.
636
- describe:
637
- The talk event allows agents to broadcast events that other Deva can listen
638
- to and make a response. talk events can be then returned with a talk even id
639
- to create seamless collaboration between Devas.
640
- ***************/
641
- talk(evt, packet=false) {
642
- return this.events.emit(evt, packet);
643
- }
644
-
645
- /**************
646
- func: listen
647
- params:
648
- - evt: The vent label to listen for
649
- - callback: The callback function to run when the event fires.
650
- describe: setup a new event listener in the system.
651
- ***************/
652
- listen(evt, callback) {
653
- this.action('listen', evt);
654
- this.intent('good', `listen:${evt}`);
655
- this.listeners[evt] = callback;
656
- const handler = packet => this.listeners[evt](packet);
657
- this._bound.set(evt, handler);
658
- return this.events.on(evt, handler);
659
- }
660
-
661
- /**************
662
- func: once
663
- params:
664
- - evt: The event to listen to for a once call.
665
- - callback: The callback functoin to run when the event fires.
666
- describe:
667
- ***************/
668
- once(evt, callback) {
669
- this.action('once', evt);
670
- this.intent('good', `once:${evt}`);
671
- return this.events.once(evt, callback);
672
- }
673
-
674
- /**************
675
- func: ignore
676
- params:
677
- - evt: The event you'd like to ignore.
678
- - callback: a callback function to execute after removing the event from listerns.
679
- describe: The ignore function allow the removal of events in the listener group.
680
- ***************/
681
- ignore(evt, callback) {
682
- this.action('ignore', evt);
683
- this.intent('bad', `ignore:${evt}`);
684
- return this.events.removeListener(evt, callback);
685
- }
686
-
687
- /**************
688
- func: question
689
- example: this.question('#*agent.key *method* *text*')
690
- example: this.question('#*agent.key* *method* *properties*', {*data*})
691
- params:
692
- = TEXT: The text string is the question to process in the current state.
693
- - DATA: The data is a data array or object that also can be passed to the question.
694
- describe:
695
- ***************/
696
- question(TEXT=false, DATA=false) {
697
- if (!this._active) return Promise.resolve(this._messages.offline); // resolve with offline message when not active.
698
- if (!TEXT || typeof TEXT !== 'string') return Promise.resolve(this._messages.notext); // resolve with the no text message if the client says nothing.
699
-
700
- const id = this.uid(); // generate a unique id for transport.
701
- this.zone('question', id.uid);
702
- this.action('question', id.uid);
703
- const t_split = TEXT.split(' '); // split the text on spaces to get words.
704
- const data = DATA; // set the DATA to data
705
-
706
- // check to see if the string is an #ask string to talk to the other Deva.
707
- const isAsk = t_split[0].startsWith(this.askChr);
708
-
709
- // check to see if the string is a command string to run a local method.
710
- const isCmd = t_split[0].startsWith(this.cmdChr);
711
-
712
- // Format the packet for return on the request.
713
- const packet = { // create the base q/a packet
714
- id, // set the id into packet
715
- q: false, // create empty q object in packet
716
- a: false, // create empty a object in packet
717
- created: Date.now(), // timestamp the packet
718
- };
719
-
720
- let text = TEXT, // let TEXT is text for a manipulation variable
721
- params = false, // params as false to build params string
722
- method = 'question', // set the default method to question
723
- key = this.agent().key; // set a temporary key from the agent key.
724
-
725
- return new Promise((resolve, reject) => {
726
-
727
- this.state('try', `${method}:${id.uid}`); // set state to try for process.
728
- try { // try to answer the question
729
- if (isAsk) { // determine if hte question isAsk
730
- // if:isAsk split the agent key and remove first command character
731
- key = t_split[0].substring(1);
732
- //if:isAsk use text split index 1 as the parameter block
733
- params = t_split[1] ? t_split[1].split(':') : false;
734
- method = params[0]; // the method to check is then params index 0
735
- text = t_split.slice(2).join(' ').trim(); // rejoin the text with space
736
- this.state('ask', `${key}:${method}:${id.uid}`);
737
- }
738
- else if (isCmd) { // determine if the question is a command
739
- //if:isCmd use text split index 1 as the parameter block
740
- params = t_split[0] ? t_split[0].split(':') : false;
741
- method = t_split[0].split(':')[0].substring(1); // if:isCmd use the 0 index as the command
742
- text = t_split.slice(1).join(' ').trim(); // if:isCmd rejoin the string on the space after removing first index
743
- this.state('cmd', `${method}:${id.uid}`); // set the state to cmd.
744
- }
745
-
746
- const agent = this.agent(); // set the agent for the packet.
747
- const client = this.client(); // set the client for the packet.
748
-
749
- this.state('data', `${method}:q:${id.uid}`);
750
- packet.q = { // build packet.q container
751
- id: this.uid(), // set the transport id for the question.
752
- agent, // set the agent
753
- client, // set the client
754
- meta: { // build the meta container
755
- key, // set the key variable
756
- method, // set method to track function use
757
- params, // set any params that are associated
758
- },
759
- text, // set the text for the packet.
760
- data, // set the data object
761
- created: Date.now(), // timestamp the question
762
- }
763
-
764
- // stamp the question
765
- packet.q = this._stamp(packet.q, method, id.uid);
766
-
767
- this.action('talk', `${this._events.question}:${id.uid}`);
768
- this.intent('good', `${this._events.question}:${id.uid}`);
769
- this.talk(this._events.question, this.lib.copy(packet)); // global question event make sure to copy data.
770
-
771
- if (isAsk) { // isAsk check if the question isAsk and talk
772
- // if: isAsk wait for the once event which is key'd to the packet ID for specified responses
773
- this.action('ask', `${key}:${id.uid}`);
774
- this.intent('good', `ask:${key}:${id.uid}`);
775
- const evt = `${key}:ask:${packet.id.uid}`; // the once event keyed to this packet.
776
- const pending = {evt, handler: false, timer: false, resolve}; // tracked so shutdown can clean up.
777
-
778
- // single place to release the listener, the timer, and the pending record.
779
- const release = () => {
780
- clearTimeout(pending.timer);
781
- this._pending.delete(pending);
782
- if (this.events) {
783
- packet.a = false;
784
- this.ignore(evt, pending.handler);
785
- this.talk(evt, this.lib.copy(packet));
786
- }
787
- };
788
-
789
- pending.handler = answer => {
790
- clearTimeout(pending.timer); // an answer arrived so cancel the timeout.
791
- this._pending.delete(pending);
792
-
793
- // the asked Deva failed so the asker handles the error like a local method error.
794
- if (answer.error) {
795
- this.state('catch', `${key}:${method}:${id.uid}`);
796
- this.intent('bad', `ask:${key}:${id.uid}`);
797
- return this.err(answer.error, packet, reject);
798
- }
799
-
800
- this.action('talk', `${this._events.ask}:${id.uid}`);
801
- this.intent('good', `${this._events.ask}:${id.uid}`);
802
- this.talk(this._events.ask, this.lib.copy(answer));
803
- this.action('return', `finish:${key}:ask:${id.uid}`);
804
- this.intent('good', `finish:${method}:${id.uid}`);
805
- return this.finish(answer, resolve); // if:isAsk resolve the answer from the call
806
- };
807
-
808
- this._pending.add(pending);
809
- this.once(evt, pending.handler);
810
-
811
- // timeout so a silent Deva cannot hang the caller. 0 disables it.
812
- const wait = this._config.timeout.ask;
813
- if (wait > 0) {
814
- pending.timer = setTimeout(() => {
815
- if (!this._active) return; // shutdown already cleaned up.
816
- release();
817
- this.state('abort', `${key}:${method}:${id.uid}`);
818
- this.intent('bad', `ask:${key}:${id.uid}`);
819
- return resolve(this._messages.asktimeout);
820
- }, wait);
821
- }
822
-
823
- // talk returns false when nobody is listening so fail fast instead of waiting.
824
- const heard = this.talk(`${key}:ask`, this.lib.copy(packet));
825
- if (!heard) {
826
- release();
827
- this.state('invalid', `${key}:${method}:${id.uid}`);
828
- this.intent('bad', `ask:${key}:${id.uid}`);
829
- return resolve(this._messages.noask);
830
- }
831
- }
832
- else { // else: answer the question locally
833
- this.state('answer', `${method}:${id.uid}`); //set the answer state to the method
834
- this.action('return', `${method}:answer:${id.uid}`); //set the answer state to the method
835
- this.intent('good', `${method}:answer:${id.uid}`); //set the answer state to the method
836
- return this.answer(packet, resolve, reject);
837
- }
838
- }
839
- catch(e) {
840
- this.state('catch', `${method}:${id.uid}`);
841
- this.intent('bad', `${method}:${id.uid}`); //set the answer state to the method
842
- return this.err(e, packet, reject); // if a overall error happens this witll call this.err
843
- }
844
- });
845
- }
846
-
847
- /**************
848
- func: answer
849
- params:
850
- - packet
851
- - resolve
852
- - reject
853
- describe:
854
- The answer function is called from the question function to return an answer
855
- from the agent from the pre-determined method.
856
- ***************/
857
- answer(packet, resolve, reject) {
858
- if (!this._active) return Promise.resolve(this._messages.offline);
859
- const id = this.uid();
860
- const key = 'answer';
861
- const subkey = 'packet_answer';
862
-
863
- const agent = this.agent();
864
- const client = this.client();
865
- const {method,params} = packet.q.meta;
866
-
867
- this.zone(key, `${method}:${id.uid}`); // set zone to answer
868
- this.action(key, `${method}:${id.uid}`);
869
- this.state(key, `${method}:${id.uid}`);
870
-
871
- // check if method exists and is of type function
872
-
873
- this.state('try', `${key}:${method}:${id.uid}`);
874
- try {
875
- const isMethod = this.methods[method] && typeof this.methods[method] == 'function';
876
- if (!isMethod) {
877
- this.action('resolve', `${key}:${method}:not_found:${packet.id.uid}`);
878
- this.state('invalid', `${key}:${method}:${packet.id.uid}`);
879
- this.intent('bad', `${key}:${method}:not_found:${packet.id.uid}`);
880
- return resolve(this._methodNotFound(packet)); // resolve method not found if check if} check fails
881
- }
882
-
883
- this.action('method', `${key}:${method}:${id.uid}`);
884
- this.methods[method](packet).then(result => {
885
- // check the result for the text, html, and data object. // this is for when answers are returned from nested Devas.
886
- this.state('set', `${key}:${method}:text:${id.uid}`);
887
- const text = typeof result === 'object' ? result.text : result;
888
-
889
- this.state('set', `${key}:${method}:html:${id.uid}`);
890
- const html = typeof result === 'object' ? result.html : result;
891
-
892
- // if the data passed is NOT an object it will FALSE
893
- this.state('set', `${key}:${method}:data:${id.uid}`);
894
- const data = typeof result === 'object' ? result.data : false;
895
-
896
- this.state('data', `${key}:${method}:${subkey}:${id.uid}`);
897
- const packet_answer = { // setup the packet.a container
898
- id,
899
- agent, // set the agent who answered the question
900
- client, // set the client asking the question
901
- meta: { // setup the answer meta container
902
- key: agent.key, // set the agent key inot the meta
903
- method, // set the method into the meta
904
- params, // set the params into the meta
905
- },
906
- text, // set answer text
907
- html, // set the answer html
908
- data, // set the answer data
909
- created: Date.now(), // set the created date for the answer
910
- };
911
- // stamp the packet_answer into packet.a
912
- packet.a = this._stamp(packet_answer, `${key}:${method}:${subkey}`, id.uid); // set the packet.a to the packet_answer
913
-
914
- this.action('talk', `${this._events.answer}:${id.uid}`);
915
- this.talk(this._events.answer, this.lib.copy(packet)); // global talk event
916
-
917
- this.action('return', `${key}:${method}:finish:${id.uid}`); // set the state resolve answer
918
- this.state('valid', `${key}:${method}:finish:${id.uid}`);
919
- this.intent('good', `${key}:${method}:finish:${id.uid}`);
920
- return this.finish(packet, resolve); // resolve the packet to the caller.
921
- }).catch(err => { // catch any errors in the method
922
- this.state('catch', `${key}:${method}:${id.uid}`); // set the state reject answer
923
- this.intent('bad', `${key}:${method}:${id.uid}`);
924
- return this.err(err, packet, reject); // return this.err with err, packet, reject
925
- });
926
- } catch (e) {
927
- this.state('catch', `${key}:${method}:${id.uid}`);
928
- this.intent('bad', `${key}:${method}:${id.uid}`);
929
- return this.err(e, packet, reject);
930
- }
931
- }
932
-
933
- /**************
934
- func: ask
935
- params: packet
936
- describe:
937
- The ask function gives each agent the ability to ask question to other agents
938
- in the system. When a question is asked the Agent with the question if it
939
- detect an ask event it will trigger. Then if an Agent with the matching ask
940
- event is listening they will respond. The question function uses this to
941
- create integrated communication between itself and other Deva in it's library.
942
-
943
- It can also be used in a custom manner to broadcast ask events inside other coe aswell.
944
-
945
- When the talk has an answer it will respond with a talk event that has the packet id
946
- so the event is specific to the talk.
947
- ***************/
948
- ask(packet) {
949
- if (!this._active) return Promise.resolve(this._messages.offline);
950
- const id = this.uid();
951
- const key = 'ask';
952
- const sub_key = 'packet_answer';
953
- const agent = this.agent();
954
- const client = this.client();
955
- const {method, params} = packet.q.meta;
956
- this.zone(key, `${method}:${packet.id.uid}`);
957
- this.action(key, `${method}:${packet.id.uid}`);
958
- // build the answer packet from this model
959
- this.state('try', `${key}:${method}:${packet.id.uid}`);
960
- try {
961
- if (typeof this.methods[method] !== 'function') {
962
- return setImmediate(() => {
963
- this.action('talk', `${key}:${method}:${packet.id.uid}`);
964
- this.state('invalid', `${key}:${method}:${packet.id.uid}`);
965
- this.intent('bad', `${key}:${method}:${packet.id.uid}`);
966
- return this.talk(`${this._agent.key}:ask:${packet.id.uid}`, this._methodNotFound(packet));
967
- });
968
- }
969
-
970
- this.state('data', `ask:${method}:${sub_key}:${packet.id.uid}`);
971
- const packet_answer = {
972
- id,
973
- agent,
974
- client,
975
- meta: {
976
- key: agent.key,
977
- method,
978
- params,
979
- },
980
- text: false,
981
- html: false,
982
- data: false,
983
- created: Date.now(),
984
- };
985
- // The method is parsed and depending on what method is asked for it returns
986
- // the response based on the passed through packet.
987
- this.methods[method](packet).then(result => {
988
- if (typeof result === 'object') {
989
- this.state('set', `${key}:${method}:${sub_key}:text:${packet.id.uid}`);
990
- packet_answer.text = result.text || false;
991
- this.state('set', `${key}:${method}:${sub_key}:text:${packet.id.uid}`);
992
- packet_answer.html = result.html || false;
993
- this.state('set', `${key}:${method}:${sub_key}:data:${packet.id.uid}`);
994
- packet_answer.data = result.data || false;
995
- }
996
- else {
997
- this.state('set', `${key}:${method}:${sub_key}:result:${packet.id.uid}`);
998
- packet_answer.text = result;
999
- }
1000
-
1001
- // stamp the packet_answer and set it into packet.a.
1002
- this.state('set', `${key}:${method}:packet:a:${packet.id.uid}`);
1003
- packet.a = this._stamp(packet_answer, `${key}:${method}:packet:a`, packet.id.uid); // set the packet answer.
1004
-
1005
- this.state('set', `${key}:${method}:packet:q:agent:${packet.id.uid}`);
1006
- packet.q.agent = agent; // set the question agent as the ask agent.
1007
-
1008
- // create new hashes for the packet before return.
1009
- const packet_stamped = this._stamp(this._unstamp(packet), `${key}:${method}:packet`, packet.id.uid);
1010
-
1011
- this.action('talk', `${this._events.answer}:${key}:${method}:${packet.id.uid}`);
1012
- this.state('valid', `${this._events.answer}:${key}:${method}:${packet.id.uid}`);
1013
- this.intent('good', `${this._events.answer}:${key}:${method}:${packet.id.uid}`);
1014
- this.talk(this._events.answer, this.lib.copy(packet_stamped)); // global talk event
1015
-
1016
- this.action('talk', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1017
- this.state('valid', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1018
- this.intent('good', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1019
- this.talk(`${agent.key}:ask:${packet.id.uid}`, packet_stamped);
1020
-
1021
- }).catch(err => {
1022
- this.action('talk', `${agent.key}:${key}:${method}:err:${packet.id.uid}`);
1023
- this.state('catch', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1024
- this.intent('bad', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1025
- // reply on the asker's event so the asker hears the error right away.
1026
- this.talk(`${agent.key}:${key}:${packet.id.uid}`, {error:err});
1027
- // log the error here; the asker owns the reject.
1028
- return this.err(err, packet, () => {});
1029
- })
1030
- }
1031
- catch (e) {
1032
- this.action('talk', `${agent.key}:${key}:${method}:err:${packet.id.uid}`);
1033
- this.state('catch', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1034
- this.intent('bad', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1035
- this.talk(`${agent.key}:${key}:${packet.id.uid}`, {error:e});
1036
- return this.err(e, packet, () => {});
1037
- }
1038
- // now when we ask the meta params[0] should be the method
1039
- }
1040
-
1041
-
1042
- /**************
1043
- func: init
1044
- params: client - the client data to use that is provided by the clients.
1045
- describe:
1046
- The main init interface where the chain begins. Where the states fire for
1047
- each process of setting:
1048
- 1. Set the Max listeners to control event memory buffer.
1049
- 2. Assign the Inherited Properties
1050
- 3. Assign binding functions and methods to 'this' scope.
1051
- 4. Assign any listeners for additional functionality.
1052
- 5. run the onInit custom function if preset or the start function.
1053
- 6. The start function will create a chain reaction of states that load.
1054
- 7. If there is an error the init function rejects the call.
1055
- usage: this.init(client_object)
1056
- ***************/
1057
- init(client) {
1058
- // set client
1059
- return new Promise((resolve, reject) => {
1060
- // manually set the core hashes to avoid stack overflow from calls
1061
- // this is for the early core hashing needed for uid generation.
1062
- this._core.md5 = this.hash(this._core, 'md5'); // md5 the core and created.
1063
- this._core.sha256 = this.hash(this._core, 'sha256'); // sha256 the core, created, md5
1064
- this._core.sha512 = this.hash(this._core, 'sha512'); // sha512 the core, created, md5, sha256.
1065
-
1066
- // do the core license check on init.
1067
- const license_check = this.license_check(client.VLA, this._core.VLA);
1068
- if (!license_check?.id) {
1069
- this.prompt(license_check); // set license invalid prompt
1070
- return resolve(license_check); // return if} license check fails
1071
- }
15
+ constructor(opts) {
16
+ opts = opts || {}; // set opts to provided opts or an empty object.
17
+ this._core = pkg; // set the core from the package data.
18
+ this._id = opts.id || randomUUID(); // the unique id assigned to the agent at load
19
+ this._info = opts.info || false; // the deva information from the package file.
20
+ this._config = opts.config || {}; // local Config Object
21
+ this._config.hashes = config.hashes; // set hashes array from config for stamping.
22
+ this._config.ready_hash = config.ready_hash; // items to hash at ready
23
+ this._config.timeout = {...config.timeout, ...this._config.timeout}; // add timeout values to _config.
24
+ this._config.hash = this._config.hash || {}; // set the default config hash
25
+
26
+ this._agent = opts.agent || false; // Agent profile object
27
+ this._client = {}; // this will be set on init.
28
+ this._active = false; // the active/birth date.
29
+ this._license = false; // inherited License features.
30
+ this._error = false; // inherited Error features.
31
+ this._log = false; // inherited Log features.
32
+ this._data = false; // inherited Data features.
33
+ this._report = false; // inherited Report features.
34
+ this._legal = false; // inherited Legal features.
35
+ this._security = false; // inherited Security features.
36
+ this._support = false; // inherited Support features.
37
+ this._services = false; // inherited Service features.
38
+ this._systems = false; // inherited Systems features.
39
+
40
+ this.events = opts.events || new EventEmitter({}); // Event Bus
41
+ this.lib = new lib({pkg}); // used for loading library functions
42
+ this.utils = opts.utils || {}; // parse functions inside the deva
43
+ this.devas = opts.devas || {}; // Devas which are loaded
44
+ this.vars = opts.vars || {}; // Variables object
45
+ this.listeners = opts.listeners || {}; // local Listeners
46
+ this.modules = opts.modules || {}; // 3rd Party Modules
47
+ this.func = opts.func || {}; // local Functions
48
+ this.methods = opts.methods || {}; // local Methods
49
+ this.maxListeners = opts.maxListeners || 0; // set the local maxListeners
50
+ // prevent overwriting existing functions and variables with same name
51
+ for (const opt in opts) {
52
+ if (!this[opt] || !this[`_${opt}`]) this[opt] = opts[opt];
53
+ }
54
+
55
+ this.cmdChr = config.cmdChr; // the trigger for local commands
56
+ this.askChr = config.askChr; // the trigger for ask other DEva features
57
+ this.container = config.container // set the container object
58
+ this.box = config.box // set the box object
59
+
60
+ this._inherit = config.inherit; // set inherit from config data.
61
+ this._bind = config.bind; // set the bind from the config data.
62
+ this._binding = new Map(); // set the binding map
63
+
64
+ this._uid = config.uid; // set the uid options
65
+
66
+ this._events = config.events; // set the core system events
67
+ this._bound = new Map(); // evt -> wrapper registered on the shared bus
68
+ this._pending = new Set(); // pending asks: {evt, handler, timer}
69
+ this._stateBound = []; // [event, handler] pairs for the state listeners
70
+
71
+ this._feature = config.feature; // set the feature from config data.
72
+ this._features = config.features; // set the features from config data.
73
+
74
+ this._zone = config.zone; // set the current zone from config data.
75
+ this._zones = {...config.zones}; // set the zones from config data.
76
+ // load any custom zones from the agent file
77
+ if (this._agent.zones) {
78
+ for (let item in this._agent.zones) {
79
+ if (!this._zones[item]) this._zones[item] = this._agent.zones[item];
80
+ }
81
+ delete this._agent.zones;
82
+ }
83
+
84
+ this._action = config.action; // set the action from config data.
85
+ this._actions = {...config.actions}; // set the actions from config data.
86
+ // load any custom actions from the agent file
87
+ if (this._agent.actions) {
88
+ for (let item in this._agent.actions) {
89
+ if (!this._actions[item]) this._actions[item] = this._agent.actions[item];
90
+ }
91
+ delete this._agent.actions;
92
+ }
93
+
94
+ this._state = config.state; // set the current state from config data.
95
+ this._states = {...config.states}; // set the states from options
96
+ // load any custom states from the agent file
97
+ if (this._agent.states) {
98
+ for (let item in this._agent.states) {
99
+ if (!this._states[item]) this._states[item] = this._agent.states[item];
100
+ }
101
+ delete this._agent.states;
102
+ }
103
+
104
+ this._intent = config.intent; // set the current intent from config data.
105
+ this._intents = {...config.intents}; // set the states from options
106
+ // load any custom actions from the agent file
107
+ if (this._agent.intents) {
108
+ for (let item in this._agent.intents) {
109
+ if (!this._intents[item]) this._intents[item] = this._agent.intents[item];
110
+ }
111
+ delete this._agent.intents;
112
+ }
113
+
114
+ this._belief = config.belief; // set the current belief from config data.
115
+ this._beliefs = {...config.beliefs}; // set the states from options
116
+ // load any custom actions from the agent file
117
+ if (this._agent.beliefs) {
118
+ for (let item in this._agent.beliefs) {
119
+ if (!this._beliefs[item]) this._beliefs[item] = this._agent.beliefs[item];
120
+ }
121
+ delete this._agent.beliefs;
122
+ }
123
+
124
+ this._context = config.context || false; // set the local context
125
+
126
+ this._messages = {...config.messages}; // set the messages from config data.
127
+ // load any custom actions from the agent file
128
+ if (this._agent.messages) {
129
+ for (let item in this._agent.messages) {
130
+ if (!this._messages[item]) this._messages[item] = this._agent.messages[item];
131
+ }
132
+ delete this._agent.messages;
133
+ }
134
+
135
+ }
136
+
137
+ /**************
138
+ func: _assignBind
139
+ params: none
140
+ describe:
141
+ The assign bind function will bind the translate functions and parse functions
142
+ of the agent and bind their functionality to the state machine.
143
+
144
+ ***************/
145
+ _assignBind() {
146
+ return new Promise((resolve, reject) => {
147
+ try {
148
+ this._bind.forEach(bind => { // loop over the bind items func, method, listener...
149
+ if (this[bind]) for (let x in this[bind]) { // if the root has a bind func, method, listener
150
+ // check to make sure the binding is a function.
151
+ if (typeof this[bind][x] === 'function') {
152
+ // check to make sure object is a function
153
+ if (!this._binding.has(bind)) this._binding.set(bind, {});
154
+ this._binding.get(bind)[x] = this[bind][x].toString();
155
+ this[bind][x] = this[bind][x].bind(this);
156
+ }
157
+ }
158
+ });
159
+ return resolve(); // when the configuration is complete then return an empty resolve.
160
+ }
161
+ catch (e) {
162
+ return this.err(e, false, reject); // trigger the this.err for errors
163
+ }
164
+ });
165
+ }
166
+
167
+ /**************
168
+ func: _assignListeners
169
+ params: none
170
+ describe:
171
+ Assign listeners will take the this.lisners objects and assign the appropriate
172
+ lisnter values for the event bus.
173
+ ***************/
174
+ _assignListeners() {
175
+ return new Promise((resolve, reject) => {
176
+ try {
177
+
178
+ // set the default listeners for the states of the agent.
179
+ for (let state in this._states) {
180
+ if (typeof this[state] === 'function') {
181
+ const evt = `${this._agent.key}:${state}`;
182
+ const handler = packet => this[state](packet);
183
+ this._stateBound.push([evt, handler]); // keep it so shutdown can remove it
184
+ this.events.on(evt, handler);
185
+ }
186
+ }
187
+
188
+ // set the assigned listeners for the agent.
189
+ for (let listener in this.listeners) { // loop over the listeners
190
+ const handler = packet => this.listeners[listener](packet);
191
+ this._bound.set(listener, handler);
192
+ this.events.on(listener, handler);
193
+ }
194
+ return resolve(); // resolve the function after everything is done.
195
+ }
196
+ catch (e) {
197
+ return this.err(e, false, reject); // pass errors to this.err
198
+ }
199
+ });
200
+ }
201
+
202
+ /**************
203
+ func: _removeListeners
204
+ params: none
205
+ describe:
206
+ Remove listeners will take the this.lisners objects and remove the appropriate
207
+ listener values for the event bus.
208
+ ***************/
209
+ _removeListeners() {
210
+ if (!this.events || !this.listeners) return;
211
+ for (const evt in this.listeners) {
212
+ const handler = this._bound.get(evt);
213
+ if (handler) this.ignore(evt, handler); // ignore() already calls events.removeListener
214
+ }
215
+ this._bound.clear();
216
+ for (const [evt, handler] of this._stateBound) this.ignore(evt, handler); // state listeners from _assignListeners
217
+ this._stateBound = [];
218
+ return this._clearPending(); // pending asks go in the same pass
219
+ }
220
+
221
+ /**************
222
+ func: _clearPending
223
+ params: none
224
+ describe:
225
+ Clears the timer and removes the listener for every pending ask so a
226
+ shutdown leaves nothing behind on the shared event bus.
227
+ ***************/
228
+ _clearPending() {
229
+ if (!this._pending) return;
230
+ for (const pending of this._pending) {
231
+ clearTimeout(pending.timer);
232
+ if (this.events) this.ignore(pending.evt, pending.handler);
233
+ pending.resolve(this._messages.offline); // the Deva is going offline so answer the waiting caller.
234
+ }
235
+ this._pending.clear();
236
+ }
237
+
238
+ // Some elements will inherit the data of the parent. this object will loop over
239
+ // any children data that this deva has and assign the inherited information.
240
+ /**************
241
+ func: _assignInherit
242
+ params: none
243
+ describe:
244
+ The assign inherit will make sure the Devas in the current Deva have all the
245
+ inherited properties all setup to collaborate efficiently.
246
+ ***************/
247
+ _assignInherit() {
248
+ return new Promise((resolve, reject) => {
249
+ try {
250
+ for (let d in this.devas) {
251
+ this._inherit.forEach(inherit => {
252
+ this.devas[d][inherit] = this[inherit];
253
+ });
254
+ }
255
+ return resolve();
256
+ }
257
+ catch (e) {
258
+ return this.err(e, false, reject);
259
+ }
260
+ });
261
+ }
262
+
263
+ // General handler for when a method is NOT found from a user command.
264
+ /**************
265
+ func: _methodNotFound
266
+ params:
267
+ - packet: The packet to relay when a method is not found.
268
+ describe:
269
+ The _methodNotFound function allows for additional security by firing
270
+ a specfici program functon every single time a interaction happens wehre a
271
+ method is not located. This assits in security and support by identifying
272
+ troubls or users who may be attemptng to explit features.
273
+
274
+ Then we talk a security event that watches all methods and return the packet.
275
+
276
+ This will return a not found text string preventing any furhter processing.
277
+ ***************/
278
+ _methodNotFound(packet) {
279
+ if (!this._active) return this._messages.offline; // check the active status
280
+ const id = this.uid();
281
+ const agent = this.agent() || false;
282
+ const client = this.client() || false;
283
+ const {meta, params} = packet.q;
284
+ const text = `${this._messages.method_not_found} ${agent.key} ${meta.method}`
285
+ const packet_answer = {
286
+ id,
287
+ agent,
288
+ client,
289
+ text,
290
+ meta: {
291
+ key: agent.key,
292
+ method: meta.method,
293
+ },
294
+ created: Date.now(),
295
+ };
296
+ // set packet into packet.a after stamping it.
297
+ packet.a = this._stamp(packet_answer);
298
+
299
+ // stamp the packet before return
300
+ const packet_stamped = this._stamp(this._unstamp(packet), `methodNotFound:${meta.method}`, packet.id.uid);
301
+ this.state('invalid', `${meta.method}:${packet.id.uid}`);
302
+ return packet;
303
+ }
304
+
305
+ /**************
306
+ func: _getFeature
307
+ params:
308
+ - key: the feature key parameter.
309
+ - value: the value being passed into the data.
310
+ describe:
311
+ ***************/
312
+ _getFeature(key) {
313
+ if (!this._active) return this._messages.offline; // check the active status
314
+ if (!this._features[key]) return this._messages.invalidfeature; // return no key if doesn't match.
315
+
316
+ this.feature(key); // set the security state
317
+ this.zone(key); // set the zone to the key.
318
+ this.state('try', key); // set the state to try.
319
+ try {
320
+ const data = this.lib.copy(this[`_${key}`]);
321
+ this.action('return', `_getFeature:${key}`); // set the return action
322
+ this.state('valid', `_getFeature:${key}`); // set the valid state
323
+ this.intent('good', `_getFeature:${key}`); // set the intent good
324
+ return data; // return the data
325
+ } catch (err) {
326
+ this.state('catch', `_getFeature:${key}`);
327
+ this.intent('bad', `_getFeature:${key}`);
328
+ return this.err(err);
329
+ }
330
+ }
331
+
332
+ /**************
333
+ func: _invoke
334
+ params:
335
+ - data: the data to pass to the resolve
336
+ - resolve: the complete resolve to pass back
337
+ describe: The _invoke function is used for the recursion over
338
+ init, start, enter, done ready, finish, complete
339
+ usage: this.complete(data, resolve)
340
+ ***************/
341
+ _invoke(opts) {
342
+ const {key, data, resolve} = opts;
343
+ if (!this._active) return resolve(this._messages.offline);
344
+ if (!key) return resolve (this._messages.nokey);
345
+ if (!config.invoke[key]) return resolve (this._messages.invalidkey);
346
+ if (!data) return resolve (this._messages.nodata);
347
+
348
+ const {next_key, onfunc, clear} = config.invoke[key];
349
+ this.action('invoke', `${key}:${data.id.uid}`);
350
+ this.context(key, data.id.uid);
351
+ this.zone(key, data.id.uid);
352
+ this.action(key, data.id.uid);
353
+ this.state(key, data.id.uid);
354
+
355
+ this.state('data', `${key}:date:${data.id.uid}`);
356
+ data[key] = Date.now();// set the complete date on the whole data.
357
+
358
+ const data_stamped = this._stamp(this._unstamp(data), key, data.id.uid);
359
+
360
+ // setup the complete talk veent
361
+ this.action('talk', `${this._events[key]}:${data.id.uid}`); // action talk for the event.
362
+ this.talk(this._events[key], this.lib.copy(data)); // talk the complete event
363
+
364
+ if (clear) {
365
+ this.state('loop', `${key}:clear:${data.id.uid}`);
366
+ for (let item of clear) {
367
+ if (item === 'listeners') this._removeListeners();
368
+ this[item] = false;
369
+ }
370
+ }
371
+
372
+ // determine if there is an onComplete function for the entity.
373
+ const hasOnFunc = this[onfunc] && typeof this[onfunc] === 'function';
374
+ if (hasOnFunc) {
375
+ this.action('return', `onfunc:${onfunc}:${data.id.uid}`); // action return
376
+ this.state('valid', `onfunc:${onfunc}:${data.id.uid}`); // state valid
377
+ this.intent('good', `onfunc:${onfunc}:${data.id.uid}`); // intent good
378
+ return this[onfunc](data, resolve);
379
+ }
380
+
381
+ this.action('return', `${key}:${data.id.uid}`); // return action complete
382
+ this.state('valid', `${key}:${data.id.uid}`); // return state valid
383
+ this.intent('good', `${key}:${data.id.uid}`); // return intent good
384
+ return next_key ? this[next_key](data, resolve) : resolve(data);
385
+ }
386
+
387
+ /**************
388
+ func: _stamp
389
+ params:
390
+ - data: the data to stamp
391
+ - label: the label for the hash action.
392
+ describe: the stamp function will take a data object and apply the hashes from the this._config.hashes array.
393
+ usage: this._stamp(data, 'value')
394
+ ***************/
395
+ _stamp(data, label='', uid='') {
396
+ for (const algo of this._config.hashes) {
397
+ if (label) this.action('hash', `${label}:${algo}:${uid}`);
398
+ data[algo] = this.hash(data, algo);
399
+ }
400
+ return data;
401
+ }
402
+
403
+ /**************
404
+ func: _unstamp
405
+ params:
406
+ - data: the data to unstamp
407
+ describe: the unstamp function will take a data object and remove the hashes over the this._hashes array.
408
+ usage: this._unstamp(data)
409
+ ***************/
410
+ _unstamp(data) {
411
+ const id = data.id?.uid || this._messages.noid; // check for proper id in the data.
412
+ for (const algo of this._config.hashes) {
413
+ this.action('delete', `${algo}:${id}`);
414
+ delete data[algo]
415
+ };
416
+ return data;
417
+ }
418
+
419
+ /**************
420
+ func: Client
421
+ params: client - client provided data.
422
+ describe:
423
+ The Client feature sets up the client variables and removes any unnecessary
424
+ keys from the client object that are used in other features.
425
+
426
+ usage:
427
+ this.Client = {data}
428
+ ***************/
429
+ Client(client, resolve, reject) {
430
+ this.feature('client', `client:${client.id}`);
431
+ this.zone('client', `client:${client.id}`);
432
+ this.action('client', `client:${client.id}`);
433
+ // setup any custom methods for the features
434
+ this.state('try', `client:${client.id}`);
435
+ try {
436
+ this.state('set', `client:methods:${client.id}`);
437
+ for (const x in client.features) {
438
+ const methods = client.features[x].methods || false;
439
+ if (methods) for (const y in methods) {
440
+ const isFunc = typeof methods[y] === 'function';
441
+ if (isFunc) {
442
+ this.methods[y] = methods[y].bind(this);
443
+ }
444
+ }
445
+ }
446
+ const _client = this.lib.copy(client); // copy the client parameter
447
+ this.state('data', `client:${client.id}`); // set the state to data for client.
448
+ this._client = _client; // set local _client to this scope
449
+
450
+ this.action('return', `client:${client.id}`); // set the action
451
+ this.intent('good', `client:${client.id}`); // set the intent
452
+ return resolve(_client); // resolve the client .
453
+ } catch (e) {
454
+ this.state('catch', `client:${client.id}`);
455
+ this.intent('bad', `client:${client.id}`);
456
+ return this.err(e, false, reject);
457
+ }
458
+ }
459
+
460
+ /**************
461
+ func: Feature
462
+ params: client: false
463
+ describe:
464
+ The Security feature sets the correct variables and necessary rules for the
465
+ client presented data.
466
+ ***************/
467
+ Feature(feature, resolve, reject) {
468
+ if (!this._features[feature]) return reject(this._messages.invalidfeature); // reject if there is no feature match.
469
+ const _id = this.uid();
470
+ this.feature(feature, _id.uid);
471
+ this.zone(feature, _id.uid);
472
+ try {
473
+ if (!this._features[feature]) return resolve(this._messages.invalidfeature); // if no feature resolve invalid feature
474
+ else {
475
+ const call_str = `Feature:${feature}:${_id.uid}` // call string for action state intent.
476
+ this.action('feature', call_str); // set action to feature
477
+ this.state('data', call_str); // set state to data
478
+
479
+ const {id, profile = {}, features = {}} = this.client();
480
+ const data = features[feature] || {};
481
+
482
+ this.state('set', `Feature:this._${feature}:${_id.uid}`); // set the feature state value
483
+ this[`_${feature}`] = { // set this feature with data
484
+ id: _id, // uid of the feature
485
+ client_id: id, // client id for reference
486
+ client_name: profile.name || this._messages.noname,
487
+ concerns: data.concerns || this._messages.noconcerns,
488
+ global: data.global || this._messages.noglobal,
489
+ personal: data.devas ? data.devas[this._agent.key] : this._messages.nodevas,
490
+ created: Date.now(),
491
+ };
492
+ if (this._client.features) {
493
+ this.state('delete', `Feature:client:${feature}:${_id.uid}`); // set the state to delete
494
+ delete this._client.features[feature]; // delete the feature
495
+ }
496
+
497
+ this.action('return', call_str); // set the action to return
498
+ this.state('resolve', call_str); // set the state to resolve
499
+ this.intent('good', call_str); // set the intent to good.
500
+ return resolve(feature); // resolve when done
501
+ }
502
+ } catch (e) {
503
+ this.state('catch', `${feature}:${_id.uid}`); // set the state to catch.
504
+ this.intent('bad', `${feature}:catch:${_id.uid}`); // set the intent to bad.
505
+ return this.err(e, feature, reject); // run error handling if an error is caught
506
+ }
507
+ }
508
+
509
+ /**************
510
+ func: License
511
+ params: resolve, reject
512
+ describe:
513
+ The License feature sets the correct variables and necessary rules for the
514
+ client presented data.
515
+ ***************/
516
+ License(resolve, reject) {
517
+ return this.Feature('license', resolve, reject);
518
+ }
519
+
520
+ /**************
521
+ func: Error
522
+ params: resolve, reject
523
+ describe:
524
+ The Error feature sets the correct variables and necessary rules for the
525
+ client presented data.
526
+ ***************/
527
+ Error(resolve, reject) {
528
+ return this.Feature('error', resolve, reject);
529
+ }
530
+
531
+ /**************
532
+ func: Log
533
+ params: resolve, reject
534
+ describe:
535
+ The Log feature sets the correct variables and necessary rules for the
536
+ client presented data.
537
+ ***************/
538
+ Log(resolve, reject) {
539
+ return this.Feature('log', resolve, reject);
540
+ }
541
+
542
+ /**************
543
+ func: Data
544
+ params: resolve, reject
545
+ describe:
546
+ The Data feature sets the correct variables and necessary rules for the
547
+ client presented data.
548
+ ***************/
549
+ Data(resolve, reject) {
550
+ return this.Feature('data', resolve, reject);
551
+ }
552
+
553
+ /**************
554
+ func: Report
555
+ params: resolve, reject
556
+ describe:
557
+ The Report feature sets the correct variables and necessary rules for the
558
+ client presented data.
559
+ ***************/
560
+ Report(resolve, reject) {
561
+ return this.Feature('report', resolve, reject);
562
+ }
563
+
564
+ /**************
565
+ func: Legal
566
+ params: resolve, reject
567
+ describe:
568
+ The Legal feature sets the correct variables and necessary rules for the
569
+ client presented data.
570
+ ***************/
571
+ Legal(resolve, reject) {
572
+ return this.Feature('legal', resolve, reject);
573
+ }
574
+
575
+ /**************
576
+ func: Security
577
+ params: resolve, reject
578
+ describe:
579
+ The Security feature sets the correct variables and necessary rules for the
580
+ client presented data.
581
+ ***************/
582
+ Security(resolve, reject) {
583
+ return this.Feature('security', resolve, reject);
584
+ }
585
+
586
+ /**************
587
+ func: Support
588
+ params: resolve, reject
589
+ describe:
590
+ The Support feature sets the correct variables and necessary rules for the
591
+ client presented data.
592
+ ***************/
593
+ Support(resolve, reject) {
594
+ return this.Feature('support', resolve, reject);
595
+ }
596
+
597
+ /**************
598
+ func: Services
599
+ params: resolve, reject
600
+ describe:
601
+ The Services feature sets the correct variables and necessary rules for the
602
+ client presented data.
603
+ ***************/
604
+ Services(resolve, reject) {
605
+ return this.Feature('services', resolve, reject);
606
+ }
607
+
608
+ /**************
609
+ func: Systems
610
+ params: client: false
611
+ describe:
612
+ The Systems feature sets the correct variables and necessary rules for the
613
+ client presented data.
614
+ ***************/
615
+ Systems(resolve, reject) {
616
+ return this.Feature('systems', resolve, reject);
617
+ }
618
+
619
+ /**************
620
+ func: Done
621
+ params: none
622
+ describe: The end of the workflow Client Feature Workflow
623
+ ***************/
624
+ Done(resolve, reject) {
625
+ try {
626
+ delete this._client.features; // delete the features key when done.
627
+ this.state('Done', 'Done'); // set the done state.
628
+ return resolve(this._client); // resolve an empty pr
629
+ } catch (e) {
630
+ this.state('catch', 'Done');
631
+ return this.err(e, false, reject);
632
+ }
633
+ }
634
+
635
+ /**************
636
+ func: talk
637
+ params:
638
+ - evt: The event the Deva is speaking to listen back for on a once event.
639
+ - resource: The payload resource to send with the talk event.
640
+ describe:
641
+ The talk event allows agents to broadcast events that other Deva can listen
642
+ to and make a response. talk events can be then returned with a talk even id
643
+ to create seamless collaboration between Devas.
644
+ ***************/
645
+ talk(evt, packet=false) {
646
+ if (!this.events) return this._messages.offline; // return offline if no events.
647
+ return this.events.emit(evt, packet);
648
+ }
649
+
650
+ /**************
651
+ func: listen
652
+ params:
653
+ - evt: The vent label to listen for
654
+ - callback: The callback function to run when the event fires.
655
+ describe: setup a new event listener in the system.
656
+ ***************/
657
+ listen(evt, callback) {
658
+ if (!this.events) return this._messages.offline; // return offline if no events.
659
+ this.action('listen', evt);
660
+ this.intent('good', `listen:${evt}`);
661
+
662
+ const existing = this._bound.get(evt); // already on the bus from init or an earlier listen
663
+ if (existing) this.events.removeListener(evt, existing); // take the old wrapper off first
664
+
665
+ this.listeners[evt] = callback.bind(this); // set the event into this.listeners.
666
+ const handler = packet => this.listeners[evt](packet); // build the handler
667
+ this._bound.set(evt, handler); // set the vent into _bound events.
668
+ return this.events.on(evt, handler); // return the event
669
+ }
670
+
671
+ /**************
672
+ func: once
673
+ params:
674
+ - evt: The event to listen to for a once call.
675
+ - callback: The callback functoin to run when the event fires.
676
+ describe:
677
+ ***************/
678
+ once(evt, callback) {
679
+ if (!this.events) return this._messages.offline; // return offline if no events.
680
+ this.action('once', evt);
681
+ this.intent('good', `once:${evt}`);
682
+ return this.events.once(evt, callback);
683
+ }
684
+
685
+ /**************
686
+ func: ignore
687
+ params:
688
+ - evt: The event you'd like to ignore.
689
+ - callback: a callback function to execute after removing the event from listerns.
690
+ describe: The ignore function allow the removal of events in the listener group.
691
+ ***************/
692
+ ignore(evt, callback) {
693
+ if (!this.events) return this._messages.offline; // return offline if no events.
694
+ this.action('ignore', evt);
695
+ this.intent('bad', `ignore:${evt}`);
696
+ return this.events.removeListener(evt, callback);
697
+ }
698
+
699
+ /**************
700
+ func: question
701
+ example: this.question('#*agent.key *method* *text*')
702
+ example: this.question('#*agent.key* *method* *properties*', {*data*})
703
+ params:
704
+ = TEXT: The text string is the question to process in the current state.
705
+ - DATA: The data is a data array or object that also can be passed to the question.
706
+ describe:
707
+ ***************/
708
+ question(TEXT=false, DATA=false) {
709
+ if (!this._active) return Promise.resolve(this._messages.offline); // resolve with offline message when not active.
710
+ if (!TEXT || typeof TEXT !== 'string') return Promise.resolve(this._messages.notext); // resolve with the no text message if the client says nothing.
711
+
712
+ const id = this.uid(); // generate a unique id for transport.
713
+ this.zone('question', id.uid);
714
+ this.action('question', id.uid);
715
+ const t_split = TEXT.split(' '); // split the text on spaces to get words.
716
+ const data = DATA; // set the DATA to data
717
+
718
+ // check to see if the string is an #ask string to talk to the other Deva.
719
+ const isAsk = t_split[0].startsWith(this.askChr);
720
+
721
+ // check to see if the string is a command string to run a local method.
722
+ const isCmd = t_split[0].startsWith(this.cmdChr);
723
+
724
+ // Format the packet for return on the request.
725
+ const packet = { // create the base q/a packet
726
+ id, // set the id into packet
727
+ q: false, // create empty q object in packet
728
+ a: false, // create empty a object in packet
729
+ created: Date.now(), // timestamp the packet
730
+ };
731
+
732
+ let text = TEXT, // let TEXT is text for a manipulation variable
733
+ params = false, // params as false to build params string
734
+ method = 'question', // set the default method to question
735
+ key = this.agent().key; // set a temporary key from the agent key.
736
+
737
+ return new Promise((resolve, reject) => {
738
+
739
+ this.state('try', `${method}:${id.uid}`); // set state to try for process.
740
+ try { // try to answer the question
741
+ if (isAsk) { // determine if hte question isAsk
742
+ // if:isAsk split the agent key and remove first command character
743
+ key = t_split[0].substring(1);
744
+ //if:isAsk use text split index 1 as the parameter block
745
+ params = t_split[1] ? t_split[1].split(':') : false;
746
+ method = params[0]; // the method to check is then params index 0
747
+ text = t_split.slice(2).join(' ').trim(); // rejoin the text with space
748
+ this.state('ask', `${key}:${method}:${id.uid}`);
749
+ }
750
+ else if (isCmd) { // determine if the question is a command
751
+ //if:isCmd use text split index 1 as the parameter block
752
+ params = t_split[0] ? t_split[0].split(':') : false;
753
+ method = t_split[0].split(':')[0].substring(1); // if:isCmd use the 0 index as the command
754
+ text = t_split.slice(1).join(' ').trim(); // if:isCmd rejoin the string on the space after removing first index
755
+ this.state('cmd', `${method}:${id.uid}`); // set the state to cmd.
756
+ }
757
+
758
+ const agent = this.agent(); // set the agent for the packet.
759
+ const client = this.client(); // set the client for the packet.
760
+
761
+ this.state('data', `${method}:q:${id.uid}`);
762
+ packet.q = { // build packet.q container
763
+ id: this.uid(), // set the transport id for the question.
764
+ agent, // set the agent
765
+ client, // set the client
766
+ meta: { // build the meta container
767
+ key, // set the key variable
768
+ method, // set method to track function use
769
+ params, // set any params that are associated
770
+ },
771
+ text, // set the text for the packet.
772
+ data, // set the data object
773
+ created: Date.now(), // timestamp the question
774
+ }
775
+
776
+ // stamp the question
777
+ packet.q = this._stamp(packet.q, method, id.uid);
778
+
779
+ this.action('talk', `${this._events.question}:${id.uid}`);
780
+ this.intent('good', `${this._events.question}:${id.uid}`);
781
+ this.talk(this._events.question, this.lib.copy(packet)); // global question event make sure to copy data.
782
+
783
+ if (isAsk) { // isAsk check if the question isAsk and talk
784
+ // if: isAsk wait for the once event which is key'd to the packet ID for specified responses
785
+ this.action('ask', `${key}:${id.uid}`);
786
+ this.intent('good', `ask:${key}:${id.uid}`);
787
+ const evt = `${key}:ask:${packet.id.uid}`; // the once event keyed to this packet.
788
+ const pending = {evt, handler: false, timer: false, resolve}; // tracked so shutdown can clean up.
789
+
790
+ // single place to release the listener, the timer, and the pending record.
791
+ const release = () => {
792
+ clearTimeout(pending.timer);
793
+ this._pending.delete(pending);
794
+ if (this.events) {
795
+ packet.a = false;
796
+ this.ignore(evt, pending.handler);
797
+ this.talk(evt, this.lib.copy(packet));
798
+ }
799
+ };
800
+
801
+ pending.handler = answer => {
802
+ clearTimeout(pending.timer); // an answer arrived so cancel the timeout.
803
+ this._pending.delete(pending);
804
+
805
+ // the asked Deva failed so the asker handles the error like a local method error.
806
+ if (answer.error) {
807
+ this.state('catch', `${key}:${method}:${id.uid}`);
808
+ this.intent('bad', `ask:${key}:${id.uid}`);
809
+ return this.err(answer.error, packet, reject);
810
+ }
811
+
812
+ this.action('talk', `${this._events.ask}:${id.uid}`);
813
+ this.intent('good', `${this._events.ask}:${id.uid}`);
814
+ this.talk(this._events.ask, this.lib.copy(answer));
815
+ this.action('return', `finish:${key}:ask:${id.uid}`);
816
+ this.intent('good', `finish:${method}:${id.uid}`);
817
+ return this.finish(answer, resolve); // if:isAsk resolve the answer from the call
818
+ };
819
+
820
+ this._pending.add(pending);
821
+ this.once(evt, pending.handler);
822
+
823
+ // timeout so a silent Deva cannot hang the caller. 0 disables it.
824
+ const wait = this._config.timeout.ask;
825
+ if (wait > 0) {
826
+ pending.timer = setTimeout(() => {
827
+ if (!this._active) return; // shutdown already cleaned up.
828
+ release();
829
+ this.state('abort', `${key}:${method}:${id.uid}`);
830
+ this.intent('bad', `ask:${key}:${id.uid}`);
831
+ return resolve(this._messages.asktimeout);
832
+ }, wait);
833
+ }
834
+
835
+ // talk returns false when nobody is listening so fail fast instead of waiting.
836
+ const heard = this.talk(`${key}:ask`, this.lib.copy(packet));
837
+ if (!heard) {
838
+ release();
839
+ this.state('invalid', `${key}:${method}:${id.uid}`);
840
+ this.intent('bad', `ask:${key}:${id.uid}`);
841
+ return resolve(this._messages.noask);
842
+ }
843
+ }
844
+ else { // else: answer the question locally
845
+ this.state('answer', `${method}:${id.uid}`); //set the answer state to the method
846
+ this.action('return', `${method}:answer:${id.uid}`); //set the answer state to the method
847
+ this.intent('good', `${method}:answer:${id.uid}`); //set the answer state to the method
848
+ return this.answer(packet, resolve, reject);
849
+ }
850
+ }
851
+ catch(e) {
852
+ this.state('catch', `${method}:${id.uid}`);
853
+ this.intent('bad', `${method}:${id.uid}`); //set the answer state to the method
854
+ return this.err(e, packet, reject); // if a overall error happens this witll call this.err
855
+ }
856
+ });
857
+ }
858
+
859
+ /**************
860
+ func: answer
861
+ params:
862
+ - packet
863
+ - resolve
864
+ - reject
865
+ describe:
866
+ The answer function is called from the question function to return an answer
867
+ from the agent from the pre-determined method.
868
+ ***************/
869
+ answer(packet, resolve, reject) {
870
+ if (!this._active) return Promise.resolve(this._messages.offline);
871
+ const id = this.uid();
872
+ const key = 'answer';
873
+ const subkey = 'packet_answer';
874
+
875
+ const agent = this.agent();
876
+ const client = this.client();
877
+ const {method,params} = packet.q.meta;
878
+
879
+ this.zone(key, `${method}:${id.uid}`); // set zone to answer
880
+ this.action(key, `${method}:${id.uid}`);
881
+ this.state(key, `${method}:${id.uid}`);
882
+
883
+ // check if method exists and is of type function
884
+
885
+ this.state('try', `${key}:${method}:${id.uid}`);
886
+ try {
887
+ const isMethod = this.methods[method] && typeof this.methods[method] == 'function';
888
+ if (!isMethod) {
889
+ this.action('resolve', `${key}:${method}:not_found:${packet.id.uid}`);
890
+ this.state('invalid', `${key}:${method}:${packet.id.uid}`);
891
+ this.intent('bad', `${key}:${method}:not_found:${packet.id.uid}`);
892
+ return resolve(this._methodNotFound(packet)); // resolve method not found if check if} check fails
893
+ }
894
+
895
+ this.action('method', `${key}:${method}:${id.uid}`);
896
+ this.methods[method](packet).then(result => {
897
+ // check the result for the text, html, and data object. // this is for when answers are returned from nested Devas.
898
+ this.state('set', `${key}:${method}:text:${id.uid}`);
899
+ const text = typeof result === 'object' ? result.text : result;
900
+
901
+ this.state('set', `${key}:${method}:html:${id.uid}`);
902
+ const html = typeof result === 'object' ? result.html : result;
903
+
904
+ // if the data passed is NOT an object it will FALSE
905
+ this.state('set', `${key}:${method}:data:${id.uid}`);
906
+ const data = typeof result === 'object' ? result.data : false;
907
+
908
+ this.state('data', `${key}:${method}:${subkey}:${id.uid}`);
909
+ const packet_answer = { // setup the packet.a container
910
+ id,
911
+ agent, // set the agent who answered the question
912
+ client, // set the client asking the question
913
+ meta: { // setup the answer meta container
914
+ key: agent.key, // set the agent key inot the meta
915
+ method, // set the method into the meta
916
+ params, // set the params into the meta
917
+ },
918
+ text, // set answer text
919
+ html, // set the answer html
920
+ data, // set the answer data
921
+ created: Date.now(), // set the created date for the answer
922
+ };
923
+ // stamp the packet_answer into packet.a
924
+ packet.a = this._stamp(packet_answer, `${key}:${method}:${subkey}`, id.uid); // set the packet.a to the packet_answer
925
+
926
+ this.action('talk', `${this._events.answer}:${id.uid}`);
927
+ this.talk(this._events.answer, this.lib.copy(packet)); // global talk event
928
+
929
+ this.action('return', `${key}:${method}:finish:${id.uid}`); // set the state resolve answer
930
+ this.state('valid', `${key}:${method}:finish:${id.uid}`);
931
+ this.intent('good', `${key}:${method}:finish:${id.uid}`);
932
+ return this.finish(packet, resolve); // resolve the packet to the caller.
933
+ }).catch(err => { // catch any errors in the method
934
+ this.state('catch', `${key}:${method}:${id.uid}`); // set the state reject answer
935
+ this.intent('bad', `${key}:${method}:${id.uid}`);
936
+ return this.err(err, packet, reject); // return this.err with err, packet, reject
937
+ });
938
+ } catch (e) {
939
+ this.state('catch', `${key}:${method}:${id.uid}`);
940
+ this.intent('bad', `${key}:${method}:${id.uid}`);
941
+ return this.err(e, packet, reject);
942
+ }
943
+ }
944
+
945
+ /**************
946
+ func: ask
947
+ params: packet
948
+ describe:
949
+ The ask function gives each agent the ability to ask question to other agents
950
+ in the system. When a question is asked the Agent with the question if it
951
+ detect an ask event it will trigger. Then if an Agent with the matching ask
952
+ event is listening they will respond. The question function uses this to
953
+ create integrated communication between itself and other Deva in it's library.
954
+
955
+ It can also be used in a custom manner to broadcast ask events inside other coe aswell.
956
+
957
+ When the talk has an answer it will respond with a talk event that has the packet id
958
+ so the event is specific to the talk.
959
+ ***************/
960
+ ask(packet) {
961
+ if (!this._active) return Promise.resolve(this._messages.offline);
962
+ const id = this.uid();
963
+ const key = 'ask';
964
+ const sub_key = 'packet_answer';
965
+ const agent = this.agent();
966
+ const client = this.client();
967
+ const {method, params} = packet.q.meta;
968
+ this.zone(key, `${method}:${packet.id.uid}`);
969
+ this.action(key, `${method}:${packet.id.uid}`);
970
+ // build the answer packet from this model
971
+ this.state('try', `${key}:${method}:${packet.id.uid}`);
972
+ try {
973
+ if (typeof this.methods[method] !== 'function') {
974
+ return setImmediate(() => {
975
+ this.action('talk', `${key}:${method}:${packet.id.uid}`);
976
+ this.state('invalid', `${key}:${method}:${packet.id.uid}`);
977
+ this.intent('bad', `${key}:${method}:${packet.id.uid}`);
978
+ return this.talk(`${this._agent.key}:ask:${packet.id.uid}`, this._methodNotFound(packet));
979
+ });
980
+ }
981
+
982
+ this.state('data', `ask:${method}:${sub_key}:${packet.id.uid}`);
983
+ const packet_answer = {
984
+ id,
985
+ agent,
986
+ client,
987
+ meta: {
988
+ key: agent.key,
989
+ method,
990
+ params,
991
+ },
992
+ text: false,
993
+ html: false,
994
+ data: false,
995
+ created: Date.now(),
996
+ };
997
+ // The method is parsed and depending on what method is asked for it returns
998
+ // the response based on the passed through packet.
999
+ this.methods[method](packet).then(result => {
1000
+ if (typeof result === 'object') {
1001
+ this.state('set', `${key}:${method}:${sub_key}:text:${packet.id.uid}`);
1002
+ packet_answer.text = result.text || false;
1003
+ this.state('set', `${key}:${method}:${sub_key}:text:${packet.id.uid}`);
1004
+ packet_answer.html = result.html || false;
1005
+ this.state('set', `${key}:${method}:${sub_key}:data:${packet.id.uid}`);
1006
+ packet_answer.data = result.data || false;
1007
+ }
1008
+ else {
1009
+ this.state('set', `${key}:${method}:${sub_key}:result:${packet.id.uid}`);
1010
+ packet_answer.text = result;
1011
+ }
1012
+
1013
+ // stamp the packet_answer and set it into packet.a.
1014
+ this.state('set', `${key}:${method}:packet:a:${packet.id.uid}`);
1015
+ packet.a = this._stamp(packet_answer, `${key}:${method}:packet:a`, packet.id.uid); // set the packet answer.
1016
+
1017
+ this.state('set', `${key}:${method}:packet:q:agent:${packet.id.uid}`);
1018
+ packet.q.agent = agent; // set the question agent as the ask agent.
1019
+
1020
+ // create new hashes for the packet before return.
1021
+ const packet_stamped = this._stamp(this._unstamp(packet), `${key}:${method}:packet`, packet.id.uid);
1022
+
1023
+ this.action('talk', `${this._events.answer}:${key}:${method}:${packet.id.uid}`);
1024
+ this.state('valid', `${this._events.answer}:${key}:${method}:${packet.id.uid}`);
1025
+ this.intent('good', `${this._events.answer}:${key}:${method}:${packet.id.uid}`);
1026
+ this.talk(this._events.answer, this.lib.copy(packet_stamped)); // global talk event
1027
+
1028
+ this.action('talk', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1029
+ this.state('valid', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1030
+ this.intent('good', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1031
+ this.talk(`${agent.key}:ask:${packet.id.uid}`, packet_stamped);
1032
+
1033
+ }).catch(err => {
1034
+ this.action('talk', `${agent.key}:${key}:${method}:err:${packet.id.uid}`);
1035
+ this.state('catch', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1036
+ this.intent('bad', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1037
+ // reply on the asker's event so the asker hears the error right away.
1038
+ this.talk(`${agent.key}:${key}:${packet.id.uid}`, {error:err});
1039
+ // log the error here; the asker owns the reject.
1040
+ return this.err(err, packet, () => {});
1041
+ })
1042
+ }
1043
+ catch (e) {
1044
+ this.action('talk', `${agent.key}:${key}:${method}:err:${packet.id.uid}`);
1045
+ this.state('catch', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1046
+ this.intent('bad', `${agent.key}:${key}:${method}:${packet.id.uid}`);
1047
+ this.talk(`${agent.key}:${key}:${packet.id.uid}`, {error:e});
1048
+ return this.err(e, packet, () => {});
1049
+ }
1050
+ // now when we ask the meta params[0] should be the method
1051
+ }
1052
+
1053
+
1054
+ /**************
1055
+ func: init
1056
+ params: client - the client data to use that is provided by the clients.
1057
+ describe:
1058
+ The main init interface where the chain begins. Where the states fire for
1059
+ each process of setting:
1060
+ 1. Set the Max listeners to control event memory buffer.
1061
+ 2. Assign the Inherited Properties
1062
+ 3. Assign binding functions and methods to 'this' scope.
1063
+ 4. Assign any listeners for additional functionality.
1064
+ 5. run the onInit custom function if preset or the start function.
1065
+ 6. The start function will create a chain reaction of states that load.
1066
+ 7. If there is an error the init function rejects the call.
1067
+ usage: this.init(client_object)
1068
+ ***************/
1069
+ init(client) {
1070
+ // set client
1071
+ return new Promise((resolve, reject) => {
1072
+ // manually set the core hashes to avoid stack overflow from calls
1073
+ // this is for the early core hashing needed for uid generation.
1074
+ this._core.md5 = this.hash(this._core, 'md5'); // md5 the core and created.
1075
+ this._core.sha256 = this.hash(this._core, 'sha256'); // sha256 the core, created, md5
1076
+ this._core.sha512 = this.hash(this._core, 'sha512'); // sha512 the core, created, md5, sha256.
1077
+
1078
+ // do the core license check on init.
1079
+ const license_check = this.license_check(client.VLA, this._core.VLA);
1080
+ if (!license_check?.id) {
1081
+ this.prompt(license_check); // set license invalid prompt
1082
+ return resolve(license_check); // return if} license check fails
1083
+ }
1072
1084
 
1073
- this._active = Date.now(); // after passes license check set _active date.
1074
- const id = this.uid();
1075
- const agent = this.agent();
1076
-
1077
- this.state('data', `init:${id.uid}`);
1078
- const data = {
1079
- id,
1080
- key: agent.key,
1081
- value: 'init',
1082
- agent,
1083
- client,
1084
- text: this._messages.init,
1085
- created: Date.now(),
1086
- }
1087
-
1088
- // stamp the init data
1089
- const data_stamped = this._stamp(data, 'init', data.id.uid);
1090
-
1091
- const step = (name, ...args) => new Promise((res, rej) => {
1092
- this[name](...args, res, rej);
1093
- });
1094
-
1095
- this.events.setMaxListeners(this.maxListeners);
1096
- this._assignInherit().then(() => {
1097
- return this._assignBind();
1098
- }).then(() => {
1099
- return this._assignListeners();
1100
- }).then(() => {
1101
- this.belief('vedic', `init:${data.id.uid}`);
1102
- this.feature('init', data.id.uid);
1103
- this.zone('init', data.id.uid);
1104
- this.action('init', data.id.uid);
1105
- this.state('init', data.id.uid);
1106
-
1107
- return step('Client', client);
1108
- }).then(() => {
1109
- return step('License');
1110
- }).then(() => {
1111
- return step('Error');
1112
- }).then(() => {
1113
- return step('Log');
1114
- }).then(() => {
1115
- return step('Data');
1116
- }).then(() => {
1117
- return step('Report');
1118
- }).then(() => {
1119
- return step('Legal');
1120
- }).then(() => {
1121
- return step('Security');
1122
- }).then(() => {
1123
- return step('Support');
1124
- }).then(() => {
1125
- return step('Services');
1126
- }).then(() => {
1127
- return step('Systems');
1128
- }).then(() => {
1129
- return step('Done');
1130
- }).then(() => {
1131
- const hasOnInit = this.onInit && typeof this.onInit === 'function';
1132
- if (hasOnInit) {
1133
- this.action('func', `onInit:${data.id.uid}`); // action set to onfunc
1134
- this.state('valid', `onInit:${data.id.uid}`); // state set to onfunc
1135
- this.intent('good', `onInit:${data.id.uid}`); // intent set to good
1136
- return this.onInit(data, resolve);
1137
- }
1138
- this.action('return', `init:${data.id.uid}`); // action set to return
1139
- this.state('valid', `init:${data.id.uid}`); // state set to valid
1140
- this.intent('good', `init:${data.id.uid}`); // intent set to good
1141
- return this.start(data_stamped, resolve);
1142
- }).catch(err => {
1143
- this.state('catch', `init:${data.id.uid}`); // state set to catch
1144
- this.intent('bad', `init:${data.id.uid}`); // intent set to bad
1145
- return this.err(err, client, reject);
1146
- });
1147
- });
1148
- }
1149
-
1150
- /**************
1151
- func: start
1152
- usage: this.start(data, resolve);
1153
- params: data, resolve
1154
- - data: The data packet that is passed through the invoke chain.
1155
- - resolve: The Promise resolver following the data through recursion.
1156
- describe:
1157
- The start() function initiates the Invoke Recursion Framework phase for the
1158
- current Deva context. It first checks for active runtime status, retrieves
1159
- invocation parameters (key-chain mapping, lifecycle handlers) from
1160
- config.invoke.start, declares the invoke action, and then delegates control
1161
- to _invoke(), ensuring consistent recursion through the start-enter-done
1162
- sequence. This design preserves language-agnostic interoperability and
1163
- deterministic state transitions across Deva systems.
1164
- ***************/
1165
- start(data, resolve) {
1166
- if (!this._active) return resolve(this._messages.offline);
1167
- return this._invoke({key:'start',data,resolve});
1168
- }
1169
-
1170
- /**************
1171
- func: enter
1172
- params:
1173
- - msg: the message from the caller incase need to use in calls
1174
- describe:
1175
- The enter function will check the active status of the Deva and set it to
1176
- offline or enter.
1177
-
1178
- If the Deva is offline it will return the offline message.
1179
- usage: this.enter('msg')
1180
- ***************/
1181
- enter(data, resolve) {
1182
- if (!this._active) return resolve(this._messages.offline);
1183
- return this._invoke({key:'enter',data,resolve});
1184
- }
1185
-
1186
- /**************
1187
- func: done
1188
- params:
1189
- - data: the message from the caller incase need to use in calls
1190
- describe:
1191
- When the done function is triggered the system will also set the state
1192
- of the Deva to done.
1193
-
1194
- If the deva is offline it will return the offline message.
1195
- usage: this.done('msg')
1196
- ***************/
1197
- done(data, resolve) {
1198
- if (!this._active) return resolve(this._messages.offline);
1199
- return this._invoke({key:'done',data,resolve});
1200
- }
1201
-
1202
- /**************
1203
- func: ready
1204
- params:
1205
- - data: the data to pass to the resolve
1206
- - resolve: the complete resolve to pass back
1207
- describe: This function is use to relay the to the ready state.
1208
- usage: this.ready(data, resolve)
1209
- ***************/
1210
- async ready(data, resolve) {
1211
- if (!this._active) return resolve(this._messages.offline);
1212
- const key = 'ready';
1213
-
1214
- this.state('set', `${key}:agent:${data.id.uid}`);
1215
- const agent = this.agent();
1216
- const {VLA} = this.info();
1217
-
1218
- this.state('set', `${key}:config:hash:${data.id.uid}`); // state set to watch OnFinish
1219
- this.config.hash[agent.key] = {};
1220
-
1221
- this.state('loop', `${key}:config:ready:hash:${data.id.uid}`);
1222
- for (let item of this._config.ready_hash) {
1223
- if (this[item]) {
1224
- this.action('hash', `${agent.key}:config:${item}:${data.id.uid}`);
1225
- // manually build hash for the config hash object for each agent key.
1226
- const this_item = this._binding.get(item) || this[item];
1227
- this.config.hash[agent.key][item] = this.hash(this_item, 'sha256');
1228
- }
1229
- }
1230
-
1231
- const key_len = Object.keys(this.devas).length // check the key length for looping
1232
- let x = 1; // let x equal one for iteration.
1233
- if (this.devas && key_len) {
1234
- this.state('loop', `${key}:devas:${data.id.uid}`); // set the state to loop
1235
- for (let deva in this.devas) {
1236
- // load the deva with client data
1237
- await this.load(deva, data.client).then(async entity => {
1238
- const id = this.uid(); // generate a new uid
1239
- const {dir} = this.devas[deva].info(); // get the base directory for the Deva from the info()
1240
- const deva_agent = this.devas[deva].agent(); // get the agent data from the deva.
1241
- this.talk(`deva:dir`, {id, key:deva_agent.key, dir}); // talk the deva dir event to setup tracking the Deva directories
1242
- if (x === key_len) {
1243
- setImmediate(() => {
1244
- return this._invoke({key,data,resolve}); // invoke the deva with the proper key, data, and resolve.
1245
- });
1246
- }
1247
- x = x + 1; // increment the iterator for key_len matching
1248
- });
1249
- }
1250
- }
1251
- else return this._invoke({key,data,resolve}); // else run the key invoke.
1252
- }
1253
-
1254
- /**************
1255
- func: finish
1256
- params:
1257
- - data: the data to pass to the resolve
1258
- - resolve: the finish resolve to pass back
1259
- describe: This function is used to relay into the finish state when resolving a question or data.
1260
- usage: this.finish(data, resolve)
1261
- ***************/
1262
- finish(data, resolve) {
1263
- if (!this._active) return resolve(this._messages.offline);
1264
- return this._invoke({key:'finish',data,resolve});
1265
- }
1266
-
1267
- /**************
1268
- func: complete
1269
- params:
1270
- - data: the data to pass to the resolve
1271
- - resolve: the complete resolve to pass back
1272
- describe: This function is use to relay into a complete state when
1273
- resolving a question or data.
1274
- usage: this.complete(data, resolve)
1275
- ***************/
1276
- complete(data, resolve) {
1277
- if (!this._active) return resolve(this._messages.offline);
1278
- return this._invoke({key:'complete',data,resolve});
1279
- }
1280
-
1281
- /**************
1282
- func: stop
1283
- usage: this.stop(data, resolve);
1284
- params: data, resolve
1285
- - data: The data packet that is passed through the closing invoke chain.
1286
- - resolve: The Promise resolver following the data through recursion.
1287
- describe:
1288
- The stop() function initiates the egress stop aspect of the Invoke
1289
- Recursion Framework.
1290
- ***************/
1291
- stop() {
1292
- if (!this._active) return Promise.resolve(this._messages.offline); // check for active status
1293
- const key = 'stop'; // set the stop key
1294
- const id = this.uid(); // generate the stop uid
1295
- let data;
1296
- return new Promise(async (resolve, reject) => {
1297
- try {
1298
- // stop the child Devas first so none are left running when the parent closes. ready() loads them last.
1299
- this.state('loop', `${key}:devas:${id.uid}`);
1300
- for (const deva in this.devas) await this.devas[deva].stop();
1301
-
1302
- this.state('set', `${key}:agent:${id.uid}`); // state stop agent
1303
- const agentData = this.agent();
1304
- const agent = agentData.sha256; // get the current agent
1305
- const value = agentData.key;
1306
-
1307
- this.state('set', `${key}:client:${id.uid}`); // state stop agent
1308
- const client = this.client().sha256; // set the current client
1309
-
1310
- this.state('data', `${key}:${id.uid}`);
1311
- data = { // build the stop data
1312
- id, // set the id
1313
- key, // set the key
1314
- value, // set the value
1315
- agent, // set the agent
1316
- client, // set the client
1317
- stop: Date.now(), // set the created date
1318
- }
1319
-
1320
- this.action('return', `${key}:invoke:${data.id.uid}`);
1321
- this.state('valid', `${key}:invoke:${data.id.uid}`);
1322
- this.intent('good', `${key}:invoke:${data.id.uid}`);
1323
- return this._invoke({
1324
- key,
1325
- data,
1326
- resolve,
1327
- });
1328
- }
1329
- catch (err) {
1330
- return this.err(err, data, reject);
1331
- }
1332
- });
1333
- }
1334
-
1335
- /**************
1336
- func: close
1337
- usage: this.close(data, resolve);
1338
- params: data, resolve
1339
- - data: The data packet that is passed through the closing invoke chain.
1340
- - resolve: The Promise resolver following the data through recursion.
1341
- describe:
1342
- The close() function initiates the close aspect of the Invoke Recursion Framework.
1343
- ***************/
1344
- close(data, resolve) {
1345
- if (!this._active) return resolve(this._messages.offline);
1346
- const key = 'close';
1347
- data.key = key;
1348
- return this._invoke({key,data,resolve});
1349
- }
1350
-
1351
- /**************
1352
- func: leave
1353
- usage: this.leave(data, resolve);
1354
- params: data, resolve
1355
- - data: The data packet that is passed through the closing invoke chain.
1356
- - resolve: The Promise resolver following the data through recursion.
1357
- describe:
1358
- The leave() function initiates the leave aspect of the Invoke Recursion
1359
- Framework.
1360
- ***************/
1361
- leave(data, resolve) {
1362
- if (!this._active) return resolve(this._messages.offline);
1363
- const key = 'leave';
1364
- data.key = key;
1365
- return this._invoke({key,data,resolve});
1366
- }
1367
-
1368
- /**************
1369
- func: exit
1370
- usage: this.exit(data, resolve);
1371
- params: data, resolve
1372
- - data: The data packet that is passed through the egress invoke chain.
1373
- - resolve: The Promise resolver following the data through recursion.
1374
- describe:
1375
- The exit() function initiates the exit aspect of the Invoke Recursion
1376
- Framework.
1377
- ***************/
1378
- exit(data, resolve) {
1379
- if (!this._active) return resolve(this._messages.offline);
1380
- const key = 'exit';
1381
- data.key = key;
1382
- return this._invoke({key,data,resolve});
1383
- }
1384
-
1385
- /**************
1386
- func: shutdown
1387
- params:
1388
- - msg: hte message from the caller incase need to use in calls
1389
- describe:
1390
- The exit state function is triggered when the Deva is exiting.
1391
-
1392
- The return will check for a custom onExit function or run the done
1393
- function.
1394
- ***************/
1395
- shutdown(data, resolve) {
1396
- if (!this._active) return resolve(this._messages.offline);
1397
- const key = 'shutdown';
1398
- data.key = key;
1399
- return this._invoke({key, data, resolve})
1400
- }
1401
-
1402
-
1403
- ////////////////////////////
1404
-
1405
-
1406
- /**************
1407
- func: context
1408
- params:
1409
- - value: The context flag to set for the Deva that matches to this._contexts
1410
- - extra: Any extra text that is sent with the context value.
1411
- describe
1412
- ***************/
1413
- context(value=false, extra=false) {
1414
- if (!this._active) return this._messages.offline; // check the active status
1415
- const id = this.uid();
1416
- try {
1417
- if (!value) return;
1418
- this._context = value;
1419
- const lookup = this.vars?.context?.[value] || value;
1420
- const text = extra ? `${lookup} ${extra}` : lookup;
1421
-
1422
- const data = {
1423
- id,
1424
- agent: this.agent(),
1425
- client: this.client(),
1426
- key: 'context',
1427
- value,
1428
- text,
1429
- created: Date.now(),
1430
- };
1431
-
1432
- const data_stamped = this._stamp(data, `context`, id.uid);
1433
-
1434
- this.talk(this._events.context, this.lib.copy(data_stamped));
1435
- return data_stamped;
1436
- } catch (e) {
1437
- this.state('catch', `context:${value}:${id.uid}`);
1438
- return this.err(e, value);
1439
- }
1440
- }
1441
-
1442
- contexts() {
1443
- if (!this._active) return this._messages.offline; // check the active status
1444
- const id = this.uid();
1445
- const key = 'contexts';
1446
- this.action(key, id.uid);
1447
-
1448
- this.state('data', `${key}:${id.uid}`);
1449
- const data = {
1450
- id,
1451
- key,
1452
- value: this.vars.context || false, // this loads the local agent context list.
1453
- agent: this.agent(),
1454
- client: this.client(),
1455
- created: Date.now(),
1456
- };
1457
-
1458
- this.state('return', `${key}:${id.uid}`);
1459
- return this._stamp(data, key, id.uid);
1460
- }
1461
-
1462
- /**************
1463
- func: feature
1464
- params:
1465
- - value: The feature flag to set for the Deva that matches to this._features
1466
- - extra: Any extra text to send with the feature value.
1467
- describe
1468
- ***************/
1469
- feature(value=false, extra=false) {
1470
- return this._workflow('feature', value, extra);
1471
- }
1472
-
1473
- /**************
1474
- func: features
1475
- params: none
1476
- describe: return a list of features that are available to the system.
1477
- ***************/
1478
- features() {
1479
- return this._workflowItems('features');
1480
- }
1481
-
1482
- /**************
1483
- func: zone
1484
- params:
1485
- - value: the value to pass to _workflow
1486
- - extra: Any extra text to send with the zone.
1487
- ***************/
1488
- zone(value=false, extra=false) {
1489
- return this._workflow('zone', value, extra);
1490
- }
1491
-
1492
- /**************
1493
- func: zones
1494
- params: none
1495
- describe: returns a listing of zones currently in the system.
1496
- ***************/
1497
- zones() {
1498
- return this._workflowItems('zones');
1499
- }
1500
-
1501
- /**************
1502
- func: action
1503
- params:
1504
- - value: The state flag to set for the Deva that matches to this._states
1505
- - extra: Any extra text to send with the action value.
1506
- describe
1507
- ***************/
1508
- action(value=false, extra=false) {
1509
- return this._workflow('action', value, extra);
1510
- }
1511
-
1512
- /**************
1513
- func: actions
1514
- params: none
1515
- describe: Returns a list of available actions in the system.
1516
- ***************/
1517
- actions() {
1518
- return this._workflowItems('actions');
1519
- }
1520
-
1521
- /**************
1522
- func: state
1523
- params:
1524
- - value: The state value to set for the Deva that matches to this._states
1525
- - extra: any extra text to add to the state change.
1526
- ***************/
1527
- state(value=false, extra=false) {
1528
- return this._workflow('state', value, extra);
1529
- }
1530
-
1531
- /**************
1532
- func: states
1533
- params: none
1534
- describe: returns the available states values.
1535
- ***************/
1536
- states() {
1537
- return this._workflowItems('states');
1538
- }
1539
-
1540
- /**************
1541
- func: intent
1542
- params:
1543
- - value: The intent value to set for the Deva that matches to this._intents
1544
- - extra: any extra text to add to the intent change.
1545
- ***************/
1546
- intent(value=false, extra=false) {
1547
- return this._workflow('intent', value, extra);
1548
- }
1549
-
1550
- /**************
1551
- func: intents
1552
- params: none
1553
- describe: returns the available intents values.
1554
- ***************/
1555
- intents() {
1556
- return this._workflowItems('intents');
1557
- }
1558
-
1559
- /**************
1560
- func: belief
1561
- params:
1562
- - value: The belief value to set for the Deva that matches to this._beliefs
1563
- - extra: any extra text to add to the belief change.
1564
- ***************/
1565
- belief(value=false, extra=false) {
1566
- return this._workflow('belief', value, extra);
1567
- }
1568
-
1569
- /**************
1570
- func: beliefs
1571
- params: none
1572
- describe: returns the available beliefs values.
1573
- ***************/
1574
- beliefs() {
1575
- return this._workflowItems('beliefs');
1576
- }
1577
-
1578
- /**************
1579
- func: _workflow
1580
- params:
1581
- - value: The workflow value to set for the Deva that matches to this._states
1582
- - extra: any extra text to add to the state change.
1583
- stages: Feature, Zone, Action, State, Intent
1584
- ***************/
1585
- _workflow(key, value=false, extra=false) {
1586
- if (!this._active) return this._messages.offline;
1587
- const id = this.uid();
1588
- try {
1589
- const _key = `_${key}`;
1590
- const _keys = `_${key}s`;
1591
- if (!value || !this[_keys][value]) return; // return if no matching value
1592
- this[_key] = value;
1593
- const lookup = this[_keys][value]; // set the local states lookup
1594
- const text = extra ? `${lookup} ${extra}` : lookup; // set text from lookup with extra
1595
- const data = { // build the data object
1596
- id, // set the data id
1597
- key, // set the key to state
1598
- value, // set the value to the passed in value
1599
- text, // set the text value of the data
1600
- agent: this.agent(), // set the agent
1601
- client: this.client(), // set the client
1602
- created: Date.now(), // set the data created date.
1603
- };
1604
-
1605
- // manual hashing to avoid _stamp conflict at load.
1606
- data.md5 = this.hash(data, 'md5');
1607
- data.sha256 = this.hash(data, 'sha256');
1608
- data.sha512 = this.hash(data, 'sha512');
1609
-
1610
- this.talk(this._events[key], this.lib.copy(data)); // broadcast the state event
1611
- return data;
1612
- } catch (e) { // catch any errors
1613
- return this.err(e); // return if an error happens
1614
- }
1615
- }
1616
-
1617
- /**************
1618
- func: _workflowItems
1619
- params: none
1620
- describe: returns the available workflow items for a given key.
1621
- ***************/
1622
- _workflowItems(key) {
1623
- if (!this._active) return this._messages.offline;
1624
- const id = this.uid(); // set the current uid
1625
- this.action(key, id.uid); // set the action to the passed key
1626
- const value = this[`_${key}`]; // get the _keys value
1627
- // set the data packet for the states
1628
- this.state('data', `${key}:${id.uid}`);
1629
- const data = {
1630
- id,
1631
- key,
1632
- value,
1633
- agent: this.agent(),
1634
- client: this.client(),
1635
- created: Date.now(),
1636
- }
1637
-
1638
- this.action('return', `${data.key}:${id.uid}`);
1639
- return this._stamp(data, data.key, id.uid);
1640
- }
1641
-
1642
- /**************
1643
- func: client
1644
- params: none
1645
- describe: returns the current client values in the system.
1646
- usage: this.client();
1647
- ***************/
1648
- client() {
1649
- if (!this._active) return this._messages.offline; // check the active status
1650
- const data = this.lib.copy(this._client); // create a copy of the client data
1651
- // manual hashing here to prevent stack overflow with this._stamp.
1652
- data.md5 = this.hash(data, 'md5');
1653
- data.sha256 = this.hash(data, 'sha256');
1654
- data.sha512 = this.hash(data, 'sha512');
1655
- return data; // return the copy of the client data.
1656
- }
1657
-
1658
- /**************
1659
- func: agent
1660
- params: none
1661
- describe: returns the current agent values in the system.
1662
- usage: this.agent()
1663
- ***************/
1664
- agent() {
1665
- if (!this._active) return this._messages.offline; // check the active status
1666
- const data = this.lib.copy(this._agent); // create a copy of the agent data.
1667
- // manual hashing here to prevent stack overflow with this._stamp.
1668
- data.md5 = this.hash(data, 'md5');
1669
- data.sha256 = this.hash(data, 'sha256');
1670
- data.sha512 = this.hash(data, 'sha512');
1671
- return data; // return the copy of the agent data.
1672
- }
1673
-
1674
- // FEATURE FUNCTIONS
1675
- /**************
1676
- func: license
1677
- params: none
1678
- describe: basic license features available in a Deva.
1679
- usage: this.license()
1680
- ***************/
1681
- license() {
1682
- return this._getFeature('license');
1683
- }
1684
-
1685
- /**************
1686
- func: error
1687
- params: none
1688
- describe: basic error features available in a Deva.
1689
- usage: this.error()
1690
- ***************/
1691
- error() {
1692
- return this._getFeature('error');
1693
- }
1694
-
1695
- /**************
1696
- func: log
1697
- params: none
1698
- describe: basic log features available in a Deva.
1699
- usage: this.log()
1700
- ***************/
1701
- log() {
1702
- return this._getFeature('log');
1703
- }
1704
-
1705
- /**************
1706
- func: data
1707
- params: none
1708
- describe: basic data features available in a Deva.
1709
- usage: this.data()
1710
- ***************/
1711
- data() {
1712
- return this._getFeature('data');
1713
- }
1714
-
1715
- /**************
1716
- func: report
1717
- params: none
1718
- describe: basic report features available in a Deva.
1719
- usage: this.report()
1720
- ***************/
1721
- report() {
1722
- return this._getFeature('report');
1723
- }
1724
-
1725
- /**************
1726
- func: security
1727
- params: none
1728
- describe: basic security features available in a Deva.
1729
- usage: this.security()
1730
- ***************/
1731
- security() {
1732
- return this._getFeature('security');
1733
- }
1734
-
1735
- /**************
1736
- func: legal
1737
- params: none
1738
- describe: basic legal features available in a Deva.
1739
- usage: this.systems()
1740
- ***************/
1741
- legal() {
1742
- return this._getFeature('legal');
1743
- }
1744
-
1745
- /**************
1746
- func: support
1747
- params: none
1748
- describe: basic support features available in a Deva.
1749
- usage: this.support()
1750
- ***************/
1751
- support() {
1752
- return this._getFeature('support');
1753
- }
1754
-
1755
- /**************
1756
- func: services
1757
- params: none
1758
- describe: basic services features available in a Deva.
1759
- usage: this.services()
1760
- ***************/
1761
- services() {
1762
- return this._getFeature('services');
1763
- }
1764
-
1765
- /**************
1766
- func: systems
1767
- params: none
1768
- describe: basic systems features available in a Deva.
1769
- usage: this.systems()
1770
- ***************/
1771
- systems() {
1772
- return this._getFeature('systems');
1773
- }
1774
-
1775
- /**************
1776
- func: load
1777
- params:
1778
- -deva: The Deva model to load.
1779
- describe: This function will enable fast loading of Deva into the system.
1780
- ***************/
1781
- load(key, client) {
1782
- this.zone('load', key);
1783
- this.action('load', key);
1784
- this.state('load', key);
1785
- this.intent('good', `load:${key}`);
1786
- return new Promise((resolve, reject) => {
1787
- this.devas[key].init(client).then(deva => {
1788
- return resolve(deva)
1789
- }).catch(err => {
1790
- return this.err(err, client, reject);
1791
- })
1792
- });
1793
- }
1794
-
1795
- /**************
1796
- func: unload
1797
- params:
1798
- - deva: The deva key to unload
1799
- describe: Unload a currently loaded Deva.
1800
- ***************/
1801
- unload(key) {
1802
- return new Promise((resolve, reject) => {
1803
- if (!this._active) return resolve(this._messages.offline); // check the active status
1804
- this.zone('unload', key);
1805
- this.action('unload', key);
1806
- this.state('unload', key);
1807
- this.state('try', `unload:${key}`);
1808
- try {
1809
- this.devas[key].stop().then(exit => {
1810
- delete this.devas[key];
1811
- this.action('talk', `${this._events.unload}:${key}`);
1812
- this.talk(this._events.unload, key);
1813
- });
1814
- this.action('resolve', `unload:${key}`);
1815
- this.intent('good', `unload:${key}`);
1816
- return resolve(`${this._messages.unload}:${key}`);
1817
- } catch (e) {
1818
- this.state('catch', `unload:${key}`);
1819
- this.intent('bad', `unload:${key}`);
1820
- return this.err(e, key, reject)
1821
- }
1822
- });
1823
- }
1824
-
1825
- /**************
1826
- func: prompt
1827
- params:
1828
- - text: The text string to send to the prompt.
1829
- describe:-
1830
- The prompt function is used to broadcasat a global prompt event with a string. Thsi is handy when passing events between a cli and user interface for example.
1831
-
1832
- usage: this.prompt('text')
1833
- ***************/
1834
- prompt(text) {
1835
- if (!this._active) return this._messages.offline; // return offline message if inactive.
1836
- const id = this.uid(); // generate the id for the prompt
1837
- const agent = this.agent(); // set the agent for the prompt
1838
- const client = this.client(); // set the client for the prompt
1839
- const {key} = agent; // set the key from agent
1840
- const value = 'prompt'; // set the value of the key.
1841
- // create data packet to generate prompt
1842
-
1843
- this.state('data', `${key}:${value}:${id.uid}`)
1844
- const data = {
1845
- id,
1846
- key,
1847
- value,
1848
- agent,
1849
- client,
1850
- text,
1851
- created: Date.now(),
1852
- }
1853
-
1854
- // stamp the data
1855
- const data_stamped = this._stamp(data, `${key}:${value}`, data.id.uid);
1856
-
1857
- // talk the prompt event to anyone listening
1858
- this.action('talk', `${key}:${value}:${id.uid}`);
1859
- this.talk(this._events.prompt, data_stamped);
1860
-
1861
- this.action('return', `${key}:${value}:${id.uid}`);
1862
- return data_stamped;
1863
- }
1864
-
1865
- /**************
1866
- func: core
1867
- params: none
1868
- describe: return core data.
1869
- ***************/
1870
- core() {
1871
- if (!this._active) return this._messages.offline;
1872
- const id = this.uid();
1873
- this.action('core', id.uid);
1874
-
1875
- // check the active status
1876
- const data = this.lib.copy(this._core);
1877
- data.id = id;
1878
- data.created = Date.now();
1879
-
1880
- this.action('return', `core:${id.uid}`);
1881
- this.intent('good', `core:${id.uid}`);
1882
- return this._stamp(this._unstamp(data), 'core', data.id.uid);
1883
- }
1884
-
1885
- // machine returns the sha256 machine fingerprint
1886
- machine() {
1887
- const {os} = this.lib;
1888
- const data = {
1889
- arch: os.arch(),
1890
- hostname: os.hostname(),
1891
- network: os.networkInterfaces(),
1892
- platform: os.platform(),
1893
- release: os.release(),
1894
- type: os.type(),
1895
- user: os.userInfo(),
1896
- version: os.version(),
1897
- uptime: os.uptime(),
1898
- cpus: os.cpus(),
1899
- created: Date.now(),
1900
- };
1901
- // machine has to do manual hashing to prevent stack overflow.
1902
- data.md5 = this.hash(data, 'md5');
1903
- data.sha256 = this.hash(data, 'sha256');
1904
- data.sha512 = this.hash(data, 'sha512');
1905
- return data;
1906
- }
1907
-
1908
- /**************
1909
- func: info
1910
- params: none
1911
- describe: return info data.
1912
- ***************/
1913
- info() {
1914
- if (!this._active) return this._messages.offline;
1915
- const data = this.lib.copy(this._info);
1916
- data.created = Date.now();
1917
-
1918
- this.action('return', `info:${data.id}`);
1919
- this.intent('good', `info:${data.id}`);
1920
- return this._stamp(data, 'info', data.id);
1921
- }
1922
-
1923
- /**************
1924
- func: status
1925
- params:
1926
- - msg: The msg is any additonal string to append to the end of hte call.
1927
- describe:
1928
- The status function provides an easy way to get the current status of a Deva
1929
- and append custom status messages that may pertain to any custom status call.
1930
-
1931
- If the deva is offline it will return the offline message.
1932
- usage: this.status('msg')
1933
- ***************/
1934
- status() {
1935
- if (!this._active) return this._messages.offline;
1936
- const id = this.uid();
1937
- this.action('status', id);
1938
- // check the active status
1939
-
1940
- // format the date since active for output.
1941
- const dateFormat = this.lib.formatDate(this._active, 'long', true);
1942
- // create the text msg string
1943
- this.action('return', `status:${id.uid}`);
1944
- this.intent('good', `status:${id.uid}`);
1945
- return `${this._agent.profile.name} active since ${dateFormat}`; // return final text string
1946
- }
1947
-
1948
- /**************
1949
- func: help
1950
- params:
1951
- - msg: the help msg to search against
1952
- - help_dir: base directory of the deva help files.
1953
- describe:
1954
- the help utility makes it easy to create help files for your deva. the utility
1955
- checks the existence of a help file in the passed in directory then if
1956
- one exists it will then present it based on the users request text input.
1957
- ***************/
1958
- help(msg, help_dir) {
1959
- return new Promise((resolve, reject) => {
1960
- if (!this._active) return resolve(this._messages.offline);
1961
- let helpDoc = false;
1962
- const id = this.uid();
1963
- const key = 'help';
1964
- this.zone(key, id.uid);
1965
-
1966
- this.feature(key, id.uid);
1967
- this.action(key, id.uid);
1968
- this.state(key, id.uid);
1969
- this.context(key, id.uid);
1970
-
1971
- const params = msg.split(' '); // split the msg into an array by spaces.
1972
-
1973
- const splitText = params[0].split(':');
1974
- const part = splitText[1] ? splitText[1].toUpperCase() : 'MAIN';
1975
- const helpFile = splitText[0] ? splitText[0] : 'main';
1976
-
1977
- const helpPath = this.lib.path.join(help_dir, key, `${helpFile}.feecting`);
1978
-
1979
- this.state('try', `${key}:${id.uid}`);
1980
- try {
1981
- // check if help file exists first and resolve if no file
1982
- const helpExists = this.lib.fs.existsSync(helpPath); // check if help file exists
1983
- if (!helpExists) {
1984
- this.action('resolve', `${key}:not:exists:${id.uid}`);
1985
- this.state('invalid', `${key}:not:exists:${id.uid}`);
1986
- this.intent('bad', `${key}:not:exists:${id.uid}`);
1987
- return resolve(this._messages.help_not_found);
1988
- }
1989
-
1990
- // get the help file and check to make sure the part we are looking for exists.
1991
- const helpFile = this.lib.fs.readFileSync(helpPath, 'utf8');
1992
- const helpPart = helpFile.split(`${this.container.begin}:${part}`);
1993
- if (!helpPart[1]) {
1994
- this.action('resolve', `${key}:not:found:${id.uid}`);
1995
- this.state('invalid', `${key}:not:found:${id.uid}`);
1996
- this.intent('bad', `${key}:not:found:${id.uid}`);
1997
- return resolve(this._messages.help_not_found);
1998
- }
1999
-
2000
- // last set the help doc and split out the selected part.
2001
- helpDoc = helpFile.split(`${this.container.begin}:${part}`)[1].split(`${this.container.end}:${part}`)[0];
2002
-
2003
- this.action('resolve', `${key}:${id.uid}`);
2004
- this.state('valid', `${key}:${id.uid}`);
2005
- this.intent('good', `${key}:${id.uid}`);
2006
- return resolve(helpDoc);
2007
- }
2008
- catch(e) {
2009
- this.state('catch', `${key}:${id.uid}`);
2010
- this.intent('bad', `${key}:${id.uid}`);
2011
- return this.err(e, msg, reject);
2012
- }
2013
- });
2014
- }
2015
-
2016
- /**************
2017
- func: err
2018
- params:
2019
- - err: The error to process
2020
- - data: Any additional data associated with the error
2021
- - reject: An associated promise reject if the caller requires.
2022
- describe:
2023
- The err function provides the consistent error manage of the system.
2024
-
2025
- If the agent defines an onError function, err hands it (err, packet, reject)
2026
- and returns its result. In that case the agent owns the outcome: onError must
2027
- call reject to fail the caller's promise, or the promise will stay pending.
2028
- If there is no onError function, err calls reject(err) itself.
2029
-
2030
- usage: this.err(err, data, reject);
2031
-
2032
-
2033
- ***************/
2034
- err(err,packet,reject=false) {
2035
- const id = this.uid();
2036
- const key = 'error';
2037
- this.feature(key, id.uid);
2038
- this.zone(key, id.uid);
2039
- this.action(key, id.uid);
2040
- this.state(key, id.uid);
2041
- this.intent('bad', `${key}:${id.uid}`);
2042
-
2043
- const agent = this.agent();
2044
- const client = this.client();
2045
-
2046
- this.state('data', `${key}:${id.uid}`);
2047
- const data = {
2048
- id,
2049
- key,
2050
- value: agent.key,
2051
- agent,
2052
- client,
2053
- error: {
2054
- name: err.name,
2055
- message: err.message,
2056
- stack: err.stack,
2057
- },
2058
- packet,
2059
- created: Date.now(),
2060
- };
2061
- // stamp the data before return
2062
- const data_stamped = this._stamp(data, `${data.key}:${data.value}`, data.id.uid);
2063
-
2064
- // set the action to talk and emit the talk error.
2065
- this.action('talk', `${this._events.error}:${data.id.uid}`);
2066
- this.talk(this._events.error, this.lib.copy(data_stamped));
2067
-
2068
- const hasOnError = this.onError && typeof this.onError === 'function' ? true : false;
2069
- // if block handles returning the onError and setting the state to hasOnError
2070
- if (hasOnError) {
2071
- this.action('func', `onError:${data.value}:${data.id.uid}`);
2072
- this.state('invalid', `onError:${data.value}:${data.id.uid}`);
2073
- this.intent('bad', `hasOnError:${data.id.uid}`);
2074
- return this.onError(err, packet, reject);
2075
- }
2076
- // else block handled the reject if there is no onError function.
2077
- else {
2078
- this.action('reject', `${data.value}:${id.uid}`);
2079
- this.intent('bad', `error:${data.id.uid}`);
2080
- return reject ? reject(err) : Promise.reject(err);
2081
- }
2082
- }
2083
-
2084
- /**************
2085
- func: uid
2086
- params:
2087
- - guid: This is a true false flag for generating a guid.
2088
- describe:
2089
- The uid function can create two types of id for you.
2090
- 1. random GUID - this is good for when you need a uinique record id returned
2091
- 2. transport uid - The transport id is a number generated to provide a
2092
- secure numerical number used for transporting records
2093
- across networks without collision or needing to store system uuid.
2094
- 3. the uid is then returned with a created, md5, sha256, and sha512 hash of the value
2095
- copyright: Copyright ©2000-2026 Quinn Michaels. All rights reserved.
2096
- ***************/
2097
- uid(guid=false) {
2098
- const time = Date.now(); // set time to local constant
2099
- const iso = this.lib.formatDate(time, 'iso', true); // set date to local constant
2100
- const utc = this.lib.formatDate(time, 'utc', true); // set date to local constant
2101
- const date = this.lib.formatDate(time, 'long', true); // set date to local constant
2102
- const license = this._info.VLA ? this._info.VLA.uid : false;
2103
- const client = this.client(); // get the client
2104
- const agent = this.agent(); // get the agent
2105
- const machine = this.machine(); // get the machine hash
2106
-
2107
- const core_hash = this._core.sha256; // get the core sha256 hash
2108
-
2109
- const warning = this._agent.profile.warning || this._messages.warning; // agent or default warning
2110
- const notice = this._agent.profile.notice || this._messages.notice; // agent or default notice
2111
- const copyright = this._agent.profile.copyright || this._messages.copyright; // agent or default copyright
2112
-
2113
- const status = this._agent.profile.status || this._messages.status;
2114
-
2115
- const vectors = this._agent.profile.vectors || this._messages.vectors;
2116
- const owner = this._agent.profile.owner || this._messages.owner;
2117
- const creator = this._agent.profile.creator || this._messages.creator;
2118
- const salute = this._agent.profile.salute || this._messages.salute;
2119
-
2120
- const fingerprint_data = {
2121
- license,
2122
- client: client.sha256,
2123
- agent: agent.sha256,
2124
- machine: machine.sha256,
2125
- core_hash,
2126
- };
2127
- const fingerprint = this.hash(fingerprint_data, 'sha256');
2128
-
2129
- const data = {
2130
- uid: false,
2131
- time,
2132
- iso,
2133
- utc,
2134
- date,
2135
- license,
2136
- fingerprint,
2137
- client: client.sha256,
2138
- agent: agent.sha256,
2139
- machine: machine.sha256,
2140
- core_hash,
2141
- status,
2142
- warning,
2143
- notice,
2144
- vectors,
2145
- owner,
2146
- creator,
2147
- salute,
2148
- copyright,
2149
- }
2150
- if (guid) {
2151
- const uid = randomUUID(); // set uid into local constant.
2152
- data.uid = uid; // set base data object.
2153
- }
2154
- else {
2155
- const min = Math.floor(time - (time / Math.PI)); // generate min time from Math.PI divisor.
2156
- const max = Math.ceil(time + (time * Math.PI)); // generate max time form Math.PI multiplier.
2157
- const begin_random = Math.floor(Math.random() * (max - min) + min); // generate random number between min and max.
2158
- const {end_min, end_max} = this._uid; // set end min and max in to constant
2159
- const end_random = Math.ceil(Math.random() * (end_max - end_min) + end_min); // generate end salt on the number for added randomness.
2160
-
2161
- const uid = `${begin_random}${end_random}`; // set uid to local constant
2162
- data.uid = uid; // set base data object.
2163
- }
2164
- // manual hashing to prevent overflow on stack calls.
2165
- data.md5 = this.hash(data, 'md5'); // md5 the uid and created.
2166
- data.sha256 = this.hash(data, 'sha256'); // sha256 the uid, created, md5
2167
- data.sha512 = this.hash(data, 'sha512'); // sha512 the uid, created, md5, sha256.
2168
- return data; // return the complete uid data.
2169
- }
2170
-
2171
- /**************
2172
- func: sign
2173
- params:
2174
- - packet: The packet to sign data to.
2175
- describe:
2176
- The sign function can create a digital signature to a packet.
2177
- copyright: Copyright ©2000-2026 Quinn Michaels. All rights reserved.
2178
- ***************/
2179
- sign(packet) {
2180
- const id = this.uid();
2181
- const {time, date, fingerprint} = id;
2182
-
2183
- const client = this.client();
2184
- const agent = this.agent();
2185
- const {q} = packet;
2186
-
2187
- const {meta, text} = q;
2188
- const {key, method, params} = meta;
2189
-
2190
- const opts = this.lib.copy(params); // copy the params and set as opts.
2191
- const command = opts.shift();
2192
-
2193
- const {invalid_agent,invalid_client} = this._messages;
2194
-
2195
- const agent_hash = agent.sha256 === packet.q.agent.sha256 ? agent.sha256 : invalid_agent;
2196
- const client_hash = client.sha256 === packet.q.client.sha256 ? client.sha256 : invalid_client;
2197
-
2198
- const container = `OM:O:${key.toUpperCase()}:${id.uid}`; // set container string.
2199
-
2200
- this.action('hash', `${key}:packet:sha256:${id.uid}`);
2201
- const packet_hash = this.hash(packet, 'sha256');
2202
-
2203
- this.action('hash', `${key}:token:sha256:${id.uid}`);
2204
- const token = this.hash(`${key} client:${client.profile.id} fullname:${client.profile.fullname} uid:${id.uid}`, 'sha256');
2205
-
2206
- const warning = agent.profile.warning || this._messages.warning;
2207
- const copyright = agent.profile.copyright || this._core.copyright;
2208
-
2209
- // build the main data packet.
2210
- this.state('data', `${key}:sign:${id.uid}`); // set state data
2211
- const data = {
2212
- id,
2213
- key,
2214
- method,
2215
- opts: opts.join('.'),
2216
- text,
2217
- time,
2218
- date,
2219
- container,
2220
- client: {
2221
- key: client.key,
2222
- name: client.profile.name,
2223
- fullname: client.profile.fullname,
2224
- emojis: client.profile.emojis,
2225
- company: client.profile.company,
2226
- expires: client.profile.expires ? time + client.profile.expires : 'none',
2227
- caseid: client.profile.caseid || 'none',
2228
- token,
2229
- hash: client_hash,
2230
- },
2231
- agent: {
2232
- key: agent.key,
2233
- name: agent.profile.name,
2234
- hash: agent_hash,
2235
- },
2236
- packet: packet_hash,
2237
- warning,
2238
- copyright,
2239
- };
2240
-
2241
- this.action('return', `${data.key}:sign:${data.id.uid}`); // set the action to return
2242
- this.intent('good', `${data.key}:sign:${data.id.uid}`); // set the intent to good
2243
- return this._stamp(data, 'sign', data.id.uid);
2244
- }
2245
-
2246
- /**************
2247
- func: license_check
2248
- params:
2249
- - personalVLA: The Personal VLA to validate.
2250
- - packageVLA: The Package VLA to validate against
2251
- describe:
2252
- The license_check function can checks VLA license validity.
2253
- copyright: Copyright ©2000-2026 Quinn Michaels. All rights reserved.
2254
- ***************/
2255
- license_check(personalVLA=false, packageVLA=false) {
2256
- const id = this.uid();
2257
-
2258
- // check the personal VLA is passed
2259
- if (!personalVLA) {
2260
- const personalVLA_str = `license_check:personalVLA:${id.uid}`;
2261
- this.action('return', personalVLA_str); // set the action to return
2262
- this.state('invalid', personalVLA_str); // set the state to invalid
2263
- this.intent('bad', personalVLA_str); // set the intent to bad
2264
- return this._messages.personalVLA; // return the invalid personal VLA message
2265
- };
2266
-
2267
- // check the package VLA is passed.
2268
- if (!packageVLA) {
2269
- const packageVLA_str = `license_check:packageVLA:${id.uid}`;
2270
- this.action('return', packageVLA_str); // set the action to return
2271
- this.state('invalid', packageVLA_str); // set the state to invalid
2272
- this.intent('bad', packageVLA_str); // set the intent to bad
2273
- return this._messages.packageVLA; // return the invalid package VLA message
2274
- }
2275
-
2276
- // this is to ensure no additional information is being transmitted.
2277
- this.state('check', `license_check:compare:${packageVLA.uid}`);
2278
- const personalVLA_hash = this.hash(personalVLA, 'sha256'); // hash the entire personal VLA locally
2279
- const packageVLA_hash = this.hash(packageVLA, 'sha256'); // hash the entire package VLA locally
2280
- if (personalVLA_hash !== packageVLA_hash) return this._messages.checkVLA; // if invalid return the invalid message
2281
-
2282
- this.state('approved', `license_check:${packageVLA.uid}`);
2283
- const approved = {
2284
- id,
2285
- time: Date.now(),
2286
- personal: personalVLA_hash,
2287
- package: packageVLA_hash,
2288
- };
2289
-
2290
- this.action('return', `license_check:${packageVLA.uid}`); // set action to return
2291
- this.state('valid', `license_check:${packageVLA.uid}`); // set the state to valid
2292
- this.intent('good', `license_check:${packageVLA.uid}`); // set the intent to good
2293
- return this._stamp(approved, 'license_check', packageVLA.uid);
2294
- }
2295
-
2296
- /**************
2297
- func: hash
2298
- params:
2299
- - data: The data packet to create a hash value for.
2300
- - algo: The hashing algorithm to use for hashing. md5, sha256, or sha512
2301
-
2302
- describe:
2303
- The hash algorithm will take a string of text and produce a hash.
2304
- ***************/
2305
- hash(data, algo='md5') {
2306
- const the_hash = createHash(algo);
2307
- the_hash.update(JSON.stringify(data));
2308
- return the_hash.digest('base64');
2309
- }
2310
-
1085
+ this._active = Date.now(); // after passes license check set _active date.
1086
+ const id = this.uid();
1087
+ const agent = this.agent();
1088
+
1089
+ this.state('data', `init:${id.uid}`);
1090
+ const data = {
1091
+ id,
1092
+ key: agent.key,
1093
+ value: 'init',
1094
+ agent,
1095
+ client,
1096
+ text: this._messages.init,
1097
+ created: Date.now(),
1098
+ }
1099
+
1100
+ // stamp the init data
1101
+ const data_stamped = this._stamp(data, 'init', data.id.uid);
1102
+
1103
+ const step = (name, ...args) => new Promise((res, rej) => {
1104
+ this[name](...args, res, rej);
1105
+ });
1106
+
1107
+ this.events.setMaxListeners(this.maxListeners);
1108
+ this._assignInherit().then(() => {
1109
+ return this._assignBind();
1110
+ }).then(() => {
1111
+ return this._assignListeners();
1112
+ }).then(() => {
1113
+ this.belief('vedic', `init:${data.id.uid}`);
1114
+ this.feature('init', data.id.uid);
1115
+ this.zone('init', data.id.uid);
1116
+ this.action('init', data.id.uid);
1117
+ this.state('init', data.id.uid);
1118
+
1119
+ return step('Client', client);
1120
+ }).then(() => {
1121
+ return step('License');
1122
+ }).then(() => {
1123
+ return step('Error');
1124
+ }).then(() => {
1125
+ return step('Log');
1126
+ }).then(() => {
1127
+ return step('Data');
1128
+ }).then(() => {
1129
+ return step('Report');
1130
+ }).then(() => {
1131
+ return step('Legal');
1132
+ }).then(() => {
1133
+ return step('Security');
1134
+ }).then(() => {
1135
+ return step('Support');
1136
+ }).then(() => {
1137
+ return step('Services');
1138
+ }).then(() => {
1139
+ return step('Systems');
1140
+ }).then(() => {
1141
+ return step('Done');
1142
+ }).then(() => {
1143
+ const hasOnInit = this.onInit && typeof this.onInit === 'function';
1144
+ if (hasOnInit) {
1145
+ this.action('func', `onInit:${data.id.uid}`); // action set to onfunc
1146
+ this.state('valid', `onInit:${data.id.uid}`); // state set to onfunc
1147
+ this.intent('good', `onInit:${data.id.uid}`); // intent set to good
1148
+ return this.onInit(data_stamped, resolve); // return stamped data
1149
+ }
1150
+ this.action('return', `init:${data.id.uid}`); // action set to return
1151
+ this.state('valid', `init:${data.id.uid}`); // state set to valid
1152
+ this.intent('good', `init:${data.id.uid}`); // intent set to good
1153
+ return this.start(data_stamped, resolve);
1154
+ }).catch(err => {
1155
+ this.state('catch', `init:${data.id.uid}`); // state set to catch
1156
+ this.intent('bad', `init:${data.id.uid}`); // intent set to bad
1157
+ return this.err(err, client, reject);
1158
+ });
1159
+ });
1160
+ }
1161
+
1162
+ /**************
1163
+ func: start
1164
+ usage: this.start(data, resolve);
1165
+ params: data, resolve
1166
+ - data: The data packet that is passed through the invoke chain.
1167
+ - resolve: The Promise resolver following the data through recursion.
1168
+ describe:
1169
+ The start() function initiates the Invoke Recursion Framework phase for the
1170
+ current Deva context. It first checks for active runtime status, retrieves
1171
+ invocation parameters (key-chain mapping, lifecycle handlers) from
1172
+ config.invoke.start, declares the invoke action, and then delegates control
1173
+ to _invoke(), ensuring consistent recursion through the start-enter-done
1174
+ sequence. This design preserves language-agnostic interoperability and
1175
+ deterministic state transitions across Deva systems.
1176
+ ***************/
1177
+ start(data, resolve) {
1178
+ if (!this._active) return resolve(this._messages.offline);
1179
+ return this._invoke({key:'start',data,resolve});
1180
+ }
1181
+
1182
+ /**************
1183
+ func: enter
1184
+ params:
1185
+ - msg: the message from the caller incase need to use in calls
1186
+ describe:
1187
+ The enter function will check the active status of the Deva and set it to
1188
+ offline or enter.
1189
+
1190
+ If the Deva is offline it will return the offline message.
1191
+ usage: this.enter('msg')
1192
+ ***************/
1193
+ enter(data, resolve) {
1194
+ if (!this._active) return resolve(this._messages.offline);
1195
+ return this._invoke({key:'enter',data,resolve});
1196
+ }
1197
+
1198
+ /**************
1199
+ func: done
1200
+ params:
1201
+ - data: the message from the caller incase need to use in calls
1202
+ describe:
1203
+ When the done function is triggered the system will also set the state
1204
+ of the Deva to done.
1205
+
1206
+ If the deva is offline it will return the offline message.
1207
+ usage: this.done('msg')
1208
+ ***************/
1209
+ done(data, resolve) {
1210
+ if (!this._active) return resolve(this._messages.offline);
1211
+ return this._invoke({key:'done',data,resolve});
1212
+ }
1213
+
1214
+ /**************
1215
+ func: ready
1216
+ params:
1217
+ - data: the data to pass to the resolve
1218
+ - resolve: the complete resolve to pass back
1219
+ describe: This function is use to relay the to the ready state.
1220
+ usage: this.ready(data, resolve)
1221
+ ***************/
1222
+ async ready(data, resolve) {
1223
+ if (!this._active) return resolve(this._messages.offline);
1224
+ const key = 'ready';
1225
+
1226
+ this.state('set', `${key}:agent:${data.id.uid}`);
1227
+ const agent = this.agent();
1228
+ const {VLA} = this.info();
1229
+
1230
+ this.state('set', `${key}:config:hash:${data.id.uid}`); // state set to watch OnFinish
1231
+ this._config.hash[agent.key] = {};
1232
+
1233
+ this.state('loop', `${key}:config:ready:hash:${data.id.uid}`);
1234
+ for (let item of this._config.ready_hash) {
1235
+ if (this[item]) {
1236
+ this.action('hash', `${agent.key}:config:${item}:${data.id.uid}`);
1237
+ // manually build hash for the config hash object for each agent key.
1238
+ const this_item = this._binding.get(item) || this[item];
1239
+ this._config.hash[agent.key][item] = this.hash(this_item, 'sha256');
1240
+ }
1241
+ }
1242
+
1243
+ const key_len = Object.keys(this.devas).length // check the key length for looping
1244
+ let x = 1; // let x equal one for iteration.
1245
+ if (this.devas && key_len) {
1246
+ this.state('loop', `${key}:devas:${data.id.uid}`); // set the state to loop
1247
+ for (let deva in this.devas) {
1248
+ // load the deva with client data
1249
+ await this.load(deva, data.client).then(async entity => {
1250
+ const id = this.uid(); // generate a new uid
1251
+ const {dir} = this.devas[deva].info(); // get the base directory for the Deva from the info()
1252
+ const deva_agent = this.devas[deva].agent(); // get the agent data from the deva.
1253
+ this.talk(`deva:dir`, {id, key:deva_agent.key, dir}); // talk the deva dir event to setup tracking the Deva directories
1254
+ if (x === key_len) {
1255
+ setImmediate(() => {
1256
+ return this._invoke({key,data,resolve}); // invoke the deva with the proper key, data, and resolve.
1257
+ });
1258
+ }
1259
+ x = x + 1; // increment the iterator for key_len matching
1260
+ });
1261
+ }
1262
+ }
1263
+ else return this._invoke({key,data,resolve}); // else run the key invoke.
1264
+ }
1265
+
1266
+ /**************
1267
+ func: finish
1268
+ params:
1269
+ - data: the data to pass to the resolve
1270
+ - resolve: the finish resolve to pass back
1271
+ describe: This function is used to relay into the finish state when resolving a question or data.
1272
+ usage: this.finish(data, resolve)
1273
+ ***************/
1274
+ finish(data, resolve) {
1275
+ if (!this._active) return resolve(this._messages.offline);
1276
+ return this._invoke({key:'finish',data,resolve});
1277
+ }
1278
+
1279
+ /**************
1280
+ func: complete
1281
+ params:
1282
+ - data: the data to pass to the resolve
1283
+ - resolve: the complete resolve to pass back
1284
+ describe: This function is use to relay into a complete state when
1285
+ resolving a question or data.
1286
+ usage: this.complete(data, resolve)
1287
+ ***************/
1288
+ complete(data, resolve) {
1289
+ if (!this._active) return resolve(this._messages.offline);
1290
+ return this._invoke({key:'complete',data,resolve});
1291
+ }
1292
+
1293
+ /**************
1294
+ func: stop
1295
+ usage: this.stop();
1296
+ params: none
1297
+ describe:
1298
+ The stop() function initiates the egress stop aspect of the Invoke
1299
+ Recursion Framework.
1300
+ ***************/
1301
+ stop() {
1302
+ if (!this._active) return Promise.resolve(this._messages.offline); // check for active status
1303
+ const key = 'stop'; // set the stop key
1304
+ const id = this.uid(); // generate the stop uid
1305
+ let data;
1306
+ return new Promise(async (resolve, reject) => {
1307
+ try {
1308
+ // stop the child Devas first so none are left running when the parent closes. ready() loads them last.
1309
+ this.state('loop', `${key}:devas:${id.uid}`);
1310
+ for (const deva in this.devas) await this.devas[deva].stop();
1311
+
1312
+ this.state('set', `${key}:agent:${id.uid}`); // state stop agent
1313
+ const agentData = this.agent();
1314
+ const agent = agentData.sha256; // get the current agent
1315
+ const value = agentData.key;
1316
+
1317
+ this.state('set', `${key}:client:${id.uid}`); // state stop agent
1318
+ const client = this.client().sha256; // set the current client
1319
+
1320
+ this.state('data', `${key}:${id.uid}`);
1321
+ data = { // build the stop data
1322
+ id, // set the id
1323
+ key, // set the key
1324
+ value, // set the value
1325
+ agent, // set the agent
1326
+ client, // set the client
1327
+ stop: Date.now(), // set the created date
1328
+ }
1329
+
1330
+ this.action('return', `${key}:invoke:${data.id.uid}`);
1331
+ this.state('valid', `${key}:invoke:${data.id.uid}`);
1332
+ this.intent('good', `${key}:invoke:${data.id.uid}`);
1333
+ return this._invoke({
1334
+ key,
1335
+ data,
1336
+ resolve,
1337
+ });
1338
+ }
1339
+ catch (err) {
1340
+ return this.err(err, data, reject);
1341
+ }
1342
+ });
1343
+ }
1344
+
1345
+ /**************
1346
+ func: close
1347
+ usage: this.close(data, resolve);
1348
+ params: data, resolve
1349
+ - data: The data packet that is passed through the closing invoke chain.
1350
+ - resolve: The Promise resolver following the data through recursion.
1351
+ describe:
1352
+ The close() function initiates the close aspect of the Invoke Recursion Framework.
1353
+ ***************/
1354
+ close(data, resolve) {
1355
+ if (!this._active) return resolve(this._messages.offline);
1356
+ const key = 'close';
1357
+ data.key = key;
1358
+ return this._invoke({key,data,resolve});
1359
+ }
1360
+
1361
+ /**************
1362
+ func: leave
1363
+ usage: this.leave(data, resolve);
1364
+ params: data, resolve
1365
+ - data: The data packet that is passed through the closing invoke chain.
1366
+ - resolve: The Promise resolver following the data through recursion.
1367
+ describe:
1368
+ The leave() function initiates the leave aspect of the Invoke Recursion
1369
+ Framework.
1370
+ ***************/
1371
+ leave(data, resolve) {
1372
+ if (!this._active) return resolve(this._messages.offline);
1373
+ const key = 'leave';
1374
+ data.key = key;
1375
+ return this._invoke({key,data,resolve});
1376
+ }
1377
+
1378
+ /**************
1379
+ func: exit
1380
+ usage: this.exit(data, resolve);
1381
+ params: data, resolve
1382
+ - data: The data packet that is passed through the egress invoke chain.
1383
+ - resolve: The Promise resolver following the data through recursion.
1384
+ describe:
1385
+ The exit() function initiates the exit aspect of the Invoke Recursion
1386
+ Framework.
1387
+ ***************/
1388
+ exit(data, resolve) {
1389
+ if (!this._active) return resolve(this._messages.offline);
1390
+ const key = 'exit';
1391
+ data.key = key;
1392
+ return this._invoke({key,data,resolve});
1393
+ }
1394
+
1395
+ /**************
1396
+ func: shutdown
1397
+ params:
1398
+ - msg: hte message from the caller incase need to use in calls
1399
+ describe:
1400
+ The exit state function is triggered when the Deva is exiting.
1401
+
1402
+ The return will check for a custom onExit function or run the done
1403
+ function.
1404
+ ***************/
1405
+ shutdown(data, resolve) {
1406
+ if (!this._active) return resolve(this._messages.offline);
1407
+ const key = 'shutdown';
1408
+ data.key = key;
1409
+ return this._invoke({key, data, resolve})
1410
+ }
1411
+
1412
+
1413
+ ////////////////////////////
1414
+
1415
+
1416
+ /**************
1417
+ func: context
1418
+ params:
1419
+ - value: The context flag to set for the Deva that matches to this._contexts
1420
+ - extra: Any extra text that is sent with the context value.
1421
+ describe
1422
+ ***************/
1423
+ context(value=false, extra=false) {
1424
+ if (!this._active) return this._messages.offline; // check the active status
1425
+ const id = this.uid();
1426
+ try {
1427
+ if (!value) return;
1428
+ this._context = value;
1429
+ const lookup = this.vars?.context?.[value] || value;
1430
+ const text = extra ? `${lookup} ${extra}` : lookup;
1431
+
1432
+ const data = {
1433
+ id,
1434
+ agent: this.agent(),
1435
+ client: this.client(),
1436
+ key: 'context',
1437
+ value,
1438
+ text,
1439
+ created: Date.now(),
1440
+ };
1441
+
1442
+ const data_stamped = this._stamp(data, `context`, id.uid);
1443
+
1444
+ this.talk(this._events.context, this.lib.copy(data_stamped));
1445
+ return data_stamped;
1446
+ } catch (e) {
1447
+ this.state('catch', `context:${value}:${id.uid}`);
1448
+ return this.err(e, value);
1449
+ }
1450
+ }
1451
+
1452
+ contexts() {
1453
+ if (!this._active) return this._messages.offline; // check the active status
1454
+ const id = this.uid();
1455
+ const key = 'contexts';
1456
+ this.action(key, id.uid);
1457
+
1458
+ this.state('data', `${key}:${id.uid}`);
1459
+ const data = {
1460
+ id,
1461
+ key,
1462
+ value: this.vars.context || false, // this loads the local agent context list.
1463
+ agent: this.agent(),
1464
+ client: this.client(),
1465
+ created: Date.now(),
1466
+ };
1467
+
1468
+ this.state('return', `${key}:${id.uid}`);
1469
+ return this._stamp(data, key, id.uid);
1470
+ }
1471
+
1472
+ /**************
1473
+ func: feature
1474
+ params:
1475
+ - value: The feature flag to set for the Deva that matches to this._features
1476
+ - extra: Any extra text to send with the feature value.
1477
+ describe
1478
+ ***************/
1479
+ feature(value=false, extra=false) {
1480
+ return this._workflow('feature', value, extra);
1481
+ }
1482
+
1483
+ /**************
1484
+ func: features
1485
+ params: none
1486
+ describe: return a list of features that are available to the system.
1487
+ ***************/
1488
+ features() {
1489
+ return this._workflowItems('features');
1490
+ }
1491
+
1492
+ /**************
1493
+ func: zone
1494
+ params:
1495
+ - value: the value to pass to _workflow
1496
+ - extra: Any extra text to send with the zone.
1497
+ ***************/
1498
+ zone(value=false, extra=false) {
1499
+ return this._workflow('zone', value, extra);
1500
+ }
1501
+
1502
+ /**************
1503
+ func: zones
1504
+ params: none
1505
+ describe: returns a listing of zones currently in the system.
1506
+ ***************/
1507
+ zones() {
1508
+ return this._workflowItems('zones');
1509
+ }
1510
+
1511
+ /**************
1512
+ func: action
1513
+ params:
1514
+ - value: The state flag to set for the Deva that matches to this._states
1515
+ - extra: Any extra text to send with the action value.
1516
+ describe
1517
+ ***************/
1518
+ action(value=false, extra=false) {
1519
+ return this._workflow('action', value, extra);
1520
+ }
1521
+
1522
+ /**************
1523
+ func: actions
1524
+ params: none
1525
+ describe: Returns a list of available actions in the system.
1526
+ ***************/
1527
+ actions() {
1528
+ return this._workflowItems('actions');
1529
+ }
1530
+
1531
+ /**************
1532
+ func: state
1533
+ params:
1534
+ - value: The state value to set for the Deva that matches to this._states
1535
+ - extra: any extra text to add to the state change.
1536
+ ***************/
1537
+ state(value=false, extra=false) {
1538
+ return this._workflow('state', value, extra);
1539
+ }
1540
+
1541
+ /**************
1542
+ func: states
1543
+ params: none
1544
+ describe: returns the available states values.
1545
+ ***************/
1546
+ states() {
1547
+ return this._workflowItems('states');
1548
+ }
1549
+
1550
+ /**************
1551
+ func: intent
1552
+ params:
1553
+ - value: The intent value to set for the Deva that matches to this._intents
1554
+ - extra: any extra text to add to the intent change.
1555
+ ***************/
1556
+ intent(value=false, extra=false) {
1557
+ return this._workflow('intent', value, extra);
1558
+ }
1559
+
1560
+ /**************
1561
+ func: intents
1562
+ params: none
1563
+ describe: returns the available intents values.
1564
+ ***************/
1565
+ intents() {
1566
+ return this._workflowItems('intents');
1567
+ }
1568
+
1569
+ /**************
1570
+ func: belief
1571
+ params:
1572
+ - value: The belief value to set for the Deva that matches to this._beliefs
1573
+ - extra: any extra text to add to the belief change.
1574
+ ***************/
1575
+ belief(value=false, extra=false) {
1576
+ return this._workflow('belief', value, extra);
1577
+ }
1578
+
1579
+ /**************
1580
+ func: beliefs
1581
+ params: none
1582
+ describe: returns the available beliefs values.
1583
+ ***************/
1584
+ beliefs() {
1585
+ return this._workflowItems('beliefs');
1586
+ }
1587
+
1588
+ /**************
1589
+ func: _workflow
1590
+ params:
1591
+ - value: The workflow value to set for the Deva that matches to this._states
1592
+ - extra: any extra text to add to the state change.
1593
+ stages: Feature, Zone, Action, State, Intent
1594
+ ***************/
1595
+ _workflow(key, value=false, extra=false) {
1596
+ if (!this._active) return this._messages.offline;
1597
+ const id = this.uid();
1598
+ try {
1599
+ const _key = `_${key}`;
1600
+ const _keys = `_${key}s`;
1601
+ if (!value || !this[_keys][value]) return; // return if no matching value
1602
+ this[_key] = value;
1603
+ const lookup = this[_keys][value]; // set the local states lookup
1604
+ const text = extra ? `${lookup} ${extra}` : lookup; // set text from lookup with extra
1605
+ const data = { // build the data object
1606
+ id, // set the data id
1607
+ key, // set the key to state
1608
+ value, // set the value to the passed in value
1609
+ text, // set the text value of the data
1610
+ agent: this.agent(), // set the agent
1611
+ client: this.client(), // set the client
1612
+ created: Date.now(), // set the data created date.
1613
+ };
1614
+
1615
+ // manual hashing to avoid _stamp conflict at load.
1616
+ data.md5 = this.hash(data, 'md5');
1617
+ data.sha256 = this.hash(data, 'sha256');
1618
+ data.sha512 = this.hash(data, 'sha512');
1619
+
1620
+ this.talk(this._events[key], this.lib.copy(data)); // broadcast the state event
1621
+ return data;
1622
+ } catch (e) { // catch any errors
1623
+ return this.err(e); // return if an error happens
1624
+ }
1625
+ }
1626
+
1627
+ /**************
1628
+ func: _workflowItems
1629
+ params: none
1630
+ describe: returns the available workflow items for a given key.
1631
+ ***************/
1632
+ _workflowItems(key) {
1633
+ if (!this._active) return this._messages.offline;
1634
+ const id = this.uid(); // set the current uid
1635
+ this.action(key, id.uid); // set the action to the passed key
1636
+ const value = this[`_${key}`]; // get the _keys value
1637
+ // set the data packet for the states
1638
+ this.state('data', `${key}:${id.uid}`);
1639
+ const data = {
1640
+ id,
1641
+ key,
1642
+ value,
1643
+ agent: this.agent(),
1644
+ client: this.client(),
1645
+ created: Date.now(),
1646
+ }
1647
+
1648
+ this.action('return', `${data.key}:${id.uid}`);
1649
+ return this._stamp(data, data.key, id.uid);
1650
+ }
1651
+
1652
+ /**************
1653
+ func: client
1654
+ params: none
1655
+ describe: returns the current client values in the system.
1656
+ usage: this.client();
1657
+ ***************/
1658
+ client() {
1659
+ if (!this._active) return this._messages.offline; // check the active status
1660
+ const data = this.lib.copy(this._client); // create a copy of the client data
1661
+ // manual hashing here to prevent stack overflow with this._stamp.
1662
+ data.md5 = this.hash(data, 'md5');
1663
+ data.sha256 = this.hash(data, 'sha256');
1664
+ data.sha512 = this.hash(data, 'sha512');
1665
+ return data; // return the copy of the client data.
1666
+ }
1667
+
1668
+ /**************
1669
+ func: agent
1670
+ params: none
1671
+ describe: returns the current agent values in the system.
1672
+ usage: this.agent()
1673
+ ***************/
1674
+ agent() {
1675
+ if (!this._active) return this._messages.offline; // check the active status
1676
+ const data = this.lib.copy(this._agent); // create a copy of the agent data.
1677
+ // manual hashing here to prevent stack overflow with this._stamp.
1678
+ data.md5 = this.hash(data, 'md5');
1679
+ data.sha256 = this.hash(data, 'sha256');
1680
+ data.sha512 = this.hash(data, 'sha512');
1681
+ return data; // return the copy of the agent data.
1682
+ }
1683
+
1684
+ // FEATURE FUNCTIONS
1685
+ /**************
1686
+ func: license
1687
+ params: none
1688
+ describe: basic license features available in a Deva.
1689
+ usage: this.license()
1690
+ ***************/
1691
+ license() {
1692
+ return this._getFeature('license');
1693
+ }
1694
+
1695
+ /**************
1696
+ func: error
1697
+ params: none
1698
+ describe: basic error features available in a Deva.
1699
+ usage: this.error()
1700
+ ***************/
1701
+ error() {
1702
+ return this._getFeature('error');
1703
+ }
1704
+
1705
+ /**************
1706
+ func: log
1707
+ params: none
1708
+ describe: basic log features available in a Deva.
1709
+ usage: this.log()
1710
+ ***************/
1711
+ log() {
1712
+ return this._getFeature('log');
1713
+ }
1714
+
1715
+ /**************
1716
+ func: data
1717
+ params: none
1718
+ describe: basic data features available in a Deva.
1719
+ usage: this.data()
1720
+ ***************/
1721
+ data() {
1722
+ return this._getFeature('data');
1723
+ }
1724
+
1725
+ /**************
1726
+ func: report
1727
+ params: none
1728
+ describe: basic report features available in a Deva.
1729
+ usage: this.report()
1730
+ ***************/
1731
+ report() {
1732
+ return this._getFeature('report');
1733
+ }
1734
+
1735
+ /**************
1736
+ func: security
1737
+ params: none
1738
+ describe: basic security features available in a Deva.
1739
+ usage: this.security()
1740
+ ***************/
1741
+ security() {
1742
+ return this._getFeature('security');
1743
+ }
1744
+
1745
+ /**************
1746
+ func: legal
1747
+ params: none
1748
+ describe: basic legal features available in a Deva.
1749
+ usage: this.systems()
1750
+ ***************/
1751
+ legal() {
1752
+ return this._getFeature('legal');
1753
+ }
1754
+
1755
+ /**************
1756
+ func: support
1757
+ params: none
1758
+ describe: basic support features available in a Deva.
1759
+ usage: this.support()
1760
+ ***************/
1761
+ support() {
1762
+ return this._getFeature('support');
1763
+ }
1764
+
1765
+ /**************
1766
+ func: services
1767
+ params: none
1768
+ describe: basic services features available in a Deva.
1769
+ usage: this.services()
1770
+ ***************/
1771
+ services() {
1772
+ return this._getFeature('services');
1773
+ }
1774
+
1775
+ /**************
1776
+ func: systems
1777
+ params: none
1778
+ describe: basic systems features available in a Deva.
1779
+ usage: this.systems()
1780
+ ***************/
1781
+ systems() {
1782
+ return this._getFeature('systems');
1783
+ }
1784
+
1785
+ /**************
1786
+ func: load
1787
+ params:
1788
+ -deva: The Deva model to load.
1789
+ describe: This function will enable fast loading of Deva into the system.
1790
+ ***************/
1791
+ load(key, client) {
1792
+ this.zone('load', key);
1793
+ this.action('load', key);
1794
+ this.state('load', key);
1795
+ this.intent('good', `load:${key}`);
1796
+ return new Promise((resolve, reject) => {
1797
+ this.devas[key].init(client).then(deva => {
1798
+ return resolve(deva)
1799
+ }).catch(err => {
1800
+ return this.err(err, client, reject);
1801
+ })
1802
+ });
1803
+ }
1804
+
1805
+ /**************
1806
+ func: unload
1807
+ params:
1808
+ - deva: The deva key to unload
1809
+ describe: Unload a currently loaded Deva.
1810
+ ***************/
1811
+ unload(key) {
1812
+ return new Promise((resolve, reject) => {
1813
+ if (!this._active) return resolve(this._messages.offline); // check the active status
1814
+ this.zone('unload', key);
1815
+ this.action('unload', key);
1816
+ this.state('unload', key);
1817
+ this.state('try', `unload:${key}`);
1818
+ try {
1819
+ this.devas[key].stop().then(exit => {
1820
+ delete this.devas[key];
1821
+ this.action('talk', `${this._events.unload}:${key}`);
1822
+ this.talk(this._events.unload, key);
1823
+ });
1824
+ this.action('resolve', `unload:${key}`);
1825
+ this.intent('good', `unload:${key}`);
1826
+ return resolve(`${this._messages.unload}:${key}`);
1827
+ } catch (e) {
1828
+ this.state('catch', `unload:${key}`);
1829
+ this.intent('bad', `unload:${key}`);
1830
+ return this.err(e, key, reject)
1831
+ }
1832
+ });
1833
+ }
1834
+
1835
+ /**************
1836
+ func: prompt
1837
+ params:
1838
+ - text: The text string to send to the prompt.
1839
+ describe:-
1840
+ The prompt function is used to broadcasat a global prompt event with a string. Thsi is handy when passing events between a cli and user interface for example.
1841
+
1842
+ usage: this.prompt('text')
1843
+ ***************/
1844
+ prompt(text) {
1845
+ if (!this._active) return this._messages.offline; // return offline message if inactive.
1846
+ const id = this.uid(); // generate the id for the prompt
1847
+ const agent = this.agent(); // set the agent for the prompt
1848
+ const client = this.client(); // set the client for the prompt
1849
+ const {key} = agent; // set the key from agent
1850
+ const value = 'prompt'; // set the value of the key.
1851
+ // create data packet to generate prompt
1852
+
1853
+ this.state('data', `${key}:${value}:${id.uid}`)
1854
+ const data = {
1855
+ id,
1856
+ key,
1857
+ value,
1858
+ agent,
1859
+ client,
1860
+ text,
1861
+ created: Date.now(),
1862
+ }
1863
+
1864
+ // stamp the data
1865
+ const data_stamped = this._stamp(data, `${key}:${value}`, data.id.uid);
1866
+
1867
+ // talk the prompt event to anyone listening
1868
+ this.action('talk', `${key}:${value}:${id.uid}`);
1869
+ this.talk(this._events.prompt, data_stamped);
1870
+
1871
+ this.action('return', `${key}:${value}:${id.uid}`);
1872
+ return data_stamped;
1873
+ }
1874
+
1875
+ /**************
1876
+ func: core
1877
+ params: none
1878
+ describe: return core data.
1879
+ ***************/
1880
+ core() {
1881
+ if (!this._active) return this._messages.offline;
1882
+ const id = this.uid();
1883
+ this.action('core', id.uid);
1884
+
1885
+ // check the active status
1886
+ const data = this.lib.copy(this._core);
1887
+ data.id = id;
1888
+ data.created = Date.now();
1889
+
1890
+ this.action('return', `core:${id.uid}`);
1891
+ this.intent('good', `core:${id.uid}`);
1892
+ return this._stamp(this._unstamp(data), 'core', data.id.uid);
1893
+ }
1894
+
1895
+ // machine returns the sha256 machine fingerprint
1896
+ machine() {
1897
+ const {os} = this.lib;
1898
+ const data = {
1899
+ arch: os.arch(),
1900
+ hostname: os.hostname(),
1901
+ network: os.networkInterfaces(),
1902
+ platform: os.platform(),
1903
+ release: os.release(),
1904
+ type: os.type(),
1905
+ user: os.userInfo(),
1906
+ version: os.version(),
1907
+ uptime: os.uptime(),
1908
+ cpus: os.cpus(),
1909
+ created: Date.now(),
1910
+ };
1911
+ // machine has to do manual hashing to prevent stack overflow.
1912
+ data.md5 = this.hash(data, 'md5');
1913
+ data.sha256 = this.hash(data, 'sha256');
1914
+ data.sha512 = this.hash(data, 'sha512');
1915
+ return data;
1916
+ }
1917
+
1918
+ /**************
1919
+ func: info
1920
+ params: none
1921
+ describe: return info data.
1922
+ ***************/
1923
+ info() {
1924
+ if (!this._active) return this._messages.offline;
1925
+ const data = this.lib.copy(this._info);
1926
+ data.created = Date.now();
1927
+
1928
+ this.action('return', `info:${data.id}`);
1929
+ this.intent('good', `info:${data.id}`);
1930
+ return this._stamp(data, 'info', data.id);
1931
+ }
1932
+
1933
+ /**************
1934
+ func: status
1935
+ params:
1936
+ - msg: The msg is any additonal string to append to the end of hte call.
1937
+ describe:
1938
+ The status function provides an easy way to get the current status of a Deva
1939
+ and append custom status messages that may pertain to any custom status call.
1940
+
1941
+ If the deva is offline it will return the offline message.
1942
+ usage: this.status('msg')
1943
+ ***************/
1944
+ status() {
1945
+ if (!this._active) return this._messages.offline;
1946
+ const id = this.uid();
1947
+ this.action('status', id);
1948
+ // check the active status
1949
+
1950
+ // format the date since active for output.
1951
+ const dateFormat = this.lib.formatDate(this._active, 'long', true);
1952
+ // create the text msg string
1953
+ this.action('return', `status:${id.uid}`);
1954
+ this.intent('good', `status:${id.uid}`);
1955
+ return `${this._agent.profile.name} active since ${dateFormat}`; // return final text string
1956
+ }
1957
+
1958
+ /**************
1959
+ func: help
1960
+ params:
1961
+ - msg: the help msg to search against
1962
+ - help_dir: base directory of the deva help files.
1963
+ describe:
1964
+ the help utility makes it easy to create help files for your deva. the utility
1965
+ checks the existence of a help file in the passed in directory then if
1966
+ one exists it will then present it based on the users request text input.
1967
+ ***************/
1968
+ help(msg, help_dir) {
1969
+ return new Promise((resolve, reject) => {
1970
+ if (!this._active) return resolve(this._messages.offline);
1971
+ let helpDoc = false;
1972
+ const id = this.uid();
1973
+ const key = 'help';
1974
+ this.zone(key, id.uid);
1975
+
1976
+ this.feature(key, id.uid);
1977
+ this.action(key, id.uid);
1978
+ this.state(key, id.uid);
1979
+ this.context(key, id.uid);
1980
+
1981
+ const params = msg.split(' '); // split the msg into an array by spaces.
1982
+
1983
+ const splitText = params[0].split(':');
1984
+ const part = splitText[1] ? splitText[1].toUpperCase() : 'MAIN';
1985
+ const helpFile = splitText[0] ? splitText[0] : 'main';
1986
+
1987
+ const helpPath = this.lib.path.join(help_dir, key, `${helpFile}.feecting`);
1988
+
1989
+ this.state('try', `${key}:${id.uid}`);
1990
+ try {
1991
+ // check if help file exists first and resolve if no file
1992
+ const helpExists = this.lib.fs.existsSync(helpPath); // check if help file exists
1993
+ if (!helpExists) {
1994
+ this.action('resolve', `${key}:not:exists:${id.uid}`);
1995
+ this.state('invalid', `${key}:not:exists:${id.uid}`);
1996
+ this.intent('bad', `${key}:not:exists:${id.uid}`);
1997
+ return resolve(this._messages.help_not_found);
1998
+ }
1999
+
2000
+ // get the help file and check to make sure the part we are looking for exists.
2001
+ const helpFile = this.lib.fs.readFileSync(helpPath, 'utf8');
2002
+ const helpPart = helpFile.split(`${this.container.begin}:${part}`);
2003
+ if (!helpPart[1]) {
2004
+ this.action('resolve', `${key}:not:found:${id.uid}`);
2005
+ this.state('invalid', `${key}:not:found:${id.uid}`);
2006
+ this.intent('bad', `${key}:not:found:${id.uid}`);
2007
+ return resolve(this._messages.help_not_found);
2008
+ }
2009
+
2010
+ // last set the help doc and split out the selected part.
2011
+ helpDoc = helpFile.split(`${this.container.begin}:${part}`)[1].split(`${this.container.end}:${part}`)[0];
2012
+
2013
+ this.action('resolve', `${key}:${id.uid}`);
2014
+ this.state('valid', `${key}:${id.uid}`);
2015
+ this.intent('good', `${key}:${id.uid}`);
2016
+ return resolve(helpDoc);
2017
+ }
2018
+ catch(e) {
2019
+ this.state('catch', `${key}:${id.uid}`);
2020
+ this.intent('bad', `${key}:${id.uid}`);
2021
+ return this.err(e, msg, reject);
2022
+ }
2023
+ });
2024
+ }
2025
+
2026
+ /**************
2027
+ func: err
2028
+ params:
2029
+ - err: The error to process
2030
+ - data: Any additional data associated with the error
2031
+ - reject: An associated promise reject if the caller requires.
2032
+ describe:
2033
+ The err function provides the consistent error manage of the system.
2034
+
2035
+ If the agent defines an onError function, err hands it (err, packet, reject)
2036
+ and returns its result. In that case the agent owns the outcome: onError must
2037
+ call reject to fail the caller's promise, or the promise will stay pending.
2038
+ If there is no onError function, err calls reject(err) itself.
2039
+
2040
+ usage: this.err(err, data, reject);
2041
+
2042
+
2043
+ ***************/
2044
+ err(err,packet,reject=false) {
2045
+ const id = this.uid();
2046
+ const key = 'error';
2047
+ this.feature(key, id.uid);
2048
+ this.zone(key, id.uid);
2049
+ this.action(key, id.uid);
2050
+ this.state(key, id.uid);
2051
+ this.intent('bad', `${key}:${id.uid}`);
2052
+
2053
+ const agent = this.agent();
2054
+ const client = this.client();
2055
+
2056
+ this.state('data', `${key}:${id.uid}`);
2057
+ const data = {
2058
+ id,
2059
+ key,
2060
+ value: agent.key,
2061
+ agent,
2062
+ client,
2063
+ error: {
2064
+ name: err.name,
2065
+ message: err.message,
2066
+ stack: err.stack,
2067
+ },
2068
+ packet,
2069
+ created: Date.now(),
2070
+ };
2071
+ // stamp the data before return
2072
+ const data_stamped = this._stamp(data, `${data.key}:${data.value}`, data.id.uid);
2073
+
2074
+ // set the action to talk and emit the talk error.
2075
+ this.action('talk', `${this._events.error}:${data.id.uid}`);
2076
+ this.talk(this._events.error, this.lib.copy(data_stamped));
2077
+
2078
+ const hasOnError = this.onError && typeof this.onError === 'function' ? true : false;
2079
+ // if block handles returning the onError and setting the state to hasOnError
2080
+ if (hasOnError) {
2081
+ this.action('func', `onError:${data.value}:${data.id.uid}`);
2082
+ this.state('invalid', `onError:${data.value}:${data.id.uid}`);
2083
+ this.intent('bad', `hasOnError:${data.id.uid}`);
2084
+ return this.onError(err, packet, reject);
2085
+ }
2086
+ // else block handled the reject if there is no onError function.
2087
+ else {
2088
+ this.action('reject', `${data.value}:${id.uid}`);
2089
+ this.intent('bad', `error:${data.id.uid}`);
2090
+ return reject ? reject(err) : Promise.reject(err);
2091
+ }
2092
+ }
2093
+
2094
+ /**************
2095
+ func: uid
2096
+ params:
2097
+ - guid: This is a true false flag for generating a guid.
2098
+ describe:
2099
+ The uid function can create two types of id for you.
2100
+ 1. random GUID - this is good for when you need a uinique record id returned
2101
+ 2. transport uid - The transport id is a number generated to provide a
2102
+ secure numerical number used for transporting records
2103
+ across networks without collision or needing to store system uuid.
2104
+ 3. the uid is then returned with a created, md5, sha256, and sha512 hash of the value
2105
+ copyright: Copyright ©2000-2026 Quinn Michaels. All rights reserved.
2106
+ ***************/
2107
+ uid(guid=false) {
2108
+ const time = Date.now(); // set time to local constant
2109
+ const iso = this.lib.formatDate(time, 'iso', true); // set date to local constant
2110
+ const utc = this.lib.formatDate(time, 'utc', true); // set date to local constant
2111
+ const date = this.lib.formatDate(time, 'long', true); // set date to local constant
2112
+ const license = this._info.VLA ? this._info.VLA.uid : false;
2113
+ const client = this.client(); // get the client
2114
+ const agent = this.agent(); // get the agent
2115
+ const machine = this.machine(); // get the machine hash
2116
+
2117
+ const core_hash = this._core.sha256; // get the core sha256 hash
2118
+
2119
+ const warning = this._agent.profile.warning || this._messages.warning; // agent or default warning
2120
+ const notice = this._agent.profile.notice || this._messages.notice; // agent or default notice
2121
+ const copyright = this._agent.profile.copyright || this._messages.copyright; // agent or default copyright
2122
+
2123
+ const status = this._agent.profile.status || this._messages.status;
2124
+
2125
+ const vectors = this._agent.profile.vectors || this._messages.vectors;
2126
+ const owner = this._agent.profile.owner || this._messages.owner;
2127
+ const creator = this._agent.profile.creator || this._messages.creator;
2128
+ const salute = this._agent.profile.salute || this._messages.salute;
2129
+
2130
+ const fingerprint_data = {
2131
+ license,
2132
+ client: client.sha256,
2133
+ agent: agent.sha256,
2134
+ machine: machine.sha256,
2135
+ core_hash,
2136
+ };
2137
+ const fingerprint = this.hash(fingerprint_data, 'sha256');
2138
+
2139
+ const data = {
2140
+ uid: false,
2141
+ time,
2142
+ iso,
2143
+ utc,
2144
+ date,
2145
+ license,
2146
+ fingerprint,
2147
+ client: client.sha256,
2148
+ agent: agent.sha256,
2149
+ machine: machine.sha256,
2150
+ core_hash,
2151
+ status,
2152
+ warning,
2153
+ notice,
2154
+ vectors,
2155
+ owner,
2156
+ creator,
2157
+ salute,
2158
+ copyright,
2159
+ }
2160
+ if (guid) {
2161
+ const uid = randomUUID(); // set uid into local constant.
2162
+ data.uid = uid; // set base data object.
2163
+ }
2164
+ else {
2165
+ const min = Math.floor(time - (time / Math.PI)); // generate min time from Math.PI divisor.
2166
+ const max = Math.ceil(time + (time * Math.PI)); // generate max time form Math.PI multiplier.
2167
+ const begin_random = Math.floor(Math.random() * (max - min) + min); // generate random number between min and max.
2168
+ const {end_min, end_max} = this._uid; // set end min and max in to constant
2169
+ const end_random = Math.ceil(Math.random() * (end_max - end_min) + end_min); // generate end salt on the number for added randomness.
2170
+
2171
+ const uid = `${begin_random}${end_random}`; // set uid to local constant
2172
+ data.uid = uid; // set base data object.
2173
+ }
2174
+ // manual hashing to prevent overflow on stack calls.
2175
+ data.md5 = this.hash(data, 'md5'); // md5 the uid and created.
2176
+ data.sha256 = this.hash(data, 'sha256'); // sha256 the uid, created, md5
2177
+ data.sha512 = this.hash(data, 'sha512'); // sha512 the uid, created, md5, sha256.
2178
+ return data; // return the complete uid data.
2179
+ }
2180
+
2181
+ /**************
2182
+ func: sign
2183
+ params:
2184
+ - packet: The packet to sign data to.
2185
+ describe:
2186
+ The sign function can create a digital signature to a packet.
2187
+ copyright: Copyright ©2000-2026 Quinn Michaels. All rights reserved.
2188
+ ***************/
2189
+ sign(packet) {
2190
+ const id = this.uid();
2191
+ const {time, date, fingerprint} = id;
2192
+
2193
+ const client = this.client();
2194
+ const agent = this.agent();
2195
+ const {q} = packet;
2196
+
2197
+ const {meta, text} = q;
2198
+ const {key, method, params} = meta;
2199
+
2200
+ const opts = this.lib.copy(params); // copy the params and set as opts.
2201
+ const command = opts.shift();
2202
+
2203
+ const {invalid_agent,invalid_client} = this._messages;
2204
+
2205
+ const agent_hash = agent.sha256 === packet.q.agent.sha256 ? agent.sha256 : invalid_agent;
2206
+ const client_hash = client.sha256 === packet.q.client.sha256 ? client.sha256 : invalid_client;
2207
+
2208
+ const container = `OM:O:${key.toUpperCase()}:${id.uid}`; // set container string.
2209
+
2210
+ this.action('hash', `${key}:packet:sha256:${id.uid}`);
2211
+ const packet_hash = this.hash(packet, 'sha256');
2212
+
2213
+ this.action('hash', `${key}:token:sha256:${id.uid}`);
2214
+ const token = this.hash(`${key} client:${client.profile.id} fullname:${client.profile.fullname} uid:${id.uid}`, 'sha256');
2215
+
2216
+ const warning = agent.profile.warning || this._messages.warning;
2217
+ const copyright = agent.profile.copyright || this._core.copyright;
2218
+
2219
+ // build the main data packet.
2220
+ this.state('data', `${key}:sign:${id.uid}`); // set state data
2221
+ const data = {
2222
+ id,
2223
+ key,
2224
+ method,
2225
+ opts: opts.join('.'),
2226
+ text,
2227
+ time,
2228
+ date,
2229
+ container,
2230
+ client: {
2231
+ key: client.key,
2232
+ name: client.profile.name,
2233
+ fullname: client.profile.fullname,
2234
+ emojis: client.profile.emojis,
2235
+ company: client.profile.company,
2236
+ expires: client.profile.expires ? time + client.profile.expires : 'none',
2237
+ caseid: client.profile.caseid || 'none',
2238
+ token,
2239
+ hash: client_hash,
2240
+ },
2241
+ agent: {
2242
+ key: agent.key,
2243
+ name: agent.profile.name,
2244
+ hash: agent_hash,
2245
+ },
2246
+ packet: packet_hash,
2247
+ warning,
2248
+ copyright,
2249
+ };
2250
+
2251
+ this.action('return', `${data.key}:sign:${data.id.uid}`); // set the action to return
2252
+ this.intent('good', `${data.key}:sign:${data.id.uid}`); // set the intent to good
2253
+ return this._stamp(data, 'sign', data.id.uid);
2254
+ }
2255
+
2256
+ /**************
2257
+ func: license_check
2258
+ params:
2259
+ - personalVLA: The Personal VLA to validate.
2260
+ - packageVLA: The Package VLA to validate against
2261
+ describe:
2262
+ The license_check function can checks VLA license validity.
2263
+ copyright: Copyright ©2000-2026 Quinn Michaels. All rights reserved.
2264
+ ***************/
2265
+ license_check(personalVLA=false, packageVLA=false) {
2266
+ const id = this.uid();
2267
+
2268
+ // check the personal VLA is passed
2269
+ if (!personalVLA) {
2270
+ const personalVLA_str = `license_check:personalVLA:${id.uid}`;
2271
+ this.action('return', personalVLA_str); // set the action to return
2272
+ this.state('invalid', personalVLA_str); // set the state to invalid
2273
+ this.intent('bad', personalVLA_str); // set the intent to bad
2274
+ return this._messages.personalVLA; // return the invalid personal VLA message
2275
+ };
2276
+
2277
+ // check the package VLA is passed.
2278
+ if (!packageVLA) {
2279
+ const packageVLA_str = `license_check:packageVLA:${id.uid}`;
2280
+ this.action('return', packageVLA_str); // set the action to return
2281
+ this.state('invalid', packageVLA_str); // set the state to invalid
2282
+ this.intent('bad', packageVLA_str); // set the intent to bad
2283
+ return this._messages.packageVLA; // return the invalid package VLA message
2284
+ }
2285
+
2286
+ // this is to ensure no additional information is being transmitted.
2287
+ this.state('check', `license_check:compare:${packageVLA.uid}`);
2288
+ const personalVLA_hash = this.hash(personalVLA, 'sha256'); // hash the entire personal VLA locally
2289
+ const packageVLA_hash = this.hash(packageVLA, 'sha256'); // hash the entire package VLA locally
2290
+ if (personalVLA_hash !== packageVLA_hash) return this._messages.checkVLA; // if invalid return the invalid message
2291
+
2292
+ this.state('approved', `license_check:${packageVLA.uid}`);
2293
+ const approved = {
2294
+ id,
2295
+ time: Date.now(),
2296
+ personal: personalVLA_hash,
2297
+ package: packageVLA_hash,
2298
+ };
2299
+
2300
+ this.action('return', `license_check:${packageVLA.uid}`); // set action to return
2301
+ this.state('valid', `license_check:${packageVLA.uid}`); // set the state to valid
2302
+ this.intent('good', `license_check:${packageVLA.uid}`); // set the intent to good
2303
+ return this._stamp(approved, 'license_check', packageVLA.uid);
2304
+ }
2305
+
2306
+ /**************
2307
+ func: hash
2308
+ params:
2309
+ - data: The data packet to create a hash value for.
2310
+ - algo: The hashing algorithm to use for hashing. md5, sha256, or sha512
2311
+
2312
+ describe:
2313
+ The hash algorithm will take a string of text and produce a hash.
2314
+ ***************/
2315
+ hash(data, algo='md5') {
2316
+ const the_hash = createHash(algo);
2317
+ the_hash.update(JSON.stringify(data));
2318
+ return the_hash.digest('base64');
2319
+ }
2320
+
2311
2321
  }
2312
2322
  export default Deva;