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