@agentshouse/mdruntime-adapter 0.1.0-c55b0f26f7582 → 0.1.0-c57d433251ca5

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 (53) hide show
  1. package/AGENTS.md +286 -209
  2. package/dist/actions.d.ts +69 -2
  3. package/dist/actions.d.ts.map +1 -1
  4. package/dist/actions.js +197 -198
  5. package/dist/adapter.d.ts +1 -0
  6. package/dist/adapter.d.ts.map +1 -1
  7. package/dist/adapter.js +392 -113
  8. package/dist/discovery.d.ts +7 -6
  9. package/dist/discovery.d.ts.map +1 -1
  10. package/dist/discovery.js +50 -18
  11. package/dist/gather.d.ts +2 -1
  12. package/dist/gather.d.ts.map +1 -1
  13. package/dist/gather.js +15 -20
  14. package/dist/handed.d.ts +15 -0
  15. package/dist/handed.d.ts.map +1 -0
  16. package/dist/handed.js +45 -0
  17. package/dist/index.d.ts +2 -2
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +1 -1
  20. package/dist/model.d.ts +1 -1
  21. package/dist/model.d.ts.map +1 -1
  22. package/dist/model.js +21 -7
  23. package/dist/part.d.ts +13 -0
  24. package/dist/part.d.ts.map +1 -0
  25. package/dist/part.js +80 -0
  26. package/dist/read.d.ts +54 -16
  27. package/dist/read.d.ts.map +1 -1
  28. package/dist/read.js +269 -149
  29. package/dist/referrer.d.ts +7 -0
  30. package/dist/referrer.d.ts.map +1 -0
  31. package/dist/referrer.js +33 -0
  32. package/dist/refusal.d.ts +5 -9
  33. package/dist/refusal.d.ts.map +1 -1
  34. package/dist/refusal.js +31 -17
  35. package/dist/site.d.ts +1 -1
  36. package/dist/site.d.ts.map +1 -1
  37. package/dist/site.js +181 -62
  38. package/dist/stream.d.ts +6 -4
  39. package/dist/stream.d.ts.map +1 -1
  40. package/dist/stream.js +374 -42
  41. package/dist/transport.d.ts +83 -12
  42. package/dist/transport.d.ts.map +1 -1
  43. package/dist/transport.js +3 -1
  44. package/dist/version.d.ts +1 -0
  45. package/dist/version.d.ts.map +1 -1
  46. package/dist/version.js +1 -1
  47. package/dist/write.d.ts +14 -9
  48. package/dist/write.d.ts.map +1 -1
  49. package/dist/write.js +161 -43
  50. package/package.json +3 -4
  51. package/dist/links.d.ts +0 -20
  52. package/dist/links.d.ts.map +0 -1
  53. package/dist/links.js +0 -104
package/dist/stream.js CHANGED
@@ -1,19 +1,101 @@
1
+ import { ROW_WEIGHT, } from '@agentshouse/mdruntime';
1
2
  import { acceptedMessage } from './actions.js';
2
- import { headChange } from './read.js';
3
+ import { sha256Hex } from './digest.js';
4
+ import { answered, answering, binaryFileOf, forgotten, headChange, revised } from './read.js';
3
5
  import { roomVersion } from './version.js';
4
6
  const HELD_FRAMES_MAX = 256;
5
7
  function turnOperation(frame) {
6
8
  const { type: _type, conversation_id: _conversation, turn_id: _turn, ...operation } = frame;
7
9
  return structuredClone(operation);
8
10
  }
11
+ function listedConversation(listed) {
12
+ return {
13
+ conversation: listed.conversation_id,
14
+ agent: listed.agent_id,
15
+ name: listed.name,
16
+ created: listed.created_at,
17
+ finished: listed.finished_at,
18
+ outcome: listed.outcome,
19
+ waiting: listed.waiting,
20
+ };
21
+ }
9
22
  function position(value) {
10
23
  if (!/^(?:0|[1-9][0-9]*)$/.test(value))
11
24
  return null;
12
25
  return BigInt(value);
13
26
  }
