@agentshouse/mdruntime-adapter 0.1.0-cacce09fc82c6 → 0.1.0-cad6a4aeee9e8

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
@@ -1,13 +1,13 @@
1
1
  # Instructions for the App Creator's agent
2
2
 
3
3
  These instructions address an agent in an environment with Git. Obtain the
4
- App Repository, change it, build, and push. They are documentation, not
5
- enforcement.
4
+ App Repository, change it, build, and push. They are documentation, not enforcement.
6
5
 
7
6
  ## The MD Runtime API
8
7
 
9
8
  App code reaches the MD Runtime through the remote client. The surfaces are
10
- Rooms, Query, Search, Observe, Types, Room Draft, Save, History, Call, Reached, Log,
9
+ Rooms, Query, Search, Observe, Types, Room Draft, Save, History, the binary file
10
+ reads, 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
13
  statement, the deployment facts and the signed-in member are observations only.
@@ -27,6 +27,8 @@ value whole and returns its unsubscribe, and `close()` ends the observation.
27
27
  Closing the port ends every handle and rejects every pending call and
28
28
  observation; a client that reconnects observes again.
29
29
 
30
+ `observe('agents')` answers every Agent a new conversation can go to, each
31
+ `{ identity, name }`, whether or not it has a conversation yet.
30
32
  Each conversation the Provider's conversation list names is held complete in the
31
33
  browser. `conversation.list()` and `observe('conversations')` answer each with its
32
34
  Agent's identity and name, its name, created and finished times, last outcome and live
@@ -43,15 +45,34 @@ and none of them is stored or searchable.
43
45
  sending it is a Provider Action that needs the Provider reachable and is never
44
46
  queued.
45
47
 
46
- Each Room in Rooms lists its `attachments`, the files the Provider holds for it
47
- that its Documents link by the Provider's reference, ordered by `reference`,
48
- each with `name`, `byteLength`, `mediaType` and the Provider's own entry as
49
- `entry`. They are as the Provider last declared them and hold no bytes;
50
- open one through the Provider Action that serves it.
48
+ A binary file at a Path of a Room is a binary Path entry. Query lists it by
49
+ `path` with its `binaryFile` record and never its bytes: `{ state: 'accepted',
50
+ revision, path, fileRef, byteLength, mediaType, sha256 }`, or, from a Save until
51
+ the Provider accepts it, `{ state: 'pending', localId, path, byteLength,
52
+ mediaType, sha256 }` with no revision. Write one with a Room Draft whose only part
53
+ is `file: { blob }`, a `Blob` whose `type` is its media type; Save keeps the bytes
54
+ in its Pending Change, works offline, and the record turns accepted with the
55
+ Provider's revision once the Pending Change is accepted. Move or remove an
56
+ accepted one as a Document. Move or remove a pending one the same way, before or
57
+ after Save: the Room Draft or its queued Pending Change carries the bytes to the
58
+ new Path or drops them, and once that Pending Change has gone to the Provider
59
+ Save refuses it as `unknown-revision` until it is accepted. Read the bytes with
60
+ `binaryFile.read(room, path)`: a pending record answers its saved bytes, and
61
+ every read of an accepted one asks the Provider again and keeps nothing. Pass a
62
+ History revision as `binaryFile.read(room, path, revision)` to open that
63
+ revision, a removed file's last one included. Text, a Record attachment or a conversation
64
+ message may name a file directly by its `fileRef`; read that file with
65
+ `binaryFile.readReference({ fileRef, referrer })`, where the referrer is the
66
+ `referrer` the Provider gave beside the reference, or `{ room, path }` of the
67
+ document whose text names it. Both answer `{ kind: 'binary', blob }` or a
68
+ refusal or failure. History of a binary Path lists each revision's
69
+ `binaryFile` metadata without bytes.
51
70
 
52
71
  Rooms, Query, Search, Observe, Types, Room Draft, Save, and Reached never
53
72
  touch the network.
54
- History and Call go to the Provider through the Adapter. A Call result whose
73
+ History, the binary file reads and Call go to the Provider through the Adapter. Call takes the Action names
74
+ the Adapter declares; any other name answers `undeclared` without reaching the
75
+ Provider. A Call result whose
55
76
  effect the Provider places in a Room carries `at`, that Room and Room Version;
