@stackstackstack/dsh-agent 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,474 @@
1
+ /**
2
+ * Agent service: live registry, factory delegation, and process-local
3
+ * initiator scope. Concrete creation and driving belong to the loop.
4
+ *
5
+ * @module @stackstackstack/dsh-agent
6
+ */
7
+ import { getTraceable, Service, symbols } from '@deepseek-ai/cordis';
8
+ import { AsyncLocalStorage } from 'node:async_hooks';
9
+ import { isPromise } from 'node:util/types';
10
+ import { scopeTarget } from '@stackstackstack/dsh-scope';
11
+ export * from "./runtime-types.js";
12
+ export * from "./types.js";
13
+ export * from "./inbox.js";
14
+ export * from "./consumed-work.js";
15
+ export * from "./model-selection.js";
16
+ export { agentCarrier, agentEvents, assembleContextFor, emitAgentEvent } from "./dispatch.js";
17
+ /** Thrown when create/resume is called before an agent factory is registered. */
18
+ const NO_FACTORY_MESSAGE = 'no agent factory registered (load an agent-loop plugin)';
19
+ const NO_INITIATOR_MESSAGE = 'no initiating agent is active';
20
+ const DISPOSED_INITIATOR_MESSAGE = 'agent initiator scope is disposed';
21
+ /**
22
+ * Agent service (`ctx.agents`): tracks live agents and carries the initiating
23
+ * Agent through one process-local asynchronous driver chain. Agent *creation*
24
+ * is provided by whichever plugin implements the {@link AgentFactory}
25
+ * (`@stackstackstack/dsh-agent-loop`), registered via {@link setFactory}.
26
+ *
27
+ * Initiator methods provide same-process causal attribution only. Ambient
28
+ * presence is neither liveness proof nor authorization; subjects and owners
29
+ * remain explicit, as does identity at worker, process, persistence, and wire
30
+ * boundaries. Returned Promise boundaries drain during teardown, except a
31
+ * nested lineage that starts an owning-fiber unload is excluded from its own drain.
32
+ */
33
+ export class AgentRegistry extends Service {
34
+ store = new Map();
35
+ factory;
36
+ initiators = new AsyncLocalStorage();
37
+ initiatorRuns = new AsyncLocalStorage();
38
+ initiatorState = 'active';
39
+ activeInitiatorRuns = 0;
40
+ initiatorDrain;
41
+ initiatorDisposal;
42
+ constructor(ctx) {
43
+ super(ctx, 'agents');
44
+ ctx.inject(['typert'], (typeCtx) => {
45
+ typeCtx.typert.lookups.register('agent', {
46
+ parameter: 'agent',
47
+ wire: 'agentId',
48
+ hostTypeSymbol: '@stackstackstack/dsh-agent#Agent',
49
+ wireTypeSymbol: '@stackstackstack/dsh-session/types#SessionId',
50
+ resolve: sessionId => this.get(sessionId),
51
+ });
52
+ typeCtx.typert.contexts.registerHost('agent', {
53
+ wire: 'agentId',
54
+ wireTypeSymbol: '@stackstackstack/dsh-session/types#SessionId',
55
+ resolve: sessionId => this.get(sessionId)?.ctx,
56
+ });
57
+ });
58
+ // The `ctx.agent` DX accessor: default `undefined` on every context, so a
59
+ // plain plugin context reads cleanly instead of hitting the Cordis
60
+ // unknown-property throw. Each Agent.ctx shadows it with an own property
61
+ // (own properties resolve before the context proxy is consulted), so the
62
+ // accessor body never needs to resolve a scope itself. Effect-scoped:
63
+ // unwinds with this service's fiber.
64
+ ctx.accessor('agent', { get: () => undefined });
65
+ ctx.on('internal/status', (fiber) => {
66
+ if (fiber.state === 5 /* FiberState.UNLOADING */ && this.hasLifecycleAncestor(fiber)) {
67
+ this.closeInitiators();
68
+ }
69
+ });
70
+ ctx.effect(function* () {
71
+ yield () => this.disposeInitiators();
72
+ yield () => { this.closeInitiators(); };
73
+ }.bind(this), 'agents.initiatorLifecycle()');
74
+ }
75
+ /**
76
+ * Read the Agent that initiated the inherited asynchronous driver chain.
77
+ * Use this optional form for logging, tracing, metrics, or host attribution
78
+ * that also supports agentless calls. When a parent creates a child, setup
79
+ * reports the causal parent while `agentCtx.agent` identifies the child.
80
+ * @returns the inherited Agent, or `undefined` outside an initiator boundary
81
+ * and inside an explicit clearing boundary.
82
+ * @throws when this service instance has been disposed.
83
+ */
84
+ currentInitiator() {
85
+ this.assertInitiatorsReadable();
86
+ return this.initiators.getStore();
87
+ }
88
+ /**
89
+ * Read the initiating Agent and fail when no initiator boundary is active.
90
+ * Use this for private helpers contractually below a driver, or for a
91
+ * deployment-owned outbound request whose contract forbids agentless calls.
92
+ * Generic or direct-call paths use optional lookup or explicit request fields.
93
+ * @returns the inherited Agent.
94
+ * @throws when no initiator is active or this service instance has been disposed.
95
+ */
96
+ requireInitiator() {
97
+ const agent = this.currentInitiator();
98
+ if (agent === undefined)
99
+ throw new Error(NO_INITIATOR_MESSAGE);
100
+ return agent;
101
+ }
102
+ /**
103
+ * Run an operation with one exact Agent as its process-local initiator. The
104
+ * exact synchronous value or Promise returned by the operation is preserved.
105
+ * Custom drivers and test harnesses wrap their complete returned foreground
106
+ * lifetime.
107
+ * A queue or wire receiver may establish this boundary only after validating
108
+ * explicit identity and resolving the exact live Agent; this method does neither.
109
+ * Detached work remains owned by the subsystem that starts it.
110
+ * @param agent - initiating Agent to inherit; presence is neither liveness proof nor authorization.
111
+ * @param operation - synchronous or asynchronous operation to invoke.
112
+ * @returns the exact value returned by `operation`.
113
+ * @throws when the initiator scope is closing/disposed, or when `operation` throws.
114
+ */
115
+ withInitiator(agent, operation) {
116
+ return this.runWithInitiator(agent, operation);
117
+ }
118
+ /**
119
+ * Run an operation inside a boundary that hides any inherited initiating
120
+ * Agent. The exact synchronous value or Promise is preserved.
121
+ * Use this while creating lazy shared timers, queue pumps, pool maintenance,
122
+ * watchers, or exporters so they do not inherit the first Agent that happens
123
+ * to initialize them. It clears only initiator attribution, not explicit
124
+ * fields, and does not own or drain detached resources.
125
+ * @param operation - synchronous or asynchronous operation to invoke without an initiator.
126
+ * @returns the exact value returned by `operation`.
127
+ * @throws when the initiator scope is closing/disposed, or when `operation` throws.
128
+ */
129
+ withoutInitiator(operation) {
130
+ return this.runWithInitiator(undefined, operation);
131
+ }
132
+ /**
133
+ * Register the agent-creation factory (the loop calls this on construction,
134
+ * effect-scoped). A traced Cordis service is canonicalized to its concrete
135
+ * target; each create/resume call is then traced through that caller's
136
+ * context so ownership follows the caller without stacking proxy layers.
137
+ * Throws if a factory is already registered. Returns the disposer; on
138
+ * dispose the factory slot is cleared.
139
+ * @param factory - the loop-owned factory {@link create}/{@link resume} delegate to.
140
+ * @returns the disposer that clears the factory slot. The exact
141
+ * Cordis effect disposer (single-shot): composite (generator) effects may
142
+ * yield it directly — exact identity nests the teardown in order.
143
+ */
144
+ setFactory(factory) {
145
+ const dispose = this.ctx.effect(() => {
146
+ if (this.factory !== undefined)
147
+ throw new Error('an agent factory is already registered');
148
+ // Avoid stacking two Cordis shadow layers when a caller passes a Service
149
+ // already read through a context. Calls are re-traced through their
150
+ // actual owner context below.
151
+ const target = factory[symbols.original] ?? factory;
152
+ this.factory = { target };
153
+ return () => { this.factory = undefined; };
154
+ }, 'agents.setFactory()');
155
+ // The exact cordis effect disposer (the agents.register() convention): a
156
+ // caller's composite effect can yield it for in-order teardown; the
157
+ // loop's constructor effect returns it directly, identity-nesting the
158
+ // registration under that effect.
159
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
160
+ return dispose;
161
+ }
162
+ /** Return the active creation factory. */
163
+ requireFactory() {
164
+ if (this.factory === undefined)
165
+ throw new Error(NO_FACTORY_MESSAGE);
166
+ return this.factory;
167
+ }
168
+ /**
169
+ * Create and publish a new agent through the registered factory.
170
+ * Distinct from {@link register} (which records an already-constructed
171
+ * agent): this constructs the agent and its session. Rejects if no factory is
172
+ * registered or creation/setup fails. The resolved {@link AgentHandle} lets
173
+ * the owner tear down exactly this agent.
174
+ * @param options - shared identity, session seed/metadata, and agent options.
175
+ * @returns the handle after setup, rollback-covered publication, and loop start complete.
176
+ */
177
+ async create(options) {
178
+ const ownerCtx = this.ctx;
179
+ // Re-trace a Service-backed factory through the accessing context
180
+ // explicitly. This preserves AgentLoop's dependency origin while binding
181
+ // its effects to ownerCtx; plain factories receive ownerCtx as an explicit
182
+ // capability and need no Cordis tracker magic.
183
+ const { target } = this.requireFactory();
184
+ const receiver = getTraceable(ownerCtx, target);
185
+ // oxlint-disable-next-line typescript/unbound-method -- Reflect.apply intentionally supplies the caller-traced receiver
186
+ return Reflect.apply(target.createAgent, receiver, [ownerCtx, options]);
187
+ }
188
+ /**
189
+ * Load a persisted session and resume an agent on it through the registered
190
+ * factory. Rejects if no factory is registered; the factory rejects if
191
+ * session persistence is not configured or persistence/setup fails.
192
+ * @param options - persisted identity, configuration, and optional setup.
193
+ * @returns the handle after setup, rollback-covered publication, and loop start complete.
194
+ */
195
+ async resume(options) {
196
+ const ownerCtx = this.ctx;
197
+ const { target } = this.requireFactory();
198
+ const receiver = getTraceable(ownerCtx, target);
199
+ // oxlint-disable-next-line typescript/unbound-method -- Reflect.apply intentionally supplies the caller-traced receiver
200
+ return Reflect.apply(target.resume, receiver, [ownerCtx, options]);
201
+ }
202
+ /**
203
+ * Register a live agent. Throws if an agent with the same id is already
204
+ * registered. Emits `agent/created` on registration and `agent/disposed`
205
+ * when the calling fiber is disposed — both with the agent's scope carrier
206
+ * (`scopeTarget(agent, agent)`): the subject is the agent in hand, so the
207
+ * emits are scope-filtered regardless of which context invoked `register`
208
+ * (calling through `agent.ctx` scopes EFFECTS; dispatch scoping always
209
+ * requires passing the carrier). Returns the disposer.
210
+ * @param agent - the already-constructed agent to record in the store.
211
+ * @returns the EXACT Cordis effect disposer (single-shot; a repeat call
212
+ * returns undefined without awaiting an in-flight teardown). Exact
213
+ * identity is load-bearing: a composite (generator) effect that owns a
214
+ * teardown ORDER — the agent factory's lifecycle chain — must yield THIS
215
+ * function so Cordis nests the unregistration at that yield position;
216
+ * yielding a wrapper would leave it disposing as a concurrent sibling on
217
+ * owner unload, unregistering the agent (and emitting `agent/disposed`)
218
+ * while its final turn is still draining.
219
+ */
220
+ register(agent) {
221
+ const dispose = this.ctx.effect(function* () {
222
+ yield this.enter(agent, this.ctx.agent);
223
+ this.announce(agent);
224
+ }.bind(this), 'agents.register()');
225
+ // oxlint-disable-next-line typescript/no-misused-promises -- synchronous cleanup; direct return preserves disposer identity
226
+ return dispose;
227
+ }
228
+ /**
229
+ * Insert an already-constructed agent without announcing it. This is the
230
+ * advanced ordered-lifecycle primitive used by the async agent factory: it
231
+ * first completes setup while the agent is unpublished, then assigns the
232
+ * returned detach closure into its pre-installed composite teardown before
233
+ * calling {@link announce}. Ordinary callers use {@link register}.
234
+ * @param agent - the prepared, unpublished agent.
235
+ * @param owner - live agent whose scoped context created this agent, or
236
+ * undefined for a top-level runtime root. This is runtime ownership, not
237
+ * the resumed session's durable parent lineage.
238
+ * @returns an idempotent closure that removes this exact entry and emits
239
+ * `agent/disposed` with listener failures contained. When called from a
240
+ * synchronous `agent/created` listener, removal and disposal wait until
241
+ * that creation dispatch unwinds.
242
+ */
243
+ enter(agent, owner) {
244
+ const id = agent.id;
245
+ if (id !== agent.session.id) {
246
+ throw new Error(`agent id "${id}" does not match session id "${agent.session.id}"`);
247
+ }
248
+ const carrier = scopeTarget(agent, agent);
249
+ // This is the authoritative collision boundary. Concurrent create/resume
250
+ // operations may both prepare, but only one exact entry can publish.
251
+ if (this.store.has(id))
252
+ throw new Error(`agent "${id}" is already registered`);
253
+ const entry = {
254
+ id,
255
+ agent,
256
+ owner,
257
+ carrier,
258
+ announced: false,
259
+ announcing: false,
260
+ detachRequested: false,
261
+ };
262
+ this.store.set(id, entry);
263
+ let entered = true;
264
+ const detach = () => {
265
+ if (!entered)
266
+ return;
267
+ entered = false;
268
+ // Every callback reached by this creation dispatch must observe the same
269
+ // live entry, and disposal must follow creation. A listener may own
270
+ // the advanced detach capability, so make that ordering structural:
271
+ // visibility and the paired disposal are deferred until announce()'s
272
+ // synchronous dispatch has unwound.
273
+ if (entry.announcing) {
274
+ entry.detachRequested = true;
275
+ return;
276
+ }
277
+ this.detachEntered(entry);
278
+ };
279
+ return detach;
280
+ }
281
+ /** Remove one exact entered agent and emit its paired disposal when announced. */
282
+ detachEntered(entry) {
283
+ entry.detachRequested = false;
284
+ // A stale capability can never delete a later same-id lifecycle. The
285
+ // captured entry identity is the final boundary.
286
+ /* v8 ignore next -- enter() rejects replacement while this single-shot detach capability is live. */
287
+ if (this.store.get(entry.id) !== entry)
288
+ return;
289
+ this.store.delete(entry.id);
290
+ // An insertion rolled back before announce was never externally created,
291
+ // so emitting disposed would invent an impossible lifecycle edge. Marking
292
+ // happens before the created emit: if a later created listener throws,
293
+ // earlier listeners may already have observed it and must see disposal.
294
+ if (!entry.announced)
295
+ return;
296
+ this.emitDisposed(entry);
297
+ }
298
+ /** Emit the paired disposal edge through the entry's stable carrier. */
299
+ emitDisposed(entry) {
300
+ const args = [entry.carrier, 'agent/disposed', { agent: entry.agent }];
301
+ for (const callback of this.ctx.events.dispatch('emit', args)) {
302
+ try {
303
+ const returned = callback(...args);
304
+ void Promise.resolve(returned).catch((error) => {
305
+ this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener rejected: ${String(error)}`);
306
+ });
307
+ }
308
+ catch (error) {
309
+ this.ctx.logger.warn(`agent "${entry.id}": agent/disposed listener threw: ${String(error)}`);
310
+ }
311
+ }
312
+ }
313
+ /**
314
+ * Announce an agent previously inserted with {@link enter}.
315
+ * @param agent - the live inserted agent to announce.
316
+ * @throws if `agent` is not the exact live registry entry for its id, or its
317
+ * creation announcement already began (including a reentrant call from a
318
+ * creation listener).
319
+ */
320
+ announce(agent) {
321
+ const entry = this.store.get(agent.id);
322
+ if (entry === undefined || entry.agent !== agent) {
323
+ throw new Error(`agent "${agent.id}" is not live in this registry`);
324
+ }
325
+ if (entry.announced || entry.announcing) {
326
+ throw new Error(`agent "${entry.id}" was already announced`);
327
+ }
328
+ // Mark before dispatch so a listener cannot recursively create a second
329
+ // lifecycle edge; detach still pairs a partially delivered first edge.
330
+ entry.announcing = true;
331
+ entry.announced = true;
332
+ const args = [entry.carrier, 'agent/created', { agent: entry.agent }];
333
+ try {
334
+ for (const callback of this.ctx.events.dispatch('emit', args)) {
335
+ // A synchronous creation failure vetoes publication and rolls back.
336
+ // Returned-promise rejection happens after this synchronous boundary, so
337
+ // observe and report it instead of leaking an unhandled rejection.
338
+ const returned = callback(...args);
339
+ void Promise.resolve(returned).catch((error) => {
340
+ this.ctx.logger.warn(`agent "${entry.id}": agent/created listener rejected: ${String(error)}`);
341
+ });
342
+ }
343
+ }
344
+ finally {
345
+ entry.announcing = false;
346
+ if (entry.detachRequested)
347
+ this.detachEntered(entry);
348
+ }
349
+ }
350
+ /**
351
+ * Look up a live agent.
352
+ * @param id - the shared agent/session id to look up.
353
+ * @returns the agent, or undefined when no live agent has that id.
354
+ */
355
+ get(id) {
356
+ return this.store.get(id)?.agent;
357
+ }
358
+ /**
359
+ * Test whether a live agent was created through one exact parent agent's
360
+ * scoped context. Runtime ownership is independent of durable session
361
+ * lineage and remains unambiguous when unrelated providers reuse an id.
362
+ * @param id - the candidate child agent's shared agent/session id.
363
+ * @param owner - the expected runtime creator agent.
364
+ * @returns true only while the exact child entry is live under that owner.
365
+ */
366
+ isOwnedBy(id, owner) {
367
+ return this.store.get(id)?.owner === owner;
368
+ }
369
+ /**
370
+ * All live agents, in registration order.
371
+ * @returns a fresh array; mutating it does not affect the registry.
372
+ */
373
+ list() {
374
+ return [...this.store.values()].map(entry => entry.agent);
375
+ }
376
+ /**
377
+ * All live top-level agents in registration order. A top-level agent was
378
+ * created without an owning agent context; durable session lineage does not
379
+ * affect this runtime relation, so a resumed fork may still be a root.
380
+ * @returns a fresh array; mutating it does not affect the registry.
381
+ */
382
+ roots() {
383
+ return [...this.store.values()]
384
+ .filter(entry => entry.owner === undefined)
385
+ .map(entry => entry.agent);
386
+ }
387
+ /** Reject new initiator boundaries while inherited continuations drain. */
388
+ closeInitiators() {
389
+ if (this.initiatorState === 'active')
390
+ this.initiatorState = 'closing';
391
+ }
392
+ /** Wait for returned-Promise boundaries, then invalidate retained references. */
393
+ disposeInitiators() {
394
+ return (this.initiatorDisposal ??= (async () => {
395
+ this.closeInitiators();
396
+ this.releaseReentrantInitiatorRuns();
397
+ if (this.activeInitiatorRuns !== 0) {
398
+ this.initiatorDrain ??= Promise.withResolvers();
399
+ await this.initiatorDrain.promise;
400
+ }
401
+ this.initiatorState = 'disposed';
402
+ this.initiators.disable();
403
+ this.initiatorRuns.disable();
404
+ })());
405
+ }
406
+ /** Establish one tracked initiator or clearing boundary. */
407
+ runWithInitiator(agent, operation) {
408
+ if (this.initiatorState !== 'active')
409
+ throw new Error(DISPOSED_INITIATOR_MESSAGE);
410
+ const run = {
411
+ active: true,
412
+ parent: this.initiatorRuns.getStore(),
413
+ };
414
+ this.activeInitiatorRuns += 1;
415
+ let result;
416
+ try {
417
+ result = this.initiatorRuns.run(run, () => this.initiators.run(agent, operation));
418
+ }
419
+ catch (error) {
420
+ this.releaseInitiatorRun(run);
421
+ throw error;
422
+ }
423
+ if (isPromise(result)) {
424
+ try {
425
+ void Promise.prototype.then.call(result, () => { this.releaseInitiatorRun(run); }, () => { this.releaseInitiatorRun(run); });
426
+ }
427
+ catch {
428
+ // A branded Promise may expose a failing @@species. Observer setup did
429
+ // not attach, so preserve the exact return without leaking the run.
430
+ this.releaseInitiatorRun(run);
431
+ }
432
+ }
433
+ else {
434
+ this.releaseInitiatorRun(run);
435
+ }
436
+ return result;
437
+ }
438
+ /** Whether one unloading fiber owns this service's lifecycle. */
439
+ hasLifecycleAncestor(candidate) {
440
+ let fiber = this.ctx.fiber;
441
+ while (true) {
442
+ if (fiber === candidate)
443
+ return true;
444
+ const parent = fiber.parent.fiber;
445
+ if (parent === fiber)
446
+ return false;
447
+ fiber = parent;
448
+ }
449
+ }
450
+ assertInitiatorsReadable() {
451
+ if (this.initiatorState === 'disposed')
452
+ throw new Error(DISPOSED_INITIATOR_MESSAGE);
453
+ }
454
+ /** Exclude the boundary chain that initiated this teardown from its own drain. */
455
+ releaseReentrantInitiatorRuns() {
456
+ let run = this.initiatorRuns.getStore();
457
+ while (run !== undefined) {
458
+ this.releaseInitiatorRun(run);
459
+ run = run.parent;
460
+ }
461
+ }
462
+ releaseInitiatorRun(run) {
463
+ if (!run.active)
464
+ return;
465
+ run.active = false;
466
+ this.activeInitiatorRuns -= 1;
467
+ if (this.activeInitiatorRuns !== 0)
468
+ return;
469
+ this.initiatorDrain?.resolve();
470
+ this.initiatorDrain = undefined;
471
+ }
472
+ }
473
+ export default AgentRegistry;
474
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,13 @@
1
+ /** Package-owned agent lifecycle invariants. @module @stackstackstack/dsh-agent/invariant */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ /** Cordis companion plugin name. */
4
+ export declare const name = "agent-invariant";
5
+ /** Services required before the companion can register. */
6
+ export declare const inject: string[];
7
+ /**
8
+ * Register the agent invariant companion.
9
+ * @param ctx - Cordis context carrying the invariant service.
10
+ * @returns the installed registration's disposer after setup succeeds.
11
+ */
12
+ export declare const apply: (ctx: Context) => Promise<() => void>;
13
+ //# sourceMappingURL=invariant.d.ts.map
@@ -0,0 +1,24 @@
1
+ /** Package-owned agent lifecycle invariants. @module @stackstackstack/dsh-agent/invariant */
2
+ const PACKAGE_NAME = '@stackstackstack/dsh-agent';
3
+ /** Cordis companion plugin name. */
4
+ export const name = 'agent-invariant';
5
+ /** Services required before the companion can register. */
6
+ export const inject = ['invariants'];
7
+ /** Install the agent contribution into its child registration fiber. */
8
+ const install = (ctx, fail) => {
9
+ const lastStatus = new WeakMap();
10
+ ctx.on('agent/status', ({ agent, status }) => {
11
+ const previous = lastStatus.get(agent);
12
+ if (previous === status) {
13
+ fail(`agent/status repeated ${status} (no-op transition)`);
14
+ }
15
+ lastStatus.set(agent, status);
16
+ }, { global: true });
17
+ };
18
+ /**
19
+ * Register the agent invariant companion.
20
+ * @param ctx - Cordis context carrying the invariant service.
21
+ * @returns the installed registration's disposer after setup succeeds.
22
+ */
23
+ export const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
24
+ //# sourceMappingURL=invariant.js.map
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Agent-scoped model selection shared by runtime entry points.
3
+ * @module @stackstackstack/dsh-agent/model-selection
4
+ */
5
+ import type { Context } from '@deepseek-ai/cordis';
6
+ import type { ReasoningEffortId } from '@stackstackstack/dsh-llm';
7
+ /** Complete provider, model, and optional reasoning effort selected for one live Agent. */
8
+ export interface ModelSelection {
9
+ /** Registered provider route. */
10
+ provider: string;
11
+ /** Provider-owned model id. */
12
+ model: string;
13
+ /** Adapter-owned reasoning effort, or provider/default behavior when absent. */
14
+ reasoningEffort?: ReasoningEffortId;
15
+ }
16
+ /** Mutable model selection plus the value captured for the current step. */
17
+ export interface ModelSelectionRef {
18
+ /** Model selected for the next step that enters prompt assembly. */
19
+ current: ModelSelection | undefined;
20
+ /** Selection captured when the current step entered prompt assembly. */
21
+ assembled: ModelSelection | undefined;
22
+ }
23
+ /**
24
+ * Couple one mutable selection to Agent-scoped prompt assembly and request routing.
25
+ * Prompt assembly snapshots the selected model before delegating, then applies
26
+ * its provider/model pair and effort to request config so a
27
+ * concurrent switch takes effect on a later step instead of splitting the two
28
+ * surfaces. An absent selected effort clears any inherited effort, restoring
29
+ * the selected model's provider/default behavior.
30
+ *
31
+ * @param agentCtx - The selected Agent's scoped context.
32
+ * @param selection - Mutable selection owned by the calling entry point.
33
+ * @returns Disposer for both scoped waterfall listeners.
34
+ */
35
+ export declare function installModelSelection(agentCtx: Context, selection: ModelSelectionRef): () => void;
36
+ //# sourceMappingURL=model-selection.d.ts.map
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Agent-scoped model selection shared by runtime entry points.
3
+ * @module @stackstackstack/dsh-agent/model-selection
4
+ */
5
+ /**
6
+ * Couple one mutable selection to Agent-scoped prompt assembly and request routing.
7
+ * Prompt assembly snapshots the selected model before delegating, then applies
8
+ * its provider/model pair and effort to request config so a
9
+ * concurrent switch takes effect on a later step instead of splitting the two
10
+ * surfaces. An absent selected effort clears any inherited effort, restoring
11
+ * the selected model's provider/default behavior.
12
+ *
13
+ * @param agentCtx - The selected Agent's scoped context.
14
+ * @param selection - Mutable selection owned by the calling entry point.
15
+ * @returns Disposer for both scoped waterfall listeners.
16
+ */
17
+ export function installModelSelection(agentCtx, selection) {
18
+ const disposeAssembly = agentCtx.on('system-prompt/assemble', async (_assembly, _context, next) => {
19
+ const selected = selection.current;
20
+ const assembled = await next();
21
+ selection.assembled = selected;
22
+ if (selected === undefined)
23
+ return assembled;
24
+ return {
25
+ ...assembled,
26
+ variables: {
27
+ ...assembled.variables,
28
+ provider: selected.provider,
29
+ model: selected.model,
30
+ },
31
+ };
32
+ });
33
+ const disposeRequest = agentCtx.on('agent/request', async (_payload, next) => {
34
+ const resolved = await next();
35
+ const selected = selection.assembled;
36
+ if (selected === undefined)
37
+ return resolved;
38
+ const { reasoningEffort: _inheritedEffort, ...withoutInheritedEffort } = resolved;
39
+ return {
40
+ ...withoutInheritedEffort,
41
+ provider: selected.provider,
42
+ model: selected.model,
43
+ ...selected.reasoningEffort === undefined
44
+ ? {}
45
+ : { reasoningEffort: selected.reasoningEffort },
46
+ };
47
+ });
48
+ return () => {
49
+ disposeAssembly();
50
+ disposeRequest();
51
+ };
52
+ }
53
+ //# sourceMappingURL=model-selection.js.map