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

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/AGENTS.md CHANGED
@@ -10,7 +10,7 @@ App code reaches the MD Runtime through the remote client. The surfaces are
10
10
  Rooms, Query, Search, Observe, Types, Room Draft, Save, History, Call, Reached, Log,
11
11
  the reported persistence answer, reauthorization, conversation, the chat draft,
12
12
  and Presentation State. Sync Status, the Service Mode, the storage-loss
13
- statement and the deployment facts are observations only.
13
+ statement, the deployment facts and the signed-in member are observations only.
14
14
 
15
15
  The host attaches each port with its reach, and every member and observation
16
16
  answers within it: a Room outside it answers as one the replica does not hold,
@@ -51,21 +51,42 @@ open one through the Provider Action that serves it.
51
51
 
52
52
  Rooms, Query, Search, Observe, Types, Room Draft, Save, and Reached never
53
53
  touch the network.
54
- History and Call go to the Provider through the Adapter. A Call result whose
54
+ History and Call go to the Provider through the Adapter. Call takes the Action names
55
+ the Adapter declares; any other name answers `undeclared` without reaching the
56
+ Provider. A Call result whose
55
57
  effect the Provider places in a Room carries `at`, that Room and Room Version;
56
58
  `reached(room, roomVersion)` answers whether the Room's confirmed state has
57
59
  reached it, and the MD Runtime keeps refreshing that Room until it has;
58
60
  `reached(room, roomVersion, path)` answers whether the held confirmed copy of
59
61
  that document was written at a later Room Version. Each History revision
60
- names its author, `{ kind: 'user', id }` or `{ kind: 'site', id, name }`. Every
62
+ names its author, `{ kind: 'user', id }` or `{ kind: 'site', id, name }`.
63
+ History of a Path no current document holds answers the removed document's
64
+ revisions with `deleted: true`, newest first; that revision is what a link to
65
+ the Path opens. Every
61
66
  member of the
62
67
  client is asynchronous. Results are detached snapshots. Nothing in this
63
68
  surface returns the authorization, performs a request the App's code
64
69
  composes, or exposes the browser store.
65
70
 
71
+ Every refusal and failure carries `code` and `retryable`: each Call and History answer
72
+ other than its result, a refused Save or Room Draft write, a returned Room Draft's
73
+ reason, a Room's refusal and the Connection Refusal, and every error a member rejects
74
+ with, beside its message. A Provider refusal carries the Provider's own `retryable`.
75
+ Every code and every value the API answers is open: handle one you do not know by its
76
+ `code` and `retryable`.
77
+
66
78
  Read the deployment facts with `observe('deployment-facts')`. Interpret the
67
79
  opaque value using the host's contract.
68
80
 
81
+ `observe('member')` answers who uses the App: the User the Provider signed in,
82
+ `{ kind: 'user', id, name }` in the shape of a change's `author`, so a Document
83
+ whose `change.author.id` equals its `id` is that User's own. It is `null` until
84
+ the Provider first names one, and where it names none, such as a Site. The
85
+ MD Runtime keeps it with the Local Replicas, so it answers offline once known,
86
+ and every port hears the next member the Provider names; signing out answers
87
+ `null`, then ends the observation with the authorization. It is the only way App code learns who
88
+ uses it.
89
+
69
90
  The in-memory Adapter at `@agentshouse/mdruntime/memory` is for tests and
70
91
  ships in no bundle.
71
92
 
@@ -109,7 +130,7 @@ data:
109
130
  or `null` for a write the Provider made itself, and `time` is the Provider's
110
131
  ISO 8601 change time. It is `null` where the Provider delivered no time, as at
111
132
  a Site. An unsent edit or move keeps it, an unsent creation has none, and a
112
- saved write takes the Provider's own once it is Accepted and refreshed. A
133
+ saved write takes the Provider's own once it is Accepted. A
113
134
  Room's last change is its Document with the latest `time`.
114
135
  - **Order and groups.** `orderBy` sorts by `room`, `path`, `type` or `{ field }`
115
136
  with TanStack DB's own options, and ties end with Room, then Path. `groupBy` by
@@ -117,9 +138,9 @@ data:
117
138
  over every match and ordered by `count` or a key. A sort or group takes only a
118
139
  pointer that holds one value. `limit` bounds the Documents or the groups.
119
140
  - **Results and errors.** A result carries no Room Version: read freshness from
