import Schema from "@deepseek-ai/schemastery"; import { z } from "zod"; import { Context, Service, Volatile } from "@deepseek-ai/cordis"; import { FileAttachmentRef, ImageAttachmentRef, ImageRequestTarget } from "@deepseek-ai/dsh-attachment"; //#region node_modules/.pnpm/@deepseek-ai+dsh-scope@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-scope/lib/types/index.d.ts declare const ScopedBrand: unique symbol; /** * A routing-only event receiver built by {@link scopeTarget}. The type * parameter records the subject type for dispatch checking; the carrier does * not expose the subject's properties. Event payloads carry the real subject. */ type Scoped = object & { readonly [ScopedBrand]: T; }; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-brand@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-brand/lib/types/index.d.ts /** * Duplicate-install-safe nominal primitive helpers. * * A brand makes structurally identical strings or numbers non-interchangeable * at the type level: a `SessionId` cannot be passed where a `ToolCallId` is * expected, and an event sequence cannot be passed as a log offset. Comparison, * logging, and serialization retain the underlying primitive behavior. * * This package owns no concrete domain value and keeps no runtime identity or mutable * state, so independently installed copies produce interchangeable values. * * @module @deepseek-ai/dsh-brand */ declare const BRAND: unique symbol; /** A string carrying a compile-time-only brand `B`. */ type Branded = string & { readonly [BRAND]: B; }; /** A number carrying a compile-time-only brand `B`. */ type BrandedNumber = number & { readonly [BRAND]: B; }; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-typert-protocol/lib/types/owned-value.d.ts /** Generic invocation-owned values returned by synchronous Client Context resolvers. */ /** Shared identity across independently bundled Context providers and Gateway. */ declare const TYPERT_OWNED_VALUE: unique symbol; /** A borrowed payload paired with the invocation owner's idempotent cleanup. */ interface TypertOwnedValue extends Disposable { readonly [TYPERT_OWNED_VALUE]: true; readonly value: Value; } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-typert-protocol/lib/types/types.d.ts declare const LOOKUP_HOST: unique symbol; declare const LOOKUP_WIRE: unique symbol; declare const CONTEXT_WIRE: unique symbol; declare const RESOURCE_ID: unique symbol; /** Type-level association between a Host object and its wire identity. */ interface TypertLookup { readonly [LOOKUP_HOST]: Host; readonly [LOOKUP_WIRE]: Wire; } /** Extract the Host object associated with one lookup declaration. */ type TypertLookupHost = Lookup extends TypertLookup ? Host : never; /** Extract the wire identity associated with one lookup declaration. */ type TypertLookupWire = Lookup extends TypertLookup ? Wire : never; /** Type-level association between a scoped Context kind and its wire identity. */ interface TypertContext { readonly [CONTEXT_WIRE]: Wire; } /** Extract the wire identity associated with one scoped Context declaration. */ type TypertContextWire = ContextType extends TypertContext ? Wire : never; /** Merge-extensible Host object lookup declarations. */ interface TypertLookupMap {} /** Merge-extensible scoped Context declarations. */ interface TypertContextMap {} /** Type-level association between a resource kind and its identity type. */ interface TypertResource { readonly [RESOURCE_ID]: Id; } /** Extract the identity type associated with one resource declaration. */ type TypertResourceId = Resource extends TypertResource ? Id : never; /** * Merge-extensible resource kinds whose identities a Remote call or forwarded * event may carry. The package that owns an identity type declares its kind; * the value is that kind's identity type, a string type such as a branded id. * `global` names the built-in identity-less resource and is never a kind here. */ interface TypertResourceMap {} /** One declared resource kind. */ type TypertResourceKind = Extract; /** Awaitable disposer returned by Cordis-owned Typert registrations. */ type TypertDisposer = () => Promise; type StringKeyOf = Extract; /** Minimal runtime-schema capability carried by strict generated codecs. */ interface TypertSchema { /** * Parse and validate one boundary value. * @param value - untrusted boundary value. * @returns the validated value. */ parse(value: unknown): Output; } /** Codec attached to one invocation parameter or result. */ type TypertCodec = (TypertRemoteValue & { readonly mode: 'strict'; readonly typeSymbol: string; /** * Decode a unary result whose fields require type-specific handling. * @param value - result reconstructed by the RPC carrier. * @returns the validated result, retaining native byte views. */ readonly decode?: ((value: unknown) => unknown) | undefined; /** * Project typed binary fields into RPC result attachments. * @param value - native unary result. * @param writeBytes - records a byte view at its result-relative path and returns its JSON placeholder. * @returns JSON metadata with untouched JSON subtrees retained. */ readonly encode?: ((value: unknown, writeBytes: (bytes: Uint8Array, path: readonly (string | number)[]) => null) => unknown) | undefined; }) | { readonly mode: 'src-json'; }; /** One ordered business parameter in a Remote invocation. */ interface InvocationParameterDescriptor { /** Source-level parameter name. */ readonly name: string; /** Source parameter documentation, independent of JSON Schema support. */ readonly description?: string; /** Required key in the wire `args` object. */ readonly wire: string; /** Whether the value is JSON or requires a registered Host lookup. */ readonly source: 'json' | 'lookup'; /** Lookup key when `source` is `lookup`. */ readonly lookup?: string; /** Boundary codec for the wire representation. */ readonly codec: TypertCodec; /** Missing wire fields decode to `undefined` only for an explicitly declared `T | undefined`. */ readonly acceptsUndefined?: true; } /** Source position retained for diagnostics from generated definitions. */ interface InvocationSourceLocation { readonly file: string; readonly line: number; readonly column: number; } /** Carrier-independent description of one exported method invocation. */ interface InvocationDescriptor { /** Globally stable generated identity. */ readonly id: string; /** Cordis service key owning the method. */ readonly service: string; /** Wire namespace, defaulting to the service key. */ readonly namespace: string; /** Public instance method name. */ readonly method: string; /** Service member invoked when the exported method name is an alias. */ readonly implementation?: string; /** Absent for unary calls; stream calls deliver every yielded item as the Host produced it. */ readonly mode?: 'stream'; /** Receiver selection mode. */ readonly invocation: { readonly kind: 'direct'; } | { readonly kind: 'context'; readonly context: string; readonly wire: string; readonly codec: TypertCodec; }; /** Optional consuming-Context projection for one direct lookup parameter. */ readonly scope?: { /** Context kind whose Client adapter supplies the identity. */ readonly context: string; /** Lookup parameter wire field replaced by the Context identity. */ readonly wire: string; }; /** Ordered business parameters. */ readonly parameters: readonly InvocationParameterDescriptor[]; /** * Client-to-Host items of the same logical stream, generated from the `In` * type argument of the method's `RemoteStream` return type; absent * when `In` is `never`. The method reads the items through * `RemoteInvocation.uplink()`, so nothing enters the parameter list. */ readonly uplink?: { /** Codec validating every uplink item before `uplink()` delivers it. */ readonly codec: TypertCodec; }; /** Transport cancellation injected after business parameters instead of entering wire args. */ readonly cancellation?: { /** Reserved final Host method parameter. */ readonly parameter: 'signal'; }; /** Codec for the unary result or each yielded stream item. */ readonly result: TypertCodec; /** Source-owned method documentation; ordinary methods need not have JSDoc. */ readonly description?: string; /** Source declaration used only for diagnostics. */ readonly sourceLocation?: InvocationSourceLocation; } /** * Opaque identity of one Peer: a party admitted to this Host by the connection * layer. "Peer" is a connection-layer word; the browser application keeps the * word "Client". */ type PeerId = Branded<'PeerId'>; /** * Merge-extensible caller identities. Each driver declares its own entry. * Every entry is a JSON value with a unique literal `kind`, carries no * credential, and is safe to persist in a Session log. */ interface PrincipalMap { /** The local user who owns this Host. */ owner: { readonly kind: 'owner'; }; } /** One caller identity; the authorization layer reads only this. */ type Principal = PrincipalMap[keyof PrincipalMap]; /** * One Peer's session on this Host. Its creator owns it: `ctx` is the Cordis * scope that owns connection-lifetime registrations and is disposed with the * Peer, and `principal` is the caller identity fixed when the Peer was created. */ interface PeerScope { readonly id: PeerId; /** Connection-lifetime registrations; disposed with the Peer. */ readonly ctx: Context; /** Caller identity fixed at creation by in-process Host code; no wire field can set it. */ readonly principal: Principal; /** Aborted once the Peer is disposed; Remote streams that speak for the Peer end with it. */ readonly signal: AbortSignal; /** Whether the Peer may open a forwarded-event stream; this does not grant business permissions. */ readonly interactions: 'answer' | 'none'; /** * Tear down every registration made through `ctx`. * @returns settles once the scope has quiesced; racing calls share one completion. */ dispose(): Promise; } /** Carrier capacity for buffered uplink frames of one logical stream. */ interface RemoteUplinkWindow { /** Maximum complete encoded frame bytes waiting for the Host consumer. */ readonly maxBytes: number; /** UTF-8 envelope bytes added to a compact JSON item with a present value field. */ readonly frameOverheadBytes: number; } /** * The context of one Remote call, reachable inside the receiving method as * `this.ctx.invocation`. The Gateway derives the receiver from a Context that * carries it, so no parameter is injected and nothing crosses the wire. */ interface RemoteInvocation { readonly request: { readonly namespace: string; readonly method: string; readonly args: Readonly>; }; /** Cordis service key of the receiving Service. */ readonly service: string; /** Peer the call speaks for; every carrier names it explicitly. */ readonly peer: PeerScope; /** Carrier cancellation: Client cancel, socket close, or an uplink failure. */ readonly signal: AbortSignal; /** Carrier frame capacity; absent when the carrier imposes no encoded-frame inbox limit. */ readonly uplinkWindow?: RemoteUplinkWindow | undefined; /** * The Client's uplink items for this call. Available once; a second call * throws. With an uplink codec on the descriptor every item is decoded to * `In`; without one items arrive as `unknown` after a JSON-safety check. * Iteration ends when the Client ends its uplink; when the method finishes * its downlink the Gateway calls the iterator's `return()` and unread items * are dropped. `In` is the caller's assertion: the runtime decodes by the * descriptor and does not cross-check it. * @template In - item type the caller reads; the descriptor codec decides what arrives. * @returns the single-consumer uplink iterable. */ uplink(): AsyncIterable; } /** Generated Host contract selected explicitly by a Client assembly. */ interface TypertRemoteContribution { /** npm package that owns the Remote methods. */ readonly package: string; /** Consumer-side invocation descriptors generated from that package. */ readonly descriptors: readonly InvocationDescriptor[]; } /** Generated parser and optional lossless tool-schema projection of one Remote value. */ interface TypertRemoteValue { /** Materialize the generated parser without loading the owning Service. */ readonly create: () => TypertSchema; /** Source-owned value documentation, independent of tool projection support. */ readonly description?: string | undefined; /** Present when the value is representable in the tool-schema subset without losing constraints; may be derived lazily. */ readonly jsonSchema?: Readonly> | undefined; /** Projection failure for consumers that require JSON Schema; parsing remains available. */ readonly jsonSchemaError?: string | undefined; } /** * Resolve one validated wire identity, synchronously or asynchronously. * @param id - validated wire identity. * @returns the Host object, or `undefined` when unavailable. */ type TypertLookupResolver = (id: Wire) => Host | undefined | Promise; /** Resource kinds whose identity type is a wire identity; every kind for a type-erased provider. */ type TypertResourceKindFor = unknown extends Wire ? TypertResourceKind : { [Kind in TypertResourceKind]: [Wire] extends [TypertResourceId] ? Kind : never; }[TypertResourceKind]; /** Runtime provider for one declared Host object lookup. */ interface TypertLookupProvider { /** Source parameter name recognized by the SRC weak parser. */ readonly parameter: string; /** Wire field replacing the Host object parameter. */ readonly wire: string; /** Resource kind the wire identity names; a parameter of this lookup carries that resource. */ readonly resource?: TypertResourceKindFor; /** Canonical Host type symbol used by strict generation. */ readonly hostTypeSymbol: string; /** Canonical wire type symbol used by strict generation. */ readonly wireTypeSymbol: string; /** * Resolve a wire identity through the provider's default policy. * @param id - validated wire identity. * @returns the object, `undefined` when unavailable, or either asynchronously. */ resolve(id: Wire): Host | undefined | Promise; } /** Stable wire declaration retained after a lookup provider unloads. */ interface TypertLookupDefinition { /** Merge-declared lookup key. */ readonly key: string; /** Source parameter name recognized by the SRC weak parser. */ readonly parameter: string; /** Wire field replacing the Host object parameter. */ readonly wire: string; /** Canonical Host type symbol used by strict generation. */ readonly hostTypeSymbol: string; /** Canonical wire type symbol used by strict generation. */ readonly wireTypeSymbol: string; } /** Host wire-to-Context resolver plus the declaration used by strict Remote methods. */ interface TypertHostContextAdapter { /** Wire field carrying the Context identity. */ readonly wire: string; /** Canonical wire type symbol used by strict generation. */ readonly wireTypeSymbol: string; /** Resource kind the wire identity names; a call scoped to this Context carries that resource. */ readonly resource?: TypertResourceKindFor; /** * Resolve a validated wire identity to a live Host Context. * @param id - validated wire identity. * @returns the Context, or `undefined` when it is unavailable. */ resolve(id: Wire): Context | undefined | Promise; } /** Composition-owned resolver replacing one Host Context adapter's default lookup policy. */ type TypertHostContextResolver = (id: Wire) => Context | undefined | Promise; /** Client-side bidirectional Context adapter. */ interface TypertClientContextAdapter { /** * Read the identity represented by a live Client Context. * @param ctx - Client Context inspected by a scoped Remote caller. * @returns the wire identity, or `undefined` for another Context kind. */ identity(ctx: Context): Wire | undefined; /** * Resolve a validated identity synchronously for one Client invocation. * @param id - validated wire identity. * @returns a borrowed or invocation-owned Client Context, or undefined when unavailable. */ resolve(id: Wire): Context | TypertOwnedValue | undefined; } /** Notification emitted after a Typert runtime registry changes. */ interface TypertRegistryChange { readonly kind: 'local' | 'remote' | 'lookup' | 'host-context' | 'client-context' | 'resource'; readonly key: string; } /** Listener for one Typert runtime registry. */ type TypertRegistryListener = (change: TypertRegistryChange) => void; /** Current-environment invocation definitions. */ interface TypertLocalRegistry { /** * Look up one invocation by `/`. * @param endpoint - canonical endpoint. * @returns the live descriptor, or `undefined` when absent. */ get(endpoint: string): InvocationDescriptor | undefined; /** * Report whether a strict definition has existed during this Typert Service lifetime. * @param endpoint - canonical endpoint. * @returns `true` after the endpoint has been registered at least once, even if withdrawn. */ hasSeen(endpoint: string): boolean; /** @returns a registration-order snapshot of local descriptors. */ list(): readonly InvocationDescriptor[]; /** * Observe later local-definition changes. * @param listener - synchronous contained observer. * @returns disposer for this subscription. */ subscribe(listener: TypertRegistryListener): TypertDisposer; } /** Consumer-selected Remote contribution registry. */ interface TypertRemoteRegistry { /** * Register one generated contribution for the calling Cordis fiber. * @param contribution - generated Remote descriptors. * @returns disposer withdrawing the exact contribution. */ register(contribution: TypertRemoteContribution): TypertDisposer; /** * Look up one Remote descriptor by endpoint. * @param endpoint - canonical endpoint. * @returns the descriptor, or `undefined` when unmounted. */ get(endpoint: string): InvocationDescriptor | undefined; /** @returns a registration-order snapshot of Remote descriptors. */ list(): readonly InvocationDescriptor[]; /** * Observe later Remote contribution changes. * @param listener - synchronous contained observer. * @returns disposer for this subscription. */ subscribe(listener: TypertRegistryListener): TypertDisposer; } /** Runtime registry for Host object lookup providers. */ interface TypertLookupRegistry { /** * Register one provider under its merge-declared key. * @param key - lookup key. * @param provider - owning package's live resolver. * @returns disposer withdrawing the exact provider. */ register>(key: K, provider: TypertLookupProvider, TypertLookupWire>): TypertDisposer; /** * Replace one provider's default resolution policy while this contribution is active. * Configuration may precede provider registration; without a live provider, `get()` remains unavailable. * @param key - lookup key whose wire declaration remains provider-owned. * @param resolver - composition-owned resolver used by every lookup of this key. * @returns disposer restoring the provider's default resolver. */ configure>(key: K, resolver: TypertLookupResolver, TypertLookupWire>): TypertDisposer; /** * Look up one provider by runtime key. * @param key - descriptor lookup key. * @returns the live provider, or `undefined` when absent. */ get(key: string): TypertLookupProvider | undefined; /** @returns lookup declarations observed during this Typert Service lifetime. */ definitions(): readonly TypertLookupDefinition[]; /** @returns a snapshot of registered provider keys. */ keys(): readonly string[]; /** * Observe later lookup changes. * @param listener - synchronous contained observer. * @returns disposer for this subscription. */ subscribe(listener: TypertRegistryListener): TypertDisposer; } /** Runtime registry for the Host and Client adapters of each Context kind. */ interface TypertContextRegistry { /** * Register a Host Context adapter. * @param key - merge-declared Context key. * @param adapter - owning package's Host resolver and wire declaration. * @returns disposer withdrawing the exact adapter. */ registerHost>(key: K, adapter: TypertHostContextAdapter>): TypertDisposer; /** * Override one Host Context key's resolution policy for the calling fiber. * Configuration may precede provider registration and restores the provider's default resolver on disposal. * @param key - merge-declared Context key. * @param resolver - composition-owned resolver used by every Host Context lookup of this key. * @returns disposer restoring the provider's default resolver. */ configureHost>(key: K, resolver: TypertHostContextResolver>): TypertDisposer; /** * Register a Client Context adapter. * @param key - merge-declared Context key. * @param adapter - owning package's bidirectional Client projection. * @returns disposer withdrawing the exact adapter. */ registerClient>(key: K, adapter: TypertClientContextAdapter>): TypertDisposer; /** * Look up a Host Context adapter; a configured resolver keeps the adapter's declaration and `resource`. * @param key - descriptor Context key. * @returns the adapter, or `undefined` when absent. */ getHost(key: string): TypertHostContextAdapter | undefined; /** * Look up a Client Context adapter. * @param key - descriptor Context key. * @returns the adapter, or `undefined` when absent. */ getClient(key: string): TypertClientContextAdapter | undefined; /** * Observe later Context adapter changes. * @param listener - synchronous contained observer. * @returns disposer for this subscription. */ subscribe(listener: TypertRegistryListener): TypertDisposer; } /** Default wire field of one resource kind. */ interface TypertResourceDeclaration { /** Top-level or first-object wire field holding one identity of the kind. */ readonly field: string; } /** One registered resource kind with its default wire field. */ interface TypertResourceEntry extends TypertResourceDeclaration { /** Registered resource kind. */ readonly kind: string; } /** Runtime registry of resource kinds' default wire fields. */ interface TypertResourceRegistry { /** * Register one kind's default wire field for the calling fiber. Only the * domain that owns the kind registers it. * @param kind - merge-declared resource kind. * @param declaration - the kind's default wire field. * @returns disposer withdrawing the exact registration. * @throws Error when the kind is already registered or is `global`, the built-in resource kind. */ register(kind: TypertResourceKind, declaration: TypertResourceDeclaration): TypertDisposer; /** * Look up one kind's declaration. * @param kind - resource kind. * @returns the live declaration, or `undefined` when unregistered. */ get(kind: string): TypertResourceDeclaration | undefined; /** @returns a registration-order snapshot of registered kinds with their fields. */ entries(): readonly TypertResourceEntry[]; /** * Observe later resource-kind changes. * @param listener - synchronous contained observer. * @returns disposer for this subscription. */ subscribe(listener: TypertRegistryListener): TypertDisposer; } /** Minimal Typert runtime consumed through dependency inversion. */ interface TypertRegistryContract { readonly local: TypertLocalRegistry; readonly remotes: TypertRemoteRegistry; readonly lookups: TypertLookupRegistry; readonly contexts: TypertContextRegistry; readonly resources: TypertResourceRegistry; } declare module '@deepseek-ai/cordis' { interface Context { typert: TypertRegistryContract; /** * The Remote call this Context was derived for, or `undefined` on a * Context no Remote call derived. A Service method reads it as * `this.ctx.invocation`. */ readonly invocation: RemoteInvocation | undefined; } } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-typert-protocol@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-typert-protocol/lib/types/index.d.ts /** Options for an explicit Service-to-Gateway binding. */ interface TypertGatewayBindingOptions { /** Wire namespace; defaults to the Cordis service key. */ readonly namespace?: string; } /** Visible declaration that one Service participates in Typert Gateway export. */ interface TypertGatewayBinding { readonly service: Service; readonly serviceKey: string; readonly namespace: string; } /** Cordis Service base that exposes its registered name through Typert Gateway. */ declare abstract class TypertRemoteService extends Service { /** Visible binding consumed by the Gateway's source-mode discovery. */ readonly typertRemote: TypertGatewayBinding; /** * Register the Service and bind the same key to Typert Gateway. * @param ctx - owning Cordis Context. * @param serviceKey - exact Cordis service key and default wire namespace. * @param options - optional wire namespace. */ protected constructor(ctx: Context, serviceKey: string, options?: TypertGatewayBindingOptions); } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/brand.d.ts /** Stable identity carried by one message across inbox, log, and model-request boundaries. */ type MessageId = Branded<'MessageId'>; /** * Brand a message identifier. * @param id - the opaque message identifier. * @returns the same string with the message-id brand. */ declare function MessageId(id: string): MessageId; /** * Correlates a model-issued tool call with its result. Provider-issued for * real adapters; synthesized by mocks/assembler fallbacks. */ type ToolCallId = Branded<'ToolCallId'>; /** * Brand a string as a {@link ToolCallId}. * @param id - the provider-issued or synthesized call id. * @returns the same string with the tool-call-id brand. */ declare function ToolCallId(id: string): ToolCallId; /** Provider-issued request identifier retained for diagnostics across package boundaries. */ type ProviderRequestId = Branded<'ProviderRequestId'>; /** * Brand a provider-issued request identifier. * @param id - the opaque provider-issued string. * @returns the same string, branded; no validation is performed. */ declare function ProviderRequestId(id: string): ProviderRequestId; /** Adapter-owned identifier for one model's selectable reasoning effort. */ type ReasoningEffortId = Branded<'ReasoningEffortId'>; /** * Brand an adapter-owned reasoning-effort identifier. * @param id - the opaque identifier exposed by one model capability. * @returns the same string, branded; no validation is performed. */ declare function ReasoningEffortId(id: string): ReasoningEffortId; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/message.d.ts /** Provider/model identity and adapter-private replay data for an assistant message. */ interface AssistantProviderMetadata { /** Provider route that produced the message. */ provider: string; /** Provider model id that produced the message. */ model: string; /** * Lossless-JSON adapter state needed to replay the provider response. * `LlmRuntime` exposes it to a target adapter only when that adapter instance * currently owns both this historical provider and the target provider. */ replayState?: unknown; } /** Required source of an assistant message produced by a routed model. */ interface ModelMessageSource extends AssistantProviderMetadata { kind: 'model'; } /** Required source of a tool-role message carrying one tool result. */ interface ToolMessageSource { kind: 'tool'; callId: ToolCallId; } /** Required source of a system-role message produced by the system-prompt plugin. */ interface SystemPromptMessageSource { kind: 'system-prompt'; } /** * Where a message (or injected content) came from, in the harness's own * vocabulary. Merge-extensible sum type — each producer declares its own * `kind` in its own module; there is no shared catch-all `plugin` kind. * Model and tool sources answer their role messages; user messages carry any * producer's kind, and consumers fall through unknown kinds. */ interface MessageSourceMap { user: { kind: 'user'; }; model: ModelMessageSource; tool: ToolMessageSource; 'system-prompt': SystemPromptMessageSource; } /** Any known message source, derived from {@link MessageSourceMap}; switch on `kind` and fall through unknowns (merge-extensible). */ type MessageSource = MessageSourceMap[keyof MessageSourceMap]; /** Shared immutable fields of every conversation message. */ interface MessageBase { /** Stable identity preserved across every representation boundary. */ readonly id: MessageId; /** Exact model-facing blocks. */ readonly content: readonly ContentBlock[]; /** Required source fields supplied by the producer. * @persistenceSource user developer */ readonly source: MessageSource; } /** A rendered system prompt attributed to the system-prompt producer; empty content sends no prompt. */ interface SystemMessage extends MessageBase { readonly role: 'system'; readonly source: MessageSourceMap['system-prompt']; } /** Incremental agent session changes in conversation order, currently tool additions and removals. */ interface DeveloperMessage extends MessageBase { readonly role: 'developer'; } /** A user-role specialization of the shared message representation. */ interface UserMessage extends MessageBase { readonly role: 'user'; } /** A model-produced assistant specialization of the shared message representation. */ interface AssistantMessage extends MessageBase { readonly role: 'assistant'; readonly source: ModelMessageSource; } /** A first-class tool-role message carrying the result of one tool invocation. */ interface ToolResultMessage extends MessageBase { readonly role: 'tool'; readonly source: ToolMessageSource; /** Provider-issued id of the tool call this message answers. */ readonly toolCallId: ToolCallId; /** Whether the tool invocation failed. */ readonly isError?: boolean; } /** * The conversation messages persisted by Session, keyed by role. This map is * closed because every model-visible role must have a durable Session event * and an adapter projection. */ interface MessageRoleMap { system: SystemMessage; developer: DeveloperMessage; user: UserMessage; assistant: AssistantMessage; tool: ToolResultMessage; } /** Any persisted conversation message, discriminated by its `role`. */ type Message = MessageRoleMap[keyof MessageRoleMap]; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/types.d.ts declare module '@deepseek-ai/cordis' { interface Events { /** * The provider topology changed: an adapter registered or unregistered * routes, or the configurable-provider directory gained or lost entries. * This payload-free registry notification fires at each commit point * (including registration disposal); consumers re-read `listProviders()`, * `listModels()`, or `listConfigurableProviders()` for the new state. * Observer failures are contained and cannot veto the registry mutation. * @mode emit */ 'llm/adapters-updated'(): void; } } /** Serializable provider or transport failure facts; policy decides whether they are retryable. */ interface LlmFailure { /** Human-readable provider or transport failure. */ readonly message: string; /** Stable provider-neutral machine-routing code. */ readonly code: string; /** HTTP status returned by the provider, when available. */ readonly status?: number; /** Provider-requested delay in milliseconds, when valid and available. */ readonly providerRetryAfterMs?: number; /** Opaque provider-issued request identifier for diagnostics. */ readonly requestId?: ProviderRequestId; /** * With code `IMAGE_OFFLOAD_REQUIRED`: how many more of the oldest retained * image occurrences the route needs offloaded before the same request fits * its exact byte accounting. `dsh-compaction-image-offload` records the * selected occurrences in an `image/offload` event and retries the step. */ readonly offloadImages?: number; } /** Plain text visible to the end user. */ interface TextBlock { type: 'text'; text: string; } /** Reasoning / thinking content, distinct from visible text. */ interface ReasoningBlock { type: 'reasoning'; text: string; } /** * A durable raster image reference, valid in user or assistant content. The * block is deliberately role-neutral; assistant-side rendering is forward * compatibility — the current production adapters declare text-only output, * so only user messages may carry images. */ interface ImageBlock { type: 'image'; /** Immutable bytes and intrinsic display metadata owned by the attachment service. */ attachment: ImageAttachmentRef; /** * Derived from a durable image-offload decision or preserved by a message * rewrite. Every route sends placeholder text naming the image and its * available read-only path instead of image bytes. */ offloaded?: true; } /** * A durable verbatim file reference, valid in user content. Files never reach * a provider natively: request assembly projects every occurrence to * deterministic handle text (name, byte size, and the read-only saved path), * so adapters and providers see text in its place while the durable log keeps * the structured reference for presentation and authorization. */ interface FileBlock { type: 'file'; /** Immutable verbatim bytes and display metadata owned by the attachment service. */ attachment: FileAttachmentRef; } /** A tool invocation requested by the model. */ interface ToolCallBlock { type: 'tool-call'; /** Provider-issued call id; correlates with the matching tool result. */ id: ToolCallId; name: string; /** Raw JSON string as produced by the model. */ arguments: string; } /** Activates a tool definition from the developer event's referenced request header. */ interface ToolAdditionBlock { type: 'tool-addition'; /** Name of exactly one tool in the referenced historical header. */ toolName: string; /** * Reserved against inline definitions; the historical request header owns the schema. * @persistenceReserved */ tool?: never; } /** Records the dynamic removal of a tool identified by its session-local name. */ interface ToolRemovalBlock { type: 'tool-removal'; toolName: string; } /** * Merge-extensible content blocks keyed by `type`. New core blocks must land * with adapter, UI, and compaction support. Tool-change blocks belong to * developer messages; `projectToolUpdates` selects what each route receives. */ interface ContentBlockMap { 'text': TextBlock; 'reasoning': ReasoningBlock; 'image': ImageBlock; 'file': FileBlock; 'tool-call': ToolCallBlock; 'tool-addition': ToolAdditionBlock; 'tool-removal': ToolRemovalBlock; } /** The block `type` tag vocabulary; widens as plugins add entries to {@link ContentBlockMap}. */ type ContentBlockType = keyof ContentBlockMap; /** Any known content block, derived from {@link ContentBlockMap}; switch on `type` and fall through unknowns (merge-extensible). */ type ContentBlock = ContentBlockMap[ContentBlockType]; /** * Why a model response stopped. * Merge-extensible so adapters can surface provider-specific reasons. */ interface FinishReasonMap { 'stop': { kind: 'stop'; }; 'tool-calls': { kind: 'tool-calls'; }; 'max-tokens': { kind: 'max-tokens'; }; 'aborted': { kind: 'aborted'; failure: LlmFailure; }; 'error': { kind: 'error'; failure: LlmFailure; }; } /** Any known finish reason, derived from {@link FinishReasonMap}; switch on `kind` and fall through unknowns (merge-extensible). */ type FinishReason = FinishReasonMap[keyof FinishReasonMap]; /** * Token accounting for one model call (cache fields are optional). * * Counts are DISJOINT: `inputTokens` is uncached input only; cached input is * reported separately as `cacheReadTokens`/`cacheWriteTokens` (billed input = * sum of the three). Adapters whose providers fold cache hits into a total * prompt count (DeepSeek's `prompt_tokens`) subtract them out. */ interface TokenUsage { inputTokens: number; outputTokens: number; /** * Exact full-call total including aggregate prompt and output tokens. * * Adapters preserve a provider total or derive it from authoritative * aggregate prompt/output counters; they omit it when unavailable or * inconsistent. */ totalTokens?: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number; } /** * Request price of one ordered image occurrence under one exact model route's * request projection. Every occurrence resolves to the pair the wire actually * carries: provider visual tokens for a retained image, plus the model-visible * text sent with or instead of it (request-preview handle, offload placeholder, * or text-only substitution). The caller prices `text` with its own text * estimator so provider pricing never fixes a text tokenization. */ interface LlmImageRequestPrice { /** Provider visual tokens for the retained request image; 0 when only text represents this occurrence. */ visualTokens: number; /** Model-visible text sent for this occurrence, to be priced by the caller's text estimator. */ text: string; } /** * Provider-side request-image pricing for one exact model route. Implemented * by adapters whose provider charges visual tokens; consumers (the token * meter) resolve it synchronously per measurement, so implementations must not * perform I/O. */ interface LlmImageRequestPricing { /** * Price every image occurrence of one request projection. * @param images - surface image blocks in request order, one entry per occurrence; an `offloaded` block * is priced as its placeholder text. * @returns one price per occurrence, aligned by index with `images`. */ priceImages(images: readonly ImageBlock[]): readonly LlmImageRequestPrice[]; } /** Display metadata for one registered provider route. */ interface LlmProviderInfo { /** Provider route key used by {@link GenerateOptions.provider}. */ id: string; /** Human-readable provider name for selectors and diagnostics. */ name: string; } /** Merge-extensible provider model modality vocabulary. */ interface ModelModalityMap { text: 'text'; image: 'image'; } /** Any declared provider model modality. */ type ModelModality = ModelModalityMap[keyof ModelModalityMap]; /** * One provider route an adapter plugin can activate through configuration, * whether or not the route is currently registered. Configuration surfaces * merge this directory with `listProviders()` to offer every configurable * provider alongside its live/dormant state. */ interface LlmConfigurableProvider { /** Provider route key this entry activates when configured. */ provider: string; /** Human-readable provider name for configuration surfaces. */ displayName: string; /** User-settings namespace whose section configures this provider. */ settingsNs: string; /** * Path from that namespace's section root to this provider's profile * object; empty when the whole section is the profile. */ settingsPath: readonly string[]; /** * Whether the owning adapter knows this route only because configuration * declared it — a gateway or self-hosted server it ships nothing about. * Absent means the adapter draws no such distinction; false means it does * and this route is one of its own. Only the adapter can answer: a stored * profile is how a user-added route AND a corrected shipped one both look * from outside. */ declared?: boolean; /** * Route endpoint the adapter uses when the profile sets no `baseURL`; the * adapter may still send an individual model to that model's own endpoint. * Absent when the route has no fixed endpoint. */ defaultBaseURL?: string; /** Environment variables used to construct a provider endpoint; absent when none are reported. */ baseURLEnv?: readonly string[]; /** Authentication the adapter performs when the profile names no credential reference; absent when it reports none. */ nativeAuth?: LlmNativeAuth; /** Configuration diagnostic for repair; unaffected models may remain serviceable. */ error?: string; } /** Authentication a provider route performs without a credential reference in its profile. */ interface LlmNativeAuth { /** Environment variables the route's authentication reads, in lookup order; empty when it reads none. */ env: readonly string[]; /** Whether a stored OAuth sign-in can authenticate the route. */ oauth: boolean; } /** * One interrogation of a provider endpoint that configuration has not stored * yet. Configuration surfaces send the draft a user is still editing, so the * request carries the endpoint and credential directly instead of naming a * route: a provider being added has no route to name. */ interface LlmModelDiscoveryRequest { /** * Route the draft is editing, when it edits an existing one. A route whose * adapter already knows its models answers from that knowledge instead of * asking the endpoint — the adapter's own registry is the better answer, and * it costs no network call. */ provider?: string; /** * Endpoint to interrogate. Optional because a route the adapter already * describes needs none; a route it does not must supply one. */ baseURL?: string; /** Wire protocol the endpoint speaks, when the draft names one. */ api?: string; /** Credential for this interrogation alone; the harness never stores it. */ apiKey?: string; } declare module '@deepseek-ai/dsh-typert-protocol' { interface RemoteErrorDetailsMap { /** A draft provider interrogation refused or failed. */ 'llm/model-discovery-rejected': { readonly settingsNs: string; readonly baseURL?: string; }; } } /** * One model an endpoint reports about itself. Every field but the id is * optional because most provider listings disclose an id and nothing else; * a surface adopting one of these still owes the capacities its adapter needs. */ interface LlmDiscoveredModel { /** Model id the endpoint accepts. */ id: string; /** Human-readable name when the endpoint supplies one. */ name?: string; /** Maximum combined request and response context, when disclosed. */ contextWindow?: number; /** Maximum output tokens, when disclosed. */ maxTokens?: number; /** Accepted input types when disclosed by the catalog or endpoint; absent means unknown. */ inputModalities?: readonly ModelModality[]; } /** One adapter-discovered model; catalog membership is advisory, not request validation. */ interface LlmModelInfo { /** Provider route that owns this model entry. */ provider: string; /** Model id passed to {@link GenerateOptions.model}. */ id: string; /** Human-readable model name for selectors. */ name: string; /** Optional user-facing distinction from otherwise similar models. */ description?: string; /** Accepted request modalities; absent means unknown, while an explicit omission is negative capability. */ inputModalities?: readonly ModelModality[]; } /** Provider-owned context capacity for one exact provider/model route. */ interface LlmModelContext { /** Maximum combined request and response context in tokens. */ contextWindow: number; } /** Display metadata for one adapter-owned reasoning effort. */ interface LlmReasoningEffortInfo { /** Opaque stable value accepted by {@link GenerateOptions.reasoningEffort}. */ id: ReasoningEffortId; /** Human-readable effort name for selectors and diagnostics. */ name: string; /** Optional user-facing distinction from otherwise similar efforts. */ description?: string; } /** Selectable reasoning efforts for one exact provider/model route. */ interface LlmModelReasoningInfo { /** Supported efforts from least to greatest selectable reasoning effort, not predicted token use or latency. */ efforts: readonly LlmReasoningEffortInfo[]; /** * Adapter-configured default materialized into requests when callers omit * an effort. Absence preserves the provider's own default. */ defaultEffort?: ReasoningEffortId; } /** * How a model applies a system prompt that changes mid-conversation. * `'in-history'`: the model reads the latest `system` message at any position * of `messages` as the complete effective system prompt, so a changed prompt * can follow the cached history instead of rewriting message 0. */ type SystemPromptUpdate = 'in-history'; /** * How a model accepts native tool declarations that change mid-conversation. * `'addition-only'`: the model reads a `tool-addition` block in a later * developer message as activating a tool declared with `deferLoading`, so an * added tool follows the cached history instead of rewriting the declaration * list. `'in-history'`: the model additionally reads `tool-removal` blocks, * so a removed tool keeps its declaration and the removal follows the history. * Absent means every request declares the complete current tool list. */ type ToolUpdate = 'in-history' | 'addition-only'; /** Exact-route model metadata resolved by its owning adapter. */ interface LlmResolvedModelInfo extends LlmModelInfo { /** Provider-owned context capacity when known. */ context?: LlmModelContext; /** Adapter-configured per-request output cap materialized when callers omit one. */ defaultMaxTokens?: number; /** Adapter-owned selectable reasoning levels when exposed. */ reasoning?: LlmModelReasoningInfo; /** Declared mid-conversation system prompt handling; absent means only a leading system message is read. */ systemPromptUpdate?: SystemPromptUpdate; /** Declared mid-conversation tool declaration handling; absent means every request declares the complete tool list. */ toolUpdate?: ToolUpdate; } /** * Adapter-private lossless-JSON state for replaying a successful response, * carried by a terminal `finish` chunk and stored on the assembled assistant * message's model source. Both halves stay opaque to the harness; only the * split is shared vocabulary, so assembly can keep stored metadata aligned * with stored content without reading either half. */ interface ReplayEnvelope { /** Response-level adapter-private metadata (ids, native stop reason). */ response: unknown; /** * Per-block adapter-private metadata, one entry per emitted block in * first-seen stream order. When assembly drops a block it drops the entry at * the same position; entries whose length does not match the emitted block * count discard the whole envelope. An adapter whose metadata is independent * of block structure omits this field and the envelope passes through * assembly unchanged. */ blocks?: readonly unknown[]; } /** * Raw streaming protocol emitted by adapters. * Block indexes correlate interleaved deltas, and `block-end` carries the * assembled block. Adapters emit usage before the terminal finish and nothing * afterward; tool arguments remain raw JSON strings. An adapter implementation * may throw, but `LlmRuntime.stream()` normalizes that failure to a terminal * `error` or `aborted` finish before exposing it to consumers. */ type StreamChunk = { type: 'block-start'; index: number; blockType: ContentBlockType; } | { type: 'text-delta'; index: number; text: string; } | { type: 'reasoning-delta'; index: number; text: string; } | { type: 'tool-call-delta'; index: number; id: ToolCallId; name?: string; argumentsDelta: string; } | { type: 'block-end'; index: number; block: ContentBlock; } | { type: 'usage'; usage: TokenUsage; } | { type: 'finish'; reason: FinishReason; /** Replay metadata for a successful response; see {@link ReplayEnvelope}. */ replayState?: ReplayEnvelope; }; /** * JSON-schema description of a tool, as sent to the model. * * Declared here (not in dsh-tools) because it is part of {@link GenerateOptions}; * dsh-tools' ToolDefinition and dsh-system-prompt's PromptAssembly both import * it from this package. */ interface ToolSchema { /** * Requests deferred loading of the tool definition into model context, * independently of whether a tool-addition block records the tool. * Uses Anthropic's defer_loading terminology. */ deferLoading?: true; name: string; description: string; /** JSON Schema object for the arguments. */ parameters: Record; } /** User input for one LLM request; it has no durable Session identity or source. */ interface RequestUserInput { readonly role: 'user'; readonly content: UserMessage['content']; readonly id?: never; readonly source?: never; } /** A durable conversation message or a user input used only for one request. */ type RequestMessage = Message | RequestUserInput; /** Logged tool declarations and update identities since the last declaration reset. */ interface ToolHistory { /** Complete active declarations at the start of this history. */ readonly tools: readonly ToolSchema[]; /** Ordered developer messages, with additions resolved from their historical headers. */ readonly updates: readonly { /** Identity used to locate this update in the derived request history. */ readonly messageId: MessageId; /** Added definitions resolved from the event's referenced request header. */ readonly additions: readonly ToolSchema[]; }[]; } /** A single model request, fully assembled. */ interface GenerateOptions { /** Registered provider route selecting the adapter instance. */ provider: string; model: string; /** Adapter-owned reasoning effort selected for this exact model. */ reasoningEffort?: ReasoningEffortId; /** * Ordered conversation messages, exactly as the provider sees them. A * loop-built request passes the derived history (dsh-agent-loop), whose * leading system-role message carries the system prompt; a hand-built * one-shot may include identity-free user inputs. */ messages: RequestMessage[]; /** * System prompt text for one-shot callers; adapters map it to the provider's * system slot ahead of `messages`. Loop-built requests leave it undefined. */ system?: string; /** Tool schemas (adapters map to the provider's `tools` field). */ tools?: ToolSchema[]; /** Session-folded tool history used for route projection; omission sends complete declarations without tool updates. */ toolHistory?: ToolHistory; temperature?: number; maxTokens?: number; /** * Stop sequences: generation halts as soon as the model produces any one of * these strings (adapters map to the provider's stop field, e.g. OpenAI * `stop`). The stop string itself is not included in the output. */ stop?: string[]; signal?: AbortSignal; /** * Session identity stamped by the loop for request routing. Replay uses it * to separate cursors; adapters may map it to model-hidden transport metadata. */ sessionId?: Branded<'SessionId'>; /** * Provider-neutral classification for an auxiliary model call. Adapters may * map the purpose to model-hidden transport metadata. Ordinary conversation * requests leave it unset. */ purpose?: 'compaction' | 'session-title'; } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/retry-policy.d.ts /** Fully resolved backoff shared by both retry modes. */ interface ResolvedRetryBackoff { readonly initialDelayMs: number; readonly maxDelayMs: number; readonly jitterRatio: number; } /** Fully resolved bounded transient retry policy. */ interface ResolvedNormalRetryPolicy extends ResolvedRetryBackoff { readonly mode: 'normal'; readonly maxRetries: number; readonly retryableCodes: readonly string[]; } /** Fully resolved unbounded retry policy. */ interface ResolvedAlwaysRetryPolicy extends ResolvedRetryBackoff { readonly mode: 'always'; } /** Immutable provider policy captured when its adapter route is registered. */ type ResolvedRetryPolicy = ResolvedNormalRetryPolicy | ResolvedAlwaysRetryPolicy; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/call-config.d.ts /** Concrete generation settings; omitted controls use the selected route's defaults. */ interface LlmCallControls { reasoningEffort?: ReasoningEffortId; temperature?: number; maxTokens?: number; stop?: string[]; } /** * Provider, model, reasoning effort, and sampling scalars of one conversation's * requests. Every field maps 1:1 onto the same-named `GenerateOptions` field; * the loop builds requests from the logged header rather than accepting these * per call. */ interface LlmCallConfig extends LlmCallControls { provider: string; model: string; } /** * Synchronous, pure configuration of one call before defaults and validation. * Compose functions in the desired order; later writes replace earlier ones. * The returned controls cannot change the captured route. Errors reject * preparation before dispatch; only the resolved configuration is recordable. * @param controls - detached, deeply frozen proposed controls, without defaults. * @param model - detached, deeply frozen metadata from the captured adapter generation. * @returns concrete controls; omitted fields receive the route's defaults. */ type ConfigureCall = (controls: Readonly, model: Readonly) => LlmCallControls; /** * Effective config fields supplied by exact-model adapter resolution rather * than by the caller's request proposal. */ interface LlmCallConfigAdapterDefaults { reasoningEffort?: true; maxTokens?: true; } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/assistant-stream.d.ts /** Lossless compact records embedded in durable Assistant attempt events. */ type AssistantStreamRecord = { readonly type: 'text-chunks'; readonly time0: number; readonly index: number; readonly dt: readonly number[]; readonly texts: readonly string[]; } | { readonly type: 'reasoning-chunks'; readonly time0: number; readonly index: number; readonly dt: readonly number[]; readonly texts: readonly string[]; } | { readonly type: 'tool-call-chunks'; readonly time0: number; readonly index: number; readonly dt: readonly number[]; readonly id: ToolCallId; readonly name?: string; readonly args: readonly string[]; } | { readonly type: 'chunk'; readonly time: number; readonly chunk: StreamChunk; }; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-llm@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-llm/lib/types/index.d.ts declare module '@deepseek-ai/cordis' { interface Context { llm: LlmRuntime; } interface Events { /** * Waterfall around every streaming model call (retry, replay, routing). * Bound to the {@link LlmRuntime}; call `next()` to reach the resolved * adapter's stream, or yield your own chunks to short-circuit. * @param options - the full request. A LOOP-built request carries the * process-local {@link markAgentLoopRequest} identity and arrives deep-frozen * (mutation throws): its content is a pure function of the session log (the * reconstructability Agent Note), so listeners read it, never rewrite it. * Hand-built calls do not carry that marker; callers own their request * inputs and must keep them unchanged until the stream settles. * @mode waterfall */ 'llm/stream'(this: LlmRuntime, options: GenerateOptions, next: () => AsyncIterable): AsyncIterable; } } /** One model call whose config and adapter registration were resolved together. */ interface PreparedLlmCall { /** Detached, deep-frozen config with any adapter-owned default materialized. */ readonly config: LlmCallConfig; /** Immutable retry policy captured with the adapter registration. */ readonly retryPolicy: ResolvedRetryPolicy; /** Detached context metadata resolved with the registration-bound call. */ readonly context?: LlmModelContext; /** Exact model modalities captured with the adapter dispatch generation. */ readonly inputModalities?: readonly ModelModality[]; /** Exact model system prompt update mode captured with the adapter dispatch generation. */ readonly systemPromptUpdate?: SystemPromptUpdate; /** Exact model tool update mode captured with the adapter dispatch generation. */ readonly toolUpdate?: ToolUpdate; /** Config fields materialized by the captured adapter rather than proposed by the caller. */ readonly adapterDefaults: LlmCallConfigAdapterDefaults; /** * Dispatch this call once through the registration captured during * preparation. The request's call-config fields must match {@link config}; * reuse or mismatch fails with `INVALID_PREPARED_CALL`. * @param options - fully assembled request carrying the prepared config. * @returns the chunk stream, including the `llm/stream` waterfall. */ stream(options: GenerateOptions): AsyncIterable; } /** One adapter-owned model-resolution generation bound to its eventual stream call. */ interface PreparedAdapterCall { /** Exact model metadata from the same adapter generation as {@link stream}. */ readonly model: LlmResolvedModelInfo; /** Dispatch through that generation without re-reading dynamic connection facts. */ stream(options: GenerateOptions): AsyncIterable; } /** * Provider-wire adapter for the harness message and stream vocabulary. Register implementations * with `ctx.llm.registerAdapter(providers, adapter)`. Every provider HTTP request must include * `attributionHeaders()`; prove the headers are added in the wire request or library header hook. The direct-fetch * DeepSeek and library-backed pi-ai adapters meet this contract through different internals. */ declare abstract class LlmAdapter { /** * Describe one provider route owned by this adapter. * @param provider - a route passed to `registerAdapter()` for this instance. * @returns detached display metadata whose id must equal `provider`. */ providerInfo(provider: string): LlmProviderInfo; /** * Return the provider-owned retry policy captured with this route. * @param _provider - a route passed to `registerAdapter()` for this instance. * @returns a resolved policy, or `undefined` to use the normal defaults. */ providerRetryPolicy(_provider: string): ResolvedRetryPolicy | undefined; /** * Resolve provider-side request-image pricing for one exact model route. * The default declares none, so consumers fall back to their own neutral * estimate. Implementations must answer synchronously without I/O; the * token meter resolves this per measurement. * @param _provider - a route passed to `registerAdapter()` for this instance. * @param _model - exact model id passed to {@link GenerateOptions.model}. * @returns route-owned image pricing, or `undefined` when the route declares none. */ imageRequestPricing(_provider: string, _model: string): LlmImageRequestPricing | undefined; /** * Resolve the image dimensions and byte target this adapter sends to the model. * The default preserves normalized images; adapters that resize must override it. * @param _provider - registered provider route. * @param _model - exact model id. * @param image - normalized image whose request projection is being resolved. * @returns the same target used by request serialization, before provider-internal processing. */ imageRequestTarget(_provider: string, _model: string, image: ImageAttachmentRef): ImageRequestTarget; /** * List models this adapter can currently advertise for one owned provider. * Core routing accepts unlisted model ids; catalog-driven entry points such * as the GUI may require membership. Adapters used there must advertise * their available models; the base empty catalog offers no GUI selection. * @param _provider - one provider route owned by this adapter. * @returns discoverable models in adapter-preferred order. */ listModels(_provider: string): Promise; /** * Resolve all metadata available for one exact model. This query is * independent of the advisory catalog and does not validate request routing. * @param provider - one provider route owned by this adapter. * @param model - exact model id passed to {@link GenerateOptions.model}. * @param _signal - cancellation for this exact-model lookup; asynchronous * implementations must settle promptly after it aborts. * @returns provider/model identity plus any context, call-default, and reasoning metadata. */ resolveModel(provider: string, model: string, _signal?: AbortSignal): Promise; /** * Bind exact model metadata and the eventual request dispatch to one adapter generation. * Dynamic adapters override this so settings changes between preparation and * dispatch cannot combine one generation's capabilities with another's endpoint. * @param provider - registered provider route. * @param model - exact model id. * @param signal - cancellation for model resolution. * @returns model metadata and a one-generation stream entry point. */ prepareCall(provider: string, model: string, signal?: AbortSignal): Promise; /** * Stream one model call as raw chunks. The only required method. * @param options - the fully-assembled request; implementations must honor `options.signal`. * @returns the chunk stream, obeying the adapter contract documented on `StreamChunk`. */ abstract stream(options: GenerateOptions): AsyncIterable; } /** * What {@link LlmRuntime.registerAdapter} returns: the disposer, plus an * atomic route replacement for the same adapter instance. */ interface AdapterRegistrationHandle { /** Release every route this registration currently holds. */ (): void; /** * Replace this registration's routes with `providers`, keeping the same * adapter instance. The candidate set is validated in full first — a * conflict with another adapter, an invalid name, or bad provider metadata * throws and leaves the current routes untouched — and the swap itself is * one synchronous section, so no request can observe a gap. An empty array * is legal here (a settings section that emptied holds zero routes while * staying registered), unlike an empty initial registration. * * Throws `LlmError` with code `REGISTRATION_DISPOSED` once the registration * has been released: its routes are gone and its disposer has already run, * so anything registered afterwards would have no owner left to release it. * @param providers - the complete next route set for this registration. */ replace(providers: string[]): void; } /** * A live configurable-provider registration, disposable and atomically * replaceable — the directory counterpart of {@link AdapterRegistrationHandle}. */ interface DirectoryRegistrationHandle { /** Withdraw every entry this registration currently holds. */ (): void; /** * Replace this registration's entries with `entries`. The candidate set is * validated in full first — an entry another registration already declares, * a duplicate within the set, or invalid metadata throws and leaves the * current entries untouched — and the swap is one synchronous section, so no * reader observes a gap. An empty array is legal here, unlike an empty * initial registration. * * Throws `LlmError` with code `REGISTRATION_DISPOSED` once the registration * has been disposed. */ replace(entries: readonly LlmConfigurableProvider[]): void; } /** * The abstract `llm` service: an adapter registry plus a streaming model-call * API, interceptable via the `llm/stream` waterfall. */ declare class LlmRuntime extends TypertRemoteService { private adapters; private directory; private discoveries; constructor(ctx: Context); /** Notify topology observers without letting one broken listener veto the commit. */ private emitAdaptersUpdated; /** Contained-listener diagnostic shared by the sync and async failure paths. */ private warnAdaptersListenerFailure; /** * Register an adapter for the given provider routes. Throws `LlmError` with code * `DUPLICATE_ADAPTER` if any provider already has an adapter (all-or-nothing). * Disposed with the fiber. * @param providers - every provider route this adapter should serve. * @param adapter - the adapter that streams calls for those providers. * @returns the disposer, carrying {@link AdapterRegistrationHandle.replace}. */ registerAdapter(providers: string[], adapter: LlmAdapter): AdapterRegistrationHandle; /** * Validate one candidate route set for `adapter`, treating routes this * registration already holds as available. Nothing is mutated: a rejected * candidate leaves the registry exactly as it was. */ private prepareRoutes; /** * Swap this registration's routes for the prepared ones in one synchronous * section, so no observer can see the registry between the release and the * re-registration. The route set's one mutation point is also where * `llm/adapters-updated` is published, so a `replace` announces itself * exactly like a first registration. */ private commitRoutes; /** * Describe provider routes with a registered adapter. * @returns detached provider metadata in registration order. */ listProviders(): LlmProviderInfo[]; /** * Declare provider routes an adapter plugin can activate through * configuration. Registration is all-or-nothing: an empty list, invalid * entry, or a provider already declared by any registration throws * `LlmError` without registering the rest. Disposed with the fiber. * @param entries - every configurable provider this plugin owns. * @returns a handle that withdraws all of them, and can atomically replace them. */ registerConfigurableProviders(entries: readonly LlmConfigurableProvider[]): DirectoryRegistrationHandle; /** * List every declared configurable provider, registered or dormant. * @returns detached directory entries in declaration order. */ listConfigurableProviders(): LlmConfigurableProvider[]; /** * Offer to interrogate provider endpoints on behalf of the settings * namespace this plugin owns. The namespace is the key because that is what * a configuration surface already holds from the configurable-provider * directory, and because a provider being *added* has no route to name yet. * Disposed with the fiber. * @param settingsNs - the namespace whose profiles this discovery serves. * @param discover - interrogates one endpoint and must honor the supplied signal. * @returns the disposer that withdraws the offer. */ registerModelDiscovery(settingsNs: string, discover: (request: LlmModelDiscoveryRequest, signal?: AbortSignal) => Promise): () => void; /** * Interrogate one provider endpoint for the models it advertises. The * request describes a draft, not a stored route, so nothing here reads or * writes settings or credentials — the caller owns both, and the reply is * candidate metadata a surface may offer for adoption. * @param settingsNs - namespace whose registered discovery serves this draft. * @param request - the endpoint, protocol, and one-shot credential to use. * @param signal - caller cancellation. * @returns the advertised models, deduplicated in endpoint order. */ discoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal?: AbortSignal): Promise; /** * Remote adapter for one draft provider interrogation. * @param settingsNs - namespace whose registered discovery serves this draft. * @param request - endpoint, protocol, and one-shot credential to use. * @param signal - caller cancellation supplied by the Remote carrier. * @returns advertised models in endpoint order. * @throws RemoteError with `llm/model-discovery-rejected` when discovery refuses or fails. */ remoteDiscoverModels(settingsNs: string, request: LlmModelDiscoveryRequest, signal: AbortSignal): Promise; /** * Resolve the retry policy captured when one provider route was registered. * @param provider - registered provider route to inspect. * @returns the provider-owned policy, with normal defaults already resolved. */ providerRetryPolicy(provider: string): ResolvedRetryPolicy; /** * Resolve provider-side request-image pricing for one exact route, or * `undefined` when the provider is unregistered or declares none. Unknown * providers degrade to `undefined` rather than throwing because callers * price durable history whose route may no longer be mounted. * @param provider - provider route named by a request header. * @param model - exact model id named by the same header. * @returns the owning adapter's image pricing for the route, when declared. */ imageRequestPricing(provider: string, model: string): LlmImageRequestPricing | undefined; /** * Resolve the image projection for an exact registered model route. * @param provider - registered provider route. * @param model - exact model id. * @param image - normalized image reference. * @returns dimensions and byte target used by the adapter's request serializer. */ imageRequestTarget(provider: string, model: string, image: ImageAttachmentRef): ImageRequestTarget; /** * Resolve the exact text one durable file occurrence contributes to every * provider request in the current execution environment. * @param ref - durable verbatim file reference from model history. * @returns the same deterministic handle text used at adapter dispatch. */ fileRequestText(ref: FileAttachmentRef): string; /** Detach typed adapter-owned modality metadata. */ private detachedModalities; /** * Discover models advertised by one registered provider. Catalog membership * does not constrain core routing. Catalog-driven entry points may restrict * selection and submission to the advertised models. * @param provider - registered provider route to inspect. * @returns detached model metadata in adapter-preferred order. */ listModels(provider: string): Promise; /** * Resolve and validate all metadata from the adapter that owns one exact * route. The result is detached from adapter-owned objects; catalog * membership remains advisory and does not control request routing. * @param provider - registered provider route to inspect. * @param model - exact model id passed to the adapter. * @param signal - optional cancellation for adapter-owned asynchronous lookup. * @returns exact model identity plus available context and reasoning metadata. */ resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise; private resolveModelInfoFor; /** Validate and detach one adapter-returned exact model result. */ private normalizeModelInfo; /** * Validate a conversation call config against its exact model capability and * materialize adapter-configured defaults. Unsupported explicit efforts * reject before provider I/O; no clamping or aliasing is performed. This * standalone query does not bind a later dispatch; use {@link prepareCall} * when logging and streaming must share one adapter registration. * @param config - provider/model route and optional request controls. * @param signal - optional cancellation for adapter-owned capability lookup. * @returns a detached config only when a default must be materialized. */ resolveCallConfig(config: LlmCallConfig, signal?: AbortSignal): Promise; private resolveCallFor; /** Validate request controls against one already-bound exact model result. */ private resolveCallWithInfo; /** * Resolve one call under its current adapter registration. The returned * one-shot handle keeps that registration across header logging and dispatch, * so HMR cannot combine one adapter's capability result with another adapter. * An optional synchronous callback selects concrete controls using captured * model metadata. Defaults and validation apply to its result. Callback * failures and cancellation reject preparation before dispatch. * @param config - provider/model route and optional concrete request controls. * @param signal - optional cancellation for adapter-owned capability lookup. * @param configure - pure control selection, called once before defaults and validation. * @returns a prepared config and its registration-bound stream entry point. */ prepareCall(config: LlmCallConfig, signal?: AbortSignal, configure?: ConfigureCall): Promise; private registration; /** Remove replay state whose historical route is owned by another adapter. */ private forAdapter; /** * Resolve the current execution-world read path of one durable file * reference through the mounted attachment and filesystem providers. */ private fileReadPath; /** * Final adapter boundary. Adapter selection, dispatch, iterator construction, * and iteration failures become one terminal failure chunk. Middleware and * downstream consumer failures remain thrown plugin or consumer errors. */ private adapterStream; /** * Stream one model call as raw chunks (token-level deltas). Replay state is * retained only when the same adapter instance owns its historical provider * and the target provider. Final adapter selection remains fixed through * asynchronous exact-model resolution and dispatch. Adapter selection, * dispatch, and iteration failures become terminal `error` or `aborted` * finish chunks; middleware, nested-call, cleanup, and consumer failures * remain thrown. * @param options - the full request; `options.provider` selects the adapter. * @returns the chunk stream, possibly wrapped by `llm/stream` listeners. */ stream(options: GenerateOptions): AsyncIterable; private streamWithRegistration; } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-util-values@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5/node_modules/@deepseek-ai/dsh-util-values/lib/types/index.d.ts /** Duplicate-install-safe JSON and immutable-value helpers. @module @deepseek-ai/dsh-util-values */ /** A value that round-trips through JSON without loss. */ type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue; }; //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-session@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5_@deepseek-ai+dsh-scope@0._f72072f8db4331da4f9afb922400d5de/node_modules/@deepseek-ai/dsh-session/lib/types/types.d.ts /** Identifies one session in the store (and its persistence artifacts). */ type SessionId = Branded<'SessionId'>; /** * Brand a string as a {@link SessionId}. * @param id - the raw session id string. * @returns the same string with the session-id brand. */ declare function SessionId(id: string): SessionId; /** Sequence number of one existing event in a Session log. */ type SessionSeq = BrandedNumber<'SessionSeq'>; /** * Admit a numeric value as an existing Session event position. * @param value - non-negative safe integer admitted by the owning log operation. * @returns the same number with the Session-sequence brand. */ declare function SessionSeq(value: number): SessionSeq; /** A Session log gap, prefix length, or read offset, which may equal the event count. */ type SessionLogOffset = BrandedNumber<'SessionLogOffset'>; /** * Admit a numeric value as a Session log offset. * @param value - non-negative safe integer used as a gap or prefix length. * @returns the same number with the Session-log-offset brand. */ declare function SessionLogOffset(value: number): SessionLogOffset; /** * Current logical Session format version, stamped into every newly written * {@link SessionHeader}. Current Session and persistence code accept only this * value; header-only readers classify supported historical formats, while an * event-body read composes the build-static adjacent chain and publishes only * this final generation before constructing a Session. * * The version is a single monotonic integer with no major/minor split. Retain * it when older readers resume correctly, preserve safely ignorable records, * or refuse required features before execution, mutation, or tail repair. * New readers must preserve historical meanings, including logs mixing old * and new record representations. Bump when an existing discriminator cannot * prevent unsafe interpretation; a structural difference alone is insufficient. * Unknown fields and values require evidence of the released reader's actual * admission behavior. The per-event {@link SessionEvent.ignorable} marker * governs unknown event types, not arbitrary nested payload changes. * Same-version readers retain earlier representations: the adjacent migration * chain does not run when stored and current versions match. A subsequent * migration must account for all supported representations of its source. * Compatibility review and the retained migration obligations are recorded in * `.agents/notes/implemented/process/2026-10-08-session-reader-compatibility-review.md`. */ declare const SESSION_FORMAT_VERSION = 4; /** * Immutable validated storage metadata, kept outside the conversation event log. */ interface SessionHeader { /** * Current logical format version, stamped from {@link SESSION_FORMAT_VERSION}. * Historical physical headers are translated before entering this interface. */ readonly version: typeof SESSION_FORMAT_VERSION; /** The session's id (mirrors the {@link Session}'s id). */ readonly id: SessionId; /** Non-negative safe-integer Unix epoch milliseconds when the session was created. */ readonly createdAt: number; /** Absolute working directory the session was created in (if any). */ readonly cwd?: string; /** The session this one was forked from (seed lineage), if any. */ readonly parentSession?: SessionId; /** * Whether this Session contains a fork-inherited event prefix. The exact prefix * length is Session state rather than ordinary header metadata. */ readonly isSeeded: boolean; /** * Coarse product classification for a session created as a subagent child. * This is presentation metadata, not proof that the child is continuable. */ readonly origin?: 'subagent'; /** * Delegation depth: absent (zero) for a top-level session, parent depth + 1 * for a subagent child. Persisted so a recursion budget survives restart and * resume — a runtime-only depth would reset a resumed child to top-level. */ readonly delegationDepth?: number; /** * Id of the agent preset this session's agent was composed from, when the * deployment composes per session. Durable because the preset decides the * session's tools and prompt: a resume that restored a different composition * would replay history the model can no longer act on. */ readonly agentPreset?: string; } /** * Options for creating a {@link Session} via the store. `seed` replays/forks * an existing event log; `meta` carries the caller-supplied storage fields the * store folds into a {@link SessionHeader}. */ interface CreateSessionOptions { /** Initial replay or fork history supplied at construction. */ readonly seed?: readonly SessionEvent[]; /** * Exact fork-inherited prefix length when `meta.isSeeded` is true. The * constructor appends the child-owned tagged marker at the cut unless * the seed already includes it followed by child-owned fork closers. */ readonly inheritedEventCount?: SessionLogOffset; /** * Storage metadata read once before publication. `isSeeded` marks fork * lineage; supplying replay history alone does not make it inherited. */ readonly meta?: { readonly cwd?: string; readonly parentSession?: SessionId; readonly createdAt?: number; readonly isSeeded?: boolean; readonly origin?: 'subagent'; readonly delegationDepth?: number; readonly agentPreset?: string; }; } /** * Aliasing state of an adoptable Session seed. `shared-frozen` permits deeply * frozen aliases plus independently owned unfrozen values in the same seed. */ type SessionSeedEventState = 'detached' | 'shared-frozen'; /** * Adoptable storage values transferred to {@link SessionStore.prepare} * without another copy or freeze pass. */ interface RestoredSessionOptions { /** Events that are independently owned or already deeply frozen. */ readonly seed: SessionEvent[]; /** Independently owned storage metadata to validate and freeze in place. */ readonly meta: SessionHeader; /** Exact number of fork-inherited leading events decoded from storage. */ readonly inheritedEventCount: SessionLogOffset; /** Aliasing state carried from the operation that produced the seed. */ readonly eventState: SessionSeedEventState; } /** Inputs accepted while constructing an unpublished Session. */ type PrepareSessionOptions = (CreateSessionOptions & { readonly eventState?: undefined; }) | RestoredSessionOptions; /** Why an active agent driver was cancelled. */ type AgentCancelCause = { readonly kind: 'user'; } | { readonly kind: 'parent'; } | { readonly kind: 'hook'; readonly reason: string; } | { readonly kind: 'disposed'; }; /** Durable cancellation cause, including imports whose original coarse record carried no cause. */ type TurnEndCancelCause = AgentCancelCause | { readonly kind: 'legacy'; }; /** * Why a turn ended. Merge-extensible sum type. */ interface TurnEndReasonMap { completed: { kind: 'completed'; }; /** A cancellation request interrupted the live turn. */ aborted: { kind: 'aborted'; reason: TurnEndCancelCause; }; blocked: { kind: 'blocked'; }; /** * The turn failed. `error` is always a structured failure: the `LlmError` * facts verbatim, or `{ message: errorChain(error), code: 'UNKNOWN' }` * flattened from any other error. */ error: { kind: 'error'; error: LlmFailure; }; /** At least one step reached its output-token ceiling, even if a plugin continued the turn. */ 'max-tokens': { kind: 'max-tokens'; }; /** * A crash-orphaned turn was closed after the fact: agent-loop resume appends * this closer for a stored log whose last turn never ended, and session-query * synthesizes it on cold reads. The loop never emits this marker live, and * the events recorded before the crash remain intact. */ interrupted: { kind: 'interrupted'; }; /** * Fork-seed construction closed a turn that was still open at the fork * boundary in the source session. Only fork seeds carry this marker — the * loop never emits it — and the source events before the boundary remain * intact in the child. */ forked: { kind: 'forked'; }; } /** The union over {@link TurnEndReasonMap} — why a turn ended; plugins extend it by merging variants into the map. */ type TurnEndReason = TurnEndReasonMap[keyof TurnEndReasonMap]; /** * Logged request state outside derived history: call config and tools. The * system prompt is derived history — surface node 0, a `system/message` event. * The latest full `request/header` snapshot reconstructs the header; canonical * empty optional fields are absent. */ interface EpochHeader { /** The conversation's call configuration (provider, model, reasoning effort, and sampling scalars). */ config: LlmCallConfig; /** Effective config fields materialized from the exact adapter rather than proposed by a caller. */ adapterDefaults?: LlmCallConfigAdapterDefaults; /** Assembled tool schemas; absent for a tool-less request. */ tools?: ToolSchema[]; /** Retired request text; system prompts belong to system/message events. * @persistenceReserved */ system?: never; } /** Registration-bound metadata for one resolved model route. */ interface RequestContext { /** Registered provider route the metadata belongs to. */ provider: string; /** Provider-owned model id the metadata belongs to. */ model: string; /** Maximum combined request and response context in tokens, when advertised. */ contextWindow?: number; /** `'in-history'` when the route reads the latest `system` message at any position as the effective system prompt. */ systemPromptUpdate?: SystemPromptUpdate; } /** * Why a `request/header` snapshot was appended: `'initial'` — the log's first * header (a new conversation); `'resume'` — a loop instance's first request * over a log that already has header events (process restart, fork seed); * `'change'` — a later request used a different header; `'series'` — an unchanged * header began an explicitly distinct message series or followed a surface * replacement. Other reasons carry `startsSeries` when a new series coincides. */ type RequestHeaderReason = 'initial' | 'resume' | 'change' | 'series'; /** * The merge-extensible, append-only source of truth for an agent interaction. * Message history is derived from this log. Every event is lossless JSON and * sequence numbers stay contiguous. Assistant attempt events embed their exact * compact raw streams so persistence stores one durable settlement per attempt. */ interface SessionEventMap { /** * Opens turn `turn` before the loop claims queued input or runs pre-step. * Rejection, empty input, cancellation, or failure may close it with no * step; otherwise the following identified `user/message` event or batch * records the messages entering the step. */ 'turn/start': { turn: number; }; /** * Closes turn `turn` with the {@link TurnEndReason} that ended it. A turn * with no entered step has no `step/start` or `step/end`. The loop does not await a * flush at turn boundaries: `dsh-session-checkpoint-policy` owns the * per-request durability checkpoint, and consumers that read storage after * `whenIdle()` flush themselves. Success commits the turn; rejection is * reported live and does not prevent later work. */ 'turn/end': { turn: number; reason: TurnEndReason; }; /** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */ 'step/start': { turn: number; step: number; }; /** Closes step `step` of turn `turn`. */ 'step/end': { turn: number; step: number; }; /** * A user-role message on the model-visible surface: a direct human prompt * (the queued message claimed for this turn), a synthetic `agent.inject()` * context (file-change notices, subdir AGENTS.md, skill content, cron * notifications, …), or an entered goal continuation round. All three * project their `content` verbatim; `source` tells them apart. */ 'user/message': UserMessage; /** An incremental agent session change admitted at the named turn and step. */ 'developer/message': { turn: number; step: number; message: DeveloperMessage; /** Earlier request/header defining every tool addition; required exactly when additions are present. */ headerSeq?: SessionSeq; }; /** * The rendered system prompt on the model-visible surface. The loop appends * the first one as surface node 0 before the step's first `user/message`. * A prepared in-history route can append nonempty changes in a continuing * series. An incapable route or new series normalizes text to the first system * node. Normalization empties nonempty later nodes, then rewrites the head if * needed, through logged per-node replacements. An empty rendering always * clears all active system nodes, leaving no older instructions model-visible. * Empty later nodes are dormant and project to no message; an empty head with * no active later node records "no system prompt". Restored nonempty text follows * the same route and series rule; empty nodes never restore older text. */ 'system/message': { turn: number; step: number; message: SystemMessage; }; /** * Assembled assistant message for one step (derived history uses this). * Carries the step's `usage` when the adapter reported token accounting, so * the model output and its accounting travel together (there is no separate * usage record). `usage` is absent when the adapter reported none. A turn * cancelled mid-stream finalizes its delivered text/reasoning prefix as this * event with `interrupted: true`; undispatched tool calls are absent. The * marker distinguishes that prefix without re-deriving interruption from turn * boundaries. An aborted turn with no such event streamed no visible content. */ 'assistant/message': { turn: number; step: number; message: AssistantMessage; /** Exact timed model stream, compacted without joining delta boundaries. */ stream: AssistantStreamRecord[]; usage?: TokenUsage; interrupted?: true; }; /** * One model attempt that committed no surface message. The embedded stream * preserves a failed, retried, cancelled, or stream-error attempt that * reached settlement without fabricating model-visible history. */ 'assistant/attempt': { turn: number; step: number; stream: AssistantStreamRecord[]; }; /** * The model requested one tool invocation: `name` with the raw `arguments` * JSON string exactly as the model produced it (unparsed). `callId` pairs the * call with its `tool/result`. */ 'tool/call': { turn: number; step: number; callId: ToolCallId; name: string; arguments: string; }; /** * A completed tool call's model-facing result, optional internal failure * identity and user-facing reason, and optional tool-private `meta` * presentation payload. The reason remains outside the model-facing message. * `meta` is * opaque to the core (the producing tool owns its shape and reads it back in * `presentResult`) but MUST be JSON-serializable: `Session.append` * runtime-validates all event data with `isJsonValue`, so a non-serializable * `meta` is rejected at the source, and the durable log reproduces the * identical card on replay. Absent * unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time * contextual diff here). */ 'tool/result': { turn: number; step: number; message: ToolResultMessage; /** * Optional failure identity and raw user-facing reason, outside model content; * allowed only when the message has `isError: true`. */ error?: { name: string; code: string; reason?: string; }; meta?: JsonValue; }; /** * Full header for the next request, appended inside its step before dispatch. * It is log-only; the latest snapshot reconstructs the request header. */ 'request/header': { header: EpochHeader; reason: RequestHeaderReason; /** This request begins a distinct model-message series, independently of the header reason. */ startsSeries?: true; }; /** * Route metadata for the next request, logged only when the route, capacity, * or system prompt update mode changes. It does not participate in request * reconstruction or header equality. Prompt admission uses the bound prepared * call's capability, not this snapshot from an earlier request. */ 'request/context': RequestContext; /** * Separates inherited or restored history from later lifecycle-owned work. * This log-only marker need not be at {@link Session.firstLiveSeq}: a fork * seed can already contain its tagged marker and child-owned synthetic * closers before construction. * * A fresh fork child owns one `{ inherited: true }` marker at its exact * inherited-prefix cut, even when that prefix ends in an ancestor marker. * `buildForkSeed` appends that marker before any synthetic closers; the * `Session` constructor supplies it when given only the inherited prefix. * The last tagged marker is the current Session's cut; untagged markers * keep ordinary restore and replay lifecycle boundaries. * * Only the `Session` constructor and `buildForkSeed` may create this marker. * Session append does not reject other writers, so a plugin appending one * would silently classify every live bracket before it as seed history. * * An owner of a standalone open/close bracket (`compaction/start` … * `compaction/end`) reads it because seed history and live work are otherwise * byte-identical: an unmatched opening marker before this event belongs to * an ended lifecycle, whatever ended it. NOT a liveness signal about other * writers — a concurrently live session holds its own boundary elsewhere, * so tolerating concurrent writers needs a signal beyond the log. */ 'session/end-seed': { inherited?: true; }; } /** The appendable event-type keys of {@link SessionEventMap}, plugin-merged extensions included. */ type SessionEventType = keyof SessionEventMap; /** * The subset of {@link SessionEventType} values whose events produce LLM * messages and are eligible to appear on the ordered surface. Only these * event types may carry {@link SurfaceOp}; system, user, and tool events may also cite * earlier sources through {@link SessionEvent.sourceEventSeqs}. */ type SurfaceEventType = 'system/message' | 'developer/message' | 'user/message' | 'assistant/message' | 'tool/result'; /** * How a session event entered the ordered surface. Only valid on * {@link SurfaceEventType} events. * * - `'append'`: added to the tail — normal path for user/assistant/tool * messages. * - `{ op: 'replace', startSeq, endSeq }`: replaces surface nodes from `startSeq` * (inclusive) through `endSeq` (inclusive) with this node. Both must exist as * surface nodes in the current surface. `startSeq === endSeq` replaces a single * node. The node's {@link SessionEvent.sourceEventSeqs} must include every * shadowed surface node. Used by compaction; any surface-replacing producer * may use it. */ type SurfaceOp = 'append' | { op: 'replace'; startSeq: SessionSeq; endSeq: SessionSeq; }; /** * Surface placement and cited source-event seqs for {@link Session.append}. Required on * message-producing events and forbidden on log-only events. */ type SurfaceIntent = { surfaceOp: SurfaceOp; } & (T extends 'assistant/message' ? { /** Assistant messages embed their provider stream instead of citing source events. */ sourceEventSeqs?: never; } : { /** Complete non-empty set of known earlier source-event seqs. */ sourceEventSeqs?: SessionSeq[]; }); /** * One immutable entry in the session log. * * A proper discriminated union over `type` (not independent `type`/`data` * unions), so `switch (event.type)` narrows `event.data` without casts. * * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional: * they only exist on {@link SurfaceEventType} variants (`system/message`, `user/message`, * `assistant/message`, `tool/result`). * Non-surface events (boundary markers, attempts, errors) never carry * surface metadata — the compiler enforces this at `Session.append()` * call sites. */ type SessionEvent = { [K in SessionEventType]: { type: K; /** Monotonic sequence number within the session. */ seq: SessionSeq; /** Unix epoch milliseconds. */ time: number; data: SessionEventMap[K]; /** * Marks an event a reader may safely skip when it does not recognize * `type`. Absent means required: a reader meeting an unrecognized type * without this marker MUST refuse to reconstruct the session instead of * silently dropping the event, because an unrecognized required event may * change how the rest of the log is interpreted. A writer sets `true` only * on purely informational records whose loss cannot affect reconstruction; * defaulting to required means a forgotten marker over-refuses (an * inconvenience) rather than silently resuming a gutted session. */ ignorable?: true; } & (K extends SurfaceEventType ? SurfaceIntent : { surfaceOp?: never; sourceEventSeqs?: never; }); }[T]; declare module '@deepseek-ai/dsh-typert-protocol' { interface TypertResourceMap { /** One Session; the Session Controller registers its default `sessionId` wire field. */ session: TypertResource; } interface RemoteErrorDetailsMap { /** The named Session does not exist; produced by every layer that resolves a SessionId. */ 'session/not-found': { readonly sessionId: SessionId; }; } } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-session@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5_@deepseek-ai+dsh-scope@0._f72072f8db4331da4f9afb922400d5de/node_modules/@deepseek-ai/dsh-session/lib/types/surface.d.ts /** Readonly history immediately before a message-projection event. */ interface SessionMessageProjectionContext { /** Current message-producing event sequences in model-visible order. */ nodes: readonly SessionSeq[]; /** Contiguous event window; entries at or beyond the candidate seq are not committed inputs. */ events: readonly SessionEvent[]; /** Absolute sequence of the window's first event. */ baseSeq: SessionLogOffset; /** Previously projected messages keyed by their original event sequences. */ messages: ReadonlyMap; } /** Pure interpretation of one plugin-owned event that changes existing message content. */ interface SessionMessageProjection { /** Event interpreted by this definition; declare it with `@messageProjection` in SessionEventMap. */ type: T; /** * Validate the complete durable decision before returning any updates. Preserve * message identities and publish immutable copies without mutating the input. * @param event - candidate event, not yet applied to the supplied history. * @param context - history preceding this decision. * @returns changed current messages keyed by their original sequences. * @throws when the durable decision cannot be applied to this history. */ project(event: SessionEvent, context: SessionMessageProjectionContext): ReadonlyMap; } /** Readonly live projection of the message-producing session events. */ interface SessionSurface { /** Current surface event sequences in model-visible order. */ readonly nodes: readonly SessionSeq[]; /** Monotonic count of committed positional replacements. */ readonly replaceGeneration: number; /** Monotonic count of committed replacements and plugin-owned message changes. */ readonly contentGeneration: number; } //#endregion //#region node_modules/.pnpm/@deepseek-ai+dsh-session@0.2.1-rc.2_@deepseek-ai+cordis@4.0.5_@deepseek-ai+dsh-scope@0._f72072f8db4331da4f9afb922400d5de/node_modules/@deepseek-ai/dsh-session/lib/types/index.d.ts declare module '@deepseek-ai/cordis' { interface Context { sessions: SessionStore; } interface Events { /** * Creation announcement during session publication. A synchronous throw vetoes and rolls * back with a paired disposal; detach requested during dispatch is deferred. * A returned-promise rejection is logged but cannot retroactively veto this * synchronous boundary. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners * receive only sessions entered through that agent's context. * @param session - the session just entered and announced. * @mode emit */ 'session/created'(this: Scoped, session: Session): void; /** * Emitted once when an announced session leaves the store, including * publication rollback, but never for an entry whose creation announcement * did not begin. Listener failures are logged and contained. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`) reuses the owner scope. * @param session - the session that is no longer live in the store. * @mode emit */ 'session/disposed'(this: Scoped, session: Session): void; /** * Post-commit, fire-and-forget append feed. The listener snapshot resolves * before the log push, but callbacks run after it; observer failures are * logged and contained without making the committed append fail. * Scope-filtered dispatch (`@deepseek-ai/dsh-scope`): agent-scoped listeners * receive only events from sessions entered through that agent's context. * @param session - the session whose log grew. * @param event - the appended event, exactly as recorded. * @mode emit */ 'session/event'(this: Scoped, session: Session, event: SessionEvent): void; /** * Awaited parallel durability checkpoint: every listener runs and the * caller awaits all of them, with no waterfall veto. Scope-filtered dispatch * (`@deepseek-ai/dsh-scope`) reuses the session's owner scope. * @param session - the session whose buffered events must reach durable storage. * @mode parallel */ 'session/flush'(this: Scoped, session: Session): Promise | void; } } declare module '@deepseek-ai/dsh-typert-protocol' { interface TypertLookupMap { session: TypertLookup; } } /** * An event-sourced session: an append-only log of {@link SessionEvent}s. * * Plain class (not a Service) — create live instances via * `ctx.sessions.create()` and detached instances via {@link create}. * Seeding with an existing event log replays/forks a session. * @typert object */ declare class Session { #private; private log; /** Single incremental owner of surface acceptance and projection state. */ private readonly surfaceManager; /** The ordered surface over this session's event log. */ get surface(): SessionSurface; /** * Detached, deep-frozen creation metadata (format version, cwd, lineage, * and whether fork history exists). Supplied by the store via `ctx.sessions.create()`. When a * `Session` is created without a store-owned header, a minimal header is * synthesized (stamped with the current {@link SESSION_FORMAT_VERSION}) so * `session.header` is always present. Kept out of the event log — it is a * storage concern, not replayable conversation state. */ readonly header: SessionHeader; /** Number of leading events inherited from this Session's fork parent. */ readonly inheritedEventCount: SessionLogOffset; /** The session identity, derived from its durable header's single copy. */ get id(): SessionId; /** * The constructor seed length (0 without one), before any marker appended * during construction. Seed events never publish on `session/event`. A * marker appended before the store attaches occupies this seq without * publishing either; otherwise this seq is available for the next append. * * This in-process offset is not persisted. A fork seed can already contain * the child's inherited marker and synthetic closers, so its child-owned * history starts at {@link inheritedEventCount}, before this offset. A * resumed Session's seed contains its full stored log, while its inherited * count keeps the durable fork cut. Consumers needing complete canonical * history start at seq 0. */ readonly firstLiveSeq: SessionLogOffset; /** * First event produced for this object lifecycle. A new fork includes its * child-owned seed marker and closers; a restored Session starts after its * complete stored prefix. This in-process capture offset is not persisted. */ readonly firstLifecycleSeq: SessionLogOffset; /** * Create a detached session by validating and snapshotting borrowed seed * events and storage metadata. * @param id - session identity. * @param seed - optional borrowed replay or fork events. * @param header - optional borrowed storage metadata. * @param inheritedEventCount - exact fork-inherited prefix length for a seeded header. * @param projections - pure interpreters for plugin-owned message changes. * @returns a detached session. * @throws when a seed event requires a missing message interpreter or fails validation. */ static create(id: SessionId, seed?: readonly SessionEvent[], header?: SessionHeader, inheritedEventCount?: SessionLogOffset, projections?: readonly SessionMessageProjection[]): Session; /** * Restore a detached session by adopting an independently owned or deeply frozen seed. * Runtime-required event fields, event envelopes, sequence continuity, surface * transitions, and header fields are validated without copying or freezing events. * Embedded Assistant streams remain opaque until a stream consumer or storage * verifier reads them. * @param id - restored session identity. * @param seed - independently owned or deeply frozen events. * @param header - independently owned storage metadata. * @param inheritedEventCount - exact fork-inherited prefix length decoded from storage. * @param eventState - aliasing state carried from the operation that produced the seed. * @param projections - pure interpreters for plugin-owned message changes. * @returns a restored detached session. * @throws when a seed event requires a missing message interpreter or fails validation. */ static fromRestore(id: SessionId, seed: readonly SessionEvent[], header: SessionHeader, inheritedEventCount: SessionLogOffset, eventState: SessionSeedEventState, projections?: readonly SessionMessageProjection[]): Session; private constructor(); /** Cached immutable full snapshot of the private append-only log. */ private eventsSnapshot; /** * Return the immutable event stored at one exact sequence number. * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited. * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md). * @param seq - event sequence number. * @returns the accepted event, or undefined when the log does not contain it. */ eventAt(seq: SessionSeq): SessionEvent | undefined; /** * Materialize an immutable snapshot of a half-open event sequence range. * A full current snapshot is reused until the next append; every previously * returned snapshot remains stable after later appends. * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited. * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md). * @param fromSeq - non-negative inclusive sequence number; defaults to the log start. * @param toSeqExclusive - non-negative exclusive sequence number; defaults to the current end. * @returns a frozen array of the selected deeply frozen events. */ snapshotEvents(fromSeq?: SessionLogOffset, toSeqExclusive?: SessionLogOffset): readonly SessionEvent[]; /** * Return this Session's events after its fork-inherited prefix. * @deprecated Existing logic may remain unmigrated for now, but new calls are prohibited. * See the [Agent Note](../../../../.agents/notes/implemented/architecture/2026-09-09-deprecate-synchronous-session-event-reads.md). * @returns a fresh array containing child-owned events in log order. */ ownEvents(): readonly SessionEvent[]; /** * Whether one existing event position is outside the fork-inherited prefix. * @param seq - event position in this Session. * @returns true when the event belongs to this Session rather than its parent. */ isOwnSeq(seq: SessionSeq): boolean; /** The next event's sequence number — always the log length (the `seq = log.length` contiguity contract). */ get seq(): SessionLogOffset; /** * Append one typed event to the log and synchronously notify observers via * the store-owned, module-private publication hooks. The hot path never blocks * on I/O — persistence plugins buffer asynchronously. Once the event enters * the log, the append is committed: observer failures are logged and * contained per listener, so they do not change the return value or prevent * later listeners from observing the same accepted event. * * @param type - The event type (key of {@link SessionEventMap}). * @param data - The event payload; must be JSON-serializable. * @param opts - Surface metadata: `surfaceOp` controls how the event enters * the ordered surface; `sourceEventSeqs` lists the seq numbers of earlier * events this one derives from. REQUIRED for * {@link SurfaceEventType} events (every message-producing event must * declare how it joins the surface, the sole source of derived model * history) and * rejected by the compiler for non-surface types like `turn/start` or * `assistant/attempt`. Assistant messages embed their exact provider * stream and cannot cite top-level source events. * @returns the logged event — its assigned `seq`/`time` plus the SNAPSHOT of * `data` that entered the log, so reading `event.data` back sees the logged * value, never the caller's still-mutable input. * @throws if `data` or surface metadata is not losslessly JSON-serializable * (BigInt, function, symbol, undefined, negative zero, non-finite number, * circular reference, sparse array, or an exotic object such as * Map/Set/Date/class instance), or when the candidate violates the * request-header empty-field or tool-error consistency rules, or the * canonical surface contract (marker shape and eligibility, unique * earlier source-event references, positional replacement validity, and complete * shadowed-node coverage). One iterative pass reads, validates, and * copies each nested value once, so a stateful getter cannot supply one value * to validation and another to storage. The event log is the durable source * of truth, so a bad event fails at the append site rather than later during * a backend flush. A synchronous internal dispatch validation failure or an * append reentered while this acceptance/publication boundary is open also * rejects before the log changes. */ append(type: T, data: SessionEventMap[T], ...opts: T extends SurfaceEventType ? [opts: SurfaceIntent] : []): SessionEvent; /** * Read the store attachment for one append, refusing an append that * reenters while another append is being published. * @returns the attachment, or undefined for a detached Session. */ private publicationEntry; /** * Accept one frozen candidate at the next sequence number, enter it into the * log, and notify `session/event` observers with per-listener containment. * @param event - the candidate built at the current log length. * @param entry - the attachment read before the candidate was built. */ private commit; /** Cached fold of the request-header events — see {@link requestHeader}. */ private headerFold; /** Log position (events consumed) the header fold has reached. */ private headerFoldSeq; /** * The {@link EpochHeader} in force after the log's last header event — the * header the NEXT request will be compared against — or undefined before * the first `request/header` snapshot. The live, incrementally-maintained * form of `foldRequestHeader(session.snapshotEvents())`: each header event is folded * once, when first seen, so a per-step read costs O(new events). * @returns the folded header, or undefined when no header event exists yet. */ requestHeader(): EpochHeader | undefined; /** Cached fold of `request/context` events. */ private contextFold; private contextFoldSeq; /** * Return the latest resolved route metadata, or `undefined` before the first * `request/context` event. Each event is folded once. * @returns the latest immutable route metadata. */ requestContext(): RequestContext | undefined; /** Cached historical tool definitions and updates for request projection. */ private readonly toolHistoryProjection; /** Index of the next committed event not yet consumed by the tool-history fold. */ private toolHistorySeq; /** * Fold unseen committed events into capability-independent tool history. * Initial access reconstructs inherited history; later reads consume only new events. * @returns an immutable snapshot for LLM request projection, including historical addition definitions. */ toolHistory(): ToolHistory; /** The derived-message cache: frozen projections, extended per unseen node. */ private derived; /** Surface position (nodes projected) the cache has reached. */ private derivedNodes; /** {@link SurfaceManager.contentGeneration} the cache was built under. */ private derivedGeneration; /** * Derive the LLM message history by walking the ordered sequences of * message-producing events maintained by `surfaceOp` markers. The * surface is the single source of derived history: every message-producing * append records its `surfaceOp`, so a raw event with no marker (a chunk, a * turn boundary) is correctly absent, and a compaction `replace` deletes the * shadowed nodes from the derivation. The projection rules are * {@link deriveEventMessage}, with logged message projections applied * without changing node membership or message identity. * * CACHED: pure tail growth costs O(new nodes); a replacement or message projection * ({@link SessionSurface.contentGeneration}) rebuilds. The returned array is * a fresh snapshot per call (later appends never grow an array a caller * already holds); the `Message` objects in it are SHARED and **deep-frozen**. * Unchanged content reuses frozen event data; projected blocks are frozen * derived copies. Consumers cannot mutate the log through either form. * @returns a fresh array of the shared, frozen derived history. */ deriveMessages(): Message[]; /** * Project one event with all committed message projections applied. * The original durable event remains unchanged. * @param event - the event to project. * @returns the derived message, or null when the event produces none. */ deriveEventMessage(event: SessionEvent): Message | null; } /** A fork source: either the live session object or its live store id. */ type SessionForkSource = Session | SessionId; /** * In-memory session store (`ctx.sessions`). * * Persistence is intentionally not implemented here — the agent lifecycle * attaches a session-log writer to each published session's write handle; * a session published outside that lifecycle persists nothing. */ declare class SessionStore extends Service { private store; private counter; private readonly projections; /** Borrowed definitions for detached replay; contributions live until their registering fibers unload. */ get messageProjections(): readonly SessionMessageProjection[]; /** * Register one event interpreter for live creation, restore, and fork. * Disposing the contribution makes sessions that used it refuse further derivation. * @param projection - pure definition owned by the event's plugin. * @returns the fiber-owned disposer. * @throws when another definition already owns this event type. */ registerMessageProjection(projection: SessionMessageProjection): () => Promise; constructor(ctx: Context); /** * Create a session owned by the calling fiber: disposing that fiber stops * event notification and removes the session from the store. `options.seed` * populates the session with a copy of those events (replay/fork); * `options.meta` attaches creation metadata (validated absolute `cwd`, seed * and parent lineage, and delegation depth) as the immutable * {@link SessionHeader} (the store fills `version`/`id`/`createdAt`). * * For an agent whose session must be torn down IN ORDER with its loop (so the * loop's final events are published before the store attachment ends), do NOT use this * — fold the session lifecycle into the agent's own effect via * {@link prepare} + {@link enter} + {@link announce} (see * `dsh-agent-loop`'s creation transaction). * * @param id - the session id; omitted, the store mints `session-`. * @param options - seed events and/or creation metadata for the header. * @returns the live session, already entered and announced. * @throws if a session with `id` already exists, metadata is not a plain * lossless-JSON record with valid scalar fields, or `meta.cwd` is a * non-absolute path (storage backends key directories off it). */ create(id?: SessionId, options?: CreateSessionOptions): Session; /** * Build a session WITHOUT entering it into the store — validate the id/cwd and * construct the {@link Session} (with its immutable {@link SessionHeader}). * Pairs with {@link enter} + {@link announce}: a caller that owns a composite * `ctx.effect` (the agent factory) folds the session lifecycle into that ONE * effect so a fiber unload tears the session + agent down as a single ORDERED * chain rather than as racing sibling effects — which would remove the publication hooks * before the driver's closing events commit, dropping them. * * @param id - the session id; omitted, the store mints `session-`. * @param options - seed events and/or creation metadata for the header. With * `eventState`, every seed event is either independently owned or any * shared value is deeply frozen; {@link Session.fromRestore} validates and * adopts those values without copying or freezing them. * @returns the constructed session, NOT yet in the store. * @throws if a session with `id` already exists, metadata is not a plain * lossless-JSON record with valid scalar fields, or `meta.cwd` is a * non-absolute path. */ prepare(id?: SessionId, options?: PrepareSessionOptions): Session; /** * Enter a {@link prepare}d session into the store: install the module-private * append publication hooks and add it to the store. Returns the DETACH * disposer (hooks + store removal). Does NOT emit `session/created` — * the caller yields this disposer inside its effect and THEN calls * {@link announce}, so a throwing `session/created` listener rolls the attach * back instead of leaking it. * * Re-checks the id for a duplicate: `prepare` and `enter` are public * cross-package primitives and a caller may interleave arbitrary work (or * another create) between them, so a stale prepared session must NOT overwrite * a live store entry of the same id — its detach disposer would later delete * the REAL session. The {@link create} convenience and the agent factory call * the two back-to-back so they never trip this, but the public API cannot * assume that. * * @param session - a {@link prepare}d session not yet in the store. * @returns the detach disposer (publication hooks + store removal). When called from * a synchronous `session/created` listener, removal and disposal wait until * that creation dispatch unwinds. * @throws if a session with this id is already in the store. */ enter(session: Session): () => void; /** Remove one exact entered session and emit its paired disposal when announced. */ private detachEntered; /** Emit `session/created` exactly once for an {@link enter}ed session (with * the carrier {@link enter} captured). Separate from {@link enter} so the * caller can yield the detach disposer first (rollback safety — see * {@link enter}). * @param session - the entered session to announce to listeners. * @throws if the session is not live or its announcement already began, * including a reentrant call from a creation listener. */ announce(session: Session): void; /** Emit the paired teardown notification with per-listener containment. */ private emitDisposed; /** * Dispatch the awaited `session/flush` durability checkpoint for `session`, * with the carrier captured at {@link enter}. THE flush entry point: the * store owns the carrier, so callers (the checkpoint policy's per-request * barrier, goal-round-driver's idle checkpoint, teardown drains, and consumers * that flush themselves before reading storage) must come through here * rather than dispatch a raw `ctx.parallel('session/flush', …)` — one owner * and one spelling. * @param session - the session whose buffered events must reach durable storage. * @returns whether at least one durability listener participated, after every * listener has settled successfully. * @throws the first registered listener failure after every listener settles. */ flush(session: Session): Promise; /** Return the exact live entry; detached/prepared objects reject. */ private liveEntryFor; /** * Look up a live session. * @param id - the session id to look up. * @returns the session, or undefined when no live session has that id. */ get(id: SessionId): Session | undefined; /** * All live sessions, in creation order. * @returns a fresh array; mutating it does not affect the store. */ list(): Session[]; /** * Create a live child session from an exact prefix of a live source. * `boundary` is an inclusive source event seq; omitted means the source's * current last event. An open tail receives synthetic tool results and * step/turn closers with the forked cause. Closed steps and turns remain * unchanged, including any failed tool calls already missing results. * `inheritedEventCount` counts only copied source events, excluding these closers. * * @param source - Live source session object or id. * @param boundary - Inclusive source event seq to fork through; omitted means * the source's current last event, and omitted on an empty source forks an * empty child. * @param childSessionId - Optional child session id; omitted delegates to * `SessionStore`'s id policy. * @returns The created live child session. */ fork(source: SessionForkSource, boundary?: SessionSeq, childSessionId?: SessionId): Session; private _forkBoundary; private _resolveForkSource; } //#endregion //#region src/index.d.ts declare const name = "dsh-plugin-cost"; /** 需要宿主侧的 sessionProjections 服务(dsh-base 内置)。 */ declare const inject: string[]; declare const DEFAULT_PRICES: Record; /** 单个模型的单价(高峰价,元 / 百万 tokens)。 */ interface ModelPrice { /** 缓存命中的输入单价。 */ cacheHit: number; /** 缓存未命中的输入单价。 */ cacheMiss: number; /** 输出单价。 */ output: number; } /** 峰谷策略:auto=按事件发生时刻的北京时间自动判断;peak=恒按高峰;off-peak=恒按空闲。 */ type PeakMode = 'auto' | 'peak' | 'off-peak'; /** 插件配置:价格可被 cordis.yml 覆盖(价格变动无需改代码)。 */ interface Config extends ProjectionConfig { /** 每轮消费限额。volatile:Web 插件页保存后原地生效,无需重启。 */ budget: Volatile; } /** 投影折叠只依赖这三项(测试可以只传这些)。 */ interface ProjectionConfig { /** 按模型名 → 高峰价。key 与 assistant message 的 model 匹配。 */ prices: Record; /** 峰谷策略。 */ peakMode: PeakMode; /** message 未带 model 时兜底使用的模型名。 */ defaultModel: string; } /** 每轮消费限额配置(整体作为 live 字段:volatile 引用读取当前生效值)。 */ interface BudgetConfig { /** 是否启用每轮限额。 */ enabled: boolean; /** 每轮消费上限(元)。 */ perTurn: number; /** 超限行为:'warn'=仅提示(当前);'ask' 预留。 */ mode: 'warn' | 'ask'; } /** 下发到浏览器的限额视图(wire view 附加字段,读取当前生效值)。 */ interface BudgetView { enabled: boolean; perTurn: number; mode: 'warn' | 'ask'; } declare const Config: Schema; /** * 是否处于高峰时段:北京时间周一至周五 9:00–12:00、14:00–18:00。 * @param date - 事件发生时刻(毫秒级 epoch 或 Date)。 */ declare function isPeakHour(date?: Date | number): boolean; /** 一次请求的用量明细(disjoint 计数,来自 usage 桶)。 */ interface UsageCost { /** 缓存未命中输入 token 数。 */ input: number; /** 缓存命中输入 token 数。 */ cacheRead: number; /** 输出 token 数。 */ output: number; /** 估算费用(元,人民币)。 */ cost: number; /** 该请求发生在高峰时段。 */ peak: boolean; } /** * 按单价表计算一次请求的费用。 * @param input - 未命中输入 token。 * @param cacheRead - 命中输入 token。 * @param output - 输出 token。 * @param prices - 该模型的【高峰】单价(元/百万)。 * @param peak - 是否高峰;false 时按半价。 */ declare function computeCost(input: number, cacheRead: number, output: number, prices: ModelPrice, peak: boolean): UsageCost; /** 单条消息的费用明细(浏览器侧会读这个形状)。 */ interface CostMessage { input: number; cacheRead: number; output: number; cost: number; peak: boolean; model: string; /** 该消息所属的轮次(assistant/message 事件的 data.turn)。 */ turn: number; /** 该消息在轮次内的步序(data.step),用于按轮分组后保持稳定顺序。 */ step: number; /** 消息发生时刻(事件 time,epoch ms),用于详情里的时间展示。 */ time: number; /** 内容里是否含可见文本(纯工具调用步骤为 false)。 */ text: boolean; /** 内容里 tool-call 的工具名列表(并行调用多个工具时 >1)。 */ tools: string[]; } /** 会话累计。 */ interface CostTotals { input: number; cacheRead: number; output: number; cost: number; messages: number; } /** projection 的宿主状态。 */ interface CostState { totals: CostTotals; messages: Record; /** 当前打开(进行中)的轮次;空闲为 null。由 turn/start、turn/end 维护。 */ openTurn: number | null; } /** 流式估算口径:浏览器半身用 Chat 的 partial 字符数 × 该口径自行估算。 */ interface CostEstimation { /** 流式估算的字符→输出 token 近似系数(离线校准,中英混排约 3.2 字/token)。 */ charsPerToken: number; /** 各模型的输出单价(高峰价,元/百万 token);浏览器按最近一次调用的模型取价。 */ outputPrices: Record; /** 拿不到当前模型时的兜底模型名。 */ defaultModel: string; /** 峰谷策略(浏览器按发生时刻判断)。 */ peakMode: PeakMode; } /** 流式估算的字符→输出 token 近似系数(离线校准,中英混排约 3.2 字/token)。 */ declare const OUTPUT_CHARS_PER_TOKEN = 3.2; declare const costStateSchema: z.ZodObject<{ totals: z.ZodObject<{ input: z.ZodNumber; cacheRead: z.ZodNumber; output: z.ZodNumber; cost: z.ZodNumber; messages: z.ZodNumber; }, z.core.$strict>; messages: z.ZodRecord; }, z.core.$strict>>; openTurn: z.ZodNullable; }, z.core.$strict>; type CostStateInferred = z.infer; /** wire 视图 = 宿主状态 + 当前生效的限额 + 流式估算口径。 */ declare const costViewSchema: z.ZodObject<{ totals: z.ZodObject<{ input: z.ZodNumber; cacheRead: z.ZodNumber; output: z.ZodNumber; cost: z.ZodNumber; messages: z.ZodNumber; }, z.core.$strict>; messages: z.ZodRecord; }, z.core.$strict>>; openTurn: z.ZodNullable; budget: z.ZodObject<{ enabled: z.ZodBoolean; perTurn: z.ZodNumber; mode: z.ZodEnum<{ warn: "warn"; ask: "ask"; }>; }, z.core.$strict>; estimation: z.ZodObject<{ charsPerToken: z.ZodNumber; outputPrices: z.ZodRecord; defaultModel: z.ZodString; peakMode: z.ZodEnum<{ peak: "peak"; auto: "auto"; "off-peak": "off-peak"; }>; }, z.core.$strict>; }, z.core.$strict>; /** 浏览器侧拿到的完整视图类型(状态 + 当前限额 + 估算口径)。 */ type CostView = z.infer; declare module '@deepseek-ai/dsh-session-projection/types' { interface SessionProjectionStateMap { cost: CostStateInferred; } interface SessionProjectionMap { cost: CostView; } } /** * 组装投影单元:apply 为纯 fold,闭包只引用启动期确定的 config。 * `readBudget` 在每次产出 wire 视图时读取【当前生效】的限额 * (Web 插件页保存后无需重启即反映到浏览器)。导出以便测试。 */ declare function makeProjection(config: ProjectionConfig, readBudget?: () => BudgetView): { key: "cost"; stateVersion: number; stateSchema: z.ZodObject<{ totals: z.ZodObject<{ input: z.ZodNumber; cacheRead: z.ZodNumber; output: z.ZodNumber; cost: z.ZodNumber; messages: z.ZodNumber; }, z.core.$strict>; messages: z.ZodRecord; }, z.core.$strict>>; openTurn: z.ZodNullable; }, z.core.$strict>; init: () => CostStateInferred; apply: (state: CostStateInferred, event: SessionEvent) => CostStateInferred; wire: { viewSchema: z.ZodObject<{ totals: z.ZodObject<{ input: z.ZodNumber; cacheRead: z.ZodNumber; output: z.ZodNumber; cost: z.ZodNumber; messages: z.ZodNumber; }, z.core.$strict>; messages: z.ZodRecord; }, z.core.$strict>>; openTurn: z.ZodNullable; budget: z.ZodObject<{ enabled: z.ZodBoolean; perTurn: z.ZodNumber; mode: z.ZodEnum<{ warn: "warn"; ask: "ask"; }>; }, z.core.$strict>; estimation: z.ZodObject<{ charsPerToken: z.ZodNumber; outputPrices: z.ZodRecord; defaultModel: z.ZodString; peakMode: z.ZodEnum<{ peak: "peak"; auto: "auto"; "off-peak": "off-peak"; }>; }, z.core.$strict>; }, z.core.$strict>; view: (state: NoInfer<{ totals: { input: number; cacheRead: number; output: number; cost: number; messages: number; }; messages: Record; openTurn: number | null; }>) => CostView; }; }; /** 插件主体:注册投影(限额字段是 volatile,由 Loader 原地更新)。 */ declare function apply(ctx: Context, config: Config): void; //#endregion export { BudgetConfig, BudgetView, Config, CostEstimation, CostMessage, CostState, CostTotals, CostView, DEFAULT_PRICES, ModelPrice, OUTPUT_CHARS_PER_TOKEN, PeakMode, ProjectionConfig, UsageCost, apply, computeCost, inject, isPeakHour, makeProjection, name };