@auxiora/behaviors 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +191 -0
  2. package/dist/behavior-manager.d.ts +46 -0
  3. package/dist/behavior-manager.d.ts.map +1 -0
  4. package/dist/behavior-manager.js +240 -0
  5. package/dist/behavior-manager.js.map +1 -0
  6. package/dist/executor.d.ts +44 -0
  7. package/dist/executor.d.ts.map +1 -0
  8. package/dist/executor.js +89 -0
  9. package/dist/executor.js.map +1 -0
  10. package/dist/index.d.ts +8 -0
  11. package/dist/index.d.ts.map +1 -0
  12. package/dist/index.js +7 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/monitor.d.ts +9 -0
  15. package/dist/monitor.d.ts.map +1 -0
  16. package/dist/monitor.js +37 -0
  17. package/dist/monitor.js.map +1 -0
  18. package/dist/scheduler.d.ts +10 -0
  19. package/dist/scheduler.d.ts.map +1 -0
  20. package/dist/scheduler.js +45 -0
  21. package/dist/scheduler.js.map +1 -0
  22. package/dist/store.d.ts +14 -0
  23. package/dist/store.d.ts.map +1 -0
  24. package/dist/store.js +70 -0
  25. package/dist/store.js.map +1 -0
  26. package/dist/types.d.ts +53 -0
  27. package/dist/types.d.ts.map +1 -0
  28. package/dist/types.js +10 -0
  29. package/dist/types.js.map +1 -0
  30. package/package.json +33 -0
  31. package/src/behavior-manager.ts +305 -0
  32. package/src/executor.ts +132 -0
  33. package/src/index.ts +16 -0
  34. package/src/monitor.ts +45 -0
  35. package/src/scheduler.ts +55 -0
  36. package/src/store.ts +83 -0
  37. package/src/types.ts +59 -0
  38. package/tests/behavior-manager.test.ts +162 -0
  39. package/tests/executor.test.ts +128 -0
  40. package/tests/integration.test.ts +148 -0
  41. package/tests/monitor.test.ts +60 -0
  42. package/tests/scheduler.test.ts +58 -0
  43. package/tests/store.test.ts +108 -0
  44. package/tsconfig.json +14 -0
  45. package/tsconfig.tsbuildinfo +1 -0