120
- Rooms and Sync Status. An invalid query fails with `invalid-query`,
121
- `unknown-type`, `unknown-field` or `wrong-kind`, naming where, and never
122
- answers an empty result in its place.
141
+ Rooms and Sync Status. An invalid query fails with the `code`
142
+ `invalid-query`, `unknown-type`, `unknown-field` or `wrong-kind`, naming where,
143
+ and never answers an empty result in its place.
123
144
 
124
145
  ## Local Search rules
125
146
 
@@ -157,9 +178,9 @@ the current Room Draft; read it and write again.
157
178
 
158
179
  Save takes one Room and the Room Drafts of it to save, each with its revision,
159
180
  validates locally, and on success appends one Change Batch to that Room's
160
- queue and removes those Room Drafts. It is refused as `stale`, as
181
+ queue and removes those Room Drafts. It is refused with the `code` `stale`,
161
182
  `changed-underneath` naming each part whose base no longer matches the visible
162
- state, or by a local validation rule, and then creates nothing and leaves every
183
+ state, or a local validation rule, and then creates nothing and leaves every
163
184
  Room Draft in place. A directory move or removal is a move or removal part on
164
185
  each Document and binary link target beneath it, saved together.
165
186
 
@@ -179,6 +200,13 @@ it names; the MD Runtime retries the same Change Batch identity and payload and
179
200
  never infers an outcome from transport uncertainty. The MD Runtime never
180
201
  combines, reorders, or rebases.
181
202
 
203
+ On a Site, every Save stays in the visitor's browser. Write grants and
204
+ revisions do not refuse it, and its Pending Change shows in every query and
205
+ across reloads until the browser's storage is cleared. It is never sent:
206
+ `observe('queue', room)` shows it `local`, and Sync Status never waits on it.
207
+ Once the Room changes so that it no longer applies, it leaves the queue and
208
+ returns no Room Draft.
209
+
182
210
  `observe('service-mode')` answers the Provider's Service
183
211
  Mode, `open` or `write-halted`. While writes are halted, Save still succeeds,
184
212
  its Change Batch waits unsent, and the queue is submitted in order once the
@@ -215,7 +243,7 @@ the network. Data lives only in the App Creator's browser and with the Provider.
215
243
  ## App code takes the client its host hands it and never constructs a Runtime
216
244
 
217
245
  App code takes the client its host hands it: in House,
218
- `connectHouseBridge().runtime` from `@agentshouse/app-bridge` resolves to the
246
+ `houseBridge().runtime` from `@agentshouse/app-bridge` resolves to the
219
247
  client House built into the page. It never constructs a Runtime or a client.
220
248
  It imports only types from `@agentshouse/mdruntime/client`, does not call
221
249
  `connectMdRuntime` or `serveMdRuntime`, and does not import the package main,
@@ -224,13 +252,16 @@ served App does not.
224
252
 
225
253
  A React App may observe and save through `@agentshouse/mdruntime/react`, which
226
254
  names React as a peer dependency. `useObserve(client, topic, ...input)` takes
227
- the arguments of `observe` and returns the topic's current value, `undefined`
228
- until it arrives, re-rendering on each change; a `null` client observes
229
- nothing. `useSave(client)` returns `busy`, the last `outcome` or `failure`, and
255
+ the arguments of `observe` and returns `{ state: 'loading' }` until the topic's
256
+ first value arrives, then `{ state: 'ready', value }`, re-rendering on each
257
+ change; a `null` client observes nothing and stays loading. `useSave(client)` returns `busy`, the last `outcome` or `failure`, and
230
258
  `save(room, roomDrafts)`, which writes each Path's parts onto the Room Draft
231
259
  already there, keeping the bases its parts have, or onto a new one, and saves
232
260
  them together. A refused Save leaves the Room Drafts for the App to save again
233
- or discard; a failure is recorded and rejects.
261
+ or discard; a failure is recorded and rejects. `saveRoomDrafts(client, room,
262
+ roomDrafts)` is that save outside a component. A react-admin or Refine App
263
+ reads and writes its Rooms through the data providers of
264
+ `@agentshouse/mdruntime-families`.
234
265
 
235
266
  ## What an agent must never do
236
267
 
package/dist/actions.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type AcceptedMessage, type ActionDeclaration, type ActionRequest, type ActionResult, type ConversationAgents } from '@agentshouse/mdruntime';
2
2
  import type { HouseDoorAnswer, HouseTransport } from './transport.js';
