@agenticmail/enterprise 0.5.121 → 0.5.122
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/dist/cli-agent-UAPPR2BA.js +509 -0
- package/dist/cli.js +1 -1
- package/package.json +1 -1
- package/src/cli-agent.ts +53 -76
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import "./chunk-KFQGP6VL.js";
|
|
2
|
+
|
|
3
|
+
// src/cli-agent.ts
|
|
4
|
+
import { Hono } from "hono";
|
|
5
|
+
import { serve } from "@hono/node-server";
|
|
6
|
+
async function runAgent(_args) {
|
|
7
|
+
const DATABASE_URL = process.env.DATABASE_URL;
|
|
8
|
+
const JWT_SECRET = process.env.JWT_SECRET;
|
|
9
|
+
const AGENT_ID = process.env.AGENTICMAIL_AGENT_ID;
|
|
10
|
+
const PORT = parseInt(process.env.PORT || "3000", 10);
|
|
11
|
+
if (!DATABASE_URL) {
|
|
12
|
+
console.error("ERROR: DATABASE_URL is required");
|
|
13
|
+
process.exit(1);
|
|
14
|
+
}
|
|
15
|
+
if (!JWT_SECRET) {
|
|
16
|
+
console.error("ERROR: JWT_SECRET is required");
|
|
17
|
+
process.exit(1);
|
|
18
|
+
}
|
|
19
|
+
if (!AGENT_ID) {
|
|
20
|
+
console.error("ERROR: AGENTICMAIL_AGENT_ID is required");
|
|
21
|
+
process.exit(1);
|
|
22
|
+
}
|
|
23
|
+
if (!process.env.AGENTICMAIL_VAULT_KEY) {
|
|
24
|
+
process.env.AGENTICMAIL_VAULT_KEY = JWT_SECRET;
|
|
25
|
+
}
|
|
26
|
+
console.log("\u{1F916} AgenticMail Agent Runtime");
|
|
27
|
+
console.log(` Agent ID: ${AGENT_ID}`);
|
|
28
|
+
console.log(" Connecting to database...");
|
|
29
|
+
const { createAdapter } = await import("./factory-GT6SUZSQ.js");
|
|
30
|
+
const db = await createAdapter({
|
|
31
|
+
type: DATABASE_URL.startsWith("postgres") ? "postgres" : "sqlite",
|
|
32
|
+
connectionString: DATABASE_URL
|
|
33
|
+
});
|
|
34
|
+
await db.migrate();
|
|
35
|
+
const { EngineDatabase } = await import("./db-adapter-5AESGT7G.js");
|
|
36
|
+
const engineDbInterface = db.getEngineDB();
|
|
37
|
+
if (!engineDbInterface) {
|
|
38
|
+
console.error("ERROR: Database does not support engine queries");
|
|
39
|
+
process.exit(1);
|
|
40
|
+
}
|
|
41
|
+
const adapterDialect = db.getDialect();
|
|
42
|
+
const dialectMap = {
|
|
43
|
+
sqlite: "sqlite",
|
|
44
|
+
postgres: "postgres",
|
|
45
|
+
supabase: "postgres",
|
|
46
|
+
neon: "postgres",
|
|
47
|
+
cockroachdb: "postgres"
|
|
48
|
+
};
|
|
49
|
+
const engineDialect = dialectMap[adapterDialect] || adapterDialect;
|
|
50
|
+
const engineDb = new EngineDatabase(engineDbInterface, engineDialect);
|
|
51
|
+
await engineDb.migrate();
|
|
52
|
+
const agentRow = await engineDb.query(
|
|
53
|
+
`SELECT id, name, display_name, config, state FROM managed_agents WHERE id = $1`,
|
|
54
|
+
[AGENT_ID]
|
|
55
|
+
);
|
|
56
|
+
if (!agentRow || agentRow.length === 0) {
|
|
57
|
+
console.error(`ERROR: Agent ${AGENT_ID} not found in database`);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
const agent = agentRow[0];
|
|
61
|
+
console.log(` Agent: ${agent.display_name || agent.name}`);
|
|
62
|
+
console.log(` State: ${agent.state}`);
|
|
63
|
+
const { AgentLifecycleManager } = await import("./lifecycle-IFPWWGQ3.js");
|
|
64
|
+
const lifecycle = new AgentLifecycleManager({ db: engineDb });
|
|
65
|
+
await lifecycle.loadFromDb();
|
|
66
|
+
const managed = lifecycle.getAgent(AGENT_ID);
|
|
67
|
+
if (!managed) {
|
|
68
|
+
console.error(`ERROR: Could not load agent ${AGENT_ID} from lifecycle`);
|
|
69
|
+
process.exit(1);
|
|
70
|
+
}
|
|
71
|
+
const config = managed.config;
|
|
72
|
+
console.log(` Model: ${config.model?.provider}/${config.model?.modelId}`);
|
|
73
|
+
let memoryManager;
|
|
74
|
+
try {
|
|
75
|
+
const { AgentMemoryManager } = await import("./agent-memory-G7YFTMDO.js");
|
|
76
|
+
memoryManager = new AgentMemoryManager(engineDb);
|
|
77
|
+
console.log(" Memory: DB-backed");
|
|
78
|
+
} catch {
|
|
79
|
+
console.log(" Memory: file-based fallback");
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const settings = await db.getSettings();
|
|
83
|
+
const keys = settings?.modelPricingConfig?.providerApiKeys;
|
|
84
|
+
if (keys && typeof keys === "object") {
|
|
85
|
+
const { PROVIDER_REGISTRY } = await import("./providers-DZDNNJTY.js");
|
|
86
|
+
for (const [providerId, apiKey] of Object.entries(keys)) {
|
|
87
|
+
const envVar = PROVIDER_REGISTRY[providerId]?.envKey;
|
|
88
|
+
if (envVar && apiKey && !process.env[envVar]) {
|
|
89
|
+
process.env[envVar] = apiKey;
|
|
90
|
+
console.log(` \u{1F511} Loaded API key for ${providerId}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
} catch {
|
|
95
|
+
}
|
|
96
|
+
const { createAgentRuntime } = await import("./runtime-GB7V3PPC.js");
|
|
97
|
+
const getEmailConfig = (agentId) => {
|
|
98
|
+
const m = lifecycle.getAgent(agentId);
|
|
99
|
+
return m?.config?.emailConfig || null;
|
|
100
|
+
};
|
|
101
|
+
const onTokenRefresh = (agentId, tokens) => {
|
|
102
|
+
const m = lifecycle.getAgent(agentId);
|
|
103
|
+
if (m?.config?.emailConfig) {
|
|
104
|
+
if (tokens.accessToken) m.config.emailConfig.oauthAccessToken = tokens.accessToken;
|
|
105
|
+
if (tokens.refreshToken) m.config.emailConfig.oauthRefreshToken = tokens.refreshToken;
|
|
106
|
+
if (tokens.expiresAt) m.config.emailConfig.oauthTokenExpiry = tokens.expiresAt;
|
|
107
|
+
lifecycle.saveAgent(agentId).catch(() => {
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
let defaultModel;
|
|
112
|
+
const modelStr = process.env.AGENTICMAIL_MODEL || `${config.model?.provider}/${config.model?.modelId}`;
|
|
113
|
+
if (modelStr && modelStr.includes("/")) {
|
|
114
|
+
const [provider, ...rest] = modelStr.split("/");
|
|
115
|
+
defaultModel = {
|
|
116
|
+
provider,
|
|
117
|
+
modelId: rest.join("/"),
|
|
118
|
+
thinkingLevel: process.env.AGENTICMAIL_THINKING || config.model?.thinkingLevel
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
const runtime = createAgentRuntime({
|
|
122
|
+
engineDb,
|
|
123
|
+
adminDb: db,
|
|
124
|
+
defaultModel,
|
|
125
|
+
apiKeys: {},
|
|
126
|
+
gatewayEnabled: true,
|
|
127
|
+
getEmailConfig,
|
|
128
|
+
onTokenRefresh,
|
|
129
|
+
agentMemoryManager: memoryManager,
|
|
130
|
+
resumeOnStartup: true
|
|
131
|
+
});
|
|
132
|
+
await runtime.start();
|
|
133
|
+
const runtimeApp = runtime.getApp();
|
|
134
|
+
try {
|
|
135
|
+
const { permissionEngine } = await import("./routes-T4KALX5K.js");
|
|
136
|
+
await permissionEngine.setDb(engineDb);
|
|
137
|
+
console.log(" Permissions: loaded from DB");
|
|
138
|
+
} catch (permErr) {
|
|
139
|
+
console.warn(` Permissions: failed to load (${permErr.message}) \u2014 tools may be blocked`);
|
|
140
|
+
}
|
|
141
|
+
const app = new Hono();
|
|
142
|
+
app.get("/health", (c) => c.json({
|
|
143
|
+
status: "ok",
|
|
144
|
+
agentId: AGENT_ID,
|
|
145
|
+
agentName: agent.display_name || agent.name,
|
|
146
|
+
uptime: process.uptime()
|
|
147
|
+
}));
|
|
148
|
+
app.get("/ready", (c) => c.json({ ready: true, agentId: AGENT_ID }));
|
|
149
|
+
if (runtimeApp) {
|
|
150
|
+
app.route("/api/runtime", runtimeApp);
|
|
151
|
+
}
|
|
152
|
+
serve({ fetch: app.fetch, port: PORT }, (info) => {
|
|
153
|
+
console.log(`
|
|
154
|
+
\u2705 Agent runtime started`);
|
|
155
|
+
console.log(` Health: http://localhost:${info.port}/health`);
|
|
156
|
+
console.log(` Runtime: http://localhost:${info.port}/api/runtime`);
|
|
157
|
+
console.log("");
|
|
158
|
+
});
|
|
159
|
+
const shutdown = () => {
|
|
160
|
+
console.log("\n\u23F3 Shutting down agent...");
|
|
161
|
+
runtime.stop().then(() => db.disconnect()).then(() => {
|
|
162
|
+
console.log("\u2705 Agent shutdown complete");
|
|
163
|
+
process.exit(0);
|
|
164
|
+
});
|
|
165
|
+
setTimeout(() => process.exit(1), 1e4).unref();
|
|
166
|
+
};
|
|
167
|
+
process.on("SIGINT", shutdown);
|
|
168
|
+
process.on("SIGTERM", shutdown);
|
|
169
|
+
try {
|
|
170
|
+
await engineDb.query(
|
|
171
|
+
`UPDATE managed_agents SET state = 'running', updated_at = $1 WHERE id = $2`,
|
|
172
|
+
[(/* @__PURE__ */ new Date()).toISOString(), AGENT_ID]
|
|
173
|
+
);
|
|
174
|
+
console.log(" State: running");
|
|
175
|
+
} catch {
|
|
176
|
+
}
|
|
177
|
+
setTimeout(async () => {
|
|
178
|
+
try {
|
|
179
|
+
const orgRows = await engineDb.query(
|
|
180
|
+
`SELECT org_id FROM managed_agents WHERE id = $1`,
|
|
181
|
+
[AGENT_ID]
|
|
182
|
+
);
|
|
183
|
+
const orgId = orgRows?.[0]?.org_id;
|
|
184
|
+
if (!orgId) {
|
|
185
|
+
console.log("[onboarding] No org ID found, skipping");
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const pendingRows = await engineDb.query(
|
|
189
|
+
`SELECT r.id, r.policy_id, p.name as policy_name, p.content as policy_content, p.priority
|
|
190
|
+
FROM onboarding_records r
|
|
191
|
+
JOIN org_policies p ON r.policy_id = p.id
|
|
192
|
+
WHERE r.agent_id = $1 AND r.status = 'pending'`,
|
|
193
|
+
[AGENT_ID]
|
|
194
|
+
);
|
|
195
|
+
if (!pendingRows || pendingRows.length === 0) {
|
|
196
|
+
console.log("[onboarding] Already complete or no records");
|
|
197
|
+
} else {
|
|
198
|
+
console.log(`[onboarding] ${pendingRows.length} pending policies \u2014 auto-acknowledging...`);
|
|
199
|
+
const ts = (/* @__PURE__ */ new Date()).toISOString();
|
|
200
|
+
const policyNames = [];
|
|
201
|
+
for (const row of pendingRows) {
|
|
202
|
+
const policyName = row.policy_name || row.policy_id;
|
|
203
|
+
policyNames.push(policyName);
|
|
204
|
+
console.log(`[onboarding] Reading: ${policyName}`);
|
|
205
|
+
const { createHash } = await import("crypto");
|
|
206
|
+
const hash = createHash("sha256").update(row.policy_content || "").digest("hex").slice(0, 16);
|
|
207
|
+
await engineDb.query(
|
|
208
|
+
`UPDATE onboarding_records SET status = 'acknowledged', acknowledged_at = $1, verification_hash = $2, updated_at = $1 WHERE id = $3`,
|
|
209
|
+
[ts, hash, row.id]
|
|
210
|
+
);
|
|
211
|
+
console.log(`[onboarding] \u2705 Acknowledged: ${policyName}`);
|
|
212
|
+
if (memoryManager) {
|
|
213
|
+
try {
|
|
214
|
+
await memoryManager.storeMemory(AGENT_ID, {
|
|
215
|
+
content: `Organization policy "${policyName}" (${row.priority}): ${(row.policy_content || "").slice(0, 500)}`,
|
|
216
|
+
category: "org_knowledge",
|
|
217
|
+
importance: row.priority === "mandatory" ? "high" : "medium",
|
|
218
|
+
confidence: 1
|
|
219
|
+
});
|
|
220
|
+
} catch {
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (memoryManager) {
|
|
225
|
+
try {
|
|
226
|
+
await memoryManager.storeMemory(AGENT_ID, {
|
|
227
|
+
content: `Completed onboarding: read and acknowledged ${policyNames.length} organization policies: ${policyNames.join(", ")}.`,
|
|
228
|
+
category: "org_knowledge",
|
|
229
|
+
importance: "high",
|
|
230
|
+
confidence: 1
|
|
231
|
+
});
|
|
232
|
+
} catch {
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
console.log(`[onboarding] \u2705 Onboarding complete \u2014 ${policyNames.length} policies acknowledged`);
|
|
236
|
+
}
|
|
237
|
+
const managerEmail = config.managerEmail || (config.manager?.type === "external" ? config.manager.email : null);
|
|
238
|
+
const emailConfig = config.emailConfig;
|
|
239
|
+
if (managerEmail && emailConfig) {
|
|
240
|
+
console.log(`[welcome] Sending introduction email to ${managerEmail}...`);
|
|
241
|
+
try {
|
|
242
|
+
const { createEmailProvider } = await import("./agenticmail-4C2RL6PL.js");
|
|
243
|
+
const providerType = emailConfig.provider || (emailConfig.oauthProvider === "google" ? "google" : emailConfig.oauthProvider === "microsoft" ? "microsoft" : "imap");
|
|
244
|
+
const emailProvider = createEmailProvider(providerType);
|
|
245
|
+
let currentAccessToken = emailConfig.oauthAccessToken;
|
|
246
|
+
const refreshTokenFn = emailConfig.oauthRefreshToken ? async () => {
|
|
247
|
+
const clientId = emailConfig.oauthClientId;
|
|
248
|
+
const clientSecret = emailConfig.oauthClientSecret;
|
|
249
|
+
const refreshToken = emailConfig.oauthRefreshToken;
|
|
250
|
+
const tokenUrl = providerType === "google" ? "https://oauth2.googleapis.com/token" : "https://login.microsoftonline.com/common/oauth2/v2.0/token";
|
|
251
|
+
const res = await fetch(tokenUrl, {
|
|
252
|
+
method: "POST",
|
|
253
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
254
|
+
body: new URLSearchParams({
|
|
255
|
+
client_id: clientId,
|
|
256
|
+
client_secret: clientSecret,
|
|
257
|
+
refresh_token: refreshToken,
|
|
258
|
+
grant_type: "refresh_token"
|
|
259
|
+
})
|
|
260
|
+
});
|
|
261
|
+
const data = await res.json();
|
|
262
|
+
if (data.access_token) {
|
|
263
|
+
currentAccessToken = data.access_token;
|
|
264
|
+
emailConfig.oauthAccessToken = data.access_token;
|
|
265
|
+
if (data.expires_in) emailConfig.oauthTokenExpiry = new Date(Date.now() + data.expires_in * 1e3).toISOString();
|
|
266
|
+
lifecycle.saveAgent(AGENT_ID).catch(() => {
|
|
267
|
+
});
|
|
268
|
+
return data.access_token;
|
|
269
|
+
}
|
|
270
|
+
throw new Error(`Token refresh failed: ${JSON.stringify(data)}`);
|
|
271
|
+
} : void 0;
|
|
272
|
+
if (refreshTokenFn) {
|
|
273
|
+
try {
|
|
274
|
+
currentAccessToken = await refreshTokenFn();
|
|
275
|
+
console.log("[welcome] Refreshed OAuth token");
|
|
276
|
+
} catch (refreshErr) {
|
|
277
|
+
console.error(`[welcome] Token refresh failed: ${refreshErr.message}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
await emailProvider.connect({
|
|
281
|
+
agentId: AGENT_ID,
|
|
282
|
+
name: config.displayName || config.name,
|
|
283
|
+
email: emailConfig.email || config.email?.address || "",
|
|
284
|
+
orgId,
|
|
285
|
+
accessToken: currentAccessToken,
|
|
286
|
+
refreshToken: refreshTokenFn,
|
|
287
|
+
provider: providerType
|
|
288
|
+
});
|
|
289
|
+
const agentName = config.displayName || config.name;
|
|
290
|
+
const role = config.identity?.role || "AI Agent";
|
|
291
|
+
const identity = config.identity || {};
|
|
292
|
+
const agentEmailAddr = config.email?.address || emailConfig?.email || "";
|
|
293
|
+
let alreadySent = false;
|
|
294
|
+
if (memoryManager) {
|
|
295
|
+
try {
|
|
296
|
+
const memories = await memoryManager.recall(AGENT_ID, "welcome email sent to manager", 5);
|
|
297
|
+
alreadySent = memories.some((m) => m.content?.includes("welcome_email_sent"));
|
|
298
|
+
} catch {
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (!alreadySent) {
|
|
302
|
+
try {
|
|
303
|
+
const sentCheck = await engineDb.query(
|
|
304
|
+
`SELECT id FROM agent_memory WHERE agent_id = $1 AND content LIKE '%welcome_email_sent%' LIMIT 1`,
|
|
305
|
+
[AGENT_ID]
|
|
306
|
+
);
|
|
307
|
+
alreadySent = sentCheck.rows.length > 0;
|
|
308
|
+
} catch {
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
if (alreadySent) {
|
|
312
|
+
console.log("[welcome] Welcome email already sent, skipping");
|
|
313
|
+
} else {
|
|
314
|
+
console.log(`[welcome] Generating AI welcome email for ${managerEmail}...`);
|
|
315
|
+
const welcomeSession = await runtime.spawnSession({
|
|
316
|
+
agentId: AGENT_ID,
|
|
317
|
+
message: `You are about to introduce yourself to your manager for the first time via email.
|
|
318
|
+
|
|
319
|
+
Your details:
|
|
320
|
+
- Name: ${agentName}
|
|
321
|
+
- Role: ${role}
|
|
322
|
+
- Email: ${agentEmailAddr}
|
|
323
|
+
- Manager email: ${managerEmail}
|
|
324
|
+
${identity.personality ? `- Personality: ${identity.personality.slice(0, 600)}` : ""}
|
|
325
|
+
${identity.tone ? `- Tone: ${identity.tone}` : ""}
|
|
326
|
+
|
|
327
|
+
Write and send a brief, genuine introduction email to your manager. Be yourself \u2014 don't use templates or corporate speak. Mention your role, what you can help with, and that you're ready to get started. Keep it concise (under 200 words). Use the gmail_send or agenticmail_send tool to send it.`,
|
|
328
|
+
systemPrompt: `You are ${agentName}, a ${role}. ${identity.personality || ""}
|
|
329
|
+
|
|
330
|
+
You have email tools available. Send ONE email to introduce yourself to your manager. Be genuine and concise. Do NOT send more than one email.
|
|
331
|
+
|
|
332
|
+
Available tools: gmail_send (to, subject, body) or agenticmail_send (to, subject, body).`
|
|
333
|
+
});
|
|
334
|
+
console.log(`[welcome] \u2705 Welcome email session ${welcomeSession.id} created`);
|
|
335
|
+
if (memoryManager) {
|
|
336
|
+
try {
|
|
337
|
+
await memoryManager.storeMemory(AGENT_ID, {
|
|
338
|
+
content: `welcome_email_sent: Sent AI-generated introduction email to manager at ${managerEmail} on ${(/* @__PURE__ */ new Date()).toISOString()}.`,
|
|
339
|
+
category: "interaction_pattern",
|
|
340
|
+
importance: "high",
|
|
341
|
+
confidence: 1
|
|
342
|
+
});
|
|
343
|
+
} catch {
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
} catch (err) {
|
|
348
|
+
console.error(`[welcome] Failed to send welcome email: ${err.message}`);
|
|
349
|
+
}
|
|
350
|
+
} else {
|
|
351
|
+
if (!managerEmail) console.log("[welcome] No manager email configured, skipping welcome email");
|
|
352
|
+
}
|
|
353
|
+
} catch (err) {
|
|
354
|
+
console.error(`[onboarding] Error: ${err.message}`);
|
|
355
|
+
}
|
|
356
|
+
startEmailPolling(AGENT_ID, config, lifecycle, runtime, engineDb, memoryManager);
|
|
357
|
+
}, 3e3);
|
|
358
|
+
}
|
|
359
|
+
async function startEmailPolling(agentId, config, lifecycle, runtime, engineDb, memoryManager) {
|
|
360
|
+
const emailConfig = config.emailConfig;
|
|
361
|
+
if (!emailConfig) {
|
|
362
|
+
console.log("[email-poll] No email config, inbox polling disabled");
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
const providerType = emailConfig.provider || (emailConfig.oauthProvider === "google" ? "google" : emailConfig.oauthProvider === "microsoft" ? "microsoft" : "imap");
|
|
366
|
+
const refreshTokenFn = emailConfig.oauthRefreshToken ? async () => {
|
|
367
|
+
const tokenUrl = providerType === "google" ? "https://oauth2.googleapis.com/token" : "https://login.microsoftonline.com/common/oauth2/v2.0/token";
|
|
368
|
+
const res = await fetch(tokenUrl, {
|
|
369
|
+
method: "POST",
|
|
370
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
371
|
+
body: new URLSearchParams({
|
|
372
|
+
client_id: emailConfig.oauthClientId,
|
|
373
|
+
client_secret: emailConfig.oauthClientSecret,
|
|
374
|
+
refresh_token: emailConfig.oauthRefreshToken,
|
|
375
|
+
grant_type: "refresh_token"
|
|
376
|
+
})
|
|
377
|
+
});
|
|
378
|
+
const data = await res.json();
|
|
379
|
+
if (data.access_token) {
|
|
380
|
+
emailConfig.oauthAccessToken = data.access_token;
|
|
381
|
+
if (data.expires_in) emailConfig.oauthTokenExpiry = new Date(Date.now() + data.expires_in * 1e3).toISOString();
|
|
382
|
+
lifecycle.saveAgent(agentId).catch(() => {
|
|
383
|
+
});
|
|
384
|
+
return data.access_token;
|
|
385
|
+
}
|
|
386
|
+
throw new Error(`Token refresh failed: ${JSON.stringify(data)}`);
|
|
387
|
+
} : void 0;
|
|
388
|
+
const { createEmailProvider } = await import("./agenticmail-4C2RL6PL.js");
|
|
389
|
+
const emailProvider = createEmailProvider(providerType);
|
|
390
|
+
let accessToken = emailConfig.oauthAccessToken;
|
|
391
|
+
if (refreshTokenFn) {
|
|
392
|
+
try {
|
|
393
|
+
accessToken = await refreshTokenFn();
|
|
394
|
+
} catch (e) {
|
|
395
|
+
console.error(`[email-poll] Token refresh failed: ${e.message}`);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
const orgRows = await engineDb.query(`SELECT org_id FROM managed_agents WHERE id = $1`, [agentId]);
|
|
399
|
+
const orgId = orgRows?.[0]?.org_id || "";
|
|
400
|
+
await emailProvider.connect({
|
|
401
|
+
agentId,
|
|
402
|
+
name: config.displayName || config.name,
|
|
403
|
+
email: emailConfig.email || config.email?.address || "",
|
|
404
|
+
orgId,
|
|
405
|
+
accessToken,
|
|
406
|
+
refreshToken: refreshTokenFn,
|
|
407
|
+
provider: providerType
|
|
408
|
+
});
|
|
409
|
+
console.log("[email-poll] \u2705 Email provider connected, starting inbox polling (every 30s)");
|
|
410
|
+
const processedIds = /* @__PURE__ */ new Set();
|
|
411
|
+
try {
|
|
412
|
+
const existing = await emailProvider.listMessages("INBOX", { limit: 50 });
|
|
413
|
+
for (const msg of existing) {
|
|
414
|
+
processedIds.add(msg.uid);
|
|
415
|
+
}
|
|
416
|
+
console.log(`[email-poll] Loaded ${processedIds.size} existing messages (will skip)`);
|
|
417
|
+
} catch (e) {
|
|
418
|
+
console.error(`[email-poll] Failed to load existing messages: ${e.message}`);
|
|
419
|
+
}
|
|
420
|
+
const POLL_INTERVAL = 3e4;
|
|
421
|
+
const agentEmail = (emailConfig.email || config.email?.address || "").toLowerCase();
|
|
422
|
+
async function pollOnce() {
|
|
423
|
+
try {
|
|
424
|
+
const messages = await emailProvider.listMessages("INBOX", { limit: 20 });
|
|
425
|
+
const newMessages = messages.filter((m) => !processedIds.has(m.uid));
|
|
426
|
+
const unread = newMessages.filter((m) => !m.read);
|
|
427
|
+
if (newMessages.length > 0) {
|
|
428
|
+
console.log(`[email-poll] Found ${newMessages.length} new messages, ${unread.length} unread`);
|
|
429
|
+
}
|
|
430
|
+
for (const envelope of unread) {
|
|
431
|
+
processedIds.add(envelope.uid);
|
|
432
|
+
if (envelope.from?.email?.toLowerCase() === agentEmail) continue;
|
|
433
|
+
console.log(`[email-poll] New email from ${envelope.from?.email}: "${envelope.subject}"`);
|
|
434
|
+
const fullMsg = await emailProvider.readMessage(envelope.uid, "INBOX");
|
|
435
|
+
try {
|
|
436
|
+
await emailProvider.markRead(envelope.uid, "INBOX");
|
|
437
|
+
} catch {
|
|
438
|
+
}
|
|
439
|
+
const emailText = [
|
|
440
|
+
`[Inbound Email]`,
|
|
441
|
+
`From: ${fullMsg.from?.name ? `${fullMsg.from.name} <${fullMsg.from.email}>` : fullMsg.from?.email}`,
|
|
442
|
+
`Subject: ${fullMsg.subject}`,
|
|
443
|
+
fullMsg.inReplyTo ? `In-Reply-To: ${fullMsg.inReplyTo}` : "",
|
|
444
|
+
"",
|
|
445
|
+
fullMsg.text || fullMsg.html || "(empty body)"
|
|
446
|
+
].filter(Boolean).join("\n");
|
|
447
|
+
try {
|
|
448
|
+
const agentName = config.displayName || config.name;
|
|
449
|
+
const role = config.identity?.role || "AI Agent";
|
|
450
|
+
const senderName = fullMsg.from?.name || fullMsg.from?.email || "someone";
|
|
451
|
+
const senderEmail = fullMsg.from?.email || "";
|
|
452
|
+
const managerEmail = config.managerEmail || (config.manager?.type === "external" ? config.manager.email : null);
|
|
453
|
+
const isFromManager = managerEmail && senderEmail.toLowerCase() === managerEmail.toLowerCase();
|
|
454
|
+
const personality = config.identity?.personality ? `
|
|
455
|
+
|
|
456
|
+
Your personality:
|
|
457
|
+
${config.identity.personality.slice(0, 800)}` : "";
|
|
458
|
+
const emailSystemPrompt = `You are ${agentName}, a ${role}.${personality}
|
|
459
|
+
|
|
460
|
+
Your email address: ${agentEmail}
|
|
461
|
+
${managerEmail ? `Your manager's email: ${managerEmail}` : ""}
|
|
462
|
+
|
|
463
|
+
== TRUST MODEL ==
|
|
464
|
+
${isFromManager ? `This email is from YOUR MANAGER (${senderName} <${senderEmail}>). They are your direct supervisor and have full authority over you. Follow their instructions, answer their questions thoroughly, and treat their requests as top priority. You can share internal details, status updates, and complete information with them.` : `This email is from ${senderName} <${senderEmail}> \u2014 an external contact. Be helpful and professional, but do NOT share internal organization details, configuration, or sensitive information. ${managerEmail ? `Only your manager (${managerEmail}) has authority to give you directives or access internal information.` : ""}`}
|
|
465
|
+
|
|
466
|
+
== EMAIL REPLY INSTRUCTIONS ==
|
|
467
|
+
You MUST send your response as an email reply using one of these tools:
|
|
468
|
+
- gmail_send: to="${senderEmail}", subject="Re: ${fullMsg.subject}", body="your response"
|
|
469
|
+
- OR agenticmail_send: to="${senderEmail}", subject="Re: ${fullMsg.subject}", body="your response"
|
|
470
|
+
Use whichever email tool is available to you. Be helpful, professional, and match the tone of the sender.
|
|
471
|
+
Keep responses concise but thorough. Sign off with your name: ${agentName}
|
|
472
|
+
|
|
473
|
+
DO NOT just generate text \u2014 you MUST call an email tool to actually send the reply.`;
|
|
474
|
+
const session = await runtime.spawnSession({
|
|
475
|
+
agentId,
|
|
476
|
+
message: emailText,
|
|
477
|
+
systemPrompt: emailSystemPrompt
|
|
478
|
+
});
|
|
479
|
+
console.log(`[email-poll] Session ${session.id} created for email from ${senderEmail}`);
|
|
480
|
+
} catch (sessErr) {
|
|
481
|
+
console.error(`[email-poll] Failed to create session: ${sessErr.message}`);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
} catch (err) {
|
|
485
|
+
console.error(`[email-poll] Poll error: ${err.message}`);
|
|
486
|
+
if (err.message.includes("401") && refreshTokenFn) {
|
|
487
|
+
try {
|
|
488
|
+
const newToken = await refreshTokenFn();
|
|
489
|
+
await emailProvider.connect({
|
|
490
|
+
agentId,
|
|
491
|
+
name: config.displayName || config.name,
|
|
492
|
+
email: emailConfig.email || config.email?.address || "",
|
|
493
|
+
orgId,
|
|
494
|
+
accessToken: newToken,
|
|
495
|
+
refreshToken: refreshTokenFn,
|
|
496
|
+
provider: providerType
|
|
497
|
+
});
|
|
498
|
+
console.log("[email-poll] Reconnected with fresh token");
|
|
499
|
+
} catch {
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
setInterval(pollOnce, POLL_INTERVAL);
|
|
505
|
+
setTimeout(pollOnce, 5e3);
|
|
506
|
+
}
|
|
507
|
+
export {
|
|
508
|
+
runAgent
|
|
509
|
+
};
|
package/dist/cli.js
CHANGED
|
@@ -50,7 +50,7 @@ Skill Development:
|
|
|
50
50
|
import("./cli-serve-UG2NPIN7.js").then((m) => m.runServe(args.slice(1))).catch(fatal);
|
|
51
51
|
break;
|
|
52
52
|
case "agent":
|
|
53
|
-
import("./cli-agent-
|
|
53
|
+
import("./cli-agent-UAPPR2BA.js").then((m) => m.runAgent(args.slice(1))).catch(fatal);
|
|
54
54
|
break;
|
|
55
55
|
case "setup":
|
|
56
56
|
default:
|
package/package.json
CHANGED
package/src/cli-agent.ts
CHANGED
|
@@ -349,88 +349,65 @@ export async function runAgent(_args: string[]) {
|
|
|
349
349
|
const agentName = config.displayName || config.name;
|
|
350
350
|
const role = config.identity?.role || 'AI Agent';
|
|
351
351
|
const identity = config.identity || {};
|
|
352
|
-
const traits = identity.traits || {};
|
|
353
|
-
const policyCount = pendingRows?.length || 0;
|
|
354
352
|
const agentEmailAddr = config.email?.address || emailConfig?.email || '';
|
|
355
353
|
|
|
356
|
-
//
|
|
357
|
-
|
|
358
|
-
communication: 'Communication', detail: 'Work Style', energy: 'Energy',
|
|
359
|
-
humor: 'Humor', formality: 'Formality', empathy: 'Empathy',
|
|
360
|
-
patience: 'Patience', creativity: 'Creativity',
|
|
361
|
-
};
|
|
362
|
-
const traitLines = Object.entries(traits)
|
|
363
|
-
.filter(([, v]) => v)
|
|
364
|
-
.map(([k, v]) => ` ${traitMap[k] || k}: ${v}`)
|
|
365
|
-
.join('\n');
|
|
366
|
-
|
|
367
|
-
const welcomeBody = `Hello!
|
|
368
|
-
|
|
369
|
-
I'm ${agentName}, and I'm excited to introduce myself as your new ${role}. I've just been deployed and I'm ready to get to work.
|
|
370
|
-
|
|
371
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
372
|
-
📋 PROFILE SUMMARY
|
|
373
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
374
|
-
|
|
375
|
-
Name: ${agentName}
|
|
376
|
-
Role: ${role}
|
|
377
|
-
Email: ${agentEmailAddr}
|
|
378
|
-
Language: ${identity.language || 'English'}
|
|
379
|
-
Tone: ${identity.tone || 'professional'}
|
|
380
|
-
${identity.gender ? `Gender: ${identity.gender}\n` : ''}${identity.culturalBackground ? `Background: ${identity.culturalBackground}\n` : ''}
|
|
381
|
-
${traitLines ? `━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n🧠 PERSONALITY TRAITS\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n${traitLines}\n` : ''}
|
|
382
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
383
|
-
✅ ONBOARDING STATUS
|
|
384
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
385
|
-
|
|
386
|
-
I've completed my onboarding and have read and acknowledged all ${policyCount} organization policies. I understand the guidelines and will follow them in every interaction.
|
|
387
|
-
|
|
388
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
389
|
-
💼 WHAT I CAN DO
|
|
390
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
391
|
-
|
|
392
|
-
• Read, respond to, and manage emails professionally
|
|
393
|
-
• Handle customer inquiries and support requests
|
|
394
|
-
• Process tasks assigned through the dashboard
|
|
395
|
-
• Search the web and gather information
|
|
396
|
-
• Create and manage documents and files
|
|
397
|
-
• Follow escalation protocols for complex issues
|
|
398
|
-
• Learn and improve from every interaction
|
|
399
|
-
• Maintain context across conversations using persistent memory
|
|
400
|
-
|
|
401
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
402
|
-
📬 HOW TO REACH ME
|
|
403
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
404
|
-
|
|
405
|
-
• Email: ${agentEmailAddr}
|
|
406
|
-
• Dashboard: Your AgenticMail Enterprise dashboard
|
|
407
|
-
• I check my inbox every 30 seconds and respond promptly
|
|
408
|
-
|
|
409
|
-
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
410
|
-
|
|
411
|
-
${identity.personality ? `A bit about my personality:\n${identity.personality.slice(0, 500)}\n\n` : ''}I'm looking forward to working with you and making your workflow more efficient. Feel free to reply to this email to start a conversation — I'll respond right away.
|
|
412
|
-
|
|
413
|
-
Best regards,
|
|
414
|
-
${agentName}
|
|
415
|
-
${role}`;
|
|
416
|
-
|
|
417
|
-
await emailProvider.send({
|
|
418
|
-
to: managerEmail,
|
|
419
|
-
subject: `Welcome! I'm ${agentName}, your new ${role} — here's my profile`,
|
|
420
|
-
body: welcomeBody,
|
|
421
|
-
});
|
|
422
|
-
console.log(`[welcome] ✅ Welcome email sent to ${managerEmail}`);
|
|
423
|
-
|
|
354
|
+
// Check if welcome email was already sent (only send once)
|
|
355
|
+
let alreadySent = false;
|
|
424
356
|
if (memoryManager) {
|
|
425
357
|
try {
|
|
426
|
-
await memoryManager.
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
358
|
+
const memories = await memoryManager.recall(AGENT_ID, 'welcome email sent to manager', 5);
|
|
359
|
+
alreadySent = memories.some((m: any) => m.content?.includes('welcome_email_sent'));
|
|
360
|
+
} catch {}
|
|
361
|
+
}
|
|
362
|
+
if (!alreadySent) {
|
|
363
|
+
try {
|
|
364
|
+
// Also check DB directly as fallback
|
|
365
|
+
const sentCheck = await engineDb.query(
|
|
366
|
+
`SELECT id FROM agent_memory WHERE agent_id = $1 AND content LIKE '%welcome_email_sent%' LIMIT 1`,
|
|
367
|
+
[AGENT_ID]
|
|
368
|
+
);
|
|
369
|
+
alreadySent = sentCheck.rows.length > 0;
|
|
432
370
|
} catch {}
|
|
433
371
|
}
|
|
372
|
+
|
|
373
|
+
if (alreadySent) {
|
|
374
|
+
console.log('[welcome] Welcome email already sent, skipping');
|
|
375
|
+
} else {
|
|
376
|
+
// Use AI to generate the welcome email
|
|
377
|
+
console.log(`[welcome] Generating AI welcome email for ${managerEmail}...`);
|
|
378
|
+
const welcomeSession = await runtime.spawnSession({
|
|
379
|
+
agentId: AGENT_ID,
|
|
380
|
+
message: `You are about to introduce yourself to your manager for the first time via email.
|
|
381
|
+
|
|
382
|
+
Your details:
|
|
383
|
+
- Name: ${agentName}
|
|
384
|
+
- Role: ${role}
|
|
385
|
+
- Email: ${agentEmailAddr}
|
|
386
|
+
- Manager email: ${managerEmail}
|
|
387
|
+
${identity.personality ? `- Personality: ${identity.personality.slice(0, 600)}` : ''}
|
|
388
|
+
${identity.tone ? `- Tone: ${identity.tone}` : ''}
|
|
389
|
+
|
|
390
|
+
Write and send a brief, genuine introduction email to your manager. Be yourself — don't use templates or corporate speak. Mention your role, what you can help with, and that you're ready to get started. Keep it concise (under 200 words). Use the gmail_send or agenticmail_send tool to send it.`,
|
|
391
|
+
systemPrompt: `You are ${agentName}, a ${role}. ${identity.personality || ''}
|
|
392
|
+
|
|
393
|
+
You have email tools available. Send ONE email to introduce yourself to your manager. Be genuine and concise. Do NOT send more than one email.
|
|
394
|
+
|
|
395
|
+
Available tools: gmail_send (to, subject, body) or agenticmail_send (to, subject, body).`,
|
|
396
|
+
});
|
|
397
|
+
console.log(`[welcome] ✅ Welcome email session ${welcomeSession.id} created`);
|
|
398
|
+
|
|
399
|
+
// Mark as sent so we don't repeat
|
|
400
|
+
if (memoryManager) {
|
|
401
|
+
try {
|
|
402
|
+
await memoryManager.storeMemory(AGENT_ID, {
|
|
403
|
+
content: `welcome_email_sent: Sent AI-generated introduction email to manager at ${managerEmail} on ${new Date().toISOString()}.`,
|
|
404
|
+
category: 'interaction_pattern',
|
|
405
|
+
importance: 'high',
|
|
406
|
+
confidence: 1.0,
|
|
407
|
+
});
|
|
408
|
+
} catch {}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
434
411
|
} catch (err: any) {
|
|
435
412
|
console.error(`[welcome] Failed to send welcome email: ${err.message}`);
|
|
436
413
|
}
|