package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2026 Auxiora Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,46 @@
1
+ import type { Behavior, BehaviorType, BehaviorStatus, BehaviorSchedule, BehaviorPolling, BehaviorDelay, BehaviorChannel } from './types.js';
2
+ import { type ExecutorDeps } from './executor.js';
3
+ export interface CreateBehaviorInput {
4
+ type: BehaviorType;
5
+ action: string;
6
+ schedule?: BehaviorSchedule;
7
+ polling?: BehaviorPolling;
8
+ delay?: BehaviorDelay;
9
+ channel: BehaviorChannel;
10
+ createdBy: string;
11
+ }
12
+ export interface BehaviorManagerOptions {
13
+ storePath: string;
14
+ executorDeps: ExecutorDeps;
15
+ auditFn: (event: string, details: Record<string, unknown>) => Promise<void> | void;
16
+ }
17
+ export declare class BehaviorManager {
18
+ private store;
19
+ private scheduler;
20
+ private monitor;
21
+ private executor;
22
+ private auditFn;
23
+ private executionQueue;
24
+ private oneshotTimers;
25
+ constructor(options: BehaviorManagerOptions);
26
+ start(): Promise<void>;
27
+ stop(): Promise<void>;
28
+ create(input: CreateBehaviorInput): Promise<Behavior>;
29
+ list(filter?: {
30
+ type?: BehaviorType;
31
+ status?: BehaviorStatus;
32
+ }): Promise<Behavior[]>;
33
+ get(id: string): Promise<Behavior | undefined>;
34
+ update(id: string, updates: Partial<Behavior>): Promise<Behavior | undefined>;
35
+ executeNow(id: string): Promise<{
36
+ success: boolean;
37
+ error?: string;
38
+ }>;
39
+ remove(id: string): Promise<boolean>;
40
+ private validate;
41
+ private activate;
42
+ private deactivate;
43
+ private enqueueExecution;
44
+ private executeWithRetry;
45
+ }
46
+ //# sourceMappingURL=behavior-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"behavior-manager.d.ts","sourceRoot":"","sources":["../src/behavior-manager.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,QAAQ,EACR,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,aAAa,EACb,eAAe,EAChB,MAAM,YAAY,CAAC;AAKpB,OAAO,EAAoB,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAIpE,MAAM,WAAW,mBAAmB;IAClC,IAAI,EAAE,YAAY,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,gBAAgB,CAAC;IAC5B,OAAO,CA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AC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IASrE,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAc1C,OAAO,CAAC,QAAQ;IAgChB,OAAO,CAAC,QAAQ;IAyChB,OAAO,CAAC,UAAU;IAUlB,OAAO,CAAC,gBAAgB;YAQV,gBAAgB;CAkD/B"}
@@ -0,0 +1,240 @@
1
+ import { nanoid } from 'nanoid';
2
+ import { getLogger } from '@auxiora/logger';
3
+ import { BEHAVIOR_DEFAULTS } from './types.js';
4
+ import { BehaviorStore } from './store.js';
5
+ import { Scheduler } from './scheduler.js';
6
+ import { MonitorEngine } from './monitor.js';
7
+ import { BehaviorExecutor } from './executor.js';
8
+ const logger = getLogger('behaviors:manager');
9
+ export class BehaviorManager {
10
+ store;
11
+ scheduler;
12
+ monitor;
13
+ executor;
14
+ auditFn;
15
+ executionQueue = Promise.resolve();
16
+ oneshotTimers = new Map();
17
+ constructor(options) {
18
+ this.store = new BehaviorStore(options.storePath);
19
+ this.scheduler = new Scheduler();
20
+ this.monitor = new MonitorEngine();
21
+ this.executor = new BehaviorExecutor(options.executorDeps);
22
+ this.auditFn = options.auditFn;
23
+ }
24
+ async start() {
25
+ const behaviors = await this.store.listActive();
26
+ logger.info('Starting behavior manager', { activeBehaviors: behaviors.length });
27
+ for (const behavior of behaviors) {
28
+ this.activate(behavior);
29
+ }
30
+ }
31
+ async stop() {
32
+ this.scheduler.stopAll();
33
+ this.monitor.stopAll();
34
+ for (const [, timer] of this.oneshotTimers) {
35
+ clearTimeout(timer);
36
+ }
37
+ this.oneshotTimers.clear();
38
+ logger.info('Behavior manager stopped');
39
+ }
40
+ async create(input) {
41
+ this.validate(input);
42
+ const behavior = {
43
+ id: `bh_${nanoid(8)}`,
44
+ type: input.type,
45
+ status: 'active',
46
+ action: input.action,
47
+ schedule: input.schedule,
48
+ polling: input.polling,
49
+ delay: input.delay,
50
+ channel: input.channel,
51
+ createdBy: input.createdBy,
52
+ createdAt: new Date().toISOString(),
53
+ runCount: 0,
54
+ failCount: 0,
55
+ maxFailures: BEHAVIOR_DEFAULTS.maxFailures,
56
+ };
57
+ await this.store.save(behavior);
58
+ this.activate(behavior);
59
+ this.auditFn('behavior.created', {
60
+ behaviorId: behavior.id,
61
+ type: behavior.type,
62
+ });
63
+ logger.info('Created behavior', { id: behavior.id, type: behavior.type, action: behavior.action });
64
+ return behavior;
65
+ }
66
+ async list(filter) {
67
+ const all = await this.store.getAll();
68
+ return all.filter((b) => {
69
+ if (filter?.type && b.type !== filter.type)
70
+ return false;
71
+ if (filter?.status && b.status !== filter.status)
72
+ return false;
73
+ return true;
74
+ });
75
+ }
76
+ async get(id) {
77
+ return this.store.get(id);
78
+ }
79
+ async update(id, updates) {
80
+ const current = await this.store.get(id);
81
+ if (!current)
82
+ return undefined;
83
+ const wasActive = current.status === 'active';
84
+ const updated = await this.store.update(id, updates);
85
+ if (!updated)
86
+ return undefined;
87
+ const isActive = updated.status === 'active';
88
+ // Handle status transitions
89
+ if (wasActive && !isActive) {
90
+ this.deactivate(id);
91
+ }
92
+ else if (!wasActive && isActive) {
93
+ this.activate(updated);
94
+ }
95
+ else if (wasActive && isActive) {
96
+ // Re-activate with new settings
97
+ this.deactivate(id);
98
+ this.activate(updated);
99
+ }
100
+ logger.info('Updated behavior', { id, updates: Object.keys(updates) });
101
+ return updated;
102
+ }
103
+ async executeNow(id) {
104
+ const behavior = await this.store.get(id);
105
+ if (!behavior) {
106
+ throw new Error(`Behavior ${id} not found`);
107
+ }
108
+ const result = await this.executor.execute(behavior);
109
+ return { success: result.success, error: result.error };
110
+ }
111
+ async remove(id) {
112
+ this.deactivate(id);
113
+ const removed = await this.store.remove(id);
114
+ if (removed) {
115
+ this.auditFn('behavior.deleted', {
116
+ behaviorId: id,
117
+ });
118
+ logger.info('Removed behavior', { id });
119
+ }
120
+ return removed;
121
+ }
122
+ validate(input) {
123
+ if (input.type === 'scheduled') {
124
+ if (!input.schedule?.cron) {
125
+ throw new Error('Scheduled behaviors require a cron expression');
126
+ }
127
+ if (!Scheduler.isValidCron(input.schedule.cron)) {
128
+ throw new Error(`Invalid cron expression: ${input.schedule.cron}`);
129
+ }
130
+ }
131
+ if (input.type === 'monitor') {
132
+ if (!input.polling?.intervalMs || !input.polling?.condition) {
133
+ throw new Error('Monitor behaviors require polling interval and condition');
134
+ }
135
+ if (input.polling.intervalMs < BEHAVIOR_DEFAULTS.minPollingIntervalMs) {
136
+ throw new Error(`Polling interval must be at least ${BEHAVIOR_DEFAULTS.minPollingIntervalMs}ms (${BEHAVIOR_DEFAULTS.minPollingIntervalMs / 1000}s)`);
137
+ }
138
+ }
139
+ if (input.type === 'one-shot') {
140
+ if (!input.delay?.fireAt) {
141
+ throw new Error('One-shot behaviors require a fireAt timestamp');
142
+ }
143
+ const fireAt = new Date(input.delay.fireAt);
144
+ if (fireAt.getTime() <= Date.now()) {
145
+ throw new Error('One-shot fireAt must be in the future');
146
+ }
147
+ }
148
+ }
149
+ activate(behavior) {
150
+ switch (behavior.type) {
151
+ case 'scheduled':
152
+ if (behavior.schedule) {
153
+ this.scheduler.schedule(behavior.id, behavior.schedule.cron, () => this.enqueueExecution(behavior.id), behavior.schedule.timezone);
154
+ }
155
+ break;
156
+ case 'monitor':
157
+ if (behavior.polling) {
158
+ this.monitor.start(behavior.id, behavior.polling.intervalMs, () => this.enqueueExecution(behavior.id));
159
+ }
160
+ break;
161
+ case 'one-shot':
162
+ if (behavior.delay) {
163
+ const delayMs = new Date(behavior.delay.fireAt).getTime() - Date.now();
164
+ if (delayMs > 0) {
165
+ const timer = setTimeout(() => {
166
+ this.oneshotTimers.delete(behavior.id);
167
+ this.enqueueExecution(behavior.id);
168
+ }, delayMs);
169
+ this.oneshotTimers.set(behavior.id, timer);
170
+ }
171
+ else {
172
+ // Missed one-shot
173
+ this.store.update(behavior.id, { status: 'missed' });
174
+ }
175
+ }
176
+ break;
177
+ }
178
+ }
179
+ deactivate(id) {
180
+ this.scheduler.stop(id);
181
+ this.monitor.stop(id);
182
+ const timer = this.oneshotTimers.get(id);
183
+ if (timer) {
184
+ clearTimeout(timer);
185
+ this.oneshotTimers.delete(id);
186
+ }
187
+ }
188
+ enqueueExecution(behaviorId) {
189
+ this.executionQueue = this.executionQueue.then(async () => {
190
+ await this.executeWithRetry(behaviorId);
191
+ }).catch((error) => {
192
+ logger.error('Execution queue error', { behaviorId, error: error instanceof Error ? error : new Error(String(error)) });
193
+ });
194
+ }
195
+ async executeWithRetry(behaviorId) {
196
+ const behavior = await this.store.get(behaviorId);
197
+ if (!behavior || behavior.status !== 'active')
198
+ return;
199
+ let result = await this.executor.execute(behavior);
200
+ // Retry once on transient failure
201
+ if (!result.success) {
202
+ logger.info('Retrying behavior execution', { id: behaviorId });
203
+ await new Promise((resolve) => setTimeout(resolve, BEHAVIOR_DEFAULTS.retryDelayMs));
204
+ result = await this.executor.execute(behavior);
205
+ }
206
+ // Update behavior state
207
+ const updates = {
208
+ lastRun: new Date().toISOString(),
209
+ lastResult: result.success ? result.result?.slice(0, 500) : result.error,
210
+ runCount: behavior.runCount + 1,
211
+ };
212
+ if (result.success) {
213
+ updates.failCount = 0;
214
+ // Auto-remove completed one-shots
215
+ if (behavior.type === 'one-shot') {
216
+ updates.status = 'deleted';
217
+ this.deactivate(behaviorId);
218
+ }
219
+ }
220
+ else {
221
+ updates.failCount = behavior.failCount + 1;
222
+ // Auto-pause on repeated failures
223
+ if (updates.failCount >= behavior.maxFailures) {
224
+ updates.status = 'paused';
225
+ this.deactivate(behaviorId);
226
+ logger.warn('Auto-paused behavior due to repeated failures', {
227
+ id: behaviorId,
228
+ failCount: updates.failCount,
229
+ });
230
+ }
231
+ }
232
+ await this.store.update(behaviorId, updates);
233
+ this.auditFn('behavior.executed', {
234
+ behaviorId,
235
+ success: result.success,
236
+ error: result.error,
237
+ });
238
+ }
239
+ }
240
+ //# sourceMappingURL=behavior-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":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AAC;gBACjC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC;gBAC3B,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC;aAAM,CAAC;YACN,OAAO,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS,GAAG,CAAC,CAAC;YAE3C,kCAAkC;YAClC,IAAI,OAAO,CAAC,SAAS,IAAI,QAAQ,CAAC,WAAW,EAAE,CAAC;gBAC9C,OAAO,CAAC,MAAM,GAAG,QAAQ,CAAC;gBAC1B,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;gBAC5B,MAAM,CAAC,IAAI,CAAC,+CAA+C,EAAE;oBAC3D,EAAE,EAAE,UAAU;oBACd,SAAS,EAAE,OAAO,CAAC,SAAS;iBAC7B,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QAED,MAAM,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE7C,IAAI,CAAC,OAAO,CAAC,mBAAmB,EAAE;YAChC,UAAU;YACV,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,KAAK,EAAE,MAAM,CAAC,KAAK;SACpB,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -0,0 +1,44 @@
1
+ import type { Behavior, BehaviorExecution } from './types.js';
2
+ export interface ExecutorDeps {
3
+ getProvider: () => {
4
+ name: string;
5
+ complete: (messages: Array<{
6
+ role: string;
7
+ content: string;
8
+ }>, options?: any) => Promise<{
9
+ content: string;
10
+ usage: {
11
+ inputTokens: number;
12
+ outputTokens: number;
13
+ };
14
+ model: string;
15
+ finishReason: string;
16
+ }>;
17
+ };
18
+ sendToChannel: (channelType: string, channelId: string, message: {
19
+ content: string;
20
+ }) => Promise<{
21
+ success: boolean;
22
+ error?: string;
23
+ }>;
24
+ getSystemPrompt: () => string;
25
+ executeWithTools?: (messages: Array<{
26
+ role: string;
27
+ content: string;
28
+ }>, systemPrompt: string) => Promise<{
29
+ content: string;
30
+ usage: {
31
+ inputTokens: number;
32
+ outputTokens: number;
33
+ };
34
+ }>;
35
+ }
36
+ export declare class BehaviorExecutor {
37
+ private deps;
38
+ constructor(deps: ExecutorDeps);
39
+ execute(behavior: Behavior): Promise<BehaviorExecution>;
40
+ private buildMessages;
41
+ private buildSystemPrompt;
42
+ private getLabel;
43
+ }
44
+ //# sourceMappingURL=executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.d.ts","sourceRoot":"","sources":["../src/executor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAI9D,MAAM,WAAW,YAAY;IAC3B,WAAW,EAAE,MAAM;QACjB,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,CAAC,EAAE,OAAO,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC;YACvF,OAAO,EAAE,MAAM,CAAC;YAChB,KAAK,EAAE;gBAAE,WAAW,EAAE,MAAM,CAAC;gBAAC,YAAY,EAAE,MAAM,CAAA;aAAE,CAAC;YACrD,KAAK,EAAE,MAAM,CAAC;YACd,YAAY,EAAE,MAAM,CAAC;SACtB,CAAC,CAAC;KACJ,CAAC;IACF,aAAa,EAAE,CACb,WAAW,EAAE,MAAM,EACnB,SAAS,EAAE,MAAM,EACjB,OAAO,EAAE;QAAE,OAAO,EAAE,MAAM,CAAA;KAAE,KACzB,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACnD,eAAe,EAAE,MAAM,MAAM,CAAC;IAC9B,gBAAgB,CAAC,EAAE,CACjB,QAAQ,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,EAClD,YAAY,EAAE,MAAM,KACjB,OAAO,CAAC;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE;YAAE,WAAW,EAAE,MAAM,CAAC;YAAC,YAAY,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC,CAAC;CACzF;AAED,qBAAa,gBAAgB;IAC3B,OAAO,CAAC,IAAI,CAAe;gBAEf,IAAI,EAAE,YAAY;IAIxB,OAAO,CAAC,QAAQ,EAAE,QAAQ,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAkE7D,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,iBAAiB;IAMzB,OAAO,CAAC,QAAQ;CAYjB"}
@@ -0,0 +1,89 @@
1
+ import { getLogger } from '@auxiora/logger';
2
+ const logger = getLogger('behaviors:executor');
3
+ export class BehaviorExecutor {
4
+ deps;
5
+ constructor(deps) {
6
+ this.deps = deps;
7
+ }
8
+ async execute(behavior) {
9
+ const startedAt = new Date().toISOString();
10
+ logger.info('Executing behavior', { id: behavior.id, type: behavior.type, action: behavior.action });
11
+ try {
12
+ const provider = this.deps.getProvider();
13
+ const messages = this.buildMessages(behavior);
14
+ const systemPrompt = this.buildSystemPrompt(behavior);
15
+ const result = await provider.complete(messages, { systemPrompt });
16
+ const content = result.content;
17
+ logger.debug('Behavior AI response received', {
18
+ id: behavior.id,
19
+ tokens: result.usage,
20
+ });
21
+ // Deliver to channel
22
+ const label = this.getLabel(behavior);
23
+ const formattedContent = label + '\n' + content;
24
+ const sendResult = await this.deps.sendToChannel(behavior.channel.type, behavior.channel.id, { content: formattedContent });
25
+ if (!sendResult.success) {
26
+ logger.warn('Failed to deliver behavior result', {
27
+ id: behavior.id,
28
+ channelType: behavior.channel.type,
29
+ error: sendResult.error ? new Error(sendResult.error) : undefined,
30
+ });
31
+ return {
32
+ behaviorId: behavior.id,
33
+ startedAt,
34
+ completedAt: new Date().toISOString(),
35
+ success: false,
36
+ error: 'Delivery failed: ' + sendResult.error,
37
+ };
38
+ }
39
+ logger.info('Behavior executed successfully', { id: behavior.id });
40
+ return {
41
+ behaviorId: behavior.id,
42
+ startedAt,
43
+ completedAt: new Date().toISOString(),
44
+ success: true,
45
+ result: content,
46
+ };
47
+ }
48
+ catch (error) {
49
+ const errorMessage = error instanceof Error ? error.message : String(error);
50
+ logger.error('Behavior execution failed', { id: behavior.id, error: new Error(errorMessage) });
51
+ return {
52
+ behaviorId: behavior.id,
53
+ startedAt,
54
+ completedAt: new Date().toISOString(),
55
+ success: false,
56
+ error: errorMessage,
57
+ };
58
+ }
59
+ }
60
+ buildMessages(behavior) {
61
+ if (behavior.type === 'monitor' && behavior.polling?.condition) {
62
+ return [
63
+ {
64
+ role: 'user',
65
+ content: behavior.action + '\n\nIMPORTANT: Only provide a result if this condition is met: ' + behavior.polling.condition + '\nIf the condition is NOT met, respond with exactly: [CONDITION_NOT_MET]',
66
+ },
67
+ ];
68
+ }
69
+ return [{ role: 'user', content: behavior.action }];
70
+ }
71
+ buildSystemPrompt(behavior) {
72
+ const base = this.deps.getSystemPrompt();
73
+ const context = '\n\n---\nThis is an automated proactive behavior execution. Behavior ID: ' + behavior.id + '. Be concise and direct in your response.';
74
+ return base + context;
75
+ }
76
+ getLabel(behavior) {
77
+ switch (behavior.type) {
78
+ case 'scheduled':
79
+ return '**[Scheduled]** _' + behavior.action.slice(0, 50) + '_';
80
+ case 'monitor':
81
+ return '**[Monitor Alert]** _' + (behavior.polling?.condition || behavior.action.slice(0, 50)) + '_';
82
+ case 'one-shot':
83
+ return '**[Reminder]**';
84
+ default:
85
+ return '**[Behavior]**';
86
+ }
87
+ }
88
+ }
89
+ //# sourceMappingURL=executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../src/executor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAG5C,MAAM,MAAM,GAAG,SAAS,CAAC,oBAAoB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AAC;CACF"}
@@ -0,0 +1,8 @@
1
+ export type { Behavior, BehaviorType, BehaviorStatus, BehaviorSchedule, BehaviorPolling, BehaviorDelay, BehaviorChannel, BehaviorExecution, } from './types.js';
2
+ export { BEHAVIOR_DEFAULTS } from './types.js';
3
+ export { BehaviorStore } from './store.js';
4
+ export { Scheduler } from './scheduler.js';
5
+ export { MonitorEngine } from './monitor.js';
6
+ export { BehaviorExecutor, type ExecutorDeps } from './executor.js';
7
+ export { BehaviorManager, type CreateBehaviorInput, type BehaviorManagerOptions } from './behavior-manager.js';
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,QAAQ,EACR,YAAY,EACZ,cAAc,EACd,gBAAgB,EAChB,eAAe,EACf,aAAa,EACb,eAAe,EACf,iBAAiB,GAClB,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,gBAAgB,EAAE,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,KAAK,mBAAmB,EAAE,KAAK,sBAAsB,EAAE,MAAM,uBAAuB,CAAC"}