27
+ function assembled(entries) {
28
+ const whole = [];
29
+ let open = null;
30
+ for (const entry of entries) {
31
+ if (entry.kind === 'piece') {
32
+ if (open === null || open.entry.path !== entry.path || entry.text === undefined)
33
+ return null;
34
+ open.texts.push(entry.text);
35
+ }
36
+ else {
37
+ if (open !== null)
38
+ return null;
39
+ if (entry.continued !== true) {
40
+ whole.push(entry);
41
+ continue;
42
+ }
43
+ if (entry.text === undefined)
44
+ return null;
45
+ open = { entry, texts: [entry.text] };
46
+ }
47
+ if (entry.continued === true)
48
+ continue;
49
+ const { continued: _continued, ...head } = open.entry;
50
+ whole.push({ ...head, text: open.texts.join('') });
51
+ open = null;
52
+ }
53
+ return open === null ? whole : null;
54
+ }
55
+ async function verified(entries) {
56
+ try {
57
+ for (const entry of entries) {
58
+ if (entry.text === undefined || entry.sha256 === undefined)
59
+ continue;
60
+ if ((await sha256Hex(entry.text)) !== entry.sha256)
61
+ return false;
62
+ }
63
+ return true;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ function resumed(kept, frame) {
70
+ const last = frame.entries.at(-1);
71
+ const point = { parts: frame.index + 1, from: frame.from, target: frame.target };
72
+ if (last?.continued !== true)
73
+ return { ...point, handled: frame.handled, piece: null };
74
+ const text = last.text?.length ?? 0;
75
+ if (last.kind !== 'piece') {
76
+ return last.sha256 === undefined
77
+ ? kept.resume
78
+ : { ...point, handled: frame.handled, piece: { sha256: last.sha256, offset: text } };
79
+ }
80
+ const piece = kept.resume?.piece ?? null;
81
+ if (piece === null)
82
+ return kept.resume;
83
+ const pieces = frame.entries.reduce((sum, entry) => sum + (entry.kind === 'piece' ? (entry.text?.length ?? 0) : 0), 0);
84
+ return {
85
+ ...point,
86
+ handled: frame.handled,
87
+ piece: { sha256: piece.sha256, offset: piece.offset + pieces },
88
+ };
89
+ }
14
90
  export function houseNotifications(transport, mode) {
15
91
  const stream = transport.stream;
16
92
  const lines = new Map();
93
+ const kept = new Map();
94
+ let receipts = null;
95
+ let loaded = Promise.resolve();
96
+ let acknowledging = null;
97
+ let receiving = Promise.resolve();
98
+ let verifying = 0;
17
99
  const locators = new Map();
18
100
  const observers = new Set();
19
101
  const conversationObservers = new Set();
@@ -21,18 +103,28 @@ export function houseNotifications(transport, mode) {
21
103
  let replicated = [];
22
104
  const live = new Set();
23
105
  let opening = null;
106
+ const runtime = crypto.randomUUID();
24
107
  function emit(event) {
25
108
  for (const observer of observers)
26
109
  observer(event);
27
110
  }
28
111
  function emitConversation(event) {
29
- if (event.kind !== 'gap' && event.kind !== 'accepted-message')
112
+ if (event.kind === 'turn' ||
113
+ event.kind === 'questions' ||
114
+ event.kind === 'process' ||
115
+ event.kind === 'commands' ||
116
+ event.kind === 'options' ||
117
+ event.kind === 'starting' ||
118
+ event.kind === 'link' ||
119
+ event.kind === 'deliveries') {
30
120
  live.add(event.conversation);
121
+ }
31
122
  for (const observer of conversationObservers)
32
123
  observer(event);
33
124
  }
34
125
  function reopened(next) {
35
126
  opening = next;
127
+ acknowledging = next;
36
128
  const gapped = new Set([...replicated, ...live]);
37
129
  live.clear();
38
130
  for (const conversation of gapped)
@@ -70,6 +162,18 @@ export function houseNotifications(transport, mode) {
70
162
  emitConversation({ kind: 'options', conversation, options: structuredClone(frame.options) });
71
163
  return;
72
164
  }
165
+ if (frame.type === 'starting') {
166
+ emitConversation({ kind: 'starting', conversation, step: frame.step });
167
+ return;
168
+ }
169
+ if (frame.type === 'link') {
170
+ emitConversation({ kind: 'link', conversation, connected: frame.connected });
171
+ return;
172
+ }
173
+ if (frame.type === 'deliveries') {
174
+ emitConversation({ kind: 'deliveries', conversation, unknown: [...frame.unknown] });
175
+ return;
176
+ }
73
177
  if (frame.type === 'interactions') {
74
178
  emitConversation({
75
179
  kind: 'questions',
@@ -94,7 +198,162 @@ export function houseNotifications(transport, mode) {
94
198
  if (line !== undefined)
95
199
  lines.set(authority, { ...line, frames: [] });
96
200
  }
97
- function receive(frame) {
201
+ async function forget(carries) {
202
+ const held = carries.filter((carry) => kept.delete(carry));
203
+ if (held.length > 0)
204
+ await receipts?.drop(held).catch(() => { });
205
+ }
206
+ async function lost(authority, carry) {
207
+ interrupt(authority);
208
+ await forget([carry]);
209
+ }
210
+ async function stage(frame, via) {
211
+ await loaded;
212
+ const port = receipts;
213
+ if (port === null)
214
+ return;
215
+ const held = kept.get(frame.carry);
216
+ if (held === undefined && frame.index !== 0) {
217
+ interrupt(frame.authority);
218
+ return;
219
+ }
220
+ if (held !== undefined &&
221
+ (held.fenced !== null || frame.index > held.parts || frame.index < (held.resume?.parts ?? 0))) {
222
+ await lost(frame.authority, frame.carry);
223
+ return;
224
+ }
225
+ if (held === undefined) {
226
+ await forget([...kept.values()]
227
+ .filter((other) => other.authority === frame.authority && other.fenced === null)
228
+ .map((other) => other.carry));
229
+ }
230
+ const start = held ?? {
231
+ authority: frame.authority,
232
+ carry: frame.carry,
233
+ logEpoch: lines.get(frame.authority)?.logEpoch ?? null,
234
+ after: frame.after,
235
+ parts: 0,
236
+ resume: null,
237
+ fenced: null,
238
+ };
239
+ const next = { ...start, parts: frame.index + 1, resume: resumed(start, frame) };
240
+ const part = { entries: frame.entries };
241
+ try {
242
+ await port.keep(frame.carry, next, { index: frame.index, value: part });
243
+ }
244
+ catch {
245
+ await lost(frame.authority, frame.carry);
246
+ return;
247
+ }
248
+ kept.set(frame.carry, next);
249
+ via?.received(frame.authority, frame.carry, frame.index);
250
+ }
251
+ async function keptEntries(carry, parts) {
252
+ if (parts === 0)
253
+ return [];
254
+ if (receipts === null)
255
+ return null;
256
+ const read = (await receipts.parts(carry, parts));
257
+ if (read.length !== parts)
258
+ return null;
259
+ const entries = assembled(read.flatMap((part) => part.entries));
260
+ return entries !== null && (await verified(entries)) ? entries : null;
261
+ }
262
+ async function carried(frame) {
263
+ await loaded;
264
+ const held = kept.get(frame.carry);
265
+ if (frame.parts > 0 && held?.parts !== frame.parts) {
266
+ await lost(frame.authority, frame.carry);
267
+ return;
268
+ }
269
+ const entries = await keptEntries(frame.carry, frame.parts).catch(() => null);
270
+ if (entries === null) {
271
+ await lost(frame.authority, frame.carry);
272
+ return;
273
+ }
274
+ const fenced = {
275
+ ...(held ?? {
276
+ authority: frame.authority,
277
+ carry: frame.carry,
278
+ logEpoch: frame.log_epoch,
279
+ after: frame.after,
280
+ parts: 0,
281
+ resume: null,
282
+ }),
283
+ after: frame.after,
284
+ fenced: { position: frame.position, logEpoch: frame.log_epoch },
285
+ };
286
+ try {
287
+ await receipts?.keep(frame.carry, fenced);
288
+ }
289
+ catch {
290
+ await lost(frame.authority, frame.carry);
291
+ return;
292
+ }
293
+ kept.set(frame.carry, fenced);
294
+ publish(frame, entries);
295
+ }
296
+ async function load(port) {
297
+ try {
298
+ for (const { key, head } of await port.heads())
299
+ kept.set(key, head);
300
+ }
301
+ catch {
302
+ kept.clear();
303
+ }
304
+ }
305
+ async function restored(room) {
306
+ const line = lines.get(room.authority);
307
+ let at = room.position;
308
+ const chain = [];
309
+ for (;;) {
310
+ const next = [...kept.values()].find((carry) => carry.authority === room.authority &&
311
+ carry.after === at &&
312
+ carry.fenced?.logEpoch === room.log_epoch);
313
+ if (next?.fenced == null)
314
+ break;
315
+ const entries = await keptEntries(next.carry, next.parts).catch(() => null);
316
+ if (entries === null)
317
+ break;
318
+ chain.push({ carry: next, entries });
319
+ at = next.fenced.position;
320
+ }
321
+ const partial = [...kept.values()].find((carry) => carry.authority === room.authority &&
322
+ carry.fenced === null &&
323
+ carry.logEpoch === room.log_epoch &&
324
+ carry.after === at &&
325
+ carry.resume !== null &&
326
+ carry.resume.parts > 0);
327
+ const stale = [...kept.values()].filter((carry) => carry.authority === room.authority &&
328
+ carry !== partial &&
329
+ !chain.some((link) => link.carry === carry));
330
+ await forget(stale.map((carry) => carry.carry));
331
+ if (line !== undefined && line.logEpoch === room.log_epoch && chain.length > 0) {
332
+ const frames = chain.map(({ carry, entries }) => ({
333
+ after: BigInt(carry.after),
334
+ position: BigInt(carry.fenced.position),
335
+ entries,
336
+ }));
337
+ lines.set(room.authority, { ...line, frames: [...line.frames, ...frames] });
338
+ }
339
+ return {
340
+ ...room,
341
+ position: at,
342
+ ...(partial?.resume == null
343
+ ? {}
344
+ : {
345
+ carry: {
346
+ id: partial.carry,
347
+ parts: partial.resume.parts,
348
+ from: partial.resume.from,
349
+ target: partial.resume.target,
350
+ handled: partial.resume.handled,
351
+ ...(partial.resume.piece === null ? {} : { piece: partial.resume.piece }),
352
+ },
353
+ }),
354
+ };
355
+ }
356
+ function handle(frame, via) {
98
357
  if (frame.type === 'signal') {
99
358
  const mode = frame.service_mode;
100
359
  if (mode !== 'open' && mode !== 'write-halted')
@@ -110,17 +369,40 @@ export function houseNotifications(transport, mode) {
110
369
  });
111
370
  return;
112
371
  }
372
+ if (frame.type === 'authority_changed') {
373
+ emit({ kind: 'authority-changed', scope: { authorities: frame.rooms } });
374
+ return;
375
+ }
376
+ if (frame.type === 'conversations') {
377
+ emitConversation({ kind: 'list', entries: frame.conversations.map(listedConversation) });
378
+ return;
379
+ }
380
+ if (frame.type === 'conversation') {
381
+ emitConversation({ kind: 'listed', entry: listedConversation(frame.conversation) });
382
+ return;
383
+ }
384
+ if (frame.type === 'conversation_deleted') {
385
+ emitConversation({ kind: 'unlisted', conversation: frame.conversation_id });
386
+ return;
387
+ }
113
388
  if (frame.type === 'turn' ||
114
389
  frame.type === 'process' ||
115
390
  frame.type === 'commands' ||
116
391
  frame.type === 'options' ||
392
+ frame.type === 'starting' ||
393
+ frame.type === 'link' ||
394
+ frame.type === 'deliveries' ||
117
395
  frame.type === 'interactions' ||
118
396
  frame.type === 'message') {
119
397
  converse(frame);
120
398
  return;
121
399
  }
122
- if (frame.type !== 'entries')
123
- return;
400
+ if (frame.type === 'part')
401
+ return stage(frame, via);
402
+ if (frame.type === 'carried')
403
+ return carried(frame);
404
+ }
405
+ function publish(frame, entries) {
124
406
  const at = position(frame.position);
125
407
  const after = position(frame.after);
126
408
  if (at === null || after === null || after >= at) {
@@ -134,7 +416,7 @@ export function houseNotifications(transport, mode) {
134
416
  const last = line.frames.at(-1);
135
417
  if (last !== undefined && at <= last.position)
136
418
  return;
137
- const held = { after, position: at, entries: frame.entries };
419
+ const held = { after, position: at, entries };
138
420
  const next = last !== undefined && after <= last.position ? [...line.frames, held] : [held];
139
421
  lines.set(frame.authority, { ...line, frames: next.length > HELD_FRAMES_MAX ? [] : next });
140
422
  }
@@ -143,13 +425,33 @@ export function houseNotifications(transport, mode) {
143
425
  }
144
426
  announce(frame.authority, { position: frame.position, logEpoch: frame.log_epoch });
145
427
  }
146
- stream.observe(receive);
428
+ stream.observe((frame) => {
429
+ const via = acknowledging;
430
+ if (verifying === 0) {
431
+ const handled = handle(frame, via);
432
+ if (handled === undefined)
433
+ return;
434
+ verifying += 1;
435
+ receiving = handled.finally(() => {
436
+ verifying -= 1;
437
+ });
438
+ return;
439
+ }
440
+ verifying += 1;
441
+ receiving = receiving
442
+ .then(() => handle(frame, via))
443
+ .finally(() => {
444
+ verifying -= 1;
445
+ });
446
+ });
147
447
  stream.opened(reopened);
148
- stream.closed((revoked) => {
448
+ stream.closed(({ revoked, lost }) => {
149
449
  opening = null;
150
- emit({ kind: 'closed', revoked });
450
+ acknowledging = null;
451
+ emit({ kind: 'closed', revoked, lost });
151
452
  });
152
453
  return {
454
+ runtime,
153
455
  serviceMode: {
154
456
  observe(notify) {
155
457
  modeObservers.add(notify);
@@ -169,8 +471,12 @@ export function houseNotifications(transport, mode) {
169
471
  };
170
472
  },
171
473
  },
172
- observe(notify) {
474
+ observe(notify, port) {
173
475
  observers.add(notify);
476
+ if (receipts === null) {
477
+ receipts = port;
478
+ loaded = load(port);
479
+ }
174
480
  if (opening !== null) {
175
481
  queueMicrotask(() => {
176
482
  if (observers.has(notify))
@@ -191,7 +497,35 @@ export function houseNotifications(transport, mode) {
191
497
  }
192
498
  const current = opening;
193
499
  opening = null;
194
- current?.hold(rooms);
500
+ if (current === null)
501
+ return;
502
+ void loaded
503
+ .then(() => Promise.all(rooms.map(restored)))
504
+ .then((presented) => {
505
+ current.hold(presented, runtime);
506
+ for (const [index, room] of presented.entries()) {
507
+ if (room.position === rooms[index].position)
508
+ continue;
509
+ announce(room.authority, { position: room.position, logEpoch: room.log_epoch });
510
+ }
511
+ });
512
+ },
513
+ published(locator, at) {
514
+ const authority = [...locators].find(([, held]) => held.includes(locator))?.[0];
515
+ const reached = position(at.position);
516
+ if (authority === undefined || reached === null)
517
+ return;
518
+ void forget([...kept.values()]
519
+ .filter((carry) => carry.authority === authority &&
520
+ carry.fenced !== null &&
521
+ carry.fenced.logEpoch === at.logEpoch &&
522
+ BigInt(carry.fenced.position) <= reached)
523
+ .map((carry) => carry.carry));
524
+ },
525
+ reopen() {
526
+ const current = opening;
527
+ opening = null;
528
+ current?.close();
195
529
  },
196
530
  track(entries) {
197
531
  locators.clear();
@@ -205,6 +539,9 @@ export function houseNotifications(transport, mode) {
205
539
  if (!locators.has(authority))
206
540
  lines.delete(authority);
207
541
  }
542
+ void loaded.then(() => forget([...kept.values()]
543
+ .filter((carry) => !locators.has(carry.authority))
544
+ .map((carry) => carry.carry)));
208
545
  },
209
546
  reach(authority, at) {
210
547
  const line = lines.get(authority);
@@ -219,7 +556,7 @@ export function houseNotifications(transport, mode) {
219
556
  held,
220
557
  });
221
558
  },
222
- advance(tracked, from, holds) {
559
+ *advance(tracked, from, holds) {
223
560
  const line = lines.get(tracked.authority);
224
561
  const start = position(from.position);
225
562
  if (line === undefined || start === null || line.logEpoch !== from.logEpoch)
@@ -228,64 +565,59 @@ export function houseNotifications(transport, mode) {
228
565
  const first = pending[0];
229
566
  if (first === undefined || first.after > start)
230
567
  return null;
231
- const documents = {};
232
- const revisions = {};
233
- const changes = {};
234
- const removals = [];
235
- const applied = [];
568
+ const answer = answering();
236
569
  const schemas = new Map();
237
- const forget = (path) => {
238
- delete documents[path];
239
- delete revisions[path];
240
- delete changes[path];
241
- const removed = removals.indexOf(path);
242
- if (removed !== -1)
243
- removals.splice(removed, 1);
244
- };
245
570
  for (const frame of pending) {
246
571
  for (const entry of frame.entries) {
572
+ yield ROW_WEIGHT + (entry.text?.length ?? 0);
247
573
  if (entry.kind === 'edited' &&
248
574
  entry.revision !== undefined &&
249
575
  holds?.(entry.path, entry.revision) === true) {
250
- forget(entry.path);
576
+ forgotten(answer, entry.path);
251
577
  continue;
252
578
  }
253
- applied.push(entry);
254
579
  if (tracked.schemas.includes(entry.path))
255
580
  schemas.set(entry.path, entry);
256
581
  if (entry.kind === 'removed') {
257
- forget(entry.path);
258
- removals.push(entry.path);
582
+ forgotten(answer, entry.path);
583
+ answer.removals.add(entry.path);
259
584
  continue;
260
585
  }
261
- if (entry.text === undefined)
586
+ const binary = binaryFileOf(entry);
587
+ if (binary === null || (binary === undefined && entry.text === undefined))
262
588
  return null;
263
589
  if (mode === 'credential' && entry.revision === undefined)
264
590
  return null;
265
591
  const head = headChange(entry);
266
592
  if (head === null)
267
593
  return null;
268
- forget(entry.path);
269
- documents[entry.path] = entry.text;
270
- if (entry.revision !== undefined)
271
- revisions[entry.path] = entry.revision;
594
+ forgotten(answer, entry.path);
595
+ if (binary === undefined)
596
+ answer.documents.set(entry.path, entry.text);
597
+ else
598
+ answer.binaryFiles.set(entry.path, binary);
599
+ const revision = entry.revision ?? binary?.sha256;
600
+ if (revision !== undefined)
601
+ revised(answer, entry.path, revision);
272
602
  if (head !== undefined)
273
- changes[entry.path] = head;
603
+ answer.changes.set(entry.path, head);
274
604
  }
275
605
  }
276
606
  const last = pending.at(-1);
277
- lines.set(tracked.authority, { ...line, frames: pending, held: last.position });
607
+ const current = lines.get(tracked.authority);
608
+ if (current?.logEpoch === line.logEpoch) {
609
+ lines.set(tracked.authority, {
610
+ ...current,
611
+ frames: current.frames.filter((frame) => frame.position > start),
612
+ held: current.held !== null && current.held > last.position ? current.held : last.position,
613
+ });
614
+ }
278
615
  return {
279
616
  page: {
280
617
  kind: 'net-advancement',
281
618
  roomVersion: roomVersion({ position: last.position.toString(), logEpoch: line.logEpoch }),
282
- documents,
283
- revisions,
284
- changes,
285
- binaryTargets: [],
286
- removals: removals.sort(),
619
+ ...(yield* answered(answer)),
287
620
  },
288
- entries: applied,
289
621
  schemas,
290
622
  };
291
623
  },