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

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
@@ -7,9 +7,19 @@ enforcement.
7
7
  ## The MD Runtime API
8
8
 
9
9
  App code reaches the MD Runtime through the remote client. The surfaces are
10
- Rooms, Slots, Query, Search, Observe, Types, Room Draft, Save, History, Call, Reached, Log,
11
- storage loss, the reported persistence answer, deployment facts, Sync Status, the Service Mode,
12
- reauthorization, conversation, the chat draft, and Presentation State.
10
+ Rooms, Query, Search, Observe, Types, Room Draft, Save, History, Call, Reached, Log,
11
+ the reported persistence answer, reauthorization, conversation, the chat draft,
12
+ and Presentation State. Sync Status, the Service Mode, the storage-loss
13
+ statement and the deployment facts are observations only.
14
+
15
+ The host attaches each port with its reach, and every member and observation
16
+ answers within it: a Room outside it answers as one the replica does not hold,
17
+ Rooms lists only the Rooms reached whole, a Room reached for single Documents
18
+ shows only those Documents and the Types of the models that govern them, and
19
+ without conversations the conversation members, the chat draft and the
20
+ conversation observation hold none.
21
+ A change of the reach reaches every open observation as its new value, a query
22
+ keeping every unchanged Document the same object.
13
23
 
14
24
  Every `observe` resolves, once its first value has arrived, to a handle:
15
25
  `current()` is the latest complete value, `subscribe(listener)` hears each later
@@ -17,29 +27,29 @@ value whole and returns its unsubscribe, and `close()` ends the observation.
17
27
  Closing the port ends every handle and rejects every pending call and
18
28
  observation; a client that reconnects observes again.
19
29
 
20
- Each conversation a Provider card names is held complete in the browser.
30
+ Each conversation the Provider's conversation list names is held complete in the
31
+ browser. `conversation.list()` and `observe('conversations')` answer each with its
32
+ Agent's identity and name, its name, created and finished times, last outcome and live
33
+ `state`: `asking` while a question waits, `working` while a turn runs, else `idle`,
34
+ and `started`, when the running turn began, or `null`.
21
35
  Observe one with `observe('conversation', id, { limit })`: the view
22
36
  holds its latest `limit` messages, or all of them, oldest first, its chat
23
37
  draft, and what the Provider streams for it whether or not anything views it:
24
- the growing text and plan of the running turn, the open questions, the process
25
- state, the CLI's commands and options, and the latest `workingNote`. These live
26
- only in memory: the turn's accepted message replaces its growing text and plan,
27
- a working note is never part of a message, and none of them is stored or
28
- searchable.
38
+ the running `turn` with its message parts and its context in use and window, the
39
+ open questions, the process state, and the CLI's commands and options. These live
40
+ only in memory: the message accepted under the turn's id replaces the running turn,
41
+ and none of them is stored or searchable.
29
42
  `chatDraft.write` and `chatDraft.discard` keep what the App Creator composes;
30
43
  sending it is a Provider Action that needs the Provider reachable and is never
31
44
  queued.
32
45
 
33
- Slots answers each Slot the Provider declares, in its order, with its entries
34
- in order, each a Room and its segment; a Room two Slots list is the same Room.
35
-
36
46
  Each Room in Rooms lists its `attachments`, the files the Provider holds for it
37
47
  that its Documents link by the Provider's reference, ordered by `reference`,
38
48
  each with `name`, `byteLength`, `mediaType` and the Provider's own entry as
39
49
  `entry`. They are as the Provider last declared them and hold no bytes;
40
50
  open one through the Provider Action that serves it.
41
51
 
42
- Rooms, Slots, Query, Search, Observe, Types, Room Draft, Save, and Reached never
52
+ Rooms, Query, Search, Observe, Types, Room Draft, Save, and Reached never
43
53
  touch the network.
44
54
  History and Call go to the Provider through the Adapter. A Call result whose
45
55
  effect the Provider places in a Room carries `at`, that Room and Room Version;
@@ -47,15 +57,17 @@ effect the Provider places in a Room carries `at`, that Room and Room Version;
47
57
  reached it, and the MD Runtime keeps refreshing that Room until it has;
