@qlairoslabs/acp-client 0.9.3 → 0.10.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/CONSUMER_GUIDE.md +93 -5
- package/package.json +1 -1
- package/src/agent-conversation-contracts.ts +15 -0
- package/src/agent-conversation-errors.ts +55 -0
- package/src/agent-conversation-owner.ts +21 -1
- package/src/agent-conversation-queue.ts +30 -12
- package/src/agent-session.ts +481 -137
- package/src/agent.ts +148 -46
- package/src/checkpointing/strategy.ts +4 -1
- package/src/index.ts +1 -0
- package/src/internal-inference/contracts.ts +12 -1
- package/src/internal-inference/coordination/manager.ts +13 -1
- package/src/metering/engine.ts +13 -0
- package/src/metering/record.ts +33 -1
- package/src/observation/agent-event-bus.ts +154 -0
- package/src/observation/index.ts +8 -0
- package/src/persistence/file-registry-store.ts +11 -0
- package/src/persistence/provider-attachment.ts +46 -0
- package/src/persistence/reducer.ts +16 -3
- package/src/persistence/state-runtime.ts +7 -0
- package/src/persistence/transcript-runtime.ts +21 -0
package/src/agent.ts
CHANGED
|
@@ -59,12 +59,22 @@ import {
|
|
|
59
59
|
type NormalizedAgentObservation,
|
|
60
60
|
type ResolvedAgentAuditLogConfig,
|
|
61
61
|
} from "./audit/index.ts";
|
|
62
|
+
import { noopLogger } from "./logger.ts";
|
|
63
|
+
import {
|
|
64
|
+
CommittedRecordEventBus,
|
|
65
|
+
type AgentEventBus,
|
|
66
|
+
} from "./observation/agent-event-bus.ts";
|
|
62
67
|
import type {
|
|
63
68
|
AgentConversationOwnerLifecycle,
|
|
69
|
+
OwnedPromptCommitResult,
|
|
64
70
|
OwnedPromptCompleted,
|
|
65
71
|
OwnedPromptFailed,
|
|
66
72
|
OwnedPromptInput,
|
|
67
73
|
} from "./agent-conversation-owner.ts";
|
|
74
|
+
import { OwnedPromptPostCommitError } from "./agent-conversation-owner.ts";
|
|
75
|
+
import type {
|
|
76
|
+
ProviderAttachmentCommitAcknowledgement,
|
|
77
|
+
} from "./persistence/provider-attachment.ts";
|
|
68
78
|
import {
|
|
69
79
|
resolveInternalInferenceConfig,
|
|
70
80
|
type InternalInferenceConfig,
|
|
@@ -188,7 +198,10 @@ export class Agent {
|
|
|
188
198
|
readonly internalInferences?: InternalInferenceManager;
|
|
189
199
|
readonly checkpointing?: ConversationCheckpointCoordinator;
|
|
190
200
|
readonly audit?: AgentAuditRuntime;
|
|
201
|
+
/** Process-local stream of committed canonical conversation records. */
|
|
202
|
+
readonly events: AgentEventBus;
|
|
191
203
|
|
|
204
|
+
private readonly eventBus: CommittedRecordEventBus;
|
|
192
205
|
private readonly manager: DefaultAgentConversationManager;
|
|
193
206
|
private auditObservationTail: Promise<void> = Promise.resolve();
|
|
194
207
|
private auditObservationError: unknown;
|
|
@@ -208,6 +221,19 @@ export class Agent {
|
|
|
208
221
|
this.persistence = persistence;
|
|
209
222
|
this.adapters = adapters;
|
|
210
223
|
this.audit = audit;
|
|
224
|
+
const logger = config.conversationDefaults?.logger ?? noopLogger;
|
|
225
|
+
this.eventBus = new CommittedRecordEventBus({
|
|
226
|
+
agentSessionId: id,
|
|
227
|
+
onListenerError: ({ error, event }) => {
|
|
228
|
+
// A subscriber is observation, never operation authority: log and move on. It must
|
|
229
|
+
// not become an error record, which would recursively emit another event.
|
|
230
|
+
logger.warn("agent_event_listener_failed", {
|
|
231
|
+
error: error instanceof Error ? error.message : String(error),
|
|
232
|
+
deliverySequence: event.deliverySequence,
|
|
233
|
+
});
|
|
234
|
+
},
|
|
235
|
+
});
|
|
236
|
+
this.events = this.eventBus;
|
|
211
237
|
const checkpointing = config.checkpointing
|
|
212
238
|
? resolveConversationCheckpointingConfig(config.checkpointing)
|
|
213
239
|
: null;
|
|
@@ -309,6 +335,7 @@ export class Agent {
|
|
|
309
335
|
beginMetering: async (attempt, session) => {
|
|
310
336
|
return await this.manager.beginInternalInferenceMetering(attempt, session);
|
|
311
337
|
},
|
|
338
|
+
onCommittedRecords: (records) => this.publishCommittedRecords(records),
|
|
312
339
|
resolveAdapterId: async (requestedAdapterId, agentConversationId) => {
|
|
313
340
|
if (requestedAdapterId) {
|
|
314
341
|
adapters.require(requestedAdapterId);
|
|
@@ -427,6 +454,19 @@ export class Agent {
|
|
|
427
454
|
return await Agent.open(config);
|
|
428
455
|
}
|
|
429
456
|
|
|
457
|
+
/**
|
|
458
|
+
* Publish records whose persistence transaction has already committed.
|
|
459
|
+
*
|
|
460
|
+
* Internal to the Agent-owned persistence boundary; it is not a public write API. Keeping
|
|
461
|
+
* publication here is what makes "an event requires an assigned canonical sequence"
|
|
462
|
+
* mechanically true rather than a convention each producer must remember.
|
|
463
|
+
*
|
|
464
|
+
* @internal
|
|
465
|
+
*/
|
|
466
|
+
publishCommittedRecords(records: readonly ConversationRecord[]): void {
|
|
467
|
+
this.eventBus.publish(records);
|
|
468
|
+
}
|
|
469
|
+
|
|
430
470
|
async close(): Promise<void> {
|
|
431
471
|
if (this.closed) return;
|
|
432
472
|
this.closed = true;
|
|
@@ -439,6 +479,8 @@ export class Agent {
|
|
|
439
479
|
await this.auditObservationTail;
|
|
440
480
|
const observationError = this.auditObservationError;
|
|
441
481
|
await this.manager.stopAll();
|
|
482
|
+
// Every authorized shutdown write has finished; nothing may be observed after this.
|
|
483
|
+
this.eventBus.close();
|
|
442
484
|
await this.recordAgentAuditObservation("agent_lifecycle", "closed");
|
|
443
485
|
if (observationError !== undefined) throw observationError;
|
|
444
486
|
} catch (error) {
|
|
@@ -614,12 +656,11 @@ class DefaultAgentConversationManager implements AgentConversationManager {
|
|
|
614
656
|
const conversation = await this.start(id, summary.participants, {
|
|
615
657
|
...startConfig,
|
|
616
658
|
providerSession: "new",
|
|
617
|
-
deferProviderSessionPersistence: true,
|
|
618
659
|
});
|
|
619
660
|
try {
|
|
620
661
|
config.onRecoveryProgress?.({ stage: "seeding", checkpointId: checkpoint.checkpointId });
|
|
621
662
|
await conversation.seedRecoveryContext(seed.prompt);
|
|
622
|
-
await this.persistProviderSession(conversation, id,
|
|
663
|
+
const acknowledgement = await this.persistProviderSession(conversation, id, {
|
|
623
664
|
transitionId: `recovery-${randomUUID()}`,
|
|
624
665
|
metadata: JSON.stringify({
|
|
625
666
|
recoveryCheckpointId: checkpoint.checkpointId,
|
|
@@ -627,6 +668,7 @@ class DefaultAgentConversationManager implements AgentConversationManager {
|
|
|
627
668
|
recoveredThroughSequence: seed.recoveredThroughSequence,
|
|
628
669
|
}),
|
|
629
670
|
}, true);
|
|
671
|
+
conversation.acknowledgeProviderAttachment(acknowledgement);
|
|
630
672
|
} catch (recoveryError) {
|
|
631
673
|
this.live.delete(id);
|
|
632
674
|
await conversation.stop().catch(() => undefined);
|
|
@@ -787,7 +829,6 @@ class DefaultAgentConversationManager implements AgentConversationManager {
|
|
|
787
829
|
config: (CreateAgentConversationConfig | OpenAgentConversationConfig) & {
|
|
788
830
|
readonly providerSession: "new" | "load";
|
|
789
831
|
readonly internalSessionId?: string;
|
|
790
|
-
readonly deferProviderSessionPersistence?: boolean;
|
|
791
832
|
},
|
|
792
833
|
): Promise<AgentConversation> {
|
|
793
834
|
const releaseSetup = await this.acquireMeteringSetupLock(id);
|
|
@@ -824,15 +865,20 @@ class DefaultAgentConversationManager implements AgentConversationManager {
|
|
|
824
865
|
: { kind: "new" },
|
|
825
866
|
persistence: false,
|
|
826
867
|
});
|
|
827
|
-
|
|
828
|
-
|
|
868
|
+
const openedConversation = conversation;
|
|
869
|
+
this.live.set(id, openedConversation);
|
|
870
|
+
openedConversation.subscribe((notification) => {
|
|
829
871
|
if (notification.event.kind === "state_changed" && notification.event.state.phase === "stopped") {
|
|
830
|
-
|
|
872
|
+
// The stopped state is published before the active turn finishes its
|
|
873
|
+
// error/finalization path. Keep it discoverable to stopAll() until stop()
|
|
874
|
+
// has drained those writes, or Agent.close() may close SQLite too early.
|
|
875
|
+
void openedConversation.stop().then(() => {
|
|
876
|
+
if (this.live.get(id) === openedConversation) this.live.delete(id);
|
|
877
|
+
}, () => {
|
|
878
|
+
if (this.live.get(id) === openedConversation) this.live.delete(id);
|
|
879
|
+
});
|
|
831
880
|
}
|
|
832
881
|
});
|
|
833
|
-
if (conversation.internalSessionId && !config.deferProviderSessionPersistence) {
|
|
834
|
-
await this.persistProviderSession(conversation, id, adapterId, {}, config.providerSession === "new");
|
|
835
|
-
}
|
|
836
882
|
return conversation;
|
|
837
883
|
} catch (error) {
|
|
838
884
|
this.live.delete(id);
|
|
@@ -870,24 +916,32 @@ class DefaultAgentConversationManager implements AgentConversationManager {
|
|
|
870
916
|
private async persistProviderSession(
|
|
871
917
|
conversation: AgentConversation,
|
|
872
918
|
id: AgentConversationId,
|
|
873
|
-
adapterId: string,
|
|
874
919
|
extra: { readonly transitionId?: string; readonly metadata?: string } = {},
|
|
875
920
|
newContext = false,
|
|
876
|
-
): Promise<
|
|
877
|
-
|
|
921
|
+
): Promise<ProviderAttachmentCommitAcknowledgement> {
|
|
922
|
+
const attachment = conversation.providerAttachmentState;
|
|
923
|
+
if (attachment.kind !== "runtime_only") {
|
|
924
|
+
throw new Error("provider attachment is not awaiting persistence");
|
|
925
|
+
}
|
|
926
|
+
const descriptor = attachment.descriptor;
|
|
927
|
+
const providerSessionRecordId = `provider-${randomUUID()}`;
|
|
878
928
|
await this.agent.persistence.transaction(async (persistence) => {
|
|
879
|
-
if (newContext) await persistence.identityDelivery?.reset(id,
|
|
929
|
+
if (newContext) await persistence.identityDelivery?.reset(id, descriptor.internalSessionId);
|
|
880
930
|
await persistence.providerSessions.append({
|
|
881
|
-
providerSessionRecordId
|
|
931
|
+
providerSessionRecordId,
|
|
882
932
|
agentConversationId: id,
|
|
883
|
-
internalSessionId:
|
|
884
|
-
adapterId,
|
|
885
|
-
mode:
|
|
886
|
-
...(
|
|
887
|
-
activatedAt:
|
|
933
|
+
internalSessionId: descriptor.internalSessionId,
|
|
934
|
+
adapterId: descriptor.adapterId,
|
|
935
|
+
mode: descriptor.mode,
|
|
936
|
+
...(descriptor.model ? { model: descriptor.model } : {}),
|
|
937
|
+
activatedAt: descriptor.acquiredAt,
|
|
888
938
|
...extra,
|
|
889
939
|
});
|
|
890
940
|
});
|
|
941
|
+
return Object.freeze({
|
|
942
|
+
attachmentAttemptId: descriptor.attachmentAttemptId,
|
|
943
|
+
providerSessionRecordId,
|
|
944
|
+
});
|
|
891
945
|
}
|
|
892
946
|
}
|
|
893
947
|
|
|
@@ -933,7 +987,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
933
987
|
});
|
|
934
988
|
}
|
|
935
989
|
|
|
936
|
-
async afterPrompt(input: OwnedPromptCompleted): Promise<
|
|
990
|
+
async afterPrompt(input: OwnedPromptCompleted): Promise<OwnedPromptCommitResult> {
|
|
937
991
|
const timestamp = new Date().toISOString();
|
|
938
992
|
const status = input.result.status === "error" ? "failed" : input.result.status;
|
|
939
993
|
const records = input.result.messages.map((message, index): NewConversationRecord => ({
|
|
@@ -951,13 +1005,50 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
951
1005
|
...(message.messageId ? { providerMessageId: message.messageId } : {}),
|
|
952
1006
|
}),
|
|
953
1007
|
}));
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
1008
|
+
const persisted: ConversationRecord[] = [];
|
|
1009
|
+
let providerAttachment: ProviderAttachmentCommitAcknowledgement | undefined;
|
|
1010
|
+
await this.agent.persistence.transaction(async (persistence) => {
|
|
1011
|
+
await this.persistObservationsInTransaction(persistence, records, true, persisted);
|
|
1012
|
+
if (status === "completed" && input.providerAttachment.kind === "runtime_only") {
|
|
1013
|
+
const descriptor = input.providerAttachment.descriptor;
|
|
1014
|
+
const providerSessionRecordId = `provider-${randomUUID()}`;
|
|
1015
|
+
await persistence.identityDelivery?.reset(
|
|
1016
|
+
this.conversationId,
|
|
1017
|
+
descriptor.internalSessionId,
|
|
1018
|
+
);
|
|
1019
|
+
await persistence.providerSessions.append({
|
|
1020
|
+
providerSessionRecordId,
|
|
1021
|
+
agentConversationId: this.conversationId,
|
|
1022
|
+
internalSessionId: descriptor.internalSessionId,
|
|
1023
|
+
adapterId: descriptor.adapterId,
|
|
1024
|
+
mode: descriptor.mode,
|
|
1025
|
+
...(descriptor.model ? { model: descriptor.model } : {}),
|
|
1026
|
+
activatedAt: descriptor.acquiredAt,
|
|
1027
|
+
...(descriptor.transitionId ? { transitionId: descriptor.transitionId } : {}),
|
|
1028
|
+
});
|
|
1029
|
+
providerAttachment = Object.freeze({
|
|
1030
|
+
attachmentAttemptId: descriptor.attachmentAttemptId,
|
|
1031
|
+
providerSessionRecordId,
|
|
1032
|
+
});
|
|
1033
|
+
}
|
|
1034
|
+
});
|
|
1035
|
+
this.agent.publishCommittedRecords(persisted);
|
|
1036
|
+
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
1037
|
+
const commit: OwnedPromptCommitResult = Object.freeze({
|
|
1038
|
+
...(providerAttachment ? { providerAttachment } : {}),
|
|
1039
|
+
});
|
|
1040
|
+
try {
|
|
1041
|
+
await this.updateIdentity(Object.freeze(persisted));
|
|
1042
|
+
if (status === "completed" && input.identityDeliveryReceipt) {
|
|
1043
|
+
await this.agent.identity.delivered?.(input.identityDeliveryReceipt);
|
|
1044
|
+
}
|
|
1045
|
+
if (status === "completed") {
|
|
1046
|
+
await this.agent.checkpointing?.afterSuccessfulResponse(this.conversationId);
|
|
1047
|
+
}
|
|
1048
|
+
} catch (error) {
|
|
1049
|
+
throw new OwnedPromptPostCommitError(commit, error);
|
|
960
1050
|
}
|
|
1051
|
+
return commit;
|
|
961
1052
|
}
|
|
962
1053
|
|
|
963
1054
|
async promptFailed(input: OwnedPromptFailed): Promise<void> {
|
|
@@ -1050,6 +1141,7 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
1050
1141
|
}, this.settings.auditLog);
|
|
1051
1142
|
}
|
|
1052
1143
|
});
|
|
1144
|
+
if (reference) this.agent.publishCommittedRecords([reference]);
|
|
1053
1145
|
if (this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
1054
1146
|
if (reference) await this.updateIdentity([reference]);
|
|
1055
1147
|
}
|
|
@@ -1090,31 +1182,41 @@ class PersistedConversationLifecycle implements AgentConversationOwnerLifecycle
|
|
|
1090
1182
|
})) return Object.freeze([]);
|
|
1091
1183
|
const persisted: ConversationRecord[] = [];
|
|
1092
1184
|
await this.agent.persistence.transaction(async (persistence) => {
|
|
1093
|
-
|
|
1094
|
-
const level = record.kind === "protocol"
|
|
1095
|
-
? this.settings.capture.protocol.level
|
|
1096
|
-
: this.settings.capture[record.kind];
|
|
1097
|
-
const canonicalAccepted = level !== "none" && (
|
|
1098
|
-
record.kind !== "protocol"
|
|
1099
|
-
|| shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method)
|
|
1100
|
-
);
|
|
1101
|
-
if (canonicalAccepted) {
|
|
1102
|
-
persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
|
|
1103
|
-
}
|
|
1104
|
-
if (audit && this.settings.auditLog) {
|
|
1105
|
-
await enqueueAuditObservation(persistence, {
|
|
1106
|
-
scope: "conversation",
|
|
1107
|
-
sourceObservationId: record.recordId,
|
|
1108
|
-
operationId: operationIdFromMetadata(record.metadata),
|
|
1109
|
-
record,
|
|
1110
|
-
}, this.settings.auditLog);
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1185
|
+
await this.persistObservationsInTransaction(persistence, records, audit, persisted);
|
|
1113
1186
|
});
|
|
1187
|
+
this.agent.publishCommittedRecords(persisted);
|
|
1114
1188
|
if (audit && this.settings.auditLog) this.agent.audit?.notifyPending();
|
|
1115
1189
|
return Object.freeze(persisted);
|
|
1116
1190
|
}
|
|
1117
1191
|
|
|
1192
|
+
private async persistObservationsInTransaction(
|
|
1193
|
+
persistence: PersistenceScope,
|
|
1194
|
+
records: readonly NewConversationRecord[],
|
|
1195
|
+
audit: boolean,
|
|
1196
|
+
persisted: ConversationRecord[],
|
|
1197
|
+
): Promise<void> {
|
|
1198
|
+
for (const record of records) {
|
|
1199
|
+
const level = record.kind === "protocol"
|
|
1200
|
+
? this.settings.capture.protocol.level
|
|
1201
|
+
: this.settings.capture[record.kind];
|
|
1202
|
+
const canonicalAccepted = level !== "none" && (
|
|
1203
|
+
record.kind !== "protocol"
|
|
1204
|
+
|| shouldCaptureProtocolMethod(this.settings.capture.protocol, record.method)
|
|
1205
|
+
);
|
|
1206
|
+
if (canonicalAccepted) {
|
|
1207
|
+
persisted.push(await persistence.records.append(captureRuntimeRecord(record, level)));
|
|
1208
|
+
}
|
|
1209
|
+
if (audit && this.settings.auditLog) {
|
|
1210
|
+
await enqueueAuditObservation(persistence, {
|
|
1211
|
+
scope: "conversation",
|
|
1212
|
+
sourceObservationId: record.recordId,
|
|
1213
|
+
operationId: operationIdFromMetadata(record.metadata),
|
|
1214
|
+
record,
|
|
1215
|
+
}, this.settings.auditLog);
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
|
|
1118
1220
|
private async updateIdentity(records: readonly ConversationRecord[]): Promise<void> {
|
|
1119
1221
|
await this.agent.identity.update({
|
|
1120
1222
|
agentSessionId: this.agent.id,
|
|
@@ -79,7 +79,7 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
|
|
|
79
79
|
generatorInternalInferenceId: result.internalInferenceId,
|
|
80
80
|
summary,
|
|
81
81
|
});
|
|
82
|
-
await context.persistence.records.append({
|
|
82
|
+
const appended = await context.persistence.records.append({
|
|
83
83
|
recordId: `${result.internalInferenceId}:checkpoint`,
|
|
84
84
|
agentSessionId: context.attempt.agentSessionId,
|
|
85
85
|
agentConversationId: conversationId,
|
|
@@ -93,6 +93,9 @@ implements InternalInferenceStrategy<ConversationCheckpointPayload> {
|
|
|
93
93
|
coveredSequence: checkpoint.coveredSequence,
|
|
94
94
|
},
|
|
95
95
|
});
|
|
96
|
+
// Hand the committed record to the manager so it reaches the Agent's live bus after
|
|
97
|
+
// the completion transaction commits, exactly like every other Agent-owned record.
|
|
98
|
+
context.onRecordAppended?.(appended);
|
|
96
99
|
return Object.freeze({
|
|
97
100
|
internalInferenceId: result.internalInferenceId,
|
|
98
101
|
rootInternalInferenceId: context.attempt.rootId,
|
package/src/index.ts
CHANGED
|
@@ -2,7 +2,11 @@ import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
|
|
|
2
2
|
import type { AgentSessionMeteringState } from "../metering/state.ts";
|
|
3
3
|
import type { OperationMeteringRecord, OperationOutcome } from "../metering/record.ts";
|
|
4
4
|
import type { StatefulSubscribable, Subscribable } from "../observation/contracts.ts";
|
|
5
|
-
import type {
|
|
5
|
+
import type {
|
|
6
|
+
ConversationRecord,
|
|
7
|
+
PersistenceJsonValue,
|
|
8
|
+
PersistenceScope,
|
|
9
|
+
} from "../persistence/backend.ts";
|
|
6
10
|
import type { ResponseMessage, TokenUsage } from "../types.ts";
|
|
7
11
|
|
|
8
12
|
export type InternalInferenceId = `aii-${string}`;
|
|
@@ -202,6 +206,13 @@ export interface InternalInferenceCompletionContext {
|
|
|
202
206
|
/** Transaction-scoped persistence used to publish the purpose artifact atomically. */
|
|
203
207
|
readonly persistence: PersistenceScope;
|
|
204
208
|
readonly meteringState?: AgentSessionMeteringState;
|
|
209
|
+
/**
|
|
210
|
+
* Register a canonical record appended in this completion transaction for post-commit
|
|
211
|
+
* publication. The manager publishes it only after the transaction commits, so a
|
|
212
|
+
* rolled-back completion is never observed. Strategies that append no canonical record
|
|
213
|
+
* simply do not call it.
|
|
214
|
+
*/
|
|
215
|
+
readonly onRecordAppended?: (record: ConversationRecord) => void;
|
|
205
216
|
}
|
|
206
217
|
|
|
207
218
|
export interface InternalInferenceStrategy<TPayload = PersistenceJsonValue> {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import type { AgentSessionId } from "../../agent-ids.ts";
|
|
3
|
-
import type { PersistenceBackend } from "../../persistence/backend.ts";
|
|
3
|
+
import type { ConversationRecord, PersistenceBackend } from "../../persistence/backend.ts";
|
|
4
4
|
import type { OperationMeteringRecord } from "../../metering/record.ts";
|
|
5
5
|
import { SubscriptionHub } from "../../observation/subscription-hub.ts";
|
|
6
6
|
import { createInternalInferenceId } from "../ids.ts";
|
|
@@ -43,6 +43,13 @@ export interface DefaultInternalInferenceManagerConfig {
|
|
|
43
43
|
) => Promise<InternalInferenceMeteringOperation | null>;
|
|
44
44
|
readonly meteringRecords?: import("../../persistence/backend.ts").MeteringRecordRetention;
|
|
45
45
|
readonly pollIntervalMs?: number;
|
|
46
|
+
/**
|
|
47
|
+
* Observe canonical records appended by a strategy's completion, after the transaction
|
|
48
|
+
* that wrote them commits. The Agent uses this to publish internal-inference artifacts
|
|
49
|
+
* (such as conversation-checkpoint `native_action` records) through the same committed
|
|
50
|
+
* record stream as every other Agent-owned record.
|
|
51
|
+
*/
|
|
52
|
+
readonly onCommittedRecords?: (records: readonly ConversationRecord[]) => void;
|
|
46
53
|
}
|
|
47
54
|
|
|
48
55
|
/** Agent-scoped durable scheduler. Purpose-specific artifact transactions remain strategies' responsibility. */
|
|
@@ -274,10 +281,14 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
274
281
|
? await openedMetering.close({ outcome: "completed", result })
|
|
275
282
|
: null;
|
|
276
283
|
if (this.fenced.has(attempt.internalInferenceId)) return;
|
|
284
|
+
// Canonical records a strategy appends here are buffered and published only after
|
|
285
|
+
// the transaction commits; a rollback must leave them unobserved.
|
|
286
|
+
const appended: ConversationRecord[] = [];
|
|
277
287
|
const completed = await this.config.persistence.transaction(async (persistence) => {
|
|
278
288
|
const completion = await strategy.complete({
|
|
279
289
|
attempt: snapshotOf(attempt),
|
|
280
290
|
persistence,
|
|
291
|
+
onRecordAppended: (record) => appended.push(record),
|
|
281
292
|
}, result);
|
|
282
293
|
if (this.fenced.has(attempt.internalInferenceId)) {
|
|
283
294
|
throw new Error("internal inference was fenced during completion");
|
|
@@ -309,6 +320,7 @@ export class DefaultInternalInferenceManager implements InternalInferenceManager
|
|
|
309
320
|
: {}),
|
|
310
321
|
});
|
|
311
322
|
});
|
|
323
|
+
if (appended.length > 0) this.config.onCommittedRecords?.(appended);
|
|
312
324
|
this.publishAttempt(completed);
|
|
313
325
|
await this.refreshRun(attempt.rootInternalInferenceId);
|
|
314
326
|
await this.pruneTerminal();
|
package/src/metering/engine.ts
CHANGED
|
@@ -905,6 +905,19 @@ export class MeteringEngine {
|
|
|
905
905
|
* provider usage, and pretending otherwise would put a fabricated operation in the
|
|
906
906
|
* consumer's ledger.
|
|
907
907
|
*/
|
|
908
|
+
/**
|
|
909
|
+
* Adopt totals accumulated by a parallel engine that is being discarded.
|
|
910
|
+
*
|
|
911
|
+
* A transition meters its target on its own engine, because the target's counters start
|
|
912
|
+
* at zero. When the transition fails, those operations were still minted, reported and
|
|
913
|
+
* paid for, so their totals belong to the session that remains. Unlike `reconcile` this
|
|
914
|
+
* is not a correction: nothing this engine measured was wrong, so its own baseline and
|
|
915
|
+
* any block it is under both stand.
|
|
916
|
+
*/
|
|
917
|
+
adoptAccounting(state: AgentSessionMeteringState): void {
|
|
918
|
+
this.state = Object.freeze({ ...state, activeBaseline: this.state.activeBaseline });
|
|
919
|
+
}
|
|
920
|
+
|
|
908
921
|
reconcile(state: AgentSessionMeteringState): { before: AgentSessionMeteringState } {
|
|
909
922
|
const before = this.state;
|
|
910
923
|
this.state = state;
|
package/src/metering/record.ts
CHANGED
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// to assert it cost zero, which is the difference between "we don't know" and a false
|
|
10
10
|
// accounting entry.
|
|
11
11
|
|
|
12
|
-
import type { TokenUsage } from "../types.ts";
|
|
12
|
+
import type { PromptResult, TokenUsage } from "../types.ts";
|
|
13
13
|
import type { ContextWindowStatus, ProviderCostSnapshot } from "./context.ts";
|
|
14
14
|
import type { Money } from "./money.ts";
|
|
15
15
|
import type { AttributableUsage } from "./rating.ts";
|
|
@@ -261,18 +261,50 @@ export class AgentSessionOperationError extends Error {
|
|
|
261
261
|
* A rejected handoff cannot return a HandoffResult, but the summary and seed prompts it
|
|
262
262
|
* already ran consumed real tokens, so their records must still reach the caller.
|
|
263
263
|
*/
|
|
264
|
+
export interface AgentSessionHandoffErrorDetails {
|
|
265
|
+
readonly fromInternalSessionId?: string | null;
|
|
266
|
+
/** Present once the provider returned an id for the target. */
|
|
267
|
+
readonly toInternalSessionId?: string;
|
|
268
|
+
/** Local attachment state of the target, when one was created. */
|
|
269
|
+
readonly providerAttachment?: "runtime_only" | "recorded";
|
|
270
|
+
/** Whether the target became the recorded continuation before the failure. */
|
|
271
|
+
readonly activationCompleted?: boolean;
|
|
272
|
+
readonly summary?: string;
|
|
273
|
+
/** Result of `targetPrompt`, including a non-completed one that caused this failure. */
|
|
274
|
+
readonly targetResult?: PromptResult;
|
|
275
|
+
}
|
|
276
|
+
|
|
264
277
|
export class AgentSessionHandoffError extends Error {
|
|
265
278
|
readonly handoffId: string;
|
|
266
279
|
readonly meteringRecords: readonly OperationMeteringRecord[];
|
|
280
|
+
readonly fromInternalSessionId: string | null;
|
|
281
|
+
readonly toInternalSessionId?: string;
|
|
282
|
+
readonly providerAttachment?: "runtime_only" | "recorded";
|
|
283
|
+
/**
|
|
284
|
+
* Distinguishes a target that never superseded the source from one that already did.
|
|
285
|
+
*
|
|
286
|
+
* A target prompt can fail after the target is the recorded continuation; that is an
|
|
287
|
+
* operation failure, not an activation rollback, and the two need different handling.
|
|
288
|
+
*/
|
|
289
|
+
readonly activationCompleted: boolean;
|
|
290
|
+
readonly summary?: string;
|
|
291
|
+
readonly targetResult?: PromptResult;
|
|
267
292
|
|
|
268
293
|
constructor(
|
|
269
294
|
handoffId: string,
|
|
270
295
|
meteringRecords: readonly OperationMeteringRecord[],
|
|
271
296
|
cause: unknown,
|
|
297
|
+
details: AgentSessionHandoffErrorDetails = {},
|
|
272
298
|
) {
|
|
273
299
|
super(cause instanceof Error ? cause.message : String(cause), { cause });
|
|
274
300
|
this.name = "AgentSessionHandoffError";
|
|
275
301
|
this.handoffId = handoffId;
|
|
276
302
|
this.meteringRecords = Object.freeze([...meteringRecords]);
|
|
303
|
+
this.fromInternalSessionId = details.fromInternalSessionId ?? null;
|
|
304
|
+
if (details.toInternalSessionId !== undefined) this.toInternalSessionId = details.toInternalSessionId;
|
|
305
|
+
if (details.providerAttachment !== undefined) this.providerAttachment = details.providerAttachment;
|
|
306
|
+
this.activationCompleted = details.activationCompleted ?? false;
|
|
307
|
+
if (details.summary !== undefined) this.summary = details.summary;
|
|
308
|
+
if (details.targetResult !== undefined) this.targetResult = details.targetResult;
|
|
277
309
|
}
|
|
278
310
|
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import type { AgentConversationId, AgentSessionId } from "../agent-ids.ts";
|
|
2
|
+
import {
|
|
3
|
+
isConversationRecordKind,
|
|
4
|
+
type ConversationRecord,
|
|
5
|
+
type ConversationRecordKind,
|
|
6
|
+
} from "../persistence/backend.ts";
|
|
7
|
+
import type { Subscribable, Unsubscribe } from "./contracts.ts";
|
|
8
|
+
import { SubscriptionHub, type SubscriptionListenerError } from "./subscription-hub.ts";
|
|
9
|
+
|
|
10
|
+
/** Declarative selection of committed records. Filters are fixed for one subscription. */
|
|
11
|
+
export interface AgentEventSubscriptionOptions {
|
|
12
|
+
/** Undefined means every Agent-owned conversation. An empty array selects nothing. */
|
|
13
|
+
readonly conversationIds?: readonly AgentConversationId[];
|
|
14
|
+
/** Undefined means every canonical conversation-record kind. An empty array selects nothing. */
|
|
15
|
+
readonly recordKinds?: readonly ConversationRecordKind[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ConversationRecordCommittedEvent {
|
|
19
|
+
readonly kind: "conversation_record_committed";
|
|
20
|
+
readonly record: ConversationRecord;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type AgentEvent = ConversationRecordCommittedEvent;
|
|
24
|
+
|
|
25
|
+
export interface AgentEventNotification {
|
|
26
|
+
/** Process-local order assigned before subscriber filtering. Not a durable cursor. */
|
|
27
|
+
readonly deliverySequence: number;
|
|
28
|
+
/** Time at which the committed record was offered to listeners. */
|
|
29
|
+
readonly emittedAt: string;
|
|
30
|
+
readonly agentSessionId: AgentSessionId;
|
|
31
|
+
readonly event: AgentEvent;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type AgentEventListener = (notification: AgentEventNotification) => void;
|
|
35
|
+
|
|
36
|
+
export interface AgentEventBus extends Subscribable<AgentEventNotification> {
|
|
37
|
+
subscribe(listener: AgentEventListener, options?: AgentEventSubscriptionOptions): Unsubscribe;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface AgentEventBusOptions {
|
|
41
|
+
readonly agentSessionId: AgentSessionId;
|
|
42
|
+
readonly onListenerError?: (failure: SubscriptionListenerError<AgentEventNotification>) => void;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
type RecordFilter = (record: ConversationRecord) => boolean;
|
|
46
|
+
|
|
47
|
+
function compileFilter(options: AgentEventSubscriptionOptions): RecordFilter {
|
|
48
|
+
const conversationIds = compileConversationIds(options.conversationIds);
|
|
49
|
+
const recordKinds = compileRecordKinds(options.recordKinds);
|
|
50
|
+
return (record) =>
|
|
51
|
+
(conversationIds === null || conversationIds.has(record.agentConversationId))
|
|
52
|
+
&& (recordKinds === null || recordKinds.has(record.kind));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function compileConversationIds(
|
|
56
|
+
ids: readonly AgentConversationId[] | undefined,
|
|
57
|
+
): ReadonlySet<AgentConversationId> | null {
|
|
58
|
+
if (ids === undefined) return null;
|
|
59
|
+
if (!Array.isArray(ids)) {
|
|
60
|
+
throw new TypeError("agent event subscription conversationIds must be an array");
|
|
61
|
+
}
|
|
62
|
+
const normalized = new Set<AgentConversationId>();
|
|
63
|
+
for (const id of ids) {
|
|
64
|
+
if (typeof id !== "string" || id.trim() === "") {
|
|
65
|
+
throw new TypeError("agent event subscription conversationIds must contain non-blank strings");
|
|
66
|
+
}
|
|
67
|
+
normalized.add(id as AgentConversationId);
|
|
68
|
+
}
|
|
69
|
+
return normalized;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function compileRecordKinds(
|
|
73
|
+
kinds: readonly ConversationRecordKind[] | undefined,
|
|
74
|
+
): ReadonlySet<ConversationRecordKind> | null {
|
|
75
|
+
if (kinds === undefined) return null;
|
|
76
|
+
if (!Array.isArray(kinds)) {
|
|
77
|
+
throw new TypeError("agent event subscription recordKinds must be an array");
|
|
78
|
+
}
|
|
79
|
+
const normalized = new Set<ConversationRecordKind>();
|
|
80
|
+
for (const kind of kinds) {
|
|
81
|
+
if (!isConversationRecordKind(kind)) {
|
|
82
|
+
throw new TypeError(`agent event subscription received an unknown record kind: ${String(kind)}`);
|
|
83
|
+
}
|
|
84
|
+
normalized.add(kind);
|
|
85
|
+
}
|
|
86
|
+
return normalized;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Process-local observation of committed canonical conversation records.
|
|
91
|
+
*
|
|
92
|
+
* Not durable, not replayable, and never a source of truth: SQLite remains authoritative.
|
|
93
|
+
* A record is published only after the transaction that appended it commits, and every
|
|
94
|
+
* physical append emits one notification, so evolving records produce one event per
|
|
95
|
+
* revision. Consumers reconcile those by canonical identity exactly as a reload would.
|
|
96
|
+
*/
|
|
97
|
+
export class CommittedRecordEventBus implements AgentEventBus {
|
|
98
|
+
private readonly hub: SubscriptionHub<AgentEventNotification>;
|
|
99
|
+
private deliverySequence = 0;
|
|
100
|
+
private subscriptionCount = 0;
|
|
101
|
+
private closed = false;
|
|
102
|
+
|
|
103
|
+
constructor(private readonly options: AgentEventBusOptions) {
|
|
104
|
+
this.hub = new SubscriptionHub(options.onListenerError);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
subscribe(listener: AgentEventListener, options: AgentEventSubscriptionOptions = {}): Unsubscribe {
|
|
108
|
+
if (typeof listener !== "function") {
|
|
109
|
+
throw new TypeError("agent event subscription listener must be a function");
|
|
110
|
+
}
|
|
111
|
+
const matches = compileFilter(options);
|
|
112
|
+
this.subscriptionCount += 1;
|
|
113
|
+
const unsubscribe = this.hub.subscribe((notification) => {
|
|
114
|
+
if (!matches(notification.event.record)) return;
|
|
115
|
+
listener(notification);
|
|
116
|
+
});
|
|
117
|
+
let subscribed = true;
|
|
118
|
+
return () => {
|
|
119
|
+
if (!subscribed) return;
|
|
120
|
+
subscribed = false;
|
|
121
|
+
this.subscriptionCount -= 1;
|
|
122
|
+
unsubscribe();
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @internal Publish records whose persistence transaction has already committed. */
|
|
127
|
+
publish(records: readonly ConversationRecord[]): void {
|
|
128
|
+
// No subscribers means no notification to allocate; the delivery sequence is
|
|
129
|
+
// process-local and never a durable cursor, so skipping it is unobservable.
|
|
130
|
+
if (this.closed || this.subscriptionCount === 0 || records.length === 0) return;
|
|
131
|
+
const ordered = records.length > 1
|
|
132
|
+
? [...records].sort((left, right) => left.sequence - right.sequence)
|
|
133
|
+
: records;
|
|
134
|
+
for (const record of ordered) {
|
|
135
|
+
const notification: AgentEventNotification = Object.freeze({
|
|
136
|
+
deliverySequence: (this.deliverySequence += 1),
|
|
137
|
+
emittedAt: new Date().toISOString(),
|
|
138
|
+
agentSessionId: this.options.agentSessionId,
|
|
139
|
+
event: Object.freeze({
|
|
140
|
+
kind: "conversation_record_committed" as const,
|
|
141
|
+
record,
|
|
142
|
+
}),
|
|
143
|
+
});
|
|
144
|
+
this.hub.emit(notification);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** @internal Prevent further publication and drop every subscription. */
|
|
149
|
+
close(): void {
|
|
150
|
+
this.closed = true;
|
|
151
|
+
this.subscriptionCount = 0;
|
|
152
|
+
this.hub.clear();
|
|
153
|
+
}
|
|
154
|
+
}
|
package/src/observation/index.ts
CHANGED
|
@@ -6,3 +6,11 @@ export type {
|
|
|
6
6
|
} from "./contracts.ts";
|
|
7
7
|
export { SubscriptionHub } from "./subscription-hub.ts";
|
|
8
8
|
export type { SubscriptionListenerError } from "./subscription-hub.ts";
|
|
9
|
+
export type {
|
|
10
|
+
AgentEvent,
|
|
11
|
+
AgentEventBus,
|
|
12
|
+
AgentEventListener,
|
|
13
|
+
AgentEventNotification,
|
|
14
|
+
AgentEventSubscriptionOptions,
|
|
15
|
+
ConversationRecordCommittedEvent,
|
|
16
|
+
} from "./agent-event-bus.ts";
|