56
77
  `reached(room, roomVersion)` answers whether the Room's confirmed state has
57
78
  reached it, and the MD Runtime keeps refreshing that Room until it has;
@@ -66,6 +87,13 @@ client is asynchronous. Results are detached snapshots. Nothing in this
66
87
  surface returns the authorization, performs a request the App's code
67
88
  composes, or exposes the browser store.
68
89
 
90
+ Every refusal and failure carries `code` and `retryable`: each Call and History answer
91
+ other than its result, a refused Save or Room Draft write, a returned Room Draft's
92
+ reason, a Room's refusal and the Connection Refusal, and every error a member rejects
93
+ with, beside its message. A Provider refusal carries the Provider's own `retryable`.
94
+ Every code and every value the API answers is open: handle one you do not know by its
95
+ `code` and `retryable`.
96
+
69
97
  Read the deployment facts with `observe('deployment-facts')`. Interpret the
70
98
  opaque value using the host's contract.
71
99
 
@@ -113,8 +141,9 @@ data:
113
141
  list of pointers and `sections` `'all'` or a list of names. Selected pointers
114
142
  return the frontmatter holding only them, nested as written. A backlink names
115
143
  the referring Path, MD Type and the pointer it came from as `field`. Room and Path always return; a Markdown
116
- Document also returns its MD Type. A non-Markdown Document or binary link
117
- target returns only Room and Path. An unselected part is absent. Select only
144
+ Document also returns its MD Type. A non-Markdown Document returns only Room
145
+ and Path, and a binary Path entry Room, Path and its `binaryFile` record,
146
+ whatever is selected. An unselected part is absent. Select only
118
147
  what a screen shows: a list that selects the Markdown hears every edit of it.
119
148
  - **Change.** `change` is `{ author, time }` of the Document's head revision as
120
149
  the Provider last delivered it: `author` is `{ kind: 'user' | 'site', id, name }`
@@ -129,9 +158,9 @@ data:
129
158
  over every match and ordered by `count` or a key. A sort or group takes only a
130
159
  pointer that holds one value. `limit` bounds the Documents or the groups.
131
160
  - **Results and errors.** A result carries no Room Version: read freshness from
132
- Rooms and Sync Status. An invalid query fails with `invalid-query`,
133
- `unknown-type`, `unknown-field` or `wrong-kind`, naming where, and never
134
- answers an empty result in its place.
161
+ Rooms and Sync Status. An invalid query fails with the `code`
162
+ `invalid-query`, `unknown-type`, `unknown-field` or `wrong-kind`, naming where,
163
+ and never answers an empty result in its place.
135
164
 
136
165
  ## Local Search rules
137
166
 
@@ -169,9 +198,9 @@ the current Room Draft; read it and write again.
169
198
 
170
199
  Save takes one Room and the Room Drafts of it to save, each with its revision,
171
200
  validates locally, and on success appends one Change Batch to that Room's
172
- queue and removes those Room Drafts. It is refused as `stale`, as
201
+ queue and removes those Room Drafts. It is refused with the `code` `stale`,
173
202
  `changed-underneath` naming each part whose base no longer matches the visible
174
- state, or by a local validation rule, and then creates nothing and leaves every
203
+ state, or a local validation rule, and then creates nothing and leaves every
175
204
  Room Draft in place. A directory move or removal is a move or removal part on
176
205
  each Document and binary link target beneath it, saved together.
177
206
 
@@ -191,6 +220,13 @@ it names; the MD Runtime retries the same Change Batch identity and payload and
191
220
  never infers an outcome from transport uncertainty. The MD Runtime never
192
221
  combines, reorders, or rebases.
193
222
 
223
+ On a Site, every Save stays in the visitor's browser. Write grants and
224
+ revisions do not refuse it, and its Pending Change shows in every query and
225
+ across reloads until the browser's storage is cleared. It is never sent:
226
+ `observe('queue', room)` shows it `local`, and Sync Status never waits on it.
227
+ Once the Room changes so that it no longer applies, it leaves the queue and
228
+ returns no Room Draft.
229
+
194
230
  `observe('service-mode')` answers the Provider's Service
195
231
  Mode, `open` or `write-halted`. While writes are halted, Save still succeeds,