48
58
  `reached(room, roomVersion, path)` answers whether the held confirmed copy of
49
59
  that document was written at a later Room Version. Each History revision
50
- names its author, `{ kind: 'user', id }` or `{ kind: 'site', id, name }`. Every
60
+ names its author, `{ kind: 'user', id }` or `{ kind: 'site', id, name }`.
61
+ History of a Path no current document holds answers the removed document's
62
+ revisions with `deleted: true`, newest first; that revision is what a link to
63
+ the Path opens. Every
51
64
  member of the
52
65
  client is asynchronous. Results are detached snapshots. Nothing in this
53
66
  surface returns the authorization, performs a request the App's code
54
67
  composes, or exposes the browser store.
55
68
 
56
- Read deployment facts with `deploymentFacts()` and observe replacements with
57
- `observe('deployment-facts')`. Interpret the opaque value using the
58
- host's contract.
69
+ Read the deployment facts with `observe('deployment-facts')`. Interpret the
70
+ opaque value using the host's contract.
59
71
 
60
72
  The in-memory Adapter at `@agentshouse/mdruntime/memory` is for tests and
61
73
  ships in no bundle.
@@ -70,22 +82,28 @@ data:
70
82
  - **Filter.** `rooms` names Room locators and defaults to every Room. `types`
71
83
  names MD Types, and `any` names untyped Markdown Documents. `pathPrefix` is a
72
84
  directory: `notes` keeps `notes/a.md` and not `notes2/a.md`.
73
- - **Fields.** `where` names frontmatter fields, ANDs them, and nests `$and` and
74
- `$or`. A bare value is equality; the operators are `$eq`, `$ne`, `$in`, `$nin`,
75
- `$gt`, `$gte`, `$lt`, `$lte`, `$all`, `$size` and `$exists`. Equality on a list
76
- asks whether it contains the value. Missing, null and empty differ:
85
+ - **Fields.** Every frontmatter value is named by JSON Pointer: `/status`,
86
+ `/shipping/city`, `~1` for a `/` and `~0` for a `~` in a key. A segment that
87
+ meets a list applies to every item and a number names one item. `where` names
88
+ pointers, ANDs them, and nests `$and` and `$or`; a pointer through a list holds
89
+ when any item satisfies it. A bare value is equality; the operators are `$eq`,
90
+ `$ne`, `$in`, `$nin`, `$gt`, `$gte`, `$lt`, `$lte`, `$all`, `$size` and
91
+ `$exists`. Equality on a list asks whether it contains the value. Missing, null and empty differ:
77
92
  `$exists: false` keeps a missing field, `null` an explicit null, `''` empty
78
93
  text and `$size: 0` an empty list. A date compares in calendar order and never
79
94
  with a date-time. A reference compares by the Room Path it resolves to.
80
- Untyped frontmatter is plain values. There is no text containment or regular
95
+ Untyped frontmatter, and a value under `oneOf` or a conditional, is plain
96
+ values. There is no text containment or regular
81
97
  expression.
82
98
  - **Relations.** `hop: { field, types, where, pathPrefix }` keeps Documents whose
83
- reference `field` points to a matching Document of the same Room.
84
- `backlinks: { field, types, where, pathPrefix }` keeps Documents that a
99
+ reference at pointer `field`, at any depth, points to a matching Document of the
100
+ same Room. `backlinks: { field, types, where, pathPrefix }` keeps Documents that a
85
101
  matching Document of the same Room references. Each keeps a Document once.
86
102
  - **Parts.** A Document query must `select`: `'all'`, or `fields`, `sections`,
87
- `preamble`, `markdown`, `backlinks` and `change`, where `fields` and `sections`
88
- are `'all'` or a list of names. Room and Path always return; a Markdown
103
+ `preamble`, `markdown`, `backlinks` and `change`, where `fields` is `'all'` or a
104
+ list of pointers and `sections` `'all'` or a list of names. Selected pointers
105
+ return the frontmatter holding only them, nested as written. A backlink names
106
+ the referring Path, MD Type and the pointer it came from as `field`. Room and Path always return; a Markdown
89
107
  Document also returns its MD Type. A non-Markdown Document or binary link
