@byok-sdk/bot-collaboration 0.0.0-stage → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2058 -2
  3. package/dist/adapter-steps.d.ts +49 -0
  4. package/dist/channel.d.ts +111 -0
  5. package/dist/chunk-33YA66U7.js +7 -0
  6. package/dist/chunk-33YA66U7.js.map +1 -0
  7. package/dist/chunk-5J5SOWWI.js +12 -0
  8. package/dist/chunk-5J5SOWWI.js.map +1 -0
  9. package/dist/chunk-XTZUCECQ.js +12 -0
  10. package/dist/chunk-XTZUCECQ.js.map +1 -0
  11. package/dist/chunk-ZUFZCROA.js +27 -0
  12. package/dist/chunk-ZUFZCROA.js.map +1 -0
  13. package/dist/coalesce.d.ts +18 -0
  14. package/dist/commit-vectors.test-support.d.ts +173 -0
  15. package/dist/commit.d.ts +52 -0
  16. package/dist/compaction.d.ts +13 -0
  17. package/dist/delegation.d.ts +12 -0
  18. package/dist/delivery-routing.d.ts +63 -0
  19. package/dist/delivery-vectors.test-support.d.ts +78 -0
  20. package/dist/delivery.d.ts +20 -0
  21. package/dist/dream.d.ts +88 -0
  22. package/dist/home-projections.d.ts +5 -0
  23. package/dist/host-kit.d.ts +40 -0
  24. package/dist/host-kit.js +6 -0
  25. package/dist/host-kit.js.map +1 -0
  26. package/dist/host.d.ts +433 -0
  27. package/dist/inbound.d.ts +17 -0
  28. package/dist/index.d.ts +5 -0
  29. package/dist/index.js +16 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/k4-fixtures.test-support.d.ts +10 -0
  32. package/dist/l-test-host.test-support.d.ts +72 -0
  33. package/dist/migration.d.ts +251 -0
  34. package/dist/model.d.ts +83 -0
  35. package/dist/persona.d.ts +2 -0
  36. package/dist/retention-vectors.test-support.d.ts +17 -0
  37. package/dist/retention.d.ts +61 -0
  38. package/dist/rooms.d.ts +22 -0
  39. package/dist/routine-vectors.test-support.d.ts +81 -0
  40. package/dist/routines.d.ts +110 -0
  41. package/dist/rules/autonomy.d.ts +67 -0
  42. package/dist/rules/cards.d.ts +31 -0
  43. package/dist/rules/coalesce.d.ts +111 -0
  44. package/dist/rules/commands.d.ts +306 -0
  45. package/dist/rules/commit.d.ts +82 -0
  46. package/dist/rules/compaction.d.ts +33 -0
  47. package/dist/rules/context.d.ts +484 -0
  48. package/dist/rules/delegation.d.ts +353 -0
  49. package/dist/rules/due.d.ts +15 -0
  50. package/dist/rules/frame.d.ts +4 -0
  51. package/dist/rules/history.d.ts +34 -0
  52. package/dist/rules/inbound.d.ts +53 -0
  53. package/dist/rules/index.d.ts +13 -0
  54. package/dist/rules/index.js +4 -0
  55. package/dist/rules/index.js.map +1 -0
  56. package/dist/rules/message.d.ts +31 -0
  57. package/dist/rules/outcome.d.ts +45 -0
  58. package/dist/rules/priority.d.ts +52 -0
  59. package/dist/rules/rooms.d.ts +187 -0
  60. package/dist/rules/schema.d.ts +110 -0
  61. package/dist/rules/sync.d.ts +157 -0
  62. package/dist/rules/team.d.ts +119 -0
  63. package/dist/rules/turn.d.ts +129 -0
  64. package/dist/schema.d.ts +154 -0
  65. package/dist/switch.d.ts +53 -0
  66. package/dist/team-model.d.ts +54 -0
  67. package/dist/team.d.ts +56 -0
  68. package/dist/testing.d.ts +6 -0
  69. package/dist/testing.js +20 -0
  70. package/dist/testing.js.map +1 -0
  71. package/dist/toolset-policy.d.ts +2 -0
  72. package/dist/topology.d.ts +49 -0
  73. package/package.json +80 -4
