@agentshouse/mdruntime-adapter 0.1.0-c6229cc476473 → 0.1.0-c658cd7165027

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 (66) hide show
  1. package/README.md +4 -4
  2. package/dist/actions.d.ts +164 -3
  3. package/dist/actions.d.ts.map +1 -1
  4. package/dist/actions.js +124 -219
  5. package/dist/adapter.d.ts +1 -0
  6. package/dist/adapter.d.ts.map +1 -1
  7. package/dist/adapter.js +369 -182
  8. package/dist/app-reference.d.ts +2 -0
  9. package/dist/app-reference.d.ts.map +1 -0
  10. package/dist/app-reference.js +2 -0
  11. package/dist/crockford.d.ts +4 -0
  12. package/dist/crockford.d.ts.map +1 -0
  13. package/dist/crockford.js +3 -0
  14. package/dist/discovery.d.ts +14 -30
  15. package/dist/discovery.d.ts.map +1 -1
  16. package/dist/discovery.js +69 -110
  17. package/dist/gather.d.ts +1 -1
  18. package/dist/gather.d.ts.map +1 -1
  19. package/dist/gather.js +15 -20
  20. package/dist/house-model.d.ts +2938 -0
  21. package/dist/house-model.d.ts.map +1 -0
  22. package/dist/house-model.js +1614 -0
  23. package/dist/index.d.ts +8 -2
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +7 -1
  26. package/dist/model.d.ts +11 -18
  27. package/dist/model.d.ts.map +1 -1
  28. package/dist/model.js +56 -37
  29. package/dist/part.d.ts +14 -0
  30. package/dist/part.d.ts.map +1 -0
  31. package/dist/part.js +90 -0
  32. package/dist/read.d.ts +75 -22
  33. package/dist/read.d.ts.map +1 -1
  34. package/dist/read.js +353 -189
  35. package/dist/refusal.d.ts +5 -7
  36. package/dist/refusal.d.ts.map +1 -1
  37. package/dist/refusal.js +31 -31
  38. package/dist/room-stream.d.ts +19 -0
  39. package/dist/room-stream.d.ts.map +1 -0
  40. package/dist/room-stream.js +57 -0
  41. package/dist/room-types.d.ts +7 -0
  42. package/dist/room-types.d.ts.map +1 -0
  43. package/dist/room-types.js +126 -0
  44. package/dist/site.d.ts +1 -1
  45. package/dist/site.d.ts.map +1 -1
  46. package/dist/site.js +149 -118
  47. package/dist/stream.d.ts +10 -7
  48. package/dist/stream.d.ts.map +1 -1
  49. package/dist/stream.js +205 -111
  50. package/dist/transport.d.ts +90 -22
  51. package/dist/transport.d.ts.map +1 -1
  52. package/dist/transport.js +4 -2
  53. package/dist/upload.d.ts +12 -0
  54. package/dist/upload.d.ts.map +1 -0
  55. package/dist/upload.js +63 -0
  56. package/dist/version.d.ts +2 -0
  57. package/dist/version.d.ts.map +1 -1
  58. package/dist/version.js +10 -1
  59. package/dist/write.d.ts +20 -6
  60. package/dist/write.d.ts.map +1 -1
  61. package/dist/write.js +175 -53
  62. package/package.json +9 -6
  63. package/AGENTS.md +0 -210
  64. package/dist/links.d.ts +0 -12
  65. package/dist/links.d.ts.map +0 -1
  66. package/dist/links.js +0 -66
package/dist/adapter.js CHANGED
@@ -1,103 +1,175 @@
1
- import { DISCOVER_PREFIXES, HOUSE_SCHEMA, capabilities, discoveredRoom, locatorOf, mapDiscovery, parseDiscovery, providerSelection, trackedFrom, } from './discovery.js';
2
- import { MODEL_ABSENT, failedModel, heldModel, modelKey, modelShelf, } from './model.js';
1
+ import { stepped } from '@agentshouse/mdruntime';
2
+ import { DISCOVER_PREFIXES, capabilities, discoveredRoom, mapDiscovery, parseDiscovery, trackedFrom, } from './discovery.js';
3
+ import { streamedModels, viewModels } from './model.js';
3
4
  import { gathered, selections } from './gather.js';
4
5
  import { createSiteAdapter } from './site.js';
5
- import { bootstrapOf, contentPrefixes, matchesScope, parseEnumeration, parseEnvelope, parseGrant, refreshFrom, schemaFrom, schemaPath, viewOf, } from './read.js';
6
- import { enumeratedLinks, scopeLinks, streamedLinks } from './links.js';
6
+ import { authorityRoot, bootstrapping, parseEnumeration, parseFileAddress, parseGrant, refreshFrom, viewOf, wholeView, } from './read.js';
7
+ import { roomStreams } from './room-stream.js';
8
+ import { sha256Hex } from './digest.js';
9
+ import { finishedUpload, houseUpload } from './upload.js';
7
10
  import { houseAction } from './actions.js';
