@modootoday/pmcp 0.17.4 → 0.18.2

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 (272) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +2 -2
  4. package/.mcp.json +1 -1
  5. package/CHANGELOG.md +152 -0
  6. package/CONTRIBUTING.md +71 -0
  7. package/README.md +98 -201
  8. package/SECURITY.md +17 -1
  9. package/dist/apply-JUTGS5WZ.js +242 -0
  10. package/dist/{attachment-tU5FZrgZ.d.ts → attachment-D84OGI6n.d.ts} +1 -1
  11. package/dist/available-DBSIVVJ6.js +73 -0
  12. package/dist/broadcast-CBMVOV3G.js +18 -0
  13. package/dist/chunk-26WLNWDG.js +93 -0
  14. package/dist/chunk-2FIV63WC.js +252 -0
  15. package/dist/chunk-2P4Z2NUX.js +28 -0
  16. package/dist/chunk-34DECPVC.js +22 -0
  17. package/dist/chunk-3FCFAQDG.js +42 -0
  18. package/dist/chunk-3IDXEV5E.js +1934 -0
  19. package/dist/chunk-3PW4FI7U.js +32 -0
  20. package/dist/chunk-3Y3HDMHA.js +108 -0
  21. package/dist/chunk-47O3X4VS.js +113 -0
  22. package/dist/chunk-4NDEP7HU.js +26 -0
  23. package/dist/chunk-5OMOPUE6.js +39 -0
  24. package/dist/chunk-5QQWS4US.js +53 -0
  25. package/dist/chunk-5ZABTVSW.js +48 -0
  26. package/dist/chunk-65KAQSJP.js +7 -0
  27. package/dist/chunk-6STKGOCW.js +27 -0
  28. package/dist/chunk-6WXMJOMI.js +9 -0
  29. package/dist/chunk-73AKO4UL.js +24 -0
  30. package/dist/chunk-7DLZC73N.js +29 -0
  31. package/dist/chunk-7GBYECSK.js +72 -0
  32. package/dist/chunk-7HFIGCSL.js +419 -0
  33. package/dist/chunk-7TD53M7L.js +13 -0
  34. package/dist/chunk-7UCZAN4J.js +778 -0
  35. package/dist/chunk-A4PKLESO.js +112 -0
  36. package/dist/chunk-A7VF7A35.js +1025 -0
  37. package/dist/chunk-ABTJQ4QV.js +74 -0
  38. package/dist/chunk-AJ4VXM2U.js +349 -0
  39. package/dist/chunk-BBTBJCFA.js +380 -0
  40. package/dist/chunk-BU65MNVU.js +13 -0
  41. package/dist/chunk-C4NHQGHL.js +142 -0
  42. package/dist/chunk-CJTKR6K6.js +1213 -0
  43. package/dist/chunk-D77IRGHO.js +1246 -0
  44. package/dist/chunk-DCU2EXQV.js +78 -0
  45. package/dist/chunk-DMZHQZ7P.js +104 -0
  46. package/dist/chunk-DZ2MRTYT.js +135 -0
  47. package/dist/chunk-E2YOZ2FF.js +207 -0
  48. package/dist/chunk-E3DQB5LS.js +48 -0
  49. package/dist/chunk-EATCUWGG.js +66 -0
  50. package/dist/chunk-EAWPJHJ7.js +155 -0
  51. package/dist/chunk-EIDIVIAD.js +33 -0
  52. package/dist/chunk-F5QYZK7E.js +396 -0
  53. package/dist/chunk-F5XMGOOX.js +28 -0
  54. package/dist/chunk-FENOGX3U.js +31 -0
  55. package/dist/chunk-GZHHEHKY.js +44 -0
  56. package/dist/chunk-HDMBVLCZ.js +53 -0
  57. package/dist/chunk-HQOB7OQS.js +81 -0
  58. package/dist/chunk-I2ZP2PSA.js +211 -0
  59. package/dist/chunk-IG33DXLT.js +151 -0
  60. package/dist/chunk-IJBSOWHK.js +86 -0
  61. package/dist/chunk-INT7QLEU.js +114 -0
  62. package/dist/chunk-J7UYNJCR.js +9 -0
  63. package/dist/chunk-JEL35P7S.js +53 -0
  64. package/dist/chunk-JGJ4INEN.js +32 -0
  65. package/dist/chunk-JS5RTH4I.js +84 -0
  66. package/dist/chunk-JWRZDYB5.js +59 -0
  67. package/dist/chunk-KMXRRSKT.js +660 -0
  68. package/dist/chunk-LBXO4VPG.js +73 -0
  69. package/dist/chunk-LLBPVZXM.js +67 -0
  70. package/dist/chunk-LLT5FQBE.js +57 -0
  71. package/dist/chunk-LMT3PPXJ.js +17 -0
  72. package/dist/chunk-LMUBBIE2.js +83 -0
  73. package/dist/chunk-LTZH5E3G.js +479 -0
  74. package/dist/chunk-LW4TG7EL.js +39 -0
  75. package/dist/chunk-MPSQXSC6.js +346 -0
  76. package/dist/chunk-MVFH26QT.js +97 -0
  77. package/dist/chunk-NLEXKE7U.js +67 -0
  78. package/dist/chunk-NQPURJT5.js +44 -0
  79. package/dist/chunk-NRBQK6UX.js +105 -0
  80. package/dist/chunk-OEH47H6A.js +48 -0
  81. package/dist/chunk-OG7QR2DP.js +75 -0
  82. package/dist/chunk-OPYFEHKG.js +52 -0
  83. package/dist/chunk-P4N7DBD5.js +83 -0
  84. package/dist/chunk-PAX3QXX2.js +140 -0
  85. package/dist/chunk-PKODFR5F.js +102 -0
  86. package/dist/chunk-PMJG2CXF.js +122 -0
  87. package/dist/chunk-Q5H3L6Y4.js +23 -0
  88. package/dist/chunk-QEF7EK3T.js +28 -0
  89. package/dist/chunk-QEW4J3IZ.js +74 -0
  90. package/dist/chunk-QPL7E2HW.js +464 -0
  91. package/dist/chunk-R2GPCZUX.js +22 -0
  92. package/dist/chunk-R5MT42JS.js +284 -0
  93. package/dist/chunk-RMATE45Z.js +197 -0
  94. package/dist/chunk-RPQOBHVU.js +87 -0
  95. package/dist/chunk-S3PIAMXV.js +230 -0
  96. package/dist/chunk-T3LKX23M.js +168 -0
  97. package/dist/chunk-T6GOWHK6.js +30 -0
  98. package/dist/chunk-TIA4SPU2.js +10 -0
  99. package/dist/chunk-TNCZ6444.js +57 -0
  100. package/dist/chunk-TVL5RTE6.js +269 -0
  101. package/dist/chunk-TXQ7L33K.js +45 -0
  102. package/dist/chunk-UPQTAHUK.js +189 -0
  103. package/dist/chunk-V4NPDK6X.js +14 -0
  104. package/dist/chunk-VJFEN6DJ.js +38 -0
  105. package/dist/chunk-VMHUEOT5.js +643 -0
  106. package/dist/chunk-VRPMYPZU.js +4985 -0
  107. package/dist/chunk-WIW772I3.js +25 -0
  108. package/dist/chunk-XELAZAIM.js +136 -0
  109. package/dist/chunk-XNML2KIC.js +23 -0
  110. package/dist/chunk-XP2U3LO3.js +30 -0
  111. package/dist/chunk-YGOWIJPE.js +51 -0
  112. package/dist/chunk-YIXDHQYE.js +11 -0
  113. package/dist/chunk-YSAWTGNA.js +117 -0
  114. package/dist/claude-U2JC2DNQ.js +77 -0
  115. package/dist/cli-MI4ZCAZ3.js +41 -0
  116. package/dist/cli-ZN7ZVDEZ.js +46 -0
  117. package/dist/cli.js +144 -16197
  118. package/dist/completion-ILSRB3LW.js +142 -0
  119. package/dist/config-DnpLL2kT.d.ts +46 -0
  120. package/dist/{service-qpCsOXkQ.d.ts → core-C1LPjxK6.d.ts} +2 -6
  121. package/dist/diagnostics-XKXVVQWH.js +93 -0
  122. package/dist/doctor-O2E63YGO.js +538 -0
  123. package/dist/entry-X6CSYQRQ.js +305 -0
  124. package/dist/exec-mcp-2PMWBPD7.js +365 -0
  125. package/dist/harness-L2KSI2ZB.js +177 -0
  126. package/dist/harness-egress-bridge.js +4 -4
  127. package/dist/harness-launch-gate.js +47 -940
  128. package/dist/harness-pane-runner.js +13 -80
  129. package/dist/harness-worker.js +21 -2703
  130. package/dist/hook-body.js +5222 -0
  131. package/dist/hook-spec-C5fWTSCH.d.ts +100 -0
  132. package/dist/hook.js +26 -0
  133. package/dist/hooks-BHTA44X7.js +21 -0
  134. package/dist/host-UIZAXXQH.js +22 -0
  135. package/dist/host-UWK754BW.js +210 -0
  136. package/dist/host-run-BI2OTZDZ.js +307 -0
  137. package/dist/http.d.ts +5 -42
  138. package/dist/http.js +21 -2234
  139. package/dist/import-mcp-GPKJI7DI.js +400 -0
  140. package/dist/index.d.ts +146 -168
  141. package/dist/index.js +133 -4948
  142. package/dist/init-3C2Y7BNJ.js +14 -0
  143. package/dist/install-GG7HHZK2.js +796 -0
  144. package/dist/invoke-44CJRVMK.js +23 -0
  145. package/dist/list-MCP2FXUF.js +68 -0
  146. package/dist/list-WL6L4J5H.js +65 -0
  147. package/dist/load-BEUBABtB.d.ts +21 -0
  148. package/dist/logout-F5EJ5MOU.js +44 -0
  149. package/dist/logs-TBUA4UWU.js +107 -0
  150. package/dist/mailbox/index.d.ts +10 -5
  151. package/dist/mailbox/index.js +53 -1572
  152. package/dist/mailbox-BMTZOSZ7.js +285 -0
  153. package/dist/mailbox-GDJ7BWQN.js +189 -0
  154. package/dist/mainline-KAD2ERLP.js +639 -0
  155. package/dist/marketplace-G4VQET5W.js +191 -0
  156. package/dist/mcp-235QZN2A.js +15 -0
  157. package/dist/mcp-FJ2UQ4RH.js +193 -0
  158. package/dist/models-ISU4DCMA.js +32 -0
  159. package/dist/opencode-CN7JLQYO.js +60 -0
  160. package/dist/pause-7LILUVGL.js +18 -0
  161. package/dist/preview-DT7DWG5F.js +91 -0
  162. package/dist/project/hook-adapter.d.ts +5 -2
  163. package/dist/project/hook-adapter.js +41 -27
  164. package/dist/project-5YV5CUEG.js +70 -0
  165. package/dist/pty-XTJ4MIWK.js +94 -0
  166. package/dist/recovery-U6QB3PMT.js +100 -0
  167. package/dist/reindex-Y27QJFDB.js +22 -0
  168. package/dist/resume-26VFAAMH.js +18 -0
  169. package/dist/run-3AXTZSR7.js +126 -0
  170. package/dist/run-3SOVRQIA.js +19 -0
  171. package/dist/serve-DQMKTFIV.js +104 -0
  172. package/dist/session-XM2CR425.js +159 -0
  173. package/dist/setup-DTKZLZUT.js +18 -0
  174. package/dist/start-login-YTZV6KMF.js +416 -0
  175. package/dist/status-A2OUTNGK.js +9 -0
  176. package/dist/status-H2VAHIDV.js +10 -0
  177. package/dist/status-MROQ7WR7.js +43 -0
  178. package/dist/status-RO55QPKV.js +55 -0
  179. package/dist/status-UME2L33L.js +286 -0
  180. package/dist/stdio.d.ts +3 -13
  181. package/dist/stdio.js +16 -3186
  182. package/dist/sweep-35LGQTTO.js +18 -0
  183. package/dist/test-AGZOJLRZ.js +561 -0
  184. package/dist/tools-gpHNq9Dh.d.ts +328 -0
  185. package/dist/tui-G5LLWCSV.js +153 -0
  186. package/dist/unbroadcast-5QNGAJR2.js +18 -0
  187. package/dist/validate-IU52H2IC.js +46 -0
  188. package/dist/worker-QZ5T6LJD.js +80 -0
  189. package/dist/worktree-create-PZSRB7PH.js +89 -0
  190. package/dist/worktree-list-JYB6VXLW.js +51 -0
  191. package/dist/worktree-sync-UF5CXPWV.js +30 -0
  192. package/docs/authoring.md +82 -0
  193. package/docs/browser-and-desktop.md +46 -0
  194. package/docs/commands.md +325 -0
  195. package/docs/compare.md +35 -0
  196. package/docs/compatibility.md +55 -0
  197. package/docs/embeddings.md +1 -1
  198. package/docs/getting-started.md +105 -0
  199. package/docs/git-workflow.md +60 -0
  200. package/docs/glossary.md +31 -0
  201. package/docs/hooks/capabilities/antigravity.json +199 -0
  202. package/docs/hooks/capabilities/claude.json +179 -0
  203. package/docs/hooks/capabilities/codex.json +179 -0
  204. package/docs/hooks/capabilities/gemini.json +196 -0
  205. package/docs/hooks/capabilities/grok.json +192 -0
  206. package/docs/hooks/capabilities/opencode.json +184 -0
  207. package/docs/hooks.md +264 -0
  208. package/docs/install.md +72 -0
  209. package/docs/library-skills.md +132 -0
  210. package/docs/mailbox.md +16 -5
  211. package/docs/project-configuration.md +540 -58
  212. package/docs/sessions.md +64 -0
  213. package/docs/skills.md +4 -45
  214. package/docs/terminal-harness.md +92 -44
  215. package/docs/terminal-workspace.md +81 -169
  216. package/gemini-extension.json +2 -2
  217. package/mcp.json +1 -1
  218. package/package.json +16 -2
  219. package/plugin.json +2 -2
  220. package/plugins/pmcp/.claude-plugin/plugin.json +4 -2
  221. package/plugins/pmcp/.mcp.json +1 -1
  222. package/plugins/pmcp/gemini-extension.json +2 -2
  223. package/plugins/pmcp/mcp.json +1 -1
  224. package/plugins/pmcp/mod/commands.ts +72 -0
  225. package/plugins/pmcp/mod/contract.d.ts +39 -0
  226. package/plugins/pmcp/mod/draw.tsx +216 -0
  227. package/plugins/pmcp/mod/guard.ts +42 -0
  228. package/plugins/pmcp/mod/hooks.json +4 -0
  229. package/plugins/pmcp/mod/host.ts +46 -0
  230. package/plugins/pmcp/mod/model.ts +144 -0
  231. package/plugins/pmcp/mod/reader/index.ts +18 -0
  232. package/plugins/pmcp/mod/reader/read.ts +76 -0
  233. package/plugins/pmcp/mod/reader/settings.ts +54 -0
  234. package/plugins/pmcp/mod/reader/types.ts +38 -0
  235. package/plugins/pmcp/mod/register.tsx +73 -0
  236. package/plugins/pmcp/mod/sessions/format.ts +91 -0
  237. package/plugins/pmcp/mod/sessions/types.ts +162 -0
  238. package/plugins/pmcp/mod/snapshot.ts +75 -0
  239. package/plugins/pmcp/mod/spinner.tsx +30 -0
  240. package/plugins/pmcp/mod/state.ts +28 -0
  241. package/plugins/pmcp/plugin.json +2 -2
  242. package/plugins/pmcp/skills/agent-assets-migrate/SKILL.md +96 -0
  243. package/plugins/pmcp/skills/headless-agents-ci-scaffold/SKILL.md +101 -0
  244. package/plugins/pmcp/skills/marketplace-plugin-scaffold/SKILL.md +87 -0
  245. package/plugins/pmcp/skills/package-skill-catalog/SKILL.md +51 -15
  246. package/plugins/pmcp/skills/pmcp-browser/SKILL.md +27 -0
  247. package/plugins/pmcp/skills/pmcp-desktop/SKILL.md +25 -0
  248. package/plugins/pmcp/skills/pmcp-project-init/SKILL.md +153 -0
  249. package/plugins/pmcp/skills/pmcp-sessions-and-git/SKILL.md +96 -0
  250. package/plugins/pmcp/skills/skill-package-scaffold/SKILL.md +89 -0
  251. package/schema/catalog-v1.json +187 -0
  252. package/schema/library.json +196 -0
  253. package/schema/marketplace-manifest.json +144 -0
  254. package/schema/plugin-manifest.json +59 -0
  255. package/schema/skill-frontmatter.json +170 -0
  256. package/schema/skill-metadata-core.json +131 -0
  257. package/skills/agent-assets-migrate/SKILL.md +96 -0
  258. package/skills/headless-agents-ci-scaffold/SKILL.md +101 -0
  259. package/skills/marketplace-plugin-scaffold/SKILL.md +87 -0
  260. package/skills/package-skill-catalog/SKILL.md +51 -15
  261. package/skills/pmcp-browser/SKILL.md +27 -0
  262. package/skills/pmcp-desktop/SKILL.md +25 -0
  263. package/skills/pmcp-project-init/SKILL.md +153 -0
  264. package/skills/pmcp-sessions-and-git/SKILL.md +96 -0
  265. package/skills/skill-package-scaffold/SKILL.md +89 -0
  266. package/dist/config-BkSpjUG6.d.ts +0 -50
  267. package/dist/embed-DRROSD3F.d.ts +0 -53
  268. package/dist/hook-spec-CSJJySsH.d.ts +0 -11
  269. package/dist/server-VWSY3Shw.d.ts +0 -543
  270. package/dist/tui-worker.js +0 -6549
  271. package/docs/manual-library-skills.md +0 -74
  272. /package/dist/{tui-worker.d.ts → hook.d.ts} +0 -0
