@agentshouse/mdruntime-adapter 0.1.0-c3bd45bca89d3 → 0.1.0-c447081d8ccca

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.
package/dist/actions.js CHANGED
@@ -11,20 +11,19 @@ function mapped(door, input = (given) => given) {
11
11
  },
12
12
  };
13
13
  }
14
- function carried(door, carry) {
14
+ function carried(door, carry, batched) {
15
15
  return {
16
16
  door,
17
+ ...(batched === undefined ? {} : { batched }),
17
18
  carry: (transport, input, name) => carry(transport, `/door/${door}`, input, name),
18
19
  };
19
20
  }
20
21
  const APP_ACTS = {
21
22
  'access.read': mapped('rooms/access/read'),
22
- 'attachment.read': carried('attachments/get', openAction),
23
- 'attachment.upload': carried('attachments/upload', attachAction),
24
23
  'conversation.answer': mapped('conversations/interaction/answer', answerBody),
25
- 'conversation.create': mapped('conversations/create', createBody),
24
+ 'conversation.create': carried('conversations/create', createAction),
26
25
  'conversation.delete': mapped('conversations/delete', controlBody),
27
- 'conversation.history': carried('conversations/history', historyAction),
26
+ 'conversation.history': carried('conversations/history', historyAction, ['conversations']),
28
27
  'conversation.interrupt': mapped('conversations/interrupt', controlBody),
29
28
  'conversation.kill': mapped('conversations/kill', controlBody),
30
29
  'conversation.markDone': mapped('conversations/done'),
@@ -37,7 +36,7 @@ const APP_ACTS = {
37
36
  'member.list': mapped('rooms/members'),
38
37
  'message.send': mapped('apps/messages/send'),
39
38
  'processing.read': mapped('rooms/settings/processing/read'),
40
- 'record.list': mapped('records/read'),
39
+ 'record.list': carried('records/read', recordsAction),
41
40
  'relay.read': mapped('apps/relay'),
42
41
  'routine.list': mapped('routines/access'),
43
42
  'routineAccess.list': mapped('routines/granted'),
@@ -48,9 +47,14 @@ const APP_ACTS = {
48
47
  'triggerOccurrence.list': mapped('triggers/fired'),
49
48
  };
50
49
  export const HOUSE_APP_ACTS = Object.fromEntries(Object.entries(APP_ACTS).map(([name, act]) => [name, act.door]));
50
+ export const SITE_SUBMIT = 'submit';
51
+ export const HOUSE_SITE_ACTS = {
52
+ [SITE_SUBMIT]: 'site/submission',
53
+ };
54
+ export const HOUSE_APP_BATCHES = Object.fromEntries(Object.entries(APP_ACTS).flatMap(([name, act]) => act.batched === undefined ? [] : [[name, act.batched]]));
51
55
  const APP_NAMES = new Map(Object.entries(APP_ACTS).map(([name, act]) => [act.door, name]));
52
56
  export function houseConversationAgents(locator) {
53
- return { locator, type: 'house-agent', identity: 'agent', name: 'name' };
57
+ return { locator, type: 'house-agent', identity: 'agent', name: 'name', retired: 'retired' };
54
58
  }
55
59
  export function declaredActions(routes) {
56
60
  return routes.map((route) => ({
@@ -112,10 +116,25 @@ function answerBody(input) {
112
116
  response: nested.response,
113
117
  };
114
118
  }
119
+ async function createAction(transport, route, input, name) {
120
+ const outcome = actionOutcome(await transport.door(route, createBody(input)), name);
121
+ if (outcome.kind !== 'action')
122
+ return outcome;
123
+ const held = record(outcome.result);
124
+ const conversation = text(held, 'conversation_id');
125
+ return conversation === undefined
126
+ ? outcome
127
+ : {
128
+ ...outcome,
129
+ result: { ...held, conversation },
130
+ };
131
+ }
115
132
  function withTurn(body) {
116
133
  const held = record(body);
117
134
  const turn = text(held, 'message_id');
118
- return turn === undefined ? body : { ...held, turn };
135
+ return turn === undefined
136
+ ? body
137
+ : { ...held, turn };
119
138
  }
120
139
  export function actionOutcome(answer, name) {
121
140
  if (answer.status === 401)
@@ -129,6 +148,32 @@ export function actionOutcome(answer, name) {
129
148
  return { kind: 'transport-uncertainty' };
130
149
  return { kind: 'action', result: answer.body };
131
150
  }
151
+ function referredRecord(view, roomRef) {
152
+ const held = record(view);
153
+ if (roomRef === undefined || typeof held.record !== 'string' || !Array.isArray(held.attachments))
154
+ return view;
155
+ const referrer = {
156
+ room_ref: roomRef,
157
+ record: held.record,
158
+ };
159
+ return {
160
+ ...held,
161
+ attachments: held.attachments.map((attachment) => ({ ...record(attachment), referrer })),
162
+ };
163
+ }
164
+ async function recordsAction(transport, route, input, name) {
165
+ const outcome = actionOutcome(await transport.door(route, input), name);
166
+ if (outcome.kind !== 'action')
167
+ return outcome;
168
+ const roomRef = text(input, 'room_ref');
169
+ const read = record(outcome.result);
170
+ return {
171
+ ...outcome,
172
+ result: Array.isArray(read.records)
173
+ ? { ...read, records: read.records.map((view) => referredRecord(view, roomRef)) }
174
+ : referredRecord(outcome.result, roomRef),
175
+ };
176
+ }
132
177
  async function carry(transport, route, name, input) {
133
178
  return actionOutcome(await transport.door(route, input), name);
134
179
  }
@@ -169,12 +214,13 @@ function sendFiles(input) {
169
214
  }
170
215
  function sendBody(input) {
171
216
  const files = sendFiles(input);
172
- if (files === null)
217
+ const operation = text(input, 'operation_id');
218
+ if (files === null || operation === undefined)
173
219
  return null;
174
220
  const textValue = text(input, 'text');
175
221
  return {
176
222
  conversation_id: text(input, 'conversation'),
177
- operation_id: operationId(input),
223
+ operation_id: operation,
178
224
  ...(textValue !== undefined && textValue.length > 0 ? { text: textValue } : {}),
179
225
  ...(files.length === 0 ? {} : { files }),
180
226
  };
@@ -187,9 +233,6 @@ async function fileBytes(file) {
187
233
  return null;
188
234
  return new Uint8Array(await blob.arrayBuffer());
189
235
  }
190
- function delivered(answer, name) {
191
- return answer.status === 200 ? null : actionOutcome(answer, name);
192
- }
193
236
  function uploadGrant(entry) {
194
237
  if (!('upload' in record(entry)))
195
238
  return 'absent';
@@ -200,84 +243,28 @@ function uploadGrant(entry) {
200
243
  return null;
201
244
  return { method: 'POST', operation: upload.operation, url: upload.url };
202
245
  }
203
- async function uploadOriginals(transport, input, result, name) {
204
- const originals = record(result).originals;
205
- if (!Array.isArray(originals) || originals.length === 0)
206
- return null;
246
+ async function uploadFiles(transport, input, result) {
247
+ const sent = record(result).files;
248
+ if (!Array.isArray(sent))
249
+ return true;
207
250
  const files = Array.isArray(record(input).files) ? record(input).files : [];
208
- for (const [index, entry] of originals.entries()) {
251
+ for (const [index, entry] of sent.entries()) {
209
252
  const grant = uploadGrant(entry);
210
253
  if (grant === 'absent')
211
254
  continue;
212
- if (grant === null)
213
- return malformed();
214
255
  const bytes = index < files.length ? await fileBytes(files[index]) : null;
215
- if (bytes === null) {
216
- return {
217
- kind: 'rejected',
218
- code: 'conversation_original_descriptor_required',
219
- fields: {},
220
- retryable: false,
221
- };
222
- }
223
- const failed = delivered(await transport.transfer({
224
- act: 'conversation_original_upload',
225
- method: 'POST',
256
+ if (grant === null || bytes === null)
257
+ return false;
258
+ const answer = await transport.transfer({
259
+ act: 'conversation_file_upload',
226
260
  url: grant.url,
227
- answer: 'json',
228
261
  body: bytes,
229
262
  operation: grant.operation,
230
- }), name);
231
- if (failed !== null)
232
- return failed;
263
+ });
264
+ if (answer.status !== 200)
265
+ return false;
233
266
  }
234
- return null;
235
- }
236
- async function attachAction(transport, route, input, name) {
237
- const { blob, ...descriptor } = record(input);
238
- const bytes = await fileBytes({ blob });
239
- if (bytes === null)
240
- return malformed();
241
- const outcome = actionOutcome(await transport.door(route, descriptor), name);
242
- if (outcome.kind !== 'action')
243
- return outcome;
244
- const grant = uploadGrant(outcome.result);
245
- if (grant === 'absent')
246
- return outcome;
247
- if (grant === null)
248
- return malformed();
249
- const stored = await transport.transfer({
250
- act: 'original_upload',
251
- method: 'POST',
252
- url: grant.url,
253
- answer: 'json',
254
- body: bytes,
255
- operation: grant.operation,
256
- });
257
- return delivered(stored, name) ?? { kind: 'action', result: stored.body };
258
- }
259
- async function openAction(transport, route, input, name) {
260
- const outcome = actionOutcome(await transport.door(route, input), name);
261
- if (outcome.kind !== 'action')
262
- return outcome;
263
- const { download, ...opened } = record(outcome.result);
264
- if (download === undefined)
265
- return outcome;
266
- const grant = record(download);
267
- if (grant.method !== 'GET' || typeof grant.url !== 'string')
268
- return malformed();
269
- const read = await transport.transfer({
270
- act: 'original_download',
271
- method: 'GET',
272
- url: grant.url,
273
- answer: 'bytes',
274
- });
275
- const failed = delivered(read, name);
276
- if (failed !== null)
277
- return failed;
278
- if (!(read.body instanceof Blob))
279
- return { kind: 'transport-uncertainty' };
280
- return { kind: 'action', result: { ...opened, blob: read.body } };
267
+ return true;
281
268
  }
282
269
  async function sendAction(transport, route, input, name) {
283
270
  const body = sendBody(input);
@@ -286,9 +273,9 @@ async function sendAction(transport, route, input, name) {
286
273
  const outcome = actionOutcome(await transport.door(route, body), name);
287
274
  if (outcome.kind !== 'action')
288
275
  return outcome;
289
- const uploaded = await uploadOriginals(transport, input, outcome.result, name);
290
- if (uploaded !== null)
291
- return uploaded;
276
+ if (!(await uploadFiles(transport, input, outcome.result))) {
277
+ return { kind: 'transport-uncertainty' };
278
+ }
292
279
  return { ...outcome, result: withTurn(outcome.result) };
293
280
  }
294
281
  function historyCursor(value) {
@@ -313,12 +300,19 @@ export function acceptedMessage(entry) {
313
300
  const cursor = historyCursor(entry);
314
301
  if (cursor === null)
315
302
  return null;
303
+ const message = structuredClone(record(entry));
304
+ const referrer = { message: cursor.message_id };
316
305
  return {
317
306
  identity: cursor.message_id,
318
307
  turn: text(entry, 'turn_id') ?? cursor.message_id,
319
308
  position: position(cursor),
320
309
  text: text(entry, 'text') ?? '',
321
- message: structuredClone(entry),
310
+ message: Array.isArray(message.files)
311
+ ? {
312
+ ...message,
313
+ files: message.files.map((file) => ({ ...record(file), referrer })),
314
+ }
315
+ : message,
322
316
  };
323
317
  }
324
318
  function historyPage(entry) {
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,OAAO,EACP,aAAa,EAWd,MAAM,wBAAwB,CAAC;AAuChC,OAAO,EAOL,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AAyBxB,MAAM,MAAM,yBAAyB,GACjC;IACE,SAAS,EAAE,cAAc,CAAC;IAC1B,SAAS,IAAI,OAAO,CAAC,aAAa,CAAC,CAAC;CACrC,GACD;IAAE,IAAI,EAAE,kBAAkB,CAAA;CAAE,CAAC;AAwBjC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAyYpF"}
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAIV,OAAO,EACP,aAAa,EAiBd,MAAM,wBAAwB,CAAC;AA4ChC,OAAO,EASL,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AAyBxB,MAAM,MAAM,yBAAyB,GACjC;IACE,SAAS,EAAE,cAAc,CAAC;IAC1B,SAAS,IAAI,OAAO,CAAC,aAAa,CAAC,CAAC;CACrC,GACD;IAAE,IAAI,EAAE,kBAAkB,CAAA;CAAE,CAAC;AAoEjC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CA+gBpF"}
package/dist/adapter.js CHANGED
@@ -2,19 +2,48 @@ import { DISCOVER_PREFIXES, capabilities, discoveredRoom, mapDiscovery, parseDis
2
2
  import { partModels, streamedModels, viewModels } from './model.js';
3
3
  import { gathered, gatheredEach, selections } from './gather.js';
4
4
  import { createSiteAdapter } from './site.js';
5
- import { bootstrapOf, contentPrefixes, matchesScope, parseEnumeration, parseEnvelope, parseGrant, refreshFrom, viewOf, } from './read.js';
6
- import { acceptedLinks, enumeratedLinks, heldLinks, scopeLinks, streamedLinks, } from './links.js';
5
+ import { bootstrapOf, contentPrefixes, matchesScope, parseEnumeration, parseEnvelope, parseGrant, refreshFrom, viewOf, wholeView, } from './read.js';
6
+ import { sha256Hex } from './digest.js';
7
+ import { acceptedHanded, enumeratedHanded, heldHanded, scopeHanded, streamedHanded, } from './handed.js';
7
8
  import { houseAction } from './actions.js';
8
9
  import { classifyDoor, classifyRead, discoveryFailure, doorRefusal } from './refusal.js';
9
10
  import { houseNotifications } from './stream.js';
10
- import { DOOR_BATCH, DOOR_BATCH_UPLOAD, DOOR_BOOTSTRAP, DOOR_DISCOVER, DOOR_ENUMERATE, DOOR_REVISIONS, } from './transport.js';
11
+ import { DOOR_BATCH, DOOR_BATCH_UPLOAD, DOOR_BOOTSTRAP, DOOR_DISCOVER, DOOR_ENUMERATE, DOOR_FILES_GET, DOOR_REVISIONS, } from './transport.js';
11
12
  import { batchPaths, deltaBody, deltaBytes, deltaDigest, historyOutcome, houseChanges, mutationOutcome, operationHead, rejectedMapping, revisionBody, uploadable, } from './write.js';
13
+ import { houseReferrer } from './referrer.js';
12
14
  import { followsVersion, logPosition, presented, reachedVersion, roomVersion, } from './version.js';
13
15
  const UNCERTAIN = { kind: 'transport-uncertainty' };
14
16
  const UNCERTAIN_READ = { kind: 'transport-uncertainty' };
15
17
  function lapsedGrant(outcome) {
16
18
  return outcome.kind === 'rejected' && outcome.code === 'upload_unavailable';
17
19
  }
20
+ function heldFiles(authority, held, after, budget) {
21
+ if (held === undefined || budget === 0)
22
+ return null;
23
+ const paths = Object.keys(held.revisions)
24
+ .filter((path) => held.documents[path] !== undefined && (after === null || path > after))
25
+ .sort();
26
+ if (paths.length === 0)
27
+ return null;
28
+ const files = paths.slice(0, budget).map((path) => ({ path, revision: held.revisions[path] }));
29
+ return { room: authority, through: paths.length > budget ? files.at(-1).path : null, files };
30
+ }
31
+ async function reused(scope, held) {
32
+ const sent = new Set(scope.contents.map((entry) => entry.path));
33
+ const contents = [...scope.contents];
34
+ for (const file of scope.files) {
35
+ if (file.binary !== undefined || sent.has(file.path))
36
+ continue;
37
+ const content = held?.documents[file.path];
38
+ if (content === undefined ||
39
+ held?.revisions[file.path] !== file.revision ||
40
+ (await sha256Hex(content)) !== file.sha256) {
41
+ return null;
42
+ }
43
+ contents.push({ path: file.path, content });
44
+ }
45
+ return { ...scope, contents };
46
+ }
18
47
  export function createAgentsHouseAdapter(options) {
19
48
  if ('site' in options)
20
49
  return createSiteAdapter(options.site);
@@ -28,12 +57,22 @@ export function createAgentsHouseAdapter(options) {
28
57
  throw new Error('no Discovery declared the bounds');
29
58
  return bounds;
30
59
  }
31
- async function bootstrappedRoom(envelope, scope, entry, continued) {
32
- if (scope === undefined)
60
+ async function bootstrappedRoom(envelope, sent, asked, continued) {
61
+ const { entry } = asked;
62
+ if (sent === undefined)
33
63
  return { kind: 'room-not-readable', locator: entry.locator };
34
- const next = envelope.next?.room === entry.authority ? envelope.next.path : null;
64
+ const scope = await reused(sent, asked.held);
65
+ if (scope === null) {
66
+ return asked.held === undefined
67
+ ? UNCERTAIN_READ
68
+ : continued === null
69
+ ? bootstrapTogether({ entry, held: undefined })
70
+ : continuedBootstrap({ entry, held: undefined }, continued);
71
+ }
72
+ const cursor = envelope.next?.room === entry.authority ? envelope.next : undefined;
73
+ const next = cursor?.path ?? null;
35
74
  if (continued === null && next === null)
36
- handed.set(entry.locator, scopeLinks(scope));
75
+ handed.set(entry.locator, scopeHanded(scope));
37
76
  else
38
77
  handed.delete(entry.locator);
39
78
  notifications.reach(entry.authority, scope);
@@ -42,36 +81,56 @@ export function createAgentsHouseAdapter(options) {
42
81
  ...entry.schemas.filter((schema) => scope.files.some((file) => file.path === schema)),
43
82
  ];
44
83
  const models = await partModels(scope, entry, new Set(seen), next === null);
45
- const continuation = next === null ? null : { after: next, seen };
84
+ const continuation = next === null
85
+ ? null
86
+ : { after: next, seen, ...(cursor?.cut === undefined ? {} : { cut: cursor.cut }) };
46
87
  return {
47
88
  ...bootstrapOf(scope),
48
89
  ...(models === undefined ? {} : { models }),
49
90
  ...(continuation === null ? {} : { pageToken: JSON.stringify(continuation) }),
50
91
  };
51
92
  }
93
+ async function enumeratedPage(ask, page) {
94
+ const answer = await transport.door(DOOR_ENUMERATE, {
95
+ prefixes: contentPrefixes(ask.entry),
96
+ positions: [
97
+ {
98
+ ...presented(ask.entry.authority, { position: page.after, logEpoch: ask.from.logEpoch }),
99
+ page: { through: page.through, read: page.read },
100
+ },
101
+ ],
102
+ });
103
+ const failure = classifyRead(answer.status, answer.body, ask.entry.locator);
104
+ if (failure !== null)
105
+ return failure;
106
+ const enumeration = parseEnumeration(answer.body, 'credential');
107
+ if (enumeration === null)
108
+ return UNCERTAIN_READ;
109
+ return (viewOf(enumeration, ask.entry) ?? { kind: 'room-not-readable', locator: ask.entry.locator });
110
+ }
52
111
  async function enumeratedRoom(enumeration, ask) {
53
- const view = viewOf(enumeration, ask.entry);
54
- if (view === undefined)
112
+ const first = viewOf(enumeration, ask.entry);
113
+ if (first === undefined)
55
114
  return { kind: 'room-not-readable', locator: ask.entry.locator };
115
+ const view = await wholeView(first, (page) => enumeratedPage(ask, page));
116
+ if ('kind' in view)
117
+ return view;
56
118
  notifications.reach(ask.entry.authority, view);
57
119
  const answer = refreshFrom(view, ask.fromRoomVersion);
58
120
  if (answer.kind !== 'net-advancement')
59
121
  return answer;
60
- handed.set(ask.entry.locator, enumeratedLinks(view, handed.get(ask.entry.locator)));
122
+ handed.set(ask.entry.locator, enumeratedHanded(view, handed.get(ask.entry.locator)));
61
123
  const models = await viewModels(view, ask.entry);
62
124
  return models === undefined ? answer : { ...answer, models };
63
125
  }
64
126
  async function streamed(entry, request, from) {
65
- const links = handed.get(entry.locator);
66
- if (links?.roomVersion !== request.fromRoomVersion)
127
+ const held = handed.get(entry.locator);
128
+ if (held?.roomVersion !== request.fromRoomVersion)
67
129
  return null;
68
- const advanced = notifications.advance(entry, from, (path, revision) => links.revisions.get(path) === revision);
130
+ const advanced = notifications.advance(entry, from, (path, revision) => held.revisions.get(path) === revision);
69
131
  if (advanced === null)
70
132
  return null;
71
- const relinked = streamedLinks(links, advanced);
72
- if (relinked === null)
73
- return null;
74
- handed.set(entry.locator, relinked);
133
+ handed.set(entry.locator, streamedHanded(held, advanced));
75
134
  const models = await streamedModels(advanced.schemas, entry, 'credential');
76
135
  return models === undefined ? advanced.page : { ...advanced.page, models };
77
136
  }
@@ -81,7 +140,7 @@ export function createAgentsHouseAdapter(options) {
81
140
  const at = logPosition(room.roomVersion);
82
141
  if (entry === undefined || at === null)
83
142
  return [];
84
- handed.set(room.locator, heldLinks(room));
143
+ handed.set(room.locator, heldHanded(room));
85
144
  notifications.reach(entry.authority, at);
86
145
  return [presented(entry.authority, at)];
87
146
  });
@@ -90,19 +149,15 @@ export function createAgentsHouseAdapter(options) {
90
149
  function adopted(entry, outcome) {
91
150
  if (outcome.kind !== 'accepted')
92
151
  return outcome;
93
- const { originals, ...accepted } = outcome;
94
- const links = handed.get(entry.locator);
95
- if (links === undefined)
96
- return accepted;
97
- const follows = followsVersion(links.roomVersion, accepted.roomVersion);
98
- const relinked = acceptedLinks(links, accepted, follows ? accepted.roomVersion : links.roomVersion, originals);
99
- handed.set(entry.locator, relinked.links);
100
- const at = logPosition(accepted.roomVersion);
152
+ const held = handed.get(entry.locator);
153
+ if (held === undefined)
154
+ return outcome;
155
+ const follows = followsVersion(held.roomVersion, outcome.roomVersion);
156
+ handed.set(entry.locator, acceptedHanded(held, outcome, follows ? outcome.roomVersion : held.roomVersion));
157
+ const at = logPosition(outcome.roomVersion);
101
158
  if (follows && at !== null)
102
159
  notifications.reach(entry.authority, at);
103
- return relinked.attachments === undefined
104
- ? accepted
105
- : { ...accepted, attachments: relinked.attachments };
160
+ return outcome;
106
161
  }
107
162
  function authorityFor(locator) {
108
163
  return tracked.get(locator);
@@ -124,13 +179,19 @@ export function createAgentsHouseAdapter(options) {
124
179
  function weight(entry) {
125
180
  return contentPrefixes(entry).length;
126
181
  }
127
- async function bootstrapped(entries, answer) {
128
- let open = entries.map((entry, ask) => ({ entry, ask }));
182
+ function holding(asks, after) {
183
+ const budget = Math.floor(declared().max_held_files / Math.max(1, asks.filter((ask) => ask.held !== undefined).length));
184
+ return asks.flatMap((ask) => heldFiles(ask.entry.authority, ask.held, after, budget) ?? []);
185
+ }
186
+ async function bootstrapped(asks, answer) {
187
+ let open = asks.map((asked, ask) => ({ entry: asked.entry, asked, ask }));
129
188
  while (open.length > 0) {
130
189
  const unreached = [];
131
190
  for (const part of selections(open, ({ entry }) => weight(entry), declared().max_prefixes)) {
191
+ const held = holding(part.map(({ asked }) => asked), null);
132
192
  const answered = await transport.door(DOOR_BOOTSTRAP, {
133
193
  prefixes: part.flatMap(({ entry }) => contentPrefixes(entry)),
194
+ ...(held.length === 0 ? {} : { held }),
134
195
  });
135
196
  const classified = part.map(({ entry }) => classifyDoor(answered.status, answered.body, entry.locator));
136
197
  const envelope = classified[0] === null ? parseEnvelope(answered.body) : null;
@@ -149,26 +210,33 @@ export function createAgentsHouseAdapter(options) {
149
210
  unreached.push(asked);
150
211
  continue;
151
212
  }
152
- answer(asked.ask, await bootstrappedRoom(envelope, scope, asked.entry, null));
213
+ answer(asked.ask, await bootstrappedRoom(envelope, scope, asked.asked, null));
153
214
  }
154
215
  }
155
216
  open = unreached;
156
217
  }
157
218
  }
158
- async function continuedBootstrap(entry, continued) {
159
- const after = { room: entry.authority, path: continued.after };
219
+ async function continuedBootstrap(asked, continued) {
220
+ const { entry } = asked;
221
+ const after = {
222
+ room: entry.authority,
223
+ path: continued.after,
224
+ ...(continued.cut === undefined ? {} : { cut: continued.cut }),
225
+ };
226
+ const held = holding([asked], continued.after);
160
227
  const answered = await transport.door(DOOR_BOOTSTRAP, {
161
228
  prefixes: contentPrefixes(entry),
162
229
  after,
230
+ ...(held.length === 0 ? {} : { held }),
163
231
  });
164
- const failure = classifyDoor(answered.status, answered.body, entry.locator);
232
+ const failure = classifyRead(answered.status, answered.body, entry.locator);
165
233
  if (failure !== null)
166
234
  return failure;
167
235
  const envelope = parseEnvelope(answered.body);
168
236
  if (envelope === null)
169
237
  return UNCERTAIN_READ;
170
238
  const scope = envelope.scopes.find((candidate) => matchesScope(candidate, entry));
171
- return bootstrappedRoom(envelope, scope, entry, continued);
239
+ return bootstrappedRoom(envelope, scope, asked, continued);
172
240
  }
173
241
  function layered(asks) {
174
242
  const depths = new Map();
@@ -232,9 +300,7 @@ export function createAgentsHouseAdapter(options) {
232
300
  return { outcome: UNCERTAIN };
233
301
  const delivered = await transport.transfer({
234
302
  act: 'authored_batch_upload',
235
- method: 'POST',
236
303
  url: grant.url,
237
- answer: 'json',
238
304
  body: `${grant.operation}\n${delta}`,
239
305
  });
240
306
  if (delivered.status !== 200)
@@ -246,7 +312,30 @@ export function createAgentsHouseAdapter(options) {
246
312
  await keep(upload);
247
313
  return { body: { ...head, paths, upload, runtime: notifications.runtime } };
248
314
  }
249
- async function submit(head, changes, delta, bytes, entry, handed, keep) {
315
+ async function staged(answer, batch) {
316
+ const refusal = doorRefusal(answer.body);
317
+ if (refusal?.code !== 'files_unstaged')
318
+ return null;
319
+ const grants = refusal.fields.upload;
320
+ if (!Array.isArray(grants))
321
+ return false;
322
+ for (const grant of grants) {
323
+ const { url, operation, sha256 } = grant;
324
+ const change = batch.changes.find((held) => held.kind === 'binary' && held.sha256 === sha256);
325
+ if (typeof url !== 'string' || typeof operation !== 'string' || change === undefined)
326
+ return false;
327
+ const delivered = await transport.transfer({
328
+ act: 'binary_stage',
329
+ url,
330
+ body: change.blob,
331
+ operation,
332
+ });
333
+ if (delivered.status !== 200)
334
+ return false;
335
+ }
336
+ return true;
337
+ }
338
+ async function submit(batch, head, changes, delta, bytes, entry, handed, keep) {
250
339
  const inline = { ...head, changes, runtime: notifications.runtime };
251
340
  const prepared = uploadable(inline, bytes, declared())
252
341
  ? await uploaded(head, changes, delta, bytes, entry, handed, keep)
@@ -254,7 +343,33 @@ export function createAgentsHouseAdapter(options) {
254
343
  if ('outcome' in prepared)
255
344
  return prepared.outcome;
256
345
  const answer = await transport.door(DOOR_BATCH, prepared.body);
257
- return mutationOutcome(answer.status, answer.body, entry.locator, entry.handle);
346
+ const stagedFiles = await staged(answer, batch);
347
+ if (stagedFiles === false)
348
+ return UNCERTAIN;
349
+ const settled = stagedFiles === null ? answer : await transport.door(DOOR_BATCH, prepared.body);
350
+ if (stagedFiles === true && (await staged(settled, batch)) !== null)
351
+ return UNCERTAIN;
352
+ return mutationOutcome(settled.status, settled.body, entry.locator, entry.handle);
353
+ }
354
+ async function downloaded(answer, locator) {
355
+ const failure = classifyDoor(answer.status, answer.body, locator);
356
+ if (failure !== null) {
357
+ return failure.kind === 'scoped-refusal'
358
+ ? {
359
+ kind: 'rejected',
360
+ code: failure.code,
361
+ fields: failure.fields,
362
+ retryable: failure.retryable,
363
+ }
364
+ : failure;
365
+ }
366
+ const grant = parseGrant(answer.body);
367
+ if (grant === null || grant.method !== 'GET')
368
+ return UNCERTAIN_READ;
369
+ const read = await transport.download(grant.url);
370
+ if (read.status !== 200 || read.blob === null)
371
+ return UNCERTAIN_READ;
372
+ return { kind: 'binary', blob: read.blob };
258
373
  }
259
374
  return {
260
375
  async authorize() {
@@ -286,10 +401,11 @@ export function createAgentsHouseAdapter(options) {
286
401
  const entry = authorityFor(request.locator);
287
402
  if (entry === undefined)
288
403
  return { kind: 'room-not-readable', locator: request.locator };
404
+ const asked = { entry, held: request.held };
289
405
  if (request.pageToken !== undefined) {
290
- return continuedBootstrap(entry, JSON.parse(request.pageToken));
406
+ return continuedBootstrap(asked, JSON.parse(request.pageToken));
291
407
  }
292
- return bootstrapTogether(entry);
408
+ return bootstrapTogether(asked);
293
409
  },
294
410
  async refresh(_authorization, request) {
295
411
  const entry = authorityFor(request.locator);
@@ -316,10 +432,11 @@ export function createAgentsHouseAdapter(options) {
316
432
  const delta = deltaBody(mapped.changes);
317
433
  const bytes = deltaBytes(delta);
318
434
  const handed = request.upload;
319
- const outcome = await submit(head, mapped.changes, delta, bytes, entry, handed, keep);
435
+ const batch = request.changeBatch;
436
+ const outcome = await submit(batch, head, mapped.changes, delta, bytes, entry, handed, keep);
320
437
  if (handed === undefined || !lapsedGrant(outcome))
321
438
  return adopted(entry, outcome);
322
- return adopted(entry, await submit(head, mapped.changes, delta, bytes, entry, undefined, keep));
439
+ return adopted(entry, await submit(batch, head, mapped.changes, delta, bytes, entry, undefined, keep));
323
440
  },
324
441
  async history(_authorization, request) {
325
442
  const entry = authorityFor(request.locator);
@@ -336,6 +453,37 @@ export function createAgentsHouseAdapter(options) {
336
453
  ...(request.revision === undefined ? {} : { revision: request.revision }),
337
454
  });
338
455
  },
456
+ async binary(_authorization, request) {
457
+ if (request.kind === 'path') {
458
+ const entry = authorityFor(request.locator);
459
+ if (entry === undefined)
460
+ return { kind: 'room-not-readable', locator: request.locator };
461
+ const answer = await transport.door(DOOR_FILES_GET, {
462
+ room_ref: entry.authority,
463
+ path: request.path,
464
+ revision: request.revision,
465
+ });
466
+ return downloaded(answer, request.locator);
467
+ }
468
+ const referrer = houseReferrer(request.referrer, tracked);
469
+ if (referrer === null) {
470
+ return { kind: 'rejected', code: 'referrer_unknown', fields: {}, retryable: false };
471
+ }
472
+ const answer = await transport.door(DOOR_FILES_GET, {
473
+ file: request.fileRef,
474
+ referrer: referrer.referrer,
475
+ });
476
+ return downloaded(answer, referrer.locator);
477
+ },
478
+ referrerScope(referrer) {
479
+ const held = houseReferrer(referrer, tracked);
480
+ if (held === null)
481
+ return null;
482
+ if (held.locator === '')
483
+ return { kind: 'conversations' };
484
+ const { path } = held.referrer;
485
+ return { kind: 'room', locator: held.locator, ...(path === undefined ? {} : { path }) };
486
+ },
339
487
  reached(locator, version, target) {
340
488
  return reachedVersion(version, target, authorityFor(locator)?.logEpoch);
341
489
  },
@@ -345,7 +493,16 @@ export function createAgentsHouseAdapter(options) {
345
493
  async action(_authorization, request) {
346
494
  return withAt(await houseAction(transport, request));
347
495
  },
348
- roomStream: { hold: held, reopen: notifications.reopen, observe: notifications.observe },
496
+ roomStream: {
497
+ hold: held,
498
+ reopen: notifications.reopen,
499
+ observe: notifications.observe,
500
+ published(locator, roomVersion) {
501
+ const at = logPosition(roomVersion);
502
+ if (at !== null)
503
+ notifications.published(locator, at);
504
+ },
505
+ },
349
506
  conversations: notifications.conversations,
350
507
  serviceMode: notifications.serviceMode,
351
508
  };