90
108
  target returns only Room and Path. An unselected part is absent. Select only
91
109
  what a screen shows: a list that selects the Markdown hears every edit of it.
@@ -99,8 +117,8 @@ data:
99
117
  - **Order and groups.** `orderBy` sorts by `room`, `path`, `type` or `{ field }`
100
118
  with TanStack DB's own options, and ties end with Room, then Path. `groupBy` by
101
119
  `room`, `type` or `{ field }` answers `{ groups: [{ key, count }] }`, counted
102
- over every match and ordered by `count` or a key. `limit` bounds the Documents
103
- or the groups.
120
+ over every match and ordered by `count` or a key. A sort or group takes only a
121
+ pointer that holds one value. `limit` bounds the Documents or the groups.
104
122
  - **Results and errors.** A result carries no Room Version: read freshness from
105
123
  Rooms and Sync Status. An invalid query fails with `invalid-query`,
106
124
  `unknown-type`, `unknown-field` or `wrong-kind`, naming where, and never
@@ -114,7 +132,7 @@ search.
114
132
 
115
133
  - **What is found.** A Document by its field values, its sections' headings and
116
134
  text, its preamble and its Path; a message by its text. Frontmatter keys, Room
117
- Drafts, chat drafts and growing text are never found. There are no phrases,
135
+ Drafts, chat drafts and a running turn's parts are never found. There are no phrases,
118
136
  word forms, typo tolerance or prefix matching.
119
137
  - **Narrowing.** `documents` is a Local Query filter: `rooms`, `types`, `where`,
120
138
  `pathPrefix`, `hop` and `backlinks`. `conversations` names conversations. Both
@@ -130,7 +148,7 @@ search.
130
148
 
131
149
  The MD Runtime owns one Room Draft per Room and Path, shared by every App and
132
150
  tab. It is durable: it survives reload and navigation. A Room that Discovery
133
- stops listing takes its Room Drafts, its queue and their outcomes with it.
151
+ stops listing takes its Room Drafts and its queue with it.
134
152
  Write a Room Draft with `roomDraft.write(room, path, revision, parts)`, naming
135
153
  the revision you read, or `null` when there was none, and every part it should
136
154
  now change: fields, sections and the preamble, or the whole Markdown, a
@@ -150,20 +168,21 @@ each Document and binary link target beneath it, saved together.
150
168
 
151
169
  Outcomes follow the Provider's answer. An Accepted Change Batch stays in the
152
170
  queue, drawn over the confirmed layer, until the confirmed layer reaches the
153
- Room Version it was accepted at, and then leaves it. Conflicted and Rejected, an expired outcome record, and a change that no
171
+ Room Version it was accepted at, and then leaves it. Conflicted and Rejected, an expired operation, and a change that no
154
172
  longer applies over the Room each leave the queue and return as Room Drafts on
155
173
  the Documents they changed, marked with why: the Provider's structured refusal
156
174
  code and fields as returned, not known to have applied, or withdrawn locally.
157
175
  The rest of the queue keeps synchronizing, and Sync Status requires attention
158
- until each returned Room Draft is saved again or discarded. `outcome` answers
159
- the saved Change Batch's outcome, and `null` while it is Pending. Transport
176
+ until each returned Room Draft is saved again or discarded. A Change Batch
177
+ keeps no outcome once it leaves the queue; `observe('queue', room)` shows each
178
+ Pending one, and a returned Room Draft says why it returned. Transport
160
179
  failure and Provider unavailability keep work Pending and do not infer a
161
180
  rejection. A refusal the Provider marks retryable stays Pending until the reset
162
181
  it names; the MD Runtime retries the same Change Batch identity and payload and
163
182
  never infers an outcome from transport uncertainty. The MD Runtime never
164
183
  combines, reorders, or rebases.
165
184
 
166
- `serviceMode()` and `observe('service-mode')` answer the Provider's Service
185
+ `observe('service-mode')` answers the Provider's Service
167
186
  Mode, `open` or `write-halted`. While writes are halted, Save still succeeds,
