@deepseek-ai/dsh-session-persistence-jsonl 0.2.1-alpha.1 → 0.2.1-alpha.3
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.i18n.yaml +10 -10
- package/README.md +9 -1
- package/README.zh.md +9 -1
- package/lib/index.js +198 -83
- package/lib/types/index.d.ts +16 -249
- package/lib/types/migration-verifier.d.ts +1 -1
- package/lib/types/storage.d.ts +4 -3
- package/lib/worker.cjs +158 -37
- package/locale/en.json +5 -0
- package/locale/zh.json +6 -0
- package/package.json +18 -15
package/lib/types/index.d.ts
CHANGED
|
@@ -7,15 +7,11 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { Context } from '@deepseek-ai/cordis';
|
|
9
9
|
import z from '@deepseek-ai/schemastery';
|
|
10
|
-
import { SessionPersistence, type SessionAccess, type SessionHandle, type SessionHandleReadResult, type SessionPersistenceCreateOptions, type SessionPersistenceListOptions, type SessionPersistenceOpenOptions, type SessionPersistenceSnapshot, type SessionPersistenceStatOptions, type SessionPersistenceRevision as PersistenceRevision } from '@deepseek-ai/dsh-session-persistence';
|
|
11
|
-
import { JsonlSessionHandle } from './storage.ts';
|
|
12
|
-
import { SessionWriteLease } from './lease.ts';
|
|
13
|
-
import type { SessionEvent, SessionId, SessionHeader, SessionLogOffset as SessionLogOffsetType } from '@deepseek-ai/dsh-session';
|
|
14
10
|
import { type JsonlCompression } from './format.ts';
|
|
15
11
|
export type { JsonlCompression } from './format.ts';
|
|
16
12
|
/** Loader schema for the JSONL artifact's physical encoding. */
|
|
17
13
|
export declare const JsonlCompressionSchema: z<JsonlCompression>;
|
|
18
|
-
/** Plugin config for the JSONL backend's root and
|
|
14
|
+
/** Plugin config for the JSONL backend's root, physical encoding, and listing concurrency. */
|
|
19
15
|
export interface Config {
|
|
20
16
|
/**
|
|
21
17
|
* Root directory for all session files. Required (no default): a default of
|
|
@@ -27,253 +23,24 @@ export interface Config {
|
|
|
27
23
|
root: string;
|
|
28
24
|
/** Physical encoding; defaults to checksummed Zstandard frames. */
|
|
29
25
|
compression?: JsonlCompression;
|
|
30
|
-
}
|
|
31
|
-
/** One stored event graph whose producer has established immutable sharing. */
|
|
32
|
-
interface FrozenStoredEvents extends SessionHandleReadResult {
|
|
33
|
-
readonly eventState: 'shared-frozen';
|
|
34
|
-
}
|
|
35
|
-
/** State shared by prepared historical and published current logs. */
|
|
36
|
-
interface StoredLogBase extends FrozenStoredEvents {
|
|
37
|
-
readonly meta: SessionHeader;
|
|
38
|
-
readonly tornTruncateTo: number | undefined;
|
|
39
|
-
/** Complete events recovered from the torn final frame; the write path rewrites them durably. */
|
|
40
|
-
readonly recoveredTail: SessionEvent[];
|
|
41
|
-
/** Exact fork-inherited prefix length stored in the header line. */
|
|
42
|
-
readonly inheritedEventCount: SessionLogOffsetType;
|
|
43
|
-
readonly revision: PersistenceRevision;
|
|
44
|
-
}
|
|
45
|
-
/** A decoded current generation that is already durable. */
|
|
46
|
-
interface CurrentStoredLog extends StoredLogBase {
|
|
47
|
-
readonly status: 'current';
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* The JSONL persistence backend. Load as a plugin; it registers as
|
|
51
|
-
* `ctx.sessionPersistence`. Sessions materialize lazily: a created session is
|
|
52
|
-
* visible to this process immediately, reaches disk on its first append or
|
|
53
|
-
* flush, and never existed if the process crashes before that.
|
|
54
|
-
*/
|
|
55
|
-
declare class JsonlSessionPersistence extends SessionPersistence {
|
|
56
|
-
config: Config;
|
|
57
|
-
static Config: z<Config>;
|
|
58
|
-
/** Backend label for diagnostics and effects; shadows `Service.name` without changing the service key. */
|
|
59
|
-
readonly name = "session-persistence-jsonl";
|
|
60
|
-
private root;
|
|
61
|
-
private compression;
|
|
62
|
-
private rootEncodingCheck;
|
|
63
|
-
private readonly tracker;
|
|
64
|
-
private readonly generationFormat;
|
|
65
|
-
/**
|
|
66
|
-
* Bounded LRU of parsed, validated stored logs keyed by session id and
|
|
67
|
-
* guarded by the stat-derived revision, so an immediate cold-read handoff
|
|
68
|
-
* (observation then resume) parses the artifact once. Every local mutation
|
|
69
|
-
* for an id invalidates its entry; a foreign write misses through the
|
|
70
|
-
* revision guard.
|
|
71
|
-
*/
|
|
72
|
-
private readonly coldLogMemo;
|
|
73
|
-
/** One joinable decode/migration operation per selected historical Session file revision. */
|
|
74
|
-
private readonly migrationPreparations;
|
|
75
|
-
constructor(ctx: Context, config: Config);
|
|
76
|
-
/**
|
|
77
|
-
* Refusal-diagnostics hook: the absolute target path, without touching the filesystem.
|
|
78
|
-
* @param meta - the stored header naming the session and its cwd.
|
|
79
|
-
* @returns the artifact kind and absolute path.
|
|
80
|
-
*/
|
|
81
|
-
private locate;
|
|
82
|
-
/**
|
|
83
|
-
* Create a new stored session and take its write ownership. The session is
|
|
84
|
-
* visible to this process immediately; the physical artifact appears on the
|
|
85
|
-
* first append or flush.
|
|
86
|
-
* @param header - the immutable header to store; must be losslessly
|
|
87
|
-
* JSON-serializable with a non-negative safe-integer `createdAt`.
|
|
88
|
-
* @param options - optional cancellation.
|
|
89
|
-
* @returns the owned write handle.
|
|
90
|
-
*/
|
|
91
|
-
create(header: SessionHeader, options?: SessionPersistenceCreateOptions): Promise<SessionHandle>;
|
|
92
|
-
/**
|
|
93
|
-
* Open an existing stored session for `read` or single-writer `write`.
|
|
94
|
-
* @param id - the stored session to open.
|
|
95
|
-
* @param access - `read` (no ownership) or `write` (atomic in-process claim).
|
|
96
|
-
* @param options - optional cancellation.
|
|
97
|
-
* @returns the open handle.
|
|
98
|
-
*/
|
|
99
|
-
open(id: SessionId, access: SessionAccess, options?: SessionPersistenceOpenOptions): Promise<SessionHandle>;
|
|
100
|
-
/**
|
|
101
|
-
* Flush every active write handle in one durability barrier; see the seam
|
|
102
|
-
* contract.
|
|
103
|
-
* @returns resolution once every write handle active at the call has flushed.
|
|
104
|
-
*/
|
|
105
|
-
flush(): Promise<void>;
|
|
106
|
-
/**
|
|
107
|
-
* Observe one stored session without reading its event log.
|
|
108
|
-
* @param id - the stored session to observe.
|
|
109
|
-
* @param options - optional cancellation.
|
|
110
|
-
* @returns the snapshot (`sizeBytes` carries the physical artifact size), or
|
|
111
|
-
* `undefined` when the session does not exist.
|
|
112
|
-
*/
|
|
113
|
-
stat(id: SessionId, options?: SessionPersistenceStatOptions): Promise<SessionPersistenceSnapshot | undefined>;
|
|
114
|
-
/**
|
|
115
|
-
* List every stored session visible to this process: materialized artifacts
|
|
116
|
-
* plus this process's created-but-unmaterialized sessions.
|
|
117
|
-
* @param options - optional cancellation.
|
|
118
|
-
* @returns one snapshot per session, in no promised order.
|
|
119
|
-
*/
|
|
120
|
-
list(options?: SessionPersistenceListOptions): Promise<readonly SessionPersistenceSnapshot[]>;
|
|
121
|
-
/** Resolve and read one stored log, refusing loudly when the artifact is absent. */
|
|
122
|
-
private requireStoredLog;
|
|
123
|
-
/** Probe the memo and otherwise decode one historical generation under backend cancellation. */
|
|
124
|
-
private loadStoredMigration;
|
|
125
|
-
/** Await shared preparation for one caller and abort it only after its last waiter leaves. */
|
|
126
|
-
private waitForPreparation;
|
|
127
|
-
/** Decode one historical generation without publishing a successor. */
|
|
128
|
-
private prepareStoredMigration;
|
|
129
|
-
/** Publish a prepared historical log before granting write access. */
|
|
130
|
-
private publishStoredMigration;
|
|
131
|
-
/** Translate generation-layer failures into the persistence seam's error vocabulary. */
|
|
132
|
-
private generationFailure;
|
|
133
|
-
/**
|
|
134
|
-
* Read, parse, and validate one stored log as the current logical prefix.
|
|
135
|
-
* @param path - the artifact file to read.
|
|
136
|
-
* @param expectedId - the session identity the artifact must carry.
|
|
137
|
-
* @param signal - optional cancellation for the stat/read/decode work.
|
|
138
|
-
* @returns the validated stored log with any torn-tail truncation point.
|
|
139
|
-
*/
|
|
140
|
-
readStoredLog(path: string, expectedId: SessionId, signal?: AbortSignal): Promise<CurrentStoredLog>;
|
|
141
|
-
/** Decode and memoize one already-stable current physical snapshot. */
|
|
142
|
-
private decodeStoredLog;
|
|
143
|
-
/** Insert one parsed log into the bounded handoff cache. */
|
|
144
|
-
private memoizeStoredLog;
|
|
145
|
-
/**
|
|
146
|
-
* Resolve a session's current-generation log path.
|
|
147
|
-
* @param id - the stored session to locate.
|
|
148
|
-
* @param signal - optional cancellation for the directory scans.
|
|
149
|
-
* @returns the current artifact path, or `undefined` while only a historical generation exists.
|
|
150
|
-
*/
|
|
151
|
-
resolveCurrentLog(id: SessionId, signal?: AbortSignal): Promise<string | undefined>;
|
|
152
|
-
/**
|
|
153
|
-
* Durably append one validated batch; lazily materializes on the first write.
|
|
154
|
-
* @param header - the session's stored header.
|
|
155
|
-
* @param events - the validated contiguous batch, in seq order.
|
|
156
|
-
* @param isMaterialized - whether the session already has a durable artifact.
|
|
157
|
-
* @param inheritedEventCount - the exact fork-inherited prefix length written into a materializing header line.
|
|
158
|
-
*/
|
|
159
|
-
persistBatch(header: SessionHeader, events: readonly SessionEvent[], isMaterialized: boolean, inheritedEventCount: SessionLogOffsetType): Promise<void>;
|
|
160
|
-
/**
|
|
161
|
-
* Materialize a header-only artifact for an explicitly durable empty session.
|
|
162
|
-
* @param header - the session's stored header.
|
|
163
|
-
* @param inheritedEventCount - the exact fork-inherited prefix length written into the header line.
|
|
164
|
-
*/
|
|
165
|
-
persistHeader(header: SessionHeader, inheritedEventCount: SessionLogOffsetType): Promise<void>;
|
|
166
|
-
/**
|
|
167
|
-
* Truncate a torn physical tail durably before this session's first new append.
|
|
168
|
-
* @param header - the session's stored header.
|
|
169
|
-
* @param truncateTo - the byte offset the artifact is truncated to.
|
|
170
|
-
*/
|
|
171
|
-
truncateTornTail(header: SessionHeader, truncateTo: number): Promise<void>;
|
|
172
|
-
/**
|
|
173
|
-
* Whether this process still tracks a created-but-unmaterialized session.
|
|
174
|
-
* @param id - the session to test.
|
|
175
|
-
* @returns true while the pending entry exists.
|
|
176
|
-
*/
|
|
177
|
-
hasPendingSession(id: SessionId): boolean;
|
|
178
|
-
/**
|
|
179
|
-
* Release one handle's backend bookkeeping on close.
|
|
180
|
-
* @param handle - the closing handle.
|
|
181
|
-
* @param materialized - whether the session reached durable storage.
|
|
182
|
-
*/
|
|
183
|
-
releaseHandle(handle: JsonlSessionHandle, materialized: boolean): void;
|
|
184
|
-
/**
|
|
185
|
-
* Acquire the session directory's kernel write lock; the kernel holds it
|
|
186
|
-
* until the handle's close releases the descriptor, including on process death.
|
|
187
|
-
* @param id - the session the lock guards.
|
|
188
|
-
* @param cwd - header cwd used to derive the directory for a fresh session.
|
|
189
|
-
* @param dir - the resolved directory of an existing artifact, when known.
|
|
190
|
-
* @returns the held lock.
|
|
191
|
-
*/
|
|
192
|
-
private acquireLease;
|
|
193
|
-
/**
|
|
194
|
-
* Acquire the cross-process write lock for a materializing created session,
|
|
195
|
-
* called by its handle immediately before the first log bytes publish.
|
|
196
|
-
* @param header - the session's stored header (its cwd derives the directory).
|
|
197
|
-
* @returns the held lock.
|
|
198
|
-
*/
|
|
199
|
-
acquireWriteLease(header: SessionHeader): Promise<SessionWriteLease>;
|
|
200
|
-
/** Decode complete frames and retain complete JSONL records from a torn final frame. */
|
|
201
|
-
private readZstdPrefix;
|
|
202
|
-
/** Enumerate selected physical generations without interpreting their headers or bodies. */
|
|
203
|
-
private listGenerations;
|
|
204
|
-
/** Historical logical events depend on the corpus, including members with unreadable headers. */
|
|
205
|
-
private historicalCorpusRevision;
|
|
206
|
-
private listArtifacts;
|
|
207
|
-
/** Read and translate one selected generation header without inspecting its body. */
|
|
208
|
-
private readGenerationHeader;
|
|
209
|
-
/** Convert format-catalog string identities to current branded Session metadata. */
|
|
210
|
-
private currentHeader;
|
|
211
|
-
/** Atomically write the header line + first batch (temp-write, fsync, publish). */
|
|
212
|
-
private materialize;
|
|
213
|
-
private materializePosix;
|
|
214
|
-
private materializeWin32;
|
|
215
|
-
private rejectExistingLog;
|
|
216
|
-
private writeSyncedTempFile;
|
|
217
|
-
/** Encode the header and first batch without combining their frame boundaries. */
|
|
218
|
-
private encodeMaterialization;
|
|
219
|
-
/** Encode one durable append batch in the configured physical representation. */
|
|
220
|
-
private encodeEventBatch;
|
|
221
|
-
/** fsync a POSIX directory so a just-created/renamed entry is crash-durable. */
|
|
222
|
-
private syncDirPosix;
|
|
223
|
-
/**
|
|
224
|
-
* Append and fsync event lines. On a partial write or sync failure, restore the
|
|
225
|
-
* previous size before rethrowing because the unchanged cursor will retry the
|
|
226
|
-
* batch; leaving partial bytes would create duplicate sequence numbers.
|
|
227
|
-
*/
|
|
228
|
-
private appendLines;
|
|
229
|
-
private rollbackAppend;
|
|
230
|
-
/** Truncate the log file to `offset` bytes and fsync (discard the crash tail). */
|
|
231
|
-
private repair;
|
|
232
|
-
/**
|
|
233
|
-
* Read the first newline-terminated line of a file without loading the whole
|
|
234
|
-
* file. Returns undefined if the file is empty or has no complete first line.
|
|
235
|
-
* Reads in bounded chunks so a huge log costs only the header read.
|
|
236
|
-
*/
|
|
237
|
-
private readFirstLine;
|
|
238
|
-
/** Read only the header frame; compression failures reject as corruption, while I/O and cancellation propagate. */
|
|
239
|
-
private readFirstZstdLine;
|
|
240
|
-
/** Select the numerically highest canonical generation in one Session directory. */
|
|
241
|
-
private resolveGenerationInDirectory;
|
|
242
|
-
/** Find the unique authoritative generation for an id across project directories. */
|
|
243
|
-
private findLog;
|
|
244
|
-
/** Require an existing configured root to be a readable directory. */
|
|
245
|
-
private assertUsableRoot;
|
|
246
|
-
/** Reject metadata that does not identify the selected physical log. */
|
|
247
|
-
private assertStoredIdentity;
|
|
248
|
-
/** Validate a supported historical header against the selected source path. */
|
|
249
|
-
private validateSourceIdentity;
|
|
250
26
|
/**
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
*
|
|
27
|
+
* Maximum directory, header, and stat reads in flight across all concurrent
|
|
28
|
+
* listings of this backend (`list()`, the root encoding check, and historical
|
|
29
|
+
* fingerprints). Defaults to 3.
|
|
254
30
|
*/
|
|
255
|
-
|
|
256
|
-
/** The human-readable project directories under the configured root. */
|
|
257
|
-
private listProjectDirs;
|
|
258
|
-
/** List session-owned directories and reject the obsolete flat-file layout. */
|
|
259
|
-
private listSessionDirs;
|
|
260
|
-
/** Reject a root that already belongs to the other physical encoding. */
|
|
261
|
-
private ensureRootEncoding;
|
|
262
|
-
private checkRootEncoding;
|
|
263
|
-
private rejectLegacyFlatArtifact;
|
|
264
|
-
private rejectOppositeArtifact;
|
|
265
|
-
/** Return the highest canonical generation encoded with the other configured suffix. */
|
|
266
|
-
private findOppositeGenerationInDirectory;
|
|
267
|
-
private oppositeCompression;
|
|
268
|
-
private encodingMismatch;
|
|
269
|
-
private legacyLayout;
|
|
270
|
-
private exists;
|
|
271
|
-
private assertLogParentAllowsAbsence;
|
|
31
|
+
listConcurrency?: number;
|
|
272
32
|
}
|
|
33
|
+
/** JSONL persistence plugin label. */
|
|
34
|
+
export declare const name = "session-persistence-jsonl";
|
|
35
|
+
/** Loader schema for the backend's root, physical encoding, and listing concurrency. */
|
|
36
|
+
export declare const Config: z<Config>;
|
|
273
37
|
/**
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
38
|
+
* Mount persistence with live routing and handles retained through the
|
|
39
|
+
* consumer unloads triggered by removing this provider. Consumers must own
|
|
40
|
+
* cleanup in their injecting scope; concurrent root disposal is not ordered.
|
|
41
|
+
* @param ctx - the owning plugin context.
|
|
42
|
+
* @param config - the storage root, physical encoding, and listing concurrency.
|
|
43
|
+
* @returns resolves when the service is ready.
|
|
277
44
|
*/
|
|
278
|
-
export
|
|
45
|
+
export declare function apply(ctx: Context, config: Config): Promise<void>;
|
|
279
46
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -9,7 +9,7 @@ import type { JsonlExpectedPrefix, JsonlVerifiedGeneration } from './generation.
|
|
|
9
9
|
* @param expectedEventCount - exact logical event count expected after decoding.
|
|
10
10
|
* @param expectedPrefix - verified physical prefix; an append tail may be present and is not validated.
|
|
11
11
|
* @param signal - optional cancellation for scheduler wait and Worker execution.
|
|
12
|
-
* @returns
|
|
12
|
+
* @returns the worker's physical identity and digest after its natural zero exit.
|
|
13
13
|
*/
|
|
14
14
|
export declare function verifyCurrentGenerationInWorker(path: string, compression: JsonlCompression, expectedId: string, expectedEventCount: number, expectedPrefix?: JsonlExpectedPrefix, signal?: AbortSignal): Promise<JsonlVerifiedGeneration>;
|
|
15
15
|
//# sourceMappingURL=migration-verifier.d.ts.map
|
package/lib/types/storage.d.ts
CHANGED
|
@@ -241,9 +241,10 @@ export declare class JsonlBackendTracker {
|
|
|
241
241
|
* sessions' events by id; the teardown effect closes every open handle —
|
|
242
242
|
* close drains the routed buffer — and aggregates failures. This provider
|
|
243
243
|
* owns no separate storage connection, so closing handles is the complete
|
|
244
|
-
* teardown.
|
|
245
|
-
* @param ctx - the backend's context.
|
|
244
|
+
* teardown. The returned effect removes listeners before closing handles.
|
|
245
|
+
* @param ctx - the backend's resource-owning context.
|
|
246
|
+
* @returns the disposer to run after persistence consumers finish unloading.
|
|
246
247
|
*/
|
|
247
|
-
install(ctx: Context): void
|
|
248
|
+
install(ctx: Context): () => Promise<void>;
|
|
248
249
|
}
|
|
249
250
|
//# sourceMappingURL=storage.d.ts.map
|
package/lib/worker.cjs
CHANGED
|
@@ -3148,6 +3148,8 @@ const KNOWN_SESSION_EVENT_TYPES = new Set([
|
|
|
3148
3148
|
"hook/invoked",
|
|
3149
3149
|
"hook/result",
|
|
3150
3150
|
"image/offload",
|
|
3151
|
+
"job/registered",
|
|
3152
|
+
"job/settled",
|
|
3151
3153
|
"llm/retry",
|
|
3152
3154
|
"llm/retry-started",
|
|
3153
3155
|
"model/selection",
|
|
@@ -3184,6 +3186,7 @@ const KNOWN_SESSION_EVENT_TYPES = new Set([
|
|
|
3184
3186
|
"turn/start",
|
|
3185
3187
|
"user/message",
|
|
3186
3188
|
"web/deepseek-search-llm-request",
|
|
3189
|
+
"working-directory/change",
|
|
3187
3190
|
"workspace/changes"
|
|
3188
3191
|
]);
|
|
3189
3192
|
/** Event types whose model-visible effects require an explicit pure interpreter. */
|
|
@@ -3620,7 +3623,7 @@ const REMOTE_METHOD_DESCRIPTOR = "@deepseek-ai/dsh-typert-protocol/remote-method
|
|
|
3620
3623
|
* a Host composition to read it.
|
|
3621
3624
|
* @param service - owning Service instance, normally `this`.
|
|
3622
3625
|
* @param serviceKey - exact Cordis service key.
|
|
3623
|
-
* @param options - optional
|
|
3626
|
+
* @param options - optional wire namespace.
|
|
3624
3627
|
* @returns a frozen, inspectable binding with no compiler-injected metadata.
|
|
3625
3628
|
*/
|
|
3626
3629
|
function bindTypertRemote(service, serviceKey, options = {}) {
|
|
@@ -3628,7 +3631,7 @@ function bindTypertRemote(service, serviceKey, options = {}) {
|
|
|
3628
3631
|
const namespace = options.namespace ?? serviceKey;
|
|
3629
3632
|
validateName("namespace", namespace);
|
|
3630
3633
|
const ctx = Reflect.get(service, "ctx");
|
|
3631
|
-
if (ctx
|
|
3634
|
+
if (Context.is(ctx)) provideInvocationAccessor(ctx);
|
|
3632
3635
|
return Object.freeze({
|
|
3633
3636
|
service,
|
|
3634
3637
|
serviceKey,
|
|
@@ -3643,7 +3646,7 @@ var TypertRemoteService = class extends Service {
|
|
|
3643
3646
|
* Register the Service and bind the same key to Typert Gateway.
|
|
3644
3647
|
* @param ctx - owning Cordis Context.
|
|
3645
3648
|
* @param serviceKey - exact Cordis service key and default wire namespace.
|
|
3646
|
-
* @param options - optional
|
|
3649
|
+
* @param options - optional wire namespace.
|
|
3647
3650
|
*/
|
|
3648
3651
|
constructor(ctx, serviceKey, options = {}) {
|
|
3649
3652
|
super(ctx, serviceKey);
|
|
@@ -3663,21 +3666,42 @@ function provideInvocationAccessor(ctx) {
|
|
|
3663
3666
|
function Remote(methodExportOrOptions, context) {
|
|
3664
3667
|
if (typeof methodExportOrOptions === "string") {
|
|
3665
3668
|
validateName("Remote export name", methodExportOrOptions);
|
|
3666
|
-
return remoteDecorator({ kind: "direct" },
|
|
3667
|
-
}
|
|
3668
|
-
if (typeof methodExportOrOptions === "object") {
|
|
3669
|
-
if (remoteOptionMode(methodExportOrOptions) !== "stream" || Reflect.ownKeys(methodExportOrOptions).length !== 1) throw new TypeError("typert-protocol: Remote options must contain exactly mode: \"stream\"");
|
|
3670
|
-
return remoteDecorator({ kind: "direct" }, "stream");
|
|
3669
|
+
return remoteDecorator({ kind: "direct" }, { exportName: methodExportOrOptions });
|
|
3671
3670
|
}
|
|
3671
|
+
if (typeof methodExportOrOptions === "object") return remoteDecorator({ kind: "direct" }, markerOptions(methodExportOrOptions, REMOTE_OPTION_KEYS, "Remote options require name, mode: \"stream\", or resources"));
|
|
3672
3672
|
if (context === void 0) throw new TypeError("typert-protocol: Remote decorator context is missing");
|
|
3673
3673
|
addMarkerInitializer(context, { kind: "direct" });
|
|
3674
3674
|
}
|
|
3675
|
-
|
|
3676
|
-
|
|
3675
|
+
const REMOTE_OPTION_KEYS = new Set([
|
|
3676
|
+
"name",
|
|
3677
|
+
"mode",
|
|
3678
|
+
"resources"
|
|
3679
|
+
]);
|
|
3680
|
+
/** Validate one decorator options object against its accepted keys and select the marker fields. */
|
|
3681
|
+
function markerOptions(options, accepted, requirement) {
|
|
3682
|
+
const keys = Reflect.ownKeys(options);
|
|
3683
|
+
if (keys.length === 0 || keys.some((key) => typeof key !== "string" || !accepted.has(key)) || Object.hasOwn(options, "mode") && options.mode !== "stream") throw new TypeError(`typert-protocol: ${requirement}`);
|
|
3684
|
+
const { mode, name, resources } = options;
|
|
3685
|
+
if (name !== void 0) validateName("Remote export name", name);
|
|
3686
|
+
return {
|
|
3687
|
+
...mode === void 0 ? {} : { mode },
|
|
3688
|
+
...name === void 0 ? {} : { exportName: name },
|
|
3689
|
+
...resources === void 0 ? {} : { resources: resourceReaders(resources) }
|
|
3690
|
+
};
|
|
3677
3691
|
}
|
|
3678
|
-
|
|
3692
|
+
/** Freeze declared readers into the marker record; a misdeclared reader fails at decoration. */
|
|
3693
|
+
function resourceReaders(resources) {
|
|
3694
|
+
const readers = {};
|
|
3695
|
+
for (const [kind, reader] of Object.entries(resources)) {
|
|
3696
|
+
if (typeof reader !== "function") throw new TypeError(`typert-protocol: Remote resource reader "${kind}" must be a function`);
|
|
3697
|
+
readers[kind] = reader;
|
|
3698
|
+
}
|
|
3699
|
+
if (Object.keys(readers).length === 0) throw new TypeError("typert-protocol: Remote resources require at least one reader");
|
|
3700
|
+
return Object.freeze(readers);
|
|
3701
|
+
}
|
|
3702
|
+
function remoteDecorator(invocation, options = {}) {
|
|
3679
3703
|
return function(_method, context) {
|
|
3680
|
-
addMarkerInitializer(context, invocation,
|
|
3704
|
+
addMarkerInitializer(context, invocation, options);
|
|
3681
3705
|
};
|
|
3682
3706
|
}
|
|
3683
3707
|
function readRemoteMethodDescriptor(prototype) {
|
|
@@ -3691,26 +3715,27 @@ function readRemoteMethodDescriptor(prototype) {
|
|
|
3691
3715
|
if (!Array.isArray(methods)) throw new TypeError("typert-protocol: Remote method descriptor methods must be an array");
|
|
3692
3716
|
return descriptor;
|
|
3693
3717
|
}
|
|
3694
|
-
function addMarkerInitializer(context, invocation,
|
|
3718
|
+
function addMarkerInitializer(context, invocation, options = {}) {
|
|
3695
3719
|
if (context.private || context.static || typeof context.name !== "string") throw new TypeError("typert-protocol: Remote decorators require a public instance method with a string name");
|
|
3696
3720
|
const method = context.name;
|
|
3697
3721
|
context.addInitializer(function() {
|
|
3698
3722
|
const prototype = Object.getPrototypeOf(this);
|
|
3699
3723
|
if (prototype === null) throw new TypeError(`typert-protocol: cannot mark Remote method "${method}" on an object without a prototype`);
|
|
3700
|
-
mark(prototype, method, invocation,
|
|
3724
|
+
mark(prototype, method, invocation, options);
|
|
3701
3725
|
});
|
|
3702
3726
|
}
|
|
3703
|
-
function mark(prototype, method, invocation, mode, exportName) {
|
|
3727
|
+
function mark(prototype, method, invocation, { mode, exportName, resources }) {
|
|
3704
3728
|
const descriptor = readRemoteMethodDescriptor(prototype);
|
|
3705
3729
|
const marker = Object.freeze({
|
|
3706
3730
|
method,
|
|
3707
3731
|
...exportName === void 0 || exportName === method ? {} : { exportName },
|
|
3708
3732
|
...mode === void 0 ? {} : { mode },
|
|
3709
|
-
invocation: Object.freeze(invocation)
|
|
3733
|
+
invocation: Object.freeze(invocation),
|
|
3734
|
+
...resources === void 0 ? {} : { resources }
|
|
3710
3735
|
});
|
|
3711
3736
|
const current = descriptor?.methods.find((candidate) => candidate.method === method);
|
|
3712
3737
|
if (current !== void 0) {
|
|
3713
|
-
if (current.exportName === marker.exportName && current.mode === marker.mode && sameInvocation(current.invocation, invocation)) return;
|
|
3738
|
+
if (current.exportName === marker.exportName && current.mode === marker.mode && current.resources === marker.resources && sameInvocation(current.invocation, invocation)) return;
|
|
3714
3739
|
throw new Error(`typert-protocol: Remote method "${method}" has conflicting invocation markers`);
|
|
3715
3740
|
}
|
|
3716
3741
|
Object.defineProperty(prototype, REMOTE_METHOD_DESCRIPTOR, {
|
|
@@ -5555,10 +5580,7 @@ var LlmError = class extends HarnessError {
|
|
|
5555
5580
|
if (entry.provider.length === 0 || entry.displayName.length === 0 || entry.settingsNs.length === 0) throw new LlmError("configurable providers need a non-empty provider, displayName, and settingsNs", "INVALID_DIRECTORY");
|
|
5556
5581
|
if (entry.settingsPath.some((segment) => segment.length === 0)) throw new LlmError(`configurable provider "${entry.provider}" has an empty settingsPath segment`, "INVALID_DIRECTORY");
|
|
5557
5582
|
if (this.directory.has(entry.provider) && !own.has(entry.provider) || detached.some((seen) => seen.provider === entry.provider)) throw new LlmError(`configurable provider "${entry.provider}" is already declared`, "DUPLICATE_DIRECTORY");
|
|
5558
|
-
detached.push(
|
|
5559
|
-
...entry,
|
|
5560
|
-
settingsPath: [...entry.settingsPath]
|
|
5561
|
-
});
|
|
5583
|
+
detached.push(detachDirectoryEntry(entry));
|
|
5562
5584
|
}
|
|
5563
5585
|
for (const entry of held) this.directory.delete(entry.provider);
|
|
5564
5586
|
for (const entry of detached) this.directory.set(entry.provider, entry);
|
|
@@ -5587,10 +5609,7 @@ var LlmError = class extends HarnessError {
|
|
|
5587
5609
|
* @returns detached directory entries in declaration order.
|
|
5588
5610
|
*/
|
|
5589
5611
|
listConfigurableProviders() {
|
|
5590
|
-
return [...this.directory.values()].map(
|
|
5591
|
-
...entry,
|
|
5592
|
-
settingsPath: [...entry.settingsPath]
|
|
5593
|
-
}));
|
|
5612
|
+
return [...this.directory.values()].map(detachDirectoryEntry);
|
|
5594
5613
|
}
|
|
5595
5614
|
/**
|
|
5596
5615
|
* Offer to interrogate provider endpoints on behalf of the settings
|
|
@@ -5682,6 +5701,16 @@ var LlmError = class extends HarnessError {
|
|
|
5682
5701
|
return this.adapters.get(provider)?.adapter.imageRequestPricing(provider, model);
|
|
5683
5702
|
}
|
|
5684
5703
|
/**
|
|
5704
|
+
* Resolve the image projection for an exact registered model route.
|
|
5705
|
+
* @param provider - registered provider route.
|
|
5706
|
+
* @param model - exact model id.
|
|
5707
|
+
* @param image - normalized image reference.
|
|
5708
|
+
* @returns dimensions and byte target used by the adapter's request serializer.
|
|
5709
|
+
*/
|
|
5710
|
+
imageRequestTarget(provider, model, image) {
|
|
5711
|
+
return this.registration(provider).adapter.imageRequestTarget(provider, model, image);
|
|
5712
|
+
}
|
|
5713
|
+
/**
|
|
5685
5714
|
* Resolve the exact text one durable file occurrence contributes to every
|
|
5686
5715
|
* provider request in the current execution environment.
|
|
5687
5716
|
* @param ref - durable verbatim file reference from model history.
|
|
@@ -5827,20 +5856,33 @@ var LlmError = class extends HarnessError {
|
|
|
5827
5856
|
* Resolve one call under its current adapter registration. The returned
|
|
5828
5857
|
* one-shot handle keeps that registration across header logging and dispatch,
|
|
5829
5858
|
* so HMR cannot combine one adapter's capability result with another adapter.
|
|
5830
|
-
*
|
|
5859
|
+
* An optional synchronous callback selects concrete controls using captured
|
|
5860
|
+
* model metadata. Defaults and validation apply to its result. Callback
|
|
5861
|
+
* failures and cancellation reject preparation before dispatch.
|
|
5862
|
+
* @param config - provider/model route and optional concrete request controls.
|
|
5831
5863
|
* @param signal - optional cancellation for adapter-owned capability lookup.
|
|
5864
|
+
* @param configure - pure control selection, called once before defaults and validation.
|
|
5832
5865
|
* @returns a prepared config and its registration-bound stream entry point.
|
|
5833
5866
|
*/
|
|
5834
|
-
async prepareCall(config, signal) {
|
|
5835
|
-
|
|
5836
|
-
const
|
|
5837
|
-
const
|
|
5838
|
-
const
|
|
5867
|
+
async prepareCall(config, signal, configure) {
|
|
5868
|
+
signal?.throwIfAborted();
|
|
5869
|
+
const { provider, model, ...controls } = config;
|
|
5870
|
+
const registration = this.registration(provider);
|
|
5871
|
+
const adapterCall = await registration.adapter.prepareCall(provider, model, signal);
|
|
5872
|
+
signal?.throwIfAborted();
|
|
5873
|
+
const modelInfo = this.normalizeModelInfo(registration, model, adapterCall.model);
|
|
5874
|
+
const proposed = configure === void 0 ? config : {
|
|
5875
|
+
...configure(deepFreeze(structuredClone(controls)), deepFreeze(modelInfo)),
|
|
5876
|
+
provider,
|
|
5877
|
+
model
|
|
5878
|
+
};
|
|
5879
|
+
signal?.throwIfAborted();
|
|
5880
|
+
const resolved = this.resolveCallWithInfo(proposed, modelInfo);
|
|
5839
5881
|
const resolvedConfig = deepFreeze(structuredClone(resolved.config));
|
|
5840
5882
|
const context = resolved.context === void 0 ? void 0 : deepFreeze(structuredClone(resolved.context));
|
|
5841
5883
|
const adapterDefaults = deepFreeze({
|
|
5842
|
-
...
|
|
5843
|
-
...
|
|
5884
|
+
...proposed.reasoningEffort === void 0 && resolvedConfig.reasoningEffort !== void 0 ? { reasoningEffort: true } : {},
|
|
5885
|
+
...proposed.maxTokens === void 0 && resolvedConfig.maxTokens !== void 0 ? { maxTokens: true } : {}
|
|
5844
5886
|
});
|
|
5845
5887
|
let dispatched = false;
|
|
5846
5888
|
return Object.freeze({
|
|
@@ -6017,6 +6059,19 @@ function adapterFailureChunk(error, signal) {
|
|
|
6017
6059
|
}
|
|
6018
6060
|
};
|
|
6019
6061
|
}
|
|
6062
|
+
/** Copy a directory entry, including its arrays, so neither side can mutate the other's copy. */
|
|
6063
|
+
function detachDirectoryEntry(entry) {
|
|
6064
|
+
const { nativeAuth } = entry;
|
|
6065
|
+
return {
|
|
6066
|
+
...entry,
|
|
6067
|
+
settingsPath: [...entry.settingsPath],
|
|
6068
|
+
...entry.baseURLEnv === void 0 ? {} : { baseURLEnv: [...entry.baseURLEnv] },
|
|
6069
|
+
...nativeAuth === void 0 ? {} : { nativeAuth: {
|
|
6070
|
+
...nativeAuth,
|
|
6071
|
+
env: [...nativeAuth.env]
|
|
6072
|
+
} }
|
|
6073
|
+
};
|
|
6074
|
+
}
|
|
6020
6075
|
//#endregion
|
|
6021
6076
|
//#region ../../core/session/src/request-header.ts
|
|
6022
6077
|
/**
|
|
@@ -6321,6 +6376,32 @@ function invokeContainedSessionObservers(ctx, name, id, args, callbacks) {
|
|
|
6321
6376
|
/** Store attachment for the append path; module-private to keep Session store-agnostic publicly. */
|
|
6322
6377
|
const attachments = /* @__PURE__ */ new WeakMap();
|
|
6323
6378
|
/**
|
|
6379
|
+
* Grammar of a {@link PluginRecordType}: `plugin:` followed by
|
|
6380
|
+
* slash-separated segments of lowercase letters, digits, `.`, `_`, and `-`,
|
|
6381
|
+
* each segment starting with a letter or digit.
|
|
6382
|
+
*/
|
|
6383
|
+
const PLUGIN_RECORD_TYPE = /^plugin:[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)*$/u;
|
|
6384
|
+
/**
|
|
6385
|
+
* Whether one event type name follows the plugin record grammar.
|
|
6386
|
+
* @param type - an event type name.
|
|
6387
|
+
* @returns whether the name is a {@link PluginRecordType}.
|
|
6388
|
+
*/
|
|
6389
|
+
function isPluginRecordType(type) {
|
|
6390
|
+
return PLUGIN_RECORD_TYPE.test(type);
|
|
6391
|
+
}
|
|
6392
|
+
/**
|
|
6393
|
+
* Type one constructed plugin record as a log event after checking its type
|
|
6394
|
+
* against the plugin record grammar. A restored Session already holds events
|
|
6395
|
+
* whose types are outside `SessionEventMap` when they are marked ignorable;
|
|
6396
|
+
* a plugin record is such an event.
|
|
6397
|
+
* @param value - the frozen record envelope built by {@link Session}.
|
|
6398
|
+
* @throws when the record type is outside the plugin record grammar.
|
|
6399
|
+
*/
|
|
6400
|
+
function assertPluginRecordEvent(value) {
|
|
6401
|
+
const { type } = value;
|
|
6402
|
+
if (!isPluginRecordType(type)) throw new Error(`plugin record type "${type}" must be "plugin:" followed by lowercase slash-separated segments`);
|
|
6403
|
+
}
|
|
6404
|
+
/**
|
|
6324
6405
|
* An event-sourced session: an append-only log of {@link SessionEvent}s.
|
|
6325
6406
|
*
|
|
6326
6407
|
* Plain class (not a Service) — create live instances via
|
|
@@ -6531,8 +6612,7 @@ var Session = class Session {
|
|
|
6531
6612
|
if (dataSnapshot === void 0) throw new Error(`session event "${type}" carries non-JSON-serializable data`);
|
|
6532
6613
|
const surfaceMetadataSnapshot = snapshotJsonValue(surfaceMetadata);
|
|
6533
6614
|
if (surfaceMetadataSnapshot === void 0) throw new Error(`session event "${type}" carries non-JSON-serializable surface metadata`);
|
|
6534
|
-
const entry =
|
|
6535
|
-
if (entry?.appending) throw new Error("session append cannot reenter while another append is being published");
|
|
6615
|
+
const entry = this.publicationEntry();
|
|
6536
6616
|
const event = deepFreeze({
|
|
6537
6617
|
type,
|
|
6538
6618
|
seq: SessionSeq(this.log.length),
|
|
@@ -6541,6 +6621,48 @@ var Session = class Session {
|
|
|
6541
6621
|
...surfaceMetadataSnapshot
|
|
6542
6622
|
});
|
|
6543
6623
|
validateSessionEventData(event, `session event "${type}" at seq ${event.seq}`);
|
|
6624
|
+
this.commit(event, entry);
|
|
6625
|
+
return event;
|
|
6626
|
+
}
|
|
6627
|
+
static {}
|
|
6628
|
+
/**
|
|
6629
|
+
* Commit one plugin record; {@link appendPluginRecord} is the only caller.
|
|
6630
|
+
* @param type - record type, checked against the plugin record grammar.
|
|
6631
|
+
* @param data - JSON payload, snapshotted before it enters the log.
|
|
6632
|
+
* @returns the record's sequence number.
|
|
6633
|
+
*/
|
|
6634
|
+
#appendRecord(type, data) {
|
|
6635
|
+
const dataSnapshot = snapshotJsonValue(data);
|
|
6636
|
+
if (dataSnapshot === void 0) throw new Error(`plugin record "${type}" carries non-JSON-serializable data`);
|
|
6637
|
+
const entry = this.publicationEntry();
|
|
6638
|
+
const record = deepFreeze({
|
|
6639
|
+
type,
|
|
6640
|
+
seq: SessionSeq(this.log.length),
|
|
6641
|
+
time: Date.now(),
|
|
6642
|
+
data: dataSnapshot,
|
|
6643
|
+
ignorable: true
|
|
6644
|
+
});
|
|
6645
|
+
assertPluginRecordEvent(record);
|
|
6646
|
+
this.commit(record, entry);
|
|
6647
|
+
return record.seq;
|
|
6648
|
+
}
|
|
6649
|
+
/**
|
|
6650
|
+
* Read the store attachment for one append, refusing an append that
|
|
6651
|
+
* reenters while another append is being published.
|
|
6652
|
+
* @returns the attachment, or undefined for a detached Session.
|
|
6653
|
+
*/
|
|
6654
|
+
publicationEntry() {
|
|
6655
|
+
const entry = attachments.get(this);
|
|
6656
|
+
if (entry?.appending) throw new Error("session append cannot reenter while another append is being published");
|
|
6657
|
+
return entry;
|
|
6658
|
+
}
|
|
6659
|
+
/**
|
|
6660
|
+
* Accept one frozen candidate at the next sequence number, enter it into the
|
|
6661
|
+
* log, and notify `session/event` observers with per-listener containment.
|
|
6662
|
+
* @param event - the candidate built at the current log length.
|
|
6663
|
+
* @param entry - the attachment read before the candidate was built.
|
|
6664
|
+
*/
|
|
6665
|
+
commit(event, entry) {
|
|
6544
6666
|
this.surfaceManager.validateNext(event);
|
|
6545
6667
|
if (entry !== void 0) entry.appending = true;
|
|
6546
6668
|
try {
|
|
@@ -6554,7 +6676,6 @@ var Session = class Session {
|
|
|
6554
6676
|
this.log.push(event);
|
|
6555
6677
|
this.eventsSnapshot = void 0;
|
|
6556
6678
|
if (callbacks !== void 0 && entry !== void 0) invokeContainedSessionObservers(entry.emitCtx, "session/event", entry.id, callbackArgs, callbacks);
|
|
6557
|
-
return event;
|
|
6558
6679
|
} finally {
|
|
6559
6680
|
if (entry !== void 0) {
|
|
6560
6681
|
entry.appending = false;
|
|
@@ -12201,7 +12322,7 @@ function assertV4LifecycleRelationships(artifact, knownEventTypes) {
|
|
|
12201
12322
|
* @returns validated catalog payload.
|
|
12202
12323
|
*/
|
|
12203
12324
|
function catalogFact(value, subject = "subagent/catalog") {
|
|
12204
|
-
if (!isSessionFormatJsonObject(value) || value["version"] !== 0 && value["version"] !== 1 || typeof value["childId"] !== "string" || value["mode"] !== "continuable" && value["mode"] !== "one-shot" && value["mode"] !== "unknown" || value["version"] === 0 && value["mode"] === "unknown" || value["mode"] === "continuable" && typeof value["label"] !== "string" || value["label"] !== void 0 && typeof value["label"] !== "string") throw new SessionFormatError(`${subject} requires a supported versioned catalog fact`);
|
|
12325
|
+
if (!isSessionFormatJsonObject(value) || value["version"] !== 0 && value["version"] !== 1 && value["version"] !== 2 || typeof value["childId"] !== "string" || value["mode"] !== "continuable" && value["mode"] !== "one-shot" && value["mode"] !== "external" && value["mode"] !== "unknown" || value["version"] === 2 !== (value["mode"] === "external") || value["version"] === 0 && value["mode"] === "unknown" || value["mode"] === "continuable" && typeof value["label"] !== "string" || value["label"] !== void 0 && typeof value["label"] !== "string") throw new SessionFormatError(`${subject} requires a supported versioned catalog fact`);
|
|
12205
12326
|
sessionFormatCount(value["childCreatedAt"], "catalog child creation time");
|
|
12206
12327
|
return value;
|
|
12207
12328
|
}
|
package/locale/en.json
ADDED