196
232
  its Change Batch waits unsent, and the queue is submitted in order once the
@@ -226,26 +262,55 @@ the network. Data lives only in the App Creator's browser and with the Provider.
226
262
 
227
263
  ## App code takes the client its host hands it and never constructs a Runtime
228
264
 
229
- App code takes the client its host hands it: in House,
230
- `connectHouseBridge().runtime` from `@agentshouse/app-bridge` resolves to the
231
- client House built into the page. It never constructs a Runtime or a client.
232
- It imports only types from `@agentshouse/mdruntime/client`, does not call
233
- `connectMdRuntime` or `serveMdRuntime`, and does not import the package main,
234
- the host entry, or the Adapter package. Hosts and tests use those entries; the
235
- served App does not.
265
+ App code takes the client its host hands it: in House, `houseBridge().runtime`
266
+ from `@agentshouse/app-bridge` resolves to the client House built into the page.
267
+ It never constructs a Runtime or a client. It imports only types from
268
+ `@agentshouse/mdruntime/client`, does not call `connectMdRuntime` or
269
+ `serveMdRuntime`, and does not import the package main, the host entry, or the
270
+ Adapter package. Hosts and tests use those entries; the served App does not.
236
271
 
237
272
  A React App may observe and save through `@agentshouse/mdruntime/react`, which
238
273
  names React as a peer dependency. `useObserve(client, topic, ...input)` takes
239
274
  the arguments of `observe` and returns `{ state: 'loading' }` until the topic's
240
275
  first value arrives, then `{ state: 'ready', value }`, re-rendering on each
241
- change; a `null` client observes nothing and stays loading. `useSave(client)` returns `busy`, the last `outcome` or `failure`, and
242
- `save(room, roomDrafts)`, which writes each Path's parts onto the Room Draft
243
- already there, keeping the bases its parts have, or onto a new one, and saves
244
- them together. A refused Save leaves the Room Drafts for the App to save again
245
- or discard; a failure is recorded and rejects. `saveRoomDrafts(client, room,
246
- roomDrafts)` is that save outside a component. A react-admin or Refine App
247
- reads and writes its Rooms through the data providers of
248
- `@agentshouse/mdruntime-families`.
276
+ change; a `null` client observes nothing and stays loading. `useSave(client)`
277
+ returns `busy`, the last `outcome` or `failure`, and `save(room, roomDrafts)`,
278
+ which writes each Path's parts onto the Room Draft already there, keeping the
279
+ bases its parts have, or onto a new one, and saves them together. A refused
280
+ Save leaves the Room Drafts for the App to save again or discard; a failure is
281
+ recorded and rejects. `saveRoomDrafts(client, room, roomDrafts)` is that save
282
+ outside a component. A react-admin or Refine App reads and writes its Rooms
283
+ through the data providers of `@agentshouse/mdruntime-families`.
284
+
285
+ ## The Chat
286
+
287
+ `@agentshouse/mdruntime/chat` holds the Chat, one data layer for every App.
288
+ Its required peers are React, React DOM and `@assistant-ui/react`: add React as
289
+ a dependency, also in an App not written in React.
290
+
291
+ Place the ready chat with `<Chat client={runtime} conversation={id}
292
+ agent={agent} width="1/3" showChats />`: `conversation` opens one, `null` for a
293
+ new chat, `agent` is the Agent a new chat goes to, `onOpen` hears each one it
294
+ opens, and `width` is `full` (the place you give it), or `3/4`, `1/2` or `1/3`
295
+ of the window docked at its right edge, whole on a narrow window. `showChats`
296
+ adds its conversation list; or draw your own inside a `ChatProvider` around a
297
+ `<Chat />` with no `client`. It carries its own styles; theme it with CSS custom
298
+ properties on it or an ancestor: `--chat-background`, `--chat-surface`,
299
+ `--chat-text`, `--chat-text-muted`, `--chat-accent`, `--chat-line`,
300
+ `--chat-attention`, `--chat-danger`, `--chat-font`, `--chat-font-mono`,
301
+ `--chat-font-size`, `--chat-radius` and `--chat-density` (a factor for spacing);
302
+ an unset one keeps House's light or dark look. `mountChat(element, { client })`
303
+ places it outside React and returns `update(props)` and `unmount()`.
304
+
305
+ Mix `ChatMessageList` (`components` takes your `UserMessage` and
306
+ `AssistantMessage`), `ChatInput` and `ChatQuestionCard` with your own design
307
+ inside a `ChatProvider`, or compose assistant-ui's primitives there; `useChat()`
308
+ gives `send`, the conversations, the Agents, questions to `answer`, `options`
309
+ to `choose`, `commands`, the queue to `edit` or `unqueue`, `stop`, `kill` and
310
+ outcomes; never replace its messages, sending or store. A secret question is
311
+ never answered here; typed answers live in Presentation State's `typed` key:
312
+ keep it, and change Presentation State only inside `inTurn(client, work)` from
313
+ `@agentshouse/mdruntime/client`. `Markdown` draws Markdown safely.
249
314
 
