@nebulaos/core 0.1.1

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 (150) hide show
  1. package/README.md +206 -0
  2. package/dist/__tests__/mocks/mock-provider.d.ts +15 -0
  3. package/dist/__tests__/mocks/mock-provider.js +44 -0
  4. package/dist/agent/Agent.d.ts +96 -0
  5. package/dist/agent/Agent.js +861 -0
  6. package/dist/agent/BaseAgent.d.ts +53 -0
  7. package/dist/agent/BaseAgent.js +126 -0
  8. package/dist/agent/events/events.d.ts +14 -0
  9. package/dist/agent/events/events.js +2 -0
  10. package/dist/agent/events/events.spec.d.ts +1 -0
  11. package/dist/agent/events/events.spec.js +75 -0
  12. package/dist/agent/instruction/index.d.ts +23 -0
  13. package/dist/agent/instruction/index.js +76 -0
  14. package/dist/agent/memory/in-memory.d.ts +24 -0
  15. package/dist/agent/memory/in-memory.js +78 -0
  16. package/dist/agent/memory/index.d.ts +2 -0
  17. package/dist/agent/memory/index.js +18 -0
  18. package/dist/agent/memory/memory.d.ts +43 -0
  19. package/dist/agent/memory/memory.js +7 -0
  20. package/dist/agent/provider/file-parts.spec.d.ts +1 -0
  21. package/dist/agent/provider/file-parts.spec.js +83 -0
  22. package/dist/agent/provider/index.d.ts +130 -0
  23. package/dist/agent/provider/index.js +8 -0
  24. package/dist/agent/skills/index.d.ts +61 -0
  25. package/dist/agent/skills/index.js +9 -0
  26. package/dist/agent/tools/index.d.ts +35 -0
  27. package/dist/agent/tools/index.js +87 -0
  28. package/dist/cost/add-cost.d.ts +10 -0
  29. package/dist/cost/add-cost.js +80 -0
  30. package/dist/cost/add-cost.spec.d.ts +1 -0
  31. package/dist/cost/add-cost.spec.js +36 -0
  32. package/dist/cost/index.d.ts +1 -0
  33. package/dist/cost/index.js +17 -0
  34. package/dist/domain-events/index.d.ts +16 -0
  35. package/dist/domain-events/index.js +38 -0
  36. package/dist/eval/index.d.ts +19 -0
  37. package/dist/eval/index.js +24 -0
  38. package/dist/events/base.d.ts +5 -0
  39. package/dist/events/base.js +2 -0
  40. package/dist/events/schemas.d.ts +3463 -0
  41. package/dist/events/schemas.js +244 -0
  42. package/dist/execution-context/index.d.ts +21 -0
  43. package/dist/execution-context/index.js +17 -0
  44. package/dist/index.cjs +2958 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.d.cts +3425 -0
  47. package/dist/index.d.ts +22 -0
  48. package/dist/index.js +53 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/lgpd/index.d.ts +7 -0
  51. package/dist/lgpd/index.js +21 -0
  52. package/dist/logger/agent-logger.d.ts +16 -0
  53. package/dist/logger/agent-logger.js +110 -0
  54. package/dist/logger/formatters.d.ts +32 -0
  55. package/dist/logger/formatters.js +146 -0
  56. package/dist/logger/index.d.ts +30 -0
  57. package/dist/logger/index.js +88 -0
  58. package/dist/logger/styles.d.ts +46 -0
  59. package/dist/logger/styles.js +53 -0
  60. package/dist/logger/workflow-logger.d.ts +16 -0
  61. package/dist/logger/workflow-logger.js +79 -0
  62. package/dist/multi-agent/agent-as-tool/AgentAsTool.d.ts +16 -0
  63. package/dist/multi-agent/agent-as-tool/AgentAsTool.js +54 -0
  64. package/dist/multi-agent/agent-as-tool/AgentAsTool.spec.d.ts +1 -0
  65. package/dist/multi-agent/agent-as-tool/AgentAsTool.spec.js +76 -0
  66. package/dist/multi-agent/committee-team/CommitteeTeam.d.ts +16 -0
  67. package/dist/multi-agent/committee-team/CommitteeTeam.js +150 -0
  68. package/dist/multi-agent/committee-team/CommitteeTeam.spec.d.ts +1 -0
  69. package/dist/multi-agent/committee-team/CommitteeTeam.spec.js +43 -0
  70. package/dist/multi-agent/handoff-team/HandoffTeam.d.ts +16 -0
  71. package/dist/multi-agent/handoff-team/HandoffTeam.js +185 -0
  72. package/dist/multi-agent/handoff-team/HandoffTeam.spec.d.ts +1 -0
  73. package/dist/multi-agent/handoff-team/HandoffTeam.spec.js +105 -0
  74. package/dist/multi-agent/hierarchical-team/HierarchicalTeam.d.ts +18 -0
  75. package/dist/multi-agent/hierarchical-team/HierarchicalTeam.js +164 -0
  76. package/dist/multi-agent/hierarchical-team/HierarchicalTeam.spec.d.ts +1 -0
  77. package/dist/multi-agent/hierarchical-team/HierarchicalTeam.spec.js +53 -0
  78. package/dist/multi-agent/index.d.ts +10 -0
  79. package/dist/multi-agent/index.js +26 -0
  80. package/dist/multi-agent/pipeline-team/PipelineTeam.d.ts +13 -0
  81. package/dist/multi-agent/pipeline-team/PipelineTeam.js +104 -0
  82. package/dist/multi-agent/pipeline-team/PipelineTeam.spec.d.ts +1 -0
  83. package/dist/multi-agent/pipeline-team/PipelineTeam.spec.js +54 -0
  84. package/dist/multi-agent/router-team/RouterTeam.d.ts +15 -0
  85. package/dist/multi-agent/router-team/RouterTeam.js +153 -0
  86. package/dist/multi-agent/router-team/RouterTeam.spec.d.ts +1 -0
  87. package/dist/multi-agent/router-team/RouterTeam.spec.js +69 -0
  88. package/dist/multi-agent/types/index.d.ts +349 -0
  89. package/dist/multi-agent/types/index.js +79 -0
  90. package/dist/multi-agent/utils/guardrails.d.ts +6 -0
  91. package/dist/multi-agent/utils/guardrails.js +34 -0
  92. package/dist/multi-agent/utils/memory.d.ts +8 -0
  93. package/dist/multi-agent/utils/memory.js +40 -0
  94. package/dist/multi-agent/utils/prompts.d.ts +4 -0
  95. package/dist/multi-agent/utils/prompts.js +25 -0
  96. package/dist/tracing/index.d.ts +89 -0
  97. package/dist/tracing/index.js +188 -0
  98. package/dist/tsup.config.d.ts +2 -0
  99. package/dist/tsup.config.js +11 -0
  100. package/dist/utils/schema-to-zod.d.ts +7 -0
  101. package/dist/utils/schema-to-zod.js +36 -0
  102. package/dist/workflow/Workflow.d.ts +106 -0
  103. package/dist/workflow/Workflow.js +204 -0
  104. package/dist/workflow/adapters.d.ts +61 -0
  105. package/dist/workflow/adapters.js +29 -0
  106. package/dist/workflow/definition/DefinitionBuilder.d.ts +9 -0
  107. package/dist/workflow/definition/DefinitionBuilder.js +91 -0
  108. package/dist/workflow/definition/DefinitionBuilder.spec.d.ts +1 -0
  109. package/dist/workflow/definition/DefinitionBuilder.spec.js +66 -0
  110. package/dist/workflow/definition/DefinitionHasher.d.ts +8 -0
  111. package/dist/workflow/definition/DefinitionHasher.js +11 -0
  112. package/dist/workflow/definition/DefinitionHasher.spec.d.ts +1 -0
  113. package/dist/workflow/definition/DefinitionHasher.spec.js +28 -0
  114. package/dist/workflow/definition/types.d.ts +27 -0
  115. package/dist/workflow/definition/types.js +2 -0
  116. package/dist/workflow/events.d.ts +9 -0
  117. package/dist/workflow/events.js +2 -0
  118. package/dist/workflow/execution/AgentNodeIntegration.spec.d.ts +1 -0
  119. package/dist/workflow/execution/AgentNodeIntegration.spec.js +50 -0
  120. package/dist/workflow/execution/NodeExecutor.d.ts +9 -0
  121. package/dist/workflow/execution/NodeExecutor.js +43 -0
  122. package/dist/workflow/execution/NodeExecutor.spec.d.ts +1 -0
  123. package/dist/workflow/execution/NodeExecutor.spec.js +45 -0
  124. package/dist/workflow/execution/WorkflowEventBus.d.ts +14 -0
  125. package/dist/workflow/execution/WorkflowEventBus.js +42 -0
  126. package/dist/workflow/execution/WorkflowEventBus.spec.d.ts +1 -0
  127. package/dist/workflow/execution/WorkflowEventBus.spec.js +78 -0
  128. package/dist/workflow/execution/WorkflowRunner.d.ts +26 -0
  129. package/dist/workflow/execution/WorkflowRunner.js +212 -0
  130. package/dist/workflow/execution/WorkflowRunner.spec.d.ts +1 -0
  131. package/dist/workflow/execution/WorkflowRunner.spec.js +92 -0
  132. package/dist/workflow/execution/WorkflowTelemetry.d.ts +13 -0
  133. package/dist/workflow/execution/WorkflowTelemetry.js +43 -0
  134. package/dist/workflow/execution/WorkflowTelemetry.spec.d.ts +1 -0
  135. package/dist/workflow/execution/WorkflowTelemetry.spec.js +31 -0
  136. package/dist/workflow/graph/NodeNameRegistry.d.ts +20 -0
  137. package/dist/workflow/graph/NodeNameRegistry.js +21 -0
  138. package/dist/workflow/graph/NodeNameRegistry.spec.d.ts +1 -0
  139. package/dist/workflow/graph/NodeNameRegistry.spec.js +18 -0
  140. package/dist/workflow/graph/WorkflowGraph.d.ts +14 -0
  141. package/dist/workflow/graph/WorkflowGraph.js +23 -0
  142. package/dist/workflow/graph/nodes.d.ts +26 -0
  143. package/dist/workflow/graph/nodes.js +2 -0
  144. package/dist/workflow/queue/WorkflowQueueService.d.ts +22 -0
  145. package/dist/workflow/queue/WorkflowQueueService.js +47 -0
  146. package/dist/workflow/state/WorkflowStateService.d.ts +7 -0
  147. package/dist/workflow/state/WorkflowStateService.js +20 -0
  148. package/dist/workflow/types.d.ts +16 -0
  149. package/dist/workflow/types.js +2 -0
  150. package/package.json +56 -0
