@byok-sdk/bot-collaboration 0.43.0 → 0.44.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.
- package/README.md +84 -73
- package/dist/chunk-6X7ARUDF.js +9 -0
- package/dist/chunk-6X7ARUDF.js.map +1 -0
- package/dist/chunk-BGGEZHPC.js +27 -0
- package/dist/chunk-BGGEZHPC.js.map +1 -0
- package/dist/chunk-UXEHG75I.js +11 -0
- package/dist/chunk-UXEHG75I.js.map +1 -0
- package/dist/commit.d.ts +0 -13
- package/dist/compaction.d.ts +9 -2
- package/dist/delivery-routing.d.ts +1 -1
- package/dist/delivery-superseded.d.ts +3 -0
- package/dist/delivery.d.ts +1 -1
- package/dist/dream.d.ts +18 -4
- package/dist/host-kit.d.ts +5 -6
- package/dist/host-kit.js +4 -5
- package/dist/host-kit.js.map +1 -1
- package/dist/host.d.ts +11 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +6 -7
- package/dist/index.js.map +1 -1
- package/dist/ledger-compatibility.d.ts +4 -0
- package/dist/migration.d.ts +1 -1
- package/dist/model.d.ts +5 -9
- package/dist/routines.d.ts +0 -6
- package/dist/rules/autonomy.d.ts +1 -4
- package/dist/rules/index.js +1 -2
- package/dist/rules/priority.d.ts +2 -0
- package/dist/rules/sync.d.ts +6 -0
- package/dist/switch.d.ts +2 -30
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +1 -1
- package/package.json +6 -6
- package/dist/chunk-33YA66U7.js +0 -7
- package/dist/chunk-33YA66U7.js.map +0 -1
- package/dist/chunk-6Y2B2XCP.js +0 -12
- package/dist/chunk-6Y2B2XCP.js.map +0 -1
- package/dist/chunk-QZRWFFHM.js +0 -12
- package/dist/chunk-QZRWFFHM.js.map +0 -1
- package/dist/chunk-ZX6C5U2S.js +0 -27
- package/dist/chunk-ZX6C5U2S.js.map +0 -1
package/dist/dream.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface DreamingOptions {
|
|
|
16
16
|
models?: readonly string[];
|
|
17
17
|
/** Default `DEFAULT_DREAM_MAX_DURATION_MS`. */
|
|
18
18
|
maxDurationMs?: number;
|
|
19
|
-
/** Request native session input when the device advertises it. Default true. This applies only to
|
|
19
|
+
/** Request native session input when the device advertises it. Default true. This applies only to templates whose target names Pi: any other template, like a device that does not advertise native sessions, receives no request and the dream runs without that input. */
|
|
20
20
|
nativeSessions?: boolean;
|
|
21
21
|
}
|
|
22
22
|
export interface DreamPolicy {
|
|
@@ -28,20 +28,27 @@ export interface DreamPolicy {
|
|
|
28
28
|
/** Checks the option once, at construction. `undefined`: dreaming is off. */
|
|
29
29
|
export declare function dreamPolicy(options: DreamingOptions | false | undefined): DreamPolicy | undefined;
|
|
30
30
|
export type DreamSkip = 'superseded' | 'dreaming_off' | 'bot_archived' | 'bot_suspended' | 'device_unavailable' | 'bot_not_ready' | 'no_new_turns' | 'model_unavailable' | 'history_unavailable';
|
|
31
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* How one occurrence ended. `template` and `fallback` are set once a dream was offered. `user_input`: the dream yielded to
|
|
33
|
+
* user input before a device claimed it (#2334), with outcome `cancelled`.
|
|
34
|
+
*/
|
|
32
35
|
export interface DreamRecord {
|
|
33
36
|
occurrenceKey: string;
|
|
34
37
|
at: number;
|
|
35
38
|
outcome: 'skipped' | 'succeeded' | 'failed' | 'declined' | 'cancelled' | 'expired' | 'superseded';
|
|
36
|
-
reason?:
|
|
39
|
+
reason?: DreamSkip | 'intent_compacted' | 'user_input';
|
|
37
40
|
template?: string;
|
|
38
41
|
fallback?: boolean;
|
|
39
42
|
}
|
|
40
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
* `since` starts the next window. `throughTurn` is the last Turn of the settled run of Turns that the last successful dream covered.
|
|
45
|
+
* `userInputCancels` counts the dreams in a row that yielded to user input (#2334), so a Host can see a Bot that never dreams.
|
|
46
|
+
*/
|
|
41
47
|
export interface DreamBot {
|
|
42
48
|
since: number;
|
|
43
49
|
throughTurn?: string;
|
|
44
50
|
last?: DreamRecord;
|
|
51
|
+
userInputCancels?: number;
|
|
45
52
|
}
|
|
46
53
|
/** An occurrence that K8 has not closed. `template` is set when it joined the FIFO. */
|
|
47
54
|
export interface OpenDream {
|
|
@@ -60,6 +67,13 @@ export interface DreamState {
|
|
|
60
67
|
export declare function dreamOf(state: CollaborationState, intentKey: string): OpenDream | undefined;
|
|
61
68
|
/** The intent ids of open dreams: background work that user input goes ahead of. */
|
|
62
69
|
export declare function dreamIntentIds(state: CollaborationState): string[];
|
|
70
|
+
/**
|
|
71
|
+
* The K4 `yieldUnclaimed` predicate (#2334): `user_input` when the intent is an open dream and its Bot has a queued or frozen (`processing`) Turn that
|
|
72
|
+
* is not autonomous. K4 then cancels the dream only if no device has claimed it; a claimed dream is never interrupted.
|
|
73
|
+
*/
|
|
74
|
+
export declare function dreamYield(state: CollaborationState, intentKey: string): 'user_input' | undefined;
|
|
75
|
+
/** The `limits.maxDurationMs` of each Bot's submitted dream, by Bot (#2334): the `dreamHold` sync fact. */
|
|
76
|
+
export declare function dreamHolds(s: LedgerState): Map<string, number>;
|
|
63
77
|
/** The `bot-dream` occurrence hook. A hook gets no K4 state, so the sync decides and promotes, as for a routine Turn. */
|
|
64
78
|
export declare function recordDream(state: CollaborationState, run: HostOccurrenceRun, now: number): void;
|
|
65
79
|
/** One dream routine for each unarchived Bot with a usable template, and no other. It runs in every sync, so it covers each way a Bot starts or ends. */
|
package/dist/host-kit.d.ts
CHANGED
|
@@ -34,8 +34,8 @@ export type { CheckedOffer, ConfirmableSpec, MainAction, OutcomeOffer, TurnActio
|
|
|
34
34
|
export type { Card, CollaborationState, Delegation, InputBatch, ReplyEntry, SealReason, Turn, UserInput } from './model.js';
|
|
35
35
|
export { BOT_DREAM, BOT_ROUTINE, botRoutines } from './routines.js';
|
|
36
36
|
export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, type DreamBot, type DreamingOptions, type DreamRecord, type DreamSkip, type DreamState, type OpenDream } from './dream.js';
|
|
37
|
-
export { CommitConflict, commitInLedger,
|
|
38
|
-
export type { Command, CommandPorts, CommitRequest, CommitResult, Disposition, OutboxIntent
|
|
37
|
+
export { CommitConflict, commitInLedger, retainInLedger, revisionOf } from './commit.js';
|
|
38
|
+
export type { Command, CommandPorts, CommitRequest, CommitResult, Disposition, OutboxIntent } from './commit.js';
|
|
39
39
|
export type { BotRoutine, BotRoutineInput } from './routines.js';
|
|
40
40
|
export type { BotProfile, Room, Round, Seat, TeamState } from './team-model.js';
|
|
41
41
|
export { DEFAULT_MEMBER_MENTIONS, ROOM_GRACE_MS, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, memberMentions, type MemberMentions, type RoomMessage } from './rooms.js';
|
|
@@ -45,16 +45,15 @@ export { inboundDisposition, inboundDispositions, type InboundDisposition, type
|
|
|
45
45
|
export { DEVICE_CONCURRENCY } from './rules/priority.js';
|
|
46
46
|
export { DeviceModeError, type DeviceTopology, type SwitchWork } from './topology.js';
|
|
47
47
|
export { SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, sealSwitchExport, switchAttempts, verifySwitchExport, type ArchivedRecord, type ExecutionRecord, type IntentRecord, type MessageReceipt, type OccurrenceRecord, type OutboxRecord, type RoutineRecord, type SwitchContent, type SwitchDevice, type SwitchExport, type SwitchExportRefusal, type SwitchManifest, type SwitchSection, type TombstoneRecord } from './migration.js';
|
|
48
|
-
export { commitImport, discardImport, importForSwitch } from './switch.js';
|
|
49
48
|
export { DeviceSwitchingError, SwitchExportedError, SwitchImportedError, type SwitchReceipt } from './migration.js';
|
|
50
49
|
export { botOutcomePorts, outcomeFailure, routeTerminal, runHostIntentHandler, syncHead, syncTail } from './adapter-steps.js';
|
|
51
50
|
export { isOwner, verified } from './channel.js';
|
|
52
51
|
export { admitUserInput } from './coalesce.js';
|
|
53
|
-
export { acceptDeliveryEcho, readbackDelivery, recoverDelivery, settleDelivery, startDelivery, unknownDelivery } from './delivery.js';
|
|
52
|
+
export { acceptDeliveryEcho, readbackDelivery, recoverDelivery, settleDelivery, startDelivery, supersededDeliveryIds, unknownDelivery } from './delivery.js';
|
|
54
53
|
export { cleanReplyTokens, deliveryRoute, echoCandidates, enablePush, promoteStaged, queueDelivery, refuseRoute, rememberInbound, resendUnknown, revokePush, type IntentConclusions } from './delivery-routing.js';
|
|
55
|
-
export { checkDreamInstruction, dreamIntentIds, dreamPolicy, reconcileDreamRoutines, recordDream, syncDreams, type DreamSync } from './dream.js';
|
|
54
|
+
export { checkDreamInstruction, dreamHolds, dreamIntentIds, dreamPolicy, dreamYield, reconcileDreamRoutines, recordDream, syncDreams, type DreamSync } from './dream.js';
|
|
56
55
|
export { exportMarkOf, type SwitchExportMark, type SwitchHeader } from './migration.js';
|
|
57
56
|
export { stateOf } from './model.js';
|
|
58
|
-
export { concludeRoutineTurn, createDefinition, endable, owned, resealDefinition, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, routineCalendar, routineOccurrence, routineTurn, sealedDefinition,
|
|
57
|
+
export { concludeRoutineTurn, createDefinition, endable, owned, resealDefinition, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, routineCalendar, routineOccurrence, routineTurn, sealedDefinition, sealedTemplate, SealedRoutineVersionError, updateDefinition, type SealedRoutineAction } from './routines.js';
|
|
59
58
|
export { sealLedger } from './switch.js';
|
|
60
59
|
export { applyHomeTerminal, applyManagement, applyModels, checkHomeReadback, failHomeFlush, homeEnqueued, homeHead, homeRequests, planHomeRetry, updateBot, writeSnapshotBot, type HomeReadback } from './team.js';
|
package/dist/host-kit.js
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitUserInput, botOutcomePorts, checkDreamInstruction, cleanReplyTokens,
|
|
2
|
-
export { BOT_DREAM, BOT_ROUTINE, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, RetentionRefused, SealedRoutineVersionError, TEAM_NOTE_LIMIT, applyHomeTerminal, applyManagement, applyModels, botRoutines, checkHomeReadback, classifyInbound, concludeRoutineTurn, contextPack, createDefinition, endable, failHomeFlush, homeEnqueued, homeHead, homeRequests, inboundKey, isOwner, owned, planHomeRetry, resealDefinition, retainRoots, routineCalendar, routineOccurrence, routineTurn, sealedDefinition,
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
export { BOT_REPLY_MAX_BYTES, CommitConflict, DEFAULT_AUTONOMY, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, DEFAULT_INSTRUCTION_MAX_BYTES, DEFAULT_MEMBER_MENTIONS, DelegationError, HostIntentError, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, ROOM_GRACE_MS, RetiredIdentityError, SYSTEM_PROMPT, autonomyOf, contextTurns, historyRowFromTurn, memberMentions, minimumInstructionBytes, outcomeOffer, outcomeSchema, refuseRetired, retiredIdentity, revisionOf, wouldDoRows } from './chunk-ZX6C5U2S.js';
|
|
1
|
+
export { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, DeviceModeError, DeviceSwitchingError, IntentOutcomeError, SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, SwitchExportedError, SwitchImportedError, acceptDeliveryEcho, admitUserInput, botOutcomePorts, checkDreamInstruction, cleanReplyTokens, commitInLedger, deliveryRoute, dreamHolds, dreamIntentIds, dreamPolicy, dreamYield, echoCandidates, enablePush, exportMarkOf, inboundDisposition, inboundDispositions, outcomeFailure, promoteStaged, queueDelivery, readbackDelivery, reconcileDreamRoutines, recordDream, recoverDelivery, refuseRoute, rememberInbound, resendUnknown, retainInLedger, revokePush, routeTerminal, runHostIntentHandler, sealLedger, sealSwitchExport, settleDelivery, startDelivery, switchAttempts, syncDreams, syncHead, syncTail, unknownDelivery, verifySwitchExport } from './chunk-UXEHG75I.js';
|
|
2
|
+
export { BOT_DREAM, BOT_ROUTINE, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, RetentionRefused, SealedRoutineVersionError, TEAM_NOTE_LIMIT, applyHomeTerminal, applyManagement, applyModels, botRoutines, checkHomeReadback, classifyInbound, concludeRoutineTurn, contextPack, createDefinition, endable, failHomeFlush, homeEnqueued, homeHead, homeRequests, inboundKey, isOwner, owned, planHomeRetry, resealDefinition, retainRoots, routineCalendar, routineOccurrence, routineTurn, sealedDefinition, sealedTemplate, stateOf, supersededDeliveryIds, updateBot, updateDefinition, verified, writeSnapshotBot } from './chunk-6X7ARUDF.js';
|
|
3
|
+
import { outcomeSchema, botTurnInstruction, promptActions } from './chunk-BGGEZHPC.js';
|
|
4
|
+
export { BOT_REPLY_MAX_BYTES, CommitConflict, DEFAULT_AUTONOMY, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, DEFAULT_INSTRUCTION_MAX_BYTES, DEFAULT_MEMBER_MENTIONS, DEVICE_CONCURRENCY, DelegationError, HostIntentError, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, ROOM_GRACE_MS, RetiredIdentityError, SYSTEM_PROMPT, autonomyOf, contextTurns, historyRowFromTurn, memberMentions, minimumInstructionBytes, outcomeOffer, outcomeSchema, refuseRetired, retiredIdentity, revisionOf, wouldDoRows } from './chunk-BGGEZHPC.js';
|
|
6
5
|
|
|
7
6
|
function botTurnInstruction2(options){const routines=options.routines??[];const schema=outcomeSchema(options.turn.botId,options.state,options.turn,options.models,routines,options.offer);const{instruction}=botTurnInstruction(options.state,options.turn,options.limits,routines,options.injected,options.room,promptActions(schema,options.offer));return {instruction}}
|
|
8
7
|
|
package/dist/host-kit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/host-kit.ts"],"names":["botTurnInstruction"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/host-kit.ts"],"names":["botTurnInstruction"],"mappings":";;;;;AAcO,SAASA,mBAAAA,CAA6C,QAAgE,CAC3H,MAAM,SAAW,OAAA,CAAQ,QAAA,EAAY,EAAC,CACtC,MAAM,MAAA,CAAS,cAAc,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAO,OAAA,CAAQ,KAAA,CAAO,OAAA,CAAQ,KAAM,OAAA,CAAQ,MAAA,CAAQ,QAAA,CAAU,OAAA,CAAQ,KAAK,CAAA,CACrH,KAAM,CAAE,WAAY,EAAI,kBAAA,CAAwB,OAAA,CAAQ,MAAO,OAAA,CAAQ,IAAA,CAAM,OAAA,CAAQ,MAAA,CAAQ,QAAA,CAAU,OAAA,CAAQ,SAAU,OAAA,CAAQ,IAAA,CAAM,aAAA,CAAc,MAAA,CAAQ,OAAA,CAAQ,KAAK,CAAC,CAAA,CAC3K,OAAO,CAAE,WAAY,CACvB","file":"host-kit.js","sourcesContent":["// The `./host-kit` entry: the L modules a Host adapter composes (model, channel, delivery, routines, team,\n// migration, retention, dreaming, adapter steps). It does not load the L Host or @byok-sdk/client, so a Worker\n// can bundle it.\nimport { botTurnInstruction as buildBotTurnInstruction, type BotHistoryState, type ContextTurn, type InstructionLimits } from './rules/context.js';\nimport { outcomeSchema, promptActions, type CheckedOffer, type ContextRoutine, type ContextState } from './rules/schema.js';\nimport type { RoomMessage } from './rules/rooms.js';\nimport type { Turn } from './rules/turn.js';\n\n/** Inputs used by sync to freeze a Bot Turn's instruction. */\nexport interface BotTurnInstructionOptions<R extends ContextRoutine = ContextRoutine> {\n state: ContextState & BotHistoryState; turn: Turn; limits: InstructionLimits; models: readonly string[];\n routines?: readonly R[]; injected?: readonly ContextTurn[]; room?: readonly RoomMessage[]; offer?: CheckedOffer;\n}\n/** Compute the instruction sync freezes, with the same history, routines and offer. */\nexport function botTurnInstruction<R extends ContextRoutine>(options: BotTurnInstructionOptions<R>): { instruction: string } {\n const routines = options.routines ?? [];\n const schema = outcomeSchema(options.turn.botId, options.state, options.turn, options.models, routines, options.offer);\n const { instruction } = buildBotTurnInstruction(options.state, options.turn, options.limits, routines, options.injected, options.room, promptActions(schema, options.offer));\n return { instruction };\n}\nexport type { InstructionLimits } from './rules/context.js';\nexport { DelegationError, HostIntentError } from './rules/delegation.js';\nexport { IntentOutcomeError } from './adapter-steps.js';\nexport { RetentionRefused, retainRoots } from './retention.js';\nexport type { RetentionFacts, RetentionInput, RetentionRefusedCode, RetentionLimits, RetentionResult, RetentionStore } from './retention.js';\nexport { refuseRetired, retiredIdentity, RetiredIdentityError, type AdmittedIds, type RetiredNamespace } from './rules/commands.js';\nexport type { DelegationCancelResult, TurnCancelResult } from './rules/delegation.js';\nexport type { MessageDisposition } from './rules/message.js';\nexport { contextTurns, historyRowFromTurn, type ContextTurn } from './rules/context.js';\nexport { classifyInbound, inboundKey } from './channel.js';\nexport type { ChannelOptions, ChannelPort, Conversation, Delivery, DeliveryState, InboundClass, InboundMessage, Principal, PushRoute, ReplyRoute } from './channel.js';\nexport { BOT_REPLY_MAX_BYTES, DEFAULT_INSTRUCTION_MAX_BYTES, minimumInstructionBytes } from './delegation.js';\nexport { SYSTEM_PROMPT, contextPack, outcomeOffer, outcomeSchema, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS } from './schema.js';\nexport type { CheckedOffer, ConfirmableSpec, MainAction, OutcomeOffer, TurnAction } from './schema.js';\nexport type { Card, CollaborationState, Delegation, InputBatch, ReplyEntry, SealReason, Turn, UserInput } from './model.js';\nexport { BOT_DREAM, BOT_ROUTINE, botRoutines } from './routines.js';\nexport { DEFAULT_DREAM_MAX_DURATION_MS, DREAM_WAIT_MS, type DreamBot, type DreamingOptions, type DreamRecord, type DreamSkip, type DreamState, type OpenDream } from './dream.js';\nexport { CommitConflict, commitInLedger, retainInLedger, revisionOf } from './commit.js';\nexport type { Command, CommandPorts, CommitRequest, CommitResult, Disposition, OutboxIntent } from './commit.js';\nexport type { BotRoutine, BotRoutineInput } from './routines.js';\nexport type { BotProfile, Room, Round, Seat, TeamState } from './team-model.js';\nexport { DEFAULT_MEMBER_MENTIONS, ROOM_GRACE_MS, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, memberMentions, type MemberMentions, type RoomMessage } from './rooms.js';\nexport { TEAM_NOTE_LIMIT } from './team.js';\nexport { DEFAULT_AUTONOMY, autonomyOf, wouldDoRows, type Autonomy, type WouldDo, type WouldDoAction } from './rules/autonomy.js';\nexport { inboundDisposition, inboundDispositions, type InboundDisposition, type InboundRow, type InboundState } from './rules/inbound.js';\nexport { DEVICE_CONCURRENCY } from './rules/priority.js';\nexport { DeviceModeError, type DeviceTopology, type SwitchWork } from './topology.js';\nexport { SWITCH_EXPORT_VERSION, SWITCH_SECTIONS, SwitchExportError, sealSwitchExport, switchAttempts, verifySwitchExport, type ArchivedRecord, type ExecutionRecord, type IntentRecord, type MessageReceipt,\n type OccurrenceRecord, type OutboxRecord, type RoutineRecord, type SwitchContent, type SwitchDevice, type SwitchExport, type SwitchExportRefusal,\n type SwitchManifest, type SwitchSection, type TombstoneRecord } from './migration.js';\nexport { DeviceSwitchingError, SwitchExportedError, SwitchImportedError, type SwitchReceipt } from './migration.js';\nexport { botOutcomePorts, outcomeFailure, routeTerminal, runHostIntentHandler, syncHead, syncTail } from './adapter-steps.js';\nexport { isOwner, verified } from './channel.js';\nexport { admitUserInput } from './coalesce.js';\nexport { acceptDeliveryEcho, readbackDelivery, recoverDelivery, settleDelivery, startDelivery, supersededDeliveryIds, unknownDelivery } from './delivery.js';\nexport { cleanReplyTokens, deliveryRoute, echoCandidates, enablePush, promoteStaged, queueDelivery, refuseRoute, rememberInbound, resendUnknown,\n revokePush, type IntentConclusions } from './delivery-routing.js';\nexport { checkDreamInstruction, dreamHolds, dreamIntentIds, dreamPolicy, dreamYield, reconcileDreamRoutines, recordDream, syncDreams, type DreamSync } from './dream.js';\nexport { exportMarkOf, type SwitchExportMark, type SwitchHeader } from './migration.js';\nexport { stateOf } from './model.js';\nexport { concludeRoutineTurn, createDefinition, endable, owned, resealDefinition, ROUTINE_LATE_AFTER_MS, ROUTINE_WAIT_MS, routineCalendar,\n routineOccurrence, routineTurn, sealedDefinition, sealedTemplate, SealedRoutineVersionError, updateDefinition,\n type SealedRoutineAction } from './routines.js';\nexport { sealLedger } from './switch.js';\nexport { applyHomeTerminal, applyManagement, applyModels, checkHomeReadback, failHomeFlush, homeEnqueued, homeHead, homeRequests, planHomeRetry,\n updateBot, writeSnapshotBot, type HomeReadback } from './team.js';\n"]}
|
package/dist/host.d.ts
CHANGED
|
@@ -171,6 +171,7 @@ export declare class BotCollaboration {
|
|
|
171
171
|
private chain;
|
|
172
172
|
private timer?;
|
|
173
173
|
private closed;
|
|
174
|
+
private passQueued;
|
|
174
175
|
private readonly now;
|
|
175
176
|
private readonly connectorTimeoutMs;
|
|
176
177
|
private readonly deliveryTimeoutMs;
|
|
@@ -310,11 +311,18 @@ export declare class BotCollaboration {
|
|
|
310
311
|
outcome: 'accepted' | 'refused';
|
|
311
312
|
reasonCode?: string;
|
|
312
313
|
}>;
|
|
314
|
+
/**
|
|
315
|
+
* One coalesced K8 pass after a K4 settlement or an accepted message. The caller never awaits it: a K8 pass calls
|
|
316
|
+
* `core.drain()`, so a K4 callback that waited for it would wait on itself. A pass that is queued and not started reads
|
|
317
|
+
* the ledger when it starts, so later notices join it. After `close()` the ledger keeps the work for `recover()`.
|
|
318
|
+
*/
|
|
319
|
+
private schedulePass;
|
|
313
320
|
private applyMessage;
|
|
314
321
|
/**
|
|
315
322
|
* Owner API ("Cancel", §8.8), from A's delegation chip or from B's `bot_request` Turn. Idempotent (#1405): an earlier cancel
|
|
316
323
|
* gives `cancel_pending` and a verdict `already_settled`, and neither writes or sends. Refuses with `DelegationError`.
|
|
317
|
-
* It rejects when `core.cancel` fails. The cancel fact is already committed
|
|
324
|
+
* It rejects when `core.cancel` fails. The cancel fact is already committed. A failure before the K4 commit leaves it for
|
|
325
|
+
* the timer; a drain failure after the commit leaves it delivered (#2253).
|
|
318
326
|
*/
|
|
319
327
|
cancelDelegation(id: string, ...by: PrincipalArg): Promise<DelegationCancelResult>;
|
|
320
328
|
/** Owner API ("End", §8.3): close a held reply or an uncertain delegation with `abandoned`. */
|
|
@@ -326,6 +334,8 @@ export declare class BotCollaboration {
|
|
|
326
334
|
/**
|
|
327
335
|
* Deliver each committed cancel to its frozen target (§8.8). A crash before
|
|
328
336
|
* `delivered` leaves the fact for the next pass. It never picks a new Turn.
|
|
337
|
+
* A cancel is delivered once K4 commits it, even when the drain after that commit fails, and when its target intent has
|
|
338
|
+
* concluded or was compacted after concluding (#2253). Each fact is tried on its own; the first error is rethrown.
|
|
329
339
|
*/
|
|
330
340
|
private deliverCancels;
|
|
331
341
|
/**
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { inspectLedger } from './store-compatibility.js';
|
|
2
2
|
export { BotCollaboration } from './host.js';
|
|
3
|
-
export { botCompactVeto } from './compaction.js';
|
|
3
|
+
export { botCompactVeto, botLedgerOptions } from './compaction.js';
|
|
4
4
|
export type { AgentMessageInput, BotOptions, HostIntentCancelResult, HostIntentHandler, HostIntentMessageHandler, MessageServer } from './host.js';
|
|
5
5
|
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot, type TeamModeCode, type TeamSnapshot, type TeamSnapshotBot, type TeamSnapshotRoom } from './rules/team.js';
|
|
6
6
|
export { createBotPersonaProjection } from './persona.js';
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { checkTopology, checkSwitchRecords,
|
|
2
|
-
export { botCompactVeto } from './chunk-
|
|
3
|
-
import { stateOf,
|
|
4
|
-
import { DEVICE_CONCURRENCY, admitDeviceSlot } from './chunk-
|
|
5
|
-
|
|
6
|
-
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-ZX6C5U2S.js';
|
|
1
|
+
import { botLedgerOptions, checkTopology, checkSwitchRecords, botCompactVeto, K8_FORMAT, checkLedgerWouldDo, dreamPolicy, checkDreamInstruction, dreamYield, 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-UXEHG75I.js';
|
|
2
|
+
export { botCompactVeto, botLedgerOptions } from './chunk-UXEHG75I.js';
|
|
3
|
+
import { stateOf, verified, routineCalendar, BOT_DREAM, BOT_ROUTINE, routineTurn, applyModels, classifyInbound, inboundKey, isOwner, applyManagement, updateBot, writeSnapshotBot, owned, endable, updateDefinition, ownerRoutineUpdate, botRoutines, supersededDeliveryIds, homeHead, homeRequests, checkHomeReadback, planHomeRetry, homeEnqueued, applyHomeTerminal, failHomeFlush } from './chunk-6X7ARUDF.js';
|
|
4
|
+
import { refuseUnmigratedWouldDo, 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, DEVICE_CONCURRENCY, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, admitDeviceSlot, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-BGGEZHPC.js';
|
|
5
|
+
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-BGGEZHPC.js';
|
|
7
6
|
import { mkdtempSync, copyFileSync, rmSync, statSync } from 'fs';
|
|
8
7
|
import { tmpdir } from 'os';
|
|
9
8
|
import { resolve, join, basename } from 'path';
|
|
@@ -12,7 +11,7 @@ import { randomUUID } from 'crypto';
|
|
|
12
11
|
import { buildHandoffPack, ToolsetIdSchema } from '@byok-sdk/protocol';
|
|
13
12
|
import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';
|
|
14
13
|
|
|
15
|
-
function inspectLedger(path,tenant){const file=resolve(path),store="bot-collaboration-ledger";const stat=statOrUndefined(file);if(!stat)return {store,path:file,verdict:"absent",reason:"No ledger file at this path"};if(!stat.isFile())return {store,path:file,verdict:"rejected",reason:"The ledger path is not a regular file"};const directory=mkdtempSync(join(tmpdir(),"byok-ledger-check-"));try{const copy=join(directory,basename(file)),suffixes=["","-wal","-journal"];const fingerprint=suffix=>{const s=statOrUndefined(file+suffix);return s&&`${s.size}:${s.mtimeMs}:${s.ino}`};const before=suffixes.map(fingerprint);suffixes.forEach((suffix,i)=>{if(before[i]!==void 0)copyFileSync(file+suffix,copy+suffix);});if(suffixes.some((suffix,i)=>fingerprint(suffix)!==before[i]))throw new Error(`${file} changed while it was being checked; stop its owner and check again`);try{const{DatabaseSync}=process.getBuiltinModule("node:sqlite");const db=new DatabaseSync(copy,{readOnly:true});try{if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='host_ledger'").get())throw new Error("Not a Host ledger")}finally{db.close();}const ledger=new HostLedger(copy,tenant);try{const state=stateOf(ledger.snapshot().application);checkTopology(state);checkSwitchRecords(state);if(state.switchExport)return {store,path:file,verdict:"accepted",reason:"This build opens the exported ledger; run migrateWouldDo if the switch is aborted"};return wouldDoNeedsMigration(state)?{store,path:file,verdict:"migration-required",reason:"Would-do rows lack turnId; run migrateWouldDo before serving"}:{store,path:file,verdict:"accepted",reason:"This build opens the ledger"}}finally{ledger.close();}}catch(error){const code=error?.code;return {store,path:file,verdict:error instanceof OldCollaborationStateError?"new-path-repair":"rejected",...typeof code==="string"?{code}:{},reason:error instanceof Error?error.message:String(error)}}}finally{rmSync(directory,{recursive:true,force:true});}}function statOrUndefined(file){try{return statSync(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}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};const dispatch=await this.core.cancel(key);try{await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}if(intent.phase==="inflight")return {key,result:"cancel_pending",...dispatch};const conclusion=this.core.intent(key)?.conclusion;return {key,result:"cancelled",...conclusion===void 0?{}:{conclusion},...dispatch}})}cancelHostIntents(keys,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntents",keys.join(" "));const seen=new Set;for(const key of keys){if(seen.has(key))throw new Error(`Duplicate Host intent key: ${key}`);seen.add(key);}return this.write(s=>{const state=stateOf(s.application),rejected=[];for(const key of keys){const intent=s.intents[hash(key)];if(Object.hasOwn(state.turns,key))rejected.push({key,code:"not_host_intent"});else if(!hostIntent(state,key)||!intent)rejected.push({key,code:"unknown_intent"});else if(!intent.conclusion&&intent.phase==="inflight")rejected.push({key,code:"inflight"});}if(rejected.length){const first=rejected[0];const message=first.code==="inflight"?"The intent is in flight: use cancelHostIntent":first.code==="not_host_intent"?"The key is a Bot Turn: use cancelTurn":"No Host intent has this key";throw new HostIntentError(first.key,first.code,message,rejected)}return keys.map(key=>{const intent=s.intents[hash(key)];if(intent.conclusion)return {key,result:"already_settled",conclusion:intent.conclusion};intent.cancelReason="cancelled";settle(s,intent,"cancelled");return {key,result:"cancelled",conclusion:"cancelled"}})})})}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;const result=await this.core.cancel(d.cancel.targetTurnId);if("drainError"in result)throw result.drainError;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);const dispatch="target"in value&&value.admitted?await this.core.cancel(value.target):{};try{if("deliver"in value)await this.settleChain(result);else await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}return {turnId:id,result:"cancelled",...dispatch}}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});try{await this.process();}catch(error){return {...this.topology(deviceId),...error instanceof WakeDispatchError?{wakePending:true}:{drainError:error}}}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);})}
|
|
14
|
+
function inspectLedger(path,tenant){const file=resolve(path),store="bot-collaboration-ledger";const stat=statOrUndefined(file);if(!stat)return {store,path:file,verdict:"absent",reason:"No ledger file at this path"};if(!stat.isFile())return {store,path:file,verdict:"rejected",reason:"The ledger path is not a regular file"};const directory=mkdtempSync(join(tmpdir(),"byok-ledger-check-"));try{const copy=join(directory,basename(file)),suffixes=["","-wal","-journal"];const fingerprint=suffix=>{const s=statOrUndefined(file+suffix);return s&&`${s.size}:${s.mtimeMs}:${s.ino}`};const before=suffixes.map(fingerprint);suffixes.forEach((suffix,i)=>{if(before[i]!==void 0)copyFileSync(file+suffix,copy+suffix);});if(suffixes.some((suffix,i)=>fingerprint(suffix)!==before[i]))throw new Error(`${file} changed while it was being checked; stop its owner and check again`);try{const{DatabaseSync}=process.getBuiltinModule("node:sqlite");const db=new DatabaseSync(copy);try{if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='host_ledger'").get())throw new Error("Not a Host ledger")}finally{db.close();}const ledger=new HostLedger(copy,tenant,botLedgerOptions);try{const state=stateOf(ledger.snapshot().application);refuseUnmigratedWouldDo(state);checkTopology(state);checkSwitchRecords(state);return {store,path:file,verdict:"accepted",reason:"This build opens the ledger"}}finally{ledger.close();}}catch(error){const code=error?.code;return {store,path:file,verdict:"rejected",...typeof code==="string"?{code}:{},reason:error instanceof Error?error.message:String(error)}}}finally{rmSync(directory,{recursive:true,force:true});}}function statOrUndefined(file){try{return statSync(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}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||ledger.formats.k8!==K8_FORMAT)throw new Error("Open the Host ledger with botLedgerOptions");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(),state=stateOf(persisted.application),team=state.team;checkLedgerWouldDo(ledger,state);checkTopology(state);checkSwitchRecords(state);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 state2=stateOf(tx.application);admitBot(state2,run.input.owner);refuseExported(state2);this.commitCallback(state2,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state2,run)});},[BOT_DREAM]:(run,tx)=>{const state2=stateOf(tx.application);admitBot(state2,run.input.owner);refuseExported(state2);recordDream(state2,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),onSettled:()=>this.schedulePass(),admitSubmit:(intent,state2)=>!deviceRefusal(stateOf(state2.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state2),yieldUnclaimed:(state2,intent)=>dreamYield(stateOf(state2.application),intent.key)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state2=stateOf(s.application);if(options.team==="external"){state2.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state2.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(state2,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;passQueued=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};const dispatch=await this.core.cancel(key);try{await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}if(intent.phase==="inflight")return {key,result:"cancel_pending",...dispatch};const conclusion=this.core.intent(key)?.conclusion;return {key,result:"cancelled",...conclusion===void 0?{}:{conclusion},...dispatch}})}cancelHostIntents(keys,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntents",keys.join(" "));const seen=new Set;for(const key of keys){if(seen.has(key))throw new Error(`Duplicate Host intent key: ${key}`);seen.add(key);}return this.write(s=>{const state=stateOf(s.application),rejected=[];for(const key of keys){const intent=s.intents[hash(key)];if(Object.hasOwn(state.turns,key))rejected.push({key,code:"not_host_intent"});else if(!hostIntent(state,key)||!intent)rejected.push({key,code:"unknown_intent"});else if(!intent.conclusion&&intent.phase==="inflight")rejected.push({key,code:"inflight"});}if(rejected.length){const first=rejected[0];const message=first.code==="inflight"?"The intent is in flight: use cancelHostIntent":first.code==="not_host_intent"?"The key is a Bot Turn: use cancelTurn":"No Host intent has this key";throw new HostIntentError(first.key,first.code,message,rejected)}return keys.map(key=>{const intent=s.intents[hash(key)];if(intent.conclusion)return {key,result:"already_settled",conclusion:intent.conclusion};intent.cancelReason="cancelled";settle(s,intent,"cancelled");return {key,result:"cancelled",conclusion:"cancelled"}})})})}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")this.schedulePass();return result}schedulePass(){if(this.closed||this.passQueued)return;this.passQueued=true;queueMicrotask(()=>{void this.exclusive(async()=>{this.passQueued=false;await this.process();}).catch(()=>{});});}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(){let failure;for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;try{const target=this.core.intent(d.cancel.targetTurnId);const result=target&&!target.conclusion?await this.core.cancel(d.cancel.targetTurnId):{};this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});if("drainError"in result)throw result.drainError}catch(error){failure??={error};}}if(failure)throw failure.error}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);const dispatch="target"in value&&value.admitted?await this.core.cancel(value.target):{};try{if("deliver"in value)await this.settleChain(result);else await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}return {turnId:id,result:"cancelled",...dispatch}}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});try{await this.process();}catch(error){return {...this.topology(deviceId),...error instanceof WakeDispatchError?{wakePending:true}:{drainError:error}}}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;const deliveries=this.snapshot().channel?.deliveries??{},superseded=supersededDeliveryIds(deliveries);if(port.readback)for(const old of Object.values(deliveries).filter(row=>row.state==="unknown"&&!superseded.has(row.id))){try{const result=await port.readback(old.id);this.write(s=>{const current=stateOf(s.application).channel?.deliveries??{},row=current[old.id];if(row&&!supersededDeliveryIds(current).has(row.id))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);})}
|
|
16
15
|
|
|
17
16
|
export { BotCollaboration, createBotPersonaProjection, inspectLedger };
|
|
18
17
|
//# sourceMappingURL=index.js.map
|