@@ -0,0 +1,1213 @@
1
+ import {
2
+ actorIdSchema,
3
+ bindingSchema,
4
+ credentialSchema,
5
+ cursorSchema,
6
+ inboxSchema,
7
+ messageSchema,
8
+ operationSchema,
9
+ runtimeSchema,
10
+ sendSchema,
11
+ sessionsSchema
12
+ } from "./chunk-47O3X4VS.js";
13
+ import {
14
+ openSqlite
15
+ } from "./chunk-6STKGOCW.js";
16
+ import {
17
+ readConfig
18
+ } from "./chunk-QPL7E2HW.js";
19
+
20
+ // src/mailbox/types.ts
21
+ var MailboxError = class extends Error {
22
+ constructor(code, message, retryable = false) {
23
+ super(message);
24
+ this.code = code;
25
+ this.retryable = retryable;
26
+ this.name = "MailboxError";
27
+ }
28
+ code;
29
+ retryable;
30
+ };
31
+ function failure(error) {
32
+ if (error instanceof MailboxError) {
33
+ return {
34
+ ok: false,
35
+ error: {
36
+ code: error.code,
37
+ message: error.message,
38
+ retryable: error.retryable
39
+ }
40
+ };
41
+ }
42
+ return {
43
+ ok: false,
44
+ error: {
45
+ code: "internal_error",
46
+ message: "Mailbox operation failed",
47
+ retryable: false
48
+ }
49
+ };
50
+ }
51
+
52
+ // src/mailbox/config.ts
53
+ import { randomUUID } from "crypto";
54
+ import {
55
+ closeSync,
56
+ constants,
57
+ existsSync,
58
+ fstatSync,
59
+ mkdirSync,
60
+ openSync,
61
+ readFileSync,
62
+ renameSync,
63
+ rmSync,
64
+ writeFileSync
65
+ } from "fs";
66
+ import { homedir } from "os";
67
+ import { dirname, join, resolve } from "path";
68
+ import { z } from "zod";
69
+ var sectionSchema = z.object({
70
+ version: z.literal(1),
71
+ enabled: z.boolean(),
72
+ project_id: z.uuid(),
73
+ state_dir: z.string().min(1).optional()
74
+ }).strict();
75
+ function mailboxConfigFrom(project, env = process.env) {
76
+ if (project.raw.mailbox === void 0) return void 0;
77
+ const parsed = sectionSchema.safeParse(project.raw.mailbox);
78
+ if (!parsed.success)
79
+ throw new MailboxError("invalid_config", "Invalid [mailbox] configuration");
80
+ const section = parsed.data;
81
+ const stateRoot = env.XDG_STATE_HOME ?? join(homedir(), ".local/state");
82
+ const stateDir = section.state_dir ? resolve(project.dir, section.state_dir) : join(stateRoot, "pmcp/projects", section.project_id);
83
+ return {
84
+ projectId: section.project_id,
85
+ enabled: section.enabled,
86
+ databasePath: join(stateDir, "mailbox.sqlite")
87
+ };
88
+ }
89
+ function initializeMailboxConfig(file, stateDirectory) {
90
+ const path = resolve(file);
91
+ const original = existsSync(path) ? readFileSync(path, "utf8") : void 0;
92
+ if (original !== void 0 && readConfig(path).raw.mailbox !== void 0) {
93
+ throw new MailboxError("mailbox_exists", "Mailbox is already configured");
94
+ }
95
+ const lines = [
96
+ "[mailbox]",
97
+ "version = 1",
98
+ "enabled = true",
99
+ `project_id = ${JSON.stringify(randomUUID())}`
100
+ ];
101
+ if (stateDirectory)
102
+ lines.push(`state_dir = ${JSON.stringify(stateDirectory)}`);
103
+ const text = `${original ?? ""}
104
+ ${lines.join("\n")}
105
+ `;
106
+ mkdirSync(dirname(path), { recursive: true });
107
+ if (original === void 0) {
108
+ writeFileSync(path, text, { flag: "wx", mode: 384 });
109
+ } else {
110
+ const temporary = `${path}.${randomUUID()}.tmp`;
111
+ try {
112
+ writeFileSync(temporary, text, { flag: "wx", mode: 384 });
113
+ if (readFileSync(path, "utf8") !== original) {
114
+ throw new MailboxError(
115
+ "config_conflict",
116
+ "Configuration changed during initialization"
117
+ );
118
+ }
119
+ renameSync(temporary, path);
120
+ } finally {
121
+ rmSync(temporary, { force: true });
122
+ }
123
+ }
124
+ return mailboxConfigFrom(readConfig(path));
125
+ }
126
+ function readPrivateJson(file) {
127
+ const descriptor = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
128
+ try {
129
+ const stat = fstatSync(descriptor);
130
+ if (!stat.isFile() || (stat.mode & 63) !== 0 || stat.size > 4096) {
131
+ throw new MailboxError(
132
+ "unsafe_credential_file",
133
+ "Use a private regular credential file of at most 4096 bytes"
134
+ );
135
+ }
136
+ if (process.getuid && stat.uid !== process.getuid()) {
137
+ throw new MailboxError(
138
+ "unsafe_credential_file",
139
+ "Credential file must belong to the current user"
140
+ );
141
+ }
142
+ return JSON.parse(readFileSync(descriptor, "utf8"));
143
+ } finally {
144
+ closeSync(descriptor);
145
+ }
146
+ }
147
+ function readCredential(file) {
148
+ return credentialSchema.parse(readPrivateJson(file));
149
+ }
150
+ function readBinding(file) {
151
+ return bindingSchema.parse(readPrivateJson(file));
152
+ }
153
+ function writePrivateJson(file, value) {
154
+ mkdirSync(dirname(resolve(file)), { recursive: true, mode: 448 });
155
+ writeFileSync(file, `${JSON.stringify(value, null, 2)}
156
+ `, {
157
+ flag: "wx",
158
+ mode: 384
159
+ });
160
+ }
161
+ function writeBindingFile(file, binding) {
162
+ if (existsSync(file)) {
163
+ const previous = readBinding(file);
164
+ if (previous.projectId !== binding.projectId || previous.actorId !== binding.actorId) {
165
+ throw new MailboxError(
166
+ "binding_scope_conflict",
167
+ "Binding file belongs to another actor or project"
168
+ );
169
+ }
170
+ }
171
+ const temporary = `${file}.${randomUUID()}.tmp`;
172
+ try {
173
+ writePrivateJson(temporary, binding);
174
+ renameSync(temporary, file);
175
+ } finally {
176
+ rmSync(temporary, { force: true });
177
+ }
178
+ }
179
+
180
+ // src/mailbox/store/_shared.ts
181
+ import { createHash, randomBytes } from "crypto";
182
+ var PRESENCE_TTL_MS = 12e4;
183
+ var HEARTBEAT_INTERVAL_MS = 3e4;
184
+ function hash(secret4) {
185
+ return createHash("sha256").update(secret4).digest("hex");
186
+ }
187
+ function secret() {
188
+ return randomBytes(32).toString("hex");
189
+ }
190
+
191
+ // src/mailbox/store/core.ts
192
+ import { chmodSync as chmodSync2, existsSync as existsSync2 } from "fs";
193
+
194
+ // src/storage/schema.ts
195
+ var SCHEMA_VERSION = 3;
196
+ var SCHEMA_SQL = `
197
+ CREATE TABLE mailbox_project (
198
+ id TEXT PRIMARY KEY,
199
+ created_at_ms INTEGER NOT NULL
200
+ );
201
+ CREATE TABLE mailbox_actors (
202
+ id TEXT PRIMARY KEY,
203
+ credential_hash TEXT NOT NULL,
204
+ parent_actor_id TEXT REFERENCES mailbox_actors(id),
205
+ generation INTEGER NOT NULL DEFAULT 0,
206
+ active_session_id TEXT REFERENCES mailbox_sessions(id) DEFERRABLE INITIALLY DEFERRED,
207
+ created_at_ms INTEGER NOT NULL
208
+ );
209
+ CREATE TABLE mailbox_sessions (
210
+ id TEXT PRIMARY KEY,
211
+ actor_id TEXT NOT NULL REFERENCES mailbox_actors(id),
212
+ generation INTEGER NOT NULL,
213
+ secret_hash TEXT NOT NULL,
214
+ runtime TEXT NOT NULL,
215
+ native_session_id TEXT,
216
+ created_at_ms INTEGER NOT NULL,
217
+ heartbeat_at_ms INTEGER NOT NULL,
218
+ expires_at_ms INTEGER NOT NULL,
219
+ closed_at_ms INTEGER,
220
+ UNIQUE(actor_id, generation)
221
+ );
222
+ CREATE TABLE mailbox_messages (
223
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
224
+ id TEXT NOT NULL UNIQUE,
225
+ sender_actor_id TEXT NOT NULL REFERENCES mailbox_actors(id),
226
+ sender_session_id TEXT NOT NULL REFERENCES mailbox_sessions(id),
227
+ idempotency_key TEXT NOT NULL,
228
+ payload_json TEXT NOT NULL,
229
+ body TEXT NOT NULL,
230
+ thread_id TEXT NOT NULL REFERENCES mailbox_messages(id) DEFERRABLE INITIALLY DEFERRED,
231
+ reply_to_id TEXT REFERENCES mailbox_messages(id),
232
+ created_at_ms INTEGER NOT NULL,
233
+ UNIQUE(sender_actor_id, idempotency_key)
234
+ );
235
+ CREATE TABLE mailbox_receipts (
236
+ message_id TEXT NOT NULL REFERENCES mailbox_messages(id),
237
+ target_key TEXT NOT NULL,
238
+ actor_id TEXT NOT NULL REFERENCES mailbox_actors(id),
239
+ session_id TEXT REFERENCES mailbox_sessions(id),
240
+ read_at_ms INTEGER,
241
+ ack_at_ms INTEGER,
242
+ PRIMARY KEY(message_id, target_key),
243
+ CHECK(ack_at_ms IS NULL OR read_at_ms IS NOT NULL)
244
+ );
245
+ CREATE INDEX receipts_actor_session ON mailbox_receipts(actor_id, session_id, message_id);
246
+ CREATE INDEX messages_thread_seq ON mailbox_messages(thread_id, seq);
247
+ CREATE INDEX sessions_actor_presence ON mailbox_sessions(actor_id, closed_at_ms, expires_at_ms);
248
+ PRAGMA user_version = 1;
249
+ `;
250
+
251
+ // src/storage/migrations.ts
252
+ import { createHash as createHash2 } from "crypto";
253
+ var MIGRATION_2 = `
254
+ ALTER TABLE mailbox_actors ADD COLUMN credential_revision INTEGER NOT NULL DEFAULT 1;
255
+ ALTER TABLE mailbox_actors ADD COLUMN parent_generation INTEGER;
256
+ UPDATE mailbox_actors SET parent_generation = (SELECT generation FROM mailbox_actors p WHERE p.id = mailbox_actors.parent_actor_id) WHERE parent_actor_id IS NOT NULL;
257
+ CREATE TABLE mailbox_migrations (version INTEGER PRIMARY KEY, checksum TEXT NOT NULL);
258
+ CREATE TABLE mailbox_notifications (
259
+ message_id TEXT NOT NULL REFERENCES mailbox_messages(id),
260
+ actor_id TEXT NOT NULL REFERENCES mailbox_actors(id),
261
+ session_id TEXT NOT NULL REFERENCES mailbox_sessions(id),
262
+ generation INTEGER NOT NULL,
263
+ native_target TEXT NOT NULL,
264
+ state TEXT NOT NULL CHECK(state IN ('pending', 'leased', 'accepted', 'uncertain', 'failed', 'stale')),
265
+ attempts INTEGER NOT NULL DEFAULT 0,
266
+ lease_token TEXT,
267
+ lease_until_ms INTEGER,
268
+ next_attempt_ms INTEGER NOT NULL,
269
+ outcome_code TEXT,
270
+ PRIMARY KEY(message_id, actor_id, session_id)
271
+ );
272
+ CREATE INDEX notifications_pending ON mailbox_notifications(state, next_attempt_ms);
273
+ `;
274
+ function migrateDatabase(database) {
275
+ let version = database.get("PRAGMA user_version")?.user_version;
276
+ if (version === 1) {
277
+ database.exec(MIGRATION_2);
278
+ database.run(
279
+ "INSERT INTO mailbox_migrations(version, checksum) VALUES (?, ?)",
280
+ 2,
281
+ createHash2("sha256").update(MIGRATION_2).digest("hex")
282
+ );
283
+ database.exec("PRAGMA user_version = 2");
284
+ version = 2;
285
+ }
286
+ if (version === 2) {
287
+ database.exec(MIGRATION_3);
288
+ database.run(
289
+ "INSERT INTO mailbox_migrations(version, checksum) VALUES (?, ?)",
290
+ 3,
291
+ createHash2("sha256").update(MIGRATION_3).digest("hex")
292
+ );
293
+ database.exec("PRAGMA user_version = 3");
294
+ }
295
+ if (database.all("PRAGMA foreign_key_check").length > 0) {
296
+ throw new MailboxError(
297
+ "storage_corrupt",
298
+ "Migration failed foreign key validation"
299
+ );
300
+ }
301
+ }
302
+ var MIGRATION_3 = `
303
+ ALTER TABLE mailbox_actors ADD COLUMN authority_expires_at_ms INTEGER;
304
+ UPDATE mailbox_actors SET authority_expires_at_ms = created_at_ms + 60000 WHERE parent_actor_id IS NOT NULL;
305
+ `;
306
+ function validateMigrations(database) {
307
+ for (const [version, sql] of [
308
+ [2, MIGRATION_2],
309
+ [3, MIGRATION_3]
310
+ ]) {
311
+ const expected = createHash2("sha256").update(sql).digest("hex");
312
+ if (database.get(
313
+ "SELECT checksum FROM mailbox_migrations WHERE version = ?",
314
+ version
315
+ )?.checksum !== expected) {
316
+ throw new MailboxError(
317
+ "schema_incompatible",
318
+ "Migration checksum does not match the supported schema"
319
+ );
320
+ }
321
+ }
322
+ }
323
+
324
+ // src/mailbox/sqlite.ts
325
+ import { chmodSync, mkdirSync as mkdirSync2 } from "fs";
326
+ import { dirname as dirname2 } from "path";
327
+ import { setTimeout as delay } from "timers/promises";
328
+ function storageError(error) {
329
+ const detail = error instanceof Error ? error.message : "";
330
+ if (/busy|locked/i.test(detail)) {
331
+ return new MailboxError("storage_locked", "Mailbox storage is busy", true);
332
+ }
333
+ if (/corrupt|malformed|not a database/i.test(detail)) {
334
+ return new MailboxError("storage_corrupt", "Mailbox storage is corrupt");
335
+ }
336
+ return new MailboxError(
337
+ "storage_unavailable",
338
+ "Mailbox storage cannot be accessed"
339
+ );
340
+ }
341
+ async function openDatabase(file) {
342
+ let native;
343
+ try {
344
+ if (file !== ":memory:")
345
+ mkdirSync2(dirname2(file), { recursive: true, mode: 448 });
346
+ native = (await openSqlite(file)).db;
347
+ if (file !== ":memory:") chmodSync(file, 384);
348
+ } catch (error) {
349
+ throw storageError(error);
350
+ }
351
+ const invoke = (operation) => {
352
+ try {
353
+ return operation();
354
+ } catch (error) {
355
+ throw storageError(error);
356
+ }
357
+ };
358
+ return {
359
+ exec: (sql) => invoke(() => native.exec(sql)),
360
+ get: (sql, ...values) => invoke(() => native.prepare(sql).get(...values)),
361
+ all: (sql, ...values) => invoke(() => native.prepare(sql).all(...values)),
362
+ run: (sql, ...values) => {
363
+ invoke(() => native.prepare(sql).run(...values));
364
+ },
365
+ close: () => native.close()
366
+ };
367
+ }
368
+ async function retryLocked(database, operation) {
369
+ const deadline = performance.now() + 5e3;
370
+ while (true) {
371
+ const remaining = Math.max(1, Math.floor(deadline - performance.now()));
372
+ database.exec(`PRAGMA busy_timeout = ${Math.min(1e3, remaining)}`);
373
+ try {
374
+ return operation();
375
+ } catch (error) {
376
+ if (!(error instanceof MailboxError) || error.code !== "storage_locked") {
377
+ throw error;
378
+ }
379
+ if (performance.now() >= deadline) {
380
+ throw error;
381
+ }
382
+ await delay(Math.min(25, Math.max(1, deadline - performance.now())));
383
+ }
384
+ }
385
+ }
386
+ function transaction(database, operation, write = true) {
387
+ return retryLocked(database, () => {
388
+ database.exec(write ? "BEGIN IMMEDIATE" : "BEGIN");
389
+ try {
390
+ const result = operation();
391
+ database.exec("COMMIT");
392
+ return result;
393
+ } catch (error) {
394
+ database.exec("ROLLBACK");
395
+ throw error;
396
+ }
397
+ });
398
+ }
399
+
400
+ // src/mailbox/store/registration.ts
401
+ function registerActor(store, actorId, parentActorId, persist, authorityTtlMs = 6e4, parentBinding) {
402
+ actorIdSchema.parse(actorId);
403
+ if (parentActorId) {
404
+ actorIdSchema.parse(parentActorId);
405
+ }
406
+ return store.run(() => {
407
+ if (parentBinding) {
408
+ store.assertBinding(parentBinding);
409
+ if (parentActorId !== parentBinding.actorId) {
410
+ throw new MailboxError(
411
+ "unauthorized",
412
+ "Delegation parent does not match the issuer"
413
+ );
414
+ }
415
+ }
416
+ if (store.database.get("SELECT id FROM mailbox_actors WHERE id = ?", actorId)) {
417
+ throw new MailboxError("actor_exists", "Actor is already registered");
418
+ }
419
+ if (parentActorId && !store.database.get(
420
+ "SELECT id FROM mailbox_actors WHERE id = ?",
421
+ parentActorId
422
+ )) {
423
+ throw new MailboxError("unknown_actor", "Parent actor is not registered");
424
+ }
425
+ if (parentActorId) {
426
+ const parent = store.database.get(
427
+ "SELECT a.parent_actor_id, s.closed_at_ms, s.expires_at_ms FROM mailbox_actors a LEFT JOIN mailbox_sessions s ON s.id = a.active_session_id WHERE a.id = ?",
428
+ parentActorId
429
+ );
430
+ if (parent?.parent_actor_id || parent?.closed_at_ms !== null || Number(parent?.expires_at_ms ?? 0) <= store.now()) {
431
+ throw new MailboxError(
432
+ "stale_parent",
433
+ "Delegation requires a live root parent attachment"
434
+ );
435
+ }
436
+ if (!Number.isSafeInteger(authorityTtlMs) || authorityTtlMs < 1 || authorityTtlMs > 3e5) {
437
+ throw new MailboxError(
438
+ "invalid_ttl",
439
+ "Child authority TTL must be between 1 and 300000 milliseconds"
440
+ );
441
+ }
442
+ }
443
+ const credential = {
444
+ projectId: store.config.projectId,
445
+ actorId,
446
+ secret: secret()
447
+ };
448
+ store.database.run(
449
+ "INSERT INTO mailbox_actors(id, credential_hash, parent_actor_id, parent_generation, created_at_ms, authority_expires_at_ms) VALUES (?, ?, ?, ?, ?, ?)",
450
+ actorId,
451
+ hash(credential.secret),
452
+ parentActorId ?? null,
453
+ parentActorId ? Number(
454
+ store.database.get(
455
+ "SELECT generation FROM mailbox_actors WHERE id = ?",
456
+ parentActorId
457
+ )?.generation
458
+ ) : null,
459
+ store.now(),
460
+ parentActorId ? store.now() + authorityTtlMs : null
461
+ );
462
+ persist?.(credential);
463
+ return credential;
464
+ });
465
+ }
466
+
467
+ // src/mailbox/store/attachment.ts
468
+ import { randomUUID as randomUUID2 } from "crypto";
469
+ function attach(store, credential, runtime, replaceSessionId, nativeSessionId) {
470
+ credentialSchema.parse(credential);
471
+ runtimeSchema.parse(runtime);
472
+ if (nativeSessionId !== void 0 && (nativeSessionId.length < 1 || nativeSessionId.length > 256 || /[\x00-\x1f]/u.test(nativeSessionId))) {
473
+ throw new MailboxError(
474
+ "invalid_target",
475
+ "Native session ID must be a bounded nonempty identifier"
476
+ );
477
+ }
478
+ return store.run(() => {
479
+ const actor = store.database.get(
480
+ "SELECT * FROM mailbox_actors WHERE id = ?",
481
+ credential.actorId
482
+ );
483
+ if (credential.projectId !== store.config.projectId || actor?.credential_hash !== hash(credential.secret)) {
484
+ throw new MailboxError("unauthorized", "Actor credential is invalid");
485
+ }
486
+ if (actor.authority_expires_at_ms !== null && Number(actor.authority_expires_at_ms) <= store.now()) {
487
+ throw new MailboxError(
488
+ "authority_expired",
489
+ "Child authority has expired"
490
+ );
491
+ }
492
+ if (actor.parent_actor_id) {
493
+ const parent = store.database.get(
494
+ "SELECT a.generation, s.expires_at_ms, s.closed_at_ms FROM mailbox_actors a LEFT JOIN mailbox_sessions s ON s.id = a.active_session_id WHERE a.id = ?",
495
+ actor.parent_actor_id
496
+ );
497
+ if (!parent || parent.generation !== actor.parent_generation || parent.closed_at_ms !== null || Number(parent.expires_at_ms ?? 0) <= store.now()) {
498
+ throw new MailboxError(
499
+ "stale_parent",
500
+ "Parent attachment is no longer current"
501
+ );
502
+ }
503
+ }
504
+ const activeId = actor.active_session_id;
505
+ const active = activeId ? store.database.get(
506
+ "SELECT * FROM mailbox_sessions WHERE id = ?",
507
+ activeId
508
+ ) : void 0;
509
+ if (replaceSessionId && replaceSessionId !== activeId) {
510
+ throw new MailboxError(
511
+ "session_conflict",
512
+ "Expected attachment is no longer current"
513
+ );
514
+ }
515
+ if (active && Number(active.expires_at_ms) > store.now() && !replaceSessionId) {
516
+ throw new MailboxError(
517
+ "session_conflict",
518
+ "Actor already has a live attachment"
519
+ );
520
+ }
521
+ const generation = Number(actor.generation) + 1;
522
+ if (!Number.isSafeInteger(generation)) {
523
+ throw new MailboxError(
524
+ "sequence_overflow",
525
+ "Attachment generation exceeds safe integer range"
526
+ );
527
+ }
528
+ if (activeId) {
529
+ store.database.run(
530
+ "UPDATE mailbox_sessions SET closed_at_ms = ? WHERE id = ?",
531
+ store.now(),
532
+ activeId
533
+ );
534
+ }
535
+ const binding = {
536
+ projectId: store.config.projectId,
537
+ actorId: credential.actorId,
538
+ sessionId: randomUUID2(),
539
+ generation,
540
+ secret: secret()
541
+ };
542
+ store.database.run(
543
+ "INSERT INTO mailbox_sessions(id, actor_id, generation, secret_hash, runtime, native_session_id, created_at_ms, heartbeat_at_ms, expires_at_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
544
+ binding.sessionId,
545
+ binding.actorId,
546
+ generation,
547
+ hash(binding.secret),
548
+ runtime,
549
+ nativeSessionId ?? null,
550
+ store.now(),
551
+ store.now(),
552
+ store.now() + PRESENCE_TTL_MS
553
+ );
554
+ store.database.run(
555
+ "UPDATE mailbox_actors SET generation = ?, active_session_id = ? WHERE id = ?",
556
+ generation,
557
+ binding.sessionId,
558
+ binding.actorId
559
+ );
560
+ return binding;
561
+ });
562
+ }
563
+
564
+ // src/mailbox/store/binding.ts
565
+ function assertBinding(store, binding) {
566
+ bindingSchema.parse(binding);
567
+ const session = store.database.get(
568
+ "SELECT s.*, a.active_session_id, a.parent_actor_id, a.parent_generation, a.authority_expires_at_ms FROM mailbox_sessions s JOIN mailbox_actors a ON a.id = s.actor_id WHERE s.id = ?",
569
+ binding.sessionId
570
+ );
571
+ if (binding.projectId !== store.config.projectId || !session || session.actor_id !== binding.actorId || session.secret_hash !== hash(binding.secret) || session.generation !== binding.generation || session.active_session_id !== binding.sessionId || session.closed_at_ms !== null || Number(session.expires_at_ms) <= store.now()) {
572
+ throw new MailboxError(
573
+ "stale_session",
574
+ "Attachment is invalid, expired or superseded"
575
+ );
576
+ }
577
+ if (session.parent_actor_id) {
578
+ if (Number(session.authority_expires_at_ms ?? 0) <= store.now()) {
579
+ throw new MailboxError(
580
+ "authority_expired",
581
+ "Child authority has expired"
582
+ );
583
+ }
584
+ const parent = store.database.get(
585
+ "SELECT a.generation, s.closed_at_ms, s.expires_at_ms FROM mailbox_actors a LEFT JOIN mailbox_sessions s ON s.id = a.active_session_id WHERE a.id = ?",
586
+ session.parent_actor_id
587
+ );
588
+ if (parent?.generation !== session.parent_generation || parent?.closed_at_ms !== null || Number(parent?.expires_at_ms ?? 0) <= store.now()) {
589
+ throw new MailboxError(
590
+ "stale_parent",
591
+ "Parent attachment is no longer current"
592
+ );
593
+ }
594
+ }
595
+ return session;
596
+ }
597
+
598
+ // src/mailbox/store/rotation.ts
599
+ function rotateActor(store, actorId, persist) {
600
+ actorIdSchema.parse(actorId);
601
+ return store.run(() => {
602
+ if (!store.database.get("SELECT id FROM mailbox_actors WHERE id = ?", actorId)) {
603
+ throw new MailboxError("unknown_actor", "Actor is not registered");
604
+ }
605
+ const credential = {
606
+ projectId: store.config.projectId,
607
+ actorId,
608
+ secret: secret()
609
+ };
610
+ store.database.run(
611
+ "UPDATE mailbox_sessions SET closed_at_ms = COALESCE(closed_at_ms, ?) WHERE actor_id = ?",
612
+ store.now(),
613
+ actorId
614
+ );
615
+ store.database.run(
616
+ "UPDATE mailbox_actors SET credential_hash = ?, credential_revision = credential_revision + 1, generation = generation + 1, active_session_id = NULL WHERE id = ?",
617
+ hash(credential.secret),
618
+ actorId
619
+ );
620
+ store.database.run(
621
+ "UPDATE mailbox_notifications SET state = 'stale', lease_token = NULL, lease_until_ms = NULL WHERE actor_id = ? AND state IN ('pending', 'leased')",
622
+ actorId
623
+ );
624
+ persist?.(credential);
625
+ return credential;
626
+ });
627
+ }
628
+
629
+ // src/mailbox/store/presence.ts
630
+ function heartbeat(store, binding) {
631
+ return store.run(() => {
632
+ store.assertBinding(binding);
633
+ store.database.run(
634
+ "UPDATE mailbox_sessions SET heartbeat_at_ms = ?, expires_at_ms = ? WHERE id = ?",
635
+ store.now(),
636
+ store.now() + PRESENCE_TTL_MS,
637
+ binding.sessionId
638
+ );
639
+ });
640
+ }
641
+ function detach(store, binding) {
642
+ return store.run(() => {
643
+ const session = store.database.get(
644
+ "SELECT secret_hash FROM mailbox_sessions WHERE id = ?",
645
+ binding.sessionId
646
+ );
647
+ if (binding.projectId !== store.config.projectId || session?.secret_hash !== hash(binding.secret)) {
648
+ throw new MailboxError(
649
+ "unauthorized",
650
+ "Attachment credential is invalid"
651
+ );
652
+ }
653
+ store.database.run(
654
+ "UPDATE mailbox_sessions SET closed_at_ms = COALESCE(closed_at_ms, ?) WHERE id = ?",
655
+ store.now(),
656
+ binding.sessionId
657
+ );
658
+ store.database.run(
659
+ "UPDATE mailbox_actors SET active_session_id = NULL WHERE id = ? AND active_session_id = ?",
660
+ binding.actorId,
661
+ binding.sessionId
662
+ );
663
+ });
664
+ }
665
+
666
+ // src/mailbox/store/export.ts
667
+ function exportRecords(store, actorId) {
668
+ if (actorId) {
669
+ actorIdSchema.parse(actorId);
670
+ }
671
+ return store.run(() => {
672
+ const where = actorId ? "WHERE m.sender_actor_id = ? OR EXISTS (SELECT 1 FROM mailbox_receipts r WHERE r.message_id = m.id AND r.actor_id = ?)" : "";
673
+ const values = actorId ? [actorId, actorId] : [];
674
+ const messages = store.database.all(
675
+ `SELECT m.* FROM mailbox_messages m ${where} ORDER BY m.seq`,
676
+ ...values
677
+ );
678
+ const records = [
679
+ {
680
+ type: "metadata",
681
+ version: 1,
682
+ projectId: store.config.projectId,
683
+ exportedAtMs: store.now(),
684
+ actorId: actorId ?? null
685
+ }
686
+ ];
687
+ for (const message of messages) {
688
+ const { payload_json: _payload, ...data } = message;
689
+ records.push({ type: "message", ...data });
690
+ for (const receipt2 of store.database.all(
691
+ "SELECT * FROM mailbox_receipts WHERE message_id = ? ORDER BY target_key",
692
+ message.id
693
+ )) {
694
+ records.push({ type: "receipt", ...receipt2 });
695
+ }
696
+ }
697
+ return records;
698
+ }, false);
699
+ }
700
+
701
+ // src/mailbox/store/core.ts
702
+ var MailboxStore = class _MailboxStore {
703
+ pending = Promise.resolve();
704
+ closed = false;
705
+ config;
706
+ database;
707
+ now;
708
+ constructor(config, database, now) {
709
+ this.config = config;
710
+ this.database = database;
711
+ this.now = now;
712
+ }
713
+ static async open(config, now = Date.now) {
714
+ if (!config.databasePath || !credentialSchema.shape.projectId.safeParse(config.projectId).success) {
715
+ throw new MailboxError(
716
+ "invalid_config",
717
+ "Provide a project UUID and database path"
718
+ );
719
+ }
720
+ if (!config.enabled) {
721
+ throw new MailboxError("mailbox_disabled", "Mailbox is disabled");
722
+ }
723
+ const database = await openDatabase(config.databasePath);
724
+ const store = new _MailboxStore(config, database, now);
725
+ try {
726
+ database.exec("PRAGMA busy_timeout = 1000");
727
+ database.exec("PRAGMA foreign_keys = ON");
728
+ await retryLocked(
729
+ database,
730
+ () => database.exec("PRAGMA journal_mode = WAL")
731
+ );
732
+ await transaction(database, () => {
733
+ const version = database.get("PRAGMA user_version")?.user_version;
734
+ if (version === 0) {
735
+ database.exec(SCHEMA_SQL);
736
+ database.run(
737
+ "INSERT INTO mailbox_project(id, created_at_ms) VALUES (?, ?)",
738
+ config.projectId,
739
+ now()
740
+ );
741
+ }
742
+ migrateDatabase(database);
743
+ store.checkSchema();
744
+ validateMigrations(database);
745
+ });
746
+ return store;
747
+ } catch (error) {
748
+ database.close();
749
+ throw error;
750
+ }
751
+ }
752
+ checkSchema() {
753
+ if (this.database.get("PRAGMA user_version")?.user_version !== SCHEMA_VERSION) {
754
+ throw new MailboxError(
755
+ "schema_incompatible",
756
+ "Mailbox schema version is not supported"
757
+ );
758
+ }
759
+ if (this.database.get("SELECT id FROM mailbox_project")?.id !== this.config.projectId) {
760
+ throw new MailboxError(
761
+ "project_mismatch",
762
+ "Mailbox database belongs to another project"
763
+ );
764
+ }
765
+ }
766
+ run(operation, write = true) {
767
+ if (this.closed) {
768
+ return Promise.reject(
769
+ new MailboxError("storage_unavailable", "Mailbox storage is closed")
770
+ );
771
+ }
772
+ const next = this.pending.then(
773
+ () => transaction(
774
+ this.database,
775
+ () => {
776
+ this.checkSchema();
777
+ return operation();
778
+ },
779
+ write
780
+ )
781
+ );
782
+ this.pending = next.catch(() => void 0);
783
+ return next;
784
+ }
785
+ registerActor(actorId, parentActorId, persist, authorityTtlMs = 6e4, parentBinding) {
786
+ return registerActor(
787
+ this,
788
+ actorId,
789
+ parentActorId,
790
+ persist,
791
+ authorityTtlMs,
792
+ parentBinding
793
+ );
794
+ }
795
+ registerChild(parent, actorId, ttlMs = 6e4) {
796
+ return this.registerActor(
797
+ actorId,
798
+ parent.actorId,
799
+ void 0,
800
+ ttlMs,
801
+ parent
802
+ );
803
+ }
804
+ attach(credential, runtime, replaceSessionId, nativeSessionId) {
805
+ return attach(this, credential, runtime, replaceSessionId, nativeSessionId);
806
+ }
807
+ assertBinding(binding) {
808
+ return assertBinding(this, binding);
809
+ }
810
+ rotateActor(actorId, persist) {
811
+ return rotateActor(this, actorId, persist);
812
+ }
813
+ heartbeat(binding) {
814
+ return heartbeat(this, binding);
815
+ }
816
+ detach(binding) {
817
+ return detach(this, binding);
818
+ }
819
+ exportRecords(actorId) {
820
+ return exportRecords(this, actorId);
821
+ }
822
+ async backup(destination) {
823
+ if (this.closed) {
824
+ throw new MailboxError(
825
+ "storage_unavailable",
826
+ "Mailbox storage is closed"
827
+ );
828
+ }
829
+ if (existsSync2(destination)) {
830
+ throw new MailboxError(
831
+ "destination_exists",
832
+ "Backup destination already exists"
833
+ );
834
+ }
835
+ const next = this.pending.then(() => {
836
+ this.checkSchema();
837
+ this.database.run("VACUUM INTO ?", destination);
838
+ chmodSync2(destination, 384);
839
+ });
840
+ this.pending = next.catch(() => void 0);
841
+ await next;
842
+ }
843
+ async close() {
844
+ if (this.closed) {
845
+ return;
846
+ }
847
+ this.closed = true;
848
+ await this.pending;
849
+ this.database.close();
850
+ }
851
+ };
852
+
853
+ // src/mailbox/store/restore.ts
854
+ import { chmodSync as chmodSync3, copyFileSync, constants as constants2, unlinkSync } from "fs";
855
+ async function restoreBackup(source, config) {
856
+ copyFileSync(source, config.databasePath, constants2.COPYFILE_EXCL);
857
+ let store;
858
+ try {
859
+ chmodSync3(config.databasePath, 384);
860
+ const probe = await openDatabase(config.databasePath);
861
+ try {
862
+ if (Number(probe.get("PRAGMA user_version")?.user_version) < 1 || Number(probe.get("PRAGMA user_version")?.user_version) > SCHEMA_VERSION || probe.get("SELECT id FROM mailbox_project")?.id !== config.projectId) {
863
+ throw new MailboxError(
864
+ "schema_incompatible",
865
+ "Backup schema or project is not compatible"
866
+ );
867
+ }
868
+ } finally {
869
+ probe.close();
870
+ }
871
+ store = await MailboxStore.open(config);
872
+ const integrity = store.database.get("PRAGMA integrity_check");
873
+ if (integrity?.integrity_check !== "ok" || store.database.all("PRAGMA foreign_key_check").length > 0) {
874
+ throw new MailboxError(
875
+ "storage_corrupt",
876
+ "Restored backup failed integrity checks"
877
+ );
878
+ }
879
+ } catch (error) {
880
+ await store?.close();
881
+ unlinkSync(config.databasePath);
882
+ throw error;
883
+ }
884
+ await store.close();
885
+ }
886
+
887
+ // src/mailbox/service/send.ts
888
+ import { randomUUID as randomUUID3 } from "crypto";
889
+
890
+ // src/mailbox/service/_shared.ts
891
+ function visibleMessage(context, messageId) {
892
+ const message = context.store.database.get(
893
+ "SELECT m.*, r.target_key, r.read_at_ms, r.ack_at_ms FROM mailbox_messages m JOIN mailbox_receipts r ON r.message_id = m.id WHERE m.id = ? AND r.actor_id = ? AND (r.session_id IS NULL OR r.session_id = ?) ORDER BY r.target_key LIMIT 1",
894
+ messageId,
895
+ context.binding.actorId,
896
+ context.binding.sessionId
897
+ );
898
+ if (!message) {
899
+ throw new MailboxError(
900
+ "unknown_message",
901
+ "Message is not available to context attachment"
902
+ );
903
+ }
904
+ return message;
905
+ }
906
+
907
+ // src/mailbox/service/send.ts
908
+ function send(context, input) {
909
+ return context.store.run(() => {
910
+ const session = context.store.assertBinding(context.binding);
911
+ const recipients = [
912
+ ...new Map(
913
+ input.recipients.map((recipient) => {
914
+ const sessionId = recipient.sessionId ?? null;
915
+ const key = `${recipient.actorId}/${sessionId ?? ""}`;
916
+ return [key, { actorId: recipient.actorId, sessionId, key }];
917
+ })
918
+ ).values()
919
+ ].sort((a, b) => a.key.localeCompare(b.key, "en"));
920
+ const payload = JSON.stringify({
921
+ body: input.body,
922
+ replyToId: input.replyToId ?? null,
923
+ recipients: recipients.map(({ key: _key, ...recipient }) => recipient)
924
+ });
925
+ const previous = context.store.database.get(
926
+ "SELECT id, seq, thread_id, payload_json FROM mailbox_messages WHERE sender_actor_id = ? AND idempotency_key = ?",
927
+ context.binding.actorId,
928
+ input.idempotencyKey
929
+ );
930
+ if (previous) {
931
+ if (previous.payload_json !== payload) {
932
+ throw new MailboxError(
933
+ "idempotency_conflict",
934
+ "Idempotency key was used for a different payload"
935
+ );
936
+ }
937
+ return {
938
+ messageId: previous.id,
939
+ seq: previous.seq,
940
+ threadId: previous.thread_id,
941
+ duplicate: true
942
+ };
943
+ }
944
+ for (const recipient of recipients) {
945
+ if (session.parent_actor_id && recipient.actorId !== session.parent_actor_id) {
946
+ throw new MailboxError(
947
+ "recipient_forbidden",
948
+ "Child actor may send only to its parent"
949
+ );
950
+ }
951
+ if (!context.store.database.get(
952
+ "SELECT id FROM mailbox_actors WHERE id = ?",
953
+ recipient.actorId
954
+ )) {
955
+ throw new MailboxError(
956
+ "unknown_actor",
957
+ "Recipient actor is not registered"
958
+ );
959
+ }
960
+ if (recipient.sessionId && !context.store.database.get(
961
+ "SELECT id FROM mailbox_sessions WHERE id = ? AND actor_id = ?",
962
+ recipient.sessionId,
963
+ recipient.actorId
964
+ )) {
965
+ throw new MailboxError(
966
+ "unknown_session",
967
+ "Recipient session does not belong to the actor"
968
+ );
969
+ }
970
+ }
971
+ const id = randomUUID3();
972
+ let threadId = id;
973
+ if (input.replyToId) {
974
+ const original = visibleMessage(context, input.replyToId);
975
+ threadId = original.thread_id;
976
+ if (original.read_at_ms === null) {
977
+ throw new MailboxError(
978
+ "reply_requires_read",
979
+ "Read the original message before replying"
980
+ );
981
+ }
982
+ }
983
+ context.store.database.run(
984
+ "INSERT INTO mailbox_messages(id, sender_actor_id, sender_session_id, idempotency_key, payload_json, body, thread_id, reply_to_id, created_at_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
985
+ id,
986
+ context.binding.actorId,
987
+ context.binding.sessionId,
988
+ input.idempotencyKey,
989
+ payload,
990
+ input.body,
991
+ threadId,
992
+ input.replyToId ?? null,
993
+ context.store.now()
994
+ );
995
+ const seq = context.store.database.get(
996
+ "SELECT seq FROM mailbox_messages WHERE id = ?",
997
+ id
998
+ )?.seq;
999
+ if (!Number.isSafeInteger(seq)) {
1000
+ throw new MailboxError(
1001
+ "sequence_overflow",
1002
+ "Message sequence exceeds safe integer range"
1003
+ );
1004
+ }
1005
+ for (const recipient of recipients) {
1006
+ context.store.database.run(
1007
+ "INSERT INTO mailbox_receipts(message_id, target_key, actor_id, session_id) VALUES (?, ?, ?, ?)",
1008
+ id,
1009
+ recipient.key,
1010
+ recipient.actorId,
1011
+ recipient.sessionId
1012
+ );
1013
+ }
1014
+ return { messageId: id, seq, threadId, duplicate: false };
1015
+ });
1016
+ }
1017
+
1018
+ // src/mailbox/service/inbox.ts
1019
+ function inbox(context, input) {
1020
+ return context.store.run(() => {
1021
+ context.store.assertBinding(context.binding);
1022
+ let after = 0;
1023
+ let upper = Number(
1024
+ context.store.database.get(
1025
+ "SELECT COALESCE(MAX(seq), 0) AS upper FROM mailbox_messages"
1026
+ )?.upper
1027
+ );
1028
+ if (!Number.isSafeInteger(upper)) {
1029
+ throw new MailboxError(
1030
+ "sequence_overflow",
1031
+ "Message sequence exceeds safe integer range"
1032
+ );
1033
+ }
1034
+ if (input.cursor) {
1035
+ let decoded;
1036
+ try {
1037
+ decoded = cursorSchema.parse(
1038
+ JSON.parse(Buffer.from(input.cursor, "base64url").toString("utf8"))
1039
+ );
1040
+ } catch {
1041
+ throw new MailboxError("invalid_cursor", "Cursor is malformed");
1042
+ }
1043
+ if (decoded.projectId !== context.binding.projectId || decoded.actorId !== context.binding.actorId || decoded.sessionId !== context.binding.sessionId || decoded.state !== input.state || decoded.threadId !== (input.threadId ?? null) || decoded.after > decoded.upper || decoded.upper > upper) {
1044
+ throw new MailboxError(
1045
+ "invalid_cursor",
1046
+ "Cursor does not match the current inbox scope"
1047
+ );
1048
+ }
1049
+ after = decoded.after;
1050
+ upper = decoded.upper;
1051
+ }
1052
+ const stateSql = input.state === "unread" ? "AND r.read_at_ms IS NULL" : "";
1053
+ const ackSql = input.state === "unacknowledged" ? "AND r.ack_at_ms IS NULL" : "";
1054
+ const threadSql = input.threadId ? "AND m.thread_id = ?" : "";
1055
+ const values = [
1056
+ context.binding.actorId,
1057
+ context.binding.sessionId,
1058
+ after,
1059
+ upper
1060
+ ];
1061
+ if (input.threadId) {
1062
+ values.push(input.threadId);
1063
+ }
1064
+ values.push(input.limit + 1);
1065
+ const rows = context.store.database.all(
1066
+ `SELECT DISTINCT m.seq, m.id AS messageId, m.sender_actor_id AS senderActorId, m.thread_id AS threadId, m.reply_to_id AS replyToId, m.created_at_ms AS createdAtMs FROM mailbox_messages m JOIN mailbox_receipts r ON r.message_id = m.id WHERE r.actor_id = ? AND (r.session_id IS NULL OR r.session_id = ?) AND m.seq > ? AND m.seq <= ? ${stateSql} ${ackSql} ${threadSql} ORDER BY m.seq LIMIT ?`,
1067
+ ...values
1068
+ );
1069
+ const items = rows.slice(0, input.limit);
1070
+ let nextCursor = null;
1071
+ if (rows.length > input.limit) {
1072
+ const cursor = {
1073
+ version: 1,
1074
+ projectId: context.binding.projectId,
1075
+ actorId: context.binding.actorId,
1076
+ sessionId: context.binding.sessionId,
1077
+ state: input.state,
1078
+ threadId: input.threadId ?? null,
1079
+ after: items.at(-1)?.seq,
1080
+ upper
1081
+ };
1082
+ nextCursor = Buffer.from(JSON.stringify(cursor)).toString("base64url");
1083
+ }
1084
+ return { items, nextCursor };
1085
+ }, false);
1086
+ }
1087
+
1088
+ // src/mailbox/service/receipt.ts
1089
+ function receipt(context, messageId, operation) {
1090
+ return context.store.run(() => {
1091
+ context.store.assertBinding(context.binding);
1092
+ const message = visibleMessage(context, messageId);
1093
+ if (operation === "ack" && message.read_at_ms === null) {
1094
+ throw new MailboxError(
1095
+ "ack_requires_read",
1096
+ "Read the message before acknowledging it"
1097
+ );
1098
+ }
1099
+ const column = operation === "read" ? "read_at_ms" : "ack_at_ms";
1100
+ context.store.database.run(
1101
+ `UPDATE mailbox_receipts SET ${column} = COALESCE(${column}, ?) WHERE message_id = ? AND actor_id = ? AND (session_id IS NULL OR session_id = ?)`,
1102
+ context.store.now(),
1103
+ messageId,
1104
+ context.binding.actorId,
1105
+ context.binding.sessionId
1106
+ );
1107
+ const current = visibleMessage(context, messageId);
1108
+ const data = {
1109
+ messageId,
1110
+ readAtMs: current.read_at_ms,
1111
+ ackAtMs: current.ack_at_ms
1112
+ };
1113
+ if (operation === "ack") {
1114
+ return data;
1115
+ }
1116
+ return {
1117
+ ...data,
1118
+ body: current.body,
1119
+ senderActorId: current.sender_actor_id,
1120
+ threadId: current.thread_id,
1121
+ replyToId: current.reply_to_id
1122
+ };
1123
+ });
1124
+ }
1125
+
1126
+ // src/mailbox/service/sessions.ts
1127
+ function sessions(context) {
1128
+ return context.store.run(() => {
1129
+ const session = context.store.assertBinding(context.binding);
1130
+ const scope = session.parent_actor_id ? "AND (s.actor_id = ? OR s.actor_id = ?)" : "";
1131
+ const values = session.parent_actor_id ? [
1132
+ context.store.now(),
1133
+ context.binding.actorId,
1134
+ session.parent_actor_id
1135
+ ] : [context.store.now()];
1136
+ const items = context.store.database.all(
1137
+ `SELECT s.id AS sessionId, s.actor_id AS actorId, s.runtime, s.native_session_id AS nativeSessionId, s.expires_at_ms AS expiresAtMs FROM mailbox_sessions s JOIN mailbox_actors a ON a.active_session_id = s.id WHERE s.closed_at_ms IS NULL AND s.expires_at_ms > ? ${scope} ORDER BY s.actor_id`,
1138
+ ...values
1139
+ );
1140
+ return { items };
1141
+ }, false);
1142
+ }
1143
+
1144
+ // src/mailbox/service/core.ts
1145
+ var MailboxService = class {
1146
+ store;
1147
+ binding;
1148
+ constructor(store, binding) {
1149
+ this.store = store;
1150
+ this.binding = binding;
1151
+ }
1152
+ async call(operation, input) {
1153
+ try {
1154
+ operationSchema.parse(operation);
1155
+ let data;
1156
+ if (operation === "send") {
1157
+ data = await this.send(sendSchema.parse(input));
1158
+ } else if (operation === "inbox") {
1159
+ data = await this.inbox(inboxSchema.parse(input));
1160
+ } else if (operation === "read" || operation === "ack") {
1161
+ data = await this.receipt(
1162
+ messageSchema.parse(input).messageId,
1163
+ operation
1164
+ );
1165
+ } else {
1166
+ sessionsSchema.parse(input);
1167
+ data = await this.sessions();
1168
+ }
1169
+ return { ok: true, data };
1170
+ } catch (error) {
1171
+ if (error instanceof Error && error.name === "ZodError") {
1172
+ return failure(
1173
+ new MailboxError(
1174
+ "invalid_input",
1175
+ "Mailbox input does not match the operation schema"
1176
+ )
1177
+ );
1178
+ }
1179
+ return failure(error);
1180
+ }
1181
+ }
1182
+ send(input) {
1183
+ return send(this, input);
1184
+ }
1185
+ inbox(input) {
1186
+ return inbox(this, input);
1187
+ }
1188
+ receipt(messageId, operation) {
1189
+ return receipt(this, messageId, operation);
1190
+ }
1191
+ sessions() {
1192
+ return sessions(this);
1193
+ }
1194
+ };
1195
+
1196
+ export {
1197
+ MailboxError,
1198
+ failure,
1199
+ mailboxConfigFrom,
1200
+ initializeMailboxConfig,
1201
+ readCredential,
1202
+ readBinding,
1203
+ writePrivateJson,
1204
+ writeBindingFile,
1205
+ SCHEMA_VERSION,
1206
+ openDatabase,
1207
+ PRESENCE_TTL_MS,
1208
+ HEARTBEAT_INTERVAL_MS,
1209
+ MailboxStore,
1210
+ restoreBackup,
1211
+ MailboxService
1212
+ };
1213
+ //# sourceMappingURL=chunk-CJTKR6K6.js.map