250
315
  ## What an agent must never do
251
316
 
package/dist/actions.d.ts CHANGED
@@ -1,8 +1,47 @@
1
- import { type AcceptedMessage, type ActionDeclaration, type ActionRequest, type ActionResult, type ConversationAgents } from '@agentshouse/mdruntime';
1
+ import { type AcceptedMessage, type ActionDeclaration, type ActionRequest, type ActionResult, type ConversationAgents, type ConversationHistories, type ConversationHistoryRequest, type FileDeclaration } from '@agentshouse/mdruntime';
2
2
  import type { HouseDoorAnswer, HouseTransport } from './transport.js';
3
+ type Operated = {
4
+ readonly operation_id?: string;
5
+ };
6
+ type ConversationControl = Operated & {
7
+ readonly conversation: string;
8
+ };
9
+ type SentFile = FileDeclaration & {
10
+ readonly blob: Blob;
11
+ };
12
+ export type AppInputs = {
13
+ readonly 'conversation.answer': ConversationControl & {
14
+ readonly answer: {
15
+ readonly interaction_id: string;
16
+ readonly response: unknown;
17
+ };
18
+ };
19
+ readonly 'conversation.create': Operated & {
20
+ readonly agent_id: string;
21
+ };
22
+ readonly 'conversation.delete': ConversationControl;
23
+ readonly 'conversation.history': ConversationHistoryRequest;
24
+ readonly 'conversation.interrupt': ConversationControl;
25
+ readonly 'conversation.kill': ConversationControl;
26
+ readonly 'conversation.send': ConversationControl & {
27
+ readonly text?: string;
28
+ readonly files?: readonly SentFile[];
29
+ };
30
+ };
31
+ export type AppAnswers = {
32
+ readonly 'conversation.history': ConversationHistories;
33
+ };
34
+ export type AppAnswerAdditions = {
35
+ readonly 'conversation.send': {
36
+ readonly turn: string;
37
+ };
38
+ };
39
+ export declare const HOUSE_APP_ACTS: Readonly<Record<string, string>>;
40
+ export declare const HOUSE_APP_BATCHES: Readonly<Partial<Record<string, readonly string[]>>>;
3
41
  export declare function houseConversationAgents(locator: string): ConversationAgents;
4
42
  export declare function declaredActions(routes: readonly string[]): readonly ActionDeclaration[];
5
43
  export declare function houseAction(transport: HouseTransport, request: ActionRequest): Promise<ActionResult>;
6
44
  export declare function actionOutcome(answer: HouseDoorAnswer, name: string): ActionResult;
7
45
  export declare function acceptedMessage(entry: unknown): AcceptedMessage | null;
46
+ export {};
8
47
  //# sourceMappingURL=actions.d.ts.map