168
187
  its Change Batch waits unsent, and the queue is submitted in order once the
169
188
  Provider reopens writes. An Action is never held: a write the Provider refuses
@@ -196,13 +215,28 @@ an App's override respected. What an App Creator's agent adds carries none
196
215
  of these promises by itself. Reading, querying and searching never wait for
197
216
  the network. Data lives only in the App Creator's browser and with the Provider.
198
217
 
199
- ## App code imports only the client entry and never constructs a Runtime
200
-
201
- App code imports only `@agentshouse/mdruntime/client` and calls
202
- `connectMdRuntime` on the port the host hands it. It never constructs a
203
- Runtime. It does not import the package main, the host entry, or the Adapter
204
- package, and it does not call `createMdRuntime` or `serveMdRuntime`. Hosts
205
- and tests use those entries; the served App does not.
218
+ ## App code takes the client its host hands it and never constructs a Runtime
219
+
220
+ App code takes the client its host hands it: in House,
221
+ `connectHouseBridge().runtime` from `@agentshouse/app-bridge` resolves to the
222
+ client House built into the page. It never constructs a Runtime or a client.
223
+ It imports only types from `@agentshouse/mdruntime/client`, does not call
224
+ `connectMdRuntime` or `serveMdRuntime`, and does not import the package main,
225
+ the host entry, or the Adapter package. Hosts and tests use those entries; the
226
+ served App does not.
227
+
228
+ A React App may observe and save through `@agentshouse/mdruntime/react`, which
229
+ names React as a peer dependency. `useObserve(client, topic, ...input)` takes
230
+ the arguments of `observe` and returns the topic's current value, `undefined`
231
+ until it arrives, re-rendering on each change; a `null` client observes
232
+ nothing. `useSave(client)` returns `busy`, the last `outcome` or `failure`, and
233
+ `save(room, roomDrafts)`, which writes each Path's parts onto the Room Draft
234
+ already there, keeping the bases its parts have, or onto a new one, and saves
235
+ them together. A refused Save leaves the Room Drafts for the App to save again
236
+ or discard; a failure is recorded and rejects. `saveRoomDrafts(client, room,
237
+ roomDrafts)` is that save outside a component. A react-admin or Refine App
238
+ reads and writes its Rooms through the data providers of
239
+ `@agentshouse/mdruntime-families`.
206
240
 
207
241
  ## What an agent must never do
208
242
 
package/README.md CHANGED
@@ -19,12 +19,12 @@ import { serveMdRuntime } from '@agentshouse/mdruntime/host';
19
19
  import { createAgentsHouseAdapter } from '@agentshouse/mdruntime-adapter';
20
20
 
21
21
  const adapter = createAgentsHouseAdapter({ transport, authorize });
22
- const host = serveMdRuntime({ adapter, shell, requiredGuarantees: [] });
22
+ const host = serveMdRuntime({ adapter, shell });
23
23
  host.attach(port, 'my-app');