8
- import { classifyDoor, discoveryFailure, doorRefusal } from './refusal.js';
11
+ import { classifyDoor, classifyRead, discoveryFailure, doorRefusal } from './refusal.js';
9
12
  import { houseNotifications } from './stream.js';
10
- import { DOOR_BATCH, DOOR_BATCH_UPLOAD, DOOR_BOOTSTRAP, DOOR_DISCOVER, DOOR_ENUMERATE, DOOR_REVISIONS, DOOR_SELECTION_MAX, PRIVATE_LOCATOR, } from './transport.js';
11
- import { batchPaths, deltaBody, deltaBytes, deltaDigest, historyOutcome, houseChanges, mutationOutcome, operationHead, rejectedMapping, revisionBody, uploadable, } from './write.js';
12
- import { logPosition, presented, reachedVersion, roomVersion, } from './version.js';
13
+ import { DOOR_BATCH, DOOR_BATCH_UPLOAD, DOOR_BOOTSTRAP, DOOR_DISCOVER, DOOR_ENUMERATE, DOOR_FILES_ATTACH, DOOR_FILES_GET, DOOR_REVISIONS, } from './transport.js';
14
+ import { batchPaths, deltaBody, deltaBytes, deltaDigest, historyOutcome, houseChanges, houseMove, mutationOutcome, operationHead, rejectedMapping, revisionBody, uploadable, } from './write.js';
15
+ import { HOUSE_NAMEABLE_ROOM_TYPES, HOUSE_ROOM_TYPES } from './room-types.js';
16
+ import { followsVersion, logPosition, presented, reachedVersion, roomVersion, } from './version.js';
13
17
  const UNCERTAIN = { kind: 'transport-uncertainty' };
14
18
  const UNCERTAIN_READ = { kind: 'transport-uncertainty' };
19
+ const OCTET_STREAM = 'application/octet-stream';
20
+ const EXPIRED_ADDRESS = 403;
15
21
  function lapsedGrant(outcome) {
16
22
  return outcome.kind === 'rejected' && outcome.code === 'upload_unavailable';
17
23
  }
