@byok-sdk/bot-collaboration 0.42.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 +105 -77
- 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 -12
- 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 +25 -6
- package/dist/host-kit.js +8 -4
- package/dist/host-kit.js.map +1 -1
- package/dist/host.d.ts +58 -9
- package/dist/index.d.ts +2 -1
- package/dist/index.js +11 -9
- 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 -3
- package/dist/routines.d.ts +0 -6
- package/dist/rules/autonomy.d.ts +1 -4
- package/dist/rules/delegation.d.ts +19 -6
- 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/store-compatibility.d.ts +3 -0
- package/dist/switch.d.ts +2 -30
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +1 -1
- package/package.json +8 -8
- package/dist/chunk-33YA66U7.js +0 -7
- package/dist/chunk-33YA66U7.js.map +0 -1
- package/dist/chunk-5J5SOWWI.js +0 -12
- package/dist/chunk-5J5SOWWI.js.map +0 -1
- package/dist/chunk-XTZUCECQ.js +0 -12
- package/dist/chunk-XTZUCECQ.js.map +0 -1
- package/dist/chunk-ZUFZCROA.js +0 -27
- package/dist/chunk-ZUFZCROA.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
|
@@ -1,3 +1,23 @@
|
|
|
1
|
+
import { type BotHistoryState, type ContextTurn, type InstructionLimits } from './rules/context.js';
|
|
2
|
+
import { type CheckedOffer, type ContextRoutine, type ContextState } from './rules/schema.js';
|
|
3
|
+
import type { RoomMessage } from './rules/rooms.js';
|
|
4
|
+
import type { Turn } from './rules/turn.js';
|
|
5
|
+
/** Inputs used by sync to freeze a Bot Turn's instruction. */
|
|
6
|
+
export interface BotTurnInstructionOptions<R extends ContextRoutine = ContextRoutine> {
|
|
7
|
+
state: ContextState & BotHistoryState;
|
|
8
|
+
turn: Turn;
|
|
9
|
+
limits: InstructionLimits;
|
|
10
|
+
models: readonly string[];
|
|
11
|
+
routines?: readonly R[];
|
|
12
|
+
injected?: readonly ContextTurn[];
|
|
13
|
+
room?: readonly RoomMessage[];
|
|
14
|
+
offer?: CheckedOffer;
|
|
15
|
+
}
|
|
16
|
+
/** Compute the instruction sync freezes, with the same history, routines and offer. */
|
|
17
|
+
export declare function botTurnInstruction<R extends ContextRoutine>(options: BotTurnInstructionOptions<R>): {
|
|
18
|
+
instruction: string;
|
|
19
|
+
};
|
|
20
|
+
export type { InstructionLimits } from './rules/context.js';
|
|
1
21
|
export { DelegationError, HostIntentError } from './rules/delegation.js';
|
|
2
22
|
export { IntentOutcomeError } from './adapter-steps.js';
|
|
3
23
|
export { RetentionRefused, retainRoots } from './retention.js';
|
|
@@ -14,8 +34,8 @@ export type { CheckedOffer, ConfirmableSpec, MainAction, OutcomeOffer, TurnActio
|
|
|
14
34
|
export type { Card, CollaborationState, Delegation, InputBatch, ReplyEntry, SealReason, Turn, UserInput } from './model.js';
|
|
15
35
|
export { BOT_DREAM, BOT_ROUTINE, botRoutines } from './routines.js';
|
|
16
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';
|
|
17
|
-
export { CommitConflict, commitInLedger,
|
|
18
|
-
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';
|
|
19
39
|
export type { BotRoutine, BotRoutineInput } from './routines.js';
|
|
20
40
|
export type { BotProfile, Room, Round, Seat, TeamState } from './team-model.js';
|
|
21
41
|
export { DEFAULT_MEMBER_MENTIONS, ROOM_GRACE_MS, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, memberMentions, type MemberMentions, type RoomMessage } from './rooms.js';
|
|
@@ -25,16 +45,15 @@ export { inboundDisposition, inboundDispositions, type InboundDisposition, type
|
|
|
25
45
|
export { DEVICE_CONCURRENCY } from './rules/priority.js';
|
|
26
46
|
export { DeviceModeError, type DeviceTopology, type SwitchWork } from './topology.js';
|
|
27
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';
|
|
28
|
-
export { commitImport, discardImport, importForSwitch } from './switch.js';
|
|
29
48
|
export { DeviceSwitchingError, SwitchExportedError, SwitchImportedError, type SwitchReceipt } from './migration.js';
|
|
30
49
|
export { botOutcomePorts, outcomeFailure, routeTerminal, runHostIntentHandler, syncHead, syncTail } from './adapter-steps.js';
|
|
31
50
|
export { isOwner, verified } from './channel.js';
|
|
32
51
|
export { admitUserInput } from './coalesce.js';
|
|
33
|
-
export { acceptDeliveryEcho, readbackDelivery, recoverDelivery, settleDelivery, startDelivery, unknownDelivery } from './delivery.js';
|
|
52
|
+
export { acceptDeliveryEcho, readbackDelivery, recoverDelivery, settleDelivery, startDelivery, supersededDeliveryIds, unknownDelivery } from './delivery.js';
|
|
34
53
|
export { cleanReplyTokens, deliveryRoute, echoCandidates, enablePush, promoteStaged, queueDelivery, refuseRoute, rememberInbound, resendUnknown, revokePush, type IntentConclusions } from './delivery-routing.js';
|
|
35
|
-
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';
|
|
36
55
|
export { exportMarkOf, type SwitchExportMark, type SwitchHeader } from './migration.js';
|
|
37
56
|
export { stateOf } from './model.js';
|
|
38
|
-
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';
|
|
39
58
|
export { sealLedger } from './switch.js';
|
|
40
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,6 +1,10 @@
|
|
|
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
|
-
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-
|
|
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';
|
|
5
|
+
|
|
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}}
|
|
7
|
+
|
|
8
|
+
export { botTurnInstruction2 as botTurnInstruction };
|
|
5
9
|
//# sourceMappingURL=host-kit.js.map
|
|
6
10
|
//# sourceMappingURL=host-kit.js.map
|
package/dist/host-kit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"host-kit.js"}
|
|
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
|
@@ -149,8 +149,14 @@ export interface BotOptions {
|
|
|
149
149
|
export type HostIntentHandler = (document: unknown, transaction: OutcomeTransaction) => void;
|
|
150
150
|
/** Synchronous. A throw rolls the message transaction back, and a thenable or another result throws. */
|
|
151
151
|
export type HostIntentMessageHandler = (input: AgentMessageInput, transaction: MessageTransaction) => MessageDisposition;
|
|
152
|
-
/**
|
|
153
|
-
|
|
152
|
+
/**
|
|
153
|
+
* The cancel answer of a Host intent (K8 `IntentCancelResult`). `conclusion` is optional: an in-flight intent awaits its
|
|
154
|
+
* terminal, and an unsubmitted intent may await a successful drain after a `drainError` or `wakePending` result.
|
|
155
|
+
*/
|
|
156
|
+
export type HostIntentCancelResult = IntentCancelResult<Conclusion> & {
|
|
157
|
+
wakePending?: true;
|
|
158
|
+
drainError?: unknown;
|
|
159
|
+
};
|
|
154
160
|
/** Reply readback port (§3.3). The Host acceptance record stays the body authority. */
|
|
155
161
|
export type MessageServer = {
|
|
156
162
|
tasks: Partial<Pick<ByokServer['tasks'], 'agentMessage'>>;
|
|
@@ -165,6 +171,7 @@ export declare class BotCollaboration {
|
|
|
165
171
|
private chain;
|
|
166
172
|
private timer?;
|
|
167
173
|
private closed;
|
|
174
|
+
private passQueued;
|
|
168
175
|
private readonly now;
|
|
169
176
|
private readonly connectorTimeoutMs;
|
|
170
177
|
private readonly deliveryTimeoutMs;
|
|
@@ -255,12 +262,29 @@ export declare class BotCollaboration {
|
|
|
255
262
|
enqueueHostIntent(input: IntentInput, handler: string): Promise<Intent>;
|
|
256
263
|
/**
|
|
257
264
|
* Owner API (#1320): cancels a Host intent through K4, which records the cancel on the intent row. A settled intent returns
|
|
258
|
-
* `already_settled` and sends nothing, so a replay does not fail. An unsubmitted intent
|
|
259
|
-
*
|
|
265
|
+
* `already_settled` and sends nothing, so a replay does not fail. An unsubmitted intent returns `cancelled` once its cancel
|
|
266
|
+
* commits; `conclusion` is absent if a failed drain or process pass leaves settlement unfinished. A later successful
|
|
267
|
+
* drain settles it without running its handler and advances its FIFO. Replay to read `already_settled` with its conclusion,
|
|
268
|
+
* or `cancel_pending` while a submitted intent awaits its terminal. A submitted intent gets an SDK cancel; a
|
|
260
269
|
* `task.complete` that arrived before the cancel still runs the handler once. A `handler_failed` intent stays stuck,
|
|
261
270
|
* because K4 applies its terminal again: `failStuckIntent` settles it. Refuses a Bot Turn key and an unknown key.
|
|
271
|
+
*
|
|
272
|
+
* After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged
|
|
273
|
+
* first drain or process rejection (the whole AggregateError for mixed failures), even if a later pass succeeds.
|
|
274
|
+
* A drain error comes from that same drain, which coalesces with an in-flight drain and may fail on other Host work.
|
|
275
|
+
* Check `'drainError' in result`, report it and retry pending work with `drain()` or recovery. The cancellation
|
|
276
|
+
* committed; reconciliation may be unfinished. Job/outbox retry state is unchanged; explicit drains and wake hooks
|
|
277
|
+
* still reject. Pre-commit failures still reject.
|
|
262
278
|
*/
|
|
263
279
|
cancelHostIntent(key: string, ...by: PrincipalArg): Promise<HostIntentCancelResult>;
|
|
280
|
+
/**
|
|
281
|
+
* Cancel selected Host intents atomically without a pass. A submitted intent refuses the whole set; after a successful
|
|
282
|
+
* call, successors wait for the next pass, or the Host can call `drain()`. Results keep input order and are replayable.
|
|
283
|
+
*/
|
|
284
|
+
cancelHostIntents(keys: readonly string[], ...by: PrincipalArg): Promise<(IntentCancelResult<Conclusion> & {
|
|
285
|
+
result: 'cancelled' | 'already_settled';
|
|
286
|
+
conclusion: Conclusion;
|
|
287
|
+
})[]>;
|
|
264
288
|
/**
|
|
265
289
|
* Owner API (#882): settles as `failed` an open intent whose K4 terminal K8 refuses with `IntentOutcomeError`, so its FIFO
|
|
266
290
|
* moves on. A fresh K4 drain decides that the intent is stuck, so the call also works right after a restart. One transaction
|
|
@@ -287,11 +311,18 @@ export declare class BotCollaboration {
|
|
|
287
311
|
outcome: 'accepted' | 'refused';
|
|
288
312
|
reasonCode?: string;
|
|
289
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;
|
|
290
320
|
private applyMessage;
|
|
291
321
|
/**
|
|
292
322
|
* Owner API ("Cancel", §8.8), from A's delegation chip or from B's `bot_request` Turn. Idempotent (#1405): an earlier cancel
|
|
293
323
|
* gives `cancel_pending` and a verdict `already_settled`, and neither writes or sends. Refuses with `DelegationError`.
|
|
294
|
-
* It rejects when `core.cancel` fails. The cancel fact is already committed
|
|
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).
|
|
295
326
|
*/
|
|
296
327
|
cancelDelegation(id: string, ...by: PrincipalArg): Promise<DelegationCancelResult>;
|
|
297
328
|
/** Owner API ("End", §8.3): close a held reply or an uncertain delegation with `abandoned`. */
|
|
@@ -303,6 +334,8 @@ export declare class BotCollaboration {
|
|
|
303
334
|
/**
|
|
304
335
|
* Deliver each committed cancel to its frozen target (§8.8). A crash before
|
|
305
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.
|
|
306
339
|
*/
|
|
307
340
|
private deliverCancels;
|
|
308
341
|
/**
|
|
@@ -362,8 +395,16 @@ export declare class BotCollaboration {
|
|
|
362
395
|
* Owner API. Cancels a Turn, an input batch by its id or a member input id, or B's chain Turn through its delegation.
|
|
363
396
|
* Idempotent (#1405): a Turn whose K4 intent already has a cancel gives `cancel_pending`, and an ended Turn
|
|
364
397
|
* `already_settled`; neither writes or calls `core.cancel`.
|
|
365
|
-
|
|
366
|
-
|
|
398
|
+
* After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged
|
|
399
|
+
* first drain rejection (the whole AggregateError for mixed failures), even if a later pass retries it successfully.
|
|
400
|
+
* Its presence means cancellation committed, not that reconciliation finished. Inspect/report it and retry pending
|
|
401
|
+
* work with `drain()` or recovery, rather than repeating the cancellation. Job/outbox retry state is unchanged;
|
|
402
|
+
* explicit drains and wake hooks still reject. Pre-commit failures still reject.
|
|
403
|
+
*/
|
|
404
|
+
cancelTurn(id: string, ...by: PrincipalArg): Promise<TurnCancelResult & {
|
|
405
|
+
wakePending?: true;
|
|
406
|
+
drainError?: unknown;
|
|
407
|
+
}>;
|
|
367
408
|
private cancelOneTurn;
|
|
368
409
|
/** The L owner record of a device (#957, §4.1). A device with no record is L at revision 0. */
|
|
369
410
|
topology(deviceId: string): DeviceTopology;
|
|
@@ -403,8 +444,16 @@ export declare class BotCollaboration {
|
|
|
403
444
|
* A failed export or check: clears the freeze on the frozen revision, so L owns the device again and held Turns run. An
|
|
404
445
|
* abort of a device of the export ends the export, and the new owner discards its import. After the commit every device
|
|
405
446
|
* of the export is owned by H, so none aborts.
|
|
406
|
-
|
|
407
|
-
|
|
447
|
+
* After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged
|
|
448
|
+
* process rejection (the whole AggregateError for mixed failures). Its presence means the abort committed, not that
|
|
449
|
+
* reconciliation finished. Inspect/report it and retry pending work with `drain()` or recovery, rather than repeating
|
|
450
|
+
* the abort with its now-stale revision. Job/outbox retry state is unchanged; explicit drains and wake hooks still
|
|
451
|
+
* reject. A failure may concern other work or already be retried before return. Pre-commit failures still reject.
|
|
452
|
+
*/
|
|
453
|
+
abortSwitch(deviceId: string, expectedRevision: number): Promise<DeviceTopology & {
|
|
454
|
+
wakePending?: true;
|
|
455
|
+
drainError?: unknown;
|
|
456
|
+
}>;
|
|
408
457
|
/**
|
|
409
458
|
* Explicit retention (#798). Moves every row of each acknowledged settled root out of the state, and retires its ids.
|
|
410
459
|
* A root that is still in use throws `RetentionRefused`, and nothing changes. Never runs on its own.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
export { inspectLedger } from './store-compatibility.js';
|
|
1
2
|
export { BotCollaboration } from './host.js';
|
|
2
|
-
export { botCompactVeto } from './compaction.js';
|
|
3
|
+
export { botCompactVeto, botLedgerOptions } from './compaction.js';
|
|
3
4
|
export type { AgentMessageInput, BotOptions, HostIntentCancelResult, HostIntentHandler, HostIntentMessageHandler, MessageServer } from './host.js';
|
|
4
5
|
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot, type TeamModeCode, type TeamSnapshot, type TeamSnapshotBot, type TeamSnapshotRoom } from './rules/team.js';
|
|
5
6
|
export { createBotPersonaProjection } from './persona.js';
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
export { botCompactVeto } from './chunk-
|
|
3
|
-
import { stateOf, verified, routineCalendar, BOT_DREAM, BOT_ROUTINE, routineTurn, applyModels, classifyInbound, inboundKey, isOwner, applyManagement, updateBot, writeSnapshotBot, owned, endable, updateDefinition, ownerRoutineUpdate, botRoutines, homeHead, homeRequests, checkHomeReadback, planHomeRetry, homeEnqueued, applyHomeTerminal, failHomeFlush } from './chunk-
|
|
4
|
-
import { DEVICE_CONCURRENCY, admitDeviceSlot } from './chunk-
|
|
5
|
-
|
|
6
|
-
|
|
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';
|
|
6
|
+
import { mkdtempSync, copyFileSync, rmSync, statSync } from 'fs';
|
|
7
|
+
import { tmpdir } from 'os';
|
|
8
|
+
import { resolve, join, basename } from 'path';
|
|
9
|
+
import { HostLedger, hash, time, HostExecutionCore, isOccurrenceIntentKey, enqueue, WakeDispatchError, settle, project, setLifecycle, canonical } from '@byok-sdk/server/execution-core';
|
|
7
10
|
import { randomUUID } from 'crypto';
|
|
8
11
|
import { buildHandoffPack, ToolsetIdSchema } from '@byok-sdk/protocol';
|
|
9
|
-
import { hash, time, HostExecutionCore, isOccurrenceIntentKey, enqueue, settle, project, setLifecycle, canonical } from '@byok-sdk/server/execution-core';
|
|
10
12
|
import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';
|
|
11
13
|
|
|
12
|
-
function ownReadOnlyToolsets(ids=[]){if(!Array.isArray(ids))throw new Error("readOnlyToolsets must be an array of logical toolset IDs");if(ids.length>64||new Set(ids).size!==ids.length)throw new Error("Invalid read-only toolset policy");for(const id of ids)ToolsetIdSchema.parse(id);return Object.freeze([...ids])}async function flushHomes(server,ledger,now){const busy=botId=>Object.values(ledger.snapshot().intents).some(intent=>!intent.conclusion&&intent.execution.payload.agentRef.agentId===botId);const operation=(s,sequence)=>stateOf(s.application).team.homeOperations.find(o=>o.sequence===sequence);const snapshot=stateOf(ledger.snapshot().application),team=snapshot.team;for(const pending of team.homeOperations.filter(o=>o.status==="pending").sort((a,b)=>a.sequence-b.sequence)){const op=homeHead(team,pending.sequence,busy);if(!op)continue;if(deviceRefusal(snapshot,op.request.deviceId)&&!homeSent(op))continue;try{if(!server.enqueueAgentHomeProjection||!server.readAgentHomeProjection)throw new Error("Home projection API required");let terminal;for(const candidate of homeRequests(op)){terminal=checkHomeReadback(candidate,await server.readAgentHomeProjection(candidate.deviceId,candidate.payload.agentRef,candidate.payload.requestId));if(terminal)break}if(!terminal){const request=ledger.transaction(s=>{if(deviceRefusal(stateOf(s.application),op.request.deviceId))return void 0;const row=operation(s,op.sequence);row.sent=true;return planHomeRetry(row,now())});if(!request)continue;await server.enqueueAgentHomeProjection(request);ledger.transaction(s=>homeEnqueued(operation(s,op.sequence),now()));continue}const settled=terminal;ledger.transaction(s=>applyHomeTerminal(stateOf(s.application),operation(s,op.sequence),settled,(id,value)=>project(s,id,value)));}catch(error){ledger.transaction(s=>failHomeFlush(operation(s,op.sequence),error));}}}function hostIntent(state,key){return state.hostIntents&&Object.hasOwn(state.hostIntents,key)?state.hostIntents[key]:void 0}function openIntent(intents,key){const intent=intents[hash(key)];if(!intent)throw new HostIntentError(key,"unknown_intent",`Unknown intent: ${key}`);if(intent.conclusion)throw new HostIntentError(key,"already_settled",`Intent already settled: ${key}`);return intent}function bounded(read,ms){let timer;const late=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("History read timed out")),Math.max(0,ms));});return Promise.race([read,late]).finally(()=>clearTimeout(timer))}function awaitsOffer(ledger,state,turn){const bot=state.team.bots[turn.botId];return !turn.conclusion&&!turn.held&&!ledger.intents[hash(turn.id)]&&turn.status!=="failed"&&!!bot&&!inactive(bot)&&bot.readyRevision===bot.revision}function dispatchRow(state,row){const execution=state.executions[row.taskId];return {id:row.id,agent:row.agent,sequence:row.sequence,phase:row.phase,attempts:row.attempts,source:row.source,deviceId:row.execution.deviceId,occupies:row.phase==="inflight"&&(execution?.submission==="delivered"||execution?.attempt!==void 0||execution?.started===true)}}function admitCommand(state,command){for(const botId of commandBots(state,command))admitBot(state,botId);}function valueOf(result){if(result.disposition.outcome!=="accepted")throw new Error("Unexpected refused command");return result.disposition.value}function turnOf(result){if(result.disposition.outcome!=="accepted"||typeof result.disposition.value!=="string")throw new Error("Input command has no Turn id");return result.disposition.value}var BotCollaboration=class{constructor(server,ledger,options){this.server=server;this.ledger=ledger;this.options=options;if(!options.botId||options.execution.payload.agentRef.agentId!==options.botId)throw new Error("Select this Bot Agent");if(ledger.compactVeto!==botCompactVeto)throw new Error("Open the Host ledger with { compactVeto: botCompactVeto }");options=this.options={...options,execution:structuredClone(options.execution),...options.models===void 0?{}:{models:structuredClone(options.models)},readOnlyToolsets:ownReadOnlyToolsets(options.readOnlyToolsets)};admitBotToolsets(options.execution,options.readOnlyToolsets);for(const model of Object.values(this.models()))admitBotToolsets(model,options.readOnlyToolsets);const persisted=ledger.snapshot(),team=stateOf(persisted.application).team;checkTopology(stateOf(persisted.application));checkSwitchRecords(stateOf(persisted.application));if(options.team==="external"?!team.external&&Object.keys(team.bots).length:team.external){throw new Error(`This ledger has ${team.external?"an external":"a local"} team`)}if(options.persona!==void 0&&(options.persona!=="external"||options.team!=="external")){throw new Error("The Host persona mode needs team: 'external'")}if(team.external&&!!team.external.persona!==(options.persona==="external")){throw new Error(`This ledger has ${team.external.persona?"Host":"K8"} persona projections`)}if(options.rooms!==void 0&&(options.rooms!=="external"||options.team!=="external")){throw new Error("The external rooms mode needs team: 'external'")}if(team.external&&!!team.external.rooms!==(options.rooms==="external")){throw new Error(`This ledger has ${team.external.rooms?"external":"local"} rooms`)}for(const intent of Object.values(persisted.intents)){if(intent.conclusion)continue;admitBotToolsets(intent.execution,options.readOnlyToolsets);const execution=persisted.executions[intent.taskId];if(execution)admitBotToolsets(execution.input,options.readOnlyToolsets);}this.hostIntentHandlers=new Map(Object.entries(options.hostIntents??{}));this.hostIntentMessageHandlers=new Map(Object.entries(options.hostIntentMessages??{}));for(const name of this.hostIntentMessageHandlers.keys()){if(!this.hostIntentHandlers.has(name))throw new Error(`A Host intent message handler needs the Host intent handler ${name}`)}for(const[key,{handler}]of Object.entries(stateOf(persisted.application).hostIntents??{})){const intent=persisted.intents[hash(key)];if(intent&&intent.conclusion===void 0&&!this.hostIntentHandlers.has(handler)){throw new Error(`An open Host intent needs the handler ${handler}`)}if(intent&&intent.conclusion===void 0&&intent.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`An open Host intent needs the message handler ${handler}`)}}this.owner={id:options.owner??"owner",kind:"human"};if(!verified(this.owner))throw new Error("Invalid owner principal");this.now=()=>time((options.now??Date.now)());this.connectorTimeoutMs=time(options.connectorTimeoutMs??3e4);if(this.connectorTimeoutMs<1||this.connectorTimeoutMs>2147483647)throw new Error("Invalid connector timeout");this.deliveryTimeoutMs=time(options.channel?.sendTimeoutMs??15e3);if(this.deliveryTimeoutMs<1||this.deliveryTimeoutMs>2147483647)throw new Error("Invalid delivery timeout");this.historyTimeoutMs=time(options.historyTimeoutMs??1e4);if(this.historyTimeoutMs<1||this.historyTimeoutMs>2147483647)throw new Error("Invalid history timeout");this.contextMaxBytes=time(options.contextMaxBytes??HISTORY_MAX_BYTES);this.contextTurnLimit=time(options.contextTurnLimit??HISTORY_MAX_ITEMS);if(this.contextMaxBytes<1||this.contextTurnLimit<1)throw new Error("Invalid ContextPack limits");this.handoff=options.handoff??DEFAULT_HANDOFF_BUDGETS;buildHandoffPack([],this.handoff);if(options.coalesce)this.coalesce=coalescePolicy(options.coalesce,this.contextMaxBytes);this.offer=outcomeOffer(options.outcome??{});outcomeSchema(options.botId,stateOf({}),void 0,Object.keys(this.models()),[],this.offer);this.instructionMaxBytes=time(options.instructionMaxBytes??DEFAULT_INSTRUCTION_MAX_BYTES);const minimum=minimumInstructionBytes(SYSTEM_PROMPT);if(this.instructionMaxBytes<minimum)throw new Error(`instructionMaxBytes must be at least ${minimum}`);this.dreaming=dreamPolicy(options.dreaming);if(this.dreaming)checkDreamInstruction(this.instructionMaxBytes);this.timers={cancelGraceMs:time(options.cancelGraceMs??DEFAULT_CANCEL_GRACE_MS),uncertainAfterMs:time(options.uncertainAfterMs??REPLY_UNCERTAIN_AFTER_MS)};if(this.timers.cancelGraceMs<1||this.timers.uncertainAfterMs<1)throw new Error("Invalid delegation timers");this.deviceConcurrency=time(options.deviceConcurrency??DEVICE_CONCURRENCY);if(this.deviceConcurrency<1)throw new Error("Invalid device concurrency");this.core=new HostExecutionCore(server,ledger,{now:this.now,reconcileMs:options.reconcileMs??100,nextOccurrence:routineCalendar,hostJobExecution:"fail",executionRoutines:"refuse",...options.hostJobs?{hostJobs:options.hostJobs}:{},...options.onOutbox?{onOutbox:options.onOutbox}:{},occurrenceHooks:{[BOT_ROUTINE]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);this.commitCallback(state,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state,run)});},[BOT_DREAM]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);recordDream(state,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),admitSubmit:(intent,state)=>!deviceRefusal(stateOf(state.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state=stateOf(s.application);if(options.team==="external"){state.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state.team.bots[options.botId]??={id:options.botId,name:"Main Bot",role:"Team owner",persona:"",model:Object.keys(this.models())[0],mainBot:true,archived:false,autonomy:DEFAULT_AUTONOMY,revision:options.execution.payload.agentRef.profileRevision,readyRevision:options.execution.payload.agentRef.profileRevision,execution:structuredClone(options.execution)};}applyModels(state,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;now;connectorTimeoutMs;deliveryTimeoutMs;historyTimeoutMs;contextMaxBytes;contextTurnLimit;handoff;dreaming;instructionMaxBytes;deviceConcurrency;timers;coalesce;offer;owner;unread=new Set;hostIntentHandlers;hostIntentMessageHandlers;intentFailures=new Map;auditedFailures=new Map;models(){return this.options.models??{default:this.options.execution}}setModels(models){return this.exclusive(async()=>{const next=structuredClone(models);outcomeSchema(this.options.botId,stateOf({}),void 0,Object.keys(next),[],this.offer);this.write(s=>applyModels(stateOf(s.application),next,this.options.readOnlyToolsets??[]));this.options.models=next;await this.process();})}snapshot(){return stateOf(this.ledger.snapshot().application)}write(apply){return writeLedger(this.ledger,apply)}exclusive(work){if(this.closed)return Promise.reject(new Error("Bot Host is closed"));const next=this.chain.then(work);this.chain=next.catch(()=>{});return next}input(key,request,botId=this.options.botId,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"input",botId);const result=this.commitOwner(hash(["input",botId,key]),{kind:"input",botId,key,request,sender:principal.id});await this.process();return turnOf(result)})}inputRoot(key,botId=this.options.botId){const id=hash(["input",botId,key]),commands=stateOf(this.ledger.snapshot().application).commands;const record=commands&&Object.hasOwn(commands,id)?commands[id]:this.ledger.transaction((_,rows)=>rows.get("commands",id));return record&&turnOf(record.result)}async receive(message){if(this.closed)throw new Error("Bot Host is closed");const kind=classifyInbound(message,this.owner.id,this.options.channel?.self),{channel,conversation,platformMessageId,sender}=message;if(kind==="echo"){this.write(s=>{const state=stateOf(s.application),matches=echoCandidates(state,message);if(matches.length!==1||!acceptDeliveryEcho(matches[0],platformMessageId))state.audit.push(`Delivery unmatched_echo: ${channel} ${platformMessageId}`.slice(0,1024));cleanReplyTokens(s,state,this.now());});return {kind}}if(kind==="owner_input"||kind==="room_input")return this.exclusive(async()=>{const principal=kind==="owner_input"?this.ownerOnly([sender],"input",conversation.id):this.verifiedOnly(sender,"roomInput",conversation.id);const key=inboundKey(message);const command=kind==="owner_input"?{kind:"receive",inbound:kind,key,botId:conversation.id,request:message.text,sender:principal.id}:{kind:"receive",inbound:kind,key,roomId:conversation.id,text:message.text,mentions:this.seatMentions(conversation.id,principal,message.mentions),from:principal.id};const result=this.commitOwner(hash(["receive",key]),command,(_s,state)=>({remember:root=>rememberInbound(state,message,root)}));await this.process();return {kind,id:turnOf(result)}});if(kind==="bot_background"){return {kind,id:await this.roomInput(inboundKey(message),conversation.id,message.text,message.mentions,sender)}}const who=verified(sender)?` ${sender.kind}:${sender.id}`:"";const filtered=kind==="unverified_sender"||kind==="not_owner"?kind:void 0;await this.exclusive(async()=>this.write(s=>{const state=stateOf(s.application);if(filtered)rememberFilteredInbound(state,message,filtered);state.audit.push(`Inbound ${kind}: ${channel} ${conversation.kind}:${conversation.id} ${platformMessageId}${who}`.slice(0,1024));}));return {kind}}enablePushRoute(conversation,channel,target,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"enablePushRoute",conversation.id);if(!this.options.channel)throw new Error("Channel is not configured");return valueOf(this.commitKeyless({kind:"enable_push_route",conversation,channel,target,owner:principal.id}))})}revokePushRoute(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"revokePushRoute",id);this.commitKeyless({kind:"revoke_push_route",routeId:id});await this.process();})}resendDelivery(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"resendDelivery",id);if(!this.options.channel)throw new Error("Channel is not configured");const next=valueOf(this.commitKeyless({kind:"resend_delivery",deliveryId:id}));await this.process();return next})}audit(line){this.write(s=>{stateOf(s.application).audit.push(line.slice(0,1024));});}verifiedOnly(principal,action,target){if(verified(principal))return principal;this.audit(`Action refused unverified_sender: ${action} ${target}`);throw new Error(`unverified_sender: ${action} needs a verified principal`)}seatMentions(roomId,principal,mentions){if(!principal||isOwner(principal,this.owner.id))return mentions;if(principal.kind==="bot")return [];const room=this.snapshot().team.rooms[roomId];return room&&memberMentions(room)==="ignore"?[]:mentions}ownerOnly(by,action,target){const principal=this.verifiedOnly(by.length?by[0]:this.owner,action,target);if(isOwner(principal,this.owner.id))return principal;this.audit(`Action refused not_owner: ${action} ${target} ${principal.kind}:${principal.id}`);throw new Error(`not_owner: ${action} needs the owner principal`)}applyOutcome(document,tx){const state=stateOf(tx.application),taskId=tx.intent.taskId,key=tx.intent.key;refuseExported(state);try{const route=routeTerminal(state,key,hostIntent(state,key)?.handler);if(route.kind==="host_intent")runHostIntentHandler(key,route.handler,this.hostIntentHandlers.get(route.handler)?.bind(null,document,tx));else if(route.kind==="bot_turn"){try{this.commitBotOutcome(state,key,taskId,document,tx);}catch(cause){throw outcomeFailure(key,cause)}}}catch(error){if(error instanceof IntentOutcomeError)this.intentFailures.set(key,error);throw error}}commitBotOutcome(state,key,taskId,document,tx){this.commitCallback(state,tx.rows,taskId,{kind:"outcome",turnId:key,taskId,document},{publish:tx.publish,...this.deliverPort(state,taskId),outcome:{committed:{intent:key2=>intentRows(this.ledger.snapshot()).intent(key2)},...botOutcomePorts({taskId,routines:tx.routines,roomPosts:!!this.options.roomHistory,manage:(turn,outcome,managed)=>applyManagement(state,turn.botId,taskId,outcome,this.models(),managed,this.options.readOnlyToolsets)})}});}reportIntentFailures(){const failures=[...this.intentFailures.values()],fresh=failures.filter(f=>this.auditedFailures.get(f.key)!==f.message);if(fresh.length){this.write(s=>{const state=stateOf(s.application);for(const f of fresh)state.audit.push(`Intent outcome refused ${f.code}: ${f.key} ${f.message}`.slice(0,1024));});for(const f of fresh)this.auditedFailures.set(f.key,f.message);}return failures[0]}enqueueHostIntent(input,handler){return this.exclusive(async()=>{if(!this.hostIntentHandlers.has(handler))throw new Error(`Unknown Host intent handler: ${handler}`);if(isOccurrenceIntentKey(input.key))throw new Error("Host intent identity conflict: the key is an occurrence");if(input.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`Host intent handler ${handler} has no message handler`)}admitBotToolsets(input.execution,this.options.readOnlyToolsets);this.write(s=>{const state=stateOf(s.application),owner=hostIntent(state,input.key);if(Object.hasOwn(state.turns,input.key))throw new Error("Host intent identity conflict: the key is a Bot Turn");if(owner?owner.handler!==handler:s.intents[hash(input.key)])throw new Error("Host intent identity conflict");if(!owner)admitDevice(state,input.execution.deviceId);enqueue(s,this.ledger.tenant,input);Object.defineProperty(state.hostIntents??={},input.key,{value:{handler},enumerable:true,writable:true,configurable:true});});await this.process();return this.core.intent(input.key)})}cancelHostIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntent",key);const snapshot=this.ledger.snapshot(),state=stateOf(snapshot.application),intent=snapshot.intents[hash(key)];const settled=hostIntentCancelAnswer(key,Object.hasOwn(state.turns,key),hostIntent(state,key)&&intent);if(settled)return {key,...settled};await this.core.cancel(key);await this.process();if(intent.phase==="inflight")return {key,result:"cancel_pending"};return {key,result:"cancelled",conclusion:this.core.intent(key).conclusion}})}failStuckIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"failStuckIntent",key);openIntent(this.ledger.snapshot().intents,key);this.intentFailures.clear();const drained=await this.core.drain().then(()=>void 0,error=>({error}));const refused=this.intentFailures.get(key);this.write(s=>{const intent=openIntent(s.intents,key);if(!refused)throw drained?drained.error:new HostIntentError(key,"not_stuck",`Intent is not stuck: ${key} has no refused terminal`);settle(s,intent,"failed");if(refused.code==="outcome_failed")stateOf(s.application).turns[key].settleCode=refused.code;stateOf(s.application).audit.push(`Intent failed by owner ${refused.code}: ${key} ${refused.message}`.slice(0,1024));});this.intentFailures.delete(key);this.auditedFailures.delete(key);await this.process();})}deliverPort(state,taskId){if(!this.options.channel)return {};return {deliver:(turn,key,text,staged)=>queueDelivery(this.ledger.snapshot(),state,turn,taskId,key,text,this.now(),staged)?.id,promote:id=>promoteStaged(state,id)}}commitOwner(commandId,command,extra){return commitInLedger(this.ledger,{scope:this.ledger.tenant,commandId,command},s=>{const state=stateOf(s.application);return {now:this.now,admit:next=>admitCommand(state,next),publish:(key,value)=>project(s,key,value),intents:intentRows(s),admitInput:fields=>admitUserInput(state,fields,this.coalesce,this.now()),updatePersona:(botId,persona)=>updateBot(state,{botId,persona},this.models(),this.options.readOnlyToolsets),routes:{enable:(conversation,channel,target,owner)=>enablePush(state,conversation,channel,target,owner,this.now()).id,revoke:routeId=>revokePush(state,routeId,this.now()),resend:deliveryId=>resendUnknown(state,deliveryId,this.now()).id},...extra?.(s,state)}})}commitKeyless(command){return this.commitOwner(randomUUID(),command)}commitCallback(state,rows,commandId,command,ports){return commitInRows(state,this.ledger.tenant,{scope:this.ledger.tenant,commandId,command},rows,{now:this.now,...ports})}async consumeMessage(input){if(this.closed)throw new Error("Bot Host is closed");refuseExported(this.snapshot());const result=await this.core.consumeMessage(input);if(result.outcome==="accepted")queueMicrotask(()=>{if(!this.closed)void this.drain().catch(()=>{});});return result}applyMessage(input,tx){const state=stateOf(tx.application);refuseExported(state);const name=hostIntent(state,tx.intent.key)?.handler,handler=name===void 0?void 0:this.hostIntentMessageHandlers.get(name);let disposition;try{({disposition}=this.commitCallback(state,tx.rows,`${input.taskId}:${input.payload.messageId}`,{kind:"message",turnId:tx.intent.key,message:{taskId:input.taskId,payload:input.payload}},{publish:tx.publish,...this.deliverPort(state,input.taskId),...handler?{hostMessage:()=>hostMessageDisposition(handler(input,tx))}:{}}));}catch(cause){if(cause instanceof CommitConflict&&cause.code==="identity_conflict")return {outcome:"refused",reasonCode:"message_conflict"};throw cause}return disposition.outcome==="accepted"?{outcome:"accepted"}:{outcome:"refused",reasonCode:disposition.reasonCode}}cancelDelegation(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelDelegation",id);const settled=delegationCancelAnswer(this.snapshot(),id);if(settled)return {delegationId:id,...settled};await this.settleChain(this.commitKeyless({kind:"cancel_delegation",delegationId:id}));return {delegationId:id,result:"cancelled"}})}abandonDelegation(id,...by){return this.exclusive(()=>{this.ownerOnly(by,"abandonDelegation",id);return this.settleChain(this.commitKeyless({kind:"abandon_delegation",delegationId:id}))})}async settleChain(result){if(valueOf(result).deliver)await this.deliverCancels();await this.process();}admitsDeviceSlot(intent,state){const rows=Object.values(state.intents).map(row=>dispatchRow(state,row));return admitDeviceSlot(rows.find(row=>row.id===intent.id)??dispatchRow(state,intent),rows,this.deviceConcurrency)}async deliverCancels(){for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;await this.core.cancel(d.cancel.targetTurnId);this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});}}async personaReady(botId,revision){await this.exclusive(async()=>{this.commitKeyless({kind:"persona_ready",botId,revision});await this.process();});}async retryPersona(botId){await this.exclusive(async()=>{this.commitKeyless({kind:"retry_persona",botId});await this.process();});}async applyTeam(snapshot){await this.exclusive(async()=>{const valid=teamSnapshot(snapshot);const{disposition}=this.commitOwner(hash(["team",valid.revision]),{kind:"team_snapshot",snapshot:valid},(_s,state)=>({teamBot:row=>writeSnapshotBot(state,row,this.models(),this.options.readOnlyToolsets)}));await this.process();if(disposition.outcome==="refused")throw new TeamModeError("stale_team",disposition.reason??"stale_team")});}async setMainBot(botId,mainBot){await this.exclusive(async()=>{this.commitKeyless({kind:"set_main_bot",botId,mainBot});await this.process();});}autonomy(botId){const bots=this.snapshot().team.bots,bot=Object.hasOwn(bots,botId)?bots[botId]:void 0;if(!bot)throw new Error("Bot not found");return autonomyOf(bot)}wouldDoRecords(botId){return wouldDoRows(this.snapshot(),botId)}inboundDispositions(){return inboundDispositionsOf(this.snapshot())}setBotAutonomy(botId,autonomy,...by){return this.exclusive(async()=>{this.ownerOnly(by,"setBotAutonomy",botId);if(autonomy!=="observe"&&autonomy!=="auto")throw new Error("Invalid autonomy");this.commitKeyless({kind:"set_autonomy",botId,autonomy});await this.process();})}async roomInput(key,roomId,text,mentions=[],...by){let id;await this.exclusive(async()=>{const principal=by.length?this.verifiedOnly(by[0],"roomInput",roomId):void 0;const called=this.seatMentions(roomId,principal,mentions);const result=this.commitOwner(hash(["room_input",roomId,key]),{kind:"room_input",key,roomId,text,mentions:called,...principal?{from:principal.id}:{}});id=turnOf(result);await this.process();});return id}async setMemberMentions(roomId,value,...by){await this.exclusive(async()=>{this.ownerOnly(by,"setMemberMentions",roomId);this.commitKeyless({kind:"set_room_member_mentions",roomId,memberMentions:value});await this.process();});}async createRoom(roomId,fields){await this.exclusive(async()=>{this.commitOwner(hash(["create_room",roomId]),{kind:"create_room",roomId,fields});await this.process();});}async updateRoom(roomId,update){await this.exclusive(async()=>{this.commitKeyless({kind:"update_room",roomId,update});await this.process();});}async answer(id,answer,...by){await this.exclusive(async()=>{this.ownerOnly(by,"answer",id);this.commitOwner(hash(["answer",id]),{kind:"answer",questionId:id,answer});await this.process();});}async decide(id,decision,...by){await this.exclusive(async()=>{this.ownerOnly(by,"decide",id);let error;try{const{disposition}=this.commitOwner(hash(["decide",id]),{kind:"decide",cardId:id,decision});if(disposition.outcome==="refused")error=disposition.reason;}catch(cause){if(!(cause instanceof CommitConflict)||cause.code!=="identity_conflict")throw cause;error=cause.message;}await this.process();if(error)throw new Error(error)});}async setRoutineLifecycle(id,value){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.lifecycle(owned(this.routineRows(),this.options.botId,id).definition.id,value);}finally{await this.process();}});}async endRoutine(id){await this.exclusive(async()=>{try{this.commitOwner(randomUUID(),{kind:"end_routine",botId:this.options.botId,routineId:id},s=>({routines:{end:routineId=>setLifecycle(s,endable(Object.values(s.routines),routineId).definition.id,"completed",this.now(),routineCalendar)}}));}finally{await this.process();}});}async updateRoutine(action){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.updateRoutine(updateDefinition(this.routineRows(),this.options.botId,ownerRoutineUpdate(action)));}finally{await this.process();}});}routineRows(){return Object.values(this.ledger.snapshot().routines)}consume=(wake,signal)=>this.exclusive(async()=>{signal.throwIfAborted();this.write((s,rows)=>{this.sync(s,rows);});try{await this.core.consume(wake,signal);}finally{await this.process();}});drain(){return this.exclusive(()=>this.process())}cancelTurn(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelTurn",id);return this.cancelOneTurn(id)})}async cancelOneTurn(id){const snapshot=this.ledger.snapshot(),settled=turnCancelAnswer(stateOf(snapshot.application),intentRows(snapshot),id);if(settled)return {turnId:id,...settled};const result=this.commitKeyless({kind:"cancel_turn",turnId:id});const value=valueOf(result);if("deliver"in value)await this.settleChain(result);else {if(value.admitted)await this.core.cancel(value.target);await this.process();}return {turnId:id,result:"cancelled"}}topology(deviceId){return deviceTopology(this.snapshot(),deviceId)}freezeForSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.write(s=>switchStep(s,deviceId,expectedRevision,"freeze"));return this.topology(deviceId)})}drainForSwitch(deviceId,{cancel=false}={}){return this.exclusive(async()=>{const work=this.write(s=>{if(!deviceTopology(stateOf(s.application),deviceId).switching)throw new Error(`Device ${deviceId} is not switching`);const open=switchWork(s,deviceId);if(cancel)for(const key of open.intents)s.intents[hash(key)].cancelReason??="cancelled";return open});if(cancel){for(const id of [...work.batches,...work.turns])await this.cancelOneTurn(id);await this.process();}return switchWork(this.ledger.snapshot(),deviceId)})}exportForSwitch(devices,exportedAt=this.now()){return this.exclusive(async()=>{const state=this.snapshot();refuseExported(state);for(const{deviceId,expectedRevision}of devices){const row=deviceTopology(state,deviceId);if(row.revision!==expectedRevision){throw new CommitConflict("stale_revision",`Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`)}if(row.mode!=="L")throw new DeviceModeError(deviceId,row.mode,row.revision);if(!row.switching)throw new Error(`Device ${deviceId} is not switching`);if(!switchDrained(switchWork(this.ledger.snapshot(),deviceId)))throw new Error(`Device ${deviceId} still has open work`)}const header={source:"L",domain:this.ledger.tenant,exportedAt,devices:devices.map(({deviceId,expectedRevision})=>({deviceId,frozenRevision:expectedRevision}))};const dump=this.ledger.dumpForSwitch();const job=Object.values(dump.body.outbox).find(row=>row.kind==="host-job");if(job)throw new SwitchExportError("open_work",`Switch export source: Host job ${job.occurrenceKey} is pending; let it run first`);const document=sealSwitchExport(switchContent(dump,this.ledger.tenant,header));this.ledger.transaction(s=>{stateOf(s.application).switchExport={digest:document.manifest.digest,exportedAt,devices:document.devices.map(device=>({...device}))};});return document})}commitSwitch(deviceId,expectedRevision,receipt){return this.exclusive(async()=>{switchStep(structuredClone(this.ledger.snapshot()),deviceId,expectedRevision,"commit");const mark=this.snapshot().switchExport;if(!mark)throw new Error("This Host has not exported its domain for a switch");if(mark.digest!==receipt)throw new Error(`The receipt ${receipt} is not this Host's export ${mark.digest}`);if(!mark.devices.some(device=>device.deviceId===deviceId&&device.frozenRevision===expectedRevision)){throw new Error(`Device ${deviceId} at revision ${expectedRevision} is not a device of the export`)}const now=sealLedger(this.ledger,{source:"L",domain:this.ledger.tenant,devices:mark.devices,exportedAt:mark.exportedAt});if(now.manifest.digest!==mark.digest)throw new Error(`The ledger changed after its export: ${now.manifest.digest}, not ${mark.digest}`);this.ledger.transaction(s=>{for(const device of mark.devices)switchStep(s,device.deviceId,device.frozenRevision,"commit");});return this.topology(deviceId)})}abortSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.ledger.transaction(s=>{const state=stateOf(s.application),step=switchStep(s,deviceId,expectedRevision,"abort");if(state.switchExport?.devices.some(device=>device.deviceId===deviceId))delete state.switchExport;return step});await this.process();return this.topology(deviceId)})}retain(input){return this.exclusive(async()=>retainInLedger(this.ledger,input,{contextTurnLimit:this.contextTurnLimit,handoff:this.handoff}))}recover(){return this.exclusive(async()=>{this.write((s,rows)=>{for(const row of Object.values(stateOf(s.application).channel?.deliveries??{}))recoverDelivery(row);this.sync(s,rows);});try{await this.core.recover();}finally{await this.process();}})}sync(s,rows,injected){const state=stateOf(s.application);for(const key of Object.keys(state.hostIntents??{})){if(s.intents[hash(key)])continue;delete state.hostIntents[key];for(const[taskId,reply]of Object.entries(state.replies))if(reply.turnId===key)delete state.replies[taskId];}syncHead(state,this.coalesce,this.now());reconcileDreamRoutines(s,this.dreaming,this.models(),this.now());const routines=botRoutines(Object.values(s.routines));const limits={turnLimit:this.contextTurnLimit,contextMaxBytes:this.contextMaxBytes,instructionMaxBytes:this.instructionMaxBytes,handoff:this.handoff};const materialized=advanceRoomsAndTurns(s,state,this.now(),turn=>syncTurnInLedger(this.ledger,s,rows,turn,{now:this.now(),models:Object.keys(this.models()),readOnlyToolsets:this.options.readOnlyToolsets??[],limits,historyMode:!!this.options.history,history:injected?.turns.get(turn.id),roomHistoryMode:!!this.options.roomHistory,roomHistory:injected?.rooms.get(turn.id),routines,offer:this.offer}),(key,value)=>project(s,key,value));const dreamed=syncDreams(s,{tenant:this.ledger.tenant,policy:this.dreaming,models:this.models(),instructionMaxBytes:this.instructionMaxBytes,now:this.now(),refused:botId=>botDeviceRefusal(state,botId)!==void 0,history:injected?.dreams,historyMode:!!this.options.history});settleDelegations(s,state,this.now(),(key,value)=>project(s,key,value),this.timers);reportCardDecisions(state,(key,value)=>project(s,key,value));syncTail(state,s,this.now(),(key,value)=>project(s,key,value));return materialized||dreamed}async flushReplies(){for(const d of Object.values(this.snapshot().delegations)){if(!replyCheckDue(d,this.now()))continue;const intent=this.core.intent(d.chainTurnIds.at(-1));let check={failed:true};if(intent)try{if(!this.server.tasks.agentMessage)throw new Error("Agent message readback API required");check={taskId:intent.taskId,failed:false,readback:await this.server.tasks.agentMessage(intent.taskId,intent.execution.deviceId,intent.execution.payload.agentRef)};}catch{check={taskId:intent.taskId,failed:true};}this.write(s=>{const state=stateOf(s.application);checkReply(state,state.delegations[d.id],check,this.now(),(key,value)=>project(s,key,value),this.timers.uncertainAfterMs);});}}async callConnector(card){const controller=new AbortController;let timer;const deadline=new Promise((_,reject)=>{timer=setTimeout(()=>{const error=new Error(CONNECTOR_OUTCOME_UNKNOWN);controller.abort(error);reject(error);},this.connectorTimeoutMs);});try{return await Promise.race([Promise.resolve().then(()=>this.options.connector(card.id,card.action.action,card.action.draft,controller.signal)),deadline])}finally{clearTimeout(timer);}}async flushCards(){await callCardsInLedger(this.ledger,card=>this.callConnector(card));}async flushDeliveries(){const port=this.options.channel?.port;if(!port)return;if(port.readback)for(const old of Object.values(this.snapshot().channel?.deliveries??{}).filter(row=>row.state==="unknown")){try{const result=await port.readback(old.id);this.write(s=>{const row=stateOf(s.application).channel?.deliveries[old.id];if(row)readbackDelivery(row,old.attempts,result,this.now());});}catch{continue}}for(const old of Object.values(this.snapshot().channel?.deliveries??{})){const claim=this.write(s=>{const state=stateOf(s.application),row=state.channel.deliveries[old.id];if(row.state!=="pending"||(row.nextAttemptAt??0)>this.now())return;const route=deliveryRoute(state,row,this.now());if(!route){refuseRoute(state,row);return}if(startDelivery(row,this.now()))return {row,route}});if(!claim)continue;const controller=new AbortController;let timer;const deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>{controller.abort();reject(new Error("delivery_timeout"));},this.deliveryTimeoutMs);});try{const result=await Promise.race([Promise.resolve().then(()=>port.send({deliveryId:claim.row.id,route:claim.route,body:claim.row.body},controller.signal)),deadline]);this.write(s=>settleDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,result,this.now()));}catch{this.write(s=>unknownDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,controller.signal.aborted?"send_timeout":"send_failed"));}finally{clearTimeout(timer);}}this.write(s=>cleanReplyTokens(s,stateOf(s.application),this.now()));}async syncWithHistory(){const injected=await this.readHistory();return this.write((s,rows)=>this.sync(s,rows,injected))}async readHistory(){const read=this.options.history,readRoom=this.options.roomHistory;if(!read&&!readRoom)return void 0;const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const injected={turns:new Map,rooms:new Map,dreams:new Map};for(const turn of Object.values(state.turns)){if(!awaitsOffer(ledger,state,turn)||this.unread.has(turn.id))continue;const seat=turn.source==="room_slot"?state.team.seats[turn.id]:void 0;try{if(seat&&readRoom&&!seat.released){const roomId=state.team.rounds[seat.roundId].roomId;if(Object.values(ledger.outbox).some(row=>row.kind==="projection"&&row.id.startsWith(roomMessageProjection(roomId,""))&&row.value.roomId===roomId)){this.unread.add(turn.id);continue}const ms=Math.min(this.historyTimeoutMs,seat.deadline===void 0?Infinity:seat.deadline-this.now());const rows=roomMessages(await bounded(readRoom({roomId,botId:turn.botId,turnId:turn.id}),ms));injected.rooms.set(turn.id,{rows,digest:hash(canonical(rows))});}else if(turn.source!=="room_slot"&&read){const rows=contextTurns(await bounded(read({botId:turn.botId,turnId:turn.id}),this.historyTimeoutMs));injected.turns.set(turn.id,{rows,digest:hash(canonical(rows))});}}catch{this.unread.add(turn.id);}}if(read)for(const{key,botId,turnId}of dreamReads(state)){injected.dreams.set(key,await bounded(read({botId,turnId}),this.historyTimeoutMs).then(contextTurns).catch(()=>null));}return injected}async process(){try{await this.pass();}finally{this.armTimer();}}async pass(){if(this.snapshot().switchExport)return;this.unread.clear();let failure;let more;do{await this.deliverCancels().catch(()=>{});const admitted=await this.syncWithHistory();await flushHomes(this.server,this.ledger,this.now);this.intentFailures.clear();try{await this.core.drain();}catch(error){failure??={error};}const refused=this.reportIntentFailures();if(refused)failure??={error:refused};await this.deliverCancels().catch(()=>{});let materialized=await this.syncWithHistory();await this.refreshDevices();await this.flushCards();materialized=await this.syncWithHistory()||materialized;await this.flushReplies();materialized=await this.syncWithHistory()||materialized;await this.flushDeliveries();const ledger=this.ledger.snapshot();const state=stateOf(ledger.application);more=admitted||materialized||Object.values(ledger.intents).some(intent=>intent.phase==="queued"&&intent.cancelReason&&!intent.conclusion)||Object.values(state.turns).some(turn=>turn.status!=="blocked"&&awaitsOffer(ledger,state,turn)&&!this.unread.has(turn.id));}while(more&&!failure);if(failure)throw failure.error}armTimer(){clearTimeout(this.timer);if(!this.closed&&!this.snapshot().switchExport){const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const due=[...this.options.channel?Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="pending").map(row=>row.nextAttemptAt??this.now()):[],...Object.values(state.channel?.inbounds??{}).filter(row=>row.reply?.token).map(row=>row.reply.expiresAt),...collaborationDue(state,this.timers),...state.team.homeOperations.filter(op=>op.status==="pending"&&(homeSent(op)||!deviceRefusal(state,op.request.deviceId))).map(op=>Math.max(this.now()+1e3,op.retryAt??0)),...Object.values(state.delegations).filter(d=>d.cancel&&!d.cancel.delivered).map(()=>this.now()+1e3),...this.unread.size?[this.now()+1e3]:[]];if(due.length){this.timer=setTimeout(()=>{void this.drain().catch(()=>{});},Math.max(1,Math.min(6e4,Math.min(...due)-this.now())));this.timer.unref?.();}}}async refreshDevices(){if(!this.server.machines)return;if(!Object.values(this.snapshot().delegations).some(d=>!d.verdict&&!d.cancel&&(d.status==="queued"||d.status==="waiting_device")))return;let devices;let timer;try{devices=await Promise.race([this.server.machines.list(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("Device discovery timed out")),1e3);})]);}catch{return}finally{clearTimeout(timer);}this.write(s=>observeDevices(s,stateOf(s.application),new Map(devices.map(d=>[d.deviceId,d.connected])),(key,value)=>project(s,key,value)));}async close(){this.closed=true;clearTimeout(this.timer);await this.chain;clearTimeout(this.timer);await this.core.close();}};function createBotPersonaProjection(){return createAgentHomeProjectionConsumer(async({projection,projectionHash,writeHomeFile})=>{if(!projection||typeof projection!=="object"||!("schemaVersion"in projection)||projection.schemaVersion!=="bot-profile.v1"||!("persona"in projection)||typeof projection.persona!=="string"||projectionHash!==`sha256:${hash(projection)}`)throw new Error("Invalid Bot persona projection");await writeHomeFile("AGENTS.md",projection.persona);})}
|
|
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);})}
|
|
13
15
|
|
|
14
|
-
export { BotCollaboration, createBotPersonaProjection };
|
|
16
|
+
export { BotCollaboration, createBotPersonaProjection, inspectLedger };
|
|
15
17
|
//# sourceMappingURL=index.js.map
|
|
16
18
|
//# sourceMappingURL=index.js.map
|