@morlay/ui-conversation-manager 0.1.5 → 0.1.6

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/dist/client.d.cts CHANGED
@@ -1,5 +1,6 @@
1
- import { Context, Service } from "@deepseek-ai/cordis";
1
+ import { Context } from "@deepseek-ai/cordis";
2
2
  import { MainPanelId } from "@deepseek-ai/dsh-client-ui-layout/client";
3
+ import { SessionId } from "@deepseek-ai/dsh-session";
3
4
  import { InjectFace, PropsLocale, PropsRuntime } from "@deepseek-ai/dsh-client-ui-slots";
4
5
  import "react";
5
6
  //#region src/client/locales.d.ts
@@ -13,8 +14,12 @@ declare const zh: {
13
14
  archived: string;
14
15
  subagent: string;
15
16
  showSubagents: string;
17
+ clearSearch: string;
18
+ "filter.view": string;
19
+ "filter.subagents": string;
16
20
  "view.sessions": string;
17
21
  "view.usage": string;
22
+ "usage.dimension": string;
18
23
  "usage.overview": string;
19
24
  "usage.all": string;
20
25
  "usage.range": string;
@@ -80,3119 +85,6 @@ declare const zh: {
80
85
  };
81
86
  type ConversationManagerKey = keyof typeof zh;
82
87
  //#endregion
83
- //#region ../../../vendor/deepseek-harness/packages/core/scope/lib/types/index.d.ts
84
- declare const ScopedBrand: unique symbol;
85
- /**
86
- * A routing-only event receiver built by {@link scopeTarget}. The type
87
- * parameter records the subject type for dispatch checking; the carrier does
88
- * not expose the subject's properties. Event payloads carry the real subject.
89
- */
90
- type Scoped<T extends object> = object & {
91
- readonly [ScopedBrand]: T;
92
- };
93
- //#endregion
94
- //#region ../../../vendor/deepseek-harness/packages/util/brand/lib/types/index.d.ts
95
- /**
96
- * Duplicate-install-safe nominal primitive helpers.
97
- *
98
- * A brand makes structurally identical strings or numbers non-interchangeable
99
- * at the type level: a `SessionId` cannot be passed where a `ToolCallId` is
100
- * expected, and an event sequence cannot be passed as a log offset. Comparison,
101
- * logging, and serialization retain the underlying primitive behavior.
102
- *
103
- * This package owns no concrete domain value and keeps no runtime identity or mutable
104
- * state, so independently installed copies produce interchangeable values.
105
- *
106
- * @module @deepseek-ai/dsh-brand
107
- */
108
- declare const BRAND: unique symbol;
109
- /** A string carrying a compile-time-only brand `B`. */
110
- type Branded<B extends string> = string & {
111
- readonly [BRAND]: B;
112
- };
113
- /** A number carrying a compile-time-only brand `B`. */
114
- type BrandedNumber<B extends string> = number & {
115
- readonly [BRAND]: B;
116
- };
117
- //#endregion
118
- //#region ../../../vendor/deepseek-harness/packages/typert/protocol/lib/types/owned-value.d.ts
119
- /** Generic invocation-owned values returned by synchronous Client Context resolvers. */
120
- /** Shared identity across independently bundled Context providers and Gateway. */
121
- declare const TYPERT_OWNED_VALUE: unique symbol;
122
- /** A borrowed payload paired with the invocation owner's idempotent cleanup. */
123
- interface TypertOwnedValue<Value> extends Disposable {
124
- readonly [TYPERT_OWNED_VALUE]: true;
125
- readonly value: Value;
126
- }
127
- //#endregion
128
- //#region ../../../vendor/deepseek-harness/packages/typert/protocol/lib/types/types.d.ts
129
- declare const LOOKUP_HOST: unique symbol;
130
- declare const LOOKUP_WIRE: unique symbol;
131
- declare const CONTEXT_WIRE: unique symbol;
132
- /** Type-level association between a Host object and its wire identity. */
133
- interface TypertLookup<Host, Wire> {
134
- readonly [LOOKUP_HOST]: Host;
135
- readonly [LOOKUP_WIRE]: Wire;
136
- }
137
- /** Extract the Host object associated with one lookup declaration. */
138
- type TypertLookupHost<Lookup> = Lookup extends TypertLookup<infer Host, infer _Wire> ? Host : never;
139
- /** Extract the wire identity associated with one lookup declaration. */
140
- type TypertLookupWire<Lookup> = Lookup extends TypertLookup<infer _Host, infer Wire> ? Wire : never;
141
- /** Type-level association between a scoped Context kind and its wire identity. */
142
- interface TypertContext<Wire> {
143
- readonly [CONTEXT_WIRE]: Wire;
144
- }
145
- /** Extract the wire identity associated with one scoped Context declaration. */
146
- type TypertContextWire<ContextType> = ContextType extends TypertContext<infer Wire> ? Wire : never;
147
- /** Merge-extensible Host object lookup declarations. */
148
- interface TypertLookupMap {}
149
- /** Merge-extensible scoped Context declarations. */
150
- interface TypertContextMap {}
151
- /** Awaitable disposer returned by Cordis-owned Typert registrations. */
152
- type TypertDisposer = () => Promise<void>;
153
- type StringKeyOf<Value> = Extract<keyof Value, string>;
154
- /** Minimal runtime-schema capability carried by strict generated codecs. */
155
- interface TypertSchema<Output = unknown> {
156
- /**
157
- * Parse and validate one boundary value.
158
- * @param value - untrusted boundary value.
159
- * @returns the validated value.
160
- */
161
- parse(value: unknown): Output;
162
- }
163
- /** Codec attached to one invocation parameter or result. */
164
- type TypertCodec = {
165
- readonly mode: 'strict';
166
- readonly typeSymbol: string;
167
- /** Materialize and return the process-realm schema on first boundary use. */
168
- readonly create: () => TypertSchema;
169
- /**
170
- * Decode a unary result whose fields require type-specific handling.
171
- * @param value - result reconstructed by the RPC carrier.
172
- * @returns the validated result, retaining native byte views.
173
- */
174
- readonly decode?: (value: unknown) => unknown;
175
- /**
176
- * Project typed binary fields into RPC result attachments.
177
- * @param value - native unary result.
178
- * @param writeBytes - records a byte view at its result-relative path and returns its JSON placeholder.
179
- * @returns JSON metadata with untouched JSON subtrees retained.
180
- */
181
- readonly encode?: (value: unknown, writeBytes: (bytes: Uint8Array, path: readonly (string | number)[]) => null) => unknown;
182
- } | {
183
- readonly mode: 'src-json';
184
- };
185
- /** One ordered business parameter in a Remote invocation. */
186
- interface InvocationParameterDescriptor {
187
- /** Source-level parameter name. */
188
- readonly name: string;
189
- /** Required key in the wire `args` object. */
190
- readonly wire: string;
191
- /** Whether the value is JSON or requires a registered Host lookup. */
192
- readonly source: 'json' | 'lookup';
193
- /** Lookup key when `source` is `lookup`. */
194
- readonly lookup?: string;
195
- /** Boundary codec for the wire representation. */
196
- readonly codec: TypertCodec;
197
- /** Missing wire fields decode to `undefined` only for an explicitly declared `T | undefined`. */
198
- readonly acceptsUndefined?: true;
199
- }
200
- /** Source position retained for diagnostics from generated definitions. */
201
- interface InvocationSourceLocation {
202
- readonly file: string;
203
- readonly line: number;
204
- readonly column: number;
205
- }
206
- /** Carrier-independent description of one exported method invocation. */
207
- interface InvocationDescriptor {
208
- /** Globally stable generated identity. */
209
- readonly id: string;
210
- /** Cordis service key owning the method. */
211
- readonly service: string;
212
- /** Wire namespace, defaulting to the service key. */
213
- readonly namespace: string;
214
- /** Public instance method name. */
215
- readonly method: string;
216
- /** Service member invoked when the exported method name is an alias. */
217
- readonly implementation?: string;
218
- /** Absent for unary calls; stream calls deliver every yielded item as the Host produced it. */
219
- readonly mode?: 'stream';
220
- /** Receiver selection mode. */
221
- readonly invocation: {
222
- readonly kind: 'direct';
223
- } | {
224
- readonly kind: 'context';
225
- readonly context: string;
226
- readonly wire: string;
227
- readonly codec: TypertCodec;
228
- };
229
- /** Optional consuming-Context projection for one direct lookup parameter. */
230
- readonly scope?: {
231
- /** Context kind whose Client adapter supplies the identity. */
232
- readonly context: string;
233
- /** Lookup parameter wire field replaced by the Context identity. */
234
- readonly wire: string;
235
- };
236
- /** Ordered business parameters. */
237
- readonly parameters: readonly InvocationParameterDescriptor[];
238
- /**
239
- * Client-to-Host items of the same logical stream, generated from the `In`
240
- * type argument of the method's `RemoteStream<Out, In>` return type; absent
241
- * when `In` is `never`. The method reads the items through
242
- * `RemoteInvocation.uplink()`, so nothing enters the parameter list.
243
- */
244
- readonly uplink?: {
245
- /** Codec validating every uplink item before `uplink()` delivers it. */
246
- readonly codec: TypertCodec;
247
- };
248
- /** Transport cancellation injected after business parameters instead of entering wire args. */
249
- readonly cancellation?: {
250
- /** Reserved final Host method parameter. */
251
- readonly parameter: 'signal';
252
- };
253
- /** Codec for the unary result or each yielded stream item. */
254
- readonly result: TypertCodec;
255
- /** Source declaration used only for diagnostics. */
256
- readonly sourceLocation?: InvocationSourceLocation;
257
- }
258
- /**
259
- * Opaque identity of one Peer: a party admitted to this Host by the connection
260
- * layer. "Peer" is a connection-layer word; the browser application keeps the
261
- * word "Client".
262
- */
263
- type PeerId = Branded<'PeerId'>;
264
- /**
265
- * One Peer's session on this Host. Connection owns it: `ctx` is the Cordis
266
- * scope that owns connection-lifetime registrations and is disposed with the
267
- * Peer. Who the Peer is and what it may do are not recorded here.
268
- */
269
- interface PeerScope {
270
- readonly id: PeerId;
271
- readonly ctx: Context;
272
- /**
273
- * Tear down every registration made through `ctx`.
274
- * @returns settles once the scope has quiesced; racing calls share one completion.
275
- */
276
- dispose(): Promise<void>;
277
- }
278
- /**
279
- * The context of one Remote call, reachable inside the receiving method as
280
- * `this.ctx.invocation`. The Gateway derives the receiver from a Context that
281
- * carries it, so no parameter is injected and nothing crosses the wire.
282
- */
283
- interface RemoteInvocation {
284
- readonly request: {
285
- readonly namespace: string;
286
- readonly method: string;
287
- readonly args: Readonly<Record<string, unknown>>;
288
- };
289
- /** Cordis service key of the receiving Service. */
290
- readonly service: string;
291
- /** Peer the call speaks for; an in-process carrier speaks for the operator. */
292
- readonly peer: PeerScope;
293
- /** Carrier cancellation: Client cancel, socket close, or an uplink failure. */
294
- readonly signal: AbortSignal;
295
- /**
296
- * The Client's uplink items for this call. Available once; a second call
297
- * throws. With an uplink codec on the descriptor every item is decoded to
298
- * `In`; without one items arrive as `unknown` after a JSON-safety check.
299
- * Iteration ends when the Client ends its uplink; when the method finishes
300
- * its downlink the Gateway calls the iterator's `return()` and unread items
301
- * are dropped. `In` is the caller's assertion: the runtime decodes by the
302
- * descriptor and does not cross-check it.
303
- * @template In - item type the caller reads; the descriptor codec decides what arrives.
304
- * @returns the single-consumer uplink iterable.
305
- */
306
- uplink<In = unknown>(): AsyncIterable<In>;
307
- }
308
- /** Generated Host contract selected explicitly by a Client assembly. */
309
- interface TypertRemoteContribution {
310
- /** npm package that owns the Remote methods. */
311
- readonly package: string;
312
- /** Consumer-side invocation descriptors generated from that package. */
313
- readonly descriptors: readonly InvocationDescriptor[];
314
- }
315
- /**
316
- * Resolve one validated wire identity, synchronously or asynchronously.
317
- * @param id - validated wire identity.
318
- * @returns the Host object, or `undefined` when unavailable.
319
- */
320
- type TypertLookupResolver<Host = unknown, Wire = unknown> = (id: Wire) => Host | undefined | Promise<Host | undefined>;
321
- /** Runtime provider for one declared Host object lookup. */
322
- interface TypertLookupProvider<Host = unknown, Wire = unknown> {
323
- /** Source parameter name recognized by the SRC weak parser. */
324
- readonly parameter: string;
325
- /** Wire field replacing the Host object parameter. */
326
- readonly wire: string;
327
- /** Canonical Host type symbol used by strict generation. */
328
- readonly hostTypeSymbol: string;
329
- /** Canonical wire type symbol used by strict generation. */
330
- readonly wireTypeSymbol: string;
331
- /**
332
- * Resolve a wire identity through the provider's default policy.
333
- * @param id - validated wire identity.
334
- * @returns the object, `undefined` when unavailable, or either asynchronously.
335
- */
336
- resolve(id: Wire): Host | undefined | Promise<Host | undefined>;
337
- }
338
- /** Stable wire declaration retained after a lookup provider unloads. */
339
- interface TypertLookupDefinition {
340
- /** Merge-declared lookup key. */
341
- readonly key: string;
342
- /** Source parameter name recognized by the SRC weak parser. */
343
- readonly parameter: string;
344
- /** Wire field replacing the Host object parameter. */
345
- readonly wire: string;
346
- /** Canonical Host type symbol used by strict generation. */
347
- readonly hostTypeSymbol: string;
348
- /** Canonical wire type symbol used by strict generation. */
349
- readonly wireTypeSymbol: string;
350
- }
351
- /** Host wire-to-Context resolver plus the declaration used by strict Remote methods. */
352
- interface TypertHostContextAdapter<Wire = unknown> {
353
- /** Wire field carrying the Context identity. */
354
- readonly wire: string;
355
- /** Canonical wire type symbol used by strict generation. */
356
- readonly wireTypeSymbol: string;
357
- /**
358
- * Resolve a validated wire identity to a live Host Context.
359
- * @param id - validated wire identity.
360
- * @returns the Context, or `undefined` when it is unavailable.
361
- */
362
- resolve(id: Wire): Context | undefined | Promise<Context | undefined>;
363
- }
364
- /** Composition-owned resolver replacing one Host Context adapter's default lookup policy. */
365
- type TypertHostContextResolver<Wire = unknown> = (id: Wire) => Context | undefined | Promise<Context | undefined>;
366
- /** Client-side bidirectional Context adapter. */
367
- interface TypertClientContextAdapter<Wire = unknown> {
368
- /**
369
- * Read the identity represented by a live Client Context.
370
- * @param ctx - Client Context inspected by a scoped Remote caller.
371
- * @returns the wire identity, or `undefined` for another Context kind.
372
- */
373
- identity(ctx: Context): Wire | undefined;
374
- /**
375
- * Resolve a validated identity synchronously for one Client invocation.
376
- * @param id - validated wire identity.
377
- * @returns a borrowed or invocation-owned Client Context, or undefined when unavailable.
378
- */
379
- resolve(id: Wire): Context | TypertOwnedValue<Context> | undefined;
380
- }
381
- /** Notification emitted after a Typert runtime registry changes. */
382
- interface TypertRegistryChange {
383
- readonly kind: 'local' | 'remote' | 'lookup' | 'host-context' | 'client-context';
384
- readonly key: string;
385
- }
386
- /** Listener for one Typert runtime registry. */
387
- type TypertRegistryListener = (change: TypertRegistryChange) => void;
388
- /** Current-environment invocation definitions. */
389
- interface TypertLocalRegistry {
390
- /**
391
- * Look up one invocation by `<namespace>/<method>`.
392
- * @param endpoint - canonical endpoint.
393
- * @returns the live descriptor, or `undefined` when absent.
394
- */
395
- get(endpoint: string): InvocationDescriptor | undefined;
396
- /**
397
- * Report whether a strict definition has existed during this Typert Service lifetime.
398
- * @param endpoint - canonical endpoint.
399
- * @returns `true` after the endpoint has been registered at least once, even if withdrawn.
400
- */
401
- hasSeen(endpoint: string): boolean;
402
- /** @returns a registration-order snapshot of local descriptors. */
403
- list(): readonly InvocationDescriptor[];
404
- /**
405
- * Observe later local-definition changes.
406
- * @param listener - synchronous contained observer.
407
- * @returns disposer for this subscription.
408
- */
409
- subscribe(listener: TypertRegistryListener): TypertDisposer;
410
- }
411
- /** Consumer-selected Remote contribution registry. */
412
- interface TypertRemoteRegistry {
413
- /**
414
- * Register one generated contribution for the calling Cordis fiber.
415
- * @param contribution - generated Remote descriptors.
416
- * @returns disposer withdrawing the exact contribution.
417
- */
418
- register(contribution: TypertRemoteContribution): TypertDisposer;
419
- /**
420
- * Look up one Remote descriptor by endpoint.
421
- * @param endpoint - canonical endpoint.
422
- * @returns the descriptor, or `undefined` when unmounted.
423
- */
424
- get(endpoint: string): InvocationDescriptor | undefined;
425
- /** @returns a registration-order snapshot of Remote descriptors. */
426
- list(): readonly InvocationDescriptor[];
427
- /**
428
- * Observe later Remote contribution changes.
429
- * @param listener - synchronous contained observer.
430
- * @returns disposer for this subscription.
431
- */
432
- subscribe(listener: TypertRegistryListener): TypertDisposer;
433
- }
434
- /** Runtime registry for Host object lookup providers. */
435
- interface TypertLookupRegistry {
436
- /**
437
- * Register one provider under its merge-declared key.
438
- * @param key - lookup key.
439
- * @param provider - owning package's live resolver.
440
- * @returns disposer withdrawing the exact provider.
441
- */
442
- register<K extends StringKeyOf<TypertLookupMap>>(key: K, provider: TypertLookupProvider<TypertLookupHost<TypertLookupMap[K]>, TypertLookupWire<TypertLookupMap[K]>>): TypertDisposer;
443
- /**
444
- * Replace one provider's default resolution policy while this contribution is active.
445
- * Configuration may precede provider registration; without a live provider, `get()` remains unavailable.
446
- * @param key - lookup key whose wire declaration remains provider-owned.
447
- * @param resolver - composition-owned resolver used by every lookup of this key.
448
- * @returns disposer restoring the provider's default resolver.
449
- */
450
- configure<K extends StringKeyOf<TypertLookupMap>>(key: K, resolver: TypertLookupResolver<TypertLookupHost<TypertLookupMap[K]>, TypertLookupWire<TypertLookupMap[K]>>): TypertDisposer;
451
- /**
452
- * Look up one provider by runtime key.
453
- * @param key - descriptor lookup key.
454
- * @returns the live provider, or `undefined` when absent.
455
- */
456
- get(key: string): TypertLookupProvider | undefined;
457
- /** @returns lookup declarations observed during this Typert Service lifetime. */
458
- definitions(): readonly TypertLookupDefinition[];
459
- /** @returns a snapshot of registered provider keys. */
460
- keys(): readonly string[];
461
- /**
462
- * Observe later lookup changes.
463
- * @param listener - synchronous contained observer.
464
- * @returns disposer for this subscription.
465
- */
466
- subscribe(listener: TypertRegistryListener): TypertDisposer;
467
- }
468
- /** Runtime registry for the Host and Client adapters of each Context kind. */
469
- interface TypertContextRegistry {
470
- /**
471
- * Register a Host Context adapter.
472
- * @param key - merge-declared Context key.
473
- * @param adapter - owning package's Host resolver and wire declaration.
474
- * @returns disposer withdrawing the exact adapter.
475
- */
476
- registerHost<K extends StringKeyOf<TypertContextMap>>(key: K, adapter: TypertHostContextAdapter<TypertContextWire<TypertContextMap[K]>>): TypertDisposer;
477
- /**
478
- * Override one Host Context key's resolution policy for the calling fiber.
479
- * Configuration may precede provider registration and restores the provider's default resolver on disposal.
480
- * @param key - merge-declared Context key.
481
- * @param resolver - composition-owned resolver used by every Host Context lookup of this key.
482
- * @returns disposer restoring the provider's default resolver.
483
- */
484
- configureHost<K extends StringKeyOf<TypertContextMap>>(key: K, resolver: TypertHostContextResolver<TypertContextWire<TypertContextMap[K]>>): TypertDisposer;
485
- /**
486
- * Register a Client Context adapter.
487
- * @param key - merge-declared Context key.
488
- * @param adapter - owning package's bidirectional Client projection.
489
- * @returns disposer withdrawing the exact adapter.
490
- */
491
- registerClient<K extends StringKeyOf<TypertContextMap>>(key: K, adapter: TypertClientContextAdapter<TypertContextWire<TypertContextMap[K]>>): TypertDisposer;
492
- /**
493
- * Look up a Host Context adapter.
494
- * @param key - descriptor Context key.
495
- * @returns the adapter, or `undefined` when absent.
496
- */
497
- getHost(key: string): TypertHostContextAdapter | undefined;
498
- /**
499
- * Look up a Client Context adapter.
500
- * @param key - descriptor Context key.
501
- * @returns the adapter, or `undefined` when absent.
502
- */
503
- getClient(key: string): TypertClientContextAdapter | undefined;
504
- /**
505
- * Observe later Context adapter changes.
506
- * @param listener - synchronous contained observer.
507
- * @returns disposer for this subscription.
508
- */
509
- subscribe(listener: TypertRegistryListener): TypertDisposer;
510
- }
511
- /** Minimal Typert runtime consumed through dependency inversion. */
512
- interface TypertRegistryContract {
513
- readonly local: TypertLocalRegistry;
514
- readonly remotes: TypertRemoteRegistry;
515
- readonly lookups: TypertLookupRegistry;
516
- readonly contexts: TypertContextRegistry;
517
- }
518
- declare module '@deepseek-ai/cordis' {
519
- interface Context {
520
- typert: TypertRegistryContract;
521
- /**
522
- * The Remote call this Context was derived for, or `undefined` on a
523
- * Context no Remote call derived. A Service method reads it as
524
- * `this.ctx.invocation`.
525
- */
526
- readonly invocation: RemoteInvocation | undefined;
527
- }
528
- }
529
- //#endregion
530
- //#region ../../../vendor/deepseek-harness/packages/typert/protocol/lib/types/index.d.ts
531
- /** Options for an explicit Service-to-Gateway binding. */
532
- interface TypertGatewayBindingOptions {
533
- /** Wire namespace; defaults to the Cordis service key. */
534
- readonly namespace?: string;
535
- }
536
- /** Visible declaration that one Service participates in Typert Gateway export. */
537
- interface TypertGatewayBinding<Service extends object = object> {
538
- readonly service: Service;
539
- readonly serviceKey: string;
540
- readonly namespace: string;
541
- }
542
- /** Cordis Service base that exposes its registered name through Typert Gateway. */
543
- declare abstract class TypertRemoteService<out T = never> extends Service<T> {
544
- /** Visible binding consumed by the Gateway's source-mode discovery. */
545
- readonly typertRemote: TypertGatewayBinding<this>;
546
- /**
547
- * Register the Service and bind the same key to Typert Gateway.
548
- * @param ctx - owning Cordis Context.
549
- * @param serviceKey - exact Cordis service key and default wire namespace.
550
- * @param options - optional distinct wire namespace.
551
- */
552
- protected constructor(ctx: Context, serviceKey: string, options?: TypertGatewayBindingOptions);
553
- }
554
- //#endregion
555
- //#region ../../../vendor/deepseek-harness/packages/attachment/attachment/lib/types/error.d.ts
556
- declare const ATTACHMENT_ERROR_CODES: readonly ["TOO_MANY_IMAGES", "IMAGES_TOO_LARGE", "UNSUPPORTED_IMAGE_TYPE", "INVALID_IMAGE_BASE64", "INVALID_IMAGE", "IMAGE_TYPE_MISMATCH", "IMAGE_TOO_LARGE", "IMAGE_TOO_MANY_PIXELS", "IMAGE_DIMENSION_TOO_LARGE", "INVALID_FILE_BASE64", "INVALID_ATTACHMENT_REF", "ATTACHMENT_CORRUPT", "ATTACHMENT_WRITE_FAILED", "ATTACHMENT_NOT_FOUND", "ATTACHMENT_READ_FAILED", "ATTACHMENT_PROJECTION_UNSUPPORTED", "ATTACHMENT_FILES_UNSUPPORTED"];
557
- /** Stable attachment failure codes used for protocol error routing. */
558
- type AttachmentErrorCode = typeof ATTACHMENT_ERROR_CODES[number];
559
- /**
560
- * Stable failures suitable for host RPC error mapping.
561
- *
562
- * Deliberately re-implements the `HarnessError` shape instead of extending it:
563
- * the base lives in `@deepseek-ai/dsh-llm`, which itself depends on this
564
- * package (`ImageBlock` references `ImageAttachmentRef`), so sharing the base
565
- * would create a dependency cycle. Consumers route on `code`, never on the
566
- * prototype chain, so the shapes stay interchangeable at the wire boundary.
567
- */
568
- declare class AttachmentError extends Error {
569
- /** Stable machine-routing failure code. */
570
- readonly code: AttachmentErrorCode;
571
- /**
572
- * @param message - human-readable failure description without raw bytes or host paths.
573
- * @param code - stable machine-routing code.
574
- * @param options - optional chained cause.
575
- */
576
- constructor(message: string, code: AttachmentErrorCode, options?: ErrorOptions);
577
- }
578
- //#endregion
579
- //#region ../../../vendor/deepseek-harness/packages/attachment/attachment/lib/types/brand.d.ts
580
- /** Opaque content-addressed identifier for one immutable attachment object. */
581
- type AttachmentId = Branded<'AttachmentId'>;
582
- /**
583
- * Brand a validated storage identifier.
584
- * @param value - backend-produced opaque identifier.
585
- * @returns the branded identifier.
586
- */
587
- declare function AttachmentId(value: string): AttachmentId;
588
- /** Opaque deterministic identity for one request-image transformation. */
589
- type ImageVariantId = Branded<'ImageVariantId'>;
590
- /**
591
- * Brand a validated request-image transformation identifier.
592
- * @param value - attachment-provider-produced opaque identifier.
593
- * @returns the branded identifier.
594
- */
595
- declare function ImageVariantId(value: string): ImageVariantId;
596
- //#endregion
597
- //#region ../../../vendor/deepseek-harness/packages/attachment/attachment/lib/types/types.d.ts
598
- /** Raster image formats accepted by the version-one attachment path. */
599
- type ImageMediaType = 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif';
600
- /** Durable, serializable reference to one immutable normalized image. */
601
- interface ImageAttachmentRef {
602
- /** Opaque storage identifier; never a filesystem path or bearer URL. */
603
- attachmentId: AttachmentId;
604
- /** Media type verified from the stored bytes. */
605
- mediaType: ImageMediaType;
606
- /** Exact encoded byte length. */
607
- bytes: number;
608
- /** Intrinsic encoded width in pixels. */
609
- width: number;
610
- /** Intrinsic encoded height in pixels. */
611
- height: number;
612
- /** Optional display name stripped of local path information. */
613
- name?: string;
614
- /**
615
- * Input dimensions after applying EXIF orientation and before normalization
616
- * scaling. Present only when normalization reduced the image.
617
- */
618
- originalDimensions?: {
619
- width: number;
620
- height: number;
621
- };
622
- }
623
- /**
624
- * Durable, serializable reference to one verbatim stored file. Files are
625
- * stored byte-for-byte with no normalization; `attachmentId` is the sha256
626
- * digest of exactly those bytes.
627
- */
628
- interface FileAttachmentRef {
629
- /** Opaque content-addressed storage identifier; never a filesystem path or bearer URL. */
630
- attachmentId: AttachmentId;
631
- /** Sanitized display filename, also the stored object's leaf name. */
632
- name: string;
633
- /** Exact byte length. */
634
- bytes: number;
635
- }
636
- /** Base64-encoded file upload accompanying one wire request. */
637
- interface EncodedFileAttachment {
638
- /** Canonical base64 encoding of the file bytes. */
639
- data: string;
640
- /** Optional display name; it is never interpreted as a path. */
641
- name?: string;
642
- }
643
- /** Request to durably commit one file verbatim. */
644
- interface SaveFileAttachment {
645
- data: Uint8Array;
646
- /** Optional browser/provider display name; it is never interpreted as a path. */
647
- name?: string;
648
- }
649
- /** Request to durably commit one file from bounded byte chunks. */
650
- interface SaveFileStreamAttachment {
651
- /** Exact file bytes in order; providers must not retain the complete sequence in memory. */
652
- data: AsyncIterable<Uint8Array>;
653
- /** Optional cancellation for source reads and storage writes. */
654
- signal?: AbortSignal;
655
- /** Optional browser/provider display name; it is never interpreted as a path. */
656
- name?: string;
657
- }
658
- /** Deployment-resolved limits used by upload admission and request buffering. */
659
- interface ImageAttachmentLimits {
660
- maxImageBytes: number;
661
- maxImagesPerMessage: number;
662
- maxMessageImageBytes: number;
663
- maxImagePixels: number;
664
- /** Maximum intrinsic width and maximum intrinsic height in pixels for one image. */
665
- maxImageDimension: number;
666
- mediaTypes: readonly ImageMediaType[];
667
- }
668
- /**
669
- * Browser-submitted prompt content accepted by Host prompt endpoints; the
670
- * accepting Host promotes image parts to durable references through
671
- * `ctx.attachments.admitPromptContent()` before any message is created, so a wire caller can
672
- * never cite an attachment it did not upload.
673
- */
674
- type PromptContentPart = {
675
- readonly type: 'text';
676
- readonly text: string;
677
- } | {
678
- readonly type: 'image';
679
- readonly mediaType: ImageMediaType;
680
- readonly data: string;
681
- readonly name?: string;
682
- };
683
- /** Host prompt content whose file receipts are resolved and whose image bytes await admission. */
684
- type AttachmentAdmissionPart = PromptContentPart | {
685
- readonly type: 'file';
686
- readonly attachment: FileAttachmentRef;
687
- };
688
- /** Host-admitted prompt content with every attachment represented by its durable reference. */
689
- type AdmittedPromptContentPart = {
690
- readonly type: 'text';
691
- readonly text: string;
692
- } | {
693
- readonly type: 'image';
694
- readonly attachment: ImageAttachmentRef;
695
- } | {
696
- readonly type: 'file';
697
- readonly attachment: FileAttachmentRef;
698
- };
699
- /** Request to validate and durably commit one image. */
700
- interface SaveImageAttachment {
701
- data: Uint8Array;
702
- /** Caller-declared media type, checked against fully decoded bytes. */
703
- mediaType: ImageMediaType;
704
- /** Optional browser/provider display name; it is never interpreted as a path. */
705
- name?: string;
706
- }
707
- /** Stored image bytes returned after reference and digest verification. */
708
- interface StoredImageAttachment {
709
- ref: ImageAttachmentRef;
710
- data: Uint8Array;
711
- }
712
- /** Deterministic request-image target selected by one exact model route for one attachment. */
713
- interface ImageRequestTarget {
714
- /** Target width in pixels; a target above the source keeps the source width. */
715
- width: number;
716
- /** Target height in pixels; a target above the source keeps the source height. */
717
- height: number;
718
- /** Encoded-byte target before base64 expansion or Files API upload; the smallest quality-ladder output is kept when no quality fits. */
719
- maxBytes: number;
720
- }
721
- /** Cached request version derived from one provider-independent normalized attachment. */
722
- interface RequestImageAttachment {
723
- /** Cache and upload-index key over the attachment id, policy, and fixed encoder parameters. */
724
- variantId: ImageVariantId;
725
- /** Durable normalized attachment from which this request version was derived. */
726
- attachment: ImageAttachmentRef;
727
- /** Encoded request bytes. */
728
- data: Uint8Array;
729
- mediaType: ImageMediaType;
730
- bytes: number;
731
- width: number;
732
- height: number;
733
- /** Provider-compatible sample depth proven after request encoding. */
734
- depth: 'uchar';
735
- /** Provider-compatible color space proven after request encoding. */
736
- space: 'srgb';
737
- /** Whether the encoded request version retains an alpha channel. */
738
- hasAlpha: boolean;
739
- }
740
- //#endregion
741
- //#region ../../../vendor/deepseek-harness/packages/attachment/attachment/lib/types/index.d.ts
742
- declare module '@deepseek-ai/cordis' {
743
- interface Context {
744
- attachments: AttachmentStore;
745
- }
746
- }
747
- /** Immutable binary attachment service. Implementations validate bytes before publishing a reference. */
748
- declare abstract class AttachmentStore extends Service {
749
- constructor(ctx: Context);
750
- /** Deployment-resolved image policy used by authoritative and fast-path validation. */
751
- abstract readonly imageLimits: ImageAttachmentLimits;
752
- /**
753
- * Validate one image without persisting it.
754
- * Batch callers validate every member before saving any member.
755
- * @param input - encoded bytes, declared media type, and optional display name.
756
- * @returns completion after the encoded raster has been fully decoded.
757
- */
758
- abstract validateImage(input: SaveImageAttachment): Promise<void>;
759
- /**
760
- * Validate one ordered image batch before committing any member.
761
- * Validation failures start no writes; storage failures return no partial
762
- * references, although already published content-addressed objects may stay
763
- * unreachable until a future retention policy collects them.
764
- * @param inputs - encoded images in their owning message order.
765
- * @returns durable references in the exact input order.
766
- */
767
- protected validateImageBatch(inputs: readonly SaveImageAttachment[]): void;
768
- /**
769
- * Validate and durably commit one ordered image batch.
770
- * @param inputs - encoded images in owning-message order.
771
- * @returns durable normalized attachment references in the same order after every member succeeds.
772
- */
773
- saveImages(inputs: readonly SaveImageAttachment[]): Promise<readonly ImageAttachmentRef[]>;
774
- /**
775
- * Admit one Host prompt and replace each uploaded image with its durable reference.
776
- * Text and durable file references pass through unchanged. A prompt without image parts performs no storage operation.
777
- * @param content - prompt parts in message order after file receipt resolution.
778
- * @returns admitted prompt parts in the same order as `content`.
779
- * @throws AttachmentError when the image batch is refused.
780
- */
781
- admitPromptContent(content: readonly AttachmentAdmissionPart[]): Promise<AdmittedPromptContentPart[]>;
782
- /**
783
- * Decode and durably commit one canonical base64 file upload.
784
- * @param input - canonical base64 bytes and optional display name.
785
- * @returns the durable content-addressed file reference.
786
- * @throws AttachmentError when the encoding or storage operation is refused.
787
- */
788
- admitEncodedFile(input: EncodedFileAttachment): Promise<FileAttachmentRef>;
789
- /**
790
- * Identify a failure emitted by this attachment capability by its stable code.
791
- * @param error - value caught from an attachment operation.
792
- * @returns whether the value is an attachment failure.
793
- */
794
- isAttachmentError(error: unknown): error is AttachmentError;
795
- /**
796
- * Validate and durably commit one image before its owning session event is appended.
797
- * The returned reference describes the persisted normalized image. When
798
- * normalization reduces the raster, its `originalDimensions` records the
799
- * orientation-applied input dimensions.
800
- * @param input - encoded bytes, declared media type, and optional display name.
801
- * @returns the durable content-addressed normalized image reference.
802
- */
803
- abstract saveImage(input: SaveImageAttachment): Promise<ImageAttachmentRef>;
804
- /**
805
- * Read one image and verify that bytes still match the recorded reference.
806
- * @param ref - durable reference from the session log.
807
- * @param signal - optional cancellation for backend read and verification work.
808
- * @returns the verified bytes and normalized attachment reference.
809
- * @throws the signal reason when aborted, or a storage error when verification fails.
810
- */
811
- abstract readImage(ref: ImageAttachmentRef, signal?: AbortSignal): Promise<StoredImageAttachment>;
812
- /**
813
- * Locate the provider-owned normalized object in the harness host filesystem.
814
- * @param ref - durable normalized attachment reference.
815
- * @returns an absolute host path, or undefined when this backend is not host-file-backed.
816
- * @throws an AttachmentError when the durable reference is invalid.
817
- */
818
- imageHostPath(ref: ImageAttachmentRef): string | undefined;
819
- /**
820
- * Durably commit one file byte-for-byte before its owning session event is
821
- * appended. Files carry no admission limits: any byte content and length is
822
- * accepted, and the stored object is the exact submitted bytes. Backends
823
- * without verbatim file storage keep this default rejection.
824
- * @param input - exact bytes and optional display name.
825
- * @returns the durable content-addressed file reference.
826
- */
827
- saveFile(input: SaveFileAttachment): Promise<FileAttachmentRef>;
828
- /**
829
- * Durably commit one file byte-for-byte from bounded chunks. Providers must
830
- * apply backpressure and must not collect the complete file in memory.
831
- * Backends without streamed verbatim storage keep this default rejection.
832
- * @param input - ordered exact bytes, optional cancellation, and display name.
833
- * @returns the durable content-addressed file reference.
834
- */
835
- saveFileStream(input: SaveFileStreamAttachment): Promise<FileAttachmentRef>;
836
- /**
837
- * Read and verify one verbatim stored file as bounded chunks. Providers must
838
- * not collect the complete file in memory. Backends without verbatim file
839
- * reads keep this default rejection.
840
- * @param ref - durable reference from the session log.
841
- * @param signal - optional cancellation for backend reads and verification work.
842
- * @returns exact file bytes in order; integrity failures reject the iteration.
843
- */
844
- readFileStream(ref: FileAttachmentRef, signal?: AbortSignal): AsyncIterable<Uint8Array>;
845
- /**
846
- * Locate the verbatim stored file object in the harness host filesystem.
847
- * @param ref - durable file reference.
848
- * @returns an absolute host path, or undefined when this backend is not host-file-backed.
849
- * @throws an AttachmentError when the durable reference is invalid.
850
- */
851
- fileHostPath(ref: FileAttachmentRef): string | undefined;
852
- /**
853
- * Generate or read one deterministic model-request version from the stored normalized image.
854
- * @param ref - durable provider-independent normalized attachment reference.
855
- * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output.
856
- * @param signal - optional cancellation.
857
- * @returns request bytes and the cache/upload identity covering every transform input.
858
- */
859
- readImageRequest(ref: ImageAttachmentRef, target: ImageRequestTarget, signal?: AbortSignal): Promise<RequestImageAttachment>;
860
- }
861
- //#endregion
862
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/brand.d.ts
863
- /** Stable identity carried by one message across inbox, log, and model-request boundaries. */
864
- type MessageId = Branded<'MessageId'>;
865
- /**
866
- * Brand a message identifier.
867
- * @param id - the opaque message identifier.
868
- * @returns the same string with the message-id brand.
869
- */
870
- declare function MessageId(id: string): MessageId;
871
- /**
872
- * Correlates a model-issued tool call with its result. Provider-issued for
873
- * real adapters; synthesized by mocks/assembler fallbacks.
874
- */
875
- type ToolCallId = Branded<'ToolCallId'>;
876
- /**
877
- * Brand a string as a {@link ToolCallId}.
878
- * @param id - the provider-issued or synthesized call id.
879
- * @returns the same string with the tool-call-id brand.
880
- */
881
- declare function ToolCallId(id: string): ToolCallId;
882
- /** Provider-issued request identifier retained for diagnostics across package boundaries. */
883
- type ProviderRequestId = Branded<'ProviderRequestId'>;
884
- /**
885
- * Brand a provider-issued request identifier.
886
- * @param id - the opaque provider-issued string.
887
- * @returns the same string, branded; no validation is performed.
888
- */
889
- declare function ProviderRequestId(id: string): ProviderRequestId;
890
- /** Adapter-owned identifier for one model's selectable reasoning effort. */
891
- type ReasoningEffortId = Branded<'ReasoningEffortId'>;
892
- /**
893
- * Brand an adapter-owned reasoning-effort identifier.
894
- * @param id - the opaque identifier exposed by one model capability.
895
- * @returns the same string, branded; no validation is performed.
896
- */
897
- declare function ReasoningEffortId(id: string): ReasoningEffortId;
898
- //#endregion
899
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/message.d.ts
900
- /** Provider/model identity and adapter-private replay data for an assistant message. */
901
- interface AssistantProviderMetadata {
902
- /** Provider route that produced the message. */
903
- provider: string;
904
- /** Provider model id that produced the message. */
905
- model: string;
906
- /**
907
- * Lossless-JSON adapter state needed to replay the provider response.
908
- * `LlmRuntime` exposes it to a target adapter only when that adapter instance
909
- * currently owns both this historical provider and the target provider.
910
- */
911
- replayState?: unknown;
912
- }
913
- /** Required source of an assistant message produced by a routed model. */
914
- interface ModelMessageSource extends AssistantProviderMetadata {
915
- kind: 'model';
916
- }
917
- /** Required source of a tool-role message carrying one tool result. */
918
- interface ToolMessageSource {
919
- kind: 'tool';
920
- callId: ToolCallId;
921
- }
922
- /** Required source of a system-role message produced by the system-prompt plugin. */
923
- interface SystemPromptMessageSource {
924
- kind: 'system-prompt';
925
- }
926
- /**
927
- * Where a message (or injected content) came from, in the harness's own
928
- * vocabulary. Merge-extensible sum type — each producer declares its own
929
- * `kind` in its own module; there is no shared catch-all `plugin` kind.
930
- * Model and tool sources answer their role messages; user messages carry any
931
- * producer's kind, and consumers fall through unknown kinds.
932
- */
933
- interface MessageSourceMap {
934
- user: {
935
- kind: 'user';
936
- };
937
- model: ModelMessageSource;
938
- tool: ToolMessageSource;
939
- 'system-prompt': SystemPromptMessageSource;
940
- }
941
- /** Any known message source, derived from {@link MessageSourceMap}; switch on `kind` and fall through unknowns (merge-extensible). */
942
- type MessageSource = MessageSourceMap[keyof MessageSourceMap];
943
- /** Shared immutable fields of every conversation message. */
944
- interface MessageBase {
945
- /** Stable identity preserved across every representation boundary. */
946
- readonly id: MessageId;
947
- /** Exact model-facing blocks. */
948
- readonly content: readonly ContentBlock[];
949
- /** Required source fields supplied by the producer.
950
- * @persistenceSource user developer
951
- */
952
- readonly source: MessageSource;
953
- }
954
- /** A rendered system prompt attributed to the system-prompt producer; empty content sends no prompt. */
955
- interface SystemMessage extends MessageBase {
956
- readonly role: 'system';
957
- readonly source: MessageSourceMap['system-prompt'];
958
- }
959
- /** Incremental agent session changes in conversation order, currently tool additions and removals. */
960
- interface DeveloperMessage extends MessageBase {
961
- readonly role: 'developer';
962
- }
963
- /** A user-role specialization of the shared message representation. */
964
- interface UserMessage extends MessageBase {
965
- readonly role: 'user';
966
- }
967
- /** A model-produced assistant specialization of the shared message representation. */
968
- interface AssistantMessage extends MessageBase {
969
- readonly role: 'assistant';
970
- readonly source: ModelMessageSource;
971
- }
972
- /** A first-class tool-role message carrying the result of one tool invocation. */
973
- interface ToolResultMessage extends MessageBase {
974
- readonly role: 'tool';
975
- readonly source: ToolMessageSource;
976
- /** Provider-issued id of the tool call this message answers. */
977
- readonly toolCallId: ToolCallId;
978
- /** Whether the tool invocation failed. */
979
- readonly isError?: boolean;
980
- }
981
- /**
982
- * The conversation messages persisted by Session, keyed by role. This map is
983
- * closed because every model-visible role must have a durable Session event
984
- * and an adapter projection.
985
- */
986
- interface MessageRoleMap {
987
- system: SystemMessage;
988
- developer: DeveloperMessage;
989
- user: UserMessage;
990
- assistant: AssistantMessage;
991
- tool: ToolResultMessage;
992
- }
993
- /** Any persisted conversation message, discriminated by its `role`. */
994
- type Message = MessageRoleMap[keyof MessageRoleMap];
995
- //#endregion
996
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/types.d.ts
997
- declare module '@deepseek-ai/cordis' {
998
- interface Events {
999
- /**
1000
- * The provider topology changed: an adapter registered or unregistered
1001
- * routes, or the configurable-provider directory gained or lost entries.
1002
- * This payload-free registry notification fires at each commit point
1003
- * (including registration disposal); consumers re-read `listProviders()`,
1004
- * `listModels()`, or `listConfigurableProviders()` for the new state.
1005
- * Observer failures are contained and cannot veto the registry mutation.
1006
- * @mode emit
1007
- */
1008
- 'llm/adapters-updated'(): void;
1009
- }
1010
- }
1011
- /** Serializable provider or transport failure facts; policy decides whether they are retryable. */
1012
- interface LlmFailure {
1013
- /** Human-readable provider or transport failure. */
1014
- readonly message: string;
1015
- /** Stable provider-neutral machine-routing code. */
1016
- readonly code: string;
1017
- /** HTTP status returned by the provider, when available. */
1018
- readonly status?: number;
1019
- /** Provider-requested delay in milliseconds, when valid and available. */
1020
- readonly providerRetryAfterMs?: number;
1021
- /** Opaque provider-issued request identifier for diagnostics. */
1022
- readonly requestId?: ProviderRequestId;
1023
- /**
1024
- * With code `IMAGE_OFFLOAD_REQUIRED`: how many more of the oldest retained
1025
- * image occurrences the route needs offloaded before the same request fits
1026
- * its exact byte accounting. `dsh-compaction-image-offload` records the
1027
- * selected occurrences in an `image/offload` event and retries the step.
1028
- */
1029
- readonly offloadImages?: number;
1030
- }
1031
- /** Plain text visible to the end user. */
1032
- interface TextBlock {
1033
- type: 'text';
1034
- text: string;
1035
- }
1036
- /** Reasoning / thinking content, distinct from visible text. */
1037
- interface ReasoningBlock {
1038
- type: 'reasoning';
1039
- text: string;
1040
- }
1041
- /**
1042
- * A durable raster image reference, valid in user or assistant content. The
1043
- * block is deliberately role-neutral; assistant-side rendering is forward
1044
- * compatibility — the current production adapters declare text-only output,
1045
- * so only user messages may carry images.
1046
- */
1047
- interface ImageBlock {
1048
- type: 'image';
1049
- /** Immutable bytes and intrinsic display metadata owned by the attachment service. */
1050
- attachment: ImageAttachmentRef;
1051
- /**
1052
- * Derived from a durable image-offload decision or preserved by a message
1053
- * rewrite. Every route sends placeholder text naming the image and its
1054
- * available read-only path instead of image bytes.
1055
- */
1056
- offloaded?: true;
1057
- }
1058
- /**
1059
- * A durable verbatim file reference, valid in user content. Files never reach
1060
- * a provider natively: request assembly projects every occurrence to
1061
- * deterministic handle text (name, byte size, and the read-only saved path),
1062
- * so adapters and providers see text in its place while the durable log keeps
1063
- * the structured reference for presentation and authorization.
1064
- */
1065
- interface FileBlock {
1066
- type: 'file';
1067
- /** Immutable verbatim bytes and display metadata owned by the attachment service. */
1068
- attachment: FileAttachmentRef;
1069
- }
1070
- /** A tool invocation requested by the model. */
1071
- interface ToolCallBlock {
1072
- type: 'tool-call';
1073
- /** Provider-issued call id; correlates with the matching tool result. */
1074
- id: ToolCallId;
1075
- name: string;
1076
- /** Raw JSON string as produced by the model. */
1077
- arguments: string;
1078
- }
1079
- /** Activates a tool definition from the developer event's referenced request header. */
1080
- interface ToolAdditionBlock {
1081
- type: 'tool-addition';
1082
- /** Name of exactly one tool in the referenced historical header. */
1083
- toolName: string;
1084
- /**
1085
- * Reserved against inline definitions; the historical request header owns the schema.
1086
- * @persistenceReserved
1087
- */
1088
- tool?: never;
1089
- }
1090
- /** Records the dynamic removal of a tool identified by its session-local name. */
1091
- interface ToolRemovalBlock {
1092
- type: 'tool-removal';
1093
- toolName: string;
1094
- }
1095
- /**
1096
- * Merge-extensible content blocks keyed by `type`. New core blocks must land
1097
- * with adapter, UI, and compaction support. Tool-change blocks belong to
1098
- * developer messages; `projectToolUpdates` selects what each route receives.
1099
- */
1100
- interface ContentBlockMap {
1101
- 'text': TextBlock;
1102
- 'reasoning': ReasoningBlock;
1103
- 'image': ImageBlock;
1104
- 'file': FileBlock;
1105
- 'tool-call': ToolCallBlock;
1106
- 'tool-addition': ToolAdditionBlock;
1107
- 'tool-removal': ToolRemovalBlock;
1108
- }
1109
- /** The block `type` tag vocabulary; widens as plugins add entries to {@link ContentBlockMap}. */
1110
- type ContentBlockType = keyof ContentBlockMap;
1111
- /** Any known content block, derived from {@link ContentBlockMap}; switch on `type` and fall through unknowns (merge-extensible). */
1112
- type ContentBlock = ContentBlockMap[ContentBlockType];
1113
- /**
1114
- * Why a model response stopped.
1115
- * Merge-extensible so adapters can surface provider-specific reasons.
1116
- */
1117
- interface FinishReasonMap {
1118
- 'stop': {
1119
- kind: 'stop';
1120
- };
1121
- 'tool-calls': {
1122
- kind: 'tool-calls';
1123
- };
1124
- 'max-tokens': {
1125
- kind: 'max-tokens';
1126
- };
1127
- 'aborted': {
1128
- kind: 'aborted';
1129
- failure: LlmFailure;
1130
- };
1131
- 'error': {
1132
- kind: 'error';
1133
- failure: LlmFailure;
1134
- };
1135
- }
1136
- /** Any known finish reason, derived from {@link FinishReasonMap}; switch on `kind` and fall through unknowns (merge-extensible). */
1137
- type FinishReason = FinishReasonMap[keyof FinishReasonMap];
1138
- /**
1139
- * Token accounting for one model call (cache fields are optional).
1140
- *
1141
- * Counts are DISJOINT: `inputTokens` is uncached input only; cached input is
1142
- * reported separately as `cacheReadTokens`/`cacheWriteTokens` (billed input =
1143
- * sum of the three). Adapters whose providers fold cache hits into a total
1144
- * prompt count (DeepSeek's `prompt_tokens`) subtract them out.
1145
- */
1146
- interface TokenUsage {
1147
- inputTokens: number;
1148
- outputTokens: number;
1149
- /**
1150
- * Exact full-call total including aggregate prompt and output tokens.
1151
- *
1152
- * Adapters preserve a provider total or derive it from authoritative
1153
- * aggregate prompt/output counters; they omit it when unavailable or
1154
- * inconsistent.
1155
- */
1156
- totalTokens?: number;
1157
- cacheReadTokens?: number;
1158
- cacheWriteTokens?: number;
1159
- reasoningTokens?: number;
1160
- }
1161
- /**
1162
- * Request price of one ordered image occurrence under one exact model route's
1163
- * request projection. Every occurrence resolves to the pair the wire actually
1164
- * carries: provider visual tokens for a retained image, plus the model-visible
1165
- * text sent with or instead of it (request-preview handle, offload placeholder,
1166
- * or text-only substitution). The caller prices `text` with its own text
1167
- * estimator so provider pricing never fixes a text tokenization.
1168
- */
1169
- interface LlmImageRequestPrice {
1170
- /** Provider visual tokens for the retained request image; 0 when only text represents this occurrence. */
1171
- visualTokens: number;
1172
- /** Model-visible text sent for this occurrence, to be priced by the caller's text estimator. */
1173
- text: string;
1174
- }
1175
- /**
1176
- * Provider-side request-image pricing for one exact model route. Implemented
1177
- * by adapters whose provider charges visual tokens; consumers (the token
1178
- * meter) resolve it synchronously per measurement, so implementations must not
1179
- * perform I/O.
1180
- */
1181
- interface LlmImageRequestPricing {
1182
- /**
1183
- * Price every image occurrence of one request projection.
1184
- * @param images - surface image blocks in request order, one entry per occurrence; an `offloaded` block
1185
- * is priced as its placeholder text.
1186
- * @returns one price per occurrence, aligned by index with `images`.
1187
- */
1188
- priceImages(images: readonly ImageBlock[]): readonly LlmImageRequestPrice[];
1189
- }
1190
- /** Display metadata for one registered provider route. */
1191
- interface LlmProviderInfo {
1192
- /** Provider route key used by {@link GenerateOptions.provider}. */
1193
- id: string;
1194
- /** Human-readable provider name for selectors and diagnostics. */
1195
- name: string;
1196
- }
1197
- /** Merge-extensible provider model modality vocabulary. */
1198
- interface ModelModalityMap {
1199
- text: 'text';
1200
- image: 'image';
1201
- }
1202
- /** Any declared provider model modality. */
1203
- type ModelModality = ModelModalityMap[keyof ModelModalityMap];
1204
- /**
1205
- * One provider route an adapter plugin can activate through configuration,
1206
- * whether or not the route is currently registered. Configuration surfaces
1207
- * merge this directory with `listProviders()` to offer every configurable
1208
- * provider alongside its live/dormant state.
1209
- */
1210
- interface LlmConfigurableProvider {
1211
- /** Provider route key this entry activates when configured. */
1212
- provider: string;
1213
- /** Human-readable provider name for configuration surfaces. */
1214
- displayName: string;
1215
- /** User-settings namespace whose section configures this provider. */
1216
- settingsNs: string;
1217
- /**
1218
- * Path from that namespace's section root to this provider's profile
1219
- * object; empty when the whole section is the profile.
1220
- */
1221
- settingsPath: readonly string[];
1222
- /**
1223
- * Whether the owning adapter knows this route only because configuration
1224
- * declared it — a gateway or self-hosted server it ships nothing about.
1225
- * Absent means the adapter draws no such distinction; false means it does
1226
- * and this route is one of its own. Only the adapter can answer: a stored
1227
- * profile is how a user-added route AND a corrected shipped one both look
1228
- * from outside.
1229
- */
1230
- declared?: boolean;
1231
- /** Configuration diagnostic for repair; unaffected models may remain serviceable. */
1232
- error?: string;
1233
- }
1234
- /**
1235
- * One interrogation of a provider endpoint that configuration has not stored
1236
- * yet. Configuration surfaces send the draft a user is still editing, so the
1237
- * request carries the endpoint and credential directly instead of naming a
1238
- * route: a provider being added has no route to name.
1239
- */
1240
- interface LlmModelDiscoveryRequest {
1241
- /**
1242
- * Route the draft is editing, when it edits an existing one. A route whose
1243
- * adapter already knows its models answers from that knowledge instead of
1244
- * asking the endpoint — the adapter's own registry is the better answer, and
1245
- * it costs no network call.
1246
- */
1247
- provider?: string;
1248
- /**
1249
- * Endpoint to interrogate. Optional because a route the adapter already
1250
- * describes needs none; a route it does not must supply one.
1251
- */
1252
- baseURL?: string;
1253
- /** Wire protocol the endpoint speaks, when the draft names one. */
1254
- api?: string;
1255
- /** Credential for this interrogation alone; the harness never stores it. */
1256
- apiKey?: string;
1257
- }
1258
- declare module '@deepseek-ai/dsh-typert-protocol' {
1259
- interface RemoteErrorDetailsMap {
1260
- /** A draft provider interrogation refused or failed. */
1261
- 'llm/model-discovery-rejected': {
1262
- readonly settingsNs: string;
1263
- readonly baseURL?: string;
1264
- };
1265
- }
1266
- }
1267
- /**
1268
- * One model an endpoint reports about itself. Every field but the id is
1269
- * optional because most provider listings disclose an id and nothing else;
1270
- * a surface adopting one of these still owes the capacities its adapter needs.
1271
- */
1272
- interface LlmDiscoveredModel {
1273
- /** Model id the endpoint accepts. */
1274
- id: string;
1275
- /** Human-readable name when the endpoint supplies one. */
1276
- name?: string;
1277
- /** Maximum combined request and response context, when disclosed. */
1278
- contextWindow?: number;
1279
- /** Maximum output tokens, when disclosed. */
1280
- maxTokens?: number;
1281
- /** Accepted input types when disclosed by the catalog or endpoint; absent means unknown. */
1282
- inputModalities?: readonly ModelModality[];
1283
- }
1284
- /** One adapter-discovered model; catalog membership is advisory, not request validation. */
1285
- interface LlmModelInfo {
1286
- /** Provider route that owns this model entry. */
1287
- provider: string;
1288
- /** Model id passed to {@link GenerateOptions.model}. */
1289
- id: string;
1290
- /** Human-readable model name for selectors. */
1291
- name: string;
1292
- /** Optional user-facing distinction from otherwise similar models. */
1293
- description?: string;
1294
- /** Accepted request modalities; absent means unknown, while an explicit omission is negative capability. */
1295
- inputModalities?: readonly ModelModality[];
1296
- }
1297
- /** Provider-owned context capacity for one exact provider/model route. */
1298
- interface LlmModelContext {
1299
- /** Maximum combined request and response context in tokens. */
1300
- contextWindow: number;
1301
- }
1302
- /** Display metadata for one adapter-owned reasoning effort. */
1303
- interface LlmReasoningEffortInfo {
1304
- /** Opaque stable value accepted by {@link GenerateOptions.reasoningEffort}. */
1305
- id: ReasoningEffortId;
1306
- /** Human-readable effort name for selectors and diagnostics. */
1307
- name: string;
1308
- /** Optional user-facing distinction from otherwise similar efforts. */
1309
- description?: string;
1310
- }
1311
- /** Selectable reasoning efforts for one exact provider/model route. */
1312
- interface LlmModelReasoningInfo {
1313
- /** Supported efforts in adapter-preferred display order. */
1314
- efforts: readonly LlmReasoningEffortInfo[];
1315
- /**
1316
- * Adapter-configured default materialized into requests when callers omit
1317
- * an effort. Absence preserves the provider's own default.
1318
- */
1319
- defaultEffort?: ReasoningEffortId;
1320
- }
1321
- /**
1322
- * How a model applies a system prompt that changes mid-conversation.
1323
- * `'in-history'`: the model reads the latest `system` message at any position
1324
- * of `messages` as the complete effective system prompt, so a changed prompt
1325
- * can follow the cached history instead of rewriting message 0.
1326
- */
1327
- type SystemPromptUpdate = 'in-history';
1328
- /**
1329
- * How a model accepts native tool declarations that change mid-conversation.
1330
- * `'addition-only'`: the model reads a `tool-addition` block in a later
1331
- * developer message as activating a tool declared with `deferLoading`, so an
1332
- * added tool follows the cached history instead of rewriting the declaration
1333
- * list. `'in-history'`: the model additionally reads `tool-removal` blocks,
1334
- * so a removed tool keeps its declaration and the removal follows the history.
1335
- * Absent means every request declares the complete current tool list.
1336
- */
1337
- type ToolUpdate = 'in-history' | 'addition-only';
1338
- /** Exact-route model metadata resolved by its owning adapter. */
1339
- interface LlmResolvedModelInfo extends LlmModelInfo {
1340
- /** Provider-owned context capacity when known. */
1341
- context?: LlmModelContext;
1342
- /** Adapter-configured per-request output cap materialized when callers omit one. */
1343
- defaultMaxTokens?: number;
1344
- /** Adapter-owned selectable reasoning levels when exposed. */
1345
- reasoning?: LlmModelReasoningInfo;
1346
- /** Declared mid-conversation system prompt handling; absent means only a leading system message is read. */
1347
- systemPromptUpdate?: SystemPromptUpdate;
1348
- /** Declared mid-conversation tool declaration handling; absent means every request declares the complete tool list. */
1349
- toolUpdate?: ToolUpdate;
1350
- }
1351
- /**
1352
- * Adapter-private lossless-JSON state for replaying a successful response,
1353
- * carried by a terminal `finish` chunk and stored on the assembled assistant
1354
- * message's model source. Both halves stay opaque to the harness; only the
1355
- * split is shared vocabulary, so assembly can keep stored metadata aligned
1356
- * with stored content without reading either half.
1357
- */
1358
- interface ReplayEnvelope {
1359
- /** Response-level adapter-private metadata (ids, native stop reason). */
1360
- response: unknown;
1361
- /**
1362
- * Per-block adapter-private metadata, one entry per emitted block in
1363
- * first-seen stream order. When assembly drops a block it drops the entry at
1364
- * the same position; entries whose length does not match the emitted block
1365
- * count discard the whole envelope. An adapter whose metadata is independent
1366
- * of block structure omits this field and the envelope passes through
1367
- * assembly unchanged.
1368
- */
1369
- blocks?: readonly unknown[];
1370
- }
1371
- /**
1372
- * Raw streaming protocol emitted by adapters.
1373
- * Block indexes correlate interleaved deltas, and `block-end` carries the
1374
- * assembled block. Adapters emit usage before the terminal finish and nothing
1375
- * afterward; tool arguments remain raw JSON strings. An adapter implementation
1376
- * may throw, but `LlmRuntime.stream()` normalizes that failure to a terminal
1377
- * `error` or `aborted` finish before exposing it to consumers.
1378
- */
1379
- type StreamChunk = {
1380
- type: 'block-start';
1381
- index: number;
1382
- blockType: ContentBlockType;
1383
- } | {
1384
- type: 'text-delta';
1385
- index: number;
1386
- text: string;
1387
- } | {
1388
- type: 'reasoning-delta';
1389
- index: number;
1390
- text: string;
1391
- } | {
1392
- type: 'tool-call-delta';
1393
- index: number;
1394
- id: ToolCallId;
1395
- name?: string;
1396
- argumentsDelta: string;
1397
- } | {
1398
- type: 'block-end';
1399
- index: number;
1400
- block: ContentBlock;
1401
- } | {
1402
- type: 'usage';
1403
- usage: TokenUsage;
1404
- } | {
1405
- type: 'finish';
1406
- reason: FinishReason;
1407
- /** Replay metadata for a successful response; see {@link ReplayEnvelope}. */
1408
- replayState?: ReplayEnvelope;
1409
- };
1410
- /**
1411
- * JSON-schema description of a tool, as sent to the model.
1412
- *
1413
- * Declared here (not in dsh-tools) because it is part of {@link GenerateOptions};
1414
- * dsh-tools' ToolDefinition and dsh-system-prompt's PromptAssembly both import
1415
- * it from this package.
1416
- */
1417
- interface ToolSchema {
1418
- /**
1419
- * Requests deferred loading of the tool definition into model context,
1420
- * independently of whether a tool-addition block records the tool.
1421
- * Uses Anthropic's defer_loading terminology.
1422
- */
1423
- deferLoading?: true;
1424
- name: string;
1425
- description: string;
1426
- /** JSON Schema object for the arguments. */
1427
- parameters: Record<string, unknown>;
1428
- }
1429
- /** User input for one LLM request; it has no durable Session identity or source. */
1430
- interface RequestUserInput {
1431
- readonly role: 'user';
1432
- readonly content: UserMessage['content'];
1433
- readonly id?: never;
1434
- readonly source?: never;
1435
- }
1436
- /** A durable conversation message or a user input used only for one request. */
1437
- type RequestMessage = Message | RequestUserInput;
1438
- /** Logged tool declarations and update identities since the last declaration reset. */
1439
- interface ToolHistory {
1440
- /** Complete active declarations at the start of this history. */
1441
- readonly tools: readonly ToolSchema[];
1442
- /** Ordered developer messages, with additions resolved from their historical headers. */
1443
- readonly updates: readonly {
1444
- /** Identity used to locate this update in the derived request history. */
1445
- readonly messageId: MessageId;
1446
- /** Added definitions resolved from the event's referenced request header. */
1447
- readonly additions: readonly ToolSchema[];
1448
- }[];
1449
- }
1450
- /** A single model request, fully assembled. */
1451
- interface GenerateOptions {
1452
- /** Registered provider route selecting the adapter instance. */
1453
- provider: string;
1454
- model: string;
1455
- /** Adapter-owned reasoning effort selected for this exact model. */
1456
- reasoningEffort?: ReasoningEffortId;
1457
- /**
1458
- * Ordered conversation messages, exactly as the provider sees them. A
1459
- * loop-built request passes the derived history (dsh-agent-loop), whose
1460
- * leading system-role message carries the system prompt; a hand-built
1461
- * one-shot may include identity-free user inputs.
1462
- */
1463
- messages: RequestMessage[];
1464
- /**
1465
- * System prompt text for one-shot callers; adapters map it to the provider's
1466
- * system slot ahead of `messages`. Loop-built requests leave it undefined.
1467
- */
1468
- system?: string;
1469
- /** Tool schemas (adapters map to the provider's `tools` field). */
1470
- tools?: ToolSchema[];
1471
- /** Session-folded tool history used for route projection; omission sends complete declarations without tool updates. */
1472
- toolHistory?: ToolHistory;
1473
- temperature?: number;
1474
- maxTokens?: number;
1475
- /**
1476
- * Stop sequences: generation halts as soon as the model produces any one of
1477
- * these strings (adapters map to the provider's stop field, e.g. OpenAI
1478
- * `stop`). The stop string itself is not included in the output.
1479
- */
1480
- stop?: string[];
1481
- signal?: AbortSignal;
1482
- /**
1483
- * Session identity stamped by the loop for request routing. Replay uses it
1484
- * to separate cursors; adapters may map it to model-hidden transport metadata.
1485
- */
1486
- sessionId?: Branded<'SessionId'>;
1487
- /**
1488
- * Provider-neutral classification for an auxiliary model call. Adapters may
1489
- * map the purpose to model-hidden transport metadata or purpose-specific
1490
- * generation policy. Ordinary conversation requests leave it unset.
1491
- */
1492
- purpose?: 'compaction' | 'session-title';
1493
- }
1494
- //#endregion
1495
- //#region ../../../vendor/deepseek-harness/vendor/cosmokit/lib/types/types.d.ts
1496
- declare function isArrayBufferLike(value: any): value is ArrayBufferLike;
1497
- declare function isArrayBufferSource(value: any): value is Binary.Source;
1498
- /** Binary source detection and base64/hex conversion helpers. */
1499
- declare namespace Binary {
1500
- type Source<T extends ArrayBufferLike = ArrayBufferLike> = T | ArrayBufferView<T>;
1501
- const is: typeof isArrayBufferLike;
1502
- const isSource: typeof isArrayBufferSource;
1503
- function fromSource<T extends ArrayBufferLike>(source: Source<T>): T;
1504
- function toBase64(source: Source): string;
1505
- function fromBase64(source: string): ArrayBuffer | Uint8Array<ArrayBuffer>;
1506
- function toHex(source: Source): string;
1507
- function fromHex(source: string): ArrayBuffer;
1508
- }
1509
- //#endregion
1510
- //#region ../../../vendor/deepseek-harness/vendor/cosmokit/lib/types/misc.d.ts
1511
- /** String/symbol keyed dictionary type. */
1512
- type Dict<T = any, K extends string | symbol = string> = { [key in K]: T; };
1513
- //#endregion
1514
- //#region ../../../vendor/deepseek-harness/vendor/cosmokit/lib/types/volatile.d.ts
1515
- /** Shared config references used by schema validators and plugin runtimes. */
1516
- /** Recursively readonly data returned by a volatile config reference. */
1517
- type VolatileSnapshot<T> = T extends object ? { readonly [K in keyof T]: VolatileSnapshot<T[K]>; } : T;
1518
- /** A stable reference; keep the reference, or capture its value for one operation only. */
1519
- interface Volatile<T> {
1520
- /** @returns the current immutable snapshot, including undefined for an absent value. */
1521
- get(): VolatileSnapshot<T>;
1522
- }
1523
- //#endregion
1524
- //#region ../../../node_modules/.pnpm/@standard-schema+spec@1.1.0/node_modules/@standard-schema/spec/dist/index.d.ts
1525
- /** The Standard Typed interface. This is a base type extended by other specs. */
1526
- interface StandardTypedV1<Input = unknown, Output = Input> {
1527
- /** The Standard properties. */
1528
- readonly "~standard": StandardTypedV1.Props<Input, Output>;
1529
- }
1530
- declare namespace StandardTypedV1 {
1531
- /** The Standard Typed properties interface. */
1532
- interface Props<Input = unknown, Output = Input> {
1533
- /** The version number of the standard. */
1534
- readonly version: 1;
1535
- /** The vendor name of the schema library. */
1536
- readonly vendor: string;
1537
- /** Inferred types associated with the schema. */
1538
- readonly types?: Types<Input, Output> | undefined;
1539
- }
1540
- /** The Standard Typed types interface. */
1541
- interface Types<Input = unknown, Output = Input> {
1542
- /** The input type of the schema. */
1543
- readonly input: Input;
1544
- /** The output type of the schema. */
1545
- readonly output: Output;
1546
- }
1547
- /** Infers the input type of a Standard Typed. */
1548
- type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
1549
- /** Infers the output type of a Standard Typed. */
1550
- type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
1551
- }
1552
- /** The Standard Schema interface. */
1553
- interface StandardSchemaV1<Input = unknown, Output = Input> {
1554
- /** The Standard Schema properties. */
1555
- readonly "~standard": StandardSchemaV1.Props<Input, Output>;
1556
- }
1557
- declare namespace StandardSchemaV1 {
1558
- /** The Standard Schema properties interface. */
1559
- interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
1560
- /** Validates unknown input values. */
1561
- readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => Result<Output> | Promise<Result<Output>>;
1562
- }
1563
- /** The result interface of the validate function. */
1564
- type Result<Output> = SuccessResult<Output> | FailureResult;
1565
- /** The result interface if validation succeeds. */
1566
- interface SuccessResult<Output> {
1567
- /** The typed output value. */
1568
- readonly value: Output;
1569
- /** A falsy value for `issues` indicates success. */
1570
- readonly issues?: undefined;
1571
- }
1572
- interface Options {
1573
- /** Explicit support for additional vendor-specific parameters, if needed. */
1574
- readonly libraryOptions?: Record<string, unknown> | undefined;
1575
- }
1576
- /** The result interface if validation fails. */
1577
- interface FailureResult {
1578
- /** The issues of failed validation. */
1579
- readonly issues: ReadonlyArray<Issue>;
1580
- }
1581
- /** The issue interface of the failure output. */
1582
- interface Issue {
1583
- /** The error message of the issue. */
1584
- readonly message: string;
1585
- /** The path of the issue, if any. */
1586
- readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
1587
- }
1588
- /** The path segment interface of the issue. */
1589
- interface PathSegment {
1590
- /** The key representing a path segment. */
1591
- readonly key: PropertyKey;
1592
- }
1593
- /** The Standard types interface. */
1594
- interface Types<Input = unknown, Output = Input> extends StandardTypedV1.Types<Input, Output> {}
1595
- /** Infers the input type of a Standard. */
1596
- type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
1597
- /** Infers the output type of a Standard. */
1598
- type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
1599
- }
1600
- //#endregion
1601
- //#region ../../../vendor/deepseek-harness/vendor/schemastery/lib/types/index.d.ts
1602
- declare const kSchema: unique symbol;
1603
- declare global {
1604
- namespace Schemastery {
1605
- /** Convert primitive constructors, constants, and existing schemas into a schema type. */
1606
- type From<X> = X extends string | number | boolean ? Schema<X> : X extends Schema<any, any, SchemaMode> ? X : X extends typeof String ? Schema<string> : X extends typeof Number ? Schema<number> : X extends typeof Boolean ? Schema<boolean> : X extends typeof Function ? Schema<Function, (...args: any[]) => any> : X extends Constructor<infer S> ? Schema<S> : never;
1607
- type TypeS1<X> = X extends Schema<infer S, infer _T, infer _M> ? S : never;
1608
- type Inverse<X> = X extends Schema<infer _S, infer T, infer M> ? (arg: SchemaOutput<T, M>) => void : never;
1609
- /** Input type accepted by a schema-like value. */
1610
- type TypeS<X> = TypeS1<From<X>>;
1611
- /** Output type returned by a schema-like value after validation. */
1612
- type TypeT<X> = ReturnType<From<X>>;
1613
- /** Resolver callback used by custom schema types registered with `Schema.extend()`. */
1614
- type Resolve = (data: any, schema: Schema, options: Options, strict?: boolean) => [any, any?];
1615
- /** Input type accepted by one schema in an intersection. */
1616
- type IntersectS<X> = From<X> extends Schema<infer S, infer _T, infer _M> ? S : never;
1617
- /** Output type returned by one schema in an intersection. */
1618
- type IntersectT<X> = Inverse<From<X>> extends ((arg: infer T) => void) ? T : never;
1619
- type TupleS<X extends readonly any[]> = X extends readonly [infer L, ...infer R] ? [TypeS<L>?, ...TupleS<R>] : any[];
1620
- type TupleT<X extends readonly any[]> = X extends readonly [infer L, ...infer R] ? [TypeT<L>?, ...TupleT<R>] : any[];
1621
- type ObjectS<X extends Dict> = { [K in keyof X]?: TypeS<X[K]> | null; } & Dict;
1622
- type ObjectT<X extends Dict> = { [K in keyof X]: TypeT<X[K]>; } & Dict;
1623
- type Constructor<T = any> = new (...args: any[]) => T;
1624
- /** Static constructor and factory methods exposed by the default `Schema` export. */
1625
- interface Static {
1626
- <T = any>(options: Partial<Schema<T>>): Schema<T>;
1627
- new <T = any>(options: Partial<Schema<T>>): Schema<T>;
1628
- prototype: Schema;
1629
- /** Validate a value against a schema node and return `[output, adaptedInput?]`. */
1630
- resolve: Resolve;
1631
- /** Infer a schema from a primitive value, constructor, or existing schema. */
1632
- from<X = any>(source?: X): From<X>;
1633
- /** Register a resolver for a custom schema `type`. */
1634
- extend(type: string, resolve: Resolve): void;
1635
- /** Accept any value without validation. */
1636
- any<T = any>(): Schema<T>;
1637
- /** Accept only nullable input. */
1638
- never(): Schema<never>;
1639
- /** Accept exactly one constant value. */
1640
- const<const T>(value: T): Schema<T>;
1641
- /** Accept strings, with optional metadata constraints added by instance methods. */
1642
- string(): Schema<string>;
1643
- /** Accept numbers, with optional range and step constraints. */
1644
- number(): Schema<number>;
1645
- /** Accept non-negative integer numbers. */
1646
- natural(): Schema<number>;
1647
- /** Accept a number between 0 and 1 and mark it as a slider. */
1648
- percent(): Schema<number>;
1649
- /** Accept booleans. */
1650
- boolean(): Schema<boolean>;
1651
- /** Accept `Date` instances or parse datetime strings into `Date` objects. */
1652
- date(): Schema<string | Date, Date>;
1653
- /** Accept `RegExp` instances or parse strings into regular expressions. */
1654
- regExp(flag?: string): Schema<string | RegExp, RegExp>;
1655
- /** Accept binary sources and normalize them to `ArrayBufferLike`. */
1656
- arrayBuffer(): Schema<Binary.Source, ArrayBufferLike>;
1657
- arrayBuffer(encoding: 'hex' | 'base64'): Schema<Binary.Source | string, ArrayBufferLike>;
1658
- /** Accept a numeric bitset or string keys and normalize to a number. */
1659
- bitset<K extends string>(bits: Partial<Record<K, number>>): Schema<number | readonly K[], number>;
1660
- /** Accept functions. */
1661
- function(): Schema<Function, (...args: any[]) => any>;
1662
- /** Accept instances of a constructor or objects whose constructor name matches. */
1663
- is(constructor: string): Schema;
1664
- is<T>(constructor: Constructor<T>): Schema<T>;
1665
- /** Accept arrays whose elements match `inner`. */
1666
- array<X>(inner: X): Schema<TypeS<X>[], TypeT<X>[]>;
1667
- /** Accept plain objects with values matching `inner` and optional key schema. */
1668
- dict<X, Y extends Schema<any, string> = Schema<string>>(inner: X, sKey?: Y): Schema<Dict<TypeS<X>, TypeS<Y>>, Dict<TypeT<X>, TypeT<Y>>>;
1669
- /** Accept tuple arrays where each index matches the corresponding schema. */
1670
- tuple<const X extends readonly any[]>(list: X): Schema<TupleS<X>, TupleT<X>>;
1671
- /** Accept plain objects; infer fields from the dictionary, not the enclosing schema's output type. */
1672
- object<X extends Dict>(dict: X): Schema<ObjectS<NoInfer<X>>, ObjectT<NoInfer<X>>>;
1673
- /** Accept values matching at least one schema in `list`. */
1674
- union<const X>(list: readonly X[]): Schema<TypeS<X>, TypeT<X>>;
1675
- /** Accept values matching every schema in `list`, merging object outputs. */
1676
- intersect<const X>(list: readonly X[]): Schema<IntersectS<X>, IntersectT<X>>;
1677
- /** Validate with `inner`, then convert the result with `callback`. */
1678
- transform<X, T>(inner: X, callback: (value: TypeS<X>, options: Schemastery.Options) => T, preserve?: boolean): Schema<TypeS<X>, T>;
1679
- /** Defer construction of a recursive schema until validation or serialization. */
1680
- lazy<X extends Schema<any, any, SchemaMode>>(callback: () => X): X;
1681
- ValidationError: typeof ValidationError;
1682
- }
1683
- /** Runtime validation options shared by all schema calls. */
1684
- interface Options {
1685
- /** Remove invalid object properties instead of throwing when possible. */
1686
- autofix?: boolean;
1687
- /** Skip validation for selected values and schema nodes. */
1688
- ignore?(data: any, schema: Schema): boolean;
1689
- /** Path used to format nested validation errors. */
1690
- path?: (keyof any)[];
1691
- }
1692
- /** UI and validation metadata attached by schema builder methods. */
1693
- interface Meta<T = any> {
1694
- default?: T extends {} ? Partial<T> : T;
1695
- required?: boolean;
1696
- /** Parse this node as a stable config reference; its type and UI metadata remain unchanged. */
1697
- volatile?: boolean;
1698
- disabled?: boolean;
1699
- collapse?: boolean;
1700
- badges?: {
1701
- text: string;
1702
- type: string;
1703
- }[];
1704
- hidden?: boolean;
1705
- loose?: boolean;
1706
- role?: string;
1707
- extra?: any;
1708
- link?: string;
1709
- description?: string | Dict<string>;
1710
- comment?: string;
1711
- pattern?: {
1712
- source: string;
1713
- flags?: string;
1714
- };
1715
- max?: number;
1716
- min?: number;
1717
- step?: number;
1718
- }
1719
- }
1720
- /** Callable schema instance that validates input and returns normalized output. */
1721
- interface Schemastery<S = any, T = S, Mode extends SchemaMode = 'plain'> {
1722
- (data?: S | null, options?: Schemastery.Options): SchemaOutput<T, Mode>;
1723
- new (data?: S | null, options?: Schemastery.Options): SchemaOutput<T, Mode>;
1724
- [kSchema]: true;
1725
- uid: number;
1726
- meta: Schemastery.Meta<T>;
1727
- type: string;
1728
- sKey?: Schema;
1729
- inner?: Schema;
1730
- list?: Schema[];
1731
- dict?: Dict<Schema>;
1732
- bits?: Dict<number>;
1733
- callback?: Function;
1734
- constructor?: string | Function;
1735
- builder?: Function;
1736
- value?: T;
1737
- refs?: Dict<Schema>;
1738
- preserve?: boolean;
1739
- '~standard': StandardSchemaV1.Props;
1740
- /** Format this schema as a compact TypeScript-like type string. */
1741
- toString(inline?: boolean): string;
1742
- /** Serialize this schema, preserving shared and recursive references. */
1743
- toJSON(): Schema<S, T, Mode>;
1744
- /** Mark nullable input as invalid unless a default supplies a fallback. */
1745
- required<R extends boolean = true>(value?: R): Schema<S, T, SetRequired<Mode, R>>;
1746
- /**
1747
- * Parse this config field as a stable reference containing immutable data.
1748
- * @returns a schema whose output supports get(), including when the field is absent.
1749
- */
1750
- volatile(): Schema<NoInfer<S>, NoInfer<T>, Mode extends 'defined' | 'volatile-defined' ? 'volatile-defined' : 'volatile'>;
1751
- /** Hide this schema node from UI renderers. */
1752
- hidden(value?: boolean): Schema<S, T, Mode>;
1753
- /** Return the default value instead of throwing when validation fails. */
1754
- loose(value?: boolean): Schema<S, T, Mode>;
1755
- /** Attach a renderer role and optional role-specific metadata. */
1756
- role(text: string, extra?: any): Schema<S, T, Mode>;
1757
- /** Attach an external documentation link. */
1758
- link(link: string): Schema<S, T, Mode>;
1759
- /** Set the fallback value used for nullable input. */
1760
- default(value: T | NoInfer<Partial<S>>): Schema<S, T, SetRequired<Mode, true>>;
1761
- /** Attach an auxiliary comment for documentation or form UIs. */
1762
- comment(text: string): Schema<S, T, Mode>;
1763
- /** Attach a localized or plain description for documentation or form UIs. */
1764
- description(text: string): Schema<S, T, Mode>;
1765
- /** Mark this schema node as disabled for form UIs. */
1766
- disabled(value?: boolean): Schema<S, T, Mode>;
1767
- /** Request collapsed rendering for nested form UIs. */
1768
- collapse(value?: boolean): Schema<S, T, Mode>;
1769
- /** Add a deprecated badge to this schema node. */
1770
- deprecated(): Schema<S, T, Mode>;
1771
- /** Add an experimental badge to this schema node. */
1772
- experimental(): Schema<S, T, Mode>;
1773
- /** Require strings to match a regular expression. */
1774
- pattern(regexp: RegExp): Schema<S, T, Mode>;
1775
- /** Set an inclusive maximum for numbers or collection lengths. */
1776
- max(value: number): Schema<S, T, Mode>;
1777
- /** Set an inclusive minimum for numbers or collection lengths. */
1778
- min(value: number): Schema<S, T, Mode>;
1779
- /** Set the numeric increment constraint. */
1780
- step(value: number): Schema<S, T, Mode>;
1781
- /** Add or replace an object property schema. */
1782
- set(key: string, value: Schema): Schema<S, T, Mode>;
1783
- /** Append a tuple, union, or intersection member schema. */
1784
- push(value: Schema): Schema<S, T, Mode>;
1785
- /** Remove values equal to schema defaults from normalized output. */
1786
- simplify(value?: any): any;
1787
- /** Return a schema clone with descriptions merged from locale messages. */
1788
- i18n(messages: Dict): Schema<S, T, Mode>;
1789
- /** Attach arbitrary metadata consumed by form renderers and downstream tools. */
1790
- extra<K extends keyof Schemastery.Meta>(key: K, value: Schemastery.Meta[K]): Schema<S, T, Mode>;
1791
- }
1792
- }
1793
- declare class ValidationError extends TypeError {
1794
- options: Schemastery.Options;
1795
- name: string;
1796
- constructor(message: string, options: Schemastery.Options);
1797
- static is(error: any): error is ValidationError;
1798
- }
1799
- type SchemaMode = 'plain' | 'defined' | 'volatile' | 'volatile-defined';
1800
- type SchemaOutput<T, M extends SchemaMode> = M extends 'volatile' ? Volatile<T | undefined> : M extends 'volatile-defined' ? Volatile<T> : T;
1801
- type SetRequired<M extends SchemaMode, R extends boolean> = M extends 'volatile' | 'volatile-defined' ? R extends true ? 'volatile-defined' : 'volatile' : R extends true ? 'defined' : 'plain';
1802
- type Schema<S = any, T = S, Mode extends SchemaMode = 'plain'> = Schemastery<S, T, Mode>;
1803
- declare const Schema: Schemastery.Static;
1804
- //#endregion
1805
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/retry-policy.d.ts
1806
- /** Fully resolved backoff shared by both retry modes. */
1807
- interface ResolvedRetryBackoff {
1808
- readonly initialDelayMs: number;
1809
- readonly maxDelayMs: number;
1810
- readonly jitterRatio: number;
1811
- }
1812
- /** Fully resolved bounded transient retry policy. */
1813
- interface ResolvedNormalRetryPolicy extends ResolvedRetryBackoff {
1814
- readonly mode: 'normal';
1815
- readonly maxRetries: number;
1816
- readonly retryableCodes: readonly string[];
1817
- }
1818
- /** Fully resolved unbounded retry policy. */
1819
- interface ResolvedAlwaysRetryPolicy extends ResolvedRetryBackoff {
1820
- readonly mode: 'always';
1821
- }
1822
- /** Immutable provider policy captured when its adapter route is registered. */
1823
- type ResolvedRetryPolicy = ResolvedNormalRetryPolicy | ResolvedAlwaysRetryPolicy;
1824
- //#endregion
1825
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/call-config.d.ts
1826
- /**
1827
- * Provider, model, reasoning effort, and sampling scalars of one conversation's
1828
- * requests. Every field maps 1:1 onto the same-named `GenerateOptions` field;
1829
- * the loop builds requests from the logged header rather than accepting these
1830
- * per call.
1831
- */
1832
- interface LlmCallConfig {
1833
- provider: string;
1834
- model: string;
1835
- reasoningEffort?: ReasoningEffortId;
1836
- temperature?: number;
1837
- maxTokens?: number;
1838
- stop?: string[];
1839
- }
1840
- /**
1841
- * Effective config fields supplied by exact-model adapter resolution rather
1842
- * than by the caller's request proposal.
1843
- */
1844
- interface LlmCallConfigAdapterDefaults {
1845
- reasoningEffort?: true;
1846
- maxTokens?: true;
1847
- }
1848
- //#endregion
1849
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/assistant-stream.d.ts
1850
- /** Lossless compact records embedded in durable Assistant attempt events. */
1851
- type AssistantStreamRecord = {
1852
- readonly type: 'text-chunks';
1853
- readonly time0: number;
1854
- readonly index: number;
1855
- readonly dt: readonly number[];
1856
- readonly texts: readonly string[];
1857
- } | {
1858
- readonly type: 'reasoning-chunks';
1859
- readonly time0: number;
1860
- readonly index: number;
1861
- readonly dt: readonly number[];
1862
- readonly texts: readonly string[];
1863
- } | {
1864
- readonly type: 'tool-call-chunks';
1865
- readonly time0: number;
1866
- readonly index: number;
1867
- readonly dt: readonly number[];
1868
- readonly id: ToolCallId;
1869
- readonly name?: string;
1870
- readonly args: readonly string[];
1871
- } | {
1872
- readonly type: 'chunk';
1873
- readonly time: number;
1874
- readonly chunk: StreamChunk;
1875
- };
1876
- //#endregion
1877
- //#region ../../../vendor/deepseek-harness/packages/llm/llm/lib/types/index.d.ts
1878
- declare module '@deepseek-ai/cordis' {
1879
- interface Context {
1880
- llm: LlmRuntime;
1881
- }
1882
- interface Events {
1883
- /**
1884
- * Waterfall around every streaming model call (retry, replay, routing).
1885
- * Bound to the {@link LlmRuntime}; call `next()` to reach the resolved
1886
- * adapter's stream, or yield your own chunks to short-circuit.
1887
- * @param options - the full request. A LOOP-built request carries the
1888
- * process-local {@link markAgentLoopRequest} identity and arrives deep-frozen
1889
- * (mutation throws): its content is a pure function of the session log (the
1890
- * reconstructability Agent Note), so listeners read it, never rewrite it.
1891
- * Hand-built calls do not carry that marker; callers own their request
1892
- * inputs and must keep them unchanged until the stream settles.
1893
- * @mode waterfall
1894
- */
1895
- 'llm/stream'(this: LlmRuntime, options: GenerateOptions, next: () => AsyncIterable<StreamChunk>): AsyncIterable<StreamChunk>;
1896
- }
1897
- }
1898
- /** One model call whose config and adapter registration were resolved together. */
1899
- interface PreparedLlmCall {
1900
- /** Detached, deep-frozen config with any adapter-owned default materialized. */
1901
- readonly config: LlmCallConfig;
1902
- /** Immutable retry policy captured with the adapter registration. */
1903
- readonly retryPolicy: ResolvedRetryPolicy;
1904
- /** Detached context metadata resolved with the registration-bound call. */
1905
- readonly context?: LlmModelContext;
1906
- /** Exact model modalities captured with the adapter dispatch generation. */
1907
- readonly inputModalities?: readonly ModelModality[];
1908
- /** Exact model system prompt update mode captured with the adapter dispatch generation. */
1909
- readonly systemPromptUpdate?: SystemPromptUpdate;
1910
- /** Exact model tool update mode captured with the adapter dispatch generation. */
1911
- readonly toolUpdate?: ToolUpdate;
1912
- /** Config fields materialized by the captured adapter rather than proposed by the caller. */
1913
- readonly adapterDefaults: LlmCallConfigAdapterDefaults;
1914
- /**
1915
- * Dispatch this call once through the registration captured during
1916
- * preparation. The request's call-config fields must match {@link config};
1917
- * reuse or mismatch fails with `INVALID_PREPARED_CALL`.
1918
- * @param options - fully assembled request carrying the prepared config.
1919
- * @returns the chunk stream, including the `llm/stream` waterfall.
1920
- */
1921
- stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
1922
- }
1923
- /** One adapter-owned model-resolution generation bound to its eventual stream call. */
1924
- interface PreparedAdapterCall {
1925
- /** Exact model metadata from the same adapter generation as {@link stream}. */
1926
- readonly model: LlmResolvedModelInfo;
1927
- /** Dispatch through that generation without re-reading dynamic connection facts. */
1928
- stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
1929
- }
1930
- /**
1931
- * Provider-wire adapter for the harness message and stream vocabulary. Register implementations
1932
- * with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include
1933
- * `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch
1934
- * DeepSeek and library-backed pi-ai adapters meet this contract through different internals.
1935
- */
1936
- declare abstract class LlmAdapter {
1937
- /**
1938
- * Describe one provider route owned by this adapter.
1939
- * @param provider - a route passed to `registerAdapter()` for this instance.
1940
- * @returns detached display metadata whose id must equal `provider`.
1941
- */
1942
- providerInfo(provider: string): LlmProviderInfo;
1943
- /**
1944
- * Return the provider-owned retry policy captured with this route.
1945
- * @param _provider - a route passed to `registerAdapter()` for this instance.
1946
- * @returns a resolved policy, or `undefined` to use the normal defaults.
1947
- */
1948
- providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined;
1949
- /**
1950
- * Resolve provider-side request-image pricing for one exact model route.
1951
- * The default declares none, so consumers fall back to their own neutral
1952
- * estimate. Implementations must answer synchronously without I/O; the
1953
- * token meter resolves this per measurement.
1954
- * @param _provider - a route passed to `registerAdapter()` for this instance.
1955
- * @param _model - exact model id passed to {@link GenerateOptions.model}.
1956
- * @returns route-owned image pricing, or `undefined` when the route declares none.
1957
- */
1958
- imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined;
1959
- /**
1960
- * List models this adapter can currently advertise for one owned provider.
1961
- * Core routing accepts unlisted model ids; catalog-driven entry points such
1962
- * as the GUI may require membership. Adapters used there must advertise
1963
- * their available models; the base empty catalog offers no GUI selection.
1964
- * @param _provider - one provider route owned by this adapter.
1965
- * @returns discoverable models in adapter-preferred order.
1966
- */
1967
- listModels(_provider: string): Promise<readonly LlmModelInfo[]>;
1968
- /**
1969
- * Resolve all metadata available for one exact model. This query is
1970
- * independent of the advisory catalog and does not validate request routing.
1971
- * @param provider - one provider route owned by this adapter.
1972
- * @param model - exact model id passed to {@link GenerateOptions.model}.
1973
- * @param _signal - cancellation for this exact-model lookup; asynchronous
1974
- * implementations must settle promptly after it aborts.
1975
- * @returns provider/model identity plus any context, call-default, and reasoning metadata.
1976
- */
1977
- resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise<LlmResolvedModelInfo>;
1978
- /**
1979
- * Bind exact model metadata and the eventual request dispatch to one adapter generation.
1980
- * Dynamic adapters override this so settings changes between preparation and
1981
- * dispatch cannot combine one generation's capabilities with another's endpoint.
1982
- * @param provider - registered provider route.
1983
- * @param model - exact model id.
1984
- * @param signal - cancellation for model resolution.
1985
- * @returns model metadata and a one-generation stream entry point.
1986
- */
1987
- prepareCall(provider: string, model: string, signal?: AbortSignal): Promise<PreparedAdapterCall>;
1988
- /**
1989
- * Stream one model call as raw chunks. The only required method.
1990
- * @param options - the fully-assembled request; implementations must honor `options.signal`.
1991
- * @returns the chunk stream, obeying the adapter contract documented on `StreamChunk`.
1992
- */
1993
- abstract stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
1994
- }
1995
- /**
1996
- * What {@link LlmRuntime.registerAdapter} returns: the disposer, plus an
1997
- * atomic route replacement for the same adapter instance.
1998
- */
1999
- interface AdapterRegistrationHandle {
2000
- /** Release every route this registration currently holds. */
2001
- (): void;
2002
- /**
2003
- * Replace this registration's routes with `providers`, keeping the same
2004
- * adapter instance. The candidate set is validated in full first — a
2005
- * conflict with another adapter, an invalid name, or bad provider metadata
2006
- * throws and leaves the current routes untouched — and the swap itself is
2007
- * one synchronous section, so no request can observe a gap. An empty array
2008
- * is legal here (a settings section that emptied holds zero routes while
2009
- * staying registered), unlike an empty initial registration.
2010
- *
2011
- * Throws `LlmError` with code `REGISTRATION_DISPOSED` once the registration
2012
- * has been released: its routes are gone and its disposer has already run,
2013
- * so anything registered afterwards would have no owner left to release it.
2014
- * @param providers - the complete next route set for this registration.
2015
- */
2016
- replace(providers: string[]): void;
2017
- }
2018
- /**
2019
- * A live configurable-provider registration, disposable and atomically
2020
- * replaceable — the directory counterpart of {@link AdapterRegistrationHandle}.
2021
- */
2022
- interface DirectoryRegistrationHandle {
2023
- /** Withdraw every entry this registration currently holds. */
2024
- (): void;
2025
- /**
2026
- * Replace this registration's entries with `entries`. The candidate set is
2027
- * validated in full first — an entry another registration already declares,
2028
- * a duplicate within the set, or invalid metadata throws and leaves the
2029
- * current entries untouched — and the swap is one synchronous section, so no
2030
- * reader observes a gap. An empty array is legal here, unlike an empty
2031
- * initial registration.
2032
- *
2033
- * Throws `LlmError` with code `REGISTRATION_DISPOSED` once the registration
2034
- * has been disposed.
2035
- */
2036
- replace(entries: readonly LlmConfigurableProvider[]): void;
2037
- }
2038
- /**
2039
- * The abstract `llm` service: an adapter registry plus a streaming model-call
2040
- * API, interceptable via the `llm/stream` waterfall.
2041
- */
2042
- declare class LlmRuntime extends TypertRemoteService {
2043
- private adapters;
2044
- private directory;
2045
- private discoveries;
2046
- constructor(ctx: Context);
2047
- /** Notify topology observers without letting one broken listener veto the commit. */
2048
- private emitAdaptersUpdated;
2049
- /** Contained-listener diagnostic shared by the sync and async failure paths. */
2050
- private warnAdaptersListenerFailure;
2051
- /**
2052
- * Register an adapter for the given provider routes. Throws `LlmError` with code
2053
- * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing).
2054
- * Disposed with the fiber.
2055
- * @param providers - every provider route this adapter should serve.
2056
- * @param adapter - the adapter that streams calls for those providers.
2057
- * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}.
2058
- */
2059
- registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle;
2060
- /**
2061
- * Validate one candidate route set for `adapter`, treating routes this
2062
- * registration already holds as available. Nothing is mutated: a rejected
2063
- * candidate leaves the registry exactly as it was.
2064
- */
2065
- private prepareRoutes;
2066
- /**
2067
- * Swap this registration's routes for the prepared ones in one synchronous
2068
- * section, so no observer can see the registry between the release and the
2069
- * re-registration. The route set's one mutation point is also where
2070
- * `llm/adapters-updated` is published, so a `replace` announces itself
2071
- * exactly like a first registration.
2072
- */
2073
- private commitRoutes;
2074
- /**
2075
- * Describe provider routes with a registered adapter.
2076
- * @returns detached provider metadata in registration order.
2077
- */
2078
- listProviders(): LlmProviderInfo[];
2079
- /**
2080
- * Declare provider routes an adapter plugin can activate through
2081
- * configuration. Registration is all-or-nothing: an empty list, invalid
2082
- * entry, or a provider already declared by any registration throws
2083
- * `LlmError` without registering the rest. Disposed with the fiber.
2084
- * @param entries - every configurable provider this plugin owns.
2085
- * @returns a handle that withdraws all of them, and can atomically replace them.
2086
- */
2087
- registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle;
2088
- /**
2089
- * List every declared configurable provider, registered or dormant.
2090
- * @returns detached directory entries in declaration order.
2091
- */
2092
- listConfigurableProviders(): LlmConfigurableProvider[];
2093
- /**
2094
- * Offer to interrogate provider endpoints on behalf of the settings
2095
- * namespace this plugin owns. The namespace is the key because that is what
2096
- * a configuration surface already holds from the configurable-provider
2097
- * directory, and because a provider being *added* has no route to name yet.
2098
- * Disposed with the fiber.
2099
- * @param settingsNs - the namespace whose profiles this discovery serves.
2100
- * @param discover - interrogates one endpoint and must honor the supplied signal.
2101
- * @returns the disposer that withdraws the offer.
2102
- */
2103
- registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise<readonly LlmDiscoveredModel[]>): () => void;
2104
- /**
2105
- * Interrogate one provider endpoint for the models it advertises. The
2106
- * request describes a draft, not a stored route, so nothing here reads or
2107
- * writes settings or credentials — the caller owns both, and the reply is
2108
- * candidate metadata a surface may offer for adoption.
2109
- * @param settingsNs - namespace whose registered discovery serves this draft.
2110
- * @param request - the endpoint, protocol, and one-shot credential to use.
2111
- * @param signal - caller cancellation.
2112
- * @returns the advertised models, deduplicated in endpoint order.
2113
- */
2114
- discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise<LlmDiscoveredModel[]>;
2115
- /**
2116
- * Remote adapter for one draft provider interrogation.
2117
- * @param settingsNs - namespace whose registered discovery serves this draft.
2118
- * @param request - endpoint, protocol, and one-shot credential to use.
2119
- * @param signal - caller cancellation supplied by the Remote carrier.
2120
- * @returns advertised models in endpoint order.
2121
- * @throws RemoteError with `llm/model-discovery-rejected` when discovery refuses or fails.
2122
- */
2123
- remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise<LlmDiscoveredModel[]>;
2124
- /**
2125
- * Resolve the retry policy captured when one provider route was registered.
2126
- * @param provider - registered provider route to inspect.
2127
- * @returns the provider-owned policy, with normal defaults already resolved.
2128
- */
2129
- providerRetryPolicy(provider: string): ResolvedRetryPolicy;
2130
- /**
2131
- * Resolve provider-side request-image pricing for one exact route, or
2132
- * `undefined` when the provider is unregistered or declares none. Unknown
2133
- * providers degrade to `undefined` rather than throwing because callers
2134
- * price durable history whose route may no longer be mounted.
2135
- * @param provider - provider route named by a request header.
2136
- * @param model - exact model id named by the same header.
2137
- * @returns the owning adapter's image pricing for the route, when declared.
2138
- */
2139
- imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined;
2140
- /**
2141
- * Resolve the exact text one durable file occurrence contributes to every
2142
- * provider request in the current execution environment.
2143
- * @param ref - durable verbatim file reference from model history.
2144
- * @returns the same deterministic handle text used at adapter dispatch.
2145
- */
2146
- fileRequestText(ref: FileAttachmentRef): string;
2147
- /** Detach typed adapter-owned modality metadata. */
2148
- private detachedModalities;
2149
- /**
2150
- * Discover models advertised by one registered provider. Catalog membership
2151
- * does not constrain core routing. Catalog-driven entry points may restrict
2152
- * selection and submission to the advertised models.
2153
- * @param provider - registered provider route to inspect.
2154
- * @returns detached model metadata in adapter-preferred order.
2155
- */
2156
- listModels(provider: string): Promise<LlmModelInfo[]>;
2157
- /**
2158
- * Resolve and validate all metadata from the adapter that owns one exact
2159
- * route. The result is detached from adapter-owned objects; catalog
2160
- * membership remains advisory and does not control request routing.
2161
- * @param provider - registered provider route to inspect.
2162
- * @param model - exact model id passed to the adapter.
2163
- * @param signal - optional cancellation for adapter-owned asynchronous lookup.
2164
- * @returns exact model identity plus available context and reasoning metadata.
2165
- */
2166
- resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<LlmResolvedModelInfo>;
2167
- private resolveModelInfoFor;
2168
- /** Validate and detach one adapter-returned exact model result. */
2169
- private normalizeModelInfo;
2170
- /**
2171
- * Validate a conversation call config against its exact model capability and
2172
- * materialize adapter-configured defaults. Unsupported explicit efforts
2173
- * reject before provider I/O; no clamping or aliasing is performed. This
2174
- * standalone query does not bind a later dispatch; use {@link prepareCall}
2175
- * when logging and streaming must share one adapter registration.
2176
- * @param config - provider/model route and optional request controls.
2177
- * @param signal - optional cancellation for adapter-owned capability lookup.
2178
- * @returns a detached config only when a default must be materialized.
2179
- */
2180
- resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise<LlmCallConfig>;
2181
- private resolveCallFor;
2182
- /** Validate request controls against one already-bound exact model result. */
2183
- private resolveCallWithInfo;
2184
- /**
2185
- * Resolve one call under its current adapter registration. The returned
2186
- * one-shot handle keeps that registration across header logging and dispatch,
2187
- * so HMR cannot combine one adapter's capability result with another adapter.
2188
- * @param config - provider/model route and optional request controls.
2189
- * @param signal - optional cancellation for adapter-owned capability lookup.
2190
- * @returns a prepared config and its registration-bound stream entry point.
2191
- */
2192
- prepareCall(config: LlmCallConfig, signal?: AbortSignal): Promise<PreparedLlmCall>;
2193
- private registration;
2194
- /** Remove replay state whose historical route is owned by another adapter. */
2195
- private forAdapter;
2196
- /**
2197
- * Resolve the current execution-world read path of one durable file
2198
- * reference through the mounted attachment and filesystem providers.
2199
- */
2200
- private fileReadPath;
2201
- /**
2202
- * Final adapter boundary. Adapter selection, dispatch, iterator construction,
2203
- * and iteration failures become one terminal failure chunk. Middleware and
2204
- * downstream consumer failures remain thrown plugin or consumer errors.
2205
- */
2206
- private adapterStream;
2207
- /**
2208
- * Stream one model call as raw chunks (token-level deltas). Replay state is
2209
- * retained only when the same adapter instance owns its historical provider
2210
- * and the target provider. Final adapter selection remains fixed through
2211
- * asynchronous exact-model resolution and dispatch. Adapter selection,
2212
- * dispatch, and iteration failures become terminal `error` or `aborted`
2213
- * finish chunks; middleware, nested-call, cleanup, and consumer failures
2214
- * remain thrown.
2215
- * @param options - the full request; `options.provider` selects the adapter.
2216
- * @returns the chunk stream, possibly wrapped by `llm/stream` listeners.
2217
- */
2218
- stream(options: GenerateOptions): AsyncIterable<StreamChunk>;
2219
- private streamWithRegistration;
2220
- }
2221
- //#endregion
2222
- //#region ../../../vendor/deepseek-harness/packages/util/values/lib/types/index.d.ts
2223
- /** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */
2224
- /** A value that round-trips through JSON without loss. */
2225
- type JsonValue = null | boolean | number | string | JsonValue[] | {
2226
- [key: string]: JsonValue;
2227
- };
2228
- //#endregion
2229
- //#region ../../../vendor/deepseek-harness/packages/core/session/lib/types/types.d.ts
2230
- /** Identifies one session in the store (and its persistence artifacts). */
2231
- type SessionId = Branded<'SessionId'>;
2232
- /**
2233
- * Brand a string as a {@link SessionId}.
2234
- * @param id - the raw session id string.
2235
- * @returns the same string with the session-id brand.
2236
- */
2237
- declare function SessionId(id: string): SessionId;
2238
- /** Sequence number of one existing event in a Session log. */
2239
- type SessionSeq = BrandedNumber<'SessionSeq'>;
2240
- /**
2241
- * Admit a numeric value as an existing Session event position.
2242
- * @param value - non-negative safe integer admitted by the owning log operation.
2243
- * @returns the same number with the Session-sequence brand.
2244
- */
2245
- declare function SessionSeq(value: number): SessionSeq;
2246
- /** A Session log gap, prefix length, or read offset, which may equal the event count. */
2247
- type SessionLogOffset = BrandedNumber<'SessionLogOffset'>;
2248
- /**
2249
- * Admit a numeric value as a Session log offset.
2250
- * @param value - non-negative safe integer used as a gap or prefix length.
2251
- * @returns the same number with the Session-log-offset brand.
2252
- */
2253
- declare function SessionLogOffset(value: number): SessionLogOffset;
2254
- /**
2255
- * Current logical Session format version, stamped into every newly written
2256
- * {@link SessionHeader}. Current Session and persistence code accept only this
2257
- * value; header-only readers classify supported historical formats, while an
2258
- * event-body read composes the build-static adjacent chain and publishes only
2259
- * this final generation before constructing a Session.
2260
- *
2261
- * The version is a single monotonic integer with no major/minor split. Whether
2262
- * a bump is needed is decided by what the WRITER emits, never by what a newer
2263
- * reader can accept: bump exactly when an older runtime could no longer handle
2264
- * a new log with full semantic correctness ("parses without error" is not
2265
- * correctness — silently skipping content that shapes reconstruction is a
2266
- * wrong read). Only structural changes reach that bar: the header shape, the
2267
- * {@link SessionEvent} envelope, core event semantics, or the surface
2268
- * mechanism (the {@link SurfaceEventType} set and {@link SurfaceOp} variants).
2269
- * Adding an ordinary event type does not bump — the per-event
2270
- * {@link SessionEvent.ignorable} guard covers vocabulary growth instead. When
2271
- * in doubt, bump: a near-identity upgrade step is almost free, a missed bump
2272
- * makes older runtimes read new logs wrong silently. The released migration,
2273
- * immutable prior-generation, and current fast-path rules are recorded in
2274
- * `.agents/notes/implemented/architecture/2026-08-31-released-session-format-migrations.md`.
2275
- */
2276
- declare const SESSION_FORMAT_VERSION = 4;
2277
- /**
2278
- * Immutable validated storage metadata, kept outside the conversation event log.
2279
- */
2280
- interface SessionHeader {
2281
- /**
2282
- * Current logical format version, stamped from {@link SESSION_FORMAT_VERSION}.
2283
- * Historical physical headers are translated before entering this interface.
2284
- */
2285
- readonly version: typeof SESSION_FORMAT_VERSION;
2286
- /** The session's id (mirrors the {@link Session}'s id). */
2287
- readonly id: SessionId;
2288
- /** Non-negative safe-integer Unix epoch milliseconds when the session was created. */
2289
- readonly createdAt: number;
2290
- /** Absolute working directory the session was created in (if any). */
2291
- readonly cwd?: string;
2292
- /** The session this one was forked from (seed lineage), if any. */
2293
- readonly parentSession?: SessionId;
2294
- /**
2295
- * Whether this Session contains a fork-inherited event prefix. The exact prefix
2296
- * length is Session state rather than ordinary header metadata.
2297
- */
2298
- readonly isSeeded: boolean;
2299
- /**
2300
- * Coarse product classification for a session created as a subagent child.
2301
- * This is presentation metadata, not proof that the child is continuable.
2302
- */
2303
- readonly origin?: 'subagent';
2304
- /**
2305
- * Delegation depth: absent (zero) for a top-level session, parent depth + 1
2306
- * for a subagent child. Persisted so a recursion budget survives restart and
2307
- * resume — a runtime-only depth would reset a resumed child to top-level.
2308
- */
2309
- readonly delegationDepth?: number;
2310
- /**
2311
- * Id of the agent preset this session's agent was composed from, when the
2312
- * deployment composes per session. Durable because the preset decides the
2313
- * session's tools and prompt: a resume that restored a different composition
2314
- * would replay history the model can no longer act on.
2315
- */
2316
- readonly agentPreset?: string;
2317
- }
2318
- /**
2319
- * Options for creating a {@link Session} via the store. `seed` replays/forks
2320
- * an existing event log; `meta` carries the caller-supplied storage fields the
2321
- * store folds into a {@link SessionHeader}.
2322
- */
2323
- interface CreateSessionOptions {
2324
- /** Initial replay or fork history supplied at construction. */
2325
- readonly seed?: readonly SessionEvent[];
2326
- /**
2327
- * Exact fork-inherited prefix length when `meta.isSeeded` is true. The
2328
- * constructor appends the child-owned tagged marker at the cut unless
2329
- * the seed already includes it followed by child-owned fork closers.
2330
- */
2331
- readonly inheritedEventCount?: SessionLogOffset;
2332
- /**
2333
- * Storage metadata read once before publication. `isSeeded` marks fork
2334
- * lineage; supplying replay history alone does not make it inherited.
2335
- */
2336
- readonly meta?: {
2337
- readonly cwd?: string;
2338
- readonly parentSession?: SessionId;
2339
- readonly createdAt?: number;
2340
- readonly isSeeded?: boolean;
2341
- readonly origin?: 'subagent';
2342
- readonly delegationDepth?: number;
2343
- readonly agentPreset?: string;
2344
- };
2345
- }
2346
- /**
2347
- * Aliasing state of an adoptable Session seed. `shared-frozen` permits deeply
2348
- * frozen aliases plus independently owned unfrozen values in the same seed.
2349
- */
2350
- type SessionSeedEventState = 'detached' | 'shared-frozen';
2351
- /**
2352
- * Adoptable storage values transferred to {@link SessionStore.prepare}
2353
- * without another copy or freeze pass.
2354
- */
2355
- interface RestoredSessionOptions {
2356
- /** Events that are independently owned or already deeply frozen. */
2357
- readonly seed: SessionEvent[];
2358
- /** Independently owned storage metadata to validate and freeze in place. */
2359
- readonly meta: SessionHeader;
2360
- /** Exact number of fork-inherited leading events decoded from storage. */
2361
- readonly inheritedEventCount: SessionLogOffset;
2362
- /** Aliasing state carried from the operation that produced the seed. */
2363
- readonly eventState: SessionSeedEventState;
2364
- }
2365
- /** Inputs accepted while constructing an unpublished Session. */
2366
- type PrepareSessionOptions = (CreateSessionOptions & {
2367
- readonly eventState?: undefined;
2368
- }) | RestoredSessionOptions;
2369
- /** Why an active agent driver was cancelled. */
2370
- type AgentCancelCause = {
2371
- readonly kind: 'user';
2372
- } | {
2373
- readonly kind: 'parent';
2374
- } | {
2375
- readonly kind: 'hook';
2376
- readonly reason: string;
2377
- } | {
2378
- readonly kind: 'disposed';
2379
- };
2380
- /** Durable cancellation cause, including imports whose original coarse record carried no cause. */
2381
- type TurnEndCancelCause = AgentCancelCause | {
2382
- readonly kind: 'legacy';
2383
- };
2384
- /**
2385
- * Why a turn ended. Merge-extensible sum type.
2386
- */
2387
- interface TurnEndReasonMap {
2388
- completed: {
2389
- kind: 'completed';
2390
- };
2391
- /** A cancellation request interrupted the live turn. */
2392
- aborted: {
2393
- kind: 'aborted';
2394
- reason: TurnEndCancelCause;
2395
- };
2396
- blocked: {
2397
- kind: 'blocked';
2398
- };
2399
- /**
2400
- * The turn failed. `error` is always a structured failure: the `LlmError`
2401
- * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }`
2402
- * flattened from any other error.
2403
- */
2404
- error: {
2405
- kind: 'error';
2406
- error: LlmFailure;
2407
- };
2408
- /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */
2409
- 'max-tokens': {
2410
- kind: 'max-tokens';
2411
- };
2412
- /**
2413
- * A crash-orphaned turn was closed after the fact: agent-loop resume appends
2414
- * this closer for a stored log whose last turn never ended, and session-query
2415
- * synthesizes it on cold reads. The loop never emits this marker live, and
2416
- * the events recorded before the crash remain intact.
2417
- */
2418
- interrupted: {
2419
- kind: 'interrupted';
2420
- };
2421
- /**
2422
- * Fork-seed construction closed a turn that was still open at the fork
2423
- * boundary in the source session. Only fork seeds carry this marker — the
2424
- * loop never emits it — and the source events before the boundary remain
2425
- * intact in the child.
2426
- */
2427
- forked: {
2428
- kind: 'forked';
2429
- };
2430
- }
2431
- /** The union over {@link TurnEndReasonMap} — why a turn ended; plugins extend it by merging variants into the map. */
2432
- type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap];
2433
- /**
2434
- * Logged request state outside derived history: call config and tools. The
2435
- * system prompt is derived history — surface node 0, a `system/message` event.
2436
- * The latest full `request/header` snapshot reconstructs the header; canonical
2437
- * empty optional fields are absent.
2438
- */
2439
- interface EpochHeader {
2440
- /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */
2441
- config: LlmCallConfig;
2442
- /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */
2443
- adapterDefaults?: LlmCallConfigAdapterDefaults;
2444
- /** Assembled tool schemas; absent for a tool-less request. */
2445
- tools?: ToolSchema[];
2446
- /** Retired request text; system prompts belong to system/message events.
2447
- * @persistenceReserved
2448
- */
2449
- system?: never;
2450
- }
2451
- /** Registration-bound metadata for one resolved model route. */
2452
- interface RequestContext {
2453
- /** Registered provider route the metadata belongs to. */
2454
- provider: string;
2455
- /** Provider-owned model id the metadata belongs to. */
2456
- model: string;
2457
- /** Maximum combined request and response context in tokens, when advertised. */
2458
- contextWindow?: number;
2459
- /** `'in-history'` when the route reads the latest `system` message at any position as the effective system prompt. */
2460
- systemPromptUpdate?: SystemPromptUpdate;
2461
- }
2462
- /**
2463
- * Why a `request/header` snapshot was appended: `'initial'` — the log's first
2464
- * header (a new conversation); `'resume'` — a loop instance's first request
2465
- * over a log that already has header events (process restart, fork seed);
2466
- * `'change'` — a later request used a different header; `'series'` — an unchanged
2467
- * header began an explicitly distinct message series or followed a surface
2468
- * replacement. Other reasons carry `startsSeries` when a new series coincides.
2469
- */
2470
- type RequestHeaderReason = 'initial' | 'resume' | 'change' | 'series';
2471
- /**
2472
- * The merge-extensible, append-only source of truth for an agent interaction.
2473
- * Message history is derived from this log. Every event is lossless JSON and
2474
- * sequence numbers stay contiguous. Assistant attempt events embed their exact
2475
- * compact raw streams so persistence stores one durable settlement per attempt.
2476
- */
2477
- interface SessionEventMap {
2478
- /**
2479
- * Opens turn `turn` before the loop claims queued input or runs pre-step.
2480
- * Rejection, empty input, cancellation, or failure may close it with no
2481
- * step; otherwise the following identified `user/message` event or batch
2482
- * records the messages entering the step.
2483
- */
2484
- 'turn/start': {
2485
- turn: number;
2486
- };
2487
- /**
2488
- * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn
2489
- * with no entered step has no `step/start` or `step/end`. The loop does not await a
2490
- * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the
2491
- * per-request durability checkpoint, and consumers that read storage after
2492
- * `whenIdle()` flush themselves. Success commits the turn; rejection is
2493
- * reported live and does not prevent later work.
2494
- */
2495
- 'turn/end': {
2496
- turn: number;
2497
- reason: TurnEndReason;
2498
- };
2499
- /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */
2500
- 'step/start': {
2501
- turn: number;
2502
- step: number;
2503
- };
2504
- /** Closes step `step` of turn `turn`. */
2505
- 'step/end': {
2506
- turn: number;
2507
- step: number;
2508
- };
2509
- /**
2510
- * A user-role message on the model-visible surface: a direct human prompt
2511
- * (the queued message claimed for this turn), a synthetic `agent.inject()`
2512
- * context (file-change notices, subdir AGENTS.md, skill content, cron
2513
- * notifications, …), or an entered goal continuation round. All three
2514
- * project their `content` verbatim; `source` tells them apart.
2515
- */
2516
- 'user/message': UserMessage;
2517
- /** An incremental agent session change admitted at the named turn and step. */
2518
- 'developer/message': {
2519
- turn: number;
2520
- step: number;
2521
- message: DeveloperMessage;
2522
- /** Earlier request/header defining every tool addition; required exactly when additions are present. */
2523
- headerSeq?: SessionSeq;
2524
- };
2525
- /**
2526
- * The rendered system prompt on the model-visible surface. The loop appends
2527
- * the first one as surface node 0 before the step's first `user/message`.
2528
- * A prepared in-history route can append nonempty changes in a continuing
2529
- * series. An incapable route or new series normalizes text to the first system
2530
- * node. Normalization empties nonempty later nodes, then rewrites the head if
2531
- * needed, through logged per-node replacements. An empty rendering always
2532
- * clears all active system nodes, leaving no older instructions model-visible.
2533
- * Empty later nodes are dormant and project to no message; an empty head with
2534
- * no active later node records "no system prompt". Restored nonempty text follows
2535
- * the same route and series rule; empty nodes never restore older text.
2536
- */
2537
- 'system/message': {
2538
- turn: number;
2539
- step: number;
2540
- message: SystemMessage;
2541
- };
2542
- /**
2543
- * Assembled assistant message for one step (derived history uses this).
2544
- * Carries the step's `usage` when the adapter reported token accounting, so
2545
- * the model output and its accounting travel together (there is no separate
2546
- * usage record). `usage` is absent when the adapter reported none. A turn
2547
- * cancelled mid-stream finalizes its delivered text/reasoning prefix as this
2548
- * event with `interrupted: true`; undispatched tool calls are absent. The
2549
- * marker distinguishes that prefix without re-deriving interruption from turn
2550
- * boundaries. An aborted turn with no such event streamed no visible content.
2551
- */
2552
- 'assistant/message': {
2553
- turn: number;
2554
- step: number;
2555
- message: AssistantMessage;
2556
- /** Exact timed model stream, compacted without joining delta boundaries. */
2557
- stream: AssistantStreamRecord[];
2558
- usage?: TokenUsage;
2559
- interrupted?: true;
2560
- };
2561
- /**
2562
- * One model attempt that committed no surface message. The embedded stream
2563
- * preserves a failed, retried, cancelled, or stream-error attempt that
2564
- * reached settlement without fabricating model-visible history.
2565
- */
2566
- 'assistant/attempt': {
2567
- turn: number;
2568
- step: number;
2569
- stream: AssistantStreamRecord[];
2570
- };
2571
- /**
2572
- * The model requested one tool invocation: `name` with the raw `arguments`
2573
- * JSON string exactly as the model produced it (unparsed). `callId` pairs the
2574
- * call with its `tool/result`.
2575
- */
2576
- 'tool/call': {
2577
- turn: number;
2578
- step: number;
2579
- callId: ToolCallId;
2580
- name: string;
2581
- arguments: string;
2582
- };
2583
- /**
2584
- * A completed tool call's model-facing result, optional internal failure
2585
- * identity and user-facing reason, and optional tool-private `meta`
2586
- * presentation payload. The reason remains outside the model-facing message.
2587
- * `meta` is
2588
- * opaque to the core (the producing tool owns its shape and reads it back in
2589
- * `presentResult`) but MUST be JSON-serializable: `Session.append`
2590
- * runtime-validates all event data with `isJsonValue`, so a non-serializable
2591
- * `meta` is rejected at the source, and the durable log reproduces the
2592
- * identical card on replay. Absent
2593
- * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time
2594
- * contextual diff here).
2595
- */
2596
- 'tool/result': {
2597
- turn: number;
2598
- step: number;
2599
- message: ToolResultMessage;
2600
- /**
2601
- * Optional failure identity and raw user-facing reason, outside model content;
2602
- * allowed only when the message has `isError: true`.
2603
- */
2604
- error?: {
2605
- name: string;
2606
- code: string;
2607
- reason?: string;
2608
- };
2609
- meta?: JsonValue;
2610
- };
2611
- /**
2612
- * Full header for the next request, appended inside its step before dispatch.
2613
- * It is log-only; the latest snapshot reconstructs the request header.
2614
- */
2615
- 'request/header': {
2616
- header: EpochHeader;
2617
- reason: RequestHeaderReason;
2618
- /** This request begins a distinct model-message series, independently of the header reason. */
2619
- startsSeries?: true;
2620
- };
2621
- /**
2622
- * Route metadata for the next request, logged only when the route, capacity,
2623
- * or system prompt update mode changes. It does not participate in request
2624
- * reconstruction or header equality. Prompt admission uses the bound prepared
2625
- * call's capability, not this snapshot from an earlier request.
2626
- */
2627
- 'request/context': RequestContext;
2628
- /**
2629
- * Separates inherited or restored history from later lifecycle-owned work.
2630
- * This log-only marker need not be at {@link Session.firstLiveSeq}: a fork
2631
- * seed can already contain its tagged marker and child-owned synthetic
2632
- * closers before construction.
2633
- *
2634
- * A fresh fork child owns one `{ inherited: true }` marker at its exact
2635
- * inherited-prefix cut, even when that prefix ends in an ancestor marker.
2636
- * `buildForkSeed` appends that marker before any synthetic closers; the
2637
- * `Session` constructor supplies it when given only the inherited prefix.
2638
- * The last tagged marker is the current Session's cut; untagged markers
2639
- * keep ordinary restore and replay lifecycle boundaries.
2640
- *
2641
- * Only the `Session` constructor and `buildForkSeed` may create this marker.
2642
- * The invariant companion deliberately constrains nothing here, so a plugin
2643
- * appending one would silently classify every live bracket before it as seed history.
2644
- *
2645
- * An owner of a standalone open/close bracket (`compaction/start` …
2646
- * `compaction/end`) reads it because seed history and live work are otherwise
2647
- * byte-identical: an unmatched opening marker before this event belongs to
2648
- * an ended lifecycle, whatever ended it. NOT a liveness signal about other
2649
- * writers — a concurrently live session holds its own boundary elsewhere,
2650
- * so tolerating concurrent writers needs a signal beyond the log.
2651
- */
2652
- 'session/end-seed': {
2653
- inherited?: true;
2654
- };
2655
- }
2656
- /** The appendable event-type keys of {@link SessionEventMap}, plugin-merged extensions included. */
2657
- type SessionEventType = keyof SessionEventMap;
2658
- /**
2659
- * The subset of {@link SessionEventType} values whose events produce LLM
2660
- * messages and are eligible to appear on the ordered surface. Only these
2661
- * event types may carry {@link SurfaceOp}; system, user, and tool events may also cite
2662
- * earlier sources through {@link SessionEvent.sourceEventSeqs}.
2663
- */
2664
- type SurfaceEventType = 'system/message' | 'developer/message' | 'user/message' | 'assistant/message' | 'tool/result';
2665
- /**
2666
- * How a session event entered the ordered surface. Only valid on
2667
- * {@link SurfaceEventType} events.
2668
- *
2669
- * - `'append'`: added to the tail — normal path for user/assistant/tool
2670
- * messages.
2671
- * - `{ op: 'replace', startSeq, endSeq }`: replaces surface nodes from `startSeq`
2672
- * (inclusive) through `endSeq` (inclusive) with this node. Both must exist as
2673
- * surface nodes in the current surface. `startSeq === endSeq` replaces a single
2674
- * node. The node's {@link SessionEvent.sourceEventSeqs} must include every
2675
- * shadowed surface node. Used by compaction; any surface-replacing producer
2676
- * may use it.
2677
- */
2678
- type SurfaceOp = 'append' | {
2679
- op: 'replace';
2680
- startSeq: SessionSeq;
2681
- endSeq: SessionSeq;
2682
- };
2683
- /**
2684
- * Surface placement and cited source-event seqs for {@link Session.append}. Required on
2685
- * message-producing events and forbidden on log-only events.
2686
- */
2687
- type SurfaceIntent<T extends SurfaceEventType = SurfaceEventType> = {
2688
- surfaceOp: SurfaceOp;
2689
- } & (T extends 'assistant/message' ? {
2690
- /** Assistant messages embed their provider stream instead of citing source events. */
2691
- sourceEventSeqs?: never;
2692
- } : {
2693
- /** Complete non-empty set of known earlier source-event seqs. */
2694
- sourceEventSeqs?: SessionSeq[];
2695
- });
2696
- /**
2697
- * One immutable entry in the session log.
2698
- *
2699
- * A proper discriminated union over `type` (not independent `type`/`data`
2700
- * unions), so `switch (event.type)` narrows `event.data` without casts.
2701
- *
2702
- * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional:
2703
- * they only exist on {@link SurfaceEventType} variants (`system/message`, `user/message`,
2704
- * `assistant/message`, `tool/result`).
2705
- * Non-surface events (boundary markers, attempts, errors) never carry
2706
- * surface metadata — the compiler enforces this at `Session.append()`
2707
- * call sites.
2708
- */
2709
- type SessionEvent<T extends SessionEventType = SessionEventType> = { [K in SessionEventType]: {
2710
- type: K;
2711
- /** Monotonic sequence number within the session. */
2712
- seq: SessionSeq;
2713
- /** Unix epoch milliseconds. */
2714
- time: number;
2715
- data: SessionEventMap[K];
2716
- /**
2717
- * Marks an event a reader may safely skip when it does not recognize
2718
- * `type`. Absent means required: a reader meeting an unrecognized type
2719
- * without this marker MUST refuse to reconstruct the session instead of
2720
- * silently dropping the event, because an unrecognized required event may
2721
- * change how the rest of the log is interpreted. A writer sets `true` only
2722
- * on purely informational records whose loss cannot affect reconstruction;
2723
- * defaulting to required means a forgotten marker over-refuses (an
2724
- * inconvenience) rather than silently resuming a gutted session.
2725
- */
2726
- ignorable?: true;
2727
- } & (K extends SurfaceEventType ? SurfaceIntent<K> : {
2728
- surfaceOp?: never;
2729
- sourceEventSeqs?: never;
2730
- }); }[T];
2731
- declare module '@deepseek-ai/dsh-typert-protocol' {
2732
- interface RemoteErrorDetailsMap {
2733
- /** The named Session does not exist; produced by every layer that resolves a SessionId. */
2734
- 'session/not-found': {
2735
- readonly sessionId: SessionId;
2736
- };
2737
- }
2738
- }
2739
- //#endregion
2740
- //#region ../../../vendor/deepseek-harness/packages/core/session/lib/types/surface.d.ts
2741
- /** Readonly history immediately before a message-projection event. */
2742
- interface SessionMessageProjectionContext {
2743
- /** Current message-producing event sequences in model-visible order. */
2744
- nodes: readonly SessionSeq[];
2745
- /** Contiguous event window; entries at or beyond the candidate seq are not committed inputs. */
2746
- events: readonly SessionEvent[];
2747
- /** Absolute sequence of the window's first event. */
2748
- baseSeq: SessionLogOffset;
2749
- /** Previously projected messages keyed by their original event sequences. */
2750
- messages: ReadonlyMap<SessionSeq, Message>;
2751
- }
2752
- /** Pure interpretation of one plugin-owned event that changes existing message content. */
2753
- interface SessionMessageProjection<T extends SessionEventType = SessionEventType> {
2754
- /** Event interpreted by this definition; declare it with `@messageProjection` in SessionEventMap. */
2755
- type: T;
2756
- /**
2757
- * Validate the complete durable decision before returning any updates. Preserve
2758
- * message identities and publish immutable copies without mutating the input.
2759
- * @param event - candidate event, not yet applied to the supplied history.
2760
- * @param context - history preceding this decision.
2761
- * @returns changed current messages keyed by their original sequences.
2762
- * @throws when the durable decision cannot be applied to this history.
2763
- */
2764
- project(event: SessionEvent<T>, context: SessionMessageProjectionContext): ReadonlyMap<SessionSeq, Message>;
2765
- }
2766
- /** Readonly live projection of the message-producing session events. */
2767
- interface SessionSurface {
2768
- /** Current surface event sequences in model-visible order. */
2769
- readonly nodes: readonly SessionSeq[];
2770
- /** Monotonic count of committed positional replacements. */
2771
- readonly replaceGeneration: number;
2772
- /** Monotonic count of committed replacements and plugin-owned message changes. */
2773
- readonly contentGeneration: number;
2774
- }
2775
- //#endregion
2776
- //#region ../../../vendor/deepseek-harness/packages/core/session/lib/types/index.d.ts
2777
- declare module '@deepseek-ai/cordis' {
2778
- interface Context {
2779
- sessions: SessionStore;
2780
- }
2781
- interface Events {
2782
- /**
2783
- * Creation announcement during session publication. A synchronous throw vetoes and rolls
2784
- * back with a paired disposal; detach requested during dispatch is deferred.
2785
- * A returned-promise rejection is logged but cannot retroactively veto this
2786
- * synchronous boundary.
2787
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
2788
- * receive only sessions entered through that agent's context.
2789
- * @param session - the session just entered and announced.
2790
- * @dshScopeScan unsupported
2791
- * @mode emit
2792
- */
2793
- 'session/created'(this: Scoped<Session>, session: Session): void;
2794
- /**
2795
- * Emitted once when an announced session leaves the store, including
2796
- * publication rollback, but never for an entry whose creation announcement
2797
- * did not begin. Listener failures are logged and contained.
2798
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope.
2799
- * @param session - the session that is no longer live in the store.
2800
- * @dshScopeScan unsupported
2801
- * @mode emit
2802
- */
2803
- 'session/disposed'(this: Scoped<Session>, session: Session): void;
2804
- /**
2805
- * Post-commit, fire-and-forget append feed. The listener snapshot resolves
2806
- * before the log push, but callbacks run after it; observer failures are
2807
- * logged and contained without making the committed append fail.
2808
- * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners
2809
- * receive only events from sessions entered through that agent's context.
2810
- * @param session - the session whose log grew.
2811
- * @param event - the appended event, exactly as recorded.
2812
- * @dshScopeScan unsupported
2813
- * @mode emit
2814
- */
2815
- 'session/event'(this: Scoped<Session>, session: Session, event: SessionEvent): void;
2816
- /**
2817
- * Awaited parallel durability checkpoint: every listener runs and the
2818
- * caller awaits all of them, with no waterfall veto. Scope-filtered dispatch
2819
- * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope.
2820
- * @param session - the session whose buffered events must reach durable storage.
2821
- * @dshScopeScan unsupported
2822
- * @mode parallel
2823
- */
2824
- 'session/flush'(this: Scoped<Session>, session: Session): Promise<void> | void;
2825
- }
2826
- }
2827
- declare module '@deepseek-ai/dsh-typert-protocol' {
2828
- interface TypertLookupMap {
2829
- session: TypertLookup<Session, SessionId>;
2830
- }
2831
- }
2832
- /**
2833
- * An event-sourced session: an append-only log of {@link SessionEvent}s.
2834
- *
2835
- * Plain class (not a Service) — create live instances via
2836
- * `ctx.sessions.create()` and detached instances via {@link create}.
2837
- * Seeding with an existing event log replays/forks a session.
2838
- * @typert object
2839
- */
2840
- declare class Session {
2841
- private log;
2842
- /** Single incremental owner of surface acceptance and projection state. */
2843
- private readonly surfaceManager;
2844
- /** The ordered surface over this session's event log. */
2845
- get surface(): SessionSurface;
2846
- /**
2847
- * Detached, deep-frozen creation metadata (format version, cwd, lineage,
2848
- * and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a
2849
- * `Session` is created without a store-owned header, a minimal header is
2850
- * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so
2851
- * `session.header` is always present. Kept out of the event log — it is a
2852
- * storage concern, not replayable conversation state.
2853
- */
2854
- readonly header: SessionHeader;
2855
- /** Number of leading events inherited from this Session's fork parent. */
2856
- readonly inheritedEventCount: SessionLogOffset;
2857
- /** The session identity, derived from its durable header's single copy. */
2858
- get id(): SessionId;
2859
- /**
2860
- * The constructor seed length (0 without one), before any marker appended
2861
- * during construction. Seed events never publish on `session/event`. A
2862
- * marker appended before the store attaches occupies this seq without
2863
- * publishing either; otherwise this seq is available for the next append.
2864
- *
2865
- * This in-process offset is not persisted. A fork seed can already contain
2866
- * the child's inherited marker and synthetic closers, so its child-owned
2867
- * history starts at {@link inheritedEventCount}, before this offset. A
2868
- * resumed Session's seed contains its full stored log, while its inherited
2869
- * count keeps the durable fork cut. Consumers needing complete canonical
2870
- * history start at seq 0.
2871
- */
2872
- readonly firstLiveSeq: SessionLogOffset;
2873
- /**
2874
- * First event produced for this object lifecycle. A new fork includes its
2875
- * child-owned seed marker and closers; a restored Session starts after its
2876
- * complete stored prefix. This in-process capture offset is not persisted.
2877
- */
2878
- readonly firstLifecycleSeq: SessionLogOffset;
2879
- /**
2880
- * Create a detached session by validating and snapshotting borrowed seed
2881
- * events and storage metadata.
2882
- * @param id - session identity.
2883
- * @param seed - optional borrowed replay or fork events.
2884
- * @param header - optional borrowed storage metadata.
2885
- * @param inheritedEventCount - exact fork-inherited prefix length for a seeded header.
2886
- * @param projections - pure interpreters for plugin-owned message changes.
2887
- * @returns a detached session.
2888
- * @throws when a seed event requires a missing message interpreter or fails validation.
2889
- */
2890
- static create(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader, inheritedEventCount?: SessionLogOffset, projections?: readonly SessionMessageProjection[]): Session;
2891
- /**
2892
- * Restore a detached session by adopting an independently owned or deeply frozen seed.
2893
- * Runtime-required event fields, event envelopes, sequence continuity, surface
2894
- * transitions, and header fields are validated without copying or freezing events.
2895
- * Embedded Assistant streams remain opaque until a stream consumer or storage
2896
- * verifier reads them.
2897
- * @param id - restored session identity.
2898
- * @param seed - independently owned or deeply frozen events.
2899
- * @param header - independently owned storage metadata.
2900
- * @param inheritedEventCount - exact fork-inherited prefix length decoded from storage.
2901
- * @param eventState - aliasing state carried from the operation that produced the seed.
2902
- * @param projections - pure interpreters for plugin-owned message changes.
2903
- * @returns a restored detached session.
2904
- * @throws when a seed event requires a missing message interpreter or fails validation.
2905
- */
2906
- static fromRestore(id: SessionId, seed: readonly SessionEvent[], header: SessionHeader, inheritedEventCount: SessionLogOffset, eventState: SessionSeedEventState, projections?: readonly SessionMessageProjection[]): Session;
2907
- private constructor();
2908
- /** Cached immutable full snapshot of the private append-only log. */
2909
- private eventsSnapshot;
2910
- /**
2911
- * Return the immutable event stored at one exact sequence number.
2912
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
2913
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
2914
- * @param seq - event sequence number.
2915
- * @returns the accepted event, or undefined when the log does not contain it.
2916
- */
2917
- eventAt(seq: SessionSeq): SessionEvent | undefined;
2918
- /**
2919
- * Materialize an immutable snapshot of a half-open event sequence range.
2920
- * A full current snapshot is reused until the next append; every previously
2921
- * returned snapshot remains stable after later appends.
2922
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
2923
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
2924
- * @param fromSeq - non-negative inclusive sequence number; defaults to the log start.
2925
- * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end.
2926
- * @returns a frozen array of the selected deeply frozen events.
2927
- */
2928
- snapshotEvents(fromSeq?: SessionLogOffset, toSeqExclusive?: SessionLogOffset): readonly SessionEvent[];
2929
- /**
2930
- * Return this Session's events after its fork-inherited prefix.
2931
- * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited.
2932
- * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md).
2933
- * @returns a fresh array containing child-owned events in log order.
2934
- */
2935
- ownEvents(): readonly SessionEvent[];
2936
- /**
2937
- * Whether one existing event position is outside the fork-inherited prefix.
2938
- * @param seq - event position in this Session.
2939
- * @returns true when the event belongs to this Session rather than its parent.
2940
- */
2941
- isOwnSeq(seq: SessionSeq): boolean;
2942
- /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */
2943
- get seq(): SessionLogOffset;
2944
- /**
2945
- * Append one typed event to the log and synchronously notify observers via
2946
- * the store-owned, module-private publication hooks. The hot path never blocks
2947
- * on I/O — persistence plugins buffer asynchronously. Once the event enters
2948
- * the log, the append is committed: observer failures are logged and
2949
- * contained per listener, so they do not change the return value or prevent
2950
- * later listeners from observing the same accepted event.
2951
- *
2952
- * @param type - The event type (key of {@link SessionEventMap}).
2953
- * @param data - The event payload; must be JSON-serializable.
2954
- * @param opts - Surface metadata: `surfaceOp` controls how the event enters
2955
- * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier
2956
- * events this one derives from. REQUIRED for
2957
- * {@link SurfaceEventType} events (every message-producing event must
2958
- * declare how it joins the surface, the sole source of derived model
2959
- * history) and
2960
- * rejected by the compiler for non-surface types like `turn/start` or
2961
- * `assistant/attempt`. Assistant messages embed their exact provider
2962
- * stream and cannot cite top-level source events.
2963
- * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of
2964
- * `data` that entered the log, so reading `event.data` back sees the logged
2965
- * value, never the caller's still-mutable input.
2966
- * @throws if `data` or surface metadata is not losslessly JSON-serializable
2967
- * (BigInt, function, symbol, undefined, negative zero, non-finite number,
2968
- * circular reference, sparse array, or an exotic object such as
2969
- * Map/Set/Date/class instance), or when the candidate violates the
2970
- * request-header empty-field or tool-error consistency rules, or the
2971
- * canonical surface contract (marker shape and eligibility, unique
2972
- * earlier source-event references, positional replacement validity, and complete
2973
- * shadowed-node coverage). One iterative pass reads, validates, and
2974
- * copies each nested value once, so a stateful getter cannot supply one value
2975
- * to validation and another to storage. The event log is the durable source
2976
- * of truth, so a bad event fails at the append site rather than later during
2977
- * a backend flush. A synchronous internal dispatch validation failure or an
2978
- * append reentered while this acceptance/publication boundary is open also
2979
- * rejects before the log changes.
2980
- */
2981
- append<T extends SessionEventType>(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent<T>] : []): SessionEvent<T>;
2982
- /** Cached fold of the request-header events — see {@link requestHeader}. */
2983
- private headerFold;
2984
- /** Log position (events consumed) the header fold has reached. */
2985
- private headerFoldSeq;
2986
- /**
2987
- * The {@link EpochHeader} in force after the log's last header event — the
2988
- * header the NEXT request will be compared against — or undefined before
2989
- * the first `request/header` snapshot. The live, incrementally-maintained
2990
- * form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded
2991
- * once, when first seen, so a per-step read costs O(new events).
2992
- * @returns the folded header, or undefined when no header event exists yet.
2993
- */
2994
- requestHeader(): EpochHeader | undefined;
2995
- /** Cached fold of `request/context` events. */
2996
- private contextFold;
2997
- private contextFoldSeq;
2998
- /**
2999
- * Return the latest resolved route metadata, or `undefined` before the first
3000
- * `request/context` event. Each event is folded once.
3001
- * @returns the latest immutable route metadata.
3002
- */
3003
- requestContext(): RequestContext | undefined;
3004
- /** Cached historical tool definitions and updates for request projection. */
3005
- private readonly toolHistoryProjection;
3006
- /** Index of the next committed event not yet consumed by the tool-history fold. */
3007
- private toolHistorySeq;
3008
- /**
3009
- * Fold unseen committed events into capability-independent tool history.
3010
- * Initial access reconstructs inherited history; later reads consume only new events.
3011
- * @returns an immutable snapshot for LLM request projection, including historical addition definitions.
3012
- */
3013
- toolHistory(): ToolHistory;
3014
- /** The derived-message cache: frozen projections, extended per unseen node. */
3015
- private derived;
3016
- /** Surface position (nodes projected) the cache has reached. */
3017
- private derivedNodes;
3018
- /** {@link SurfaceManager.contentGeneration} the cache was built under. */
3019
- private derivedGeneration;
3020
- /**
3021
- * Derive the LLM message history by walking the ordered sequences of
3022
- * message-producing events maintained by `surfaceOp` markers. The
3023
- * surface is the single source of derived history: every message-producing
3024
- * append records its `surfaceOp`, so a raw event with no marker (a chunk, a
3025
- * turn boundary) is correctly absent, and a compaction `replace` deletes the
3026
- * shadowed nodes from the derivation. The projection rules are
3027
- * {@link deriveEventMessage}, with logged message projections applied
3028
- * without changing node membership or message identity.
3029
- *
3030
- * CACHED: pure tail growth costs O(new nodes); a replacement or message projection
3031
- * ({@link SessionSurface.contentGeneration}) rebuilds. The returned array is
3032
- * a fresh snapshot per call (later appends never grow an array a caller
3033
- * already holds); the `Message` objects in it are SHARED and **deep-frozen**.
3034
- * Unchanged content reuses frozen event data; projected blocks are frozen
3035
- * derived copies. Consumers cannot mutate the log through either form.
3036
- * @returns a fresh array of the shared, frozen derived history.
3037
- */
3038
- deriveMessages(): Message[];
3039
- /**
3040
- * Project one event with all committed message projections applied.
3041
- * The original durable event remains unchanged.
3042
- * @param event - the event to project.
3043
- * @returns the derived message, or null when the event produces none.
3044
- */
3045
- deriveEventMessage(event: SessionEvent): Message | null;
3046
- }
3047
- /** A fork source: either the live session object or its live store id. */
3048
- type SessionForkSource = Session | SessionId;
3049
- /**
3050
- * In-memory session store (`ctx.sessions`).
3051
- *
3052
- * Persistence is intentionally not implemented here — the agent lifecycle
3053
- * attaches a session-log writer to each published session's write handle;
3054
- * a session published outside that lifecycle persists nothing.
3055
- */
3056
- declare class SessionStore extends Service {
3057
- private store;
3058
- private counter;
3059
- private readonly projections;
3060
- /** Borrowed definitions for detached replay; contributions live until their registering fibers unload. */
3061
- get messageProjections(): readonly SessionMessageProjection[];
3062
- /**
3063
- * Register one event interpreter for live creation, restore, and fork.
3064
- * Disposing the contribution makes sessions that used it refuse further derivation.
3065
- * @param projection - pure definition owned by the event's plugin.
3066
- * @returns the fiber-owned disposer.
3067
- * @throws when another definition already owns this event type.
3068
- */
3069
- registerMessageProjection(projection: SessionMessageProjection): () => Promise<void>;
3070
- constructor(ctx: Context);
3071
- /**
3072
- * Create a session owned by the calling fiber: disposing that fiber stops
3073
- * event notification and removes the session from the store. `options.seed`
3074
- * populates the session with a copy of those events (replay/fork);
3075
- * `options.meta` attaches creation metadata (validated absolute `cwd`, seed
3076
- * and parent lineage, and delegation depth) as the immutable
3077
- * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`).
3078
- *
3079
- * For an agent whose session must be torn down IN ORDER with its loop (so the
3080
- * loop's final events are published before the store attachment ends), do NOT use this
3081
- * — fold the session lifecycle into the agent's own effect via
3082
- * {@link prepare} + {@link enter} + {@link announce} (see
3083
- * `dsh-agent-loop`'s creation transaction).
3084
- *
3085
- * @param id - the session id; omitted, the store mints `session-<n>`.
3086
- * @param options - seed events and/or creation metadata for the header.
3087
- * @returns the live session, already entered and announced.
3088
- * @throws if a session with `id` already exists, metadata is not a plain
3089
- * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
3090
- * non-absolute path (storage backends key directories off it).
3091
- */
3092
- create(id?: SessionId, options?: CreateSessionOptions): Session;
3093
- /**
3094
- * Build a session WITHOUT entering it into the store — validate the id/cwd and
3095
- * construct the {@link Session} (with its immutable {@link SessionHeader}).
3096
- * Pairs with {@link enter} + {@link announce}: a caller that owns a composite
3097
- * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE
3098
- * effect so a fiber unload tears the session + agent down as a single ORDERED
3099
- * chain rather than as racing sibling effects — which would remove the publication hooks
3100
- * before the driver's closing events commit, dropping them.
3101
- *
3102
- * @param id - the session id; omitted, the store mints `session-<n>`.
3103
- * @param options - seed events and/or creation metadata for the header. With
3104
- * `eventState`, every seed event is either independently owned or any
3105
- * shared value is deeply frozen; {@link Session.fromRestore} validates and
3106
- * adopts those values without copying or freezing them.
3107
- * @returns the constructed session, NOT yet in the store.
3108
- * @throws if a session with `id` already exists, metadata is not a plain
3109
- * lossless-JSON record with valid scalar fields, or `meta.cwd` is a
3110
- * non-absolute path.
3111
- */
3112
- prepare(id?: SessionId, options?: PrepareSessionOptions): Session;
3113
- /**
3114
- * Enter a {@link prepare}d session into the store: install the module-private
3115
- * append publication hooks and add it to the store. Returns the DETACH
3116
- * disposer (hooks + store removal). Does NOT emit `session/created` —
3117
- * the caller yields this disposer inside its effect and THEN calls
3118
- * {@link announce}, so a throwing `session/created` listener rolls the attach
3119
- * back instead of leaking it.
3120
- *
3121
- * Re-checks the id for a duplicate: `prepare` and `enter` are public
3122
- * cross-package primitives and a caller may interleave arbitrary work (or
3123
- * another create) between them, so a stale prepared session must NOT overwrite
3124
- * a live store entry of the same id — its detach disposer would later delete
3125
- * the REAL session. The {@link create} convenience and the agent factory call
3126
- * the two back-to-back so they never trip this, but the public API cannot
3127
- * assume that.
3128
- *
3129
- * @param session - a {@link prepare}d session not yet in the store.
3130
- * @returns the detach disposer (publication hooks + store removal). When called from
3131
- * a synchronous `session/created` listener, removal and disposal wait until
3132
- * that creation dispatch unwinds.
3133
- * @throws if a session with this id is already in the store.
3134
- */
3135
- enter(session: Session): () => void;
3136
- /** Remove one exact entered session and emit its paired disposal when announced. */
3137
- private detachEntered;
3138
- /** Emit `session/created` exactly once for an {@link enter}ed session (with
3139
- * the carrier {@link enter} captured). Separate from {@link enter} so the
3140
- * caller can yield the detach disposer first (rollback safety — see
3141
- * {@link enter}).
3142
- * @param session - the entered session to announce to listeners.
3143
- * @throws if the session is not live or its announcement already began,
3144
- * including a reentrant call from a creation listener. */
3145
- announce(session: Session): void;
3146
- /** Emit the paired teardown notification with per-listener containment. */
3147
- private emitDisposed;
3148
- /**
3149
- * Dispatch the awaited `session/flush` durability checkpoint for `session`,
3150
- * with the carrier captured at {@link enter}. THE flush entry point: the
3151
- * store owns the carrier, so callers (the checkpoint policy's per-request
3152
- * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers
3153
- * that flush themselves before reading storage) must come through here
3154
- * rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner,
3155
- * one spelling, and the scoped-dispatch invariant can pin it.
3156
- * @param session - the session whose buffered events must reach durable storage.
3157
- * @returns whether at least one durability listener participated, after every
3158
- * listener has settled successfully.
3159
- * @throws the first registered listener failure after every listener settles.
3160
- */
3161
- flush(session: Session): Promise<boolean>;
3162
- /** Return the exact live entry; detached/prepared objects reject. */
3163
- private liveEntryFor;
3164
- /**
3165
- * Look up a live session.
3166
- * @param id - the session id to look up.
3167
- * @returns the session, or undefined when no live session has that id.
3168
- */
3169
- get(id: SessionId): Session | undefined;
3170
- /**
3171
- * All live sessions, in creation order.
3172
- * @returns a fresh array; mutating it does not affect the store.
3173
- */
3174
- list(): Session[];
3175
- /**
3176
- * Create a live child session from an exact prefix of a live source.
3177
- * `boundary` is an inclusive source event seq; omitted means the source's
3178
- * current last event. An open tail receives synthetic tool results and
3179
- * step/turn closers with the forked cause. Closed steps and turns remain
3180
- * unchanged, including any failed tool calls already missing results.
3181
- * `inheritedEventCount` counts only copied source events, excluding these closers.
3182
- *
3183
- * @param source - Live source session object or id.
3184
- * @param boundary - Inclusive source event seq to fork through; omitted means
3185
- * the source's current last event, and omitted on an empty source forks an
3186
- * empty child.
3187
- * @param childSessionId - Optional child session id; omitted delegates to
3188
- * `SessionStore`'s id policy.
3189
- * @returns The created live child session.
3190
- */
3191
- fork(source: SessionForkSource, boundary?: SessionSeq, childSessionId?: SessionId): Session;
3192
- private _forkBoundary;
3193
- private _resolveForkSource;
3194
- }
3195
- //#endregion
3196
88
  //#region src/client/controller.d.ts
3197
89
  interface SessionRowRecord {
3198
90
  sessionId: string;