@@ -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;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"}
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,EACvB,KAAK,qBAAqB,EAE1B,KAAK,0BAA0B,EAC/B,KAAK,eAAe,EACrB,MAAM,wBAAwB,CAAC;AAEhC,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAQtE,KAAK,QAAQ,GAAG;IAAE,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnD,KAAK,mBAAmB,GAAG,QAAQ,GAAG;IAAE,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAExE,KAAK,QAAQ,GAAG,eAAe,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAA;CAAE,CAAC;AAE1D,MAAM,MAAM,SAAS,GAAG;IACtB,QAAQ,CAAC,qBAAqB,EAAE,mBAAmB,GAAG;QACpD,QAAQ,CAAC,MAAM,EAAE;YAAE,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;YAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAA;SAAE,CAAC;KAClF,CAAC;IACF,QAAQ,CAAC,qBAAqB,EAAE,QAAQ,GAAG;QAAE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;IACzE,QAAQ,CAAC,qBAAqB,EAAE,mBAAmB,CAAC;IACpD,QAAQ,CAAC,sBAAsB,EAAE,0BAA0B,CAAC;IAC5D,QAAQ,CAAC,wBAAwB,EAAE,mBAAmB,CAAC;IACvD,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,CAAC;IAClD,QAAQ,CAAC,mBAAmB,EAAE,mBAAmB,GAAG;QAClD,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QACvB,QAAQ,CAAC,KAAK,CAAC,EAAE,SAAS,QAAQ,EAAE,CAAC;KACtC,CAAC;CACH,CAAC;AAEF,MAAM,MAAM,UAAU,GAAG;IACvB,QAAQ,CAAC,sBAAsB,EAAE,qBAAqB,CAAC;CACxD,CAAC;AAEF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,mBAAmB,EAAE;QAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CACzD,CAAC;AAwEF,eAAO,MAAM,cAAc,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAE3D,CAAC;AAEF,eAAO,MAAM,iBAAiB,EAAE,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,CAKhF,CAAC;AAMJ,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;AAwED,wBAAgB,aAAa,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,CAOjF;AAkLD,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,eAAe,GAAG,IAAI,CAiBtE"}
package/dist/actions.js CHANGED
@@ -3,44 +3,74 @@ import { doorRefusal } from './refusal.js';
3
3
  const HISTORY_PAGE = 100;
4
4
  const HISTORY_CONVERSATIONS = 64;
5
5
  const OCTET_STREAM = 'application/octet-stream';
6
- const CONVERSATION_ROUTES = new Map([
7
- ['conversation.create', '/door/conversations/create'],
8
- ['conversation.send', '/door/conversations/send'],
9
- ['conversation.answer', '/door/conversations/interaction/answer'],
10
- ['conversation.interrupt', '/door/conversations/interrupt'],
11
- ['conversation.kill', '/door/conversations/kill'],
12
- ['conversation.delete', '/door/conversations/delete'],
13
- ['conversation.history', '/door/conversations/history'],
14
- ]);
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, batched) {
15
+ return {
16
+ door,
17
+ ...(batched === undefined ? {} : { batched }),
18
+ carry: (transport, input, name) => carry(transport, `/door/${door}`, input, name),
19
+ };
20
+ }
21
+ const APP_ACTS = {
22
+ 'access.read': mapped('rooms/access/read'),
23
+ 'conversation.answer': mapped('conversations/interaction/answer', answerBody),
24
+ 'conversation.create': carried('conversations/create', createAction),
25
+ 'conversation.delete': mapped('conversations/delete', controlBody),
26
+ 'conversation.history': carried('conversations/history', historyAction, ['conversations']),
27
+ 'conversation.interrupt': mapped('conversations/interrupt', controlBody),
28
+ 'conversation.kill': mapped('conversations/kill', controlBody),
29
+ 'conversation.markDone': mapped('conversations/done'),
30
+ 'conversation.rename': mapped('conversations/rename'),
31
+ 'conversation.send': carried('conversations/send', sendAction),
32
+ 'conversation.setOption': mapped('conversations/option'),
33
+ 'feature.list': mapped('apps/features/read'),
34
+ 'holder.list': mapped('apps/holders'),
35
+ 'holder.ring': mapped('apps/ring'),
36
+ 'member.list': mapped('rooms/members'),
37
+ 'message.send': mapped('apps/messages/send'),
38
+ 'processing.read': mapped('rooms/settings/processing/read'),
39
+ 'record.list': carried('records/read', recordsAction),
40
+ 'relay.read': mapped('apps/relay'),
41
+ 'routine.list': mapped('routines/access'),
42
+ 'routineAccess.list': mapped('routines/granted'),
43
+ 'routineAllowance.list': mapped('routines/allowance'),
44
+ 'routineRequest.list': mapped('routines/requests'),
45
+ 'storage.read': mapped('storage/inventory'),
46
+ 'trigger.list': mapped('triggers/read'),
47
+ 'triggerOccurrence.list': mapped('triggers/fired'),
48
+ };
49
+ export const HOUSE_APP_ACTS = Object.fromEntries(Object.entries(APP_ACTS).map(([name, act]) => [name, act.door]));
50
+ export const HOUSE_APP_BATCHES = Object.fromEntries(Object.entries(APP_ACTS).flatMap(([name, act]) => act.batched === undefined ? [] : [[name, act.batched]]));
51
+ const APP_NAMES = new Map(Object.entries(APP_ACTS).map(([name, act]) => [act.door, name]));
15
52
  export function houseConversationAgents(locator) {
16
- return { locator, type: 'house-agent', identity: 'agent', name: 'name' };
53
+ return { locator, type: 'house-agent', identity: 'agent', name: 'name', retired: 'retired' };
17
54
  }