@@ -0,0 +1,53 @@
1
+ import { AgentResult } from "./Agent.js";
2
+ import type { AgentEventMap, AgentEventName } from "./events/events.js";
3
+ import { IPIIMasker } from "../lgpd/index.js";
4
+ import type { IMemory } from "./memory/index.js";
5
+ import type { Message } from "./provider/index.js";
6
+ import type { AgentExecuteOptions } from "./Agent.js";
7
+ export type AgentKind = 'agent' | 'team:router' | 'team:handoff' | 'team:hierarchical' | 'team:pipeline' | 'team:committee' | 'team';
8
+ export declare abstract class BaseAgent {
9
+ /**
10
+ * Developer-defined, stable, semantic identifier.
11
+ * This must not change across renames to preserve runtime registry identity.
12
+ */
13
+ readonly id: string;
14
+ readonly name: string;
15
+ /**
16
+ * Identifies the type of agent (agent, router-team, handoff-team, etc.)
17
+ * Useful for UI/registry differentiation.
18
+ */
19
+ readonly kind: AgentKind;
20
+ private emitter;
21
+ protected piiMasker?: IPIIMasker;
22
+ protected memory?: IMemory;
23
+ constructor(id: string, name: string, piiMasker?: IPIIMasker, memory?: IMemory);
24
+ /**
25
+ * Executes the agent. All agent-like implementations (including multi-agent teams)
26
+ * must accept an optional input string and optional execution options.
27
+ */
28
+ abstract execute(input?: string, options?: AgentExecuteOptions): Promise<AgentResult>;
29
+ /**
30
+ * Adds a message to this agent's memory (if configured).
31
+ * Multi-agent teams MUST provide a memory implementation if they expect to be used
32
+ * through standardized execution surfaces (e.g., HTTP gateways).
33
+ */
34
+ addMessage(message: Message): Promise<void>;
35
+ /**
36
+ * Emits a typed event with automatic context injection (trace, timestamp).
37
+ *
38
+ * @param event The event name (e.g., 'agent:execution:start')
39
+ * @param payload The event payload containing 'data' and optional context like 'correlationId'
40
+ */
41
+ protected emit<K extends AgentEventName>(event: K, payload: {
42
+ data: AgentEventMap[K]["data"];
43
+ correlationId?: string;
44
+ executionId?: string;
45
+ }): boolean;
46
+ on<K extends AgentEventName>(event: K, listener: (data: AgentEventMap[K]) => void): this;
47
+ once<K extends AgentEventName>(event: K, listener: (data: AgentEventMap[K]) => void): this;
48
+ off<K extends AgentEventName>(event: K, listener: (data: AgentEventMap[K]) => void): this;
49
+ /**
50
+ * Recursively masks PII in the event payload
51
+ */
52
+ private maskEventData;
53
+ }
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseAgent = void 0;
4
+ const events_1 = require("events");
5
+ const index_js_1 = require("../tracing/index.js");
6
+ const index_js_2 = require("../execution-context/index.js");
7
+ const index_js_3 = require("../domain-events/index.js");
8
+ class BaseAgent {
9
+ /**
10
+ * Developer-defined, stable, semantic identifier.
11
+ * This must not change across renames to preserve runtime registry identity.
12
+ */
13
+ id;
14
+ name;
15
+ /**
16
+ * Identifies the type of agent (agent, router-team, handoff-team, etc.)
17
+ * Useful for UI/registry differentiation.
18
+ */
19
+ kind = 'agent';
20
+ emitter = new events_1.EventEmitter();
21
+ piiMasker;
22
+ memory;
23
+ constructor(id, name, piiMasker, memory) {
24
+ if (!id || !id.trim()) {
25
+ throw new Error("Agent id is required");
26
+ }
27
+ if (!name || !name.trim()) {
28
+ throw new Error("Agent name is required");
29
+ }
30
+ this.id = id.trim();
31
+ this.name = name.trim();
32
+ this.piiMasker = piiMasker;
33
+ this.memory = memory;
34
+ }
35
+ /**
36
+ * Adds a message to this agent's memory (if configured).
37
+ * Multi-agent teams MUST provide a memory implementation if they expect to be used
38
+ * through standardized execution surfaces (e.g., HTTP gateways).
39
+ */
40
+ async addMessage(message) {
41
+ if (!this.memory) {
42
+ throw new Error(`Agent '${this.name}' does not have memory configured`);
43
+ }
44
+ await this.memory.addMessage(message);
45
+ }
46
+ // ==========================================================================
47
+ // Typed Event Emitter Methods
48
+ // ==========================================================================
49
+ /**
50
+ * Emits a typed event with automatic context injection (trace, timestamp).
51
+ *
52
+ * @param event The event name (e.g., 'agent:execution:start')
53
+ * @param payload The event payload containing 'data' and optional context like 'correlationId'
54
+ */
55
+ emit(event, payload) {
56
+ const traceContext = index_js_1.Tracing.getContext();
57
+ const execContext = index_js_2.ExecutionContext.getOrUndefined();
58
+ // Construct the full event object matching the Zod schema
59
+ let fullEvent = {
60
+ type: event,
61
+ timestamp: new Date().toISOString(),
62
+ trace: {
63
+ traceId: traceContext?.traceId || `fallback-${Date.now()}`,
64
+ spanId: traceContext?.spanId || `fallback-${Date.now()}`,
65
+ parentSpanId: traceContext?.parentId,
66
+ },
67
+ correlationId: payload.correlationId,
68
+ executionId: payload.executionId ?? execContext?.executionId,
69
+ rootExecutionId: execContext?.rootExecutionId,
70
+ parentExecutionId: execContext?.parentExecutionId,
71
+ data: payload.data,
72
+ };
73
+ if (this.piiMasker) {
74
+ fullEvent = this.maskEventData(fullEvent);
75
+ }
76
+ // Best-effort export for Cloud materialization.
77
+ index_js_3.DomainEvents.publish(fullEvent);
78
+ return this.emitter.emit(event, fullEvent);
79
+ }
80
+ on(event, listener) {
81
+ this.emitter.on(event, listener);
82
+ return this;
83
+ }
84
+ once(event, listener) {
85
+ this.emitter.once(event, listener);
86
+ return this;
87
+ }
88
+ off(event, listener) {
89
+ this.emitter.off(event, listener);
90
+ return this;
91
+ }
92
+ /**
93
+ * Recursively masks PII in the event payload
94
+ */
95
+ maskEventData(data) {
96
+ if (!this.piiMasker)
97
+ return data;
98
+ if (typeof data === "string") {
99
+ return this.piiMasker.mask(data);
100
+ }
101
+ if (Array.isArray(data)) {
102
+ return data.map(item => this.maskEventData(item));
103
+ }
104
+ if (typeof data === "object" && data !== null) {
105
+ if (data instanceof Date)
106
+ return data;
107
+ if (data instanceof Error) {
108
+ const maskedError = {
109
+ name: data.name,
110
+ message: this.maskEventData(data.message),
111
+ stack: data.stack
112
+ };
113
+ return maskedError;
114
+ }
115
+ const maskedObj = {};
116
+ for (const key in data) {
117
+ if (Object.prototype.hasOwnProperty.call(data, key)) {
118
+ maskedObj[key] = this.maskEventData(data[key]);
119
+ }
120
+ }
121
+ return maskedObj;
122
+ }
123
+ return data;
124
+ }
125
+ }
126
+ exports.BaseAgent = BaseAgent;
@@ -0,0 +1,14 @@
1
+ import { AgentExecutionStart, AgentExecutionEnd, AgentExecutionError, AgentLLMCall, AgentLLMResponse, AgentToolCall, AgentToolResult, ToolExecutionStart, ToolExecutionEnd, ToolExecutionError } from "../../events/schemas.js";
2
+ export type AgentEventMap = {
3
+ "agent:execution:start": AgentExecutionStart;
4
+ "agent:execution:end": AgentExecutionEnd;
5
+ "agent:execution:error": AgentExecutionError;
6
+ "agent:llm:call": AgentLLMCall;
7
+ "agent:llm:response": AgentLLMResponse;
8
+ "agent:tool:call": AgentToolCall;
9
+ "agent:tool:result": AgentToolResult;
10
+ "tool:execution:start": ToolExecutionStart;
11
+ "tool:execution:end": ToolExecutionEnd;
12
+ "tool:execution:error": ToolExecutionError;
13
+ };
14
+ export type AgentEventName = keyof AgentEventMap;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Agent_js_1 = require("../Agent.js");
4
+ const in_memory_js_1 = require("../memory/in-memory.js");
5
+ const mock_provider_js_1 = require("../../__tests__/mocks/mock-provider.js");
6
+ const schemas_js_1 = require("../../events/schemas.js");
7
+ const Workflow_js_1 = require("../../workflow/Workflow.js");
8
+ describe("Event Schema Compliance", () => {
9
+ it("should emit valid agent events matching the schema", async () => {
10
+ const memory = new in_memory_js_1.InMemory();
11
+ const provider = new mock_provider_js_1.MockProvider();
12
+ provider.enqueueResponse({
13
+ content: "Hello world",
14
+ usage: { promptTokens: 10, completionTokens: 5, totalTokens: 15 },
15
+ });
16
+ const agent = new Agent_js_1.Agent({
17
+ id: "schema-test-agent",
18
+ name: "schema-test-agent",
19
+ memory,
20
+ model: provider,
21
+ instructions: "Test instructions",
22
+ });
23
+ const events = [];
24
+ // BaseAgent emits the FULL event object including type
25
+ const collector = (event) => events.push(event);
26
+ // Attach listener to all known event types
27
+ const eventTypes = [
28
+ "agent:execution:start",
29
+ "agent:execution:end",
30
+ "agent:llm:call",
31
+ "agent:llm:response",
32
+ ];
33
+ eventTypes.forEach((type) => agent.on(type, collector));
34
+ await memory.addMessage({ role: "user", content: "Hi" });
35
+ await agent.execute();
36
+ expect(events.length).toBeGreaterThan(0);
37
+ events.forEach((event) => {
38
+ const result = schemas_js_1.NebulaEventSchema.safeParse(event);
39
+ if (!result.success) {
40
+ console.error(`Event validation failed for type '${event.type}':`, JSON.stringify(result.error.format(), null, 2));
41
+ }
42
+ expect(result.success).toBe(true);
43
+ });
44
+ });
45
+ it("should emit valid workflow events matching the schema", async () => {
46
+ const workflow = new Workflow_js_1.Workflow({
47
+ id: "schema-test-workflow",
48
+ name: "Schema Test",
49
+ });
50
+ workflow
51
+ .start("start", async ({ input }) => input)
52
+ .step("step1", async ({ input }) => `${input} processed`)
53
+ .finish("finish", async ({ input }) => input);
54
+ const events = [];
55
+ const collector = (event) => events.push(event);
56
+ const eventTypes = [
57
+ "workflow:run:start",
58
+ "workflow:run:end",
59
+ "workflow:run:error",
60
+ "workflow:node:start",
61
+ "workflow:node:end",
62
+ ];
63
+ // @ts-ignore - dynamic attachment
64
+ eventTypes.forEach((type) => workflow.on(type, collector));
65
+ await workflow.run("start");
66
+ expect(events.length).toBeGreaterThan(0);
67
+ events.forEach((event) => {
68
+ const result = schemas_js_1.NebulaEventSchema.safeParse(event);
69
+ if (!result.success) {
70
+ console.error(`Event validation failed for type '${event.type}':`, JSON.stringify(result.error.format(), null, 2));
71
+ }
72
+ expect(result.success).toBe(true);
73
+ });
74
+ });
75
+ });
@@ -0,0 +1,23 @@
1
+ interface IInstruction {
2
+ resolve(): Promise<string>;
3
+ }
4
+ export type InstructionVariables = Record<string, string | number | boolean>;
5
+ export declare class Instruction implements IInstruction {
6
+ private content;
7
+ private variables;
8
+ constructor(content: string, variables?: InstructionVariables);
9
+ /**
10
+ * Resolve a instrução substituindo as variáveis.
11
+ */
12
+ resolve(): Promise<string>;
13
+ /**
14
+ * Cria uma instrução a partir de um arquivo de texto.
15
+ * Suporta caminhos absolutos ou relativos ao CWD.
16
+ */
17
+ static fromFile(filePath: string, variables?: InstructionVariables): Promise<Instruction>;
18
+ /**
19
+ * Cria uma instrução a partir de uma string direta.
20
+ */
21
+ static create(content: string, variables?: InstructionVariables): Instruction;
22
+ }
23
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.Instruction = void 0;
37
+ const fs = __importStar(require("fs/promises"));
38
+ class Instruction {
39
+ content;
40
+ variables = {};
41
+ constructor(content, variables = {}) {
42
+ this.content = content;
43
+ this.variables = variables;
44
+ }
45
+ /**
46
+ * Resolve a instrução substituindo as variáveis.
47
+ */
48
+ async resolve() {
49
+ let resolved = this.content;
50
+ for (const [key, value] of Object.entries(this.variables)) {
51
+ // Substituição simples de {{key}}
52
+ resolved = resolved.replace(new RegExp(`{{\\s*${key}\\s*}}`, "g"), String(value));
53
+ }
54
+ return resolved;
55
+ }
56
+ /**
57
+ * Cria uma instrução a partir de um arquivo de texto.
58
+ * Suporta caminhos absolutos ou relativos ao CWD.
59
+ */
60
+ static async fromFile(filePath, variables = {}) {
61
+ try {
62
+ const content = await fs.readFile(filePath, "utf-8");
63
+ return new Instruction(content, variables);
64
+ }
65
+ catch (error) {
66
+ throw new Error(`Failed to load instruction from file: ${filePath}. Error: ${error}`);
67
+ }
68
+ }
69
+ /**
70
+ * Cria uma instrução a partir de uma string direta.
71
+ */
72
+ static create(content, variables = {}) {
73
+ return new Instruction(content, variables);
74
+ }
75
+ }
76
+ exports.Instruction = Instruction;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Basic in-memory implementation (default).
3
+ */
4
+ import { IMemory, MemoryExecutionContext } from "./memory.js";
5
+ import { Message } from "../provider/index.js";
6
+ export declare class InMemory implements IMemory {
7
+ private options;
8
+ /** Partitioned message storage: memoryKey -> messages */
9
+ private partitions;
10
+ /** Partitioned state storage: memoryKey -> state map */
11
+ private statePartitions;
12
+ constructor(options?: {
13
+ maxMessages?: number;
14
+ });
15
+ private getPartitionKey;
16
+ private getOrCreatePartition;
17
+ private getOrCreateStateMap;
18
+ addMessage(message: Message, ctx?: MemoryExecutionContext): Promise<void>;
19
+ getMessages(ctx?: MemoryExecutionContext): Promise<Message[]>;
20
+ getState<T = unknown>(key: string, ctx?: MemoryExecutionContext): Promise<T | undefined>;
21
+ setState<T = unknown>(key: string, value: T, ctx?: MemoryExecutionContext): Promise<void>;
22
+ deleteState(key: string, ctx?: MemoryExecutionContext): Promise<void>;
23
+ clear(ctx?: MemoryExecutionContext): Promise<void>;
24
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ /**
3
+ * Basic in-memory implementation (default).
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.InMemory = void 0;
7
+ /** Internal key for default (no context) storage */
8
+ const DEFAULT_KEY = "__default__";
9
+ class InMemory {
10
+ options;
11
+ /** Partitioned message storage: memoryKey -> messages */
12
+ partitions = new Map();
13
+ /** Partitioned state storage: memoryKey -> state map */
14
+ statePartitions = new Map();
15
+ constructor(options = {}) {
16
+ this.options = options;
17
+ }
18
+ getPartitionKey(ctx) {
19
+ return ctx?.memoryKey ?? DEFAULT_KEY;
20
+ }
21
+ getOrCreatePartition(partitionKey) {
22
+ let messages = this.partitions.get(partitionKey);
23
+ if (!messages) {
24
+ messages = [];
25
+ this.partitions.set(partitionKey, messages);
26
+ }
27
+ return messages;
28
+ }
29
+ getOrCreateStateMap(partitionKey) {
30
+ let stateMap = this.statePartitions.get(partitionKey);
31
+ if (!stateMap) {
32
+ stateMap = new Map();
33
+ this.statePartitions.set(partitionKey, stateMap);
34
+ }
35
+ return stateMap;
36
+ }
37
+ async addMessage(message, ctx) {
38
+ const partitionKey = this.getPartitionKey(ctx);
39
+ const messages = this.getOrCreatePartition(partitionKey);
40
+ messages.push(message);
41
+ // Truncate if needed (keep latest N messages)
42
+ if (this.options.maxMessages && messages.length > this.options.maxMessages) {
43
+ const systemMessage = messages.find((m) => m.role === "system");
44
+ const removeCount = messages.length - this.options.maxMessages;
45
+ messages.splice(0, removeCount);
46
+ // Restore system message if lost
47
+ if (systemMessage && !messages.includes(systemMessage)) {
48
+ messages.unshift(systemMessage);
49
+ }
50
+ }
51
+ }
52
+ async getMessages(ctx) {
53
+ const partitionKey = this.getPartitionKey(ctx);
54
+ const messages = this.partitions.get(partitionKey);
55
+ return messages ? [...messages] : [];
56
+ }
57
+ async getState(key, ctx) {
58
+ const partitionKey = this.getPartitionKey(ctx);
59
+ const stateMap = this.statePartitions.get(partitionKey);
60
+ return stateMap?.get(key);
61
+ }
62
+ async setState(key, value, ctx) {
63
+ const partitionKey = this.getPartitionKey(ctx);
64
+ const stateMap = this.getOrCreateStateMap(partitionKey);
65
+ stateMap.set(key, value);
66
+ }
67
+ async deleteState(key, ctx) {
68
+ const partitionKey = this.getPartitionKey(ctx);
69
+ const stateMap = this.statePartitions.get(partitionKey);
70
+ stateMap?.delete(key);
71
+ }
72
+ async clear(ctx) {
73
+ const partitionKey = this.getPartitionKey(ctx);
74
+ this.partitions.delete(partitionKey);
75
+ this.statePartitions.delete(partitionKey);
76
+ }
77
+ }
78
+ exports.InMemory = InMemory;
@@ -0,0 +1,2 @@
1
+ export * from "./memory.js";
2
+ export * from "./in-memory.js";
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./memory.js"), exports);
18
+ __exportStar(require("./in-memory.js"), exports);
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Memory Interface
3
+ *
4
+ * Define como o Agente armazena e recupera o histórico de mensagens.
5
+ */
6
+ import { Message } from "../provider/index.js";
7
+ /**
8
+ * Execution context for memory partitioning.
9
+ * When provided, memory operations are scoped to the given memoryKey.
10
+ */
11
+ export interface MemoryExecutionContext {
12
+ /** Required when context is used. Partitions memory by this key. */
13
+ memoryKey: string;
14
+ /** Extensible for future metadata. */
15
+ [key: string]: unknown;
16
+ }
17
+ export interface IMemory {
18
+ /**
19
+ * Adds a message to the conversation history.
20
+ * @param message The message to add
21
+ * @param ctx Optional execution context for memory partitioning
22
+ */
23
+ addMessage(message: Message, ctx?: MemoryExecutionContext): Promise<void>;
24
+ /**
25
+ * Returns the full conversation history.
26
+ * @param ctx Optional execution context for memory partitioning
27
+ */
28
+ getMessages(ctx?: MemoryExecutionContext): Promise<Message[]>;
29
+ /**
30
+ * Clears the conversation history.
31
+ * @param ctx Optional execution context for memory partitioning
32
+ */
33
+ clear(ctx?: MemoryExecutionContext): Promise<void>;
34
+ /**
35
+ * Optional key/value state storage for agents/teams.
36
+ * Useful for persisting lightweight orchestration state (e.g., handoff current agent).
37
+ * @param key State key
38
+ * @param ctx Optional execution context for memory partitioning
39
+ */
40
+ getState?<T = unknown>(key: string, ctx?: MemoryExecutionContext): Promise<T | undefined>;
41
+ setState?<T = unknown>(key: string, value: T, ctx?: MemoryExecutionContext): Promise<void>;
42
+ deleteState?(key: string, ctx?: MemoryExecutionContext): Promise<void>;
43
+ }
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ /**
3
+ * Memory Interface
4
+ *
5
+ * Define como o Agente armazena e recupera o histórico de mensagens.
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const Agent_js_1 = require("../Agent.js");
4
+ const index_js_1 = require("../memory/index.js");
5
+ class NoopLogger {
6
+ debug() { }
7
+ info() { }
8
+ warn() { }
9
+ error() { }
10
+ }
11
+ class StubModel {
12
+ providerName = "stub";
13
+ modelName = "stub-model";
14
+ capabilities;
15
+ constructor(caps) {
16
+ this.capabilities = caps;
17
+ }
18
+ async generate(_messages, _tools) {
19
+ return { content: "ok" };
20
+ }
21
+ async *generateStream(_messages, _tools) {
22
+ yield { type: "content_delta", delta: "ok" };
23
+ yield { type: "finish", reason: "stop" };
24
+ }
25
+ }
26
+ describe("File parts validation", () => {
27
+ it("throws when model does not declare file capabilities", async () => {
28
+ const agent = new Agent_js_1.Agent({
29
+ id: "test",
30
+ name: "test",
31
+ model: new StubModel(undefined),
32
+ memory: new index_js_1.InMemory({ maxMessages: 50 }),
33
+ instructions: "test",
34
+ logger: new NoopLogger(),
35
+ });
36
+ await agent.addMessage({
37
+ role: "user",
38
+ content: [
39
+ { type: "text", text: "analyze" },
40
+ {
41
+ type: "file",
42
+ file: {
43
+ name: "a.pdf",
44
+ mimeType: "application/pdf",
45
+ source: { type: "url", url: "https://example.com/a.pdf", sizeBytes: 100 },
46
+ },
47
+ },
48
+ ],
49
+ });
50
+ await expect(agent.execute()).rejects.toThrow("Model does not support file inputs");
51
+ });
52
+ it("throws when base64 file exceeds 10MB", async () => {
53
+ const agent = new Agent_js_1.Agent({
54
+ id: "test",
55
+ name: "test",
56
+ model: new StubModel({
57
+ inputFiles: { mimeTypes: "any", sources: ["base64", "url"] },
58
+ }),
59
+ memory: new index_js_1.InMemory({ maxMessages: 50 }),
60
+ instructions: "test",
61
+ logger: new NoopLogger(),
62
+ });
63
+ // Create base64 string slightly above 10MB (decoded)
64
+ const tenMbPlusOne = (10 * 1024 * 1024) + 1;
65
+ const base64Len = Math.ceil(tenMbPlusOne / 3) * 4; // inverse of decoded length approximation
66
+ const bigBase64 = "A".repeat(base64Len);
67
+ await agent.addMessage({
68
+ role: "user",
69
+ content: [
70
+ { type: "text", text: "analyze" },
71
+ {
72
+ type: "file",
73
+ file: {
74
+ name: "big.bin",
75
+ mimeType: "application/octet-stream",
76
+ source: { type: "base64", base64: bigBase64 },
77
+ },
78
+ },
79
+ ],
80
+ });
81
+ await expect(agent.execute()).rejects.toThrow("exceeds max size");
82
+ });
83
+ });