@fabric-harness/sdk 6.3.0 → 6.5.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/connector-spec/voice-telephony.md +120 -104
- package/dist/agent-route.d.ts +22 -2
- package/dist/agent-route.d.ts.map +1 -1
- package/dist/agent-route.js +32 -1
- package/dist/agent-route.js.map +1 -1
- package/dist/agent-router.d.ts +46 -0
- package/dist/agent-router.d.ts.map +1 -1
- package/dist/agent-router.js +63 -2
- package/dist/agent-router.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +3 -0
- package/dist/agent.js.map +1 -1
- package/dist/attachment-store.d.ts +69 -0
- package/dist/attachment-store.d.ts.map +1 -1
- package/dist/attachment-store.js +183 -14
- package/dist/attachment-store.js.map +1 -1
- package/dist/attachments.d.ts +136 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +332 -0
- package/dist/attachments.js.map +1 -0
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +26 -3
- package/dist/channel.js.map +1 -1
- package/dist/conversation-history.d.ts +186 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +481 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/conversation-ui.d.ts +43 -2
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +44 -14
- package/dist/conversation-ui.js.map +1 -1
- package/dist/cost-budget.d.ts +50 -0
- package/dist/cost-budget.d.ts.map +1 -1
- package/dist/cost-budget.js +74 -4
- package/dist/cost-budget.js.map +1 -1
- package/dist/cost-enforcement.d.ts +32 -0
- package/dist/cost-enforcement.d.ts.map +1 -0
- package/dist/cost-enforcement.js +116 -0
- package/dist/cost-enforcement.js.map +1 -0
- package/dist/delivered-message.d.ts +20 -6
- package/dist/delivered-message.d.ts.map +1 -1
- package/dist/delivered-message.js +37 -8
- package/dist/delivered-message.js.map +1 -1
- package/dist/events.d.ts +16 -2
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/experimental.d.ts +2 -2
- package/dist/experimental.d.ts.map +1 -1
- package/dist/experimental.js +1 -1
- package/dist/experimental.js.map +1 -1
- package/dist/governed-voice.d.ts +6 -0
- package/dist/governed-voice.d.ts.map +1 -1
- package/dist/governed-voice.js +142 -35
- package/dist/governed-voice.js.map +1 -1
- package/dist/history.d.ts +3 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +57 -23
- package/dist/history.js.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +25 -2
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +409 -60
- package/dist/loop.js.map +1 -1
- package/dist/model-pricing.d.ts +77 -4
- package/dist/model-pricing.d.ts.map +1 -1
- package/dist/model-pricing.js +259 -18
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts +115 -3
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +376 -57
- package/dist/model.js.map +1 -1
- package/dist/otel-observer.d.ts +3 -1
- package/dist/otel-observer.d.ts.map +1 -1
- package/dist/otel-observer.js +40 -8
- package/dist/otel-observer.js.map +1 -1
- package/dist/persistent-agent.d.ts +5 -0
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js +9 -1
- package/dist/persistent-agent.js.map +1 -1
- package/dist/pi-document-attachments.d.ts +43 -0
- package/dist/pi-document-attachments.d.ts.map +1 -0
- package/dist/pi-document-attachments.js +155 -0
- package/dist/pi-document-attachments.js.map +1 -0
- package/dist/pi-loop-runtime.d.ts +103 -1
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +850 -109
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/prompt-attachments.d.ts +98 -0
- package/dist/prompt-attachments.d.ts.map +1 -0
- package/dist/prompt-attachments.js +279 -0
- package/dist/prompt-attachments.js.map +1 -0
- package/dist/session.d.ts +52 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +410 -33
- package/dist/session.js.map +1 -1
- package/dist/stream-chunks.d.ts +15 -1
- package/dist/stream-chunks.d.ts.map +1 -1
- package/dist/stream-chunks.js +39 -18
- package/dist/stream-chunks.js.map +1 -1
- package/dist/strict.d.ts +23 -16
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +12 -8
- package/dist/strict.js.map +1 -1
- package/dist/submission-context.d.ts +7 -0
- package/dist/submission-context.d.ts.map +1 -1
- package/dist/submission-context.js.map +1 -1
- package/dist/submission-runner.d.ts +5 -0
- package/dist/submission-runner.d.ts.map +1 -1
- package/dist/submission-runner.js +97 -13
- package/dist/submission-runner.js.map +1 -1
- package/dist/submission-store-contract.d.ts.map +1 -1
- package/dist/submission-store-contract.js +15 -1
- package/dist/submission-store-contract.js.map +1 -1
- package/dist/submission-store.d.ts +12 -0
- package/dist/submission-store.d.ts.map +1 -1
- package/dist/submission-store.js +13 -4
- package/dist/submission-store.js.map +1 -1
- package/dist/trace-content.d.ts +21 -0
- package/dist/trace-content.d.ts.map +1 -0
- package/dist/trace-content.js +69 -0
- package/dist/trace-content.js.map +1 -0
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/usage-completeness.d.ts +39 -0
- package/dist/usage-completeness.d.ts.map +1 -0
- package/dist/usage-completeness.js +135 -0
- package/dist/usage-completeness.js.map +1 -0
- package/dist/voice-openai-realtime.d.ts +24 -2
- package/dist/voice-openai-realtime.d.ts.map +1 -1
- package/dist/voice-openai-realtime.js +266 -49
- package/dist/voice-openai-realtime.js.map +1 -1
- package/dist/voice-pipeline.d.ts +81 -3
- package/dist/voice-pipeline.d.ts.map +1 -1
- package/dist/voice-pipeline.js +429 -60
- package/dist/voice-pipeline.js.map +1 -1
- package/dist/voice-stt-cartesia.d.ts +8 -0
- package/dist/voice-stt-cartesia.d.ts.map +1 -1
- package/dist/voice-stt-cartesia.js +77 -17
- package/dist/voice-stt-cartesia.js.map +1 -1
- package/dist/voice-stt-deepgram.d.ts +10 -2
- package/dist/voice-stt-deepgram.d.ts.map +1 -1
- package/dist/voice-stt-deepgram.js +78 -18
- package/dist/voice-stt-deepgram.js.map +1 -1
- package/dist/voice-stt.d.ts +13 -3
- package/dist/voice-stt.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.d.ts +8 -0
- package/dist/voice-tts-cartesia.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.js +48 -105
- package/dist/voice-tts-cartesia.js.map +1 -1
- package/dist/voice-tts-elevenlabs.d.ts +10 -1
- package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
- package/dist/voice-tts-elevenlabs.js +50 -113
- package/dist/voice-tts-elevenlabs.js.map +1 -1
- package/dist/voice-ws-client.js +16 -3
- package/dist/voice-ws-client.js.map +1 -1
- package/dist/voice-ws-shared.d.ts +205 -6
- package/dist/voice-ws-shared.d.ts.map +1 -1
- package/dist/voice-ws-shared.js +510 -15
- package/dist/voice-ws-shared.js.map +1 -1
- package/dist/voice.d.ts +98 -4
- package/dist/voice.d.ts.map +1 -1
- package/dist/voice.js +71 -1
- package/dist/voice.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { type ConversationStreamRecord, type ConversationStreamStore } from './conversation-stream.js';
|
|
2
|
+
import type { SessionEntry } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Bounded conversation history reads.
|
|
5
|
+
*
|
|
6
|
+
* A long-running persistent conversation should not force a client to fetch
|
|
7
|
+
* and fold every record before it can render the latest exchange. A history
|
|
8
|
+
* window is a contiguous range of the conversation's **active path** (the
|
|
9
|
+
* entries that survive every truncation), selected by projected message count
|
|
10
|
+
* and returned as ordinary entry records, so every existing fold
|
|
11
|
+
* (`projectConversationRecords`, React stores, custom reducers) consumes it
|
|
12
|
+
* unchanged.
|
|
13
|
+
*
|
|
14
|
+
* - `limit=N` — the newest N messages, through the head. Carries `offset`, so
|
|
15
|
+
* it can seed a live observation.
|
|
16
|
+
* - `from=<cursor>` — everything from the cursor's entry through the head.
|
|
17
|
+
* Carries `offset`; used to re-hydrate a window a client already holds.
|
|
18
|
+
* - `before=<cursor>[&limit=N]` — an older page strictly before the cursor.
|
|
19
|
+
* Carries no `offset`: a page cannot seed an observation.
|
|
20
|
+
*
|
|
21
|
+
* **Closure.** A window never splits a dependency. Its start expands backward
|
|
22
|
+
* until no entry inside it depends on an entry before it (a tool result on
|
|
23
|
+
* its tool call; message data and response metadata on the assistant message
|
|
24
|
+
* they decorate, or on the pending data a later assistant message absorbs),
|
|
25
|
+
* and until it holds every message that can still change live (open tool
|
|
26
|
+
* calls and the current assistant message and prompt of every unsettled
|
|
27
|
+
* submission that recorded an entry within the newest 200 messages; an older
|
|
28
|
+
* unsettled submission is treated as abandoned so it cannot pin every window).
|
|
29
|
+
* A window may therefore exceed `limit`. Pages are disjoint entry
|
|
30
|
+
* ranges, each self-projecting, and concatenating them oldest-first yields the
|
|
31
|
+
* full projection.
|
|
32
|
+
*
|
|
33
|
+
* **Settlements.** A settlement that sits before the window start but settles
|
|
34
|
+
* a submission referenced inside it is delivered in `settlements`, so a client
|
|
35
|
+
* never mistakes an old, finished submission for active work. Fold
|
|
36
|
+
* `settlements` before `records` (see {@link conversationHistoryRecords}).
|
|
37
|
+
*
|
|
38
|
+
* **Cursors** are opaque, versioned tokens bound to the stream incarnation. A
|
|
39
|
+
* cursor from another incarnation, or naming an entry no longer on the active
|
|
40
|
+
* path (for example one rewound by a truncation), is gone:
|
|
41
|
+
* {@link ConversationHistoryError} with code `history_cursor_not_found`, which
|
|
42
|
+
* HTTP surfaces map to `410`. Clients must not construct or interpret cursors.
|
|
43
|
+
*/
|
|
44
|
+
export interface ConversationHistoryWindow {
|
|
45
|
+
v: 1;
|
|
46
|
+
/** Stream generation the window and its cursors belong to; `null` when no stream exists yet. */
|
|
47
|
+
incarnation: string | null;
|
|
48
|
+
/** Contiguous active-path entry records in path order. */
|
|
49
|
+
records: ConversationHistoryEntryRecord[];
|
|
50
|
+
/**
|
|
51
|
+
* `submission_settled` entry records located before the window whose
|
|
52
|
+
* submission is referenced inside it, in path order. Fold before `records`.
|
|
53
|
+
*/
|
|
54
|
+
settlements: ConversationHistoryEntryRecord[];
|
|
55
|
+
/** Cursor for the next older page, or `null` when the window starts at the conversation origin. */
|
|
56
|
+
before: string | null;
|
|
57
|
+
/**
|
|
58
|
+
* Cursor naming the window's first entry (`null` when the window is empty).
|
|
59
|
+
* Pass it as `from` to re-hydrate everything the client holds from here on.
|
|
60
|
+
*/
|
|
61
|
+
anchor: string | null;
|
|
62
|
+
/**
|
|
63
|
+
* Stream position after the head the window was read at. Present on `limit`
|
|
64
|
+
* and `from` windows (continue a live observation from it); absent on
|
|
65
|
+
* `before` pages.
|
|
66
|
+
*/
|
|
67
|
+
offset?: string;
|
|
68
|
+
}
|
|
69
|
+
export type ConversationHistoryEntryRecord = Extract<ConversationStreamRecord, {
|
|
70
|
+
kind: 'entry';
|
|
71
|
+
}>;
|
|
72
|
+
/** A validated history request. Use {@link parseConversationHistoryRequest} for query strings. */
|
|
73
|
+
export type ConversationHistoryRequest = {
|
|
74
|
+
kind: 'newest';
|
|
75
|
+
limit?: number;
|
|
76
|
+
} | {
|
|
77
|
+
kind: 'from';
|
|
78
|
+
from: string;
|
|
79
|
+
} | {
|
|
80
|
+
kind: 'before';
|
|
81
|
+
before: string;
|
|
82
|
+
limit?: number;
|
|
83
|
+
};
|
|
84
|
+
export type ConversationHistoryErrorCode = 'history_cursor_not_found' | 'invalid_history_request' | 'history_read_incomplete';
|
|
85
|
+
/**
|
|
86
|
+
* Typed history failure. `status` is the HTTP status every Harness surface
|
|
87
|
+
* returns for it: `410` for a gone cursor, `400` for an invalid request, and
|
|
88
|
+
* `503` when the backing stream stopped advancing before reaching its head.
|
|
89
|
+
*/
|
|
90
|
+
export declare class ConversationHistoryError extends Error {
|
|
91
|
+
readonly code: ConversationHistoryErrorCode;
|
|
92
|
+
readonly status: 400 | 410 | 503;
|
|
93
|
+
constructor(code: ConversationHistoryErrorCode, message: string);
|
|
94
|
+
/** Public error envelope, `{ error: { code, type, message } }`. */
|
|
95
|
+
toResponseBody(): {
|
|
96
|
+
error: {
|
|
97
|
+
code: string;
|
|
98
|
+
type: string;
|
|
99
|
+
message: string;
|
|
100
|
+
};
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
export declare function isConversationHistoryError(error: unknown): error is ConversationHistoryError;
|
|
104
|
+
/** Largest `limit` a history read accepts (the conversation read maximum). */
|
|
105
|
+
export declare const CONVERSATION_HISTORY_MAX_LIMIT = 1000;
|
|
106
|
+
/** Encode an opaque history cursor for one entry in one stream incarnation. */
|
|
107
|
+
export declare function encodeConversationHistoryCursor(incarnation: string, entryId: string): string;
|
|
108
|
+
/**
|
|
109
|
+
* Parse and validate `limit`, `before`, and `from` query parameters.
|
|
110
|
+
* Throws {@link ConversationHistoryError} (`invalid_history_request`) for a
|
|
111
|
+
* malformed cursor or limit, a repeated parameter, `before` with `from`, or
|
|
112
|
+
* `from` with `limit`.
|
|
113
|
+
*/
|
|
114
|
+
export declare function parseConversationHistoryRequest(params: URLSearchParams): ConversationHistoryRequest;
|
|
115
|
+
/** Validate a structured history request (the programmatic twin of the query parser). */
|
|
116
|
+
export declare function validateConversationHistoryRequest(input: {
|
|
117
|
+
limit?: number;
|
|
118
|
+
before?: string;
|
|
119
|
+
from?: string;
|
|
120
|
+
}): ConversationHistoryRequest;
|
|
121
|
+
/** Records to fold for a window: carried settlements first, then the window's entries. */
|
|
122
|
+
export declare function conversationHistoryRecords(window: Pick<ConversationHistoryWindow, 'records' | 'settlements'>): ConversationStreamRecord[];
|
|
123
|
+
/** Fold stream records into the active path (truncations rewind it). */
|
|
124
|
+
export declare function activeConversationEntries(records: readonly ConversationStreamRecord[]): SessionEntry[];
|
|
125
|
+
/**
|
|
126
|
+
* Select a history window from a conversation's complete stream records.
|
|
127
|
+
*
|
|
128
|
+
* `records` must be every record from the stream origin through `offset`
|
|
129
|
+
* (truncations included); the window is computed on their active path.
|
|
130
|
+
* Throws {@link ConversationHistoryError} when a cursor is gone.
|
|
131
|
+
*/
|
|
132
|
+
export declare function selectConversationHistoryWindow(input: {
|
|
133
|
+
records: readonly ConversationStreamRecord[];
|
|
134
|
+
incarnation: string | null;
|
|
135
|
+
offset: string;
|
|
136
|
+
request: ConversationHistoryRequest;
|
|
137
|
+
}): ConversationHistoryWindow;
|
|
138
|
+
/** One page of a transport-level conversation read. */
|
|
139
|
+
export interface ConversationHistorySourcePage {
|
|
140
|
+
incarnation: string | null;
|
|
141
|
+
batches: Array<{
|
|
142
|
+
offset: string;
|
|
143
|
+
records: readonly unknown[];
|
|
144
|
+
}>;
|
|
145
|
+
nextOffset: string;
|
|
146
|
+
upToDate: boolean;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Default bound on stream records one history read may scan (folded
|
|
150
|
+
* checkpoint records count once each). A conversation longer than this
|
|
151
|
+
* without a fold checkpoint fails with `history_read_incomplete` instead of
|
|
152
|
+
* holding a request for an unbounded scan.
|
|
153
|
+
*/
|
|
154
|
+
export declare const CONVERSATION_HISTORY_MAX_SCAN_RECORDS = 250000;
|
|
155
|
+
/** Options shared by the history readers. */
|
|
156
|
+
export interface ConversationHistoryReadOptions {
|
|
157
|
+
/**
|
|
158
|
+
* Cancels the read between pages (pass the HTTP request's signal). An
|
|
159
|
+
* aborted read stops paging and rejects with the signal's reason.
|
|
160
|
+
*/
|
|
161
|
+
signal?: AbortSignal;
|
|
162
|
+
/**
|
|
163
|
+
* Most stream records the read may scan before failing with
|
|
164
|
+
* `history_read_incomplete`. Defaults to
|
|
165
|
+
* {@link CONVERSATION_HISTORY_MAX_SCAN_RECORDS}.
|
|
166
|
+
*/
|
|
167
|
+
maxRecords?: number;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Read a conversation to its head through any offset-paged reader and select a
|
|
171
|
+
* history window. Used by hosts whose conversation reads are already paged
|
|
172
|
+
* (the mountable router's backend). Restarts when the stream incarnation
|
|
173
|
+
* changes mid-read, and fails after repeated changes. Stops paging when
|
|
174
|
+
* `options.signal` aborts, and fails with `history_read_incomplete` once more
|
|
175
|
+
* than `options.maxRecords` records have been scanned.
|
|
176
|
+
*/
|
|
177
|
+
export declare function readConversationHistoryFromPages(readPage: (offset: string, signal?: AbortSignal) => Promise<ConversationHistorySourcePage>, request: ConversationHistoryRequest, options?: ConversationHistoryReadOptions): Promise<ConversationHistoryWindow>;
|
|
178
|
+
/**
|
|
179
|
+
* Read a history window straight from a {@link ConversationStreamStore},
|
|
180
|
+
* starting from its fold checkpoint when one exists. A missing stream yields
|
|
181
|
+
* an empty window for `newest` reads and a gone cursor for `before`/`from`.
|
|
182
|
+
* Honors `options.signal` and `options.maxRecords` like
|
|
183
|
+
* {@link readConversationHistoryFromPages}.
|
|
184
|
+
*/
|
|
185
|
+
export declare function readConversationHistory(store: ConversationStreamStore, path: string, request: ConversationHistoryRequest, options?: ConversationHistoryReadOptions): Promise<ConversationHistoryWindow>;
|
|
186
|
+
//# sourceMappingURL=conversation-history.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"conversation-history.d.ts","sourceRoot":"","sources":["../src/conversation-history.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,481 @@
|
|
|
1
|
+
import { CONVERSATION_STREAM_MAX_READ_LIMIT, ConversationStreamStoreError, readConversationFromFold, } from './conversation-stream.js';
|
|
2
|
+
const HISTORY_ERROR_STATUS = {
|
|
3
|
+
history_cursor_not_found: 410,
|
|
4
|
+
invalid_history_request: 400,
|
|
5
|
+
history_read_incomplete: 503,
|
|
6
|
+
};
|
|
7
|
+
const HISTORY_ERROR_TYPE = {
|
|
8
|
+
history_cursor_not_found: 'gone',
|
|
9
|
+
invalid_history_request: 'invalid_request',
|
|
10
|
+
history_read_incomplete: 'unavailable',
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Typed history failure. `status` is the HTTP status every Harness surface
|
|
14
|
+
* returns for it: `410` for a gone cursor, `400` for an invalid request, and
|
|
15
|
+
* `503` when the backing stream stopped advancing before reaching its head.
|
|
16
|
+
*/
|
|
17
|
+
export class ConversationHistoryError extends Error {
|
|
18
|
+
code;
|
|
19
|
+
status;
|
|
20
|
+
constructor(code, message) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = 'ConversationHistoryError';
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.status = HISTORY_ERROR_STATUS[code];
|
|
25
|
+
}
|
|
26
|
+
/** Public error envelope, `{ error: { code, type, message } }`. */
|
|
27
|
+
toResponseBody() {
|
|
28
|
+
return {
|
|
29
|
+
error: {
|
|
30
|
+
code: this.code,
|
|
31
|
+
type: HISTORY_ERROR_TYPE[this.code],
|
|
32
|
+
message: this.message,
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
export function isConversationHistoryError(error) {
|
|
38
|
+
return error instanceof ConversationHistoryError;
|
|
39
|
+
}
|
|
40
|
+
/** Largest `limit` a history read accepts (the conversation read maximum). */
|
|
41
|
+
export const CONVERSATION_HISTORY_MAX_LIMIT = CONVERSATION_STREAM_MAX_READ_LIMIT;
|
|
42
|
+
const CURSOR_PREFIX = 'hc1.';
|
|
43
|
+
/** Encode an opaque history cursor for one entry in one stream incarnation. */
|
|
44
|
+
export function encodeConversationHistoryCursor(incarnation, entryId) {
|
|
45
|
+
const bytes = new TextEncoder().encode(JSON.stringify([incarnation, entryId]));
|
|
46
|
+
let binary = '';
|
|
47
|
+
for (const byte of bytes)
|
|
48
|
+
binary += String.fromCharCode(byte);
|
|
49
|
+
return CURSOR_PREFIX + btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
50
|
+
}
|
|
51
|
+
function decodeCursor(token, name) {
|
|
52
|
+
const invalid = () => new ConversationHistoryError('invalid_history_request', `History "${name}" must be a cursor returned by a previous history read.`);
|
|
53
|
+
if (!token.startsWith(CURSOR_PREFIX) || token.length > 4096)
|
|
54
|
+
throw invalid();
|
|
55
|
+
const body = token.slice(CURSOR_PREFIX.length);
|
|
56
|
+
if (!/^[A-Za-z0-9_-]+$/.test(body))
|
|
57
|
+
throw invalid();
|
|
58
|
+
try {
|
|
59
|
+
const binary = atob(body.replace(/-/g, '+').replace(/_/g, '/'));
|
|
60
|
+
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
61
|
+
const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
|
|
62
|
+
if (!Array.isArray(value) ||
|
|
63
|
+
value.length !== 2 ||
|
|
64
|
+
typeof value[0] !== 'string' ||
|
|
65
|
+
typeof value[1] !== 'string' ||
|
|
66
|
+
value[0] === '' ||
|
|
67
|
+
value[1] === '') {
|
|
68
|
+
throw invalid();
|
|
69
|
+
}
|
|
70
|
+
return { token, incarnation: value[0], entryId: value[1] };
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
throw invalid();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function validLimit(limit) {
|
|
77
|
+
if (typeof limit !== 'number' ||
|
|
78
|
+
!Number.isSafeInteger(limit) ||
|
|
79
|
+
limit < 1 ||
|
|
80
|
+
limit > CONVERSATION_HISTORY_MAX_LIMIT) {
|
|
81
|
+
throw new ConversationHistoryError('invalid_history_request', `History "limit" must be an integer from 1 to ${CONVERSATION_HISTORY_MAX_LIMIT}.`);
|
|
82
|
+
}
|
|
83
|
+
return limit;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Parse and validate `limit`, `before`, and `from` query parameters.
|
|
87
|
+
* Throws {@link ConversationHistoryError} (`invalid_history_request`) for a
|
|
88
|
+
* malformed cursor or limit, a repeated parameter, `before` with `from`, or
|
|
89
|
+
* `from` with `limit`.
|
|
90
|
+
*/
|
|
91
|
+
export function parseConversationHistoryRequest(params) {
|
|
92
|
+
for (const name of ['limit', 'before', 'from']) {
|
|
93
|
+
if (params.getAll(name).length > 1) {
|
|
94
|
+
throw new ConversationHistoryError('invalid_history_request', `History reads accept at most one "${name}".`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const rawLimit = params.get('limit');
|
|
98
|
+
const limit = rawLimit === null
|
|
99
|
+
? undefined
|
|
100
|
+
: validLimit(/^[1-9][0-9]{0,15}$/.test(rawLimit) ? Number(rawLimit) : Number.NaN);
|
|
101
|
+
const before = params.get('before');
|
|
102
|
+
const from = params.get('from');
|
|
103
|
+
return validateConversationHistoryRequest({
|
|
104
|
+
...(limit !== undefined ? { limit } : {}),
|
|
105
|
+
...(before !== null ? { before } : {}),
|
|
106
|
+
...(from !== null ? { from } : {}),
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/** Validate a structured history request (the programmatic twin of the query parser). */
|
|
110
|
+
export function validateConversationHistoryRequest(input) {
|
|
111
|
+
const limit = input.limit === undefined ? undefined : validLimit(input.limit);
|
|
112
|
+
if (input.before !== undefined && input.from !== undefined) {
|
|
113
|
+
throw new ConversationHistoryError('invalid_history_request', 'History reads accept "before" or "from", not both.');
|
|
114
|
+
}
|
|
115
|
+
if (input.from !== undefined) {
|
|
116
|
+
if (limit !== undefined) {
|
|
117
|
+
throw new ConversationHistoryError('invalid_history_request', 'History "from" reads return everything through the head and do not accept "limit".');
|
|
118
|
+
}
|
|
119
|
+
decodeCursor(input.from, 'from');
|
|
120
|
+
return { kind: 'from', from: input.from };
|
|
121
|
+
}
|
|
122
|
+
if (input.before !== undefined) {
|
|
123
|
+
decodeCursor(input.before, 'before');
|
|
124
|
+
return { kind: 'before', before: input.before, ...(limit !== undefined ? { limit } : {}) };
|
|
125
|
+
}
|
|
126
|
+
return { kind: 'newest', ...(limit !== undefined ? { limit } : {}) };
|
|
127
|
+
}
|
|
128
|
+
/** Records to fold for a window: carried settlements first, then the window's entries. */
|
|
129
|
+
export function conversationHistoryRecords(window) {
|
|
130
|
+
return [...window.settlements, ...window.records];
|
|
131
|
+
}
|
|
132
|
+
/** Fold stream records into the active path (truncations rewind it). */
|
|
133
|
+
export function activeConversationEntries(records) {
|
|
134
|
+
const active = [];
|
|
135
|
+
for (const record of records) {
|
|
136
|
+
if (record.kind === 'entry') {
|
|
137
|
+
active.push(record.entry);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
const keep = record.rewoundTo
|
|
141
|
+
? active.findIndex((entry) => entry.id === record.rewoundTo) + 1
|
|
142
|
+
: 0;
|
|
143
|
+
active.length = Math.max(0, keep);
|
|
144
|
+
}
|
|
145
|
+
return active;
|
|
146
|
+
}
|
|
147
|
+
const LEGACY_KEY = '__current__';
|
|
148
|
+
/**
|
|
149
|
+
* Message starts, counted back from the head, within which an unsettled
|
|
150
|
+
* submission must have recorded an entry to keep pinning history windows.
|
|
151
|
+
*/
|
|
152
|
+
const LIVE_SUBMISSION_HORIZON = 200;
|
|
153
|
+
function dataString(entry, key) {
|
|
154
|
+
const value = entry.data?.[key];
|
|
155
|
+
return typeof value === 'string' ? value : undefined;
|
|
156
|
+
}
|
|
157
|
+
function isRecord(value) {
|
|
158
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Mirror of `projectConversationRecords`' cross-entry state, recording which
|
|
162
|
+
* earlier entry each entry's projection reads. Kept beside the projection's
|
|
163
|
+
* semantics by the "pages concatenate to the full projection" contract tests.
|
|
164
|
+
*/
|
|
165
|
+
function analyzeEntries(entries) {
|
|
166
|
+
const messageStarts = [];
|
|
167
|
+
const dependsOn = entries.map((_, index) => index);
|
|
168
|
+
const toolMessage = new Map();
|
|
169
|
+
const openCalls = new Map();
|
|
170
|
+
const currentAssistant = new Map();
|
|
171
|
+
const pending = new Map();
|
|
172
|
+
const settled = new Set();
|
|
173
|
+
const firstEntryOf = new Map();
|
|
174
|
+
const lastEntryOf = new Map();
|
|
175
|
+
let lastPrompt = -1;
|
|
176
|
+
entries.forEach((entry, index) => {
|
|
177
|
+
const submissionId = dataString(entry, 'submissionId');
|
|
178
|
+
const key = submissionId ?? LEGACY_KEY;
|
|
179
|
+
if (entry.type === 'submission_settled') {
|
|
180
|
+
if (submissionId)
|
|
181
|
+
settled.add(submissionId);
|
|
182
|
+
return;
|
|
183
|
+
}
|
|
184
|
+
if (submissionId) {
|
|
185
|
+
if (!firstEntryOf.has(submissionId))
|
|
186
|
+
firstEntryOf.set(submissionId, index);
|
|
187
|
+
lastEntryOf.set(submissionId, index);
|
|
188
|
+
}
|
|
189
|
+
switch (entry.type) {
|
|
190
|
+
case 'user_prompt':
|
|
191
|
+
currentAssistant.delete(key);
|
|
192
|
+
pending.delete(key);
|
|
193
|
+
lastPrompt = index;
|
|
194
|
+
messageStarts.push(index);
|
|
195
|
+
return;
|
|
196
|
+
case 'assistant_message': {
|
|
197
|
+
for (const source of pending.get(key) ?? []) {
|
|
198
|
+
dependsOn[index] = Math.min(dependsOn[index] ?? index, source);
|
|
199
|
+
}
|
|
200
|
+
pending.delete(key);
|
|
201
|
+
currentAssistant.set(key, index);
|
|
202
|
+
messageStarts.push(index);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
case 'message_data':
|
|
206
|
+
case 'response_metadata': {
|
|
207
|
+
if (entry.type === 'message_data' && !dataString(entry, 'name'))
|
|
208
|
+
return;
|
|
209
|
+
if (entry.type === 'response_metadata') {
|
|
210
|
+
if (!isRecord(entry.data?.metadata))
|
|
211
|
+
return;
|
|
212
|
+
if (entry.data?.phase === 'start')
|
|
213
|
+
currentAssistant.delete(key);
|
|
214
|
+
}
|
|
215
|
+
const target = currentAssistant.get(key);
|
|
216
|
+
if (target !== undefined)
|
|
217
|
+
dependsOn[index] = target;
|
|
218
|
+
else
|
|
219
|
+
pending.set(key, [...(pending.get(key) ?? []), index]);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
case 'tool_call': {
|
|
223
|
+
const callId = dataString(entry, 'toolCallId') ?? entry.id;
|
|
224
|
+
toolMessage.set(callId, index);
|
|
225
|
+
openCalls.set(callId, index);
|
|
226
|
+
messageStarts.push(index);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
case 'tool_result': {
|
|
230
|
+
const callId = dataString(entry, 'toolCallId');
|
|
231
|
+
if (!callId)
|
|
232
|
+
return;
|
|
233
|
+
openCalls.delete(callId);
|
|
234
|
+
const existing = toolMessage.get(callId);
|
|
235
|
+
if (existing !== undefined)
|
|
236
|
+
dependsOn[index] = existing;
|
|
237
|
+
else {
|
|
238
|
+
toolMessage.set(callId, index);
|
|
239
|
+
messageStarts.push(index);
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
case 'signal':
|
|
244
|
+
case 'error':
|
|
245
|
+
messageStarts.push(index);
|
|
246
|
+
return;
|
|
247
|
+
default:
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
// An unsettled submission pins the window only while it is still active:
|
|
252
|
+
// its newest entry lies within the newest LIVE_SUBMISSION_HORIZON message
|
|
253
|
+
// starts. A submission whose process died without settling (a zombie)
|
|
254
|
+
// otherwise expands every later window back to its first entry forever.
|
|
255
|
+
const horizon = messageStarts.length > LIVE_SUBMISSION_HORIZON
|
|
256
|
+
? messageStarts[messageStarts.length - LIVE_SUBMISSION_HORIZON]
|
|
257
|
+
: 0;
|
|
258
|
+
const active = (submissionId) => !settled.has(submissionId) && (lastEntryOf.get(submissionId) ?? -1) >= horizon;
|
|
259
|
+
// Anything that can still change live. Legacy entries (no submission id)
|
|
260
|
+
// have no settlement, so only the trailing turn after the last prompt counts.
|
|
261
|
+
const live = (index) => {
|
|
262
|
+
const submissionId = dataString(entries[index], 'submissionId');
|
|
263
|
+
return submissionId ? active(submissionId) : index > lastPrompt;
|
|
264
|
+
};
|
|
265
|
+
let liveMin = Number.POSITIVE_INFINITY;
|
|
266
|
+
const consider = (index) => {
|
|
267
|
+
if (index !== undefined && live(index))
|
|
268
|
+
liveMin = Math.min(liveMin, index);
|
|
269
|
+
};
|
|
270
|
+
for (const index of openCalls.values())
|
|
271
|
+
consider(index);
|
|
272
|
+
for (const index of currentAssistant.values())
|
|
273
|
+
consider(index);
|
|
274
|
+
for (const indices of pending.values())
|
|
275
|
+
for (const index of indices)
|
|
276
|
+
consider(index);
|
|
277
|
+
for (const [submissionId, index] of firstEntryOf) {
|
|
278
|
+
if (active(submissionId))
|
|
279
|
+
liveMin = Math.min(liveMin, index);
|
|
280
|
+
}
|
|
281
|
+
return { messageStarts, dependsOn, liveMin };
|
|
282
|
+
}
|
|
283
|
+
/** Expand `start` backward until no entry in `[start, end)` depends on an entry before it. */
|
|
284
|
+
function closeStart(dependsOn, start, end) {
|
|
285
|
+
let closed = start;
|
|
286
|
+
for (;;) {
|
|
287
|
+
let min = closed;
|
|
288
|
+
for (let index = closed; index < end; index += 1) {
|
|
289
|
+
const dependency = dependsOn[index] ?? index;
|
|
290
|
+
if (dependency < min)
|
|
291
|
+
min = dependency;
|
|
292
|
+
}
|
|
293
|
+
if (min >= closed)
|
|
294
|
+
return closed;
|
|
295
|
+
closed = min;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
function startForLimit(messageStarts, end, limit) {
|
|
299
|
+
if (limit === undefined)
|
|
300
|
+
return 0;
|
|
301
|
+
const inRange = messageStarts.filter((index) => index < end);
|
|
302
|
+
return inRange.length > limit ? inRange[inRange.length - limit] : 0;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Select a history window from a conversation's complete stream records.
|
|
306
|
+
*
|
|
307
|
+
* `records` must be every record from the stream origin through `offset`
|
|
308
|
+
* (truncations included); the window is computed on their active path.
|
|
309
|
+
* Throws {@link ConversationHistoryError} when a cursor is gone.
|
|
310
|
+
*/
|
|
311
|
+
export function selectConversationHistoryWindow(input) {
|
|
312
|
+
const entries = activeConversationEntries(input.records);
|
|
313
|
+
const { request, incarnation } = input;
|
|
314
|
+
const resolve = (token, name) => {
|
|
315
|
+
const cursor = decodeCursor(token, name);
|
|
316
|
+
const index = incarnation !== null && cursor.incarnation === incarnation
|
|
317
|
+
? entries.findIndex((entry) => entry.id === cursor.entryId)
|
|
318
|
+
: -1;
|
|
319
|
+
if (index < 0) {
|
|
320
|
+
throw new ConversationHistoryError('history_cursor_not_found', 'The history cursor no longer names an entry in this conversation.');
|
|
321
|
+
}
|
|
322
|
+
return index;
|
|
323
|
+
};
|
|
324
|
+
const analysis = analyzeEntries(entries);
|
|
325
|
+
let start;
|
|
326
|
+
let end = entries.length;
|
|
327
|
+
if (request.kind === 'before') {
|
|
328
|
+
end = resolve(request.before, 'before');
|
|
329
|
+
start = closeStart(analysis.dependsOn, startForLimit(analysis.messageStarts, end, request.limit), end);
|
|
330
|
+
}
|
|
331
|
+
else {
|
|
332
|
+
const requested = request.kind === 'from'
|
|
333
|
+
? resolve(request.from, 'from')
|
|
334
|
+
: startForLimit(analysis.messageStarts, end, request.limit);
|
|
335
|
+
start = closeStart(analysis.dependsOn, Math.min(requested, analysis.liveMin), end);
|
|
336
|
+
}
|
|
337
|
+
const selected = entries.slice(start, end);
|
|
338
|
+
const referenced = new Set();
|
|
339
|
+
for (const entry of selected) {
|
|
340
|
+
const submissionId = dataString(entry, 'submissionId');
|
|
341
|
+
if (submissionId)
|
|
342
|
+
referenced.add(submissionId);
|
|
343
|
+
}
|
|
344
|
+
const settlements = entries
|
|
345
|
+
.slice(0, start)
|
|
346
|
+
.filter((entry) => {
|
|
347
|
+
const submissionId = dataString(entry, 'submissionId');
|
|
348
|
+
return entry.type === 'submission_settled' && submissionId !== undefined && referenced.has(submissionId);
|
|
349
|
+
});
|
|
350
|
+
const cursor = (index) => {
|
|
351
|
+
const entry = entries[index];
|
|
352
|
+
return entry && incarnation !== null ? encodeConversationHistoryCursor(incarnation, entry.id) : null;
|
|
353
|
+
};
|
|
354
|
+
const anchor = selected.length > 0 ? cursor(start) : null;
|
|
355
|
+
return {
|
|
356
|
+
v: 1,
|
|
357
|
+
incarnation,
|
|
358
|
+
records: selected.map((entry) => ({ kind: 'entry', entry })),
|
|
359
|
+
settlements: settlements.map((entry) => ({ kind: 'entry', entry })),
|
|
360
|
+
before: start > 0 ? cursor(start) : null,
|
|
361
|
+
anchor,
|
|
362
|
+
...(request.kind === 'before' ? {} : { offset: input.offset }),
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* Default bound on stream records one history read may scan (folded
|
|
367
|
+
* checkpoint records count once each). A conversation longer than this
|
|
368
|
+
* without a fold checkpoint fails with `history_read_incomplete` instead of
|
|
369
|
+
* holding a request for an unbounded scan.
|
|
370
|
+
*/
|
|
371
|
+
export const CONVERSATION_HISTORY_MAX_SCAN_RECORDS = 250_000;
|
|
372
|
+
/** Internal: the stream changed generation while one page was being read. */
|
|
373
|
+
class RestartHistoryRead extends Error {
|
|
374
|
+
}
|
|
375
|
+
const MAX_HEAD_READ_ATTEMPTS = 3;
|
|
376
|
+
/**
|
|
377
|
+
* Read a conversation to its head through any offset-paged reader and select a
|
|
378
|
+
* history window. Used by hosts whose conversation reads are already paged
|
|
379
|
+
* (the mountable router's backend). Restarts when the stream incarnation
|
|
380
|
+
* changes mid-read, and fails after repeated changes. Stops paging when
|
|
381
|
+
* `options.signal` aborts, and fails with `history_read_incomplete` once more
|
|
382
|
+
* than `options.maxRecords` records have been scanned.
|
|
383
|
+
*/
|
|
384
|
+
export async function readConversationHistoryFromPages(readPage, request, options = {}) {
|
|
385
|
+
const { signal } = options;
|
|
386
|
+
const maxRecords = options.maxRecords ?? CONVERSATION_HISTORY_MAX_SCAN_RECORDS;
|
|
387
|
+
for (let attempt = 0; attempt < MAX_HEAD_READ_ATTEMPTS; attempt += 1) {
|
|
388
|
+
const records = [];
|
|
389
|
+
let offset = '0';
|
|
390
|
+
let incarnation;
|
|
391
|
+
let consistent = true;
|
|
392
|
+
for (let pageCount = 0;; pageCount += 1) {
|
|
393
|
+
signal?.throwIfAborted();
|
|
394
|
+
// Every non-final page advances the offset, so a head more than
|
|
395
|
+
// `maxRecords` pages away is past the bound even when pages are empty.
|
|
396
|
+
if (pageCount > maxRecords) {
|
|
397
|
+
throw new ConversationHistoryError('history_read_incomplete', `The conversation exceeds the history scan bound of ${maxRecords} records.`);
|
|
398
|
+
}
|
|
399
|
+
let page;
|
|
400
|
+
try {
|
|
401
|
+
page = await readPage(offset, signal);
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
if (error instanceof RestartHistoryRead) {
|
|
405
|
+
consistent = false;
|
|
406
|
+
break;
|
|
407
|
+
}
|
|
408
|
+
throw error;
|
|
409
|
+
}
|
|
410
|
+
signal?.throwIfAborted();
|
|
411
|
+
if (incarnation === undefined)
|
|
412
|
+
incarnation = page.incarnation;
|
|
413
|
+
else if (page.incarnation !== incarnation) {
|
|
414
|
+
consistent = false;
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
// Check the bound before copying, and append one record at a time: a
|
|
418
|
+
// fold checkpoint can carry a batch far larger than the argument limit
|
|
419
|
+
// of `push(...batch)`, which would throw RangeError.
|
|
420
|
+
for (const batch of page.batches) {
|
|
421
|
+
const batchRecords = batch.records;
|
|
422
|
+
if (records.length + batchRecords.length > maxRecords) {
|
|
423
|
+
throw new ConversationHistoryError('history_read_incomplete', `The conversation exceeds the history scan bound of ${maxRecords} records.`);
|
|
424
|
+
}
|
|
425
|
+
for (const record of batchRecords)
|
|
426
|
+
records.push(record);
|
|
427
|
+
}
|
|
428
|
+
const advanced = page.nextOffset !== offset;
|
|
429
|
+
offset = page.nextOffset;
|
|
430
|
+
if (page.upToDate)
|
|
431
|
+
break;
|
|
432
|
+
if (!advanced) {
|
|
433
|
+
// Selecting a window from a partial prefix would silently return
|
|
434
|
+
// stale history (and wrong closure), so a stalled backend fails.
|
|
435
|
+
throw new ConversationHistoryError('history_read_incomplete', 'The conversation stream stopped advancing before reaching its head.');
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (!consistent)
|
|
439
|
+
continue;
|
|
440
|
+
return selectConversationHistoryWindow({
|
|
441
|
+
records,
|
|
442
|
+
incarnation: incarnation ?? null,
|
|
443
|
+
offset,
|
|
444
|
+
request,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
throw new Error('Conversation stream was recreated repeatedly during a history read.');
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Read a history window straight from a {@link ConversationStreamStore},
|
|
451
|
+
* starting from its fold checkpoint when one exists. A missing stream yields
|
|
452
|
+
* an empty window for `newest` reads and a gone cursor for `before`/`from`.
|
|
453
|
+
* Honors `options.signal` and `options.maxRecords` like
|
|
454
|
+
* {@link readConversationHistoryFromPages}.
|
|
455
|
+
*/
|
|
456
|
+
export async function readConversationHistory(store, path, request, options = {}) {
|
|
457
|
+
return readConversationHistoryFromPages(async (offset) => {
|
|
458
|
+
const meta = await store.getMeta(path);
|
|
459
|
+
if (!meta)
|
|
460
|
+
return { incarnation: null, batches: [], nextOffset: offset, upToDate: true };
|
|
461
|
+
let page;
|
|
462
|
+
try {
|
|
463
|
+
page = await readConversationFromFold(store, path, {
|
|
464
|
+
offset,
|
|
465
|
+
limit: CONVERSATION_STREAM_MAX_READ_LIMIT,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
catch (error) {
|
|
469
|
+
if (error instanceof ConversationStreamStoreError && error.code === 'STREAM_NOT_FOUND') {
|
|
470
|
+
throw new RestartHistoryRead();
|
|
471
|
+
}
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
const after = await store.getMeta(path);
|
|
475
|
+
// A delete-and-recreate around this page restarts the whole read.
|
|
476
|
+
if (after?.incarnation !== meta.incarnation)
|
|
477
|
+
throw new RestartHistoryRead();
|
|
478
|
+
return { incarnation: meta.incarnation, ...page };
|
|
479
|
+
}, request, options);
|
|
480
|
+
}
|
|
481
|
+
//# sourceMappingURL=conversation-history.js.map
|