18
55
  export function declaredActions(routes) {
19
- const mapped = new Map([...CONVERSATION_ROUTES].map(([name, route]) => [route.slice('/door/'.length), name]));
20
56
  return routes.map((route) => ({
21
- name: mapped.get(route) ?? route,
57
+ name: APP_NAMES.get(route) ?? route,
22
58
  inputShape: {},
23
59
  resultKind: 'house',
24
60
  }));
25
61
  }
26
62
  export function houseAction(transport, request) {
27
- if (request.name === 'conversation.send')
28
- return sendAction(transport, request.input);
29
- if (request.name === 'conversation.history')
30
- return historyAction(transport, request.input);
31
- if (request.name === 'attachments/upload')
32
- return attachAction(transport, request.input);
33
- if (request.name === 'attachments/get')
34
- 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));
35
68
  const route = routeOf(request.name);
36
69
  if (route === null)
37
70
  return Promise.resolve(malformed());
38
71
  return carry(transport, route, request.name, request.input);
39
72
  }
40
73
  function routeOf(name) {
41
- const mapped = CONVERSATION_ROUTES.get(name);
42
- if (mapped !== undefined)
43
- return mapped;
44
74
  const parts = name.split('/');
45
75
  if (parts.some((part) => part === '.' || part === '..'))
46
76
  return null;
@@ -62,51 +92,78 @@ function operationId(input) {
62
92
  return text(input, 'operation_id') ?? changeBatchIdentity();
63
93
  }
64
94
  function malformed() {
65
- return { kind: 'rejected', code: 'invalid_request', fields: {} };
95
+ return { kind: 'rejected', code: 'invalid_request', fields: {}, retryable: false };
66
96
  }
67
- function bodyOf(name, input) {
68
- if (name === 'conversation.create') {
69
- return { agent_id: text(input, 'agent_id'), operation_id: operationId(input) };
70
- }
71
- if (name === 'conversation.interrupt' ||
72
- name === 'conversation.kill' ||
73
- name === 'conversation.delete') {
74
- return { conversation_id: text(input, 'conversation'), operation_id: operationId(input) };
75
- }
76
- if (name === 'conversation.answer') {
77
- const nested = record(record(input).answer);
78
- return {
79
- conversation_id: text(input, 'conversation'),
80
- operation_id: operationId(input),
81
- interaction_id: text(nested, 'interaction_id'),
82
- response: nested.response,
83
- };
84
- }
85
- 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
+ };
114
+ }
115
+ async function createAction(transport, route, input, name) {
116
+ const outcome = actionOutcome(await transport.door(route, createBody(input)), name);
117
+ if (outcome.kind !== 'action')
118
+ return outcome;
119
+ const held = record(outcome.result);
120
+ const conversation = text(held, 'conversation_id');
121
+ return conversation === undefined ? outcome : { ...outcome, result: { ...held, conversation } };
86
122
  }
87
123
  function withTurn(body) {
88
124
  const held = record(body);
89
125
  const turn = text(held, 'message_id');
90
- return turn === undefined ? body : { ...held, turn };
126
+ return turn === undefined
127
+ ? body
128
+ : { ...held, turn };
91
129
  }
