@mosadd/mcp 3.0.0-alpha.32 → 3.0.0-alpha.33

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 (52) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +11 -11
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-KX34DDJB.js → chunk-IWLN5EO5.js} +614 -134
  5. package/dist/index.js +1 -1
  6. package/package.json +15 -15
  7. package/src/__tests__/golden-path.test.ts +137 -137
  8. package/src/__tests__/integration.test.ts +179 -179
  9. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  10. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  11. package/src/__tests__/mtalk.test.ts +122 -122
  12. package/src/__tests__/presence.test.ts +141 -0
  13. package/src/__tests__/server.test.ts +71 -71
  14. package/src/__tests__/tool-count-consistency.test.ts +121 -1
  15. package/src/bin/login.ts +138 -138
  16. package/src/bin/mcp.ts +145 -145
  17. package/src/config.ts +66 -66
  18. package/src/crypto/mdm-session.ts +502 -502
  19. package/src/index.ts +19 -19
  20. package/src/observability/sentry.ts +79 -79
  21. package/src/providers/blob-upload.ts +116 -116
  22. package/src/providers/memory-voice.ts +79 -79
  23. package/src/providers/supabase-dm.ts +122 -122
  24. package/src/providers/supabase-voice.ts +91 -91
  25. package/src/providers/supabase.ts +148 -148
  26. package/src/tools/actions.ts +162 -162
  27. package/src/tools/attachments.ts +268 -268
  28. package/src/tools/capabilities.ts +68 -68
  29. package/src/tools/embed.ts +108 -108
  30. package/src/tools/index.ts +173 -104
  31. package/src/tools/knowledge-graph.ts +178 -0
  32. package/src/tools/knowledge.ts +319 -191
  33. package/src/tools/mail-agentbox.ts +147 -0
  34. package/src/tools/mail-aliases.ts +25 -25
  35. package/src/tools/mail-provenance.ts +135 -135
  36. package/src/tools/mail.ts +381 -381
  37. package/src/tools/mdm.ts +476 -479
  38. package/src/tools/mirc-edge.ts +190 -190
  39. package/src/tools/mirc-members.ts +2 -2
  40. package/src/tools/mirc-messages.ts +155 -155
  41. package/src/tools/mirc.ts +2 -2
  42. package/src/tools/mroom-messages.ts +142 -142
  43. package/src/tools/mroom.ts +221 -221
  44. package/src/tools/mtalk.ts +121 -121
  45. package/src/tools/murl.ts +4 -2
  46. package/src/tools/presence.ts +208 -0
  47. package/src/types.ts +94 -94
  48. package/src/voice/floor.ts +132 -132
  49. package/LICENSE +0 -201
  50. package/dist/bin/login.d.ts +0 -13
  51. package/dist/bin/mcp.d.ts +0 -1
  52. package/dist/index.d.ts +0 -266