24
24
  ```
25
25
 
26
- App code never imports this package; it reaches the Runtime only through
27
- `@agentshouse/mdruntime/client`. The rules an App's agent follows are in the
26
+ App code never imports this package; it reaches the Runtime only through the
27
+ client its host hands it. The rules an App's agent follows are in the
28
28
  package's `AGENTS.md`.
29
29
 
30
30
  ## License
package/dist/actions.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { type AcceptedMessage, type ActionDeclaration, type ActionRequest, type ActionResult, type ConversationCards } from '@agentshouse/mdruntime';
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_CARDS: ConversationCards;
3
+ export declare function houseConversationAgents(locator: string): ConversationAgents;
4
4
  export declare function declaredActions(routes: readonly string[]): readonly ActionDeclaration[];
5
5
  export declare function houseAction(transport: HouseTransport, request: ActionRequest): Promise<ActionResult>;
6
6
  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,iBAAiB,EAGvB,MAAM,wBAAwB,CAAC;AAGhC,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAkBtE,eAAO,MAAM,wBAAwB,EAAE,iBAKtC,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;AAkBtE,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,kBAAkB,CAE3E;AAED,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"}
package/dist/actions.js CHANGED
@@ -1,6 +1,5 @@
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';
@@ -13,12 +12,9 @@ const CONVERSATION_ROUTES = new Map([
13
12
  ['conversation.delete', '/door/conversations/delete'],
14
13
  ['conversation.history', '/door/conversations/history'],
15
14
  ]);
16
- export const HOUSE_CONVERSATION_CARDS = {
17
- locator: PRIVATE_LOCATOR,
18
- type: 'house-conversation',
19
- identity: 'conversation',
20
- agent: 'agent',
21
- };
15
+ export function houseConversationAgents(locator) {
16
+ return { locator, type: 'house-agent', identity: 'agent', name: 'name' };
17
+ }
22
18
  export function declaredActions(routes) {
23
19
  const mapped = new Map([...CONVERSATION_ROUTES].map(([name, route]) => [route.slice('/door/'.length), name]));
24
20
  return routes.map((route) => ({
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,OAAO,EACP,aAAa,EAad,MAAM,wBAAwB,CAAC;AA0ChC,OAAO,EASL,KAAK,kBAAkB,EACvB,KAAK,cAAc,EACpB,MAAM,gBAAgB,CAAC;AAuBxB,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;AAiCjC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAkZpF"}
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,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;AAsBjC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAuWpF"}
package/dist/adapter.js CHANGED
@@ -1,26 +1,20 @@
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 { DISCOVER_PREFIXES, capabilities, discoveredRoom, mapDiscovery, parseDiscovery, trackedFrom, } from './discovery.js';
2
+ import { scopeModels, streamedModels, viewModels } from './model.js';
3
3
  import { gathered, selections } from './gather.js';
4
4
  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';
5
+ import { bootstrapOf, contentPrefixes, matchesScope, parseEnumeration, parseEnvelope, parseGrant, refreshFrom, viewOf, } from './read.js';
6
+ import { acceptedLinks, enumeratedLinks, heldLinks, scopeLinks, streamedLinks, } from './links.js';
7
7
  import { houseAction } from './actions.js';
8
- import { classifyDoor, discoveryFailure, doorRefusal } from './refusal.js';
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, DOOR_SELECTION_MAX, 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
- import { logPosition, presented, reachedVersion, roomVersion, } from './version.js';
12
+ import { followsVersion, logPosition, presented, reachedVersion, roomVersion, } from './version.js';
13
13
  const UNCERTAIN = { kind: 'transport-uncertainty' };
14
14
  const UNCERTAIN_READ = { kind: 'transport-uncertainty' };
15
15
  function lapsedGrant(outcome) {
16
16
  return outcome.kind === 'rejected' && outcome.code === 'upload_unavailable';
17
17
  }
18
- function modelFailure(classified, envelope) {
19
- if (classified === null) {
20
- return envelope === null ? { kind: 'transport-uncertainty' } : MODEL_ABSENT;
21
- }
22
- return failedModel(classified);
23
- }
24
18
  export function createAgentsHouseAdapter(options) {
25
19
  if ('site' in options)
26
20
  return createSiteAdapter(options.site);
@@ -28,76 +22,75 @@ export function createAgentsHouseAdapter(options) {
28
22
  const notifications = houseNotifications(transport, 'credential');
29
23
  const tracked = new Map();
30
24
  const handed = new Map();
31
- const models = modelShelf();
32
- function bootstrappedRoom(envelope, entry) {
25
+ let bounds;
26
+ function declared() {
27
+ if (bounds === undefined)
28
+ throw new Error('no Discovery declared the bounds');
29
+ return bounds;
30
+ }
31
+ async function bootstrappedRoom(envelope, entry) {
33
32
  const scope = envelope.scopes.find((candidate) => matchesScope(candidate, entry));
34
33
  if (scope === undefined)
35
34
  return { kind: 'room-not-readable', locator: entry.locator };
36
35
  handed.set(entry.locator, scopeLinks(scope));
37
- notifications.hold(entry.authority, scope);
38
- return bootstrapOf(scope, entry);
36
+ notifications.reach(entry.authority, scope);
37
+ const models = await scopeModels(scope, entry);
38
+ return { ...bootstrapOf(scope), ...(models === undefined ? {} : { models }) };
39
39
  }
40
- function enumeratedRoom(enumeration, ask) {
40
+ async function enumeratedRoom(enumeration, ask) {
41
41
  const view = viewOf(enumeration, ask.entry);
42
42
  if (view === undefined)
43
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)));
48
- }
49
- return answer;
44
+ notifications.reach(ask.entry.authority, view);
45
+ const answer = refreshFrom(view, ask.fromRoomVersion);
46
+ if (answer.kind !== 'net-advancement')
47
+ return answer;
48
+ handed.set(ask.entry.locator, enumeratedLinks(view, handed.get(ask.entry.locator)));
49
+ const models = await viewModels(view, ask.entry);
50
+ return models === undefined ? answer : { ...answer, models };
50
51
  }
51
- function streamed(entry, request, from) {
52
+ async function streamed(entry, request, from) {
52
53
  const links = handed.get(entry.locator);
53
54
  if (links?.roomVersion !== request.fromRoomVersion)
54
55
  return null;
55
56
  const advanced = notifications.advance(entry, from, (path, revision) => links.revisions.get(path) === revision);
56
57
  if (advanced === null)
57
58
  return null;
58
- if (request.minPosition !== undefined &&
59
- !reachedVersion(advanced.page.roomVersion, request.minPosition, entry.logEpoch))
60
- return null;
61
59
  const relinked = streamedLinks(links, advanced);
62
60
  if (relinked === null)
63
61
  return null;
64
62
  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);
69
- }
70
- function modelPrefixes(entry) {
71
- return entry.schemas.map((schema) => schemaPath(entry.handle, schema));
63
+ const models = await streamedModels(advanced.schemas, entry, 'credential');
64
+ return models === undefined ? advanced.page : { ...advanced.page, models };
72
65
  }
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
- }
89
- }
90
- return acquired;
66
+ function held(rooms) {
67
+ const kept = rooms.flatMap((room) => {
68
+ const entry = tracked.get(room.locator);
69
+ const at = logPosition(room.roomVersion);
70
+ if (entry === undefined || at === null)
71
+ return [];
72
+ handed.set(room.locator, heldLinks(room));
73
+ notifications.reach(entry.authority, at);
74
+ return [presented(entry.authority, at)];
75
+ });
76
+ notifications.send(kept);
91
77
  }
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));
78
+ function adopted(entry, outcome) {
79
+ if (outcome.kind !== 'accepted')
80
+ return outcome;
81
+ const { originals, ...accepted } = outcome;
82
+ const links = handed.get(entry.locator);
83
+ if (links === undefined)
84
+ return accepted;
85
+ const follows = followsVersion(links.roomVersion, accepted.roomVersion);
86
+ const relinked = acceptedLinks(links, accepted, follows ? accepted.roomVersion : links.roomVersion, originals);
87
+ handed.set(entry.locator, relinked.links);
88
+ const at = logPosition(accepted.roomVersion);
89
+ if (follows && at !== null)
90
+ notifications.reach(entry.authority, at);
91
+ return relinked.attachments === undefined
92
+ ? accepted
93
+ : { ...accepted, attachments: relinked.attachments };
101
94
  }
102
95
  function authorityFor(locator) {
103
96
  return tracked.get(locator);
@@ -111,9 +104,7 @@ export function createAgentsHouseAdapter(options) {
111
104
  const { authority, position, log_epoch: logEpoch } = body;
112
105
  if (typeof position !== 'string' || typeof logEpoch !== 'string')
113
106
  return result;
114
- const locator = authority === undefined
115
- ? PRIVATE_LOCATOR
116
- : [...tracked.values()].find((entry) => entry.authority === authority)?.locator;
107
+ const locator = [...tracked.values()].find((entry) => entry.authority === authority)?.locator;
117
108
  if (locator === undefined)
118
109
  return result;
119
110
  return { ...result, at: { locator, roomVersion: roomVersion({ position, logEpoch }) } };
@@ -137,20 +128,20 @@ export function createAgentsHouseAdapter(options) {
137
128
  }
138
129
  async function bootstrapped(entries) {
139
130
  const answers = [];
140
- for (const part of selections(entries, weight, DOOR_SELECTION_MAX)) {
131
+ for (const part of selections(entries, weight, declared().max_prefixes)) {
141
132
  const answer = await transport.door(DOOR_BOOTSTRAP, {
142
133
  prefixes: part.flatMap((entry) => contentPrefixes(entry)),
143
134
  });
144
135
  const classified = part.map((entry) => classifyDoor(answer.status, answer.body, entry.locator));
145
136
  const envelope = classified[0] === null ? parseEnvelope(await bundled(answer.body)) : null;
146
- part.forEach((entry, index) => {
137
+ for (const [index, entry] of part.entries()) {
147
138
  const failure = classified[index];
148
139
  if (failure === null || failure === undefined) {
149
- answers.push(envelope === null ? UNCERTAIN_READ : bootstrappedRoom(envelope, entry));
150
- return;
140
+ answers.push(envelope === null ? UNCERTAIN_READ : await bootstrappedRoom(envelope, entry));
141
+ continue;
151
142
  }
152
- answers.push(failure.kind === 'beyond-horizon' ? UNCERTAIN_READ : failure);
153
- });
143
+ answers.push(failure);
144
+ }
154
145
  }
155
146
  return answers;
156
147
  }
@@ -166,27 +157,15 @@ export function createAgentsHouseAdapter(options) {
166
157
  }
167
158
  async function enumerated(asks) {
168
159
  const answers = new Map();
169
- const parts = layered(asks).flatMap((layer) => selections(layer, (ask) => weight(ask.entry), DOOR_SELECTION_MAX));
160
+ const parts = layered(asks).flatMap((layer) => selections(layer, (ask) => weight(ask.entry), declared().max_prefixes));
170
161
  for (const part of parts) {
171
162
  let open = [...part];
172
163
  while (open.length > 0) {
173
164
  const answer = await transport.door(DOOR_ENUMERATE, {
174
165
  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
- })),
166
+ positions: open.map((ask) => presented(ask.entry.authority, ask.from)),
179
167
  });
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));
168
+ const classified = open.map((ask) => classifyRead(answer.status, answer.body, ask.entry.locator));
190
169
  if (classified[0]?.kind === 'beyond-horizon') {
191
170
  const named = doorRefusal(answer.body)?.fields.authority;
192
171
  const expired = open.filter((ask) => ask.entry.authority === named);
@@ -198,14 +177,14 @@ export function createAgentsHouseAdapter(options) {
198
177
  continue;
199
178
  }
200
179
  const enumeration = classified[0] === null ? parseEnumeration(answer.body, 'credential') : null;
201
- open.forEach((ask, index) => {
180
+ for (const [index, ask] of open.entries()) {
202
181
  const failure = classified[index];
203
182
  if (failure !== null && failure !== undefined) {
204
183
  answers.set(ask, failure);
205
- return;
184
+ continue;
206
185
  }
207
- answers.set(ask, enumeration === null ? UNCERTAIN_READ : enumeratedRoom(enumeration, ask));
208
- });
186
+ answers.set(ask, enumeration === null ? UNCERTAIN_READ : await enumeratedRoom(enumeration, ask));
187
+ }
209
188
  open = [];
210
189
  }
211
190
  }
@@ -217,7 +196,7 @@ export function createAgentsHouseAdapter(options) {
217
196
  const paths = batchPaths(changes);
218
197
  const sha256 = await deltaDigest(delta);
219
198
  if (handed !== undefined && handed.sha256 === sha256) {
220
- return { body: { ...head, paths, upload: handed } };
199
+ return { body: { ...head, paths, upload: handed, runtime: notifications.runtime } };
221
200
  }
222
201
  const minted = await transport.door(DOOR_BATCH_UPLOAD, { ...head, paths, bytes, sha256 });
223
202
  if (minted.status !== 200) {
@@ -240,12 +219,13 @@ export function createAgentsHouseAdapter(options) {
240
219
  return { outcome: UNCERTAIN };
241
220
  const upload = { url: holding.url, operation: holding.operation, bytes, sha256 };
242
221
  await keep(upload);
243
- return { body: { ...head, paths, upload } };
222
+ return { body: { ...head, paths, upload, runtime: notifications.runtime } };
244
223
  }
245
224
  async function submit(head, changes, delta, bytes, entry, handed, keep) {
246
- const prepared = uploadable(bytes)
225
+ const inline = { ...head, changes, runtime: notifications.runtime };
226
+ const prepared = uploadable(inline, bytes, declared())
247
227
  ? await uploaded(head, changes, delta, bytes, entry, handed, keep)
248
- : { body: { ...head, changes } };
228
+ : { body: inline };
249
229
  if ('outcome' in prepared)
250
230
  return prepared.outcome;
251
231
  const answer = await transport.door(DOOR_BATCH, prepared.body);
@@ -255,17 +235,15 @@ export function createAgentsHouseAdapter(options) {
255
235
  async authorize() {
256
236
  return options.authorize();
257
237
  },
258
- async model(_authorization, request) {
259
- return models.answer(request);
260
- },
261
238
  async discover(_authorization) {
262
239
  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);
240
+ const failed = discoveryFailure(answer.status, answer.body);
241
+ if (failed !== null)
242
+ return failed;
266
243
  const document = parseDiscovery(answer.body);
267
244
  if (document === null)
268
245
  return { kind: 'transport-uncertainty' };
246
+ bounds = document.bounds;
269
247
  const entries = trackedFrom(document);
270
248
  tracked.clear();
271
249
  for (const entry of entries)
@@ -274,9 +252,7 @@ export function createAgentsHouseAdapter(options) {
274
252
  if (!tracked.has(locator))
275
253
  handed.delete(locator);
276
254
  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));
255
+ return mapDiscovery(document, document.authorities.map((authority) => discoveredRoom(authority)), capabilities(document));
280
256
  },
281
257
  async bootstrap(_authorization, request) {
282
258
  const entry = authorityFor(request.locator);
@@ -295,16 +271,10 @@ export function createAgentsHouseAdapter(options) {
295
271
  const from = logPosition(request.fromRoomVersion);
296
272
  if (from === null)
297
273
  return { kind: 'beyond-horizon' };
298
- const answered = streamed(entry, request, from);
274
+ const answered = await streamed(entry, request, from);
299
275
  if (answered !== null)
300
276
  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
- });
277
+ return enumerateTogether({ entry, from, fromRoomVersion: request.fromRoomVersion });
308
278
  },
309
279
  async mutate(_authorization, request, keep) {
310
280
  const entry = authorityFor(request.locator);
@@ -319,8 +289,8 @@ export function createAgentsHouseAdapter(options) {
319
289
  const handed = request.upload;
320
290
  const outcome = await submit(head, mapped.changes, delta, bytes, entry, handed, keep);
321
291
  if (handed === undefined || !lapsedGrant(outcome))
322
- return outcome;
323
- return submit(head, mapped.changes, delta, bytes, entry, undefined, keep);
292
+ return adopted(entry, outcome);
293
+ return adopted(entry, await submit(head, mapped.changes, delta, bytes, entry, undefined, keep));
324
294
  },
325
295
  async history(_authorization, request) {
326
296
  const entry = authorityFor(request.locator);
@@ -340,10 +310,13 @@ export function createAgentsHouseAdapter(options) {
340
310
  reached(locator, version, target) {
341
311
  return reachedVersion(version, target, authorityFor(locator)?.logEpoch);
342
312
  },
313
+ follows(_locator, version, next) {
314
+ return followsVersion(version, next);
315
+ },
343
316
  async action(_authorization, request) {
344
317
  return withAt(await houseAction(transport, request));
345
318
  },
346
- roomVersions: notifications,
319
+ roomStream: { hold: held, observe: notifications.observe },
347
320
  conversations: notifications.conversations,
348
321
  serviceMode: notifications.serviceMode,
349
322
  };