92
130
  export function actionOutcome(answer, name) {
93
131
  if (answer.status === 401)
94
132
  return { kind: 'revoked-authorization' };
95
133
  const refusal = doorRefusal(answer.body);
96
- if (refusal !== null) {
97
- return { kind: 'rejected', code: refusal.code, fields: refusal.fields };
98
- }
134
+ if (refusal !== null)
135
+ return { kind: 'rejected', ...refusal };
99
136
  if (answer.status === 404)
100
- return { kind: 'rejected', code: 'action-unimplemented', fields: { name } };
137
+ return unimplemented(name);
101
138
  if (answer.status === 0 || answer.status >= 400)
102
139
  return { kind: 'transport-uncertainty' };
103
- if (name === 'conversation.send')
104
- return { kind: 'action', result: withTurn(answer.body) };
105
140
  return { kind: 'action', result: answer.body };
106
141
  }
142
+ function referredRecord(view, roomRef) {
143
+ const held = record(view);
144
+ if (roomRef === undefined || typeof held.record !== 'string' || !Array.isArray(held.attachments))
145
+ return view;
146
+ const referrer = { room_ref: roomRef, record: held.record };
147
+ return {
148
+ ...held,
149
+ attachments: held.attachments.map((attachment) => ({ ...record(attachment), referrer })),
150
+ };
151
+ }
152
+ async function recordsAction(transport, route, input, name) {
153
+ const outcome = actionOutcome(await transport.door(route, input), name);
154
+ if (outcome.kind !== 'action')
155
+ return outcome;
156
+ const roomRef = text(input, 'room_ref');
157
+ const read = record(outcome.result);
158
+ return {
159
+ ...outcome,
160
+ result: Array.isArray(read.records)
161
+ ? { ...read, records: read.records.map((view) => referredRecord(view, roomRef)) }
162
+ : referredRecord(outcome.result, roomRef),
163
+ };
164
+ }
107
165
  async function carry(transport, route, name, input) {
108
- const answer = await transport.door(route, bodyOf(name, input));
109
- return actionOutcome(answer, name);
166
+ return actionOutcome(await transport.door(route, input), name);
110
167
  }
