@agentshouse/mdruntime 0.1.0-cf1e7fdb9c600 → 0.1.0-cf26dc076c1a3

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 (355) hide show
  1. package/README.md +21 -19
  2. package/dist/acceptance.d.ts +3 -0
  3. package/dist/acceptance.d.ts.map +1 -0
  4. package/dist/acceptance.js +328 -0
  5. package/dist/act-lanes.d.ts +30 -0
  6. package/dist/act-lanes.d.ts.map +1 -0
  7. package/dist/act-lanes.js +225 -0
  8. package/dist/actions.d.ts +26 -0
  9. package/dist/actions.d.ts.map +1 -0
  10. package/dist/actions.js +341 -0
  11. package/dist/adapter.d.ts +211 -95
  12. package/dist/adapter.d.ts.map +1 -1
  13. package/dist/attached-model.d.ts +3 -11
  14. package/dist/attached-model.d.ts.map +1 -1
  15. package/dist/attached-model.js +20 -60
  16. package/dist/{binary.d.ts → attachment.d.ts} +8 -4
  17. package/dist/attachment.d.ts.map +1 -0
  18. package/dist/attachment.js +15 -0
  19. package/dist/authored.d.ts +88 -0
  20. package/dist/authored.d.ts.map +1 -0
  21. package/dist/authored.js +347 -0
  22. package/dist/bootstrap.d.ts +9 -5
  23. package/dist/bootstrap.d.ts.map +1 -1
  24. package/dist/bootstrap.js +204 -86
  25. package/dist/cell.d.ts +6 -0
  26. package/dist/cell.d.ts.map +1 -0
  27. package/dist/cell.js +9 -0
  28. package/dist/chain.d.ts +1 -1
  29. package/dist/chain.d.ts.map +1 -1
  30. package/dist/chain.js +5 -2
  31. package/dist/change-set.d.ts +4 -0
  32. package/dist/change-set.d.ts.map +1 -1
  33. package/dist/change-set.js +6 -0
  34. package/dist/change.d.ts +7 -2
  35. package/dist/change.d.ts.map +1 -1
  36. package/dist/change.js +7 -2
  37. package/dist/chat-types.d.ts +3 -0
  38. package/dist/chat-types.d.ts.map +1 -0
  39. package/dist/chat-types.js +11 -0
  40. package/dist/client.d.ts +45 -24
  41. package/dist/client.d.ts.map +1 -1
  42. package/dist/client.js +58 -68
  43. package/dist/collection.d.ts +27 -4
  44. package/dist/collection.d.ts.map +1 -1
  45. package/dist/collection.js +34 -10
  46. package/dist/column.d.ts +5 -0
  47. package/dist/column.d.ts.map +1 -0
  48. package/dist/column.js +9 -0
  49. package/dist/compile.d.ts +9 -1
  50. package/dist/compile.d.ts.map +1 -1
  51. package/dist/compile.js +286 -120
  52. package/dist/connection.d.ts +6 -142
  53. package/dist/connection.d.ts.map +1 -1
  54. package/dist/connection.js +115 -5283
  55. package/dist/context.d.ts.map +1 -1
  56. package/dist/context.js +1 -1
  57. package/dist/conversation-live.d.ts +150 -0
  58. package/dist/conversation-live.d.ts.map +1 -0
  59. package/dist/conversation-live.js +260 -0
  60. package/dist/conversation-row.d.ts +40 -0
  61. package/dist/conversation-row.d.ts.map +1 -0
  62. package/dist/conversation-row.js +66 -0
  63. package/dist/conversation.d.ts +72 -47
  64. package/dist/conversation.d.ts.map +1 -1
  65. package/dist/conversation.js +1004 -901
  66. package/dist/declaration.d.ts +10 -0
  67. package/dist/declaration.d.ts.map +1 -0
  68. package/dist/declaration.js +24 -0
  69. package/dist/discovery.d.ts +12 -0
  70. package/dist/discovery.d.ts.map +1 -0
  71. package/dist/discovery.js +175 -0
  72. package/dist/download.d.ts +6 -0
  73. package/dist/download.d.ts.map +1 -0
  74. package/dist/download.js +42 -0
  75. package/dist/durability.d.ts +20 -0
  76. package/dist/durability.d.ts.map +1 -1
  77. package/dist/durability.js +7 -0
  78. package/dist/entry.d.ts +25 -1
  79. package/dist/entry.d.ts.map +1 -1
  80. package/dist/entry.js +111 -33
  81. package/dist/expectation.d.ts +26 -13
  82. package/dist/expectation.d.ts.map +1 -1
  83. package/dist/expectation.js +72 -19
  84. package/dist/failure.d.ts +3 -0
  85. package/dist/failure.d.ts.map +1 -1
  86. package/dist/failure.js +8 -0
  87. package/dist/figures.d.ts +49 -0
  88. package/dist/figures.d.ts.map +1 -0
  89. package/dist/figures.js +199 -0
  90. package/dist/file.d.ts +1 -1
  91. package/dist/file.d.ts.map +1 -1
  92. package/dist/file.js +3 -2
  93. package/dist/holdings.d.ts +29 -0
  94. package/dist/holdings.d.ts.map +1 -0
  95. package/dist/holdings.js +95 -0
  96. package/dist/host.d.ts +25 -4
  97. package/dist/host.d.ts.map +1 -1
  98. package/dist/host.js +119 -36
  99. package/dist/house-query.d.ts +24 -0
  100. package/dist/house-query.d.ts.map +1 -0
  101. package/dist/house-query.js +102 -0
  102. package/dist/identity.d.ts +1 -2
  103. package/dist/identity.d.ts.map +1 -1
  104. package/dist/identity.js +1 -4
  105. package/dist/index.d.ts +43 -16
  106. package/dist/index.d.ts.map +1 -1
  107. package/dist/index.js +21 -7
  108. package/dist/install.d.ts +60 -0
  109. package/dist/install.d.ts.map +1 -0
  110. package/dist/install.js +537 -0
  111. package/dist/lifecycle.d.ts +7 -0
  112. package/dist/lifecycle.d.ts.map +1 -0
  113. package/dist/lifecycle.js +292 -0
  114. package/dist/listing.d.ts +60 -0
  115. package/dist/listing.d.ts.map +1 -0
  116. package/dist/listing.js +168 -0
  117. package/dist/live.d.ts +22 -6
  118. package/dist/live.d.ts.map +1 -1
  119. package/dist/live.js +130 -34
  120. package/dist/loaded.d.ts +7 -0
  121. package/dist/loaded.d.ts.map +1 -0
  122. package/dist/loaded.js +46 -0
  123. package/dist/locks.d.ts +7 -0
  124. package/dist/locks.d.ts.map +1 -0
  125. package/dist/locks.js +34 -0
  126. package/dist/lost.d.ts +5 -0
  127. package/dist/lost.d.ts.map +1 -0
  128. package/dist/lost.js +49 -0
  129. package/dist/media.d.ts +20 -4
  130. package/dist/media.d.ts.map +1 -1
  131. package/dist/media.js +184 -37
  132. package/dist/memory.d.ts +12 -4
  133. package/dist/memory.d.ts.map +1 -1
  134. package/dist/memory.js +141 -41
  135. package/dist/messages.d.ts +38 -3
  136. package/dist/messages.d.ts.map +1 -1
  137. package/dist/messages.js +105 -25
  138. package/dist/modal.d.ts +2 -0
  139. package/dist/modal.d.ts.map +1 -0
  140. package/dist/modal.js +11 -0
  141. package/dist/model.d.ts +11 -15
  142. package/dist/model.d.ts.map +1 -1
  143. package/dist/model.js +6 -11
  144. package/dist/models.d.ts +10 -0
  145. package/dist/models.d.ts.map +1 -0
  146. package/dist/models.js +153 -0
  147. package/dist/name.d.ts +0 -1
  148. package/dist/name.d.ts.map +1 -1
  149. package/dist/name.js +3 -7
  150. package/dist/observation.d.ts +29 -12
  151. package/dist/observation.d.ts.map +1 -1
  152. package/dist/observation.js +217 -85
  153. package/dist/online.d.ts +7 -0
  154. package/dist/online.d.ts.map +1 -0
  155. package/dist/online.js +29 -0
  156. package/dist/opened.d.ts +6 -6
  157. package/dist/opened.d.ts.map +1 -1
  158. package/dist/opened.js +7 -7
  159. package/dist/opening.d.ts +4 -0
  160. package/dist/opening.d.ts.map +1 -0
  161. package/dist/opening.js +71 -0
  162. package/dist/outcome.d.ts +37 -14
  163. package/dist/outcome.d.ts.map +1 -1
  164. package/dist/outcome.js +39 -6
  165. package/dist/overlay.d.ts +24 -8
  166. package/dist/overlay.d.ts.map +1 -1
  167. package/dist/overlay.js +143 -48
  168. package/dist/page-metadata.d.ts +8 -0
  169. package/dist/page-metadata.d.ts.map +1 -0
  170. package/dist/page-metadata.js +19 -0
  171. package/dist/parts.d.ts +6 -0
  172. package/dist/parts.d.ts.map +1 -0
  173. package/dist/parts.js +36 -0
  174. package/dist/paths.d.ts +1 -0
  175. package/dist/paths.d.ts.map +1 -1
  176. package/dist/paths.js +22 -0
  177. package/dist/preparation.d.ts +46 -0
  178. package/dist/preparation.d.ts.map +1 -0
  179. package/dist/preparation.js +344 -0
  180. package/dist/presence.d.ts +58 -0
  181. package/dist/presence.d.ts.map +1 -0
  182. package/dist/presence.js +231 -0
  183. package/dist/queries.d.ts +16 -0
  184. package/dist/queries.d.ts.map +1 -0
  185. package/dist/queries.js +330 -0
  186. package/dist/query.d.ts +12 -4
  187. package/dist/query.d.ts.map +1 -1
  188. package/dist/questions.d.ts +30 -0
  189. package/dist/questions.d.ts.map +1 -0
  190. package/dist/questions.js +117 -0
  191. package/dist/queue.d.ts +40 -0
  192. package/dist/queue.d.ts.map +1 -0
  193. package/dist/queue.js +480 -0
  194. package/dist/reach.d.ts +20 -9
  195. package/dist/reach.d.ts.map +1 -1
  196. package/dist/reach.js +346 -127
  197. package/dist/react.d.ts +24 -2
  198. package/dist/react.d.ts.map +1 -1
  199. package/dist/react.js +33 -1
  200. package/dist/read.d.ts +7 -0
  201. package/dist/read.d.ts.map +1 -0
  202. package/dist/read.js +17 -0
  203. package/dist/readiness.d.ts +23 -5
  204. package/dist/readiness.d.ts.map +1 -1
  205. package/dist/readiness.js +18 -10
  206. package/dist/reads.d.ts +39 -0
  207. package/dist/reads.d.ts.map +1 -0
  208. package/dist/reads.js +189 -0
  209. package/dist/recovery.d.ts +4 -1
  210. package/dist/recovery.d.ts.map +1 -1
  211. package/dist/recovery.js +40 -9
  212. package/dist/reference-forms.d.ts +4 -0
  213. package/dist/reference-forms.d.ts.map +1 -0
  214. package/dist/reference-forms.js +74 -0
  215. package/dist/refresh.d.ts +1 -1
  216. package/dist/refresh.d.ts.map +1 -1
  217. package/dist/refresh.js +14 -26
  218. package/dist/refusal.d.ts +5 -0
  219. package/dist/refusal.d.ts.map +1 -0
  220. package/dist/refusal.js +55 -0
  221. package/dist/replica.d.ts +11 -22
  222. package/dist/replica.d.ts.map +1 -1
  223. package/dist/replica.js +68 -38
  224. package/dist/retried.d.ts +30 -0
  225. package/dist/retried.d.ts.map +1 -0
  226. package/dist/retried.js +72 -0
  227. package/dist/room-draft.d.ts +33 -10
  228. package/dist/room-draft.d.ts.map +1 -1
  229. package/dist/room-draft.js +282 -72
  230. package/dist/room-drafts.d.ts +24 -0
  231. package/dist/room-drafts.d.ts.map +1 -0
  232. package/dist/room-drafts.js +222 -0
  233. package/dist/room-list.d.ts +10 -0
  234. package/dist/room-list.d.ts.map +1 -0
  235. package/dist/room-list.js +47 -0
  236. package/dist/rows.d.ts +24 -6
  237. package/dist/rows.d.ts.map +1 -1
  238. package/dist/rows.js +65 -60
  239. package/dist/run-tables.d.ts +25 -0
  240. package/dist/run-tables.d.ts.map +1 -0
  241. package/dist/run-tables.js +94 -0
  242. package/dist/running.d.ts +5 -0
  243. package/dist/running.d.ts.map +1 -0
  244. package/dist/running.js +10 -0
  245. package/dist/runs.d.ts +27 -0
  246. package/dist/runs.d.ts.map +1 -0
  247. package/dist/runs.js +90 -0
  248. package/dist/runtime.d.ts +37 -0
  249. package/dist/runtime.d.ts.map +1 -0
  250. package/dist/runtime.js +1 -0
  251. package/dist/save.d.ts +43 -86
  252. package/dist/save.d.ts.map +1 -1
  253. package/dist/save.js +332 -228
  254. package/dist/saves.d.ts +34 -0
  255. package/dist/saves.d.ts.map +1 -0
  256. package/dist/saves.js +463 -0
  257. package/dist/seed.d.ts +11 -2
  258. package/dist/seed.d.ts.map +1 -1
  259. package/dist/seed.js +71 -1
  260. package/dist/selector.d.ts +3 -0
  261. package/dist/selector.d.ts.map +1 -0
  262. package/dist/selector.js +22 -0
  263. package/dist/shared.d.ts +1 -6
  264. package/dist/shared.d.ts.map +1 -1
  265. package/dist/shared.js +13 -95
  266. package/dist/shown.d.ts +35 -0
  267. package/dist/shown.d.ts.map +1 -0
  268. package/dist/shown.js +326 -0
  269. package/dist/socket/admission.d.ts +7 -0
  270. package/dist/socket/admission.d.ts.map +1 -0
  271. package/dist/socket/admission.js +39 -0
  272. package/dist/socket/answers.d.ts +6 -0
  273. package/dist/socket/answers.d.ts.map +1 -0
  274. package/dist/socket/answers.js +20 -0
  275. package/dist/socket/lanes.d.ts +28 -0
  276. package/dist/socket/lanes.d.ts.map +1 -0
  277. package/dist/socket/lanes.js +103 -0
  278. package/dist/socket/reads.d.ts +10 -0
  279. package/dist/socket/reads.d.ts.map +1 -0
  280. package/dist/socket/reads.js +31 -0
  281. package/dist/socket/session.d.ts +41 -0
  282. package/dist/socket/session.d.ts.map +1 -0
  283. package/dist/socket/session.js +26 -0
  284. package/dist/socket.d.ts +70 -0
  285. package/dist/socket.d.ts.map +1 -0
  286. package/dist/socket.js +172 -0
  287. package/dist/source.d.ts +61 -0
  288. package/dist/source.d.ts.map +1 -0
  289. package/dist/source.js +95 -0
  290. package/dist/status.d.ts +0 -2
  291. package/dist/status.d.ts.map +1 -1
  292. package/dist/status.js +0 -6
  293. package/dist/store/installs.d.ts +30 -0
  294. package/dist/store/installs.d.ts.map +1 -0
  295. package/dist/store/installs.js +40 -0
  296. package/dist/store/readiness.d.ts +11 -0
  297. package/dist/store/readiness.d.ts.map +1 -0
  298. package/dist/store/readiness.js +68 -0
  299. package/dist/store/records.d.ts +234 -0
  300. package/dist/store/records.d.ts.map +1 -0
  301. package/dist/store/records.js +474 -0
  302. package/dist/store/room-held.d.ts +8 -0
  303. package/dist/store/room-held.d.ts.map +1 -0
  304. package/dist/store/room-held.js +17 -0
  305. package/dist/store/rooms-shown.d.ts +8 -0
  306. package/dist/store/rooms-shown.d.ts.map +1 -0
  307. package/dist/store/rooms-shown.js +13 -0
  308. package/dist/store/space.d.ts +11 -0
  309. package/dist/store/space.d.ts.map +1 -0
  310. package/dist/store/space.js +41 -0
  311. package/dist/store/watchers.d.ts +17 -0
  312. package/dist/store/watchers.d.ts.map +1 -0
  313. package/dist/store/watchers.js +56 -0
  314. package/dist/store/writes.d.ts +24 -0
  315. package/dist/store/writes.d.ts.map +1 -0
  316. package/dist/store/writes.js +125 -0
  317. package/dist/store.d.ts +116 -152
  318. package/dist/store.d.ts.map +1 -1
  319. package/dist/store.js +174 -395
  320. package/dist/stored.d.ts +89 -70
  321. package/dist/stored.d.ts.map +1 -1
  322. package/dist/stored.js +438 -174
  323. package/dist/surface.d.ts +100 -0
  324. package/dist/surface.d.ts.map +1 -0
  325. package/dist/surface.js +258 -0
  326. package/dist/sync.d.ts +21 -0
  327. package/dist/sync.d.ts.map +1 -0
  328. package/dist/sync.js +557 -0
  329. package/dist/tables.d.ts +135 -87
  330. package/dist/tables.d.ts.map +1 -1
  331. package/dist/tables.js +216 -283
  332. package/dist/tallies.d.ts +18 -0
  333. package/dist/tallies.d.ts.map +1 -0
  334. package/dist/tallies.js +128 -0
  335. package/dist/validation.d.ts +2 -0
  336. package/dist/validation.d.ts.map +1 -1
  337. package/dist/validation.js +53 -13
  338. package/dist/wire.d.ts +87 -12
  339. package/dist/wire.d.ts.map +1 -1
  340. package/dist/wire.js +37 -14
  341. package/package.json +4 -3
  342. package/dist/attempt.d.ts +0 -16
  343. package/dist/attempt.d.ts.map +0 -1
  344. package/dist/attempt.js +0 -70
  345. package/dist/binary.d.ts.map +0 -1
  346. package/dist/binary.js +0 -8
  347. package/dist/fence.d.ts +0 -6
  348. package/dist/fence.d.ts.map +0 -1
  349. package/dist/fence.js +0 -10
  350. package/dist/job.d.ts +0 -14
  351. package/dist/job.d.ts.map +0 -1
  352. package/dist/job.js +0 -28
  353. package/dist/log.d.ts +0 -5
  354. package/dist/log.d.ts.map +0 -1
  355. package/dist/log.js +0 -14