package/dist/host.d.ts ADDED
@@ -0,0 +1,433 @@
1
+ import { type HandoffPackBudgets, type UpdateRoutineAction } from '@byok-sdk/protocol';
2
+ import type { ByokServer, CreateByokServerOptions, DueWake } from '@byok-sdk/server';
3
+ import { HostExecutionCore, type ExecutionServer, type HostOptions, type Intent, type IntentInput, type OutcomeTransaction, type MessageTransaction } from '@byok-sdk/server/execution-core';
4
+ import type { HostJobHandler, Routine } from '@byok-sdk/server/execution-core';
5
+ import { HostLedger, type Conclusion } from '@byok-sdk/server/execution-core';
6
+ import { type ExecutionTemplate, type Json } from '@byok-sdk/server/execution-core';
7
+ import { type CollaborationState } from './model.js';
8
+ import { type ContextTurn, type OutcomeOffer } from './schema.js';
9
+ import { type DelegationCancelResult, type IntentCancelResult, type TurnCancelResult } from './rules/delegation.js';
10
+ import { type MessageDisposition } from './rules/message.js';
11
+ import type { RetentionInput, RetentionResult } from './retention.js';
12
+ import { type DreamingOptions } from './dream.js';
13
+ import { type Autonomy, type WouldDo } from './rules/autonomy.js';
14
+ import { type TeamSnapshot } from './rules/team.js';
15
+ import { type MemberMentions, type Mentions, type RoomMessage } from './rooms.js';
16
+ import type { RoomFields } from '@byok-sdk/protocol';
17
+ import { type HomeServer } from './home-projections.js';
18
+ import { type DeviceTopology, type SwitchWork } from './topology.js';
19
+ import { type SwitchExport } from './migration.js';
20
+ import { type CoalescePolicy } from './coalesce.js';
21
+ import { type ChannelOptions, type Conversation, type InboundClass, type InboundMessage, type PrincipalArg } from './channel.js';
22
+ import type { InboundDisposition } from './rules/inbound.js';
23
+ export interface BotOptions {
24
+ botId: string;
25
+ execution: ExecutionTemplate;
26
+ now?: () => number;
27
+ /** Owner principal id (#552 R2). Default `owner`. Only the human principal with this id passes the owner checks. */
28
+ owner?: string;
29
+ /** Optional Host IM outbox. Push stays off until an owner enables a route. */
30
+ channel?: ChannelOptions;
31
+ /**
32
+ * Host-owned model templates. New Bots stay on the selected template's device. Construction and `setModels` apply each
33
+ * template by model name to every unarchived Bot. A Bot whose model has none keeps its Turns blocked (`Unavailable model`).
34
+ */
35
+ models?: Record<string, ExecutionTemplate>;
36
+ /** Host-owned read-only toolset IDs. Default empty. The Host's local tool server must enforce read-only behavior. */
37
+ readOnlyToolsets?: readonly string[];
38
+ /** Must deduplicate by id. A committed confirmation can be replayed after a crash. */
39
+ connector: (id: string, action: string, draft: Json, signal: AbortSignal) => Promise<Json>;
40
+ /** The Host also enforces this limit when a connector ignores cancellation. */
41
+ connectorTimeoutMs?: number;
42
+ contextMaxBytes?: number;
43
+ contextTurnLimit?: number;
44
+ /**
45
+ * Bytes of the Bot history in a ContextPack. Default: `DEFAULT_HANDOFF_BUDGETS`. Construction checks it against an empty
46
+ * pack only, so a `totalBytes` that cannot hold the digits of the turn count throws `RangeError` at sync.
47
+ */
48
+ handoff?: HandoffPackBudgets;
49
+ /** UTF-8 bound of a whole bot_request or bot_reply instruction. Construction refuses a value below the proven minimum. */
50
+ instructionMaxBytes?: number;
51
+ /** A cancel with no terminal after this time shows `uncertain` (§8.3). */
52
+ cancelGraceMs?: number;
53
+ /** A claimed chain Turn, or a reply check, with no verdict after this time shows `uncertain` (§8.3). */
54
+ uncertainAfterMs?: number;
55
+ /**
56
+ * Merge consecutive user inputs to a busy Bot into one Turn before K4 enqueue (#551). Absent means off.
57
+ * Defaults: windowMs 10_000, maxItems 8, maxBytes 8192. Construction refuses a value outside
58
+ * windowMs 1000 to 60_000, maxItems 2 to 16, or maxBytes 1024 to contextMaxBytes / 4.
59
+ */
60
+ coalesce?: Partial<CoalescePolicy>;
61
+ /**
62
+ * Handlers for the Host's own K4 Host job routines. They share the core with Bot routines,
63
+ * so their rules use the same calendar: a `RoutineSchedule` whose `tz` is the definition time zone.
64
+ */
65
+ hostJobs?: Readonly<Record<string, HostJobHandler>>;
66
+ /**
67
+ * Handlers of the Host's own K4 intents (#882), by name. `enqueueHostIntent` stores the name with the intent.
68
+ * At a `task.complete` terminal, the handler runs synchronously in the terminal transaction with the result document.
69
+ * An intent whose execution has `messageEgress` also needs a handler of the same name in `hostIntentMessages`.
70
+ */
71
+ hostIntents?: Readonly<Record<string, HostIntentHandler>>;
72
+ /**
73
+ * Agent message handlers of Host intents (#1356), by the `hostIntents` name. The handler runs synchronously in the K4
74
+ * message transaction and decides the message. K8 records an accepted message without its body and does not deliver it.
75
+ * A Host intent whose name has no message handler refuses its messages with `binding_mismatch`.
76
+ */
77
+ hostIntentMessages?: Readonly<Record<string, HostIntentMessageHandler>>;
78
+ /**
79
+ * Dreaming (#1475). Absent: on, one dream per Bot per day that had a completed Turn, at 03:00 local time, on the Bot's own model.
80
+ * `false`: off for the whole Host, and open dream routines end. See the README for the cost.
81
+ */
82
+ dreaming?: DreamingOptions | false;
83
+ /** Passed to the K4 core. Default 100. */
84
+ reconcileMs?: number;
85
+ /** Passed to the K4 core: a coalesced hint after a commit that wrote the outbox. */
86
+ onOutbox?: HostOptions['onOutbox'];
87
+ /**
88
+ * External history authority (#739 Q4). Absent: the ContextPack reads this ledger's Turns.
89
+ * Present: before a Bot Turn freezes its offer, the Host reads the Bot's earlier history here, oldest first,
90
+ * in the ContextPack row shape. The rows replace the stored Turns in that ContextPack and are not stored;
91
+ * the Turn keeps only their hash. Cards, questions and rejected actions stay Host state. Room seats read `roomHistory`.
92
+ * A read that throws, returns another shape or is still open after `historyTimeoutMs` leaves the Turn queued, and the timer
93
+ * tries again. A dream (#1475) reads here too, with `turnId` set to the dream's intent key. A failed read skips that day.
94
+ */
95
+ history?: (input: {
96
+ botId: string;
97
+ turnId: string;
98
+ }) => Promise<readonly ContextTurn[]>;
99
+ /**
100
+ * External room history authority (#883). Absent: a seat ContextPack reads the room messages of this ledger.
101
+ * Present: before a seat Turn freezes its offer, the Host reads here the room messages that the seat's Bot can see,
102
+ * oldest first. The authority selects them for that Bot. The rows replace `room.messages` in that ContextPack and are
103
+ * not stored; the seat Turn keeps only their hash. `room.messages` is still written, for the request text and mentions.
104
+ * A read that throws, returns another shape or is still open after `historyTimeoutMs` or at the seat deadline leaves the seat
105
+ * queued, and the timer tries again until the seat deadline.
106
+ */
107
+ roomHistory?: (input: {
108
+ roomId: string;
109
+ botId: string;
110
+ turnId: string;
111
+ }) => Promise<readonly RoomMessage[]>;
112
+ /**
113
+ * How long a `history` or `roomHistory` read may stay open before it counts as failed. The reads run one after another
114
+ * in the Host queue, so this bounds how long a stalled authority holds it. The read is not aborted. Default 10_000.
115
+ */
116
+ historyTimeoutMs?: number;
117
+ /**
118
+ * External team authority (#739 Q4c). Absent: this Host creates the Main Bot and owns its local team.
119
+ * `external`: the constructor creates no Bot. `applyTeam` writes the authority's Bot snapshots, and
120
+ * `setMainBot`, `create_bot`, `update_bot` and `delete_bot` refuse with `external_team`. The mode is stored
121
+ * in the ledger, so a ledger cannot change its mode at a restart.
122
+ */
123
+ team?: 'external';
124
+ /**
125
+ * Host persona mode (#879), only with `team: 'external'`. The Host projects each Bot's Agent home itself. A snapshot
126
+ * Bot carries the Host's `profileRevision`, which becomes its agentRef revision, and K8 queues no persona projection.
127
+ * The Host reports an applied revision with `personaReady`. `retryPersona` refuses with `external_persona`.
128
+ * The ledger stores the mode, so a restart cannot change it.
129
+ */
130
+ persona?: 'external';
131
+ /**
132
+ * External rooms mode (#1321), only with `team: 'external'`. Each team snapshot carries the authority's whole room list,
133
+ * and a room that it no longer lists is archived for good. `createRoom`, `updateRoom`, `setMemberMentions` and the Main Bot's
134
+ * `create_room` and `update_room` refuse with `external_rooms`. The ledger stores the mode, so a restart cannot change it.
135
+ */
136
+ rooms?: 'external';
137
+ /**
138
+ * Outcome offer (#881): allowlists of actions by Turn kind, the IANA time zones of routine actions, and the
139
+ * `confirmable_action` branches. Each field only narrows the default. It applies to Turns frozen after construction.
140
+ */
141
+ outcome?: OutcomeOffer;
142
+ /**
143
+ * The concurrent task limit of each device (#1229 item 1), as the daemon's `maxConcurrentTasks`. Default 8.
144
+ * The Host leaves one slot free for user-source work; submitted work is never cancelled to make room.
145
+ */
146
+ deviceConcurrency?: number;
147
+ }
148
+ /** Synchronous. A throw or a thenable leaves the intent open, and `drain()` rejects. */
149
+ export type HostIntentHandler = (document: unknown, transaction: OutcomeTransaction) => void;
150
+ /** Synchronous. A throw rolls the message transaction back, and a thenable or another result throws. */
151
+ export type HostIntentMessageHandler = (input: AgentMessageInput, transaction: MessageTransaction) => MessageDisposition;
152
+ /** The cancel answer of a Host intent (K8 `IntentCancelResult`). */
153
+ export type HostIntentCancelResult = IntentCancelResult<Conclusion>;
154
+ /** Reply readback port (§3.3). The Host acceptance record stays the body authority. */
155
+ export type MessageServer = {
156
+ tasks: Partial<Pick<ByokServer['tasks'], 'agentMessage'>>;
157
+ };
158
+ export type AgentMessageInput = Parameters<NonNullable<CreateByokServerOptions['agentMessage']>['consume']>[0];
159
+ /** The local K8 Host. Use one instance per ledger tenant. */
160
+ export declare class BotCollaboration {
161
+ readonly server: ExecutionServer & HomeServer & MessageServer & Partial<Pick<ByokServer, 'machines'>>;
162
+ readonly ledger: HostLedger;
163
+ private readonly options;
164
+ readonly core: HostExecutionCore;
165
+ private chain;
166
+ private timer?;
167
+ private closed;
168
+ private readonly now;
169
+ private readonly connectorTimeoutMs;
170
+ private readonly deliveryTimeoutMs;
171
+ private readonly historyTimeoutMs;
172
+ private readonly contextMaxBytes;
173
+ private readonly contextTurnLimit;
174
+ private readonly handoff;
175
+ private readonly dreaming;
176
+ private readonly instructionMaxBytes;
177
+ private readonly deviceConcurrency;
178
+ private readonly timers;
179
+ private readonly coalesce?;
180
+ private readonly offer;
181
+ /** The default principal of the owner APIs: the caller that the Host authenticated as the owner. */
182
+ private readonly owner;
183
+ /** History mode: Turns whose history read failed in this pass. The timer reads them again. */
184
+ private unread;
185
+ private readonly hostIntentHandlers;
186
+ private readonly hostIntentMessageHandlers;
187
+ /** Terminals that could not apply in the current K4 drain, by intent key. K4 also drains from its own timer. */
188
+ private readonly intentFailures;
189
+ /** The last audited reason of each refused key, so a stuck intent adds one audit row and not one per pass. */
190
+ private readonly auditedFailures;
191
+ constructor(server: ExecutionServer & HomeServer & MessageServer & Partial<Pick<ByokServer, 'machines'>>, ledger: HostLedger, options: BotOptions);
192
+ private models;
193
+ /**
194
+ * Replaces the Host's model templates at run time (#1357), for example after a device key changed. Each unarchived Bot takes
195
+ * the template of its model; a Turn frozen before keeps its execution. No profile revision, readiness or persona projection
196
+ * changes. A Bot whose model is missing keeps its Turns blocked until a later call provides it. A template that fails the
197
+ * toolset check, or model names that the outcome schema cannot take, refuse the call and change nothing.
198
+ */
199
+ setModels(models: Readonly<Record<string, ExecutionTemplate>>): Promise<void>;
200
+ snapshot(): CollaborationState;
201
+ /**
202
+ * Every K8 write of this Host, except the switch steps (#975). It refuses while the domain is exported, after the work,
203
+ * so a new command on a frozen or H-owned device still gets its device refusal (`writeLedger` lists the others).
204
+ */
205
+ private write;
206
+ private exclusive;
207
+ /**
208
+ * Returns the id of the Turn that answers this input. With `coalesce`, it is the batch id
209
+ * (the first batched input's id); that Turn appears when the batch seals.
210
+ * Only the owner starts a 1:1 execution (R2).
211
+ */
212
+ input(key: string, request: string, botId?: string, ...by: PrincipalArg): Promise<string>;
213
+ /**
214
+ * Read-only (#1407): the id that `input` returned for this key, from its command record, or `undefined` when the
215
+ * input is not committed. It runs no `process()` and changes no ledger state, so a caller can tell whether an `input`
216
+ * that threw on its drain committed. A record that retention moved is read from its K4 row in a transaction that writes
217
+ * nothing new; once that row expires, the key reads as not committed.
218
+ */
219
+ inputRoot(key: string, botId?: string): string | undefined;
220
+ /**
221
+ * IM entry (#552). Classify one message that the channel adapter translated (docs/host-im-adapter.md §3).
222
+ * The input key is `inboundKey(message)`. Only audit rows record a refused or 1:1 bot message.
223
+ * `id` is the Turn id of `owner_input`, or the room input id of `room_input` and `bot_background`.
224
+ */
225
+ receive(message: InboundMessage): Promise<{
226
+ kind: InboundClass;
227
+ id?: string;
228
+ }>;
229
+ /** Owner opt-in for one canonical conversation. Enabling a replacement revokes its old route. */
230
+ enablePushRoute(conversation: Conversation, channel: string, target: string, ...by: PrincipalArg): Promise<string>;
231
+ revokePushRoute(id: string, ...by: PrincipalArg): Promise<void>;
232
+ resendDelivery(id: string, ...by: PrincipalArg): Promise<string>;
233
+ /** Adapter data can be unverified, so one row is at most 1024 characters. */
234
+ private audit;
235
+ /** R2: refuse an unverified principal. The audit row commits before the error. */
236
+ private verifiedOnly;
237
+ /**
238
+ * The mention entities that may open seats (#1230). A bot mentions nothing (R5). In a group whose `memberMentions`
239
+ * setting is `ignore`, a human who is not the owner mentions nothing either: the message stays room background, with
240
+ * no seat, no device work and no BYOK key. The owner's mention still selects seats, and an omitted principal is the
241
+ * Host's own call. The setting is read here, so it applies to this inbound message only, never to an open root or seat.
242
+ */
243
+ private seatMentions;
244
+ /** R2: only the owner principal acts. An omitted principal is the owner. A given `undefined` is unverified. */
245
+ private ownerOnly;
246
+ private applyOutcome;
247
+ private commitBotOutcome;
248
+ /** The refused terminals of the last K4 drain: one audit row for each new key and reason, and the error of the pass. */
249
+ private reportIntentFailures;
250
+ /**
251
+ * Host intent (#882): the Host's own work in this tenant's K4 FIFO, with Host authority. One transaction enqueues the
252
+ * intent and records its handler name. Its outcome goes to that handler, never to a Bot Turn. An exact replay returns
253
+ * the same intent. On a Bot's agentRef, it shares that Bot's FIFO.
254
+ */
255
+ enqueueHostIntent(input: IntentInput, handler: string): Promise<Intent>;
256
+ /**
257
+ * Owner API (#1320): cancels a Host intent through K4, which records the cancel on the intent row. A settled intent returns
258
+ * `already_settled` and sends nothing, so a replay does not fail. An unsubmitted intent settles as `cancelled` inside the
259
+ * call: no handler runs, and its FIFO moves on. A submitted intent gets an SDK cancel and returns `cancel_pending`; a
260
+ * `task.complete` that arrived before the cancel still runs the handler once. A `handler_failed` intent stays stuck,
261
+ * because K4 applies its terminal again: `failStuckIntent` settles it. Refuses a Bot Turn key and an unknown key.
262
+ */
263
+ cancelHostIntent(key: string, ...by: PrincipalArg): Promise<HostIntentCancelResult>;
264
+ /**
265
+ * Owner API (#882): settles as `failed` an open intent whose K4 terminal K8 refuses with `IntentOutcomeError`, so its FIFO
266
+ * moves on. A fresh K4 drain decides that the intent is stuck, so the call also works right after a restart. One transaction
267
+ * settles it and writes the audit row. The settle runs no handler, and the intent records no terminal; the server task
268
+ * keeps it. The drain before the settle applies the terminal once more, so a `handler_failed` handler runs once inside
269
+ * the call. If that drain applies the outcome, the call refuses with `already_settled`. A Bot Turn records the refusal
270
+ * code as its `settleCode`. A Host intent keeps its `hostIntents` record until K4 compacts it, so an exact replay of
271
+ * `enqueueHostIntent` returns the failed intent. Refuses with `HostIntentError`: `unknown_intent`, `already_settled`, and
272
+ * `not_stuck` for an intent whose terminal K8 did not refuse.
273
+ */
274
+ failStuckIntent(key: string, ...by: PrincipalArg): Promise<void>;
275
+ /** The channel outbox port of a K4 callback. Delivery code reads the committed ledger. */
276
+ private deliverPort;
277
+ /** An owner command in its own ledger transaction. K4 callbacks use `commitCallback` inside the K4 transaction. */
278
+ private commitOwner;
279
+ /** A keyless owner command (#739 6a). Its id is new at each call, because the store keeps no record of it. */
280
+ private commitKeyless;
281
+ private commitCallback;
282
+ /**
283
+ * Install as the server's `agentMessage.consume`. One ledger transaction
284
+ * checks the exact binding and records the first acceptance (§3.3).
285
+ */
286
+ consumeMessage(input: AgentMessageInput): Promise<{
287
+ outcome: 'accepted' | 'refused';
288
+ reasonCode?: string;
289
+ }>;
290
+ private applyMessage;
291
+ /**
292
+ * Owner API ("Cancel", §8.8), from A's delegation chip or from B's `bot_request` Turn. Idempotent (#1405): an earlier cancel
293
+ * gives `cancel_pending` and a verdict `already_settled`, and neither writes or sends. Refuses with `DelegationError`.
294
+ * It rejects when `core.cancel` fails. The cancel fact is already committed, and the timer delivers it later.
295
+ */
296
+ cancelDelegation(id: string, ...by: PrincipalArg): Promise<DelegationCancelResult>;
297
+ /** Owner API ("End", §8.3): close a held reply or an uncertain delegation with `abandoned`. */
298
+ abandonDelegation(id: string, ...by: PrincipalArg): Promise<void>;
299
+ /** A committed cancel fact is delivered after the commit. */
300
+ private settleChain;
301
+ /** The slot admission of one device (#1229 item 1): user-source work may take the last slot, other work may not. */
302
+ private admitsDeviceSlot;
303
+ /**
304
+ * Deliver each committed cancel to its frozen target (§8.8). A crash before
305
+ * `delivered` leaves the fact for the next pass. It never picks a new Turn.
306
+ */
307
+ private deliverCancels;
308
+ /**
309
+ * Host persona mode (#879): the Host applied `revision` of this Bot's profile to its Agent home. The current revision
310
+ * readies the Bot. An older revision changes nothing, and a newer one refuses.
311
+ */
312
+ personaReady(botId: string, revision: string): Promise<void>;
313
+ /** Owner API. Advance the desired revision after a rejected persona delivery. */
314
+ retryPersona(botId: string): Promise<void>;
315
+ /**
316
+ * External team mode (#739 Q4c): apply the authority's team snapshot. The command id is its team revision,
317
+ * so the same revision with the same Bots replays, and other Bots are an identity conflict. A revision that
318
+ * is not newer, and not applied before, refuses with `stale_team` after the process pass.
319
+ */
320
+ applyTeam(snapshot: TeamSnapshot): Promise<void>;
321
+ setMainBot(botId: string, mainBot: boolean): Promise<void>;
322
+ /** The resolved autonomy of one Bot (#1229). A Bot without the field is in observe, the default of a new Bot. */
323
+ autonomy(botId: string): Autonomy;
324
+ /** The would-do rows of one Bot, or of every Bot, oldest first (#1229). The Host UI lists these for the owner. */
325
+ wouldDoRecords(botId?: string): WouldDo[];
326
+ /**
327
+ * The destination of every recorded inbound human message (#1229 item 3), oldest first. It is a projection of the
328
+ * inbound, batch and Turn rows: the ledger holds no second disposition.
329
+ */
330
+ inboundDispositions(): InboundDisposition[];
331
+ /**
332
+ * Owner API (#1229): switch one Bot between observe and auto. Only the owner principal may switch. It applies to
333
+ * outcomes recorded after the switch; a record made in observe is never replayed.
334
+ */
335
+ setBotAutonomy(botId: string, autonomy: Autonomy, ...by: PrincipalArg): Promise<void>;
336
+ /** Any verified human can post in a room. The room message records the principal id; without one it is from `user`. */
337
+ roomInput(key: string, roomId: string, text: string, mentions?: Mentions, ...by: PrincipalArg): Promise<string>;
338
+ /**
339
+ * Owner API (#1230): whether a structured mention from a non-owner human in this group opens seats. Only the owner
340
+ * changes it, and only inbound messages that arrive after it see the new value.
341
+ */
342
+ setMemberMentions(roomId: string, value: MemberMentions, ...by: PrincipalArg): Promise<void>;
343
+ /**
344
+ * Owner API (#1321): create room `roomId` with no model run. The command id comes from the room id, so the same id with
345
+ * the same fields replays, and other fields are an identity conflict.
346
+ */
347
+ createRoom(roomId: string, fields: RoomFields): Promise<void>;
348
+ updateRoom(roomId: string, update: Partial<RoomFields>): Promise<void>;
349
+ answer(id: string, answer: string, ...by: PrincipalArg): Promise<void>;
350
+ /** For IM, call it only from a verified button callback, never for a text command (R2). */
351
+ decide(id: string, decision: 'confirmed' | 'rejected', ...by: PrincipalArg): Promise<void>;
352
+ /** Owner API for the Main Bot's own routines. */
353
+ setRoutineLifecycle(id: string, value: Routine['lifecycle']): Promise<void>;
354
+ /** Owner API (§55c): completes any open Bot routine, an archived owner's too, with this Host's Main Bot authority. */
355
+ endRoutine(id: string): Promise<void>;
356
+ updateRoutine(action: UpdateRoutineAction): Promise<void>;
357
+ private routineRows;
358
+ /** K4 records routine wakes. The `bot-routine` hook writes the routine Turn in the same commit. */
359
+ readonly consume: (wake: DueWake, signal: AbortSignal) => Promise<void>;
360
+ drain(): Promise<void>;
361
+ /**
362
+ * Owner API. Cancels a Turn, an input batch by its id or a member input id, or B's chain Turn through its delegation.
363
+ * Idempotent (#1405): a Turn whose K4 intent already has a cancel gives `cancel_pending`, and an ended Turn
364
+ * `already_settled`; neither writes or calls `core.cancel`.
365
+ */
366
+ cancelTurn(id: string, ...by: PrincipalArg): Promise<TurnCancelResult>;
367
+ private cancelOneTurn;
368
+ /** The L owner record of a device (#957, §4.1). A device with no record is L at revision 0. */
369
+ topology(deviceId: string): DeviceTopology;
370
+ /**
371
+ * Step 1 of a switch away from L (#957, §4.1): durably freezes new work on the device and returns the record read back
372
+ * from the ledger. From the commit on, each entry that can create execution for the device refuses with
373
+ * `DeviceSwitchingError`, and the sync holds the device's Turns. Raises the revision.
374
+ */
375
+ freezeForSwitch(deviceId: string, expectedRevision: number): Promise<DeviceTopology>;
376
+ /**
377
+ * Step 2: the device's open work. With `cancel`, cancels every open intent and every open Turn and input batch, then runs a
378
+ * pass. Returns the work still open: a tried intent stays open until the reconciler reads its terminal. Waits for nothing.
379
+ */
380
+ drainForSwitch(deviceId: string, { cancel }?: {
381
+ cancel?: boolean;
382
+ }): Promise<SwitchWork>;
383
+ /**
384
+ * Step 3 (#975): seals the domain's whole state into a switch export, after each of its devices is frozen at the given
385
+ * revision and drained. The export must name every device of a live Bot. From the export on, this Host writes nothing to
386
+ * the ledger, also after a restart, so the commit away can check that the ledger still holds what was exported. Refuses
387
+ * Agent memory, a pending projection (flush them first), and a pending Host job, which K4 would run while the export
388
+ * waits for its commit.
389
+ */
390
+ exportForSwitch(devices: {
391
+ deviceId: string;
392
+ expectedRevision: number;
393
+ }[], exportedAt?: number): Promise<SwitchExport>;
394
+ /**
395
+ * Step 5, after the new owner imported and verified the export: L records that the new owner owns the whole domain. Every
396
+ * device of the export moves to H in one transaction, on its frozen revision, only when none has open work and `receipt`
397
+ * is the digest of this Host's export. The ledger is sealed again under the export's header and must give the same
398
+ * digest. `deviceId` and `expectedRevision` name one device of the export, whose record is returned. Every entry then
399
+ * refuses those devices with `DeviceModeError`, also after a restart. The export stays, so this Host keeps writing nothing.
400
+ */
401
+ commitSwitch(deviceId: string, expectedRevision: number, receipt: string): Promise<DeviceTopology>;
402
+ /**
403
+ * A failed export or check: clears the freeze on the frozen revision, so L owns the device again and held Turns run. An
404
+ * abort of a device of the export ends the export, and the new owner discards its import. After the commit every device
405
+ * of the export is owned by H, so none aborts.
406
+ */
407
+ abortSwitch(deviceId: string, expectedRevision: number): Promise<DeviceTopology>;
408
+ /**
409
+ * Explicit retention (#798). Moves every row of each acknowledged settled root out of the state, and retires its ids.
410
+ * A root that is still in use throws `RetentionRefused`, and nothing changes. Never runs on its own.
411
+ */
412
+ retain(input: RetentionInput): Promise<RetentionResult>;
413
+ recover(): Promise<void>;
414
+ private sync;
415
+ /** Example reconcile loop (§3.10). K4 arms no scan after a settled intent, so the Host checks replies itself. */
416
+ private flushReplies;
417
+ private callConnector;
418
+ private flushCards;
419
+ private flushDeliveries;
420
+ /** One sync transaction. In history mode, phase 1 reads the history first, outside the transaction. */
421
+ private syncWithHistory;
422
+ private readHistory;
423
+ /** A failed pass still re-arms the timer, so other timer work keeps its times. K4 retries a failed wake call itself. */
424
+ private process;
425
+ /**
426
+ * A failed K4 drain does not stop the rest of the pass, so deliveries and reply checks still move their due times.
427
+ * The pass does not repeat after it, and it rethrows the first drain error for the caller and the SDK hook.
428
+ */
429
+ private pass;
430
+ private armTimer;
431
+ private refreshDevices;
432
+ close(): Promise<void>;
433
+ }
@@ -0,0 +1,17 @@
1
+ import { type CollaborationState } from './model.js';
2
+ import type { Json } from './rules/turn.js';
3
+ import { type InboundDisposition, type InboundState } from './rules/inbound.js';
4
+ /** The rows that the pure rule reads. A round with no seat Turn is still the round root that answers its input. */
5
+ export declare function inboundState(state: CollaborationState): InboundState;
6
+ /** The Host UI read (#1229): every recorded inbound human message and its current destination, oldest first. */
7
+ export declare function inboundDispositionsOf(state: CollaborationState): InboundDisposition[];
8
+ /**
9
+ * One projection id per destination transition. The id names the destination, so a projection value never changes and
10
+ * the K4 outbox can hold every transition without an identity conflict.
11
+ */
12
+ export declare function inboundProjection(disposition: InboundDisposition): {
13
+ id: string;
14
+ value: Json;
15
+ };
16
+ /** Publishes the current destination of each message. `project` is idempotent for an unchanged destination. */
17
+ export declare function projectInboundDispositions(state: CollaborationState, emit: (id: string, value: Json) => void): void;
@@ -0,0 +1,5 @@
1
+ export { BotCollaboration } from './host.js';
2
+ export { botCompactVeto } from './compaction.js';
3
+ export type { AgentMessageInput, BotOptions, HostIntentCancelResult, HostIntentHandler, HostIntentMessageHandler, MessageServer } from './host.js';
4
+ export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot, type TeamModeCode, type TeamSnapshot, type TeamSnapshotBot, type TeamSnapshotRoom } from './rules/team.js';
5
+ export { createBotPersonaProjection } from './persona.js';
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ import { botCompactVeto, checkTopology, checkSwitchRecords, dreamPolicy, checkDreamInstruction, deviceRefusal, admitBot, refuseExported, recordDream, writeLedger, echoCandidates, acceptDeliveryEcho, cleanReplyTokens, rememberInbound, rememberFilteredInbound, routeTerminal, runHostIntentHandler, outcomeFailure, IntentOutcomeError, botOutcomePorts, intentRows, admitDevice, promoteStaged, queueDelivery, commitInLedger, resendUnknown, revokePush, enablePush, admitUserInput, commitInRows, inboundDispositionsOf, deviceTopology, switchStep, switchWork, DeviceModeError, switchDrained, SwitchExportError, sealSwitchExport, switchContent, sealLedger, retainInLedger, recoverDelivery, syncHead, reconcileDreamRoutines, advanceRoomsAndTurns, syncTurnInLedger, syncDreams, botDeviceRefusal, settleDelegations, syncTail, callCardsInLedger, readbackDelivery, deliveryRoute, refuseRoute, startDelivery, settleDelivery, unknownDelivery, dreamReads, homeSent, observeDevices } from './chunk-5J5SOWWI.js';
2
+ export { botCompactVeto } from './chunk-5J5SOWWI.js';
3
+ import { stateOf, verified, routineCalendar, BOT_DREAM, BOT_ROUTINE, routineTurn, applyModels, classifyInbound, inboundKey, isOwner, applyManagement, updateBot, writeSnapshotBot, owned, endable, updateDefinition, ownerRoutineUpdate, botRoutines, homeHead, homeRequests, checkHomeReadback, planHomeRetry, homeEnqueued, applyHomeTerminal, failHomeFlush } from './chunk-XTZUCECQ.js';
4
+ import { DEVICE_CONCURRENCY, admitDeviceSlot } from './chunk-33YA66U7.js';
5
+ import { admitBotToolsets, HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS, DEFAULT_HANDOFF_BUDGETS, coalescePolicy, outcomeOffer, outcomeSchema, DEFAULT_INSTRUCTION_MAX_BYTES, minimumInstructionBytes, SYSTEM_PROMPT, REPLY_UNCERTAIN_AFTER_MS, DEFAULT_CANCEL_GRACE_MS, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-ZUFZCROA.js';
6
+ export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-ZUFZCROA.js';
7
+ import { randomUUID } from 'crypto';
8
+ import { buildHandoffPack, ToolsetIdSchema } from '@byok-sdk/protocol';
9
+ import { hash, time, HostExecutionCore, isOccurrenceIntentKey, enqueue, settle, project, setLifecycle, canonical } from '@byok-sdk/server/execution-core';
10
+ import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';
11
+
12
+ function ownReadOnlyToolsets(ids=[]){if(!Array.isArray(ids))throw new Error("readOnlyToolsets must be an array of logical toolset IDs");if(ids.length>64||new Set(ids).size!==ids.length)throw new Error("Invalid read-only toolset policy");for(const id of ids)ToolsetIdSchema.parse(id);return Object.freeze([...ids])}async function flushHomes(server,ledger,now){const busy=botId=>Object.values(ledger.snapshot().intents).some(intent=>!intent.conclusion&&intent.execution.payload.agentRef.agentId===botId);const operation=(s,sequence)=>stateOf(s.application).team.homeOperations.find(o=>o.sequence===sequence);const snapshot=stateOf(ledger.snapshot().application),team=snapshot.team;for(const pending of team.homeOperations.filter(o=>o.status==="pending").sort((a,b)=>a.sequence-b.sequence)){const op=homeHead(team,pending.sequence,busy);if(!op)continue;if(deviceRefusal(snapshot,op.request.deviceId)&&!homeSent(op))continue;try{if(!server.enqueueAgentHomeProjection||!server.readAgentHomeProjection)throw new Error("Home projection API required");let terminal;for(const candidate of homeRequests(op)){terminal=checkHomeReadback(candidate,await server.readAgentHomeProjection(candidate.deviceId,candidate.payload.agentRef,candidate.payload.requestId));if(terminal)break}if(!terminal){const request=ledger.transaction(s=>{if(deviceRefusal(stateOf(s.application),op.request.deviceId))return void 0;const row=operation(s,op.sequence);row.sent=true;return planHomeRetry(row,now())});if(!request)continue;await server.enqueueAgentHomeProjection(request);ledger.transaction(s=>homeEnqueued(operation(s,op.sequence),now()));continue}const settled=terminal;ledger.transaction(s=>applyHomeTerminal(stateOf(s.application),operation(s,op.sequence),settled,(id,value)=>project(s,id,value)));}catch(error){ledger.transaction(s=>failHomeFlush(operation(s,op.sequence),error));}}}function hostIntent(state,key){return state.hostIntents&&Object.hasOwn(state.hostIntents,key)?state.hostIntents[key]:void 0}function openIntent(intents,key){const intent=intents[hash(key)];if(!intent)throw new HostIntentError(key,"unknown_intent",`Unknown intent: ${key}`);if(intent.conclusion)throw new HostIntentError(key,"already_settled",`Intent already settled: ${key}`);return intent}function bounded(read,ms){let timer;const late=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("History read timed out")),Math.max(0,ms));});return Promise.race([read,late]).finally(()=>clearTimeout(timer))}function awaitsOffer(ledger,state,turn){const bot=state.team.bots[turn.botId];return !turn.conclusion&&!turn.held&&!ledger.intents[hash(turn.id)]&&turn.status!=="failed"&&!!bot&&!inactive(bot)&&bot.readyRevision===bot.revision}function dispatchRow(state,row){const execution=state.executions[row.taskId];return {id:row.id,agent:row.agent,sequence:row.sequence,phase:row.phase,attempts:row.attempts,source:row.source,deviceId:row.execution.deviceId,occupies:row.phase==="inflight"&&(execution?.submission==="delivered"||execution?.attempt!==void 0||execution?.started===true)}}function admitCommand(state,command){for(const botId of commandBots(state,command))admitBot(state,botId);}function valueOf(result){if(result.disposition.outcome!=="accepted")throw new Error("Unexpected refused command");return result.disposition.value}function turnOf(result){if(result.disposition.outcome!=="accepted"||typeof result.disposition.value!=="string")throw new Error("Input command has no Turn id");return result.disposition.value}var BotCollaboration=class{constructor(server,ledger,options){this.server=server;this.ledger=ledger;this.options=options;if(!options.botId||options.execution.payload.agentRef.agentId!==options.botId)throw new Error("Select this Bot Agent");if(ledger.compactVeto!==botCompactVeto)throw new Error("Open the Host ledger with { compactVeto: botCompactVeto }");options=this.options={...options,execution:structuredClone(options.execution),...options.models===void 0?{}:{models:structuredClone(options.models)},readOnlyToolsets:ownReadOnlyToolsets(options.readOnlyToolsets)};admitBotToolsets(options.execution,options.readOnlyToolsets);for(const model of Object.values(this.models()))admitBotToolsets(model,options.readOnlyToolsets);const persisted=ledger.snapshot(),team=stateOf(persisted.application).team;checkTopology(stateOf(persisted.application));checkSwitchRecords(stateOf(persisted.application));if(options.team==="external"?!team.external&&Object.keys(team.bots).length:team.external){throw new Error(`This ledger has ${team.external?"an external":"a local"} team`)}if(options.persona!==void 0&&(options.persona!=="external"||options.team!=="external")){throw new Error("The Host persona mode needs team: 'external'")}if(team.external&&!!team.external.persona!==(options.persona==="external")){throw new Error(`This ledger has ${team.external.persona?"Host":"K8"} persona projections`)}if(options.rooms!==void 0&&(options.rooms!=="external"||options.team!=="external")){throw new Error("The external rooms mode needs team: 'external'")}if(team.external&&!!team.external.rooms!==(options.rooms==="external")){throw new Error(`This ledger has ${team.external.rooms?"external":"local"} rooms`)}for(const intent of Object.values(persisted.intents)){if(intent.conclusion)continue;admitBotToolsets(intent.execution,options.readOnlyToolsets);const execution=persisted.executions[intent.taskId];if(execution)admitBotToolsets(execution.input,options.readOnlyToolsets);}this.hostIntentHandlers=new Map(Object.entries(options.hostIntents??{}));this.hostIntentMessageHandlers=new Map(Object.entries(options.hostIntentMessages??{}));for(const name of this.hostIntentMessageHandlers.keys()){if(!this.hostIntentHandlers.has(name))throw new Error(`A Host intent message handler needs the Host intent handler ${name}`)}for(const[key,{handler}]of Object.entries(stateOf(persisted.application).hostIntents??{})){const intent=persisted.intents[hash(key)];if(intent&&intent.conclusion===void 0&&!this.hostIntentHandlers.has(handler)){throw new Error(`An open Host intent needs the handler ${handler}`)}if(intent&&intent.conclusion===void 0&&intent.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`An open Host intent needs the message handler ${handler}`)}}this.owner={id:options.owner??"owner",kind:"human"};if(!verified(this.owner))throw new Error("Invalid owner principal");this.now=()=>time((options.now??Date.now)());this.connectorTimeoutMs=time(options.connectorTimeoutMs??3e4);if(this.connectorTimeoutMs<1||this.connectorTimeoutMs>2147483647)throw new Error("Invalid connector timeout");this.deliveryTimeoutMs=time(options.channel?.sendTimeoutMs??15e3);if(this.deliveryTimeoutMs<1||this.deliveryTimeoutMs>2147483647)throw new Error("Invalid delivery timeout");this.historyTimeoutMs=time(options.historyTimeoutMs??1e4);if(this.historyTimeoutMs<1||this.historyTimeoutMs>2147483647)throw new Error("Invalid history timeout");this.contextMaxBytes=time(options.contextMaxBytes??HISTORY_MAX_BYTES);this.contextTurnLimit=time(options.contextTurnLimit??HISTORY_MAX_ITEMS);if(this.contextMaxBytes<1||this.contextTurnLimit<1)throw new Error("Invalid ContextPack limits");this.handoff=options.handoff??DEFAULT_HANDOFF_BUDGETS;buildHandoffPack([],this.handoff);if(options.coalesce)this.coalesce=coalescePolicy(options.coalesce,this.contextMaxBytes);this.offer=outcomeOffer(options.outcome??{});outcomeSchema(options.botId,stateOf({}),void 0,Object.keys(this.models()),[],this.offer);this.instructionMaxBytes=time(options.instructionMaxBytes??DEFAULT_INSTRUCTION_MAX_BYTES);const minimum=minimumInstructionBytes(SYSTEM_PROMPT);if(this.instructionMaxBytes<minimum)throw new Error(`instructionMaxBytes must be at least ${minimum}`);this.dreaming=dreamPolicy(options.dreaming);if(this.dreaming)checkDreamInstruction(this.instructionMaxBytes);this.timers={cancelGraceMs:time(options.cancelGraceMs??DEFAULT_CANCEL_GRACE_MS),uncertainAfterMs:time(options.uncertainAfterMs??REPLY_UNCERTAIN_AFTER_MS)};if(this.timers.cancelGraceMs<1||this.timers.uncertainAfterMs<1)throw new Error("Invalid delegation timers");this.deviceConcurrency=time(options.deviceConcurrency??DEVICE_CONCURRENCY);if(this.deviceConcurrency<1)throw new Error("Invalid device concurrency");this.core=new HostExecutionCore(server,ledger,{now:this.now,reconcileMs:options.reconcileMs??100,nextOccurrence:routineCalendar,hostJobExecution:"fail",executionRoutines:"refuse",...options.hostJobs?{hostJobs:options.hostJobs}:{},...options.onOutbox?{onOutbox:options.onOutbox}:{},occurrenceHooks:{[BOT_ROUTINE]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);this.commitCallback(state,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state,run)});},[BOT_DREAM]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);recordDream(state,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),admitSubmit:(intent,state)=>!deviceRefusal(stateOf(state.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state=stateOf(s.application);if(options.team==="external"){state.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state.team.bots[options.botId]??={id:options.botId,name:"Main Bot",role:"Team owner",persona:"",model:Object.keys(this.models())[0],mainBot:true,archived:false,autonomy:DEFAULT_AUTONOMY,revision:options.execution.payload.agentRef.profileRevision,readyRevision:options.execution.payload.agentRef.profileRevision,execution:structuredClone(options.execution)};}applyModels(state,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;now;connectorTimeoutMs;deliveryTimeoutMs;historyTimeoutMs;contextMaxBytes;contextTurnLimit;handoff;dreaming;instructionMaxBytes;deviceConcurrency;timers;coalesce;offer;owner;unread=new Set;hostIntentHandlers;hostIntentMessageHandlers;intentFailures=new Map;auditedFailures=new Map;models(){return this.options.models??{default:this.options.execution}}setModels(models){return this.exclusive(async()=>{const next=structuredClone(models);outcomeSchema(this.options.botId,stateOf({}),void 0,Object.keys(next),[],this.offer);this.write(s=>applyModels(stateOf(s.application),next,this.options.readOnlyToolsets??[]));this.options.models=next;await this.process();})}snapshot(){return stateOf(this.ledger.snapshot().application)}write(apply){return writeLedger(this.ledger,apply)}exclusive(work){if(this.closed)return Promise.reject(new Error("Bot Host is closed"));const next=this.chain.then(work);this.chain=next.catch(()=>{});return next}input(key,request,botId=this.options.botId,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"input",botId);const result=this.commitOwner(hash(["input",botId,key]),{kind:"input",botId,key,request,sender:principal.id});await this.process();return turnOf(result)})}inputRoot(key,botId=this.options.botId){const id=hash(["input",botId,key]),commands=stateOf(this.ledger.snapshot().application).commands;const record=commands&&Object.hasOwn(commands,id)?commands[id]:this.ledger.transaction((_,rows)=>rows.get("commands",id));return record&&turnOf(record.result)}async receive(message){if(this.closed)throw new Error("Bot Host is closed");const kind=classifyInbound(message,this.owner.id,this.options.channel?.self),{channel,conversation,platformMessageId,sender}=message;if(kind==="echo"){this.write(s=>{const state=stateOf(s.application),matches=echoCandidates(state,message);if(matches.length!==1||!acceptDeliveryEcho(matches[0],platformMessageId))state.audit.push(`Delivery unmatched_echo: ${channel} ${platformMessageId}`.slice(0,1024));cleanReplyTokens(s,state,this.now());});return {kind}}if(kind==="owner_input"||kind==="room_input")return this.exclusive(async()=>{const principal=kind==="owner_input"?this.ownerOnly([sender],"input",conversation.id):this.verifiedOnly(sender,"roomInput",conversation.id);const key=inboundKey(message);const command=kind==="owner_input"?{kind:"receive",inbound:kind,key,botId:conversation.id,request:message.text,sender:principal.id}:{kind:"receive",inbound:kind,key,roomId:conversation.id,text:message.text,mentions:this.seatMentions(conversation.id,principal,message.mentions),from:principal.id};const result=this.commitOwner(hash(["receive",key]),command,(_s,state)=>({remember:root=>rememberInbound(state,message,root)}));await this.process();return {kind,id:turnOf(result)}});if(kind==="bot_background"){return {kind,id:await this.roomInput(inboundKey(message),conversation.id,message.text,message.mentions,sender)}}const who=verified(sender)?` ${sender.kind}:${sender.id}`:"";const filtered=kind==="unverified_sender"||kind==="not_owner"?kind:void 0;await this.exclusive(async()=>this.write(s=>{const state=stateOf(s.application);if(filtered)rememberFilteredInbound(state,message,filtered);state.audit.push(`Inbound ${kind}: ${channel} ${conversation.kind}:${conversation.id} ${platformMessageId}${who}`.slice(0,1024));}));return {kind}}enablePushRoute(conversation,channel,target,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"enablePushRoute",conversation.id);if(!this.options.channel)throw new Error("Channel is not configured");return valueOf(this.commitKeyless({kind:"enable_push_route",conversation,channel,target,owner:principal.id}))})}revokePushRoute(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"revokePushRoute",id);this.commitKeyless({kind:"revoke_push_route",routeId:id});await this.process();})}resendDelivery(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"resendDelivery",id);if(!this.options.channel)throw new Error("Channel is not configured");const next=valueOf(this.commitKeyless({kind:"resend_delivery",deliveryId:id}));await this.process();return next})}audit(line){this.write(s=>{stateOf(s.application).audit.push(line.slice(0,1024));});}verifiedOnly(principal,action,target){if(verified(principal))return principal;this.audit(`Action refused unverified_sender: ${action} ${target}`);throw new Error(`unverified_sender: ${action} needs a verified principal`)}seatMentions(roomId,principal,mentions){if(!principal||isOwner(principal,this.owner.id))return mentions;if(principal.kind==="bot")return [];const room=this.snapshot().team.rooms[roomId];return room&&memberMentions(room)==="ignore"?[]:mentions}ownerOnly(by,action,target){const principal=this.verifiedOnly(by.length?by[0]:this.owner,action,target);if(isOwner(principal,this.owner.id))return principal;this.audit(`Action refused not_owner: ${action} ${target} ${principal.kind}:${principal.id}`);throw new Error(`not_owner: ${action} needs the owner principal`)}applyOutcome(document,tx){const state=stateOf(tx.application),taskId=tx.intent.taskId,key=tx.intent.key;refuseExported(state);try{const route=routeTerminal(state,key,hostIntent(state,key)?.handler);if(route.kind==="host_intent")runHostIntentHandler(key,route.handler,this.hostIntentHandlers.get(route.handler)?.bind(null,document,tx));else if(route.kind==="bot_turn"){try{this.commitBotOutcome(state,key,taskId,document,tx);}catch(cause){throw outcomeFailure(key,cause)}}}catch(error){if(error instanceof IntentOutcomeError)this.intentFailures.set(key,error);throw error}}commitBotOutcome(state,key,taskId,document,tx){this.commitCallback(state,tx.rows,taskId,{kind:"outcome",turnId:key,taskId,document},{publish:tx.publish,...this.deliverPort(state,taskId),outcome:{committed:{intent:key2=>intentRows(this.ledger.snapshot()).intent(key2)},...botOutcomePorts({taskId,routines:tx.routines,roomPosts:!!this.options.roomHistory,manage:(turn,outcome,managed)=>applyManagement(state,turn.botId,taskId,outcome,this.models(),managed,this.options.readOnlyToolsets)})}});}reportIntentFailures(){const failures=[...this.intentFailures.values()],fresh=failures.filter(f=>this.auditedFailures.get(f.key)!==f.message);if(fresh.length){this.write(s=>{const state=stateOf(s.application);for(const f of fresh)state.audit.push(`Intent outcome refused ${f.code}: ${f.key} ${f.message}`.slice(0,1024));});for(const f of fresh)this.auditedFailures.set(f.key,f.message);}return failures[0]}enqueueHostIntent(input,handler){return this.exclusive(async()=>{if(!this.hostIntentHandlers.has(handler))throw new Error(`Unknown Host intent handler: ${handler}`);if(isOccurrenceIntentKey(input.key))throw new Error("Host intent identity conflict: the key is an occurrence");if(input.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`Host intent handler ${handler} has no message handler`)}admitBotToolsets(input.execution,this.options.readOnlyToolsets);this.write(s=>{const state=stateOf(s.application),owner=hostIntent(state,input.key);if(Object.hasOwn(state.turns,input.key))throw new Error("Host intent identity conflict: the key is a Bot Turn");if(owner?owner.handler!==handler:s.intents[hash(input.key)])throw new Error("Host intent identity conflict");if(!owner)admitDevice(state,input.execution.deviceId);enqueue(s,this.ledger.tenant,input);Object.defineProperty(state.hostIntents??={},input.key,{value:{handler},enumerable:true,writable:true,configurable:true});});await this.process();return this.core.intent(input.key)})}cancelHostIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntent",key);const snapshot=this.ledger.snapshot(),state=stateOf(snapshot.application),intent=snapshot.intents[hash(key)];const settled=hostIntentCancelAnswer(key,Object.hasOwn(state.turns,key),hostIntent(state,key)&&intent);if(settled)return {key,...settled};await this.core.cancel(key);await this.process();if(intent.phase==="inflight")return {key,result:"cancel_pending"};return {key,result:"cancelled",conclusion:this.core.intent(key).conclusion}})}failStuckIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"failStuckIntent",key);openIntent(this.ledger.snapshot().intents,key);this.intentFailures.clear();const drained=await this.core.drain().then(()=>void 0,error=>({error}));const refused=this.intentFailures.get(key);this.write(s=>{const intent=openIntent(s.intents,key);if(!refused)throw drained?drained.error:new HostIntentError(key,"not_stuck",`Intent is not stuck: ${key} has no refused terminal`);settle(s,intent,"failed");if(refused.code==="outcome_failed")stateOf(s.application).turns[key].settleCode=refused.code;stateOf(s.application).audit.push(`Intent failed by owner ${refused.code}: ${key} ${refused.message}`.slice(0,1024));});this.intentFailures.delete(key);this.auditedFailures.delete(key);await this.process();})}deliverPort(state,taskId){if(!this.options.channel)return {};return {deliver:(turn,key,text,staged)=>queueDelivery(this.ledger.snapshot(),state,turn,taskId,key,text,this.now(),staged)?.id,promote:id=>promoteStaged(state,id)}}commitOwner(commandId,command,extra){return commitInLedger(this.ledger,{scope:this.ledger.tenant,commandId,command},s=>{const state=stateOf(s.application);return {now:this.now,admit:next=>admitCommand(state,next),publish:(key,value)=>project(s,key,value),intents:intentRows(s),admitInput:fields=>admitUserInput(state,fields,this.coalesce,this.now()),updatePersona:(botId,persona)=>updateBot(state,{botId,persona},this.models(),this.options.readOnlyToolsets),routes:{enable:(conversation,channel,target,owner)=>enablePush(state,conversation,channel,target,owner,this.now()).id,revoke:routeId=>revokePush(state,routeId,this.now()),resend:deliveryId=>resendUnknown(state,deliveryId,this.now()).id},...extra?.(s,state)}})}commitKeyless(command){return this.commitOwner(randomUUID(),command)}commitCallback(state,rows,commandId,command,ports){return commitInRows(state,this.ledger.tenant,{scope:this.ledger.tenant,commandId,command},rows,{now:this.now,...ports})}async consumeMessage(input){if(this.closed)throw new Error("Bot Host is closed");refuseExported(this.snapshot());const result=await this.core.consumeMessage(input);if(result.outcome==="accepted")queueMicrotask(()=>{if(!this.closed)void this.drain().catch(()=>{});});return result}applyMessage(input,tx){const state=stateOf(tx.application);refuseExported(state);const name=hostIntent(state,tx.intent.key)?.handler,handler=name===void 0?void 0:this.hostIntentMessageHandlers.get(name);let disposition;try{({disposition}=this.commitCallback(state,tx.rows,`${input.taskId}:${input.payload.messageId}`,{kind:"message",turnId:tx.intent.key,message:{taskId:input.taskId,payload:input.payload}},{publish:tx.publish,...this.deliverPort(state,input.taskId),...handler?{hostMessage:()=>hostMessageDisposition(handler(input,tx))}:{}}));}catch(cause){if(cause instanceof CommitConflict&&cause.code==="identity_conflict")return {outcome:"refused",reasonCode:"message_conflict"};throw cause}return disposition.outcome==="accepted"?{outcome:"accepted"}:{outcome:"refused",reasonCode:disposition.reasonCode}}cancelDelegation(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelDelegation",id);const settled=delegationCancelAnswer(this.snapshot(),id);if(settled)return {delegationId:id,...settled};await this.settleChain(this.commitKeyless({kind:"cancel_delegation",delegationId:id}));return {delegationId:id,result:"cancelled"}})}abandonDelegation(id,...by){return this.exclusive(()=>{this.ownerOnly(by,"abandonDelegation",id);return this.settleChain(this.commitKeyless({kind:"abandon_delegation",delegationId:id}))})}async settleChain(result){if(valueOf(result).deliver)await this.deliverCancels();await this.process();}admitsDeviceSlot(intent,state){const rows=Object.values(state.intents).map(row=>dispatchRow(state,row));return admitDeviceSlot(rows.find(row=>row.id===intent.id)??dispatchRow(state,intent),rows,this.deviceConcurrency)}async deliverCancels(){for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;await this.core.cancel(d.cancel.targetTurnId);this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});}}async personaReady(botId,revision){await this.exclusive(async()=>{this.commitKeyless({kind:"persona_ready",botId,revision});await this.process();});}async retryPersona(botId){await this.exclusive(async()=>{this.commitKeyless({kind:"retry_persona",botId});await this.process();});}async applyTeam(snapshot){await this.exclusive(async()=>{const valid=teamSnapshot(snapshot);const{disposition}=this.commitOwner(hash(["team",valid.revision]),{kind:"team_snapshot",snapshot:valid},(_s,state)=>({teamBot:row=>writeSnapshotBot(state,row,this.models(),this.options.readOnlyToolsets)}));await this.process();if(disposition.outcome==="refused")throw new TeamModeError("stale_team",disposition.reason??"stale_team")});}async setMainBot(botId,mainBot){await this.exclusive(async()=>{this.commitKeyless({kind:"set_main_bot",botId,mainBot});await this.process();});}autonomy(botId){const bots=this.snapshot().team.bots,bot=Object.hasOwn(bots,botId)?bots[botId]:void 0;if(!bot)throw new Error("Bot not found");return autonomyOf(bot)}wouldDoRecords(botId){return wouldDoRows(this.snapshot(),botId)}inboundDispositions(){return inboundDispositionsOf(this.snapshot())}setBotAutonomy(botId,autonomy,...by){return this.exclusive(async()=>{this.ownerOnly(by,"setBotAutonomy",botId);if(autonomy!=="observe"&&autonomy!=="auto")throw new Error("Invalid autonomy");this.commitKeyless({kind:"set_autonomy",botId,autonomy});await this.process();})}async roomInput(key,roomId,text,mentions=[],...by){let id;await this.exclusive(async()=>{const principal=by.length?this.verifiedOnly(by[0],"roomInput",roomId):void 0;const called=this.seatMentions(roomId,principal,mentions);const result=this.commitOwner(hash(["room_input",roomId,key]),{kind:"room_input",key,roomId,text,mentions:called,...principal?{from:principal.id}:{}});id=turnOf(result);await this.process();});return id}async setMemberMentions(roomId,value,...by){await this.exclusive(async()=>{this.ownerOnly(by,"setMemberMentions",roomId);this.commitKeyless({kind:"set_room_member_mentions",roomId,memberMentions:value});await this.process();});}async createRoom(roomId,fields){await this.exclusive(async()=>{this.commitOwner(hash(["create_room",roomId]),{kind:"create_room",roomId,fields});await this.process();});}async updateRoom(roomId,update){await this.exclusive(async()=>{this.commitKeyless({kind:"update_room",roomId,update});await this.process();});}async answer(id,answer,...by){await this.exclusive(async()=>{this.ownerOnly(by,"answer",id);this.commitOwner(hash(["answer",id]),{kind:"answer",questionId:id,answer});await this.process();});}async decide(id,decision,...by){await this.exclusive(async()=>{this.ownerOnly(by,"decide",id);let error;try{const{disposition}=this.commitOwner(hash(["decide",id]),{kind:"decide",cardId:id,decision});if(disposition.outcome==="refused")error=disposition.reason;}catch(cause){if(!(cause instanceof CommitConflict)||cause.code!=="identity_conflict")throw cause;error=cause.message;}await this.process();if(error)throw new Error(error)});}async setRoutineLifecycle(id,value){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.lifecycle(owned(this.routineRows(),this.options.botId,id).definition.id,value);}finally{await this.process();}});}async endRoutine(id){await this.exclusive(async()=>{try{this.commitOwner(randomUUID(),{kind:"end_routine",botId:this.options.botId,routineId:id},s=>({routines:{end:routineId=>setLifecycle(s,endable(Object.values(s.routines),routineId).definition.id,"completed",this.now(),routineCalendar)}}));}finally{await this.process();}});}async updateRoutine(action){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.updateRoutine(updateDefinition(this.routineRows(),this.options.botId,ownerRoutineUpdate(action)));}finally{await this.process();}});}routineRows(){return Object.values(this.ledger.snapshot().routines)}consume=(wake,signal)=>this.exclusive(async()=>{signal.throwIfAborted();this.write((s,rows)=>{this.sync(s,rows);});try{await this.core.consume(wake,signal);}finally{await this.process();}});drain(){return this.exclusive(()=>this.process())}cancelTurn(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelTurn",id);return this.cancelOneTurn(id)})}async cancelOneTurn(id){const snapshot=this.ledger.snapshot(),settled=turnCancelAnswer(stateOf(snapshot.application),intentRows(snapshot),id);if(settled)return {turnId:id,...settled};const result=this.commitKeyless({kind:"cancel_turn",turnId:id});const value=valueOf(result);if("deliver"in value)await this.settleChain(result);else {if(value.admitted)await this.core.cancel(value.target);await this.process();}return {turnId:id,result:"cancelled"}}topology(deviceId){return deviceTopology(this.snapshot(),deviceId)}freezeForSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.write(s=>switchStep(s,deviceId,expectedRevision,"freeze"));return this.topology(deviceId)})}drainForSwitch(deviceId,{cancel=false}={}){return this.exclusive(async()=>{const work=this.write(s=>{if(!deviceTopology(stateOf(s.application),deviceId).switching)throw new Error(`Device ${deviceId} is not switching`);const open=switchWork(s,deviceId);if(cancel)for(const key of open.intents)s.intents[hash(key)].cancelReason??="cancelled";return open});if(cancel){for(const id of [...work.batches,...work.turns])await this.cancelOneTurn(id);await this.process();}return switchWork(this.ledger.snapshot(),deviceId)})}exportForSwitch(devices,exportedAt=this.now()){return this.exclusive(async()=>{const state=this.snapshot();refuseExported(state);for(const{deviceId,expectedRevision}of devices){const row=deviceTopology(state,deviceId);if(row.revision!==expectedRevision){throw new CommitConflict("stale_revision",`Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`)}if(row.mode!=="L")throw new DeviceModeError(deviceId,row.mode,row.revision);if(!row.switching)throw new Error(`Device ${deviceId} is not switching`);if(!switchDrained(switchWork(this.ledger.snapshot(),deviceId)))throw new Error(`Device ${deviceId} still has open work`)}const header={source:"L",domain:this.ledger.tenant,exportedAt,devices:devices.map(({deviceId,expectedRevision})=>({deviceId,frozenRevision:expectedRevision}))};const dump=this.ledger.dumpForSwitch();const job=Object.values(dump.body.outbox).find(row=>row.kind==="host-job");if(job)throw new SwitchExportError("open_work",`Switch export source: Host job ${job.occurrenceKey} is pending; let it run first`);const document=sealSwitchExport(switchContent(dump,this.ledger.tenant,header));this.ledger.transaction(s=>{stateOf(s.application).switchExport={digest:document.manifest.digest,exportedAt,devices:document.devices.map(device=>({...device}))};});return document})}commitSwitch(deviceId,expectedRevision,receipt){return this.exclusive(async()=>{switchStep(structuredClone(this.ledger.snapshot()),deviceId,expectedRevision,"commit");const mark=this.snapshot().switchExport;if(!mark)throw new Error("This Host has not exported its domain for a switch");if(mark.digest!==receipt)throw new Error(`The receipt ${receipt} is not this Host's export ${mark.digest}`);if(!mark.devices.some(device=>device.deviceId===deviceId&&device.frozenRevision===expectedRevision)){throw new Error(`Device ${deviceId} at revision ${expectedRevision} is not a device of the export`)}const now=sealLedger(this.ledger,{source:"L",domain:this.ledger.tenant,devices:mark.devices,exportedAt:mark.exportedAt});if(now.manifest.digest!==mark.digest)throw new Error(`The ledger changed after its export: ${now.manifest.digest}, not ${mark.digest}`);this.ledger.transaction(s=>{for(const device of mark.devices)switchStep(s,device.deviceId,device.frozenRevision,"commit");});return this.topology(deviceId)})}abortSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.ledger.transaction(s=>{const state=stateOf(s.application),step=switchStep(s,deviceId,expectedRevision,"abort");if(state.switchExport?.devices.some(device=>device.deviceId===deviceId))delete state.switchExport;return step});await this.process();return this.topology(deviceId)})}retain(input){return this.exclusive(async()=>retainInLedger(this.ledger,input,{contextTurnLimit:this.contextTurnLimit,handoff:this.handoff}))}recover(){return this.exclusive(async()=>{this.write((s,rows)=>{for(const row of Object.values(stateOf(s.application).channel?.deliveries??{}))recoverDelivery(row);this.sync(s,rows);});try{await this.core.recover();}finally{await this.process();}})}sync(s,rows,injected){const state=stateOf(s.application);for(const key of Object.keys(state.hostIntents??{})){if(s.intents[hash(key)])continue;delete state.hostIntents[key];for(const[taskId,reply]of Object.entries(state.replies))if(reply.turnId===key)delete state.replies[taskId];}syncHead(state,this.coalesce,this.now());reconcileDreamRoutines(s,this.dreaming,this.models(),this.now());const routines=botRoutines(Object.values(s.routines));const limits={turnLimit:this.contextTurnLimit,contextMaxBytes:this.contextMaxBytes,instructionMaxBytes:this.instructionMaxBytes,handoff:this.handoff};const materialized=advanceRoomsAndTurns(s,state,this.now(),turn=>syncTurnInLedger(this.ledger,s,rows,turn,{now:this.now(),models:Object.keys(this.models()),readOnlyToolsets:this.options.readOnlyToolsets??[],limits,historyMode:!!this.options.history,history:injected?.turns.get(turn.id),roomHistoryMode:!!this.options.roomHistory,roomHistory:injected?.rooms.get(turn.id),routines,offer:this.offer}),(key,value)=>project(s,key,value));const dreamed=syncDreams(s,{tenant:this.ledger.tenant,policy:this.dreaming,models:this.models(),instructionMaxBytes:this.instructionMaxBytes,now:this.now(),refused:botId=>botDeviceRefusal(state,botId)!==void 0,history:injected?.dreams,historyMode:!!this.options.history});settleDelegations(s,state,this.now(),(key,value)=>project(s,key,value),this.timers);reportCardDecisions(state,(key,value)=>project(s,key,value));syncTail(state,s,this.now(),(key,value)=>project(s,key,value));return materialized||dreamed}async flushReplies(){for(const d of Object.values(this.snapshot().delegations)){if(!replyCheckDue(d,this.now()))continue;const intent=this.core.intent(d.chainTurnIds.at(-1));let check={failed:true};if(intent)try{if(!this.server.tasks.agentMessage)throw new Error("Agent message readback API required");check={taskId:intent.taskId,failed:false,readback:await this.server.tasks.agentMessage(intent.taskId,intent.execution.deviceId,intent.execution.payload.agentRef)};}catch{check={taskId:intent.taskId,failed:true};}this.write(s=>{const state=stateOf(s.application);checkReply(state,state.delegations[d.id],check,this.now(),(key,value)=>project(s,key,value),this.timers.uncertainAfterMs);});}}async callConnector(card){const controller=new AbortController;let timer;const deadline=new Promise((_,reject)=>{timer=setTimeout(()=>{const error=new Error(CONNECTOR_OUTCOME_UNKNOWN);controller.abort(error);reject(error);},this.connectorTimeoutMs);});try{return await Promise.race([Promise.resolve().then(()=>this.options.connector(card.id,card.action.action,card.action.draft,controller.signal)),deadline])}finally{clearTimeout(timer);}}async flushCards(){await callCardsInLedger(this.ledger,card=>this.callConnector(card));}async flushDeliveries(){const port=this.options.channel?.port;if(!port)return;if(port.readback)for(const old of Object.values(this.snapshot().channel?.deliveries??{}).filter(row=>row.state==="unknown")){try{const result=await port.readback(old.id);this.write(s=>{const row=stateOf(s.application).channel?.deliveries[old.id];if(row)readbackDelivery(row,old.attempts,result,this.now());});}catch{continue}}for(const old of Object.values(this.snapshot().channel?.deliveries??{})){const claim=this.write(s=>{const state=stateOf(s.application),row=state.channel.deliveries[old.id];if(row.state!=="pending"||(row.nextAttemptAt??0)>this.now())return;const route=deliveryRoute(state,row,this.now());if(!route){refuseRoute(state,row);return}if(startDelivery(row,this.now()))return {row,route}});if(!claim)continue;const controller=new AbortController;let timer;const deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>{controller.abort();reject(new Error("delivery_timeout"));},this.deliveryTimeoutMs);});try{const result=await Promise.race([Promise.resolve().then(()=>port.send({deliveryId:claim.row.id,route:claim.route,body:claim.row.body},controller.signal)),deadline]);this.write(s=>settleDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,result,this.now()));}catch{this.write(s=>unknownDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,controller.signal.aborted?"send_timeout":"send_failed"));}finally{clearTimeout(timer);}}this.write(s=>cleanReplyTokens(s,stateOf(s.application),this.now()));}async syncWithHistory(){const injected=await this.readHistory();return this.write((s,rows)=>this.sync(s,rows,injected))}async readHistory(){const read=this.options.history,readRoom=this.options.roomHistory;if(!read&&!readRoom)return void 0;const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const injected={turns:new Map,rooms:new Map,dreams:new Map};for(const turn of Object.values(state.turns)){if(!awaitsOffer(ledger,state,turn)||this.unread.has(turn.id))continue;const seat=turn.source==="room_slot"?state.team.seats[turn.id]:void 0;try{if(seat&&readRoom&&!seat.released){const roomId=state.team.rounds[seat.roundId].roomId;if(Object.values(ledger.outbox).some(row=>row.kind==="projection"&&row.id.startsWith(roomMessageProjection(roomId,""))&&row.value.roomId===roomId)){this.unread.add(turn.id);continue}const ms=Math.min(this.historyTimeoutMs,seat.deadline===void 0?Infinity:seat.deadline-this.now());const rows=roomMessages(await bounded(readRoom({roomId,botId:turn.botId,turnId:turn.id}),ms));injected.rooms.set(turn.id,{rows,digest:hash(canonical(rows))});}else if(turn.source!=="room_slot"&&read){const rows=contextTurns(await bounded(read({botId:turn.botId,turnId:turn.id}),this.historyTimeoutMs));injected.turns.set(turn.id,{rows,digest:hash(canonical(rows))});}}catch{this.unread.add(turn.id);}}if(read)for(const{key,botId,turnId}of dreamReads(state)){injected.dreams.set(key,await bounded(read({botId,turnId}),this.historyTimeoutMs).then(contextTurns).catch(()=>null));}return injected}async process(){try{await this.pass();}finally{this.armTimer();}}async pass(){if(this.snapshot().switchExport)return;this.unread.clear();let failure;let more;do{await this.deliverCancels().catch(()=>{});const admitted=await this.syncWithHistory();await flushHomes(this.server,this.ledger,this.now);this.intentFailures.clear();try{await this.core.drain();}catch(error){failure??={error};}const refused=this.reportIntentFailures();if(refused)failure??={error:refused};await this.deliverCancels().catch(()=>{});let materialized=await this.syncWithHistory();await this.refreshDevices();await this.flushCards();materialized=await this.syncWithHistory()||materialized;await this.flushReplies();materialized=await this.syncWithHistory()||materialized;await this.flushDeliveries();const ledger=this.ledger.snapshot();const state=stateOf(ledger.application);more=admitted||materialized||Object.values(ledger.intents).some(intent=>intent.phase==="queued"&&intent.cancelReason&&!intent.conclusion)||Object.values(state.turns).some(turn=>turn.status!=="blocked"&&awaitsOffer(ledger,state,turn)&&!this.unread.has(turn.id));}while(more&&!failure);if(failure)throw failure.error}armTimer(){clearTimeout(this.timer);if(!this.closed&&!this.snapshot().switchExport){const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const due=[...this.options.channel?Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="pending").map(row=>row.nextAttemptAt??this.now()):[],...Object.values(state.channel?.inbounds??{}).filter(row=>row.reply?.token).map(row=>row.reply.expiresAt),...collaborationDue(state,this.timers),...state.team.homeOperations.filter(op=>op.status==="pending"&&(homeSent(op)||!deviceRefusal(state,op.request.deviceId))).map(op=>Math.max(this.now()+1e3,op.retryAt??0)),...Object.values(state.delegations).filter(d=>d.cancel&&!d.cancel.delivered).map(()=>this.now()+1e3),...this.unread.size?[this.now()+1e3]:[]];if(due.length){this.timer=setTimeout(()=>{void this.drain().catch(()=>{});},Math.max(1,Math.min(6e4,Math.min(...due)-this.now())));this.timer.unref?.();}}}async refreshDevices(){if(!this.server.machines)return;if(!Object.values(this.snapshot().delegations).some(d=>!d.verdict&&!d.cancel&&(d.status==="queued"||d.status==="waiting_device")))return;let devices;let timer;try{devices=await Promise.race([this.server.machines.list(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("Device discovery timed out")),1e3);})]);}catch{return}finally{clearTimeout(timer);}this.write(s=>observeDevices(s,stateOf(s.application),new Map(devices.map(d=>[d.deviceId,d.connected])),(key,value)=>project(s,key,value)));}async close(){this.closed=true;clearTimeout(this.timer);await this.chain;clearTimeout(this.timer);await this.core.close();}};function createBotPersonaProjection(){return createAgentHomeProjectionConsumer(async({projection,projectionHash,writeHomeFile})=>{if(!projection||typeof projection!=="object"||!("schemaVersion"in projection)||projection.schemaVersion!=="bot-profile.v1"||!("persona"in projection)||typeof projection.persona!=="string"||projectionHash!==`sha256:${hash(projection)}`)throw new Error("Invalid Bot persona projection");await writeHomeFile("AGENTS.md",projection.persona);})}
13
+
14
+ export { BotCollaboration, createBotPersonaProjection };
15
+ //# sourceMappingURL=index.js.map
16
+ //# sourceMappingURL=index.js.map