111
168
  function sendFile(entry) {
112
169
  const file = record(entry);
@@ -176,12 +233,12 @@ function uploadGrant(entry) {
176
233
  return null;
177
234
  return { method: 'POST', operation: upload.operation, url: upload.url };
178
235
  }
179
- async function uploadOriginals(transport, input, result) {
180
- const originals = record(result).originals;
181
- if (!Array.isArray(originals) || originals.length === 0)
236
+ async function uploadFiles(transport, input, result, name) {
237
+ const sent = record(result).files;
238
+ if (!Array.isArray(sent) || sent.length === 0)
182
239
  return null;
183
240
  const files = Array.isArray(record(input).files) ? record(input).files : [];
184
- for (const [index, entry] of originals.entries()) {
241
+ for (const [index, entry] of sent.entries()) {
185
242
  const grant = uploadGrant(entry);
186
243
  if (grant === 'absent')
187
244
  continue;
@@ -189,81 +246,35 @@ async function uploadOriginals(transport, input, result) {
189
246
  return malformed();
190
247
  const bytes = index < files.length ? await fileBytes(files[index]) : null;
191
248
  if (bytes === null) {
192
- return { kind: 'rejected', code: 'conversation_original_descriptor_required', fields: {} };
249
+ return {
250
+ kind: 'rejected',
251
+ code: 'conversation_file_descriptor_required',
252
+ fields: {},
253
+ retryable: false,
254
+ };
193
255
  }
194
256
  const failed = delivered(await transport.transfer({
195
- act: 'conversation_original_upload',
196
- method: 'POST',
257
+ act: 'conversation_file_upload',
197
258
  url: grant.url,
198
- answer: 'json',
199
259
  body: bytes,
200
260
  operation: grant.operation,
201
- }), 'conversation.send');
261
+ }), name);
202
262
  if (failed !== null)
203
263
  return failed;
204
264
  }
205
265
  return null;
206
266
  }
207
- async function attachAction(transport, input) {
208
- const { blob, ...descriptor } = record(input);
209
- const bytes = await fileBytes({ blob });
210
- if (bytes === null)
211
- return malformed();
212
- const answer = await transport.door('/door/attachments/upload', descriptor);
213
- const outcome = actionOutcome(answer, 'attachments/upload');
214
- if (outcome.kind !== 'action')
215
- return outcome;
216
- const grant = uploadGrant(outcome.result);
217
- if (grant === 'absent')
218
- return outcome;
219
- if (grant === null)
220
- return malformed();
221
- const stored = await transport.transfer({
222
- act: 'original_upload',
223
- method: 'POST',
224
- url: grant.url,
225
- answer: 'json',
226
- body: bytes,
227
- operation: grant.operation,
228
- });
229
- return delivered(stored, 'attachments/upload') ?? { kind: 'action', result: stored.body };
230
- }
231
- async function openAction(transport, input) {
232
- const answer = await transport.door('/door/attachments/get', input);
233
- const outcome = actionOutcome(answer, 'attachments/get');
234
- if (outcome.kind !== 'action')
235
- return outcome;
236
- const { download, ...opened } = record(outcome.result);
237
- if (download === undefined)
238
- return outcome;
239
- const grant = record(download);
240
- if (grant.method !== 'GET' || typeof grant.url !== 'string')
241
- return malformed();
242
- const read = await transport.transfer({
243
- act: 'original_download',
244
- method: 'GET',
245
- url: grant.url,
246
- answer: 'bytes',
247
- });
248
- const failed = delivered(read, 'attachments/get');
249
- if (failed !== null)
250
- return failed;
251
- if (!(read.body instanceof Blob))
252
- return { kind: 'transport-uncertainty' };
253
- return { kind: 'action', result: { ...opened, blob: read.body } };
254
- }
255
- async function sendAction(transport, input) {
267
+ async function sendAction(transport, route, input, name) {
256
268
  const body = sendBody(input);
257
269
  if (body === null)
258
270
  return malformed();
259
- const answer = await transport.door('/door/conversations/send', body);
260
- const outcome = actionOutcome(answer, 'conversation.send');
271
+ const outcome = actionOutcome(await transport.door(route, body), name);
261
272
  if (outcome.kind !== 'action')
262
273
  return outcome;
263
- const uploaded = await uploadOriginals(transport, input, outcome.result);
274
+ const uploaded = await uploadFiles(transport, input, outcome.result, name);
264
275
  if (uploaded !== null)
265
276
  return uploaded;
266
- return outcome;
277
+ return { ...outcome, result: withTurn(outcome.result) };
267
278
  }
268
279
  function historyCursor(value) {
269
280
  const acceptedAt = text(value, 'accepted_at');
@@ -287,12 +298,19 @@ export function acceptedMessage(entry) {
287
298
  const cursor = historyCursor(entry);
288
299
  if (cursor === null)
289
300
  return null;
301
+ const message = structuredClone(record(entry));
302
+ const referrer = { message: cursor.message_id };
290
303
  return {
291
304
  identity: cursor.message_id,
292
305
  turn: text(entry, 'turn_id') ?? cursor.message_id,
293
306
  position: position(cursor),
294
307
  text: text(entry, 'text') ?? '',
295
- message: structuredClone(entry),
308
+ message: Array.isArray(message.files)
309
+ ? {
310
+ ...message,
311
+ files: message.files.map((file) => ({ ...record(file), referrer })),
312
+ }
313
+ : message,
296
314
  };
297
315
  }
298
316
  function historyPage(entry) {
@@ -329,17 +347,17 @@ function historyAsks(input) {
329
347
  }
330
348
  return asks;
331
349
  }
332
- async function historyAction(transport, input) {
350
+ async function historyAction(transport, route, input, name) {
333
351
  const asks = historyAsks(input);
334
352
  if (asks === null)
335
353
  return malformed();
336
354
  const histories = [];
337
355
  for (let at = 0; at < asks.length; at += HISTORY_CONVERSATIONS) {
338
- const answer = await transport.door('/door/conversations/history', {
356
+ const answer = await transport.door(route, {
339
357
  conversations: asks.slice(at, at + HISTORY_CONVERSATIONS),
340
358
  limit: HISTORY_PAGE,
341
359
  });
342
- const outcome = actionOutcome(answer, 'conversation.history');
360
+ const outcome = actionOutcome(answer, name);
343
361
  if (outcome.kind !== 'action')
344
362
  return outcome;
345
363
  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,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,CA0WpF"}
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../src/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,OAAO,EACP,aAAa,EAgBd,MAAM,wBAAwB,CAAC;AAuChC,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;AAwBjC,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CA8cpF"}