18
- function modelFailure(classified, envelope) {
19
- if (classified === null) {
20
- return envelope === null ? { kind: 'transport-uncertainty' } : MODEL_ABSENT;
24
+ async function heldFiles(authority, held, bound) {
25
+ const listed = await held.files(null, bound + 1);
26
+ const files = listed.slice(0, bound);
27
+ const through = listed.length > bound ? (files.at(-1)?.path ?? null) : null;
28
+ return files.length === 0 ? null : { room: authority, through, files };
29
+ }
30
+ async function reused(scope, held) {
31
+ const sent = new Set(scope.contents.map((entry) => entry.path));
32
+ const contents = [...scope.contents];
33
+ const asked = scope.files.filter((file) => file.binary === undefined && !sent.has(file.path));
34
+ if (asked.length === 0)
35
+ return scope;
36
+ if (held === undefined)
37
+ return null;
38
+ const kept = await held.contents(asked.map(({ path }) => path));
39
+ for (const file of asked) {
40
+ const found = kept.get(file.path);
41
+ if (found === undefined ||
42
+ found.revision !== file.revision ||
43
+ (await sha256Hex(found.content)) !== file.sha256) {
44
+ return null;
45
+ }
46
+ contents.push({ path: file.path, content: found.content });
21
47
  }
22
- return failedModel(classified);
48
+ return { ...scope, contents };
23
49
  }
24
50
  export function createAgentsHouseAdapter(options) {
25
51
  if ('site' in options)
26
- return createSiteAdapter(options.site);
52
+ return createSiteAdapter(options.site, options.snapshot === true);
27
53
  const transport = options.transport;
28
54
  const notifications = houseNotifications(transport, 'credential');
29
55
  const tracked = new Map();
30
56
  const handed = new Map();
31
- const models = modelShelf();
32
- function bootstrappedRoom(envelope, entry) {
33
- const scope = envelope.scopes.find((candidate) => matchesScope(candidate, entry));
34
- if (scope === undefined)
35
- return { kind: 'room-not-readable', locator: entry.locator };
36
- handed.set(entry.locator, scopeLinks(scope));
37
- notifications.hold(entry.authority, scope);
38
- return bootstrapOf(scope, entry);
57
+ const rooms = roomStreams('credential');
58
+ const unreused = new Set();
59
+ let bounds;
60
+ function declared() {
61
+ if (bounds === undefined)
62
+ throw new Error('no Discovery declared the bounds');
63
+ return bounds;
39
64
  }
40
- function enumeratedRoom(enumeration, ask) {
41
- const view = viewOf(enumeration, ask.entry);
42
- if (view === undefined)
43
- return { kind: 'room-not-readable', locator: ask.entry.locator };
44
- notifications.hold(ask.entry.authority, view);
45
- const answer = refreshFrom(view, ask.entry, ask.fromRoomVersion);
46
- if (answer.kind === 'net-advancement') {
47
- handed.set(ask.entry.locator, enumeratedLinks(view, handed.get(ask.entry.locator)));
65
+ async function streamedPage(entry, token, held) {
66
+ const part = await rooms.part(entry, token);
67
+ if ('kind' in part)
68
+ return part;
69
+ const scope = await reused(part.scope, held);
70
+ if (scope === null) {
71
+ unreused.add(entry.locator);
72
+ return UNCERTAIN_READ;
48
73
  }
49
- return answer;
74
+ if (part.first && part.ended)
75
+ handed.set(entry.locator, roomVersion(scope));
76
+ else
77
+ handed.delete(entry.locator);
78
+ notifications.reach(entry.authority, scope);
79
+ return {
80
+ ...(await stepped(bootstrapping(scope))),
81
+ ...(part.models === undefined ? {} : { models: part.models }),
82
+ ...(part.pageToken === undefined ? {} : { pageToken: part.pageToken }),
83
+ bytes: part.bytes,
84
+ };
85
+ }
86
+ async function openedRoom(entry, request) {
87
+ const reusing = unreused.delete(entry.locator) ? undefined : request.held;
88
+ const files = reusing === undefined
89
+ ? null
90
+ : await heldFiles(entry.authority, reusing, declared().max_held_files);
91
+ const answered = await transport.streamed(DOOR_BOOTSTRAP, {
92
+ prefixes: [authorityRoot(entry.handle)],
93
+ ...(files === null ? {} : { held: [files] }),
94
+ }, request.signal ?? new AbortController().signal);
95
+ if (answered.room === null)
96
+ return classifyDoor(answered.status, answered.body, entry.locator) ?? UNCERTAIN_READ;
97
+ return rooms.head(entry, answered.room, request.arriving, request.signal);
98
+ }
99
+ async function enumeratedPage(ask, page) {
100
+ const answer = await transport.door(DOOR_ENUMERATE, {
101
+ prefixes: [authorityRoot(ask.entry.handle)],
102
+ positions: [
103
+ {
104
+ ...presented(ask.entry.authority, { position: page.after, logEpoch: ask.from.logEpoch }),
105
+ page: { through: page.through, read: page.read },
106
+ },
107
+ ],
108
+ });
109
+ const failure = classifyRead(answer.status, answer.body, ask.entry.locator);
110
+ if (failure !== null)
111
+ return failure;
112
+ const enumeration = parseEnumeration(answer.body, 'credential');
113
+ if (enumeration === null)
114
+ return UNCERTAIN_READ;
115
+ return (viewOf(enumeration, ask.entry) ?? { kind: 'room-not-readable', locator: ask.entry.locator });
116
+ }
117
+ async function enumeratedRoom(enumeration, ask) {
118
+ const first = viewOf(enumeration, ask.entry);
119
+ if (first === undefined)
120
+ return { kind: 'room-not-readable', locator: ask.entry.locator };
121
+ const view = await wholeView(first, (page) => enumeratedPage(ask, page));
122
+ if ('kind' in view)
123
+ return view;
124
+ notifications.reach(ask.entry.authority, view);
125
+ const answer = await refreshFrom(view, ask.fromRoomVersion);
126
+ if (answer.kind !== 'net-advancement')
127
+ return answer;
128
+ handed.set(ask.entry.locator, roomVersion(view));
129
+ const models = await viewModels(view, ask.entry);
130
+ return models === undefined ? answer : { ...answer, models };
50
131
  }
51
- function streamed(entry, request, from) {
52
- const links = handed.get(entry.locator);
53
- if (links?.roomVersion !== request.fromRoomVersion)
132
+ async function streamed(entry, request, from) {
133
+ if (handed.get(entry.locator) !== request.fromRoomVersion)
54
134
  return null;
55
- const advanced = notifications.advance(entry, from, (path, revision) => links.revisions.get(path) === revision);
135
+ const advanced = await stepped(notifications.advance(entry, from));
56
136
  if (advanced === null)
57
137
  return null;
58
- if (request.minPosition !== undefined &&
59
- !reachedVersion(advanced.page.roomVersion, request.minPosition, entry.logEpoch))
60
- return null;
61
- const relinked = streamedLinks(links, advanced);
62
- if (relinked === null)
63
- return null;
64
- handed.set(entry.locator, relinked);
65
- return advanced.page;
66
- }
67
- function held(envelope, entry, schema, failure) {
68
- return heldModel(envelope === null ? null : schemaFrom(envelope, entry, schema), schemaPath(entry.handle, schema), failure);
138
+ handed.set(entry.locator, advanced.page.roomVersion);
139
+ const models = await streamedModels(advanced.schemas, entry, 'credential');
140
+ return models === undefined ? advanced.page : { ...advanced.page, models };
69
141
  }
70
- function modelPrefixes(entry) {
71
- return entry.schemas.map((schema) => schemaPath(entry.handle, schema));
142
+ function held(rooms) {
143
+ const kept = rooms.flatMap((room) => {
144
+ const entry = tracked.get(room.locator);
145
+ const at = logPosition(room.roomVersion);
146
+ if (entry === undefined || at === null)
147
+ return [];
148
+ handed.set(room.locator, room.roomVersion);
149
+ notifications.reach(entry.authority, at);
150
+ return [presented(entry.authority, at)];
151
+ });
152
+ notifications.send(kept);
72
153
  }
73
- async function acquireModels(entries) {
74
- const acquired = new Map();
75
- for (const part of selections(entries, (entry) => modelPrefixes(entry).length, DOOR_SELECTION_MAX)) {
76
- const privateEntry = part.find((entry) => entry.locator === PRIVATE_LOCATOR);
77
- const answer = await transport.door(DOOR_BOOTSTRAP, {
78
- prefixes: part.flatMap((entry) => modelPrefixes(entry)),
79
- });
80
- const classified = classifyDoor(answer.status, answer.body, PRIVATE_LOCATOR);
81
- const envelope = classified === null ? parseEnvelope(await bundled(answer.body)) : null;
82
- const failure = modelFailure(classified, envelope);
83
- for (const entry of part) {
84
- acquired.set(modelKey(entry.locator, 'collection'), await held(envelope, entry, entry.schema, failure));
85
- }
86
- if (privateEntry !== undefined) {
87
- acquired.set(modelKey(privateEntry.locator, 'typed-selection'), await held(envelope, privateEntry, HOUSE_SCHEMA, failure));
88
- }
154
+ async function adoptedMove(entry, into, outcome) {
155
+ if (outcome.kind === 'accepted' && outcome.destination !== undefined) {
156
+ await adopted(into, { kind: 'accepted', ...outcome.destination });
89
157
  }
90
- return acquired;
158
+ return adopted(entry, outcome);
91
159
  }
92
- function roomOf(authority, acquired) {
93
- const locator = locatorOf(authority);
94
- const key = modelKey(locator, 'collection');
95
- const collection = models.retain(key, acquired.get(key));
96
- if (locator !== PRIVATE_LOCATOR) {
97
- return discoveredRoom(authority, collection?.identity ?? null, undefined);
98
- }
99
- const selection = models.retain(modelKey(locator, 'typed-selection'), acquired.get(modelKey(locator, 'typed-selection')));
100
- return discoveredRoom(authority, collection?.identity ?? null, providerSelection(selection?.identity ?? null));
160
+ async function adopted(entry, outcome) {
161
+ if (outcome.kind !== 'accepted')
162
+ return outcome;
163
+ const held = handed.get(entry.locator);
164
+ if (held === undefined)
165
+ return outcome;
166
+ const follows = followsVersion(held, outcome.roomVersion);
167
+ if (follows)
168
+ handed.set(entry.locator, outcome.roomVersion);
169
+ const at = logPosition(outcome.roomVersion);
170
+ if (follows && at !== null)
171
+ notifications.reach(entry.authority, at);
172
+ return outcome;
101
173
  }
102
174
  function authorityFor(locator) {
103
175
  return tracked.get(locator);
@@ -111,180 +183,243 @@ export function createAgentsHouseAdapter(options) {
111
183
  const { authority, position, log_epoch: logEpoch } = body;
112
184
  if (typeof position !== 'string' || typeof logEpoch !== 'string')
113
185
  return result;
114
- const locator = authority === undefined
115
- ? PRIVATE_LOCATOR
116
- : [...tracked.values()].find((entry) => entry.authority === authority)?.locator;
186
+ const locator = [...tracked.values()].find((entry) => entry.authority === authority)?.locator;
117
187
  if (locator === undefined)
118
188
  return result;
119
189
  return { ...result, at: { locator, roomVersion: roomVersion({ position, logEpoch }) } };
120
190
  }
121
- async function bundled(body) {
122
- const grant = parseGrant(body);
123
- if (grant === null)
124
- return body;
125
- if (grant.method !== 'GET')
126
- return null;
127
- const answer = await transport.transfer({
128
- act: 'local_copy_bundle',
129
- method: 'GET',
130
- url: grant.url,
131
- answer: 'json',
132
- });
133
- return answer.status === 200 ? answer.body : null;
134
- }
135
- function weight(entry) {
136
- return contentPrefixes(entry).length;
137
- }
138
- async function bootstrapped(entries) {
139
- const answers = [];
140
- for (const part of selections(entries, weight, DOOR_SELECTION_MAX)) {
141
- const answer = await transport.door(DOOR_BOOTSTRAP, {
142
- prefixes: part.flatMap((entry) => contentPrefixes(entry)),
143
- });
144
- const classified = part.map((entry) => classifyDoor(answer.status, answer.body, entry.locator));
145
- const envelope = classified[0] === null ? parseEnvelope(await bundled(answer.body)) : null;
146
- part.forEach((entry, index) => {
147
- const failure = classified[index];
148
- if (failure === null || failure === undefined) {
149
- answers.push(envelope === null ? UNCERTAIN_READ : bootstrappedRoom(envelope, entry));
150
- return;
151
- }
152
- answers.push(failure.kind === 'beyond-horizon' ? UNCERTAIN_READ : failure);
153
- });
154
- }
155
- return answers;
156
- }
157
191
  function layered(asks) {
158
192
  const depths = new Map();
159
193
  const layers = [];
160
194
  for (const ask of asks) {
161
- const depth = depths.get(ask.entry.authority) ?? 0;
162
- depths.set(ask.entry.authority, depth + 1);
195
+ const depth = depths.get(ask.ask.entry.authority) ?? 0;
196
+ depths.set(ask.ask.entry.authority, depth + 1);
163
197
  (layers[depth] ??= []).push(ask);
164
198
  }
165
199
  return layers;
166
200
  }
167
201
  async function enumerated(asks) {
168
- const answers = new Map();
169
- const parts = layered(asks).flatMap((layer) => selections(layer, (ask) => weight(ask.entry), DOOR_SELECTION_MAX));
202
+ const answers = [];
203
+ const parts = layered(asks.map((ask, index) => ({ ask, index }))).flatMap((layer) => selections(layer, declared().max_prefixes));
170
204
  for (const part of parts) {
171
205
  let open = [...part];
172
206
  while (open.length > 0) {
173
207
  const answer = await transport.door(DOOR_ENUMERATE, {
174
- prefixes: open.flatMap((ask) => contentPrefixes(ask.entry)),
175
- positions: open.map((ask) => ({
176
- ...presented(ask.entry.authority, ask.from),
177
- ...(ask.minPosition === undefined ? {} : { min_position: ask.minPosition }),
178
- })),
208
+ prefixes: open.map(({ ask }) => authorityRoot(ask.entry.handle)),
209
+ positions: open.map(({ ask }) => presented(ask.entry.authority, ask.from)),
179
210
  });
180
- const refusal = doorRefusal(answer.body);
181
- if (refusal?.code === 'replica_behind') {
182
- const named = open.filter((ask) => ask.entry.authority === refusal.fields.authority);
183
- const behind = named.length === 0 ? open : named;
184
- for (const ask of behind)
185
- answers.set(ask, { kind: 'retryable-refusal', ...refusal });
186
- open = open.filter((ask) => !behind.includes(ask));
187
- continue;
188
- }
189
- const classified = open.map((ask) => classifyDoor(answer.status, answer.body, ask.entry.locator));
211
+ const classified = open.map(({ ask }) => classifyRead(answer.status, answer.body, ask.entry.locator));
190
212
  if (classified[0]?.kind === 'beyond-horizon') {
191
213
  const named = doorRefusal(answer.body)?.fields.authority;
192
- const expired = open.filter((ask) => ask.entry.authority === named);
214
+ const expired = open.filter(({ ask }) => ask.entry.authority === named);
193
215
  const answered = expired.length === 0 ? UNCERTAIN_READ : { kind: 'beyond-horizon' };
194
216
  const gone = expired.length === 0 ? open : expired;
195
217
  for (const ask of gone)
196
- answers.set(ask, answered);
218
+ answers[ask.index] = answered;
197
219
  open = open.filter((ask) => !gone.includes(ask));
198
220
  continue;
199
221
  }
200
222
  const enumeration = classified[0] === null ? parseEnumeration(answer.body, 'credential') : null;
201
- open.forEach((ask, index) => {
202
- const failure = classified[index];
223
+ for (const [answerIndex, { ask, index }] of open.entries()) {
224
+ const failure = classified[answerIndex];
203
225
  if (failure !== null && failure !== undefined) {
204
- answers.set(ask, failure);
205
- return;
226
+ answers[index] = failure;
227
+ continue;
206
228
  }
207
- answers.set(ask, enumeration === null ? UNCERTAIN_READ : enumeratedRoom(enumeration, ask));
208
- });
229
+ answers[index] =
230
+ enumeration === null ? UNCERTAIN_READ : await enumeratedRoom(enumeration, ask);
231
+ }
209
232
  open = [];
210
233
  }
211
234
  }
212
- return asks.map((ask) => answers.get(ask) ?? UNCERTAIN_READ);
235
+ return answers;
213
236
  }
214
- const bootstrapTogether = gathered(bootstrapped);
215
237
  const enumerateTogether = gathered(enumerated);
216
238
  async function uploaded(head, changes, delta, bytes, entry, handed, keep) {
217
239
  const paths = batchPaths(changes);
218
240
  const sha256 = await deltaDigest(delta);
219
241
  if (handed !== undefined && handed.sha256 === sha256) {
220
- return { body: { ...head, paths, upload: handed } };
242
+ return { body: { ...head, paths, upload: handed, runtime: notifications.runtime } };
221
243
  }
222
244
  const minted = await transport.door(DOOR_BATCH_UPLOAD, { ...head, paths, bytes, sha256 });
223
245
  if (minted.status !== 200) {
224
- return { outcome: mutationOutcome(minted.status, minted.body, entry.locator, entry.handle) };
246
+ return {
247
+ outcome: await stepped(mutationOutcome(minted.status, minted.body, entry.locator, entry.handle)),
248
+ };
225
249
  }
226
250
  const grant = parseGrant(minted.body);
227
- if (grant === null || grant.method !== 'POST')
251
+ if (grant === null)
228
252
  return { outcome: UNCERTAIN };
229
253
  const delivered = await transport.transfer({
230
254
  act: 'authored_batch_upload',
231
- method: 'POST',
232
255
  url: grant.url,
233
- answer: 'json',
234
256
  body: `${grant.operation}\n${delta}`,
235
257
  });
236
258
  if (delivered.status !== 200)
237
259
  return { outcome: UNCERTAIN };
238
260
  const holding = parseGrant(delivered.body);
239
- if (holding === null || holding.method !== 'POST')
261
+ if (holding === null)
240
262
  return { outcome: UNCERTAIN };
241
263
  const upload = { url: holding.url, operation: holding.operation, bytes, sha256 };
242
264
  await keep(upload);
243
- return { body: { ...head, paths, upload } };
265
+ return { body: { ...head, paths, upload, runtime: notifications.runtime } };
266
+ }
267
+ async function staged(answer, { changeBatch: batch, file }) {
268
+ const refusal = doorRefusal(answer.body);
269
+ if (refusal?.code !== 'files_unstaged')
270
+ return null;
271
+ const uploads = refusal.fields.upload;
272
+ if (!Array.isArray(uploads))
273
+ return false;
274
+ for (const named of uploads) {
275
+ const upload = houseUpload(named);
276
+ const change = batch.changes.find((held) => held.kind === 'binary' && held.sha256 === named.sha256);
277
+ if (upload === null || change === undefined)
278
+ return false;
279
+ const finished = await finishedUpload(transport, upload, await file(change.localId));
280
+ if (finished?.body?.staged !== true)
281
+ return false;
282
+ }
283
+ return true;
244
284
  }
245
- async function submit(head, changes, delta, bytes, entry, handed, keep) {
246
- const prepared = uploadable(bytes)
285
+ async function submit(request, head, changes, delta, bytes, entry, handed, keep, into) {
286
+ const inline = { ...head, changes, runtime: notifications.runtime };
287
+ const prepared = uploadable(inline, bytes, declared())
247
288
  ? await uploaded(head, changes, delta, bytes, entry, handed, keep)
248
- : { body: { ...head, changes } };
289
+ : { body: inline };
249
290
  if ('outcome' in prepared)
250
291
  return prepared.outcome;
251
292
  const answer = await transport.door(DOOR_BATCH, prepared.body);
252
- return mutationOutcome(answer.status, answer.body, entry.locator, entry.handle);
293
+ const stagedFiles = await staged(answer, request);
294
+ if (stagedFiles === false)
295
+ return UNCERTAIN;
296
+ const settled = stagedFiles === null ? answer : await transport.door(DOOR_BATCH, prepared.body);
297
+ if (stagedFiles === true && (await staged(settled, request)) !== null)
298
+ return UNCERTAIN;
299
+ return stepped(mutationOutcome(settled.status, settled.body, entry.locator, entry.handle, into === undefined
300
+ ? undefined
301
+ : {
302
+ source: { authority: entry.authority, handle: entry.handle },
303
+ destination: { authority: into.authority, handle: into.handle },
304
+ }));
305
+ }
306
+ function addressed(answer, locator) {
307
+ const failure = classifyDoor(answer.status, answer.body, locator);
308
+ if (failure !== null) {
309
+ return failure.kind === 'scoped-refusal'
310
+ ? {
311
+ kind: 'rejected',
312
+ code: failure.code,
313
+ fields: failure.fields,
314
+ retryable: failure.retryable,
315
+ }
316
+ : failure;
317
+ }
318
+ const address = parseFileAddress(answer.body);
319
+ return address === null ? UNCERTAIN_READ : { kind: 'address', ...address };
320
+ }
321
+ function linked(answer, locator) {
322
+ const address = addressed(answer, locator);
323
+ return address.kind === 'address'
324
+ ? { kind: 'link', url: address.url, name: address.name, mediaType: address.mediaType }
325
+ : address;
326
+ }
327
+ function refusedAttach(answer, locator) {
328
+ const failure = classifyDoor(answer.status, answer.body, locator);
329
+ if (failure === null)
330
+ return null;
331
+ return failure.kind === 'scoped-refusal'
332
+ ? {
333
+ kind: 'rejected',
334
+ code: failure.code,
335
+ fields: failure.fields,
336
+ retryable: failure.retryable,
337
+ }
338
+ : failure;
339
+ }
340
+ async function downloaded(ask, locator) {
341
+ let address = addressed(await ask(), locator);
342
+ if (address.kind !== 'address')
343
+ return address;
344
+ let read = await transport.download(address.url);
345
+ if (read.status === EXPIRED_ADDRESS) {
346
+ address = addressed(await ask(), locator);
347
+ if (address.kind !== 'address')
348
+ return address;
349
+ read = await transport.download(address.url);
350
+ }
351
+ if (read.status !== 200 || read.body === null)
352
+ return UNCERTAIN_READ;
353
+ return {
354
+ kind: 'binary',
355
+ body: read.body,
356
+ mediaType: address.mediaType,
357
+ sha256: address.sha256,
358
+ };
359
+ }
360
+ function pathAddress(request) {
361
+ const entry = authorityFor(request.locator);
362
+ if (entry === undefined)
363
+ return null;
364
+ return () => transport.door(DOOR_FILES_GET, {
365
+ room_ref: entry.authority,
366
+ path: request.path,
367
+ revision: request.revision,
368
+ });
253
369
  }
254
370
  return {
371
+ roomTypes: HOUSE_ROOM_TYPES,
372
+ nameableRoomTypes: HOUSE_NAMEABLE_ROOM_TYPES,
255
373
  async authorize() {
256
374
  return options.authorize();
257
375
  },
258
- async model(_authorization, request) {
259
- return models.answer(request);
260
- },
261
- async discover(_authorization) {
262
- const answer = await transport.door(DOOR_DISCOVER, { prefixes: [...DISCOVER_PREFIXES] });
263
- const classified = classifyDoor(answer.status, answer.body, PRIVATE_LOCATOR);
264
- if (classified !== null)
265
- return discoveryFailure(classified);
376
+ async discover(_authorization, scope) {
377
+ const answer = await transport.door(DOOR_DISCOVER, {
378
+ prefixes: [...DISCOVER_PREFIXES],
379
+ ...(scope === undefined ? {} : { rooms: scope.authorities }),
380
+ });
381
+ const failed = discoveryFailure(answer.status, answer.body);
382
+ if (failed !== null)
383
+ return failed;
266
384
  const document = parseDiscovery(answer.body);
267
385
  if (document === null)
268
386
  return { kind: 'transport-uncertainty' };
387
+ bounds = document.bounds;
269
388
  const entries = trackedFrom(document);
270
- tracked.clear();
389
+ const covered = scope === undefined
390
+ ? null
391
+ : [
392
+ ...new Set([
393
+ ...[...tracked.values()]
394
+ .filter((entry) => scope.authorities.includes(entry.authority))
395
+ .map((entry) => entry.locator),
396
+ ...entries.map((entry) => entry.locator),
397
+ ]),
398
+ ];
399
+ if (covered === null)
400
+ tracked.clear();
401
+ else
402
+ for (const locator of covered)
403
+ tracked.delete(locator);
271
404
  for (const entry of entries)
272
405
  tracked.set(entry.locator, entry);
273
406
  for (const locator of handed.keys())
274
407
  if (!tracked.has(locator))
275
408
  handed.delete(locator);
276
- notifications.track(entries);
277
- const acquired = await acquireModels(entries);
278
- models.keep(entries.map((entry) => entry.locator));
279
- return mapDiscovery(document, document.authorities.map((authority) => roomOf(authority, acquired)), capabilities(document.actions));
409
+ notifications.track([...tracked.values()]);
410
+ return {
411
+ ...mapDiscovery(document, document.authorities.map((authority) => discoveredRoom(authority)), capabilities(document.actions, [...tracked.values()])),
412
+ member: document.member,
413
+ ...(covered === null ? {} : { covered }),
414
+ };
280
415
  },
281
416
  async bootstrap(_authorization, request) {
282
417
  const entry = authorityFor(request.locator);
283
418
  if (entry === undefined)
284
419
  return { kind: 'room-not-readable', locator: request.locator };
285
- if (request.pageToken !== undefined)
286
- return { kind: 'transport-uncertainty' };
287
- return bootstrapTogether(entry);
420
+ return request.pageToken === undefined
421
+ ? openedRoom(entry, request)
422
+ : streamedPage(entry, request.pageToken, request.held);
288
423
  },
289
424
  async refresh(_authorization, request) {
290
425
  const entry = authorityFor(request.locator);
@@ -295,32 +430,36 @@ export function createAgentsHouseAdapter(options) {
295
430
  const from = logPosition(request.fromRoomVersion);
296
431
  if (from === null)
297
432
  return { kind: 'beyond-horizon' };
298
- const answered = streamed(entry, request, from);
433
+ const answered = await streamed(entry, request, from);
299
434
  if (answered !== null)
300
435
  return answered;
301
- const minPosition = request.minPosition === undefined ? null : logPosition(request.minPosition);
302
- return enumerateTogether({
303
- entry,
304
- from,
305
- fromRoomVersion: request.fromRoomVersion,
306
- ...(minPosition?.logEpoch === from.logEpoch ? { minPosition: minPosition.position } : {}),
307
- });
436
+ return enumerateTogether({ entry, from, fromRoomVersion: request.fromRoomVersion });
308
437
  },
309
438
  async mutate(_authorization, request, keep) {
310
439
  const entry = authorityFor(request.locator);
311
440
  if (entry === undefined)
312
441
  return { kind: 'room-not-readable', locator: request.locator };
313
- const mapped = houseChanges(request.changeBatch, entry.handle);
442
+ const batch = request.changeBatch;
443
+ const destination = batch.between?.destination.room;
444
+ const into = destination === undefined ? undefined : authorityFor(destination);
445
+ if (destination !== undefined && into === undefined) {
446
+ return { kind: 'room-not-readable', locator: destination };
447
+ }
448
+ const mapped = into === undefined
449
+ ? houseChanges(batch, entry.handle)
450
+ : houseMove(batch, entry.handle, into.handle);
314
451
  if (mapped.kind === 'unmapped')
315
452
  return rejectedMapping(mapped);
316
- const head = operationHead(request.changeBatch);
453
+ const head = operationHead(batch);
317
454
  const delta = deltaBody(mapped.changes);
318
455
  const bytes = deltaBytes(delta);
319
456
  const handed = request.upload;
320
- const outcome = await submit(head, mapped.changes, delta, bytes, entry, handed, keep);
457
+ const answer = (upload) => submit(request, head, mapped.changes, delta, bytes, entry, upload, keep, into);
458
+ const settle = (outcome) => into === undefined ? adopted(entry, outcome) : adoptedMove(entry, into, outcome);
459
+ const outcome = await answer(handed);
321
460
  if (handed === undefined || !lapsedGrant(outcome))
322
- return outcome;
323
- return submit(head, mapped.changes, delta, bytes, entry, undefined, keep);
461
+ return settle(outcome);
462
+ return settle(await answer(undefined));
324
463
  },
325
464
  async history(_authorization, request) {
326
465
  const entry = authorityFor(request.locator);
@@ -337,13 +476,61 @@ export function createAgentsHouseAdapter(options) {
337
476
  ...(request.revision === undefined ? {} : { revision: request.revision }),
338
477
  });
339
478
  },
479
+ async binary(_authorization, request) {
480
+ const ask = pathAddress(request);
481
+ if (ask === null)
482
+ return { kind: 'room-not-readable', locator: request.locator };
483
+ return downloaded(ask, request.locator);
484
+ },
485
+ async link(_authorization, request) {
486
+ const ask = pathAddress(request);
487
+ if (ask === null)
488
+ return { kind: 'room-not-readable', locator: request.locator };
489
+ return linked(await ask(), request.locator);
490
+ },
491
+ async attach(_authorization, request) {
492
+ const entry = authorityFor(request.locator);
493
+ if (entry === undefined)
494
+ return { kind: 'room-not-readable', locator: request.locator };
495
+ const declared = await transport.door(DOOR_FILES_ATTACH, {
496
+ room_ref: entry.authority,
497
+ name: request.name,
498
+ bytes: request.byteLength,
499
+ sha256: request.sha256,
500
+ media_type: request.mediaType.length > 0 ? request.mediaType : OCTET_STREAM,
501
+ });
502
+ const refused = refusedAttach(declared, request.locator);
503
+ if (refused !== null)
504
+ return refused;
505
+ const upload = houseUpload(declared.body?.upload);
506
+ if (upload === null)
507
+ return UNCERTAIN_READ;
508
+ const finished = await finishedUpload(transport, upload, request.blob);
509
+ if (finished === null)
510
+ return UNCERTAIN_READ;
511
+ const unfinished = refusedAttach(finished, request.locator);
512
+ if (unfinished !== null)
513
+ return unfinished;
514
+ const { path, revision } = (finished.body ?? {});
515
+ const root = `/rooms/${entry.handle}/`;
516
+ return typeof path === 'string' && path.startsWith(root) && typeof revision === 'string'
517
+ ? { kind: 'attached', path: path.slice(root.length), revision }
518
+ : UNCERTAIN_READ;
519
+ },
340
520
  reached(locator, version, target) {
341
521
  return reachedVersion(version, target, authorityFor(locator)?.logEpoch);
342
522
  },
523
+ follows(_locator, version, next) {
524
+ return followsVersion(version, next);
525
+ },
343
526
  async action(_authorization, request) {
344
527
  return withAt(await houseAction(transport, request));
345
528
  },
346
- roomVersions: notifications,
529
+ roomStream: {
530
+ hold: held,
531
+ reopen: notifications.reopen,
532
+ observe: notifications.observe,
533
+ },
347
534
  conversations: notifications.conversations,
348
535
  serviceMode: notifications.serviceMode,
349
536
  };