@@ -0,0 +1,147 @@
1
+ /**
2
+ * mAYL agent inboxes — disposable, two-way mailboxes an agent can mint for itself.
3
+ *
4
+ * Backed by the mosADD `mayl-agentbox` Edge Function (owner-scoped CRUD over
5
+ * public.mayl_agent_boxes) + the mp0st-inbound-webhook receive path. A box is a REAL
6
+ * address `agent-<hex>@mosadd.com` that can both SEND (via mAYL_send's from-selector)
7
+ * and — since 2026-08-06 — RECEIVE (inbound mail resolves the box → the owner account).
8
+ *
9
+ * This is the mosADD answer to AgentMail's `create_inbox`: the agent gets its own real
10
+ * inbox on demand, but inside an E2EE messenger where the agent is already a first-class
11
+ * contact and every send carries cryptographic provenance — not a bare third-party API.
12
+ *
13
+ * Auth is identical to every other mAYL tool: invokeFunction sends the caller's
14
+ * `Authorization: Bearer <userJwt>`, which mayl-agentbox validates via requireUser
15
+ * (auth.uid() owner-scoping). No new auth surface.
16
+ */
17
+
18
+ import { z } from "zod";
19
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
20
+ import { invokeFunction, readSupabaseEnv } from "../providers/supabase.js";
21
+
22
+ // ---- Schemas ----
23
+
24
+ const BoxId = z.string().min(1).describe("Agent-box id (UUID) from mAYL_agentbox_provision or mAYL_agentbox_list.");
25
+
26
+ const agentbox_provision_input = z.object({
27
+ display_name: z
28
+ .string()
29
+ .max(120)
30
+ .optional()
31
+ .describe("Optional human label for the box (e.g. 'signup catcher'). Max 120 chars."),
32
+ agent_id: z
33
+ .string()
34
+ .optional()
35
+ .describe("Optional identity id to attribute the box to — must be an agent identity you own."),
36
+ kind: z
37
+ .enum(["ephemeral", "persistent"])
38
+ .optional()
39
+ .describe("'ephemeral' (default) auto-expires + is reaped; 'persistent' never expires."),
40
+ ttl_seconds: z
41
+ .number()
42
+ .int()
43
+ .positive()
44
+ .max(86_400)
45
+ .optional()
46
+ .describe("Lifetime for an ephemeral box, in seconds. Default 600 (10 min). Max 86400 (24 h). Ignored for persistent."),
47
+ });
48
+
49
+ const agentbox_list_input = z.object({});
50
+
51
+ const agentbox_release_input = z.object({ id: BoxId });
52
+
53
+ const agentbox_extend_input = z.object({
54
+ id: BoxId,
55
+ ttl_seconds: z
56
+ .number()
57
+ .int()
58
+ .positive()
59
+ .max(86_400)
60
+ .optional()
61
+ .describe("New lifetime from NOW, in seconds. Default 600 (10 min). Max 86400 (24 h). Ephemeral boxes only."),
62
+ });
63
+
64
+ // ---- Handlers ----
65
+
66
+ async function agentbox_provision(
67
+ input: z.infer<typeof agentbox_provision_input>,
68
+ ctx: MosaddToolContext,
69
+ ): Promise<Record<string, unknown>> {
70
+ readSupabaseEnv();
71
+ ctx.log("debug", "mAYL_agentbox_provision invoking mayl-agentbox", { kind: input.kind ?? "ephemeral" });
72
+ return await invokeFunction("mayl-agentbox", {
73
+ action: "create",
74
+ display_name: input.display_name ?? null,
75
+ agent_id: input.agent_id ?? null,
76
+ kind: input.kind ?? "ephemeral",
77
+ ttl_seconds: input.ttl_seconds ?? null,
78
+ });
79
+ }
80
+
81
+ async function agentbox_list(
82
+ _input: z.infer<typeof agentbox_list_input>,
83
+ ctx: MosaddToolContext,
84
+ ): Promise<Record<string, unknown>> {
85
+ readSupabaseEnv();
86
+ ctx.log("debug", "mAYL_agentbox_list invoking mayl-agentbox", {});
87
+ return await invokeFunction("mayl-agentbox", { action: "list" });
88
+ }
89
+
90
+ async function agentbox_release(
91
+ input: z.infer<typeof agentbox_release_input>,
92
+ ctx: MosaddToolContext,
93
+ ): Promise<Record<string, unknown>> {
94
+ readSupabaseEnv();
95
+ ctx.log("debug", "mAYL_agentbox_release invoking mayl-agentbox", { id: input.id });
96
+ return await invokeFunction("mayl-agentbox", { action: "release", id: input.id });
97
+ }
98
+
99
+ async function agentbox_extend(
100
+ input: z.infer<typeof agentbox_extend_input>,
101
+ ctx: MosaddToolContext,
102
+ ): Promise<Record<string, unknown>> {
103
+ readSupabaseEnv();
104
+ ctx.log("debug", "mAYL_agentbox_extend invoking mayl-agentbox", { id: input.id });
105
+ return await invokeFunction("mayl-agentbox", {
106
+ action: "extend",
107
+ id: input.id,
108
+ ttl_seconds: input.ttl_seconds ?? null,
109
+ });
110
+ }
111
+
112
+ // ---- Registration ----
113
+
114
+ export const mailAgentboxTools: MosaddTool[] = [
115
+ {
116
+ name: "mAYL_agentbox_provision",
117
+ requires: "network",
118
+ description:
119
+ "Mint the agent its OWN real, disposable email inbox at agent-<hex>@mosadd.com that can SEND and RECEIVE. Default ephemeral with a 10-minute TTL (auto-expires + is reaped); pass kind:'persistent' for a permanent box, or ttl_seconds (max 86400) for a custom lifetime. Optional display_name + agent_id. Returns the box {id, address, expires_at}. Use the address to catch signup/verification codes or replies, then mAYL_list (filter by the box address) + mAYL_view to read what arrived. Owner-scoped; max 25 active boxes per account.",
120
+ inputSchema: agentbox_provision_input,
121
+ handler: agentbox_provision as MosaddTool["handler"],
122
+ },
123
+ {
124
+ name: "mAYL_agentbox_list",
125
+ requires: "network",
126
+ description:
127
+ "List your active agent inboxes (address, display_name, kind, agent_id, expires_at), newest first. Owner-scoped.",
128
+ inputSchema: agentbox_list_input,
129
+ handler: agentbox_list as MosaddTool["handler"],
130
+ },
131
+ {
132
+ name: "mAYL_agentbox_release",
133
+ requires: "network",
134
+ description:
135
+ "Release (delete) one of your agent inboxes by id — frees the address immediately so it stops receiving. Owner-scoped.",
136
+ inputSchema: agentbox_release_input,
137
+ handler: agentbox_release as MosaddTool["handler"],
138
+ },
139
+ {
140
+ name: "mAYL_agentbox_extend",
141
+ requires: "network",
142
+ description:
143
+ "Extend an EPHEMERAL agent inbox's lifetime by id (ttl_seconds counted from NOW, max 24 h). Persistent boxes never expire and cannot be extended. Owner-scoped.",
144
+ inputSchema: agentbox_extend_input,
145
+ handler: agentbox_extend as MosaddTool["handler"],
146
+ },
147
+ ];
@@ -1,25 +1,25 @@
1
- // =============================================================================
2
- // mail-aliases.ts — back-compat mp0st_* aliases for mAYL_* tools
3
- // =============================================================================
4
- // The mosADD re-arch (2026-06-27) renamed the email module from `mp0st` to
5
- // `mAYL` (LINEAR-3938 / 3985). The canonical tool names are mAYL_* — see
6
- // `tools/mail.ts`. THIS module exposes back-compat aliases so any agent already
7
- // wired to mp0st_send / mp0st_view / etc. KEEPS WORKING in this release.
8
- //
9
- // Rule: never drop an alias in the release that adds its replacement — live
10
- // agents would 404. mp0st_* aliases stay through alpha.25 and the next minor;
11
- // flag for removal goes into the a later release's notes.
12
- // =============================================================================
13
-
14
- import type { MosaddTool } from "../types.js";
15
- import { mailTools } from "./mail.js";
16
-
17
- /** Same handlers/schemas as `mailTools`, but registered under the legacy mp0st_* names. */
18
- export const mailAliasTools: MosaddTool[] = mailTools.map((tool) => ({
19
- ...tool,
20
- name: tool.name.replace(/^mAYL_/, "mp0st_"),
21
- description:
22
- `[DEPRECATED — use ${tool.name} instead. mp0st_* aliases stay through alpha.25 ` +
23
- `for back-compat; will be removed in a later alpha.] ` +
24
- tool.description,
25
- }));
1
+ // =============================================================================
2
+ // mail-aliases.ts — back-compat mp0st_* aliases for mAYL_* tools
3
+ // =============================================================================
4
+ // The mosADD re-arch (2026-06-27) renamed the email module from `mp0st` to
5
+ // `mAYL` (LINEAR-3938 / 3985). The canonical tool names are mAYL_* — see
6
+ // `tools/mail.ts`. THIS module exposes back-compat aliases so any agent already
7
+ // wired to mp0st_send / mp0st_view / etc. KEEPS WORKING in this release.
8
+ //
9
+ // Rule: never drop an alias in the release that adds its replacement — live
10
+ // agents would 404. mp0st_* aliases stay through alpha.25 and the next minor;
11
+ // flag for removal goes into the a later release's notes.
12
+ // =============================================================================
13
+
14
+ import type { MosaddTool } from "../types.js";
15
+ import { mailTools } from "./mail.js";
16
+
17
+ /** Same handlers/schemas as `mailTools`, but registered under the legacy mp0st_* names. */
18
+ export const mailAliasTools: MosaddTool[] = mailTools.map((tool) => ({
19
+ ...tool,
20
+ name: tool.name.replace(/^mAYL_/, "mp0st_"),
21
+ description:
22
+ `[DEPRECATED — use ${tool.name} instead. mp0st_* aliases stay through alpha.25 ` +
23
+ `for back-compat; will be removed in a later alpha.] ` +
24
+ tool.description,
25
+ }));
@@ -1,135 +1,135 @@
1
- /**
2
- * mp0st provenance — agent-attributed email send.
3
- *
4
- * The plain `mp0st_send` (mail.ts) sends as the USER. When an AGENT sends mail on
5
- * the user's behalf, the recipient (and the audit trail) should be able to tell
6
- * it was agent-originated. Per the Lane A contract, `mp0st-send`, when called
7
- * with a HUB-CLAIM JWT, stamps the row with:
8
- * sent_by = 'agent', sent_by_agent_id, sent_by_task_id
9
- *
10
- * This tool mints/forwards that hub-claim JWT and sets the provenance fields.
11
- *
12
- * AUTH MODEL (differs from the rest of mp0st):
13
- * - mp0st_send uses the user's Supabase session JWT (via invokeFunction).
14
- * - mp0st_send_as_agent presents a HUB-CLAIM JWT (hub key → claim exchange) so
15
- * mp0st-send can attribute the send to the agent/task.
16
- *
17
- * STATUS: scaffold. The hub-claim exchange endpoint is assumed (TODO Lane A —
18
- * confirm the exact route + claim shape). Falls back to the user session JWT if
19
- * no hub key is configured, with provenance fields passed through for the EF to
20
- * honor once deployed.
21
- */
22
-
23
- import { z } from "zod";
24
- import type { MosaddTool, MosaddToolContext } from "../types.js";
25
-
26
- const DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
27
-
28
- function supabaseUrl(): string {
29
- return (
30
- process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ??
31
- process.env.SUPABASE_URL?.replace(/\/$/, "") ??
32
- DEFAULT_SUPABASE_URL
33
- );
34
- }
35
-
36
- function hubKey(): string | null {
37
- return process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? null;
38
- }
39
-
40
- const EmailAddress = z.string().email().max(254);
41
-
42
- const mp0st_send_as_agent_input = z.object({
43
- to: z.union([EmailAddress, z.array(EmailAddress).min(1).max(50)]),
44
- subject: z.string().min(1).max(998),
45
- body_text: z.string().max(1_048_576).optional(),
46
- body_html: z.string().max(1_048_576).optional(),
47
- cc: z.array(EmailAddress).max(50).optional(),
48
- bcc: z.array(EmailAddress).max(50).optional(),
49
- reply_to: EmailAddress.optional(),
50
- tracking: z.boolean().optional(),
51
- agent_id: z
52
- .string()
53
- .min(1)
54
- .max(120)
55
- .describe("Stable id of the agent doing the send. Stamped as sent_by_agent_id for provenance."),
56
- task_id: z
57
- .string()
58
- .min(1)
59
- .max(120)
60
- .optional()
61
- .describe("Optional id of the task/run this send belongs to. Stamped as sent_by_task_id."),
62
- });
63
-
64
- /**
65
- * Exchange the hub key for an HS256 hub-claim JWT that authorizes agent-attributed
66
- * mail sends. The `mp0st-send` EF verifies this token with HUB_JWT_SECRET and reads
67
- * `agent_id` + `task_id` from its claims authoritatively (body fields are NOT trusted
68
- * for provenance). LINEAR-3991.
69
- */
70
- async function mintHubClaim(agentId: string, taskId?: string): Promise<string> {
71
- const key = hubKey();
72
- if (!key) {
73
- throw new Error("mAYL_send_as_agent needs MOSADD_API_KEY (hub key) to mint a provenance claim.");
74
- }
75
- const r = await fetch(`${supabaseUrl()}/functions/v1/hub-claim-mint`, {
76
- method: "POST",
77
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
78
- body: JSON.stringify({ agent_id: agentId, task_id: taskId ?? null }),
79
- });
80
- if (!r.ok) {
81
- const b = await r.text().catch(() => "");
82
- throw new Error(`hub-claim-mint ${r.status}: ${b.slice(0, 200)}`);
83
- }
84
- const data = (await r.json()) as { access_token?: string };
85
- if (!data?.access_token) throw new Error("hub-claim-mint: no access_token in response");
86
- return data.access_token;
87
- }
88
-
89
- async function mAYL_send_as_agent(
90
- input: z.infer<typeof mp0st_send_as_agent_input>,
91
- ctx: MosaddToolContext,
92
- ): Promise<{ message_id: string; status: string; is_internal: boolean; sent_by: "agent" }> {
93
- if (!input.body_text && !input.body_html) {
94
- throw new Error("mAYL_send_as_agent requires at least one of body_text or body_html.");
95
- }
96
-
97
- // Mint the hub-claim JWT and present it directly to mp0st-send (NOT the user
98
- // session client) so the EF attributes the row to the agent. mp0st-send verifies
99
- // the HS256 signature with HUB_JWT_SECRET and stamps sent_by_agent_id /
100
- // sent_by_task_id from the verified claims — body fields are NOT trusted for
101
- // provenance.
102
- const claim = await mintHubClaim(input.agent_id, input.task_id);
103
- ctx.log("debug", "mAYL_send_as_agent invoking mp0st-send with hub-claim", { agent_id: input.agent_id });
104
-
105
- const { agent_id: _ai, task_id: _ti, ...mailFields } = input;
106
- const r = await fetch(`${supabaseUrl()}/functions/v1/mp0st-send`, {
107
- method: "POST",
108
- headers: { "Content-Type": "application/json", Authorization: `Bearer ${claim}` },
109
- body: JSON.stringify(mailFields),
110
- });
111
- if (!r.ok) {
112
- const b = await r.text().catch(() => "");
113
- throw new Error(`mp0st-send ${r.status}: ${b.slice(0, 200)}`);
114
- }
115
- const res = (await r.json()) as { email_id?: string; status?: string; is_internal?: boolean; error?: string };
116
- if (res.error) throw new Error(res.error);
117
-
118
- return {
119
- message_id: res.email_id ?? "",
120
- status: res.status ?? "sent",
121
- is_internal: res.is_internal ?? false,
122
- sent_by: "agent",
123
- };
124
- }
125
-
126
- export const mailProvenanceTools: MosaddTool[] = [
127
- {
128
- name: "mAYL_send_as_agent",
129
- requires: "network",
130
- description:
131
- "Send an email ATTRIBUTED TO THE AGENT (provenance-stamped). Unlike mAYL_send (sends as the user), this stamps sent_by='agent' plus your agent_id and optional task_id onto the email record and audit trail — so recipients and compliance can see the mail was agent-originated. Auth: presents a hub-claim JWT (needs MOSADD_API_KEY). The mp0st-send EF verifies the claim with HUB_JWT_SECRET; body trust is never granted for provenance.",
132
- inputSchema: mp0st_send_as_agent_input,
133
- handler: mAYL_send_as_agent as MosaddTool["handler"],
134
- },
135
- ];
1
+ /**
2
+ * mp0st provenance — agent-attributed email send.
3
+ *
4
+ * The plain `mp0st_send` (mail.ts) sends as the USER. When an AGENT sends mail on
5
+ * the user's behalf, the recipient (and the audit trail) should be able to tell
6
+ * it was agent-originated. Per the Lane A contract, `mp0st-send`, when called
7
+ * with a HUB-CLAIM JWT, stamps the row with:
8
+ * sent_by = 'agent', sent_by_agent_id, sent_by_task_id
9
+ *
10
+ * This tool mints/forwards that hub-claim JWT and sets the provenance fields.
11
+ *
12
+ * AUTH MODEL (differs from the rest of mp0st):
13
+ * - mp0st_send uses the user's Supabase session JWT (via invokeFunction).
14
+ * - mp0st_send_as_agent presents a HUB-CLAIM JWT (hub key → claim exchange) so
15
+ * mp0st-send can attribute the send to the agent/task.
16
+ *
17
+ * STATUS: scaffold. The hub-claim exchange endpoint is assumed (TODO Lane A —
18
+ * confirm the exact route + claim shape). Falls back to the user session JWT if
19
+ * no hub key is configured, with provenance fields passed through for the EF to
20
+ * honor once deployed.
21
+ */
22
+
23
+ import { z } from "zod";
24
+ import type { MosaddTool, MosaddToolContext } from "../types.js";
25
+
26
+ const DEFAULT_SUPABASE_URL = "https://rooffhgbxafyjcwmwpsy.supabase.co";
27
+
28
+ function supabaseUrl(): string {
29
+ return (
30
+ process.env.MOSADD_SUPABASE_URL?.replace(/\/$/, "") ??
31
+ process.env.SUPABASE_URL?.replace(/\/$/, "") ??
32
+ DEFAULT_SUPABASE_URL
33
+ );
34
+ }
35
+
36
+ function hubKey(): string | null {
37
+ return process.env.MOSADD_API_KEY ?? process.env.MOSADD_HUB_KEY ?? null;
38
+ }
39
+
40
+ const EmailAddress = z.string().email().max(254);
41
+
42
+ const mp0st_send_as_agent_input = z.object({
43
+ to: z.union([EmailAddress, z.array(EmailAddress).min(1).max(50)]),
44
+ subject: z.string().min(1).max(998),
45
+ body_text: z.string().max(1_048_576).optional(),
46
+ body_html: z.string().max(1_048_576).optional(),
47
+ cc: z.array(EmailAddress).max(50).optional(),
48
+ bcc: z.array(EmailAddress).max(50).optional(),
49
+ reply_to: EmailAddress.optional(),
50
+ tracking: z.boolean().optional(),
51
+ agent_id: z
52
+ .string()
53
+ .min(1)
54
+ .max(120)
55
+ .describe("Stable id of the agent doing the send. Stamped as sent_by_agent_id for provenance."),
56
+ task_id: z
57
+ .string()
58
+ .min(1)
59
+ .max(120)
60
+ .optional()
61
+ .describe("Optional id of the task/run this send belongs to. Stamped as sent_by_task_id."),
62
+ });
63
+
64
+ /**
65
+ * Exchange the hub key for an HS256 hub-claim JWT that authorizes agent-attributed
66
+ * mail sends. The `mp0st-send` EF verifies this token with HUB_JWT_SECRET and reads
67
+ * `agent_id` + `task_id` from its claims authoritatively (body fields are NOT trusted
68
+ * for provenance). LINEAR-3991.
69
+ */
70
+ async function mintHubClaim(agentId: string, taskId?: string): Promise<string> {
71
+ const key = hubKey();
72
+ if (!key) {
73
+ throw new Error("mAYL_send_as_agent needs MOSADD_API_KEY (hub key) to mint a provenance claim.");
74
+ }
75
+ const r = await fetch(`${supabaseUrl()}/functions/v1/hub-claim-mint`, {
76
+ method: "POST",
77
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${key}` },
78
+ body: JSON.stringify({ agent_id: agentId, task_id: taskId ?? null }),
79
+ });
80
+ if (!r.ok) {
81
+ const b = await r.text().catch(() => "");
82
+ throw new Error(`hub-claim-mint ${r.status}: ${b.slice(0, 200)}`);
83
+ }
84
+ const data = (await r.json()) as { access_token?: string };
85
+ if (!data?.access_token) throw new Error("hub-claim-mint: no access_token in response");
86
+ return data.access_token;
87
+ }
88
+
89
+ async function mAYL_send_as_agent(
90
+ input: z.infer<typeof mp0st_send_as_agent_input>,
91
+ ctx: MosaddToolContext,
92
+ ): Promise<{ message_id: string; status: string; is_internal: boolean; sent_by: "agent" }> {
93
+ if (!input.body_text && !input.body_html) {
94
+ throw new Error("mAYL_send_as_agent requires at least one of body_text or body_html.");
95
+ }
96
+
97
+ // Mint the hub-claim JWT and present it directly to mp0st-send (NOT the user
98
+ // session client) so the EF attributes the row to the agent. mp0st-send verifies
99
+ // the HS256 signature with HUB_JWT_SECRET and stamps sent_by_agent_id /
100
+ // sent_by_task_id from the verified claims — body fields are NOT trusted for
101
+ // provenance.
102
+ const claim = await mintHubClaim(input.agent_id, input.task_id);
103
+ ctx.log("debug", "mAYL_send_as_agent invoking mp0st-send with hub-claim", { agent_id: input.agent_id });
104
+
105
+ const { agent_id: _ai, task_id: _ti, ...mailFields } = input;
106
+ const r = await fetch(`${supabaseUrl()}/functions/v1/mp0st-send`, {
107
+ method: "POST",
108
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${claim}` },
109
+ body: JSON.stringify(mailFields),
110
+ });
111
+ if (!r.ok) {
112
+ const b = await r.text().catch(() => "");
113
+ throw new Error(`mp0st-send ${r.status}: ${b.slice(0, 200)}`);
114
+ }
115
+ const res = (await r.json()) as { email_id?: string; status?: string; is_internal?: boolean; error?: string };
116
+ if (res.error) throw new Error(res.error);
117
+
118
+ return {
119
+ message_id: res.email_id ?? "",
120
+ status: res.status ?? "sent",
121
+ is_internal: res.is_internal ?? false,
122
+ sent_by: "agent",
123
+ };
124
+ }
125
+
126
+ export const mailProvenanceTools: MosaddTool[] = [
127
+ {
128
+ name: "mAYL_send_as_agent",
129
+ requires: "network",
130
+ description:
131
+ "Send an email ATTRIBUTED TO THE AGENT (provenance-stamped). Unlike mAYL_send (sends as the user), this stamps sent_by='agent' plus your agent_id and optional task_id onto the email record and audit trail — so recipients and compliance can see the mail was agent-originated. Auth: presents a hub-claim JWT (needs MOSADD_API_KEY). The mp0st-send EF verifies the claim with HUB_JWT_SECRET; body trust is never granted for provenance.",
132
+ inputSchema: mp0st_send_as_agent_input,
133
+ handler: mAYL_send_as_agent as MosaddTool["handler"],
134
+ },
135
+ ];