3
- export declare const HOUSE_CONVERSATION_AGENTS: ConversationAgents;
3
+ export declare const HOUSE_APP_ACTS: Readonly<Record<string, string>>;
4
+ export declare function houseConversationAgents(locator: string): ConversationAgents;
4
5
  export declare function declaredActions(routes: readonly string[]): readonly ActionDeclaration[];
5
6
  export declare function houseAction(transport: HouseTransport, request: ActionRequest): Promise<ActionResult>;
6
7
  export declare function actionOutcome(answer: HouseDoorAnswer, name: string): ActionResult;
@@ -1 +1 @@
1
- {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EAGxB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAkBtE,eAAO,MAAM,yBAAyB,EAAE,kBAKvC,CAAC;AAEF,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,iBAAiB,EAAE,CASvF;AAED,wBAAgB,WAAW,CACzB,SAAS,EAAE,cAAc,EACzB,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,YAAY,CAAC,CAQvB;AA4DD,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,CAWjF;AAuLD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAUtE"}
1
+ {"version":3,"file":"actions.d.ts","sourceRoot":"","sources":["../src/actions.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EAGxB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAmEtE,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE3D,CAAC;AAMF,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,kBAAkB,CAE3E;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,SAAS,iBAAiB,EAAE,CAMvF;AAED,wBAAgB,WAAW,CACzB,SAAS,EAAE,cAAc,EACzB,OAAO,EAAE,aAAa,GACrB,OAAO,CAAC,YAAY,CAAC,CAQvB;AAyDD,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,CAOjF;AAwMD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAUtE"}
package/dist/actions.js CHANGED
@@ -1,50 +1,76 @@
1
1
  import { changeBatchIdentity, } from '@agentshouse/mdruntime';
2
2
  import { doorRefusal } from './refusal.js';
3
- import { PRIVATE_LOCATOR } from './transport.js';
4
3
  const HISTORY_PAGE = 100;
5
4
  const HISTORY_CONVERSATIONS = 64;
6
5
  const OCTET_STREAM = 'application/octet-stream';
7
- const CONVERSATION_ROUTES = new Map([
8
- ['conversation.create', '/door/conversations/create'],
9
- ['conversation.send', '/door/conversations/send'],
10
- ['conversation.answer', '/door/conversations/interaction/answer'],
11
- ['conversation.interrupt', '/door/conversations/interrupt'],
12
- ['conversation.kill', '/door/conversations/kill'],
13
- ['conversation.delete', '/door/conversations/delete'],
14
- ['conversation.history', '/door/conversations/history'],
15
- ]);
16
- export const HOUSE_CONVERSATION_AGENTS = {
17
- locator: PRIVATE_LOCATOR,
18
- type: 'house-agent',
19
- identity: 'agent',
20
- name: 'name',
6
+ function mapped(door, input = (given) => given) {
7
+ return {
8
+ door,
9
+ async carry(transport, given, name) {
10
+ return actionOutcome(await transport.door(`/door/${door}`, input(given)), name);
11
+ },
12
+ };
13
+ }
14
+ function carried(door, carry) {
15
+ return {
16
+ door,
17
+ carry: (transport, input, name) => carry(transport, `/door/${door}`, input, name),
18
+ };
19
+ }
20
+ const APP_ACTS = {
21
+ 'access.read': mapped('rooms/access/read'),
22
+ 'attachment.read': carried('attachments/get', openAction),
23
+ 'attachment.upload': carried('attachments/upload', attachAction),
24
+ 'conversation.answer': mapped('conversations/interaction/answer', answerBody),
25
+ 'conversation.create': mapped('conversations/create', createBody),
26
+ 'conversation.delete': mapped('conversations/delete', controlBody),
27
+ 'conversation.history': carried('conversations/history', historyAction),
28
+ 'conversation.interrupt': mapped('conversations/interrupt', controlBody),
29
+ 'conversation.kill': mapped('conversations/kill', controlBody),
30
+ 'conversation.markDone': mapped('conversations/done'),
31
+ 'conversation.rename': mapped('conversations/rename'),
32
+ 'conversation.send': carried('conversations/send', sendAction),
33
+ 'conversation.setOption': mapped('conversations/option'),
34
+ 'feature.list': mapped('apps/features/read'),
35
+ 'holder.list': mapped('apps/holders'),
36
+ 'holder.ring': mapped('apps/ring'),
37
+ 'member.list': mapped('rooms/members'),
38
+ 'message.send': mapped('apps/messages/send'),
39
+ 'processing.read': mapped('rooms/settings/processing/read'),
40
+ 'record.list': mapped('records/read'),
41
+ 'relay.read': mapped('apps/relay'),
42
+ 'routine.list': mapped('routines/access'),
43
+ 'routineAccess.list': mapped('routines/granted'),
44
+ 'routineAllowance.list': mapped('routines/allowance'),
45
+ 'routineRequest.list': mapped('routines/requests'),
46
+ 'storage.read': mapped('storage/inventory'),
47
+ 'trigger.list': mapped('triggers/read'),
48
+ 'triggerOccurrence.list': mapped('triggers/fired'),
21
49
  };
50
+ export const HOUSE_APP_ACTS = Object.fromEntries(Object.entries(APP_ACTS).map(([name, act]) => [name, act.door]));
51
+ const APP_NAMES = new Map(Object.entries(APP_ACTS).map(([name, act]) => [act.door, name]));
52
+ export function houseConversationAgents(locator) {
53
+ return { locator, type: 'house-agent', identity: 'agent', name: 'name' };
54
+ }
22
55
  export function declaredActions(routes) {
23
- const mapped = new Map([...CONVERSATION_ROUTES].map(([name, route]) => [route.slice('/door/'.length), name]));
24
56
  return routes.map((route) => ({
25
- name: mapped.get(route) ?? route,
57
+ name: APP_NAMES.get(route) ?? route,
26
58
  inputShape: {},
27
59
  resultKind: 'house',
28
60
  }));
29
61
  }
30
62
  export function houseAction(transport, request) {
31
- if (request.name === 'conversation.send')
32
- return sendAction(transport, request.input);
33
- if (request.name === 'conversation.history')
34
- return historyAction(transport, request.input);
35
- if (request.name === 'attachments/upload')
36
- return attachAction(transport, request.input);
37
- if (request.name === 'attachments/get')
38
- return openAction(transport, request.input);
63
+ if (Object.hasOwn(APP_ACTS, request.name)) {
64
+ return APP_ACTS[request.name].carry(transport, request.input, request.name);
65
+ }
66
+ if (APP_NAMES.has(request.name))
67
+ return Promise.resolve(unimplemented(request.name));
39
68
  const route = routeOf(request.name);
40
69
  if (route === null)
41
70
  return Promise.resolve(malformed());
42
71
  return carry(transport, route, request.name, request.input);
43
72
  }
44
73
  function routeOf(name) {
45
- const mapped = CONVERSATION_ROUTES.get(name);
46
- if (mapped !== undefined)
47
- return mapped;
48
74
  const parts = name.split('/');
49
75
  if (parts.some((part) => part === '.' || part === '..'))
50
76
  return null;
@@ -66,27 +92,25 @@ function operationId(input) {
66
92
  return text(input, 'operation_id') ?? changeBatchIdentity();
67
93
  }
68
94
  function malformed() {
69
- return { kind: 'rejected', code: 'invalid_request', fields: {} };
95
+ return { kind: 'rejected', code: 'invalid_request', fields: {}, retryable: false };
70
96
  }
71
- function bodyOf(name, input) {
72
- if (name === 'conversation.create') {
73
- return { agent_id: text(input, 'agent_id'), operation_id: operationId(input) };
74
- }
75
- if (name === 'conversation.interrupt' ||
76
- name === 'conversation.kill' ||
77
- name === 'conversation.delete') {
78
- return { conversation_id: text(input, 'conversation'), operation_id: operationId(input) };
79
- }
80
- if (name === 'conversation.answer') {
81
- const nested = record(record(input).answer);
82
- return {
83
- conversation_id: text(input, 'conversation'),
84
- operation_id: operationId(input),
85
- interaction_id: text(nested, 'interaction_id'),
86
- response: nested.response,
87
- };
88
- }
89
- return input;
97
+ function unimplemented(name) {
98
+ return { kind: 'rejected', code: 'action-unimplemented', fields: { name }, retryable: false };
99
+ }
100
+ function createBody(input) {
101
+ return { agent_id: text(input, 'agent_id'), operation_id: operationId(input) };
102
+ }
103
+ function controlBody(input) {
104
+ return { conversation_id: text(input, 'conversation'), operation_id: operationId(input) };
105
+ }
106
+ function answerBody(input) {
107
+ const nested = record(record(input).answer);
108
+ return {
109
+ conversation_id: text(input, 'conversation'),
110
+ operation_id: operationId(input),
111
+ interaction_id: text(nested, 'interaction_id'),
112
+ response: nested.response,
113
+ };
90
114
  }
91
115
  function withTurn(body) {
92
116
  const held = record(body);
@@ -97,20 +121,16 @@ export function actionOutcome(answer, name) {
97
121
  if (answer.status === 401)
98
122
  return { kind: 'revoked-authorization' };
99
123
  const refusal = doorRefusal(answer.body);
100
- if (refusal !== null) {
101
- return { kind: 'rejected', code: refusal.code, fields: refusal.fields };
102
- }
124
+ if (refusal !== null)
125
+ return { kind: 'rejected', ...refusal };
103
126
  if (answer.status === 404)
104
- return { kind: 'rejected', code: 'action-unimplemented', fields: { name } };
127
+ return unimplemented(name);
105
128
  if (answer.status === 0 || answer.status >= 400)
106
129
  return { kind: 'transport-uncertainty' };
107
- if (name === 'conversation.send')
108
- return { kind: 'action', result: withTurn(answer.body) };
109
130
  return { kind: 'action', result: answer.body };
110
131
  }
111
132
  async function carry(transport, route, name, input) {
112
- const answer = await transport.door(route, bodyOf(name, input));
113
- return actionOutcome(answer, name);
133
+ return actionOutcome(await transport.door(route, input), name);
114
134
  }
115
135
  function sendFile(entry) {
116
136
  const file = record(entry);
@@ -180,7 +200,7 @@ function uploadGrant(entry) {
180
200
  return null;
181
201
  return { method: 'POST', operation: upload.operation, url: upload.url };
182
202
  }
183
- async function uploadOriginals(transport, input, result) {
203
+ async function uploadOriginals(transport, input, result, name) {
184
204
  const originals = record(result).originals;
185
205
  if (!Array.isArray(originals) || originals.length === 0)
186
206
  return null;
@@ -193,7 +213,12 @@ async function uploadOriginals(transport, input, result) {
193
213
  return malformed();
194
214
  const bytes = index < files.length ? await fileBytes(files[index]) : null;
195
215
  if (bytes === null) {
196
- return { kind: 'rejected', code: 'conversation_original_descriptor_required', fields: {} };
216
+ return {
217
+ kind: 'rejected',
218
+ code: 'conversation_original_descriptor_required',
219
+ fields: {},
220
+ retryable: false,
221
+ };
197
222
  }
198
223
  const failed = delivered(await transport.transfer({
199
224
  act: 'conversation_original_upload',
@@ -202,19 +227,18 @@ async function uploadOriginals(transport, input, result) {
202
227
  answer: 'json',
203
228
  body: bytes,
204
229
  operation: grant.operation,
205
- }), 'conversation.send');
230
+ }), name);
206
231
  if (failed !== null)
207
232
  return failed;
208
233
  }
209
234
  return null;
210
235
  }
211
- async function attachAction(transport, input) {
236
+ async function attachAction(transport, route, input, name) {
212
237
  const { blob, ...descriptor } = record(input);
213
238
  const bytes = await fileBytes({ blob });
214
239
  if (bytes === null)
215
240
  return malformed();
216
- const answer = await transport.door('/door/attachments/upload', descriptor);
217
- const outcome = actionOutcome(answer, 'attachments/upload');
241
+ const outcome = actionOutcome(await transport.door(route, descriptor), name);
218
242
  if (outcome.kind !== 'action')
219
243
  return outcome;
220
244
  const grant = uploadGrant(outcome.result);
@@ -230,11 +254,10 @@ async function attachAction(transport, input) {
230
254
  body: bytes,
231
255
  operation: grant.operation,
232
256
  });
233
- return delivered(stored, 'attachments/upload') ?? { kind: 'action', result: stored.body };
257
+ return delivered(stored, name) ?? { kind: 'action', result: stored.body };
234
258
  }
235
- async function openAction(transport, input) {
236
- const answer = await transport.door('/door/attachments/get', input);
237
- const outcome = actionOutcome(answer, 'attachments/get');
259
+ async function openAction(transport, route, input, name) {
260
+ const outcome = actionOutcome(await transport.door(route, input), name);
238
261
  if (outcome.kind !== 'action')
239
262
  return outcome;
240
263
  const { download, ...opened } = record(outcome.result);
@@ -249,25 +272,24 @@ async function openAction(transport, input) {
249
272
  url: grant.url,
250
273
  answer: 'bytes',
251
274
  });
252
- const failed = delivered(read, 'attachments/get');
275
+ const failed = delivered(read, name);
253
276
  if (failed !== null)
254
277
  return failed;
255
278
  if (!(read.body instanceof Blob))
256
279
  return { kind: 'transport-uncertainty' };
257
280
  return { kind: 'action', result: { ...opened, blob: read.body } };
258
281
  }
259
- async function sendAction(transport, input) {
282
+ async function sendAction(transport, route, input, name) {
260
283
  const body = sendBody(input);
261
284
  if (body === null)
262
285
  return malformed();
263
- const answer = await transport.door('/door/conversations/send', body);
264
- const outcome = actionOutcome(answer, 'conversation.send');
286
+ const outcome = actionOutcome(await transport.door(route, body), name);
265
287
  if (outcome.kind !== 'action')
266
288
  return outcome;
267
- const uploaded = await uploadOriginals(transport, input, outcome.result);
289
+ const uploaded = await uploadOriginals(transport, input, outcome.result, name);
268
290
  if (uploaded !== null)
269
291
  return uploaded;
270
- return outcome;
292
+ return { ...outcome, result: withTurn(outcome.result) };
271
293
  }
272
294
  function historyCursor(value) {
273
295
  const acceptedAt = text(value, 'accepted_at');
@@ -333,17 +355,17 @@ function historyAsks(input) {
333
355
  }
334
356
  return asks;
335
357
  }
336
- async function historyAction(transport, input) {
358
+ async function historyAction(transport, route, input, name) {
337
359
  const asks = historyAsks(input);
338
360
  if (asks === null)
339
361
  return malformed();
340
362
  const histories = [];
341
363
  for (let at = 0; at < asks.length; at += HISTORY_CONVERSATIONS) {
342
- const answer = await transport.door('/door/conversations/history', {
364
+ const answer = await transport.door(route, {
343
365
  conversations: asks.slice(at, at + HISTORY_CONVERSATIONS),
344
366
  limit: HISTORY_PAGE,
345
367
  });
346
- const outcome = actionOutcome(answer, 'conversation.history');
368
+ const outcome = actionOutcome(answer, name);
347
369
  if (outcome.kind !== 'action')
348
370
  return outcome;
349
371
  const answered = record(outcome.result).histories;
@@ -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;AAqChC,OAAO,EAQL,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;AAsBjC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CA0WpF"}
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"}
package/dist/adapter.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { DISCOVER_PREFIXES, capabilities, discoveredRoom, mapDiscovery, parseDiscovery, trackedFrom, } from './discovery.js';
2
- import { scopeModels, streamedModels, viewModels } from './model.js';
3
- import { gathered, selections } from './gather.js';
2
+ import { partModels, streamedModels, viewModels } from './model.js';
3
+ import { gathered, gatheredEach, selections } from './gather.js';
4
4
  import { createSiteAdapter } from './site.js';
5
5
  import { bootstrapOf, contentPrefixes, matchesScope, parseEnumeration, parseEnvelope, parseGrant, refreshFrom, viewOf, } from './read.js';
6
6
  import { acceptedLinks, enumeratedLinks, heldLinks, scopeLinks, streamedLinks, } from './links.js';
7
7
  import { houseAction } from './actions.js';
8
8
  import { classifyDoor, classifyRead, discoveryFailure, doorRefusal } from './refusal.js';
9
9
  import { houseNotifications } from './stream.js';
10
- import { DOOR_BATCH, DOOR_BATCH_UPLOAD, DOOR_BOOTSTRAP, DOOR_DISCOVER, DOOR_ENUMERATE, DOOR_REVISIONS, PRIVATE_LOCATOR, } from './transport.js';
10
+ import { DOOR_BATCH, DOOR_BATCH_UPLOAD, DOOR_BOOTSTRAP, DOOR_DISCOVER, DOOR_ENUMERATE, DOOR_REVISIONS, } from './transport.js';
11
11
  import { batchPaths, deltaBody, deltaBytes, deltaDigest, historyOutcome, houseChanges, mutationOutcome, operationHead, rejectedMapping, revisionBody, uploadable, } from './write.js';
12
12
  import { followsVersion, logPosition, presented, reachedVersion, roomVersion, } from './version.js';
13
13
  const UNCERTAIN = { kind: 'transport-uncertainty' };
@@ -28,14 +28,26 @@ export function createAgentsHouseAdapter(options) {
28
28
  throw new Error('no Discovery declared the bounds');
29
29
  return bounds;
30
30
  }
31
- async function bootstrappedRoom(envelope, entry) {
32
- const scope = envelope.scopes.find((candidate) => matchesScope(candidate, entry));
31
+ async function bootstrappedRoom(envelope, scope, entry, continued) {
33
32
  if (scope === undefined)
34
33
  return { kind: 'room-not-readable', locator: entry.locator };
35
- handed.set(entry.locator, scopeLinks(scope));
34
+ const next = envelope.next?.room === entry.authority ? envelope.next.path : null;
35
+ if (continued === null && next === null)
36
+ handed.set(entry.locator, scopeLinks(scope));
37
+ else
38
+ handed.delete(entry.locator);
36
39
  notifications.reach(entry.authority, scope);
37
- const models = await scopeModels(scope, entry);
38
- return { ...bootstrapOf(scope), ...(models === undefined ? {} : { models }) };
40
+ const seen = [
41
+ ...(continued?.seen ?? []),
42
+ ...entry.schemas.filter((schema) => scope.files.some((file) => file.path === schema)),
43
+ ];
44
+ const models = await partModels(scope, entry, new Set(seen), next === null);
45
+ const continuation = next === null ? null : { after: next, seen };
46
+ return {
47
+ ...bootstrapOf(scope),
48
+ ...(models === undefined ? {} : { models }),
49
+ ...(continuation === null ? {} : { pageToken: JSON.stringify(continuation) }),
50
+ };
39
51
  }
40
52
  async function enumeratedRoom(enumeration, ask) {
41
53
  const view = viewOf(enumeration, ask.entry);
@@ -104,48 +116,59 @@ export function createAgentsHouseAdapter(options) {
104
116
  const { authority, position, log_epoch: logEpoch } = body;
105
117
  if (typeof position !== 'string' || typeof logEpoch !== 'string')
106
118
  return result;
107
- const locator = authority === undefined
108
- ? PRIVATE_LOCATOR
109
- : [...tracked.values()].find((entry) => entry.authority === authority)?.locator;
119
+ const locator = [...tracked.values()].find((entry) => entry.authority === authority)?.locator;
110
120
  if (locator === undefined)
111
121
  return result;
112
122
  return { ...result, at: { locator, roomVersion: roomVersion({ position, logEpoch }) } };
113
123
  }
114
- async function bundled(body) {
115
- const grant = parseGrant(body);
116
- if (grant === null)
117
- return body;
118
- if (grant.method !== 'GET')
119
- return null;
120
- const answer = await transport.transfer({
121
- act: 'local_copy_bundle',
122
- method: 'GET',
123
- url: grant.url,
124
- answer: 'json',
125
- });
126
- return answer.status === 200 ? answer.body : null;
127
- }
128
124
  function weight(entry) {
129
125
  return contentPrefixes(entry).length;
130
126
  }
131
- async function bootstrapped(entries) {
132
- const answers = [];
133
- for (const part of selections(entries, weight, declared().max_prefixes)) {
134
- const answer = await transport.door(DOOR_BOOTSTRAP, {
135
- prefixes: part.flatMap((entry) => contentPrefixes(entry)),
136
- });
137
- const classified = part.map((entry) => classifyDoor(answer.status, answer.body, entry.locator));
138
- const envelope = classified[0] === null ? parseEnvelope(await bundled(answer.body)) : null;
139
- for (const [index, entry] of part.entries()) {
140
- const failure = classified[index];
141
- if (failure === null || failure === undefined) {
142
- answers.push(envelope === null ? UNCERTAIN_READ : await bootstrappedRoom(envelope, entry));
143
- continue;
127
+ async function bootstrapped(entries, answer) {
128
+ let open = entries.map((entry, ask) => ({ entry, ask }));
129
+ while (open.length > 0) {
130
+ const unreached = [];
131
+ for (const part of selections(open, ({ entry }) => weight(entry), declared().max_prefixes)) {
132
+ const answered = await transport.door(DOOR_BOOTSTRAP, {
133
+ prefixes: part.flatMap(({ entry }) => contentPrefixes(entry)),
134
+ });
135
+ const classified = part.map(({ entry }) => classifyDoor(answered.status, answered.body, entry.locator));
136
+ const envelope = classified[0] === null ? parseEnvelope(answered.body) : null;
137
+ for (const [index, asked] of part.entries()) {
138
+ const failure = classified[index];
139
+ if (failure !== null && failure !== undefined) {
140
+ answer(asked.ask, failure);
141
+ continue;
142
+ }
143
+ if (envelope === null) {
144
+ answer(asked.ask, UNCERTAIN_READ);
145
+ continue;
146
+ }
147
+ const scope = envelope.scopes.find((candidate) => matchesScope(candidate, asked.entry));
148
+ if (scope === undefined && envelope.next !== undefined) {
149
+ unreached.push(asked);
150
+ continue;
151
+ }
152
+ answer(asked.ask, await bootstrappedRoom(envelope, scope, asked.entry, null));
144
153
  }
145
- answers.push(failure);
146
154
  }
155
+ open = unreached;
147
156
  }
148
- return answers;
157
+ }
158
+ async function continuedBootstrap(entry, continued) {
159
+ const after = { room: entry.authority, path: continued.after };
160
+ const answered = await transport.door(DOOR_BOOTSTRAP, {
161
+ prefixes: contentPrefixes(entry),
162
+ after,
163
+ });
164
+ const failure = classifyDoor(answered.status, answered.body, entry.locator);
165
+ if (failure !== null)
166
+ return failure;
167
+ const envelope = parseEnvelope(answered.body);
168
+ if (envelope === null)
169
+ return UNCERTAIN_READ;
170
+ const scope = envelope.scopes.find((candidate) => matchesScope(candidate, entry));
171
+ return bootstrappedRoom(envelope, scope, entry, continued);
149
172
  }
150
173
  function layered(asks) {
151
174
  const depths = new Map();
@@ -192,7 +215,7 @@ export function createAgentsHouseAdapter(options) {
192
215
  }
193
216
  return asks.map((ask) => answers.get(ask) ?? UNCERTAIN_READ);
194
217
  }
195
- const bootstrapTogether = gathered(bootstrapped);
218
+ const bootstrapTogether = gatheredEach(bootstrapped);
196
219
  const enumerateTogether = gathered(enumerated);
197
220
  async function uploaded(head, changes, delta, bytes, entry, handed, keep) {
198
221
  const paths = batchPaths(changes);
@@ -239,9 +262,9 @@ export function createAgentsHouseAdapter(options) {
239
262
  },
240
263
  async discover(_authorization) {
241
264
  const answer = await transport.door(DOOR_DISCOVER, { prefixes: [...DISCOVER_PREFIXES] });
242
- const classified = classifyDoor(answer.status, answer.body, PRIVATE_LOCATOR);
243
- if (classified !== null)
244
- return discoveryFailure(classified);
265
+ const failed = discoveryFailure(answer.status, answer.body);
266
+ if (failed !== null)
267
+ return failed;
245
268
  const document = parseDiscovery(answer.body);
246
269
  if (document === null)
247
270
  return { kind: 'transport-uncertainty' };
@@ -254,14 +277,18 @@ export function createAgentsHouseAdapter(options) {
254
277
  if (!tracked.has(locator))
255
278
  handed.delete(locator);
256
279
  notifications.track(entries);
257
- return mapDiscovery(document, document.authorities.map((authority) => discoveredRoom(authority)), capabilities(document.actions));
280
+ return {
281
+ ...mapDiscovery(document, document.authorities.map((authority) => discoveredRoom(authority)), capabilities(document)),
282
+ member: document.member,
283
+ };
258
284
  },
259
285
  async bootstrap(_authorization, request) {
260
286
  const entry = authorityFor(request.locator);
261
287
  if (entry === undefined)
262
288
  return { kind: 'room-not-readable', locator: request.locator };
263
- if (request.pageToken !== undefined)
264
- return { kind: 'transport-uncertainty' };
289
+ if (request.pageToken !== undefined) {
290
+ return continuedBootstrap(entry, JSON.parse(request.pageToken));
291
+ }
265
292
  return bootstrapTogether(entry);
266
293
  },
267
294
  async refresh(_authorization, request) {
@@ -318,7 +345,7 @@ export function createAgentsHouseAdapter(options) {
318
345
  async action(_authorization, request) {
319
346
  return withAt(await houseAction(transport, request));
320
347
  },
321
- roomStream: { hold: held, observe: notifications.observe },
348
+ roomStream: { hold: held, reopen: notifications.reopen, observe: notifications.observe },
322
349
  conversations: notifications.conversations,
323
350
  serviceMode: notifications.serviceMode,
324
351
  };