package/dist/memory.js CHANGED
@@ -1,11 +1,20 @@
1
+ import { definitionAt, documentFacts, keyedDestination, keyedLink, parse, } from '@agentshouse/mdmodel';
2
+ import { NO_ROOM_TYPES, schemaTypes } from './attached-model.js';
3
+ import { selected } from './collection.js';
4
+ import { declaredType } from './outcome.js';
1
5
  import { sameChange } from './overlay.js';
2
6
  const ATTACHMENTS = 'attachments';
7
+ const UNFOUND = {
8
+ kind: 'rejected',
9
+ code: 'not_found',
10
+ fields: {},
11
+ retryable: false,
12
+ };
3
13
  function lastName(path) {
4
14
  return path.slice(path.lastIndexOf('/') + 1);
5
15
  }
6
16
  const FIXTURE_RETENTION = {
7
17
  history: { kind: 'duration', seconds: 1 },
8
- outcome: 604_800,
9
18
  refreshHorizon: 1,
10
19
  };
11
20
  function declaredRetention(value) {
@@ -52,9 +61,10 @@ export function createMemoryAdapter(options = {}) {
52
61
  const listeners = new Set();
53
62
  const modeObservers = new Set();
54
63
  const scripted = new Map();
55
- const sentTurns = new Map();
64
+ const repeats = new Map();
56
65
  const historyPageSize = options.historyPageSize;
57
66
  const attached = new Map();
67
+ const keyed = new Map();
58
68
  const linked = new WeakMap();
59
69
  const carried = new Map();
60
70
  let expiring = [];
@@ -62,6 +72,7 @@ export function createMemoryAdapter(options = {}) {
62
72
  const declaredRooms = new Set();
63
73
  let replicated = [];
64
74
  let heldCursor = null;
75
+ let agents = structuredClone(options.agents ?? []);
65
76
  let issued = 0;
66
77
  function scriptConversations(entries) {
67
78
  scripted.clear();
@@ -89,21 +100,72 @@ export function createMemoryAdapter(options = {}) {
89
100
  const wanted = ordinals.get(`${locator}\u0000${target}`);
90
101
  return held !== undefined && wanted !== undefined && held >= wanted;
91
102
  }
92
- function heldBlob(room, path) {
103
+ function heldBytes(room, path) {
93
104
  return attached.get(`${room.locator}\u0000${path}`) ?? room.blobs?.[path];
94
105
  }
106
+ function linkTo(room, path) {
107
+ const blob = room === undefined ? undefined : heldBytes(room, path);
108
+ if (blob === undefined)
109
+ return UNFOUND;
110
+ const url = linked.get(blob) ?? URL.createObjectURL(blob);
111
+ linked.set(blob, url);
112
+ return { kind: 'link', url, name: lastName(path), mediaType: declaredType(blob) };
113
+ }
114
+ function attachedKeyed(request) {
115
+ const room = rooms.find((entry) => entry.locator === options.privateRoom);
116
+ if (room === undefined) {
117
+ return { kind: 'rejected', code: 'room_not_found', fields: {}, retryable: false };
118
+ }
119
+ const path = freePath(room, request.name);
120
+ attached.set(`${room.locator}\u0000${path}`, request.blob);
121
+ const key = `memory-${keyed.size + 1}`;
122
+ keyed.set(key, { locator: room.locator, path });
123
+ return { kind: 'linked', link: keyedDestination(`/rooms/${room.handle}/${path}`, key) };
124
+ }
95
125
  function freePath(room, name) {
96
126
  const dot = name.lastIndexOf('.');
97
127
  const stem = dot > 0 ? name.slice(0, dot) : name;
98
128
  const extension = dot > 0 ? name.slice(dot) : '';
99
129
  for (let count = 1;; count += 1) {
100
130
  const path = `${ATTACHMENTS}/${count === 1 ? stem : `${stem}-${count}`}${extension}`;
101
- if (heldBlob(room, path) === undefined && room.documents?.[path] === undefined)
131
+ if (heldBytes(room, path) === undefined && room.documents?.[path] === undefined)
102
132
  return path;
103
133
  }
104
134
  }
135
+ const saved = new WeakMap();
136
+ const roomTypes = options.roomTypes ?? NO_ROOM_TYPES;
137
+ function factsAt(room, path, content) {
138
+ const types = selected({ selection: room.typedSelection ?? null }, path)
139
+ ? roomTypes.types
140
+ : schemaTypes(room.model?.kind === 'model' ? room.model.snapshot.schema : null, roomTypes);
141
+ let held = saved.get(types);
142
+ if (held === undefined) {
143
+ held = new Map();
144
+ saved.set(types, held);
145
+ }
146
+ const key = `${path}\u0000${content}`;
147
+ if (!held.has(key)) {
148
+ const facts = documentFacts(path, parse(content, path, definitionAt({ types }, path, options.typedPaths)), {
149
+ types,
150
+ });
151
+ held.set(key, facts === null ? null : JSON.parse(JSON.stringify(facts)));
152
+ }
153
+ return held.get(key);
154
+ }
155
+ function factsIn(room, paths) {
156
+ const facts = {};
157
+ for (const path of paths) {
158
+ const content = room.documents?.[path];
159
+ const held = room.facts?.[path] ?? (content === undefined ? null : factsAt(room, path, content));
160
+ if (held !== null)
161
+ facts[path] = held;
162
+ }
163
+ return facts;
164
+ }
105
165
  function retain(entries) {
106
166
  for (const room of entries) {
167
+ for (const [path, content] of Object.entries(room.documents ?? {}))
168
+ factsAt(room, path, content);
107
169
  note(room.locator, room);
108
170
  const versions = served.get(room.locator) ?? new Map();
109
171
  versions.set(room.roomVersion, room);
@@ -119,8 +181,9 @@ export function createMemoryAdapter(options = {}) {
119
181
  roomVersion: room.roomVersion,
120
182
  operations: room.operations,
121
183
  replica: room.replica,
122
- ...(room.typedSelection === undefined ? {} : { typedSelection: room.typedSelection }),
184
+ typedSelection: room.typedSelection ?? null,
123
185
  providerOwnedPaths: room.providerOwnedPaths,
186
+ authoredPaths: room.authoredPaths ?? ['**'],
124
187
  };
125
188
  }
126
189
  function page(room, after) {
@@ -130,18 +193,22 @@ export function createMemoryAdapter(options = {}) {
130
193
  const size = pageSize ?? paths.length;
131
194
  const taken = paths.slice(from, from + size);
132
195
  const next = from + taken.length;
133
- const targets = opening ? Object.keys(room.binaryFiles ?? {}) : [];
196
+ const targets = opening ? Object.keys(room.attachments ?? {}) : [];
134
197
  return {
135
198
  kind: 'bootstrap',
136
199
  roomVersion: room.roomVersion,
137
200
  ...(opening ? { models: modelsOf(room) } : {}),
138
201
  documents: named(room.documents ?? {}, taken),
202
+ facts: factsIn(room, taken),
139
203
  revisions: named(room.revisions ?? {}, [...taken, ...targets]),
140
204
  ...(room.fileIds === undefined
141
205
  ? {}
142
206
  : { fileIds: named(room.fileIds, [...taken, ...targets]) }),
207
+ ...(room.created === undefined
208
+ ? {}
209
+ : { created: named(room.created, [...taken, ...targets]) }),
143
210
  changes: named(room.changes ?? {}, [...taken, ...targets]),
144
- binaryFiles: named(room.binaryFiles ?? {}, targets),
211
+ attachments: named(room.attachments ?? {}, targets),
145
212
  ...(opening && room.folders !== undefined ? { folders: room.folders } : {}),
146
213
  ...(next < paths.length ? { pageToken: taken.at(-1) } : {}),
147
214
  };
@@ -159,10 +226,11 @@ export function createMemoryAdapter(options = {}) {
159
226
  function advancement(room, from, at, whole = false) {
160
227
  const current = room.documents ?? {};
161
228
  const previous = from.documents ?? {};
162
- const currentTargets = new Set(Object.keys(room.binaryFiles ?? {}));
163
- const previousTargets = new Set(Object.keys(from.binaryFiles ?? {}));
229
+ const currentTargets = new Set(Object.keys(room.attachments ?? {}));
230
+ const previousTargets = new Set(Object.keys(from.attachments ?? {}));
164
231
  const headMoved = (path) => room.revisions?.[path] !== from.revisions?.[path] ||
165
232
  room.fileIds?.[path] !== from.fileIds?.[path] ||
233
+ room.created?.[path] !== from.created?.[path] ||
166
234
  !sameChange(room.changes?.[path], from.changes?.[path]);
167
235
  const changed = Object.keys(current)
168
236
  .filter((path) => current[path] !== previous[path] || headMoved(path))
@@ -183,12 +251,16 @@ export function createMemoryAdapter(options = {}) {
183
251
  roomVersion: room.roomVersion,
184
252
  ...(models === undefined ? {} : { models }),
185
253
  documents: named(current, taken),
254
+ facts: factsIn(room, taken),
186
255
  revisions: named(room.revisions ?? {}, [...taken, ...targets]),
187
256
  ...(room.fileIds === undefined
188
257
  ? {}
189
258
  : { fileIds: named(room.fileIds, [...taken, ...targets]) }),
259
+ ...(room.created === undefined
260
+ ? {}
261
+ : { created: named(room.created, [...taken, ...targets]) }),
190
262
  changes: named(room.changes ?? {}, [...taken, ...targets]),
191
- binaryFiles: named(room.binaryFiles ?? {}, targets),
263
+ attachments: named(room.attachments ?? {}, targets),
192
264
  ...(opening ? foldersMoved(room, from) : {}),
193
265
  removals: opening
194
266
  ? [
@@ -221,16 +293,14 @@ export function createMemoryAdapter(options = {}) {
221
293
  }
222
294
  function pageOf(conversation, after) {
223
295
  const messages = conversation.messages ?? [];
224
- const first = typeof after === 'string' ? messages.findIndex((message) => message.position > after) : 0;
296
+ const first = typeof after === 'string' ? messages.findIndex((message) => message.change > after) : 0;
225
297
  const from = first === -1 ? messages.length : first;
226
298
  const page = messages.slice(from, from + (historyPageSize ?? messages.length));
227
299
  const last = page.at(-1);
228
300
  return {
229
301
  conversation: conversation.conversation,
230
302
  messages: page,
231
- ...(last !== undefined && from + page.length < messages.length
232
- ? { next: last.position }
233
- : {}),
303
+ ...(last !== undefined && from + page.length < messages.length ? { next: last.change } : {}),
234
304
  };
235
305
  }
236
306
  function historiesOf(request) {
@@ -250,11 +320,20 @@ export function createMemoryAdapter(options = {}) {
250
320
  function conversationAction(request) {
251
321
  const name = request.name;
252
322
  const input = (request.input ?? {});
323
+ const operation = typeof input.operation_id === 'string' ? `${name}\u0000${input.operation_id}` : null;
324
+ const first = (answer) => {
325
+ if (operation !== null)
326
+ repeats.set(operation, answer);
327
+ return answer;
328
+ };
329
+ const repeated = operation === null ? undefined : repeats.get(operation);
253
330
  if (name === 'conversations/create') {
331
+ if (repeated !== undefined)
332
+ return repeated;
254
333
  issued += 1;
255
334
  const conversation = `conversation-${issued}`;
256
335
  scripted.set(conversation, { conversation });
257
- return { kind: 'action', result: { conversation_id: conversation } };
336
+ return first({ kind: 'action', result: { conversation_id: conversation } });
258
337
  }
259
338
  const named = typeof input.conversation_id === 'string' ? input.conversation_id : '';
260
339
  const conversation = scripted.get(named);
@@ -270,26 +349,39 @@ export function createMemoryAdapter(options = {}) {
270
349
  if (outcome !== undefined)
271
350
  return outcome;
272
351
  if (name === 'conversations/send') {
273
- const operation = typeof input.operation_id === 'string' ? input.operation_id : null;
274
- const answered = operation === null ? undefined : sentTurns.get(operation);
275
- if (answered !== undefined)
276
- return { kind: 'action', result: { message_id: answered } };
352
+ if (repeated !== undefined)
353
+ return repeated;
277
354
  issued += 1;
278
- const turn = `turn-${issued}`;
279
- if (operation !== null)
280
- sentTurns.set(operation, turn);
281
- return { kind: 'action', result: { message_id: turn } };
355
+ return first({ kind: 'action', result: { message_id: `turn-${issued}` } });
282
356
  }
283
357
  if (name === 'conversations/delete')
284
358
  scripted.delete(named);
285
359
  return { kind: 'action', result: { conversation_id: named } };
286
360
  }
361
+ function decided(request) {
362
+ const { request: asked, message, decision, } = (request.input ?? {});
363
+ return {
364
+ kind: 'action',
365
+ result: {
366
+ request: asked,
367
+ ...(message === undefined ? {} : { message }),
368
+ state: decision === 'approve' ? 'started' : 'declined',
369
+ },
370
+ };
371
+ }
287
372
  function announceList() {
288
373
  const entries = [...scripted.values()].flatMap(({ conversation, listed, messages = [] }) => listed === undefined
289
374
  ? []
290
- : [{ conversation, ...listed, newest: messages.at(-1)?.position ?? null }]);
375
+ : [{ conversation, ...listed, newest: messages.at(-1)?.change ?? null }]);
291
376
  for (const listener of listeners) {
292
- listener({ kind: 'list', entries, whole: true, more: false, cursor: null });
377
+ listener({
378
+ kind: 'list',
379
+ agents: structuredClone(agents),
380
+ entries,
381
+ whole: true,
382
+ more: false,
383
+ cursor: null,
384
+ });
293
385
  }
294
386
  }
295
387
  function discovery() {
@@ -300,6 +392,7 @@ export function createMemoryAdapter(options = {}) {
300
392
  providerLimits,
301
393
  retention,
302
394
  ...(options.member === undefined ? {} : { member: options.member }),
395
+ ...(options.timeZone === undefined ? {} : { timeZone: options.timeZone }),
303
396
  };
304
397
  }
305
398
  function discovered() {
@@ -345,6 +438,9 @@ export function createMemoryAdapter(options = {}) {
345
438
  setConversations(next) {
346
439
  scriptConversations(next);
347
440
  },
441
+ setAgents(next) {
442
+ agents = structuredClone(next);
443
+ },
348
444
  open() {
349
445
  carried.clear();
350
446
  announceList();
@@ -374,6 +470,7 @@ export function createMemoryAdapter(options = {}) {
374
470
  rooms: listed.map(declared),
375
471
  left,
376
472
  ...(options.member === undefined ? {} : { member: options.member }),
473
+ ...(options.timeZone === undefined ? {} : { timeZone: options.timeZone }),
377
474
  });
378
475
  },
379
476
  notifyConversation(event) {
@@ -407,9 +504,6 @@ export function createMemoryAdapter(options = {}) {
407
504
  };
408
505
  },
409
506
  history: (request) => Promise.resolve(historiesOf(request)),
410
- ...(options.agents === undefined
411
- ? {}
412
- : { agents: () => Promise.resolve(structuredClone(options.agents)) }),
413
507
  },
414
508
  serviceMode: {
415
509
  observe(notify) {
@@ -424,9 +518,10 @@ export function createMemoryAdapter(options = {}) {
424
518
  const named = asked.map((room) => room.locator);
425
519
  const unknown = asked.flatMap((room) => {
426
520
  const current = rooms.find((entry) => entry.locator === room.locator);
521
+ const version = room.roomVersion;
427
522
  return current === undefined ||
428
- current.roomVersion === room.roomVersion ||
429
- served.get(room.locator)?.has(room.roomVersion) === true
523
+ (version !== null &&
524
+ (current.roomVersion === version || served.get(room.locator)?.has(version) === true))
430
525
  ? []
431
526
  : [room.locator];
432
527
  });
@@ -436,7 +531,7 @@ export function createMemoryAdapter(options = {}) {
436
531
  expiring = expiring.filter((locator) => !named.includes(locator));
437
532
  queueMicrotask(() => {
438
533
  for (const room of asked) {
439
- if (expired.includes(room.locator))
534
+ if (expired.includes(room.locator) || room.roomVersion === null)
440
535
  carried.delete(room.locator);
441
536
  else {
442
537
  carried.set(room.locator, room.roomVersion);
@@ -558,28 +653,31 @@ export function createMemoryAdapter(options = {}) {
558
653
  const room = rooms.find((entry) => entry.locator === request.locator);
559
654
  if (room === undefined)
560
655
  return { kind: 'room-not-readable', locator: request.locator };
561
- const blob = heldBlob(room, request.path);
656
+ const blob = heldBytes(room, request.path);
562
657
  return blob === undefined
563
- ? { kind: 'rejected', code: 'file_not_found', fields: {}, retryable: false }
564
- : { kind: 'binary', body: blob.stream(), mediaType: blob.type };
658
+ ? { kind: 'rejected', code: 'not_found', fields: {}, retryable: false }
659
+ : { kind: 'binary', body: blob.stream(), mediaType: declaredType(blob) };
565
660
  }, request);
566
661
  },
567
662
  async link(_authorization, request) {
568
663
  return resolveScript(scripts.link, () => {
664
+ if (request.kind === 'key') {
665
+ const key = keyedLink(request.link)?.key;
666
+ const named = key === undefined ? undefined : keyed.get(key);
667
+ if (named === undefined)
668
+ return UNFOUND;
669
+ return linkTo(rooms.find((entry) => entry.locator === named.locator), named.path);
670
+ }
569
671
  const room = rooms.find((entry) => entry.locator === request.locator);
570
672
  if (room === undefined)
571
673
  return { kind: 'room-not-readable', locator: request.locator };
572
- const blob = heldBlob(room, request.path);
573
- if (blob === undefined) {
574
- return { kind: 'rejected', code: 'file_not_found', fields: {}, retryable: false };
575
- }
576
- const url = linked.get(blob) ?? URL.createObjectURL(blob);
577
- linked.set(blob, url);
578
- return { kind: 'link', url, name: lastName(request.path), mediaType: blob.type };
674
+ return linkTo(room, request.path);
579
675
  }, request);
580
676
  },
581
677
  async attach(_authorization, request) {
582
678
  return resolveScript(scripts.attach, () => {
679
+ if (request.locator === undefined)
680
+ return attachedKeyed(request);
583
681
  const room = rooms.find((entry) => entry.locator === request.locator);
584
682
  if (room === undefined)
585
683
  return { kind: 'room-not-readable', locator: request.locator };
@@ -592,6 +690,8 @@ export function createMemoryAdapter(options = {}) {
592
690
  return resolveScript(scripts.action, () => {
593
691
  if (request.name.startsWith('conversations/'))
594
692
  return conversationAction(request);
693
+ if (request.name === 'agent-functions/decide')
694
+ return decided(request);
595
695
  return { kind: 'rejected', code: 'unscripted-action', fields: {}, retryable: false };
596
696
  }, request).then((answer) => {
597
697
  if (answer.kind === 'action' && answer.at !== undefined)
@@ -1,6 +1,8 @@
1
+ import type { SessionState } from '@agentshouse/session-content';
1
2
  import type { AcceptedMessage } from './adapter.js';
2
3
  import type { Connection } from './tables.js';
3
4
  export declare const MESSAGE_TABLES: readonly string[];
5
+ export declare const ROWS = "WITH chosen AS (\n SELECT listed.value AS conversation,\n (SELECT id FROM conversation_messages WHERE conversation = listed.value AND json_extract(message, '$.role') = 'assistant' ORDER BY position DESC, identity DESC LIMIT 1) AS answer,\n (SELECT id FROM conversation_messages WHERE conversation = listed.value AND text <> '' ORDER BY position DESC, identity DESC LIMIT 1) AS said,\n (SELECT id FROM conversation_messages WHERE conversation = listed.value AND json_extract(message, '$.role') = 'house' ORDER BY position, identity LIMIT 1) AS opened,\n (SELECT id FROM conversation_messages WHERE conversation = listed.value AND json_extract(message, '$.role') = 'house' AND json_extract(message, '$.waiting') = 1 ORDER BY position, identity LIMIT 1) AS asking\n FROM json_each(?) AS listed\n )\n SELECT chosen.conversation AS conversation,\n substr(said.text, 1, 512) AS said_text,\n json_extract(said.message, '$.role') AS said_role,\n json_extract(said.message, '$.accepted_at') AS said_at,\n answer.turn AS answered,\n json_extract(answer.message, '$.content.state') AS saved_state,\n json_extract(answer.message, '$.accepted_at') AS saved_at,\n substr(json_extract(answer.message, '$.failure'), 1, 512) AS failure,\n COALESCE(\n (SELECT value FROM conversation_facts WHERE conversation = chosen.conversation AND name = 'openedTurn'),\n CASE WHEN julianday(json_extract(answer.message, '$.accepted_at')) < (SELECT julianday(json_extract(value, '$')) FROM replica_facts WHERE name = 'readUntil') THEN answer.turn END\n ) AS opened_turn,\n json_extract(opened.message, '$.source') AS opened_source,\n json_extract(opened.message, '$.sender') AS opened_sender,\n asking.identity AS asking_identity,\n asking.text AS asking_text,\n json_extract(asking.message, '$.accepted_at') AS asking_at,\n json_extract(asking.message, '$.source') AS asking_source,\n json_extract(asking.message, '$.sender') AS asking_sender\n FROM chosen\n LEFT JOIN conversation_messages said ON said.id = chosen.said\n LEFT JOIN conversation_messages answer ON answer.id = chosen.answer\n LEFT JOIN conversation_messages opened ON opened.id = chosen.opened\n LEFT JOIN conversation_messages asking ON asking.id = chosen.asking";
4
6
  export type HeldConversation = {
5
7
  readonly conversation: string;
6
8
  readonly read: string | null | undefined;
@@ -10,6 +12,37 @@ export type MessageWindow = {
10
12
  readonly messages: AcceptedMessage[];
11
13
  readonly more: boolean;
12
14
  };
15
+ export type HeldSource = {
16
+ readonly source: unknown;
17
+ readonly sender: string | null;
18
+ };
19
+ export type HeldRow = {
20
+ readonly conversation: string;
21
+ readonly said: {
22
+ readonly text: string;
23
+ readonly role: string | null;
24
+ readonly at: string | null;
25
+ } | null;
26
+ readonly answered: string | null;
27
+ readonly saved: {
28
+ readonly state: SessionState;
29
+ readonly at: string;
30
+ } | null;
31
+ readonly openedTurn: string | null;
32
+ readonly failure: string | null;
33
+ readonly opened: HeldSource | null;
34
+ readonly asking: (HeldSource & {
35
+ readonly identity: string;
36
+ readonly text: string;
37
+ readonly at: string | null;
38
+ }) | null;
39
+ };
40
+ export type ConversationFact = 'openedTurn' | 'dismissedSuggestion';
41
+ export type HeldFact = {
42
+ readonly conversation: string;
43
+ readonly name: ConversationFact;
44
+ readonly value: string;
45
+ };
13
46
  export type ConversationWrite = {
14
47
  readonly conversation: string;
15
48
  readonly messages: readonly AcceptedMessage[];
@@ -18,11 +51,13 @@ export type ConversationWrite = {
18
51
  readonly partial: boolean;
19
52
  };
20
53
  };
21
- export declare function heldConversations(connection: Connection): HeldConversation[];
54
+ export declare function heldConversations(connection: Connection, conversations: readonly string[] | null): HeldConversation[];
22
55
  export declare function keptMessages(connection: Connection, { conversation, messages, read }: ConversationWrite): null;
23
56
  export declare function messageWindow(connection: Connection, conversation: string, limit: number, before: readonly [string, string] | null, phrase: string | null): MessageWindow;
24
57
  export declare function messageCount(connection: Connection, conversation: string, phrase: string | null): number;
58
+ export declare function conversationRows(connection: Connection, conversations: readonly string[]): HeldRow[];
25
59
  export declare function turnArrived(connection: Connection, conversation: string, turn: string): boolean;
26
- export declare function droppedMessages(connection: Connection, conversations: readonly string[]): void;
27
- export declare function forgottenMessages(connection: Connection): void;
60
+ export declare function conversationFacts(connection: Connection): HeldFact[];
61
+ export declare function keptFact(connection: Connection, { conversation, name, value }: HeldFact): null;
62
+ export declare function forgottenConversations(connection: Connection): void;
28
63
  //# sourceMappingURL=messages.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,KAAK,EAAE,UAAU,EAAc,MAAM,aAAa,CAAC;AAE1D,eAAO,MAAM,cAAc,EAAE,SAAS,MAAM,EAM3C,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACzC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;CAC3B,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAAE,QAAQ,CAAC,QAAQ,EAAE,eAAe,EAAE,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAE7F,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,QAAQ,EAAE,SAAS,eAAe,EAAE,CAAC;IAC9C,QAAQ,CAAC,IAAI,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC;CAC3E,CAAC;AAMF,wBAAgB,iBAAiB,CAA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AC/B,OAAO,EAAE,CA6BX;AAED,wBAAgB,WAAW,CAAC,UAAU,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAO/F;AAED,wBAAgB,iBAAiB,CAAC,UAAU,EAAE,UAAU,GAAG,QAAQ,EAAE,CAMpE;AAED,wBAAgB,QAAQ,CAAC,UAAU,EAAE,UAAU,EAAE,EAAE,YAAY,EAAE,IAAI,EAAE,KAAK,EAAE,EAAE,QAAQ,GAAG,IAAI,CAM9F;AAED,wBAAgB,sBAAsB,CAAC,UAAU,EAAE,UAAU,GAAG,IAAI,CAEnE"}
package/dist/messages.js CHANGED
@@ -1,24 +1,66 @@
1
1
  import { sql } from '@agentshouse/mdmodel';
2
+ import { text } from './column.js';
3
+ import { EXCERPT } from './read.js';
4
+ import { tablesOf } from './stored.js';
5
+ const SAID_BY_HOUSE = `json_extract(message, '$.role') = 'house'`;
6
+ const ANSWERS_THE_TURN = `json_extract(message, '$.role') = 'assistant'`;
2
7
  export const MESSAGE_TABLES = [
3
8
  'CREATE TABLE conversation_reads (conversation TEXT PRIMARY KEY, read TEXT, partial INTEGER NOT NULL) WITHOUT ROWID',
4
- 'CREATE TABLE conversation_messages (id INTEGER PRIMARY KEY, conversation TEXT NOT NULL, identity TEXT NOT NULL, turn TEXT NOT NULL, position TEXT NOT NULL, message TEXT NOT NULL, text TEXT NOT NULL)',
9
+ 'CREATE TABLE conversation_messages (id INTEGER PRIMARY KEY, conversation TEXT NOT NULL, identity TEXT NOT NULL, turn TEXT NOT NULL, position TEXT NOT NULL, change TEXT NOT NULL, message TEXT NOT NULL, text TEXT NOT NULL)',
5
10
  'CREATE UNIQUE INDEX conversation_messages_identity ON conversation_messages (conversation, identity)',
6
11
  'CREATE INDEX conversation_messages_position ON conversation_messages (conversation, position, identity)',
7
12
  'CREATE INDEX conversation_messages_turn ON conversation_messages (conversation, turn)',
13
+ `CREATE INDEX conversation_messages_house ON conversation_messages (conversation, position, identity) WHERE ${SAID_BY_HOUSE}`,
14
+ 'CREATE TABLE conversation_facts (conversation TEXT NOT NULL, name TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (conversation, name)) WITHOUT ROWID',
8
15
  ];
9
- function text(value) {
10
- return typeof value === 'string' ? value : String(value);
11
- }
12
- export function heldConversations(connection) {
16
+ const NEWEST_FIRST = 'ORDER BY position DESC, identity DESC LIMIT 1';
17
+ const OLDEST_FIRST = 'ORDER BY position, identity LIMIT 1';
18
+ const OF_THE_ROW = 'SELECT id FROM conversation_messages WHERE conversation = listed.value';
19
+ const READ_UNTIL = `(SELECT julianday(json_extract(value, '$')) FROM replica_facts WHERE name = 'readUntil')`;
20
+ export const ROWS = `WITH chosen AS (
21
+ SELECT listed.value AS conversation,
22
+ (${OF_THE_ROW} AND ${ANSWERS_THE_TURN} ${NEWEST_FIRST}) AS answer,
23
+ (${OF_THE_ROW} AND text <> '' ${NEWEST_FIRST}) AS said,
24
+ (${OF_THE_ROW} AND ${SAID_BY_HOUSE} ${OLDEST_FIRST}) AS opened,
25
+ (${OF_THE_ROW} AND ${SAID_BY_HOUSE} AND json_extract(message, '$.waiting') = 1 ${OLDEST_FIRST}) AS asking
26
+ FROM json_each(?) AS listed
27
+ )
28
+ SELECT chosen.conversation AS conversation,
29
+ substr(said.text, 1, ${EXCERPT}) AS said_text,
30
+ json_extract(said.message, '$.role') AS said_role,
31
+ json_extract(said.message, '$.accepted_at') AS said_at,
32
+ answer.turn AS answered,
33
+ json_extract(answer.message, '$.content.state') AS saved_state,
34
+ json_extract(answer.message, '$.accepted_at') AS saved_at,
35
+ substr(json_extract(answer.message, '$.failure'), 1, ${EXCERPT}) AS failure,
36
+ COALESCE(
37
+ (SELECT value FROM conversation_facts WHERE conversation = chosen.conversation AND name = 'openedTurn'),
38
+ CASE WHEN julianday(json_extract(answer.message, '$.accepted_at')) < ${READ_UNTIL} THEN answer.turn END
39
+ ) AS opened_turn,
40
+ json_extract(opened.message, '$.source') AS opened_source,
41
+ json_extract(opened.message, '$.sender') AS opened_sender,
42
+ asking.identity AS asking_identity,
43
+ asking.text AS asking_text,
44
+ json_extract(asking.message, '$.accepted_at') AS asking_at,
45
+ json_extract(asking.message, '$.source') AS asking_source,
46
+ json_extract(asking.message, '$.sender') AS asking_sender
47
+ FROM chosen
48
+ LEFT JOIN conversation_messages said ON said.id = chosen.said
49
+ LEFT JOIN conversation_messages answer ON answer.id = chosen.answer
50
+ LEFT JOIN conversation_messages opened ON opened.id = chosen.opened
51
+ LEFT JOIN conversation_messages asking ON asking.id = chosen.asking`;
52
+ export function heldConversations(connection, conversations) {
53
+ const named = conversations === null ? '' : ' AND conversation IN (SELECT value FROM json_each(?))';
54
+ const bound = conversations === null ? [] : [JSON.stringify(conversations)];
13
55
  const held = new Map();
14
- for (const row of connection.rows('SELECT conversation, read, partial FROM conversation_reads')) {
56
+ for (const row of connection.rows(`SELECT conversation, read, partial FROM conversation_reads WHERE 1 = 1${named}`, bound)) {
15
57
  held.set(text(row.conversation), {
16
58
  conversation: text(row.conversation),
17
59
  read: row.read === null ? null : text(row.read),
18
60
  partial: Number(row.partial) === 1,
19
61
  });
20
62
  }
21
- for (const row of connection.rows('SELECT DISTINCT conversation FROM conversation_messages WHERE conversation NOT IN (SELECT conversation FROM conversation_reads)')) {
63
+ for (const row of connection.rows(`SELECT DISTINCT conversation FROM conversation_messages WHERE conversation NOT IN (SELECT conversation FROM conversation_reads)${named}`, bound)) {
22
64
  held.set(text(row.conversation), {
23
65
  conversation: text(row.conversation),
24
66
  read: undefined,
@@ -29,19 +71,15 @@ export function heldConversations(connection) {
29
71
  }
30
72
  export function keptMessages(connection, { conversation, messages, read }) {
31
73
  for (const message of messages) {
32
- const [held] = connection.rows('SELECT id FROM conversation_messages WHERE conversation = ? AND identity = ?', [conversation, message.identity]);
33
- const record = [
74
+ connection.run('INSERT INTO conversation_messages (conversation, identity, turn, position, change, message, text) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT (conversation, identity) DO UPDATE SET turn = excluded.turn, position = excluded.position, change = excluded.change, message = excluded.message, text = excluded.text', [
75
+ conversation,
76
+ message.identity,
34
77
  message.turn,
35
78
  message.position,
79
+ message.change,
36
80
  JSON.stringify(message.message ?? null),
37
81
  message.text,
38
- ];
39
- if (held === undefined) {
40
- connection.run('INSERT INTO conversation_messages (conversation, identity, turn, position, message, text) VALUES (?, ?, ?, ?, ?, ?)', [conversation, message.identity, ...record]);
41
- }
42
- else {
43
- connection.run('UPDATE conversation_messages SET turn = ?, position = ?, message = ?, text = ? WHERE id = ?', [...record, held.id]);
44
- }
82
+ ]);
45
83
  }
46
84
  if (read !== undefined) {
47
85
  connection.run('INSERT OR REPLACE INTO conversation_reads (conversation, read, partial) VALUES (?, ?, ?)', [conversation, read.at, read.partial ? 1 : 0]);
@@ -53,6 +91,7 @@ function accepted(row) {
53
91
  identity: text(row.identity),
54
92
  turn: text(row.turn),
55
93
  position: text(row.position),
94
+ change: text(row.change),
56
95
  text: text(row.text),
57
96
  message: JSON.parse(text(row.message)),
58
97
  };
@@ -64,7 +103,7 @@ function holding(phrase) {
64
103
  }
65
104
  export function messageWindow(connection, conversation, limit, before, phrase) {
66
105
  const held = holding(phrase);
67
- const rows = connection.rows(`SELECT identity, turn, position, message, text FROM conversation_messages WHERE conversation = ?${held.sql}${before === null ? '' : ' AND (position < ? OR (position = ? AND identity < ?))'} ORDER BY position DESC, identity DESC LIMIT ?`, before === null
106
+ const rows = connection.rows(`SELECT identity, turn, position, change, message, text FROM conversation_messages WHERE conversation = ?${held.sql}${before === null ? '' : ' AND (position < ? OR (position = ? AND identity < ?))'} ORDER BY position DESC, identity DESC LIMIT ?`, before === null
68
107
  ? [conversation, ...held.bind, limit + 1]
69
108
  : [conversation, ...held.bind, before[0], before[0], before[1], limit + 1]);
70
109
  return { messages: rows.slice(0, limit).map(accepted).reverse(), more: rows.length > limit };
@@ -74,16 +113,57 @@ export function messageCount(connection, conversation, phrase) {
74
113
  const [counted] = connection.rows(`SELECT count(*) AS held FROM conversation_messages WHERE conversation = ?${held.sql}`, [conversation, ...held.bind]);
75
114
  return Number(counted?.held ?? 0);
76
115
  }
116
+ function textOrNull(value) {
117
+ return value === null ? null : text(value);
118
+ }
119
+ function heldSource(source, sender) {
120
+ return {
121
+ source: source === null ? null : JSON.parse(text(source)),
122
+ sender: textOrNull(sender),
123
+ };
124
+ }
125
+ export function conversationRows(connection, conversations) {
126
+ return connection.rows(ROWS, [JSON.stringify(conversations)]).map((row) => ({
127
+ conversation: text(row.conversation),
128
+ said: row.said_text === null
129
+ ? null
130
+ : {
131
+ text: text(row.said_text),
132
+ role: textOrNull(row.said_role),
133
+ at: textOrNull(row.said_at),
134
+ },
135
+ answered: textOrNull(row.answered),
136
+ saved: row.saved_state === null || row.saved_at === null
137
+ ? null
138
+ : { state: JSON.parse(text(row.saved_state)), at: text(row.saved_at) },
139
+ openedTurn: textOrNull(row.opened_turn),
140
+ failure: textOrNull(row.failure),
141
+ opened: row.opened_source === null ? null : heldSource(row.opened_source, row.opened_sender),
142
+ asking: row.asking_identity === null
143
+ ? null
144
+ : {
145
+ ...heldSource(row.asking_source, row.asking_sender),
146
+ identity: text(row.asking_identity),
147
+ text: text(row.asking_text),
148
+ at: textOrNull(row.asking_at),
149
+ },
150
+ }));
151
+ }
77
152
  export function turnArrived(connection, conversation, turn) {
78
153
  return (connection.rows('SELECT 1 FROM conversation_messages WHERE conversation = ? AND turn = ? LIMIT 1', [conversation, turn]).length > 0);
79
154
  }
80
- export function droppedMessages(connection, conversations) {
81
- for (const conversation of conversations) {
82
- connection.run('DELETE FROM conversation_messages WHERE conversation = ?', [conversation]);
83
- connection.run('DELETE FROM conversation_reads WHERE conversation = ?', [conversation]);
84
- }
155
+ export function conversationFacts(connection) {
156
+ return connection.rows('SELECT conversation, name, value FROM conversation_facts').map((row) => ({
157
+ conversation: text(row.conversation),
158
+ name: text(row.name),
159
+ value: text(row.value),
160
+ }));
161
+ }
162
+ export function keptFact(connection, { conversation, name, value }) {
163
+ connection.run('INSERT OR REPLACE INTO conversation_facts (conversation, name, value) VALUES (?, ?, ?)', [conversation, name, value]);
164
+ return null;
85
165
  }
86
- export function forgottenMessages(connection) {
87
- connection.run('DELETE FROM conversation_messages');
88
- connection.run('DELETE FROM conversation_reads');
166
+ export function forgottenConversations(connection) {
167
+ for (const table of tablesOf(MESSAGE_TABLES))
168
+ connection.run(`DELETE FROM ${table}`);
89
169
  }
@@ -0,0 +1,2 @@
1
+ export declare function shownModal(dialog: HTMLDialogElement): void;
2
+ //# sourceMappingURL=modal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modal.d.ts","sourceRoot":"","sources":["../src/modal.ts"],"names":[],"mappings":"AAMA,wBAAgB,UAAU,CAAC,MAAM,EAAE,iBAAiB,GAAG,IAAI,CAI1D"}