@byok-sdk/bot-collaboration 0.42.0 → 0.43.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 +21 -4
- package/dist/{chunk-XTZUCECQ.js → chunk-6Y2B2XCP.js} +5 -5
- package/dist/chunk-6Y2B2XCP.js.map +1 -0
- package/dist/{chunk-5J5SOWWI.js → chunk-QZRWFFHM.js} +6 -6
- package/dist/chunk-QZRWFFHM.js.map +1 -0
- package/dist/chunk-ZX6C5U2S.js +27 -0
- package/dist/chunk-ZX6C5U2S.js.map +1 -0
- package/dist/commit.d.ts +1 -0
- package/dist/host-kit.d.ts +20 -0
- package/dist/host-kit.js +8 -3
- package/dist/host-kit.js.map +1 -1
- package/dist/host.d.ts +47 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +11 -8
- package/dist/index.js.map +1 -1
- package/dist/model.d.ts +6 -0
- package/dist/rules/delegation.d.ts +19 -6
- package/dist/rules/index.js +1 -1
- package/dist/store-compatibility.d.ts +3 -0
- package/dist/testing.js +2 -2
- package/package.json +8 -8
- package/dist/chunk-5J5SOWWI.js.map +0 -1
- 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/commit.d.ts
CHANGED
|
@@ -26,6 +26,7 @@ export declare function commitInLedger(ledger: HostLedger, request: CommitReques
|
|
|
26
26
|
export declare function commitInRows(state: CollaborationState, scope: string, request: CommitRequest<Command>, rows: ApplicationRows, ports: CommandPorts): CommitResult;
|
|
27
27
|
/** One retention call in one ledger transaction. K4 facts come from the same state. */
|
|
28
28
|
export declare function retainInLedger(ledger: HostLedger, input: RetentionInput, limits: RetentionLimits): RetentionResult;
|
|
29
|
+
export declare function wouldDoNeedsMigration(state: CollaborationState): boolean;
|
|
29
30
|
/** The result of `migrateWouldDo`: rows that got their `turnId`, and rows archived because no live Turn owns them. */
|
|
30
31
|
export interface WouldDoMigration {
|
|
31
32
|
backfilled: number;
|
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';
|
package/dist/host-kit.js
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
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, commitImport, commitInLedger, deliveryRoute, discardImport, dreamIntentIds, dreamPolicy, echoCandidates, enablePush, exportMarkOf, importForSwitch, inboundDisposition, inboundDispositions, migrateWouldDo, 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-
|
|
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, sealedRoutineInstruction, sealedTemplate, stateOf, updateBot, updateDefinition, verified, writeSnapshotBot } 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, commitImport, commitInLedger, deliveryRoute, discardImport, dreamIntentIds, dreamPolicy, echoCandidates, enablePush, exportMarkOf, importForSwitch, inboundDisposition, inboundDispositions, migrateWouldDo, 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-QZRWFFHM.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, sealedRoutineInstruction, sealedTemplate, stateOf, updateBot, updateDefinition, verified, writeSnapshotBot } from './chunk-6Y2B2XCP.js';
|
|
3
3
|
export { DEVICE_CONCURRENCY } from './chunk-33YA66U7.js';
|
|
4
|
-
|
|
4
|
+
import { outcomeSchema, botTurnInstruction, promptActions } from './chunk-ZX6C5U2S.js';
|
|
5
|
+
export { BOT_REPLY_MAX_BYTES, CommitConflict, DEFAULT_AUTONOMY, DEFAULT_CONTEXT_MAX_BYTES, DEFAULT_CONTEXT_TURN_LIMIT, DEFAULT_HANDOFF_BUDGETS, DEFAULT_INSTRUCTION_MAX_BYTES, DEFAULT_MEMBER_MENTIONS, DelegationError, HostIntentError, ROOM_CONTEXT_BYTES, ROOM_CONTEXT_MESSAGES, ROOM_GRACE_MS, RetiredIdentityError, SYSTEM_PROMPT, autonomyOf, contextTurns, historyRowFromTurn, memberMentions, minimumInstructionBytes, outcomeOffer, outcomeSchema, refuseRetired, retiredIdentity, revisionOf, wouldDoRows } from './chunk-ZX6C5U2S.js';
|
|
6
|
+
|
|
7
|
+
function botTurnInstruction2(options){const routines=options.routines??[];const schema=outcomeSchema(options.turn.botId,options.state,options.turn,options.models,routines,options.offer);const{instruction}=botTurnInstruction(options.state,options.turn,options.limits,routines,options.injected,options.room,promptActions(schema,options.offer));return {instruction}}
|
|
8
|
+
|
|
9
|
+
export { botTurnInstruction2 as botTurnInstruction };
|
|
5
10
|
//# sourceMappingURL=host-kit.js.map
|
|
6
11
|
//# 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, migrateWouldDo, retainInLedger, revisionOf } from './commit.js';\nexport type { Command, CommandPorts, CommitRequest, CommitResult, Disposition, OutboxIntent, WouldDoMigration } 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 { commitImport, discardImport, importForSwitch } from './switch.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, unknownDelivery } from './delivery.js';\nexport { cleanReplyTokens, deliveryRoute, echoCandidates, enablePush, promoteStaged, queueDelivery, refuseRoute, rememberInbound, resendUnknown,\n revokePush, type IntentConclusions } from './delivery-routing.js';\nexport { checkDreamInstruction, dreamIntentIds, dreamPolicy, 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, sealedRoutineInstruction, 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'>>;
|
|
@@ -255,12 +261,29 @@ export declare class BotCollaboration {
|
|
|
255
261
|
enqueueHostIntent(input: IntentInput, handler: string): Promise<Intent>;
|
|
256
262
|
/**
|
|
257
263
|
* 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
|
-
*
|
|
264
|
+
* `already_settled` and sends nothing, so a replay does not fail. An unsubmitted intent returns `cancelled` once its cancel
|
|
265
|
+
* commits; `conclusion` is absent if a failed drain or process pass leaves settlement unfinished. A later successful
|
|
266
|
+
* drain settles it without running its handler and advances its FIFO. Replay to read `already_settled` with its conclusion,
|
|
267
|
+
* or `cancel_pending` while a submitted intent awaits its terminal. A submitted intent gets an SDK cancel; a
|
|
260
268
|
* `task.complete` that arrived before the cancel still runs the handler once. A `handler_failed` intent stays stuck,
|
|
261
269
|
* because K4 applies its terminal again: `failStuckIntent` settles it. Refuses a Bot Turn key and an unknown key.
|
|
270
|
+
*
|
|
271
|
+
* After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged
|
|
272
|
+
* first drain or process rejection (the whole AggregateError for mixed failures), even if a later pass succeeds.
|
|
273
|
+
* A drain error comes from that same drain, which coalesces with an in-flight drain and may fail on other Host work.
|
|
274
|
+
* Check `'drainError' in result`, report it and retry pending work with `drain()` or recovery. The cancellation
|
|
275
|
+
* committed; reconciliation may be unfinished. Job/outbox retry state is unchanged; explicit drains and wake hooks
|
|
276
|
+
* still reject. Pre-commit failures still reject.
|
|
262
277
|
*/
|
|
263
278
|
cancelHostIntent(key: string, ...by: PrincipalArg): Promise<HostIntentCancelResult>;
|
|
279
|
+
/**
|
|
280
|
+
* Cancel selected Host intents atomically without a pass. A submitted intent refuses the whole set; after a successful
|
|
281
|
+
* call, successors wait for the next pass, or the Host can call `drain()`. Results keep input order and are replayable.
|
|
282
|
+
*/
|
|
283
|
+
cancelHostIntents(keys: readonly string[], ...by: PrincipalArg): Promise<(IntentCancelResult<Conclusion> & {
|
|
284
|
+
result: 'cancelled' | 'already_settled';
|
|
285
|
+
conclusion: Conclusion;
|
|
286
|
+
})[]>;
|
|
264
287
|
/**
|
|
265
288
|
* Owner API (#882): settles as `failed` an open intent whose K4 terminal K8 refuses with `IntentOutcomeError`, so its FIFO
|
|
266
289
|
* moves on. A fresh K4 drain decides that the intent is stuck, so the call also works right after a restart. One transaction
|
|
@@ -362,8 +385,16 @@ export declare class BotCollaboration {
|
|
|
362
385
|
* 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
386
|
* Idempotent (#1405): a Turn whose K4 intent already has a cancel gives `cancel_pending`, and an ended Turn
|
|
364
387
|
* `already_settled`; neither writes or calls `core.cancel`.
|
|
365
|
-
|
|
366
|
-
|
|
388
|
+
* After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged
|
|
389
|
+
* first drain rejection (the whole AggregateError for mixed failures), even if a later pass retries it successfully.
|
|
390
|
+
* Its presence means cancellation committed, not that reconciliation finished. Inspect/report it and retry pending
|
|
391
|
+
* work with `drain()` or recovery, rather than repeating the cancellation. Job/outbox retry state is unchanged;
|
|
392
|
+
* explicit drains and wake hooks still reject. Pre-commit failures still reject.
|
|
393
|
+
*/
|
|
394
|
+
cancelTurn(id: string, ...by: PrincipalArg): Promise<TurnCancelResult & {
|
|
395
|
+
wakePending?: true;
|
|
396
|
+
drainError?: unknown;
|
|
397
|
+
}>;
|
|
367
398
|
private cancelOneTurn;
|
|
368
399
|
/** The L owner record of a device (#957, §4.1). A device with no record is L at revision 0. */
|
|
369
400
|
topology(deviceId: string): DeviceTopology;
|
|
@@ -403,8 +434,16 @@ export declare class BotCollaboration {
|
|
|
403
434
|
* A failed export or check: clears the freeze on the frozen revision, so L owns the device again and held Turns run. An
|
|
404
435
|
* abort of a device of the export ends the export, and the new owner discards its import. After the commit every device
|
|
405
436
|
* of the export is owned by H, so none aborts.
|
|
406
|
-
|
|
407
|
-
|
|
437
|
+
* After commit, a wake-only failure returns `wakePending: true`. Other failures return `drainError`, the unchanged
|
|
438
|
+
* process rejection (the whole AggregateError for mixed failures). Its presence means the abort committed, not that
|
|
439
|
+
* reconciliation finished. Inspect/report it and retry pending work with `drain()` or recovery, rather than repeating
|
|
440
|
+
* the abort with its now-stale revision. Job/outbox retry state is unchanged; explicit drains and wake hooks still
|
|
441
|
+
* reject. A failure may concern other work or already be retried before return. Pre-commit failures still reject.
|
|
442
|
+
*/
|
|
443
|
+
abortSwitch(deviceId: string, expectedRevision: number): Promise<DeviceTopology & {
|
|
444
|
+
wakePending?: true;
|
|
445
|
+
drainError?: unknown;
|
|
446
|
+
}>;
|
|
408
447
|
/**
|
|
409
448
|
* Explicit retention (#798). Moves every row of each acknowledged settled root out of the state, and retires its ids.
|
|
410
449
|
* A root that is still in use throws `RetentionRefused`, and nothing changes. Never runs on its own.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { inspectLedger } from './store-compatibility.js';
|
|
1
2
|
export { BotCollaboration } from './host.js';
|
|
2
3
|
export { botCompactVeto } from './compaction.js';
|
|
3
4
|
export type { AgentMessageInput, BotOptions, HostIntentCancelResult, HostIntentHandler, HostIntentMessageHandler, MessageServer } from './host.js';
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,19 @@
|
|
|
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-
|
|
1
|
+
import { checkTopology, checkSwitchRecords, wouldDoNeedsMigration, botCompactVeto, dreamPolicy, checkDreamInstruction, deviceRefusal, admitBot, refuseExported, recordDream, writeLedger, echoCandidates, acceptDeliveryEcho, cleanReplyTokens, rememberInbound, rememberFilteredInbound, routeTerminal, runHostIntentHandler, outcomeFailure, IntentOutcomeError, botOutcomePorts, intentRows, admitDevice, promoteStaged, queueDelivery, commitInLedger, resendUnknown, revokePush, enablePush, admitUserInput, commitInRows, inboundDispositionsOf, deviceTopology, switchStep, switchWork, DeviceModeError, switchDrained, SwitchExportError, sealSwitchExport, switchContent, sealLedger, retainInLedger, recoverDelivery, syncHead, reconcileDreamRoutines, advanceRoomsAndTurns, syncTurnInLedger, syncDreams, botDeviceRefusal, settleDelegations, syncTail, callCardsInLedger, readbackDelivery, deliveryRoute, refuseRoute, startDelivery, settleDelivery, unknownDelivery, dreamReads, homeSent, observeDevices } from './chunk-QZRWFFHM.js';
|
|
2
|
+
export { botCompactVeto } from './chunk-QZRWFFHM.js';
|
|
3
|
+
import { stateOf, OldCollaborationStateError, 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-6Y2B2XCP.js';
|
|
4
4
|
import { DEVICE_CONCURRENCY, admitDeviceSlot } from './chunk-33YA66U7.js';
|
|
5
|
-
import { admitBotToolsets, HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS, DEFAULT_HANDOFF_BUDGETS, coalescePolicy, outcomeOffer, outcomeSchema, DEFAULT_INSTRUCTION_MAX_BYTES, minimumInstructionBytes, SYSTEM_PROMPT, REPLY_UNCERTAIN_AFTER_MS, DEFAULT_CANCEL_GRACE_MS, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-
|
|
6
|
-
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-
|
|
5
|
+
import { admitBotToolsets, HISTORY_MAX_BYTES, HISTORY_MAX_ITEMS, DEFAULT_HANDOFF_BUDGETS, coalescePolicy, outcomeOffer, outcomeSchema, DEFAULT_INSTRUCTION_MAX_BYTES, minimumInstructionBytes, SYSTEM_PROMPT, REPLY_UNCERTAIN_AFTER_MS, DEFAULT_CANCEL_GRACE_MS, DEFAULT_AUTONOMY, memberMentions, hostIntentCancelAnswer, HostIntentError, hostMessageDisposition, CommitConflict, delegationCancelAnswer, teamSnapshot, TeamModeError, autonomyOf, wouldDoRows, turnCancelAnswer, reportCardDecisions, replyCheckDue, checkReply, roomMessageProjection, roomMessages, contextTurns, collaborationDue, CONNECTOR_OUTCOME_UNKNOWN, commandBots, inactive } from './chunk-ZX6C5U2S.js';
|
|
6
|
+
export { TEAM_ROOM_LIMIT, TeamModeError, teamSnapshot } from './chunk-ZX6C5U2S.js';
|
|
7
|
+
import { mkdtempSync, copyFileSync, rmSync, statSync } from 'fs';
|
|
8
|
+
import { tmpdir } from 'os';
|
|
9
|
+
import { resolve, join, basename } from 'path';
|
|
10
|
+
import { HostLedger, hash, time, HostExecutionCore, isOccurrenceIntentKey, enqueue, WakeDispatchError, settle, project, setLifecycle, canonical } from '@byok-sdk/server/execution-core';
|
|
7
11
|
import { randomUUID } from 'crypto';
|
|
8
12
|
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
13
|
import { createAgentHomeProjectionConsumer } from '@byok-sdk/client';
|
|
11
14
|
|
|
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);})}
|
|
15
|
+
function inspectLedger(path,tenant){const file=resolve(path),store="bot-collaboration-ledger";const stat=statOrUndefined(file);if(!stat)return {store,path:file,verdict:"absent",reason:"No ledger file at this path"};if(!stat.isFile())return {store,path:file,verdict:"rejected",reason:"The ledger path is not a regular file"};const directory=mkdtempSync(join(tmpdir(),"byok-ledger-check-"));try{const copy=join(directory,basename(file)),suffixes=["","-wal","-journal"];const fingerprint=suffix=>{const s=statOrUndefined(file+suffix);return s&&`${s.size}:${s.mtimeMs}:${s.ino}`};const before=suffixes.map(fingerprint);suffixes.forEach((suffix,i)=>{if(before[i]!==void 0)copyFileSync(file+suffix,copy+suffix);});if(suffixes.some((suffix,i)=>fingerprint(suffix)!==before[i]))throw new Error(`${file} changed while it was being checked; stop its owner and check again`);try{const{DatabaseSync}=process.getBuiltinModule("node:sqlite");const db=new DatabaseSync(copy,{readOnly:true});try{if(!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='host_ledger'").get())throw new Error("Not a Host ledger")}finally{db.close();}const ledger=new HostLedger(copy,tenant);try{const state=stateOf(ledger.snapshot().application);checkTopology(state);checkSwitchRecords(state);if(state.switchExport)return {store,path:file,verdict:"accepted",reason:"This build opens the exported ledger; run migrateWouldDo if the switch is aborted"};return wouldDoNeedsMigration(state)?{store,path:file,verdict:"migration-required",reason:"Would-do rows lack turnId; run migrateWouldDo before serving"}:{store,path:file,verdict:"accepted",reason:"This build opens the ledger"}}finally{ledger.close();}}catch(error){const code=error?.code;return {store,path:file,verdict:error instanceof OldCollaborationStateError?"new-path-repair":"rejected",...typeof code==="string"?{code}:{},reason:error instanceof Error?error.message:String(error)}}}finally{rmSync(directory,{recursive:true,force:true});}}function statOrUndefined(file){try{return statSync(file)}catch(error){if(error.code==="ENOENT")return void 0;throw error}}function ownReadOnlyToolsets(ids=[]){if(!Array.isArray(ids))throw new Error("readOnlyToolsets must be an array of logical toolset IDs");if(ids.length>64||new Set(ids).size!==ids.length)throw new Error("Invalid read-only toolset policy");for(const id of ids)ToolsetIdSchema.parse(id);return Object.freeze([...ids])}async function flushHomes(server,ledger,now){const busy=botId=>Object.values(ledger.snapshot().intents).some(intent=>!intent.conclusion&&intent.execution.payload.agentRef.agentId===botId);const operation=(s,sequence)=>stateOf(s.application).team.homeOperations.find(o=>o.sequence===sequence);const snapshot=stateOf(ledger.snapshot().application),team=snapshot.team;for(const pending of team.homeOperations.filter(o=>o.status==="pending").sort((a,b)=>a.sequence-b.sequence)){const op=homeHead(team,pending.sequence,busy);if(!op)continue;if(deviceRefusal(snapshot,op.request.deviceId)&&!homeSent(op))continue;try{if(!server.enqueueAgentHomeProjection||!server.readAgentHomeProjection)throw new Error("Home projection API required");let terminal;for(const candidate of homeRequests(op)){terminal=checkHomeReadback(candidate,await server.readAgentHomeProjection(candidate.deviceId,candidate.payload.agentRef,candidate.payload.requestId));if(terminal)break}if(!terminal){const request=ledger.transaction(s=>{if(deviceRefusal(stateOf(s.application),op.request.deviceId))return void 0;const row=operation(s,op.sequence);row.sent=true;return planHomeRetry(row,now())});if(!request)continue;await server.enqueueAgentHomeProjection(request);ledger.transaction(s=>homeEnqueued(operation(s,op.sequence),now()));continue}const settled=terminal;ledger.transaction(s=>applyHomeTerminal(stateOf(s.application),operation(s,op.sequence),settled,(id,value)=>project(s,id,value)));}catch(error){ledger.transaction(s=>failHomeFlush(operation(s,op.sequence),error));}}}function hostIntent(state,key){return state.hostIntents&&Object.hasOwn(state.hostIntents,key)?state.hostIntents[key]:void 0}function openIntent(intents,key){const intent=intents[hash(key)];if(!intent)throw new HostIntentError(key,"unknown_intent",`Unknown intent: ${key}`);if(intent.conclusion)throw new HostIntentError(key,"already_settled",`Intent already settled: ${key}`);return intent}function bounded(read,ms){let timer;const late=new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error("History read timed out")),Math.max(0,ms));});return Promise.race([read,late]).finally(()=>clearTimeout(timer))}function awaitsOffer(ledger,state,turn){const bot=state.team.bots[turn.botId];return !turn.conclusion&&!turn.held&&!ledger.intents[hash(turn.id)]&&turn.status!=="failed"&&!!bot&&!inactive(bot)&&bot.readyRevision===bot.revision}function dispatchRow(state,row){const execution=state.executions[row.taskId];return {id:row.id,agent:row.agent,sequence:row.sequence,phase:row.phase,attempts:row.attempts,source:row.source,deviceId:row.execution.deviceId,occupies:row.phase==="inflight"&&(execution?.submission==="delivered"||execution?.attempt!==void 0||execution?.started===true)}}function admitCommand(state,command){for(const botId of commandBots(state,command))admitBot(state,botId);}function valueOf(result){if(result.disposition.outcome!=="accepted")throw new Error("Unexpected refused command");return result.disposition.value}function turnOf(result){if(result.disposition.outcome!=="accepted"||typeof result.disposition.value!=="string")throw new Error("Input command has no Turn id");return result.disposition.value}var BotCollaboration=class{constructor(server,ledger,options){this.server=server;this.ledger=ledger;this.options=options;if(!options.botId||options.execution.payload.agentRef.agentId!==options.botId)throw new Error("Select this Bot Agent");if(ledger.compactVeto!==botCompactVeto)throw new Error("Open the Host ledger with { compactVeto: botCompactVeto }");options=this.options={...options,execution:structuredClone(options.execution),...options.models===void 0?{}:{models:structuredClone(options.models)},readOnlyToolsets:ownReadOnlyToolsets(options.readOnlyToolsets)};admitBotToolsets(options.execution,options.readOnlyToolsets);for(const model of Object.values(this.models()))admitBotToolsets(model,options.readOnlyToolsets);const persisted=ledger.snapshot(),team=stateOf(persisted.application).team;checkTopology(stateOf(persisted.application));checkSwitchRecords(stateOf(persisted.application));if(options.team==="external"?!team.external&&Object.keys(team.bots).length:team.external){throw new Error(`This ledger has ${team.external?"an external":"a local"} team`)}if(options.persona!==void 0&&(options.persona!=="external"||options.team!=="external")){throw new Error("The Host persona mode needs team: 'external'")}if(team.external&&!!team.external.persona!==(options.persona==="external")){throw new Error(`This ledger has ${team.external.persona?"Host":"K8"} persona projections`)}if(options.rooms!==void 0&&(options.rooms!=="external"||options.team!=="external")){throw new Error("The external rooms mode needs team: 'external'")}if(team.external&&!!team.external.rooms!==(options.rooms==="external")){throw new Error(`This ledger has ${team.external.rooms?"external":"local"} rooms`)}for(const intent of Object.values(persisted.intents)){if(intent.conclusion)continue;admitBotToolsets(intent.execution,options.readOnlyToolsets);const execution=persisted.executions[intent.taskId];if(execution)admitBotToolsets(execution.input,options.readOnlyToolsets);}this.hostIntentHandlers=new Map(Object.entries(options.hostIntents??{}));this.hostIntentMessageHandlers=new Map(Object.entries(options.hostIntentMessages??{}));for(const name of this.hostIntentMessageHandlers.keys()){if(!this.hostIntentHandlers.has(name))throw new Error(`A Host intent message handler needs the Host intent handler ${name}`)}for(const[key,{handler}]of Object.entries(stateOf(persisted.application).hostIntents??{})){const intent=persisted.intents[hash(key)];if(intent&&intent.conclusion===void 0&&!this.hostIntentHandlers.has(handler)){throw new Error(`An open Host intent needs the handler ${handler}`)}if(intent&&intent.conclusion===void 0&&intent.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`An open Host intent needs the message handler ${handler}`)}}this.owner={id:options.owner??"owner",kind:"human"};if(!verified(this.owner))throw new Error("Invalid owner principal");this.now=()=>time((options.now??Date.now)());this.connectorTimeoutMs=time(options.connectorTimeoutMs??3e4);if(this.connectorTimeoutMs<1||this.connectorTimeoutMs>2147483647)throw new Error("Invalid connector timeout");this.deliveryTimeoutMs=time(options.channel?.sendTimeoutMs??15e3);if(this.deliveryTimeoutMs<1||this.deliveryTimeoutMs>2147483647)throw new Error("Invalid delivery timeout");this.historyTimeoutMs=time(options.historyTimeoutMs??1e4);if(this.historyTimeoutMs<1||this.historyTimeoutMs>2147483647)throw new Error("Invalid history timeout");this.contextMaxBytes=time(options.contextMaxBytes??HISTORY_MAX_BYTES);this.contextTurnLimit=time(options.contextTurnLimit??HISTORY_MAX_ITEMS);if(this.contextMaxBytes<1||this.contextTurnLimit<1)throw new Error("Invalid ContextPack limits");this.handoff=options.handoff??DEFAULT_HANDOFF_BUDGETS;buildHandoffPack([],this.handoff);if(options.coalesce)this.coalesce=coalescePolicy(options.coalesce,this.contextMaxBytes);this.offer=outcomeOffer(options.outcome??{});outcomeSchema(options.botId,stateOf({}),void 0,Object.keys(this.models()),[],this.offer);this.instructionMaxBytes=time(options.instructionMaxBytes??DEFAULT_INSTRUCTION_MAX_BYTES);const minimum=minimumInstructionBytes(SYSTEM_PROMPT);if(this.instructionMaxBytes<minimum)throw new Error(`instructionMaxBytes must be at least ${minimum}`);this.dreaming=dreamPolicy(options.dreaming);if(this.dreaming)checkDreamInstruction(this.instructionMaxBytes);this.timers={cancelGraceMs:time(options.cancelGraceMs??DEFAULT_CANCEL_GRACE_MS),uncertainAfterMs:time(options.uncertainAfterMs??REPLY_UNCERTAIN_AFTER_MS)};if(this.timers.cancelGraceMs<1||this.timers.uncertainAfterMs<1)throw new Error("Invalid delegation timers");this.deviceConcurrency=time(options.deviceConcurrency??DEVICE_CONCURRENCY);if(this.deviceConcurrency<1)throw new Error("Invalid device concurrency");this.core=new HostExecutionCore(server,ledger,{now:this.now,reconcileMs:options.reconcileMs??100,nextOccurrence:routineCalendar,hostJobExecution:"fail",executionRoutines:"refuse",...options.hostJobs?{hostJobs:options.hostJobs}:{},...options.onOutbox?{onOutbox:options.onOutbox}:{},occurrenceHooks:{[BOT_ROUTINE]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);this.commitCallback(state,tx.rows,run.occurrenceKey,{kind:"occurrence",key:run.occurrenceKey},{publish:tx.publish,occurrence:()=>routineTurn(state,run)});},[BOT_DREAM]:(run,tx)=>{const state=stateOf(tx.application);admitBot(state,run.input.owner);refuseExported(state);recordDream(state,run,this.now());}},applyMessage:(input,tx)=>this.applyMessage(input,tx),applyOutcome:(document,tx)=>this.applyOutcome(document,tx),admitSubmit:(intent,state)=>!deviceRefusal(stateOf(state.application),intent.execution.deviceId)&&this.admitsDeviceSlot(intent,state)});if(!stateOf(persisted.application).switchExport)ledger.transaction(s=>{const state=stateOf(s.application);if(options.team==="external"){state.team.external??={revision:0,...options.persona==="external"?{persona:true}:{},...options.rooms==="external"?{rooms:true}:{}};}else {state.team.bots[options.botId]??={id:options.botId,name:"Main Bot",role:"Team owner",persona:"",model:Object.keys(this.models())[0],mainBot:true,archived:false,autonomy:DEFAULT_AUTONOMY,revision:options.execution.payload.agentRef.profileRevision,readyRevision:options.execution.payload.agentRef.profileRevision,execution:structuredClone(options.execution)};}applyModels(state,this.models(),options.readOnlyToolsets??[]);});}server;ledger;options;core;chain=Promise.resolve();timer;closed=false;now;connectorTimeoutMs;deliveryTimeoutMs;historyTimeoutMs;contextMaxBytes;contextTurnLimit;handoff;dreaming;instructionMaxBytes;deviceConcurrency;timers;coalesce;offer;owner;unread=new Set;hostIntentHandlers;hostIntentMessageHandlers;intentFailures=new Map;auditedFailures=new Map;models(){return this.options.models??{default:this.options.execution}}setModels(models){return this.exclusive(async()=>{const next=structuredClone(models);outcomeSchema(this.options.botId,stateOf({}),void 0,Object.keys(next),[],this.offer);this.write(s=>applyModels(stateOf(s.application),next,this.options.readOnlyToolsets??[]));this.options.models=next;await this.process();})}snapshot(){return stateOf(this.ledger.snapshot().application)}write(apply){return writeLedger(this.ledger,apply)}exclusive(work){if(this.closed)return Promise.reject(new Error("Bot Host is closed"));const next=this.chain.then(work);this.chain=next.catch(()=>{});return next}input(key,request,botId=this.options.botId,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"input",botId);const result=this.commitOwner(hash(["input",botId,key]),{kind:"input",botId,key,request,sender:principal.id});await this.process();return turnOf(result)})}inputRoot(key,botId=this.options.botId){const id=hash(["input",botId,key]),commands=stateOf(this.ledger.snapshot().application).commands;const record=commands&&Object.hasOwn(commands,id)?commands[id]:this.ledger.transaction((_,rows)=>rows.get("commands",id));return record&&turnOf(record.result)}async receive(message){if(this.closed)throw new Error("Bot Host is closed");const kind=classifyInbound(message,this.owner.id,this.options.channel?.self),{channel,conversation,platformMessageId,sender}=message;if(kind==="echo"){this.write(s=>{const state=stateOf(s.application),matches=echoCandidates(state,message);if(matches.length!==1||!acceptDeliveryEcho(matches[0],platformMessageId))state.audit.push(`Delivery unmatched_echo: ${channel} ${platformMessageId}`.slice(0,1024));cleanReplyTokens(s,state,this.now());});return {kind}}if(kind==="owner_input"||kind==="room_input")return this.exclusive(async()=>{const principal=kind==="owner_input"?this.ownerOnly([sender],"input",conversation.id):this.verifiedOnly(sender,"roomInput",conversation.id);const key=inboundKey(message);const command=kind==="owner_input"?{kind:"receive",inbound:kind,key,botId:conversation.id,request:message.text,sender:principal.id}:{kind:"receive",inbound:kind,key,roomId:conversation.id,text:message.text,mentions:this.seatMentions(conversation.id,principal,message.mentions),from:principal.id};const result=this.commitOwner(hash(["receive",key]),command,(_s,state)=>({remember:root=>rememberInbound(state,message,root)}));await this.process();return {kind,id:turnOf(result)}});if(kind==="bot_background"){return {kind,id:await this.roomInput(inboundKey(message),conversation.id,message.text,message.mentions,sender)}}const who=verified(sender)?` ${sender.kind}:${sender.id}`:"";const filtered=kind==="unverified_sender"||kind==="not_owner"?kind:void 0;await this.exclusive(async()=>this.write(s=>{const state=stateOf(s.application);if(filtered)rememberFilteredInbound(state,message,filtered);state.audit.push(`Inbound ${kind}: ${channel} ${conversation.kind}:${conversation.id} ${platformMessageId}${who}`.slice(0,1024));}));return {kind}}enablePushRoute(conversation,channel,target,...by){return this.exclusive(async()=>{const principal=this.ownerOnly(by,"enablePushRoute",conversation.id);if(!this.options.channel)throw new Error("Channel is not configured");return valueOf(this.commitKeyless({kind:"enable_push_route",conversation,channel,target,owner:principal.id}))})}revokePushRoute(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"revokePushRoute",id);this.commitKeyless({kind:"revoke_push_route",routeId:id});await this.process();})}resendDelivery(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"resendDelivery",id);if(!this.options.channel)throw new Error("Channel is not configured");const next=valueOf(this.commitKeyless({kind:"resend_delivery",deliveryId:id}));await this.process();return next})}audit(line){this.write(s=>{stateOf(s.application).audit.push(line.slice(0,1024));});}verifiedOnly(principal,action,target){if(verified(principal))return principal;this.audit(`Action refused unverified_sender: ${action} ${target}`);throw new Error(`unverified_sender: ${action} needs a verified principal`)}seatMentions(roomId,principal,mentions){if(!principal||isOwner(principal,this.owner.id))return mentions;if(principal.kind==="bot")return [];const room=this.snapshot().team.rooms[roomId];return room&&memberMentions(room)==="ignore"?[]:mentions}ownerOnly(by,action,target){const principal=this.verifiedOnly(by.length?by[0]:this.owner,action,target);if(isOwner(principal,this.owner.id))return principal;this.audit(`Action refused not_owner: ${action} ${target} ${principal.kind}:${principal.id}`);throw new Error(`not_owner: ${action} needs the owner principal`)}applyOutcome(document,tx){const state=stateOf(tx.application),taskId=tx.intent.taskId,key=tx.intent.key;refuseExported(state);try{const route=routeTerminal(state,key,hostIntent(state,key)?.handler);if(route.kind==="host_intent")runHostIntentHandler(key,route.handler,this.hostIntentHandlers.get(route.handler)?.bind(null,document,tx));else if(route.kind==="bot_turn"){try{this.commitBotOutcome(state,key,taskId,document,tx);}catch(cause){throw outcomeFailure(key,cause)}}}catch(error){if(error instanceof IntentOutcomeError)this.intentFailures.set(key,error);throw error}}commitBotOutcome(state,key,taskId,document,tx){this.commitCallback(state,tx.rows,taskId,{kind:"outcome",turnId:key,taskId,document},{publish:tx.publish,...this.deliverPort(state,taskId),outcome:{committed:{intent:key2=>intentRows(this.ledger.snapshot()).intent(key2)},...botOutcomePorts({taskId,routines:tx.routines,roomPosts:!!this.options.roomHistory,manage:(turn,outcome,managed)=>applyManagement(state,turn.botId,taskId,outcome,this.models(),managed,this.options.readOnlyToolsets)})}});}reportIntentFailures(){const failures=[...this.intentFailures.values()],fresh=failures.filter(f=>this.auditedFailures.get(f.key)!==f.message);if(fresh.length){this.write(s=>{const state=stateOf(s.application);for(const f of fresh)state.audit.push(`Intent outcome refused ${f.code}: ${f.key} ${f.message}`.slice(0,1024));});for(const f of fresh)this.auditedFailures.set(f.key,f.message);}return failures[0]}enqueueHostIntent(input,handler){return this.exclusive(async()=>{if(!this.hostIntentHandlers.has(handler))throw new Error(`Unknown Host intent handler: ${handler}`);if(isOccurrenceIntentKey(input.key))throw new Error("Host intent identity conflict: the key is an occurrence");if(input.execution.payload.messageEgress&&!this.hostIntentMessageHandlers.has(handler)){throw new Error(`Host intent handler ${handler} has no message handler`)}admitBotToolsets(input.execution,this.options.readOnlyToolsets);this.write(s=>{const state=stateOf(s.application),owner=hostIntent(state,input.key);if(Object.hasOwn(state.turns,input.key))throw new Error("Host intent identity conflict: the key is a Bot Turn");if(owner?owner.handler!==handler:s.intents[hash(input.key)])throw new Error("Host intent identity conflict");if(!owner)admitDevice(state,input.execution.deviceId);enqueue(s,this.ledger.tenant,input);Object.defineProperty(state.hostIntents??={},input.key,{value:{handler},enumerable:true,writable:true,configurable:true});});await this.process();return this.core.intent(input.key)})}cancelHostIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntent",key);const snapshot=this.ledger.snapshot(),state=stateOf(snapshot.application),intent=snapshot.intents[hash(key)];const settled=hostIntentCancelAnswer(key,Object.hasOwn(state.turns,key),hostIntent(state,key)&&intent);if(settled)return {key,...settled};const dispatch=await this.core.cancel(key);try{await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}if(intent.phase==="inflight")return {key,result:"cancel_pending",...dispatch};const conclusion=this.core.intent(key)?.conclusion;return {key,result:"cancelled",...conclusion===void 0?{}:{conclusion},...dispatch}})}cancelHostIntents(keys,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelHostIntents",keys.join(" "));const seen=new Set;for(const key of keys){if(seen.has(key))throw new Error(`Duplicate Host intent key: ${key}`);seen.add(key);}return this.write(s=>{const state=stateOf(s.application),rejected=[];for(const key of keys){const intent=s.intents[hash(key)];if(Object.hasOwn(state.turns,key))rejected.push({key,code:"not_host_intent"});else if(!hostIntent(state,key)||!intent)rejected.push({key,code:"unknown_intent"});else if(!intent.conclusion&&intent.phase==="inflight")rejected.push({key,code:"inflight"});}if(rejected.length){const first=rejected[0];const message=first.code==="inflight"?"The intent is in flight: use cancelHostIntent":first.code==="not_host_intent"?"The key is a Bot Turn: use cancelTurn":"No Host intent has this key";throw new HostIntentError(first.key,first.code,message,rejected)}return keys.map(key=>{const intent=s.intents[hash(key)];if(intent.conclusion)return {key,result:"already_settled",conclusion:intent.conclusion};intent.cancelReason="cancelled";settle(s,intent,"cancelled");return {key,result:"cancelled",conclusion:"cancelled"}})})})}failStuckIntent(key,...by){return this.exclusive(async()=>{this.ownerOnly(by,"failStuckIntent",key);openIntent(this.ledger.snapshot().intents,key);this.intentFailures.clear();const drained=await this.core.drain().then(()=>void 0,error=>({error}));const refused=this.intentFailures.get(key);this.write(s=>{const intent=openIntent(s.intents,key);if(!refused)throw drained?drained.error:new HostIntentError(key,"not_stuck",`Intent is not stuck: ${key} has no refused terminal`);settle(s,intent,"failed");if(refused.code==="outcome_failed")stateOf(s.application).turns[key].settleCode=refused.code;stateOf(s.application).audit.push(`Intent failed by owner ${refused.code}: ${key} ${refused.message}`.slice(0,1024));});this.intentFailures.delete(key);this.auditedFailures.delete(key);await this.process();})}deliverPort(state,taskId){if(!this.options.channel)return {};return {deliver:(turn,key,text,staged)=>queueDelivery(this.ledger.snapshot(),state,turn,taskId,key,text,this.now(),staged)?.id,promote:id=>promoteStaged(state,id)}}commitOwner(commandId,command,extra){return commitInLedger(this.ledger,{scope:this.ledger.tenant,commandId,command},s=>{const state=stateOf(s.application);return {now:this.now,admit:next=>admitCommand(state,next),publish:(key,value)=>project(s,key,value),intents:intentRows(s),admitInput:fields=>admitUserInput(state,fields,this.coalesce,this.now()),updatePersona:(botId,persona)=>updateBot(state,{botId,persona},this.models(),this.options.readOnlyToolsets),routes:{enable:(conversation,channel,target,owner)=>enablePush(state,conversation,channel,target,owner,this.now()).id,revoke:routeId=>revokePush(state,routeId,this.now()),resend:deliveryId=>resendUnknown(state,deliveryId,this.now()).id},...extra?.(s,state)}})}commitKeyless(command){return this.commitOwner(randomUUID(),command)}commitCallback(state,rows,commandId,command,ports){return commitInRows(state,this.ledger.tenant,{scope:this.ledger.tenant,commandId,command},rows,{now:this.now,...ports})}async consumeMessage(input){if(this.closed)throw new Error("Bot Host is closed");refuseExported(this.snapshot());const result=await this.core.consumeMessage(input);if(result.outcome==="accepted")queueMicrotask(()=>{if(!this.closed)void this.drain().catch(()=>{});});return result}applyMessage(input,tx){const state=stateOf(tx.application);refuseExported(state);const name=hostIntent(state,tx.intent.key)?.handler,handler=name===void 0?void 0:this.hostIntentMessageHandlers.get(name);let disposition;try{({disposition}=this.commitCallback(state,tx.rows,`${input.taskId}:${input.payload.messageId}`,{kind:"message",turnId:tx.intent.key,message:{taskId:input.taskId,payload:input.payload}},{publish:tx.publish,...this.deliverPort(state,input.taskId),...handler?{hostMessage:()=>hostMessageDisposition(handler(input,tx))}:{}}));}catch(cause){if(cause instanceof CommitConflict&&cause.code==="identity_conflict")return {outcome:"refused",reasonCode:"message_conflict"};throw cause}return disposition.outcome==="accepted"?{outcome:"accepted"}:{outcome:"refused",reasonCode:disposition.reasonCode}}cancelDelegation(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelDelegation",id);const settled=delegationCancelAnswer(this.snapshot(),id);if(settled)return {delegationId:id,...settled};await this.settleChain(this.commitKeyless({kind:"cancel_delegation",delegationId:id}));return {delegationId:id,result:"cancelled"}})}abandonDelegation(id,...by){return this.exclusive(()=>{this.ownerOnly(by,"abandonDelegation",id);return this.settleChain(this.commitKeyless({kind:"abandon_delegation",delegationId:id}))})}async settleChain(result){if(valueOf(result).deliver)await this.deliverCancels();await this.process();}admitsDeviceSlot(intent,state){const rows=Object.values(state.intents).map(row=>dispatchRow(state,row));return admitDeviceSlot(rows.find(row=>row.id===intent.id)??dispatchRow(state,intent),rows,this.deviceConcurrency)}async deliverCancels(){for(const d of Object.values(this.snapshot().delegations)){if(!d.cancel||d.cancel.delivered)continue;const result=await this.core.cancel(d.cancel.targetTurnId);if("drainError"in result)throw result.drainError;this.write(s=>{stateOf(s.application).delegations[d.id].cancel.delivered=true;});}}async personaReady(botId,revision){await this.exclusive(async()=>{this.commitKeyless({kind:"persona_ready",botId,revision});await this.process();});}async retryPersona(botId){await this.exclusive(async()=>{this.commitKeyless({kind:"retry_persona",botId});await this.process();});}async applyTeam(snapshot){await this.exclusive(async()=>{const valid=teamSnapshot(snapshot);const{disposition}=this.commitOwner(hash(["team",valid.revision]),{kind:"team_snapshot",snapshot:valid},(_s,state)=>({teamBot:row=>writeSnapshotBot(state,row,this.models(),this.options.readOnlyToolsets)}));await this.process();if(disposition.outcome==="refused")throw new TeamModeError("stale_team",disposition.reason??"stale_team")});}async setMainBot(botId,mainBot){await this.exclusive(async()=>{this.commitKeyless({kind:"set_main_bot",botId,mainBot});await this.process();});}autonomy(botId){const bots=this.snapshot().team.bots,bot=Object.hasOwn(bots,botId)?bots[botId]:void 0;if(!bot)throw new Error("Bot not found");return autonomyOf(bot)}wouldDoRecords(botId){return wouldDoRows(this.snapshot(),botId)}inboundDispositions(){return inboundDispositionsOf(this.snapshot())}setBotAutonomy(botId,autonomy,...by){return this.exclusive(async()=>{this.ownerOnly(by,"setBotAutonomy",botId);if(autonomy!=="observe"&&autonomy!=="auto")throw new Error("Invalid autonomy");this.commitKeyless({kind:"set_autonomy",botId,autonomy});await this.process();})}async roomInput(key,roomId,text,mentions=[],...by){let id;await this.exclusive(async()=>{const principal=by.length?this.verifiedOnly(by[0],"roomInput",roomId):void 0;const called=this.seatMentions(roomId,principal,mentions);const result=this.commitOwner(hash(["room_input",roomId,key]),{kind:"room_input",key,roomId,text,mentions:called,...principal?{from:principal.id}:{}});id=turnOf(result);await this.process();});return id}async setMemberMentions(roomId,value,...by){await this.exclusive(async()=>{this.ownerOnly(by,"setMemberMentions",roomId);this.commitKeyless({kind:"set_room_member_mentions",roomId,memberMentions:value});await this.process();});}async createRoom(roomId,fields){await this.exclusive(async()=>{this.commitOwner(hash(["create_room",roomId]),{kind:"create_room",roomId,fields});await this.process();});}async updateRoom(roomId,update){await this.exclusive(async()=>{this.commitKeyless({kind:"update_room",roomId,update});await this.process();});}async answer(id,answer,...by){await this.exclusive(async()=>{this.ownerOnly(by,"answer",id);this.commitOwner(hash(["answer",id]),{kind:"answer",questionId:id,answer});await this.process();});}async decide(id,decision,...by){await this.exclusive(async()=>{this.ownerOnly(by,"decide",id);let error;try{const{disposition}=this.commitOwner(hash(["decide",id]),{kind:"decide",cardId:id,decision});if(disposition.outcome==="refused")error=disposition.reason;}catch(cause){if(!(cause instanceof CommitConflict)||cause.code!=="identity_conflict")throw cause;error=cause.message;}await this.process();if(error)throw new Error(error)});}async setRoutineLifecycle(id,value){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.lifecycle(owned(this.routineRows(),this.options.botId,id).definition.id,value);}finally{await this.process();}});}async endRoutine(id){await this.exclusive(async()=>{try{this.commitOwner(randomUUID(),{kind:"end_routine",botId:this.options.botId,routineId:id},s=>({routines:{end:routineId=>setLifecycle(s,endable(Object.values(s.routines),routineId).definition.id,"completed",this.now(),routineCalendar)}}));}finally{await this.process();}});}async updateRoutine(action){await this.exclusive(async()=>{refuseExported(this.snapshot());try{await this.core.updateRoutine(updateDefinition(this.routineRows(),this.options.botId,ownerRoutineUpdate(action)));}finally{await this.process();}});}routineRows(){return Object.values(this.ledger.snapshot().routines)}consume=(wake,signal)=>this.exclusive(async()=>{signal.throwIfAborted();this.write((s,rows)=>{this.sync(s,rows);});try{await this.core.consume(wake,signal);}finally{await this.process();}});drain(){return this.exclusive(()=>this.process())}cancelTurn(id,...by){return this.exclusive(async()=>{this.ownerOnly(by,"cancelTurn",id);return this.cancelOneTurn(id)})}async cancelOneTurn(id){const snapshot=this.ledger.snapshot(),settled=turnCancelAnswer(stateOf(snapshot.application),intentRows(snapshot),id);if(settled)return {turnId:id,...settled};const result=this.commitKeyless({kind:"cancel_turn",turnId:id});const value=valueOf(result);const dispatch="target"in value&&value.admitted?await this.core.cancel(value.target):{};try{if("deliver"in value)await this.settleChain(result);else await this.process();}catch(error){if(error instanceof WakeDispatchError)dispatch.wakePending=true;else if(!("drainError"in dispatch))dispatch.drainError=error;}return {turnId:id,result:"cancelled",...dispatch}}topology(deviceId){return deviceTopology(this.snapshot(),deviceId)}freezeForSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.write(s=>switchStep(s,deviceId,expectedRevision,"freeze"));return this.topology(deviceId)})}drainForSwitch(deviceId,{cancel=false}={}){return this.exclusive(async()=>{const work=this.write(s=>{if(!deviceTopology(stateOf(s.application),deviceId).switching)throw new Error(`Device ${deviceId} is not switching`);const open=switchWork(s,deviceId);if(cancel)for(const key of open.intents)s.intents[hash(key)].cancelReason??="cancelled";return open});if(cancel){for(const id of [...work.batches,...work.turns])await this.cancelOneTurn(id);await this.process();}return switchWork(this.ledger.snapshot(),deviceId)})}exportForSwitch(devices,exportedAt=this.now()){return this.exclusive(async()=>{const state=this.snapshot();refuseExported(state);for(const{deviceId,expectedRevision}of devices){const row=deviceTopology(state,deviceId);if(row.revision!==expectedRevision){throw new CommitConflict("stale_revision",`Device ${deviceId} is at topology revision ${row.revision}, not ${expectedRevision}`)}if(row.mode!=="L")throw new DeviceModeError(deviceId,row.mode,row.revision);if(!row.switching)throw new Error(`Device ${deviceId} is not switching`);if(!switchDrained(switchWork(this.ledger.snapshot(),deviceId)))throw new Error(`Device ${deviceId} still has open work`)}const header={source:"L",domain:this.ledger.tenant,exportedAt,devices:devices.map(({deviceId,expectedRevision})=>({deviceId,frozenRevision:expectedRevision}))};const dump=this.ledger.dumpForSwitch();const job=Object.values(dump.body.outbox).find(row=>row.kind==="host-job");if(job)throw new SwitchExportError("open_work",`Switch export source: Host job ${job.occurrenceKey} is pending; let it run first`);const document=sealSwitchExport(switchContent(dump,this.ledger.tenant,header));this.ledger.transaction(s=>{stateOf(s.application).switchExport={digest:document.manifest.digest,exportedAt,devices:document.devices.map(device=>({...device}))};});return document})}commitSwitch(deviceId,expectedRevision,receipt){return this.exclusive(async()=>{switchStep(structuredClone(this.ledger.snapshot()),deviceId,expectedRevision,"commit");const mark=this.snapshot().switchExport;if(!mark)throw new Error("This Host has not exported its domain for a switch");if(mark.digest!==receipt)throw new Error(`The receipt ${receipt} is not this Host's export ${mark.digest}`);if(!mark.devices.some(device=>device.deviceId===deviceId&&device.frozenRevision===expectedRevision)){throw new Error(`Device ${deviceId} at revision ${expectedRevision} is not a device of the export`)}const now=sealLedger(this.ledger,{source:"L",domain:this.ledger.tenant,devices:mark.devices,exportedAt:mark.exportedAt});if(now.manifest.digest!==mark.digest)throw new Error(`The ledger changed after its export: ${now.manifest.digest}, not ${mark.digest}`);this.ledger.transaction(s=>{for(const device of mark.devices)switchStep(s,device.deviceId,device.frozenRevision,"commit");});return this.topology(deviceId)})}abortSwitch(deviceId,expectedRevision){return this.exclusive(async()=>{this.ledger.transaction(s=>{const state=stateOf(s.application),step=switchStep(s,deviceId,expectedRevision,"abort");if(state.switchExport?.devices.some(device=>device.deviceId===deviceId))delete state.switchExport;return step});try{await this.process();}catch(error){return {...this.topology(deviceId),...error instanceof WakeDispatchError?{wakePending:true}:{drainError:error}}}return this.topology(deviceId)})}retain(input){return this.exclusive(async()=>retainInLedger(this.ledger,input,{contextTurnLimit:this.contextTurnLimit,handoff:this.handoff}))}recover(){return this.exclusive(async()=>{this.write((s,rows)=>{for(const row of Object.values(stateOf(s.application).channel?.deliveries??{}))recoverDelivery(row);this.sync(s,rows);});try{await this.core.recover();}finally{await this.process();}})}sync(s,rows,injected){const state=stateOf(s.application);for(const key of Object.keys(state.hostIntents??{})){if(s.intents[hash(key)])continue;delete state.hostIntents[key];for(const[taskId,reply]of Object.entries(state.replies))if(reply.turnId===key)delete state.replies[taskId];}syncHead(state,this.coalesce,this.now());reconcileDreamRoutines(s,this.dreaming,this.models(),this.now());const routines=botRoutines(Object.values(s.routines));const limits={turnLimit:this.contextTurnLimit,contextMaxBytes:this.contextMaxBytes,instructionMaxBytes:this.instructionMaxBytes,handoff:this.handoff};const materialized=advanceRoomsAndTurns(s,state,this.now(),turn=>syncTurnInLedger(this.ledger,s,rows,turn,{now:this.now(),models:Object.keys(this.models()),readOnlyToolsets:this.options.readOnlyToolsets??[],limits,historyMode:!!this.options.history,history:injected?.turns.get(turn.id),roomHistoryMode:!!this.options.roomHistory,roomHistory:injected?.rooms.get(turn.id),routines,offer:this.offer}),(key,value)=>project(s,key,value));const dreamed=syncDreams(s,{tenant:this.ledger.tenant,policy:this.dreaming,models:this.models(),instructionMaxBytes:this.instructionMaxBytes,now:this.now(),refused:botId=>botDeviceRefusal(state,botId)!==void 0,history:injected?.dreams,historyMode:!!this.options.history});settleDelegations(s,state,this.now(),(key,value)=>project(s,key,value),this.timers);reportCardDecisions(state,(key,value)=>project(s,key,value));syncTail(state,s,this.now(),(key,value)=>project(s,key,value));return materialized||dreamed}async flushReplies(){for(const d of Object.values(this.snapshot().delegations)){if(!replyCheckDue(d,this.now()))continue;const intent=this.core.intent(d.chainTurnIds.at(-1));let check={failed:true};if(intent)try{if(!this.server.tasks.agentMessage)throw new Error("Agent message readback API required");check={taskId:intent.taskId,failed:false,readback:await this.server.tasks.agentMessage(intent.taskId,intent.execution.deviceId,intent.execution.payload.agentRef)};}catch{check={taskId:intent.taskId,failed:true};}this.write(s=>{const state=stateOf(s.application);checkReply(state,state.delegations[d.id],check,this.now(),(key,value)=>project(s,key,value),this.timers.uncertainAfterMs);});}}async callConnector(card){const controller=new AbortController;let timer;const deadline=new Promise((_,reject)=>{timer=setTimeout(()=>{const error=new Error(CONNECTOR_OUTCOME_UNKNOWN);controller.abort(error);reject(error);},this.connectorTimeoutMs);});try{return await Promise.race([Promise.resolve().then(()=>this.options.connector(card.id,card.action.action,card.action.draft,controller.signal)),deadline])}finally{clearTimeout(timer);}}async flushCards(){await callCardsInLedger(this.ledger,card=>this.callConnector(card));}async flushDeliveries(){const port=this.options.channel?.port;if(!port)return;if(port.readback)for(const old of Object.values(this.snapshot().channel?.deliveries??{}).filter(row=>row.state==="unknown")){try{const result=await port.readback(old.id);this.write(s=>{const row=stateOf(s.application).channel?.deliveries[old.id];if(row)readbackDelivery(row,old.attempts,result,this.now());});}catch{continue}}for(const old of Object.values(this.snapshot().channel?.deliveries??{})){const claim=this.write(s=>{const state=stateOf(s.application),row=state.channel.deliveries[old.id];if(row.state!=="pending"||(row.nextAttemptAt??0)>this.now())return;const route=deliveryRoute(state,row,this.now());if(!route){refuseRoute(state,row);return}if(startDelivery(row,this.now()))return {row,route}});if(!claim)continue;const controller=new AbortController;let timer;const deadline=new Promise((_resolve,reject)=>{timer=setTimeout(()=>{controller.abort();reject(new Error("delivery_timeout"));},this.deliveryTimeoutMs);});try{const result=await Promise.race([Promise.resolve().then(()=>port.send({deliveryId:claim.row.id,route:claim.route,body:claim.row.body},controller.signal)),deadline]);this.write(s=>settleDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,result,this.now()));}catch{this.write(s=>unknownDelivery(stateOf(s.application).channel.deliveries[claim.row.id],claim.row.attempts,controller.signal.aborted?"send_timeout":"send_failed"));}finally{clearTimeout(timer);}}this.write(s=>cleanReplyTokens(s,stateOf(s.application),this.now()));}async syncWithHistory(){const injected=await this.readHistory();return this.write((s,rows)=>this.sync(s,rows,injected))}async readHistory(){const read=this.options.history,readRoom=this.options.roomHistory;if(!read&&!readRoom)return void 0;const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const injected={turns:new Map,rooms:new Map,dreams:new Map};for(const turn of Object.values(state.turns)){if(!awaitsOffer(ledger,state,turn)||this.unread.has(turn.id))continue;const seat=turn.source==="room_slot"?state.team.seats[turn.id]:void 0;try{if(seat&&readRoom&&!seat.released){const roomId=state.team.rounds[seat.roundId].roomId;if(Object.values(ledger.outbox).some(row=>row.kind==="projection"&&row.id.startsWith(roomMessageProjection(roomId,""))&&row.value.roomId===roomId)){this.unread.add(turn.id);continue}const ms=Math.min(this.historyTimeoutMs,seat.deadline===void 0?Infinity:seat.deadline-this.now());const rows=roomMessages(await bounded(readRoom({roomId,botId:turn.botId,turnId:turn.id}),ms));injected.rooms.set(turn.id,{rows,digest:hash(canonical(rows))});}else if(turn.source!=="room_slot"&&read){const rows=contextTurns(await bounded(read({botId:turn.botId,turnId:turn.id}),this.historyTimeoutMs));injected.turns.set(turn.id,{rows,digest:hash(canonical(rows))});}}catch{this.unread.add(turn.id);}}if(read)for(const{key,botId,turnId}of dreamReads(state)){injected.dreams.set(key,await bounded(read({botId,turnId}),this.historyTimeoutMs).then(contextTurns).catch(()=>null));}return injected}async process(){try{await this.pass();}finally{this.armTimer();}}async pass(){if(this.snapshot().switchExport)return;this.unread.clear();let failure;let more;do{await this.deliverCancels().catch(()=>{});const admitted=await this.syncWithHistory();await flushHomes(this.server,this.ledger,this.now);this.intentFailures.clear();try{await this.core.drain();}catch(error){failure??={error};}const refused=this.reportIntentFailures();if(refused)failure??={error:refused};await this.deliverCancels().catch(()=>{});let materialized=await this.syncWithHistory();await this.refreshDevices();await this.flushCards();materialized=await this.syncWithHistory()||materialized;await this.flushReplies();materialized=await this.syncWithHistory()||materialized;await this.flushDeliveries();const ledger=this.ledger.snapshot();const state=stateOf(ledger.application);more=admitted||materialized||Object.values(ledger.intents).some(intent=>intent.phase==="queued"&&intent.cancelReason&&!intent.conclusion)||Object.values(state.turns).some(turn=>turn.status!=="blocked"&&awaitsOffer(ledger,state,turn)&&!this.unread.has(turn.id));}while(more&&!failure);if(failure)throw failure.error}armTimer(){clearTimeout(this.timer);if(!this.closed&&!this.snapshot().switchExport){const ledger=this.ledger.snapshot(),state=stateOf(ledger.application);const due=[...this.options.channel?Object.values(state.channel?.deliveries??{}).filter(row=>row.state==="pending").map(row=>row.nextAttemptAt??this.now()):[],...Object.values(state.channel?.inbounds??{}).filter(row=>row.reply?.token).map(row=>row.reply.expiresAt),...collaborationDue(state,this.timers),...state.team.homeOperations.filter(op=>op.status==="pending"&&(homeSent(op)||!deviceRefusal(state,op.request.deviceId))).map(op=>Math.max(this.now()+1e3,op.retryAt??0)),...Object.values(state.delegations).filter(d=>d.cancel&&!d.cancel.delivered).map(()=>this.now()+1e3),...this.unread.size?[this.now()+1e3]:[]];if(due.length){this.timer=setTimeout(()=>{void this.drain().catch(()=>{});},Math.max(1,Math.min(6e4,Math.min(...due)-this.now())));this.timer.unref?.();}}}async refreshDevices(){if(!this.server.machines)return;if(!Object.values(this.snapshot().delegations).some(d=>!d.verdict&&!d.cancel&&(d.status==="queued"||d.status==="waiting_device")))return;let devices;let timer;try{devices=await Promise.race([this.server.machines.list(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new Error("Device discovery timed out")),1e3);})]);}catch{return}finally{clearTimeout(timer);}this.write(s=>observeDevices(s,stateOf(s.application),new Map(devices.map(d=>[d.deviceId,d.connected])),(key,value)=>project(s,key,value)));}async close(){this.closed=true;clearTimeout(this.timer);await this.chain;clearTimeout(this.timer);await this.core.close();}};function createBotPersonaProjection(){return createAgentHomeProjectionConsumer(async({projection,projectionHash,writeHomeFile})=>{if(!projection||typeof projection!=="object"||!("schemaVersion"in projection)||projection.schemaVersion!=="bot-profile.v1"||!("persona"in projection)||typeof projection.persona!=="string"||projectionHash!==`sha256:${hash(projection)}`)throw new Error("Invalid Bot persona projection");await writeHomeFile("AGENTS.md",projection.persona);})}
|
|
13
16
|
|
|
14
|
-
export { BotCollaboration, createBotPersonaProjection };
|
|
17
|
+
export { BotCollaboration, createBotPersonaProjection, inspectLedger };
|
|
15
18
|
//# sourceMappingURL=index.js.map
|
|
16
19
|
//# sourceMappingURL=index.js.map
|