@crazx/dsh-api-session-controller 0.1.2-alpha.3.zw.1

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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +74 -0
  4. package/README.zh.md +74 -0
  5. package/lib/client.js +2724 -0
  6. package/lib/index.js +2826 -0
  7. package/lib/invariant.js +13 -0
  8. package/lib/typert.host.d.ts +3 -0
  9. package/lib/typert.host.js +2574 -0
  10. package/lib/typert.remote-client.d.ts +67 -0
  11. package/lib/typert.remote-client.js +1119 -0
  12. package/lib/types/agent.d.ts +156 -0
  13. package/lib/types/agent.js +537 -0
  14. package/lib/types/catalog.d.ts +11 -0
  15. package/lib/types/catalog.js +58 -0
  16. package/lib/types/client/contract/events.d.ts +71 -0
  17. package/lib/types/client/contract/events.js +91 -0
  18. package/lib/types/client/contract/session.d.ts +150 -0
  19. package/lib/types/client/contract/session.js +2 -0
  20. package/lib/types/client/contract/sessions.d.ts +125 -0
  21. package/lib/types/client/contract/sessions.js +2 -0
  22. package/lib/types/client/contract/snapshot.d.ts +82 -0
  23. package/lib/types/client/contract/snapshot.js +2 -0
  24. package/lib/types/client/index.d.ts +30 -0
  25. package/lib/types/client/index.js +48 -0
  26. package/lib/types/client/ordered-baseline.d.ts +12 -0
  27. package/lib/types/client/ordered-baseline.js +41 -0
  28. package/lib/types/client/scope.d.ts +36 -0
  29. package/lib/types/client/scope.js +54 -0
  30. package/lib/types/client/sessions/history-records.d.ts +22 -0
  31. package/lib/types/client/sessions/history-records.js +31 -0
  32. package/lib/types/client/sessions/lineage.d.ts +38 -0
  33. package/lib/types/client/sessions/lineage.js +56 -0
  34. package/lib/types/client/sessions/manager.d.ts +280 -0
  35. package/lib/types/client/sessions/manager.js +894 -0
  36. package/lib/types/client/sessions/notifier.d.ts +39 -0
  37. package/lib/types/client/sessions/notifier.js +98 -0
  38. package/lib/types/client/sessions/projection-store.d.ts +108 -0
  39. package/lib/types/client/sessions/projection-store.js +129 -0
  40. package/lib/types/client/sessions/queue-mirror.d.ts +26 -0
  41. package/lib/types/client/sessions/queue-mirror.js +61 -0
  42. package/lib/types/client/sessions/remotes.d.ts +30 -0
  43. package/lib/types/client/sessions/remotes.js +8 -0
  44. package/lib/types/client/sessions/service.d.ts +349 -0
  45. package/lib/types/client/sessions/service.js +574 -0
  46. package/lib/types/client/sessions/session.d.ts +294 -0
  47. package/lib/types/client/sessions/session.js +711 -0
  48. package/lib/types/client/time-zone.d.ts +8 -0
  49. package/lib/types/client/time-zone.js +14 -0
  50. package/lib/types/client/transport.d.ts +73 -0
  51. package/lib/types/client/transport.js +106 -0
  52. package/lib/types/commands.d.ts +69 -0
  53. package/lib/types/commands.js +544 -0
  54. package/lib/types/control.d.ts +23 -0
  55. package/lib/types/control.js +192 -0
  56. package/lib/types/file-references.d.ts +27 -0
  57. package/lib/types/file-references.js +69 -0
  58. package/lib/types/history.d.ts +31 -0
  59. package/lib/types/history.js +376 -0
  60. package/lib/types/index.d.ts +171 -0
  61. package/lib/types/index.js +424 -0
  62. package/lib/types/invariant.d.ts +9 -0
  63. package/lib/types/invariant.js +12 -0
  64. package/lib/types/list.d.ts +53 -0
  65. package/lib/types/list.js +405 -0
  66. package/lib/types/model-selection-projection.d.ts +8 -0
  67. package/lib/types/model-selection-projection.js +66 -0
  68. package/lib/types/remote-events.d.ts +8 -0
  69. package/lib/types/remote-events.js +2 -0
  70. package/lib/types/skill-catalog.d.ts +28 -0
  71. package/lib/types/skill-catalog.js +192 -0
  72. package/lib/types/types.d.ts +505 -0
  73. package/lib/types/types.js +6 -0
  74. package/package.json +154 -0
@@ -0,0 +1,156 @@
1
+ /** Agent activation, composition, and model-selection policy owned by API Session. */
2
+ import type { Context } from '@deepseek-ai/cordis';
3
+ import type { Agent, AgentSetup, ModelSelection as AgentModelSelection, ModelSelectionRef } from '@deepseek-ai/dsh-agent';
4
+ import type { Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session';
5
+ import { type SessionObservation } from '@deepseek-ai/dsh-session-query';
6
+ import { RemoteError } from '@deepseek-ai/dsh-typert-protocol';
7
+ /** Cold Session identity absent from persistence. */
8
+ export declare class ApiSessionNotFound extends Error {
9
+ }
10
+ /** Session identity whose lifecycle belongs to subagent routing. */
11
+ export declare class ApiSessionSubagentOwnership extends Error {
12
+ readonly sessionId: SessionId;
13
+ /** @param sessionId - identity reserved to subagent routing. */
14
+ constructor(sessionId: SessionId);
15
+ }
16
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
17
+ export declare class ApiSessionCwdConflict extends Error {
18
+ readonly sessionId: SessionId;
19
+ readonly requestedCwd: string;
20
+ readonly existingCwd: string | undefined;
21
+ constructor(sessionId: SessionId, requestedCwd: string, existingCwd: string | undefined);
22
+ }
23
+ /** Explicit-id creation attempted to adopt a Session under another preset. */
24
+ export declare class ApiSessionPresetConflict extends Error {
25
+ readonly sessionId: SessionId;
26
+ readonly requestedPreset: string;
27
+ readonly existingPreset: string | undefined;
28
+ constructor(sessionId: SessionId, requestedPreset: string, existingPreset: string | undefined);
29
+ }
30
+ /** Failures produced while resolving one ordinary Session identity to its live Agent. */
31
+ export type ApiSessionAgentError = RemoteError<'session/not-found' | 'session/agent-busy' | 'gateway/internal'>;
32
+ /** Result of resolving one ordinary Session identity to its live Agent. */
33
+ export type ApiSessionAgentResult = {
34
+ readonly agent: Agent;
35
+ } | {
36
+ readonly error: ApiSessionAgentError;
37
+ };
38
+ type InstalledSelection = ModelSelectionRef & {
39
+ current: AgentModelSelection;
40
+ consume(provider: string, model: string, reasoningEffort: string | undefined): boolean;
41
+ };
42
+ /**
43
+ * Test whether generic Session routing must leave an identity to subagent routing.
44
+ * @param ctx - Host context carrying the Agent ownership registry.
45
+ * @param session - attached or live Session whose ownership is tested.
46
+ * @param agent - live Agent when one exists for the Session.
47
+ * @returns whether subagent routing owns the Session identity.
48
+ */
49
+ export declare function hasApiSessionSubagentOwner(ctx: Context, session: Pick<Session, 'header'>, agent: Agent | undefined): boolean;
50
+ /**
51
+ * Build the stable caller-facing subagent ownership rejection.
52
+ * @param sessionId - Session identity owned by subagent routing.
53
+ * @returns a stable Session-domain failure.
54
+ */
55
+ export declare function apiSessionSubagentOwnershipError(sessionId: SessionId): ApiSessionAgentError;
56
+ /**
57
+ * Inspect one cold Session without repairing, resuming, or publishing it.
58
+ * @param ctx - Host context carrying Session persistence.
59
+ * @param sessionId - durable Session identity.
60
+ * @param signal - optional cancellation for persistence reads.
61
+ * @returns the persisted header and complete event prefix.
62
+ */
63
+ export declare function inspectApiSession(ctx: Context, sessionId: SessionId, signal?: AbortSignal): Promise<{
64
+ meta: SessionHeader;
65
+ events: SessionEvent[];
66
+ }>;
67
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
68
+ export declare class ApiSessionAgentController {
69
+ private readonly ctx;
70
+ private readonly resumes;
71
+ private readonly creations;
72
+ private readonly selections;
73
+ private readonly imageAdmissionChains;
74
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
75
+ constructor(ctx: Context);
76
+ /**
77
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
78
+ * @param sessionId - ordinary Session identity.
79
+ * @returns the live Agent or a stable Session-domain failure.
80
+ */
81
+ resolveAgent(sessionId: SessionId): Promise<ApiSessionAgentResult>;
82
+ /**
83
+ * Resolve one ordinary Session from an already-retained exact observation.
84
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
85
+ * @returns the live Agent or a stable Session-domain failure.
86
+ */
87
+ resolveObservedAgent(observation: SessionObservation): Promise<ApiSessionAgentResult>;
88
+ private resolve;
89
+ /**
90
+ * Resolve one requested identity, creating or resuming it once.
91
+ * @param sessionId - requested Session identity.
92
+ * @param cwd - directory the Session must own.
93
+ * @param checkPersistedIdentity - whether to inspect a cold identity before creation.
94
+ * @param presetId - optional Agent preset the Session must own.
95
+ * @returns the matching live ordinary Agent.
96
+ */
97
+ ensureSession(sessionId: SessionId, cwd: string, checkPersistedIdentity: boolean, presetId?: string): Promise<Agent>;
98
+ /**
99
+ * Install or return the Session-local model selection used by prompt assembly.
100
+ * @param agent - live Agent that owns the selection.
101
+ * @returns the installed mutable selection reference.
102
+ */
103
+ selectionFor(agent: Agent): InstalledSelection;
104
+ /**
105
+ * Commit and cache one validated selection for the next prompt assembly.
106
+ * @param agent - live Agent that owns the selection.
107
+ * @param selection - validated selection to record and apply.
108
+ */
109
+ selectForNextRequest(agent: Agent, selection: AgentModelSelection): void;
110
+ /**
111
+ * Let a matching durable request header retire the execution cache.
112
+ * @param agent - live Agent whose request was recorded.
113
+ * @param provider - provider route used by the request.
114
+ * @param model - provider-owned model used by the request.
115
+ * @param reasoningEffort - adapter-owned effort used by the request.
116
+ * @returns whether the pending selection was consumed.
117
+ */
118
+ consumeSelection(agent: Agent, provider: string, model: string, reasoningEffort: string | undefined): boolean;
119
+ /**
120
+ * Read the current Agent preset from the Session projection.
121
+ * @param session - live Session whose projection state is available.
122
+ * @returns the current preset, or undefined when the capability is absent.
123
+ */
124
+ presetForSession(session: Session): string | undefined;
125
+ /**
126
+ * Serialize image admission and model selection for one Agent.
127
+ * @param agent - live Agent that owns the serialization chain.
128
+ * @param operation - asynchronous operation admitted after prior work settles.
129
+ * @returns the operation result or rejection.
130
+ */
131
+ serializeImageAdmission<Value>(agent: Agent, operation: () => Promise<Value>): Promise<Value>;
132
+ /**
133
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
134
+ * @param presetId - requested preset or the configured default when omitted.
135
+ * @returns the resolved preset identity and Agent setup callback.
136
+ */
137
+ composeAgent(presetId: string | undefined): Promise<{
138
+ readonly agentPreset?: string;
139
+ readonly setup: AgentSetup;
140
+ }>;
141
+ private liveAgent;
142
+ private resume;
143
+ private resumeObserved;
144
+ private createOrAdopt;
145
+ private agentOptions;
146
+ private installSelection;
147
+ /**
148
+ * Read the current Agent preset from an all-projections observation.
149
+ * @param observation - exact Session observation carrying its projection snapshot.
150
+ * @returns the current preset, or undefined when the capability is absent.
151
+ */
152
+ presetForObservation(observation: SessionObservation): string | undefined;
153
+ private assertPresetUnchanged;
154
+ }
155
+ export {};
156
+ //# sourceMappingURL=agent.d.ts.map
@@ -0,0 +1,537 @@
1
+ /** Agent activation, composition, and model-selection policy owned by API Session. */
2
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
3
+ if (value !== null && value !== void 0) {
4
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
5
+ var dispose, inner;
6
+ if (async) {
7
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
8
+ dispose = value[Symbol.asyncDispose];
9
+ }
10
+ if (dispose === void 0) {
11
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
12
+ dispose = value[Symbol.dispose];
13
+ if (async) inner = dispose;
14
+ }
15
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
16
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
17
+ env.stack.push({ value: value, dispose: dispose, async: async });
18
+ }
19
+ else if (async) {
20
+ env.stack.push({ async: true });
21
+ }
22
+ return value;
23
+ };
24
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
25
+ return function (env) {
26
+ function fail(e) {
27
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
28
+ env.hasError = true;
29
+ }
30
+ var r, s = 0;
31
+ function next() {
32
+ while (r = env.stack.pop()) {
33
+ try {
34
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
35
+ if (r.dispose) {
36
+ var result = r.dispose.call(r.value);
37
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
38
+ }
39
+ else s |= 1;
40
+ }
41
+ catch (e) {
42
+ fail(e);
43
+ }
44
+ }
45
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
46
+ if (env.hasError) throw env.error;
47
+ }
48
+ return next();
49
+ };
50
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
51
+ var e = new Error(message);
52
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
53
+ });
54
+ import { mkdir } from 'node:fs/promises';
55
+ import { installModelSelection } from '@deepseek-ai/dsh-agent';
56
+ import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
57
+ import { SessionQueryError } from '@deepseek-ai/dsh-session-query';
58
+ import { RemoteError } from '@deepseek-ai/dsh-typert-protocol';
59
+ /** Cold Session identity absent from persistence. */
60
+ export class ApiSessionNotFound extends Error {
61
+ }
62
+ /** Session identity whose lifecycle belongs to subagent routing. */
63
+ export class ApiSessionSubagentOwnership extends Error {
64
+ sessionId;
65
+ /** @param sessionId - identity reserved to subagent routing. */
66
+ constructor(sessionId) {
67
+ super(`session "${sessionId}" is a subagent session; use subagent delivery`);
68
+ this.sessionId = sessionId;
69
+ }
70
+ }
71
+ /** Explicit-id creation attempted to adopt a Session under another cwd. */
72
+ export class ApiSessionCwdConflict extends Error {
73
+ sessionId;
74
+ requestedCwd;
75
+ existingCwd;
76
+ constructor(sessionId, requestedCwd, existingCwd) {
77
+ super(existingCwd === undefined
78
+ ? `session "${sessionId}" records no cwd and cannot be adopted for "${requestedCwd}"`
79
+ : `session "${sessionId}" belongs to "${existingCwd}", not "${requestedCwd}"`);
80
+ this.sessionId = sessionId;
81
+ this.requestedCwd = requestedCwd;
82
+ this.existingCwd = existingCwd;
83
+ }
84
+ }
85
+ /** Explicit-id creation attempted to adopt a Session under another preset. */
86
+ export class ApiSessionPresetConflict extends Error {
87
+ sessionId;
88
+ requestedPreset;
89
+ existingPreset;
90
+ constructor(sessionId, requestedPreset, existingPreset) {
91
+ super(existingPreset === undefined
92
+ ? `session "${sessionId}" records no agent preset and cannot be adopted under "${requestedPreset}"`
93
+ : `session "${sessionId}" runs agent preset "${existingPreset}", not "${requestedPreset}"`);
94
+ this.sessionId = sessionId;
95
+ this.requestedPreset = requestedPreset;
96
+ this.existingPreset = existingPreset;
97
+ }
98
+ }
99
+ /**
100
+ * Test whether generic Session routing must leave an identity to subagent routing.
101
+ * @param ctx - Host context carrying the Agent ownership registry.
102
+ * @param session - attached or live Session whose ownership is tested.
103
+ * @param agent - live Agent when one exists for the Session.
104
+ * @returns whether subagent routing owns the Session identity.
105
+ */
106
+ export function hasApiSessionSubagentOwner(ctx, session, agent) {
107
+ if (session.header.origin === 'subagent')
108
+ return true;
109
+ const parentId = session.header.parentSession;
110
+ if (parentId === undefined || agent === undefined)
111
+ return false;
112
+ const parent = ctx.agents.get(parentId);
113
+ return parent !== undefined && ctx.agents.isOwnedBy(agent.id, parent);
114
+ }
115
+ /**
116
+ * Build the stable caller-facing subagent ownership rejection.
117
+ * @param sessionId - Session identity owned by subagent routing.
118
+ * @returns a stable Session-domain failure.
119
+ */
120
+ export function apiSessionSubagentOwnershipError(sessionId) {
121
+ return new RemoteError('session/agent-busy', `session "${sessionId}" is owned by subagent routing`, { reason: 'use subagent delivery for this child session' });
122
+ }
123
+ /**
124
+ * Inspect one cold Session without repairing, resuming, or publishing it.
125
+ * @param ctx - Host context carrying Session persistence.
126
+ * @param sessionId - durable Session identity.
127
+ * @param signal - optional cancellation for persistence reads.
128
+ * @returns the persisted header and complete event prefix.
129
+ */
130
+ export async function inspectApiSession(ctx, sessionId, signal) {
131
+ try {
132
+ const env_1 = { stack: [], error: void 0, hasError: false };
133
+ try {
134
+ const observation = __addDisposableResource(env_1, await ctx.sessionQuery.observeSession(sessionId, {
135
+ ...(signal === undefined ? {} : { signal }),
136
+ projectionMode: 'none',
137
+ }), false);
138
+ if (observation.header.cwd === undefined) {
139
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
140
+ }
141
+ return { meta: observation.header, events: [...observation.events] };
142
+ }
143
+ catch (e_1) {
144
+ env_1.error = e_1;
145
+ env_1.hasError = true;
146
+ }
147
+ finally {
148
+ __disposeResources(env_1);
149
+ }
150
+ }
151
+ catch (error) {
152
+ if (error instanceof SessionQueryError
153
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
154
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
155
+ }
156
+ throw error;
157
+ }
158
+ }
159
+ /** Owns every operation that may create, resume, or configure a Web Agent. */
160
+ export class ApiSessionAgentController {
161
+ ctx;
162
+ resumes = new Map();
163
+ creations = new Map();
164
+ selections = new WeakMap();
165
+ imageAdmissionChains = new WeakMap();
166
+ /** @param ctx - Host context carrying Agent, model, persistence, and Typert services. */
167
+ constructor(ctx) {
168
+ this.ctx = ctx;
169
+ ctx.typert.lookups.configure('agent', async (sessionId) => {
170
+ const found = await this.resolveAgent(sessionId);
171
+ if ('error' in found)
172
+ throw found.error;
173
+ return found.agent;
174
+ });
175
+ ctx.typert.lookups.configure('session', async (sessionId) => {
176
+ const found = await this.resolveAgent(sessionId);
177
+ if ('error' in found)
178
+ throw found.error;
179
+ return found.agent.session;
180
+ });
181
+ ctx.typert.contexts.configureHost('agent', async (sessionId) => {
182
+ const found = await this.resolveAgent(sessionId);
183
+ if ('error' in found)
184
+ throw found.error;
185
+ return found.agent.ctx;
186
+ });
187
+ }
188
+ /**
189
+ * Resolve or resume one ordinary Session, deduplicating concurrent resumes.
190
+ * @param sessionId - ordinary Session identity.
191
+ * @returns the live Agent or a stable Session-domain failure.
192
+ */
193
+ async resolveAgent(sessionId) {
194
+ return this.resolve(sessionId);
195
+ }
196
+ /**
197
+ * Resolve one ordinary Session from an already-retained exact observation.
198
+ * @param observation - Host-owned observation whose preparation stays pinned through setup.
199
+ * @returns the live Agent or a stable Session-domain failure.
200
+ */
201
+ async resolveObservedAgent(observation) {
202
+ return this.resolve(observation.header.id, observation);
203
+ }
204
+ async resolve(sessionId, observation) {
205
+ const live = this.liveAgent(sessionId);
206
+ if (live !== undefined)
207
+ return live;
208
+ const attached = this.ctx.sessions.get(sessionId);
209
+ if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, undefined)) {
210
+ return { error: apiSessionSubagentOwnershipError(sessionId) };
211
+ }
212
+ let resume = this.resumes.get(sessionId);
213
+ if (resume === undefined) {
214
+ resume = this.resume(sessionId, observation).finally(() => { this.resumes.delete(sessionId); });
215
+ this.resumes.set(sessionId, resume);
216
+ }
217
+ try {
218
+ return { agent: await resume };
219
+ }
220
+ catch (error) {
221
+ if (error instanceof ApiSessionNotFound) {
222
+ return { error: new RemoteError('session/not-found', error.message, { sessionId }) };
223
+ }
224
+ if (error instanceof ApiSessionSubagentOwnership) {
225
+ return { error: apiSessionSubagentOwnershipError(error.sessionId) };
226
+ }
227
+ const raced = this.liveAgent(sessionId);
228
+ if (raced !== undefined)
229
+ return raced;
230
+ const racedSession = this.ctx.sessions.get(sessionId);
231
+ if (racedSession !== undefined && hasApiSessionSubagentOwner(this.ctx, racedSession, undefined)) {
232
+ return { error: apiSessionSubagentOwnershipError(sessionId) };
233
+ }
234
+ return {
235
+ error: new RemoteError('gateway/internal', `resume failed for session "${sessionId}": ${String(error)}`, {}),
236
+ };
237
+ }
238
+ }
239
+ /**
240
+ * Resolve one requested identity, creating or resuming it once.
241
+ * @param sessionId - requested Session identity.
242
+ * @param cwd - directory the Session must own.
243
+ * @param checkPersistedIdentity - whether to inspect a cold identity before creation.
244
+ * @param presetId - optional Agent preset the Session must own.
245
+ * @returns the matching live ordinary Agent.
246
+ */
247
+ async ensureSession(sessionId, cwd, checkPersistedIdentity, presetId) {
248
+ let creation = this.creations.get(sessionId);
249
+ if (creation === undefined) {
250
+ creation = this.createOrAdopt(sessionId, cwd, checkPersistedIdentity, presetId)
251
+ .catch((error) => {
252
+ const live = this.ctx.agents.get(sessionId);
253
+ if (live !== undefined) {
254
+ if (hasApiSessionSubagentOwner(this.ctx, live.session, live)) {
255
+ throw new ApiSessionSubagentOwnership(sessionId);
256
+ }
257
+ return live;
258
+ }
259
+ const attached = this.ctx.sessions.get(sessionId);
260
+ if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, undefined)) {
261
+ throw new ApiSessionSubagentOwnership(sessionId);
262
+ }
263
+ throw error;
264
+ })
265
+ .finally(() => { this.creations.delete(sessionId); });
266
+ this.creations.set(sessionId, creation);
267
+ }
268
+ const agent = await creation;
269
+ if (hasApiSessionSubagentOwner(this.ctx, agent.session, agent)) {
270
+ throw new ApiSessionSubagentOwnership(sessionId);
271
+ }
272
+ if (presetId !== undefined) {
273
+ this.assertPresetUnchanged(sessionId, presetId, this.presetForSession(agent.session));
274
+ }
275
+ if (agent.session.header.cwd !== cwd) {
276
+ throw new ApiSessionCwdConflict(sessionId, cwd, agent.session.header.cwd);
277
+ }
278
+ return agent;
279
+ }
280
+ /**
281
+ * Install or return the Session-local model selection used by prompt assembly.
282
+ * @param agent - live Agent that owns the selection.
283
+ * @returns the installed mutable selection reference.
284
+ */
285
+ selectionFor(agent) {
286
+ const installed = this.selections.get(agent);
287
+ if (installed !== undefined)
288
+ return installed;
289
+ const projectionState = this.ctx.sessionProjections.stateOf(agent.session, 'modelSelection');
290
+ if (projectionState === undefined) {
291
+ throw new Error('api-session: required modelSelection projection is not registered');
292
+ }
293
+ let picked = projectionState.pending === null
294
+ ? undefined
295
+ : agentModelSelection(projectionState.pending);
296
+ const defaultModel = this.ctx.agentDefaultModel;
297
+ const selection = {
298
+ get current() {
299
+ if (picked !== undefined)
300
+ return picked;
301
+ const loggedHeader = agent.session.requestHeader();
302
+ if (loggedHeader === undefined)
303
+ return defaultModel.currentSelection();
304
+ const logged = loggedHeader.config;
305
+ return {
306
+ provider: logged.provider,
307
+ model: logged.model,
308
+ // An effort the adapter defaulted is not a conversation choice: restoring
309
+ // it as one would make an unchanged default read as a request change.
310
+ ...(logged.reasoningEffort === undefined
311
+ || loggedHeader.adapterDefaults?.reasoningEffort === true
312
+ ? {}
313
+ : { reasoningEffort: logged.reasoningEffort }),
314
+ };
315
+ },
316
+ set current(next) {
317
+ picked = next;
318
+ },
319
+ consume(provider, model, reasoningEffort) {
320
+ if (picked?.provider !== provider
321
+ || picked.model !== model
322
+ || picked.reasoningEffort !== reasoningEffort)
323
+ return false;
324
+ picked = undefined;
325
+ return true;
326
+ },
327
+ assembled: undefined,
328
+ };
329
+ installModelSelection(agent.ctx, selection);
330
+ this.selections.set(agent, selection);
331
+ return selection;
332
+ }
333
+ /**
334
+ * Commit and cache one validated selection for the next prompt assembly.
335
+ * @param agent - live Agent that owns the selection.
336
+ * @param selection - validated selection to record and apply.
337
+ */
338
+ selectForNextRequest(agent, selection) {
339
+ agent.session.append('model/selection', selection);
340
+ this.selectionFor(agent).current = selection;
341
+ }
342
+ /**
343
+ * Let a matching durable request header retire the execution cache.
344
+ * @param agent - live Agent whose request was recorded.
345
+ * @param provider - provider route used by the request.
346
+ * @param model - provider-owned model used by the request.
347
+ * @param reasoningEffort - adapter-owned effort used by the request.
348
+ * @returns whether the pending selection was consumed.
349
+ */
350
+ consumeSelection(agent, provider, model, reasoningEffort) {
351
+ return this.selections.get(agent)?.consume(provider, model, reasoningEffort) ?? false;
352
+ }
353
+ /**
354
+ * Read the current Agent preset from the Session projection.
355
+ * @param session - live Session whose projection state is available.
356
+ * @returns the current preset, or undefined when the capability is absent.
357
+ */
358
+ presetForSession(session) {
359
+ return this.ctx.sessionProjections.stateOf(session, 'agentPreset') ?? undefined;
360
+ }
361
+ /**
362
+ * Serialize image admission and model selection for one Agent.
363
+ * @param agent - live Agent that owns the serialization chain.
364
+ * @param operation - asynchronous operation admitted after prior work settles.
365
+ * @returns the operation result or rejection.
366
+ */
367
+ serializeImageAdmission(agent, operation) {
368
+ const result = (this.imageAdmissionChains.get(agent) ?? Promise.resolve()).then(operation);
369
+ this.imageAdmissionChains.set(agent, result.then(() => undefined, () => undefined));
370
+ return result;
371
+ }
372
+ /**
373
+ * Resolve the preset id and pre-publication Agent setup for a create or resume.
374
+ * @param presetId - requested preset or the configured default when omitted.
375
+ * @returns the resolved preset identity and Agent setup callback.
376
+ */
377
+ async composeAgent(presetId) {
378
+ const presets = this.ctx.get('agentPresets');
379
+ if (presets === undefined)
380
+ return { setup: (agentCtx) => { this.installSelection(agentCtx); } };
381
+ const resolvedId = (await presets.resolve(presetId)).id;
382
+ return {
383
+ agentPreset: resolvedId,
384
+ setup: async (agentCtx) => {
385
+ this.installSelection(agentCtx);
386
+ await presets.mount(agentCtx, resolvedId);
387
+ },
388
+ };
389
+ }
390
+ liveAgent(sessionId) {
391
+ const agent = this.ctx.agents.get(sessionId);
392
+ if (agent === undefined)
393
+ return undefined;
394
+ return hasApiSessionSubagentOwner(this.ctx, agent.session, agent)
395
+ ? { error: apiSessionSubagentOwnershipError(sessionId) }
396
+ : { agent };
397
+ }
398
+ async resume(sessionId, supplied) {
399
+ if (supplied !== undefined)
400
+ return this.resumeObserved(sessionId, supplied);
401
+ try {
402
+ const env_2 = { stack: [], error: void 0, hasError: false };
403
+ try {
404
+ const observation = __addDisposableResource(env_2, await this.ctx.sessionQuery.observeSession(sessionId), false);
405
+ return await this.resumeObserved(sessionId, observation);
406
+ }
407
+ catch (e_2) {
408
+ env_2.error = e_2;
409
+ env_2.hasError = true;
410
+ }
411
+ finally {
412
+ __disposeResources(env_2);
413
+ }
414
+ }
415
+ catch (error) {
416
+ if (error instanceof SessionQueryError
417
+ && error.code === 'SESSION_QUERY_SESSION_NOT_FOUND') {
418
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
419
+ }
420
+ throw error;
421
+ }
422
+ }
423
+ async resumeObserved(sessionId, observation) {
424
+ if (observation.header.id !== sessionId || observation.header.cwd === undefined) {
425
+ throw new ApiSessionNotFound(`session "${sessionId}" not found`);
426
+ }
427
+ if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, undefined)) {
428
+ throw new ApiSessionSubagentOwnership(sessionId);
429
+ }
430
+ const composition = await this.composeAgent(this.presetForObservation(observation));
431
+ const published = this.ctx.sessions.get(sessionId);
432
+ const live = this.ctx.agents.get(sessionId);
433
+ if (published !== undefined && hasApiSessionSubagentOwner(this.ctx, published, live)) {
434
+ throw new ApiSessionSubagentOwnership(sessionId);
435
+ }
436
+ return (await this.ctx.agents.resume({
437
+ resumeSessionId: sessionId,
438
+ agentOptions: this.agentOptions(),
439
+ setup: composition.setup,
440
+ })).agent;
441
+ }
442
+ async createOrAdopt(sessionId, cwd, checkPersistedIdentity, presetId) {
443
+ const attached = this.ctx.sessions.get(sessionId);
444
+ const live = this.ctx.agents.get(sessionId);
445
+ if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) {
446
+ throw new ApiSessionSubagentOwnership(sessionId);
447
+ }
448
+ if (live !== undefined)
449
+ return live;
450
+ if (checkPersistedIdentity) {
451
+ try {
452
+ const env_3 = { stack: [], error: void 0, hasError: false };
453
+ try {
454
+ const observation = __addDisposableResource(env_3, await this.ctx.sessionQuery.observeSession(sessionId), false);
455
+ if (hasApiSessionSubagentOwner(this.ctx, { header: observation.header }, undefined)) {
456
+ throw new ApiSessionSubagentOwnership(sessionId);
457
+ }
458
+ if (observation.header.cwd !== cwd) {
459
+ throw new ApiSessionCwdConflict(sessionId, cwd, observation.header.cwd);
460
+ }
461
+ const storedPreset = this.presetForObservation(observation);
462
+ this.assertPresetUnchanged(sessionId, presetId, storedPreset);
463
+ const composition = await this.composeAgent(storedPreset);
464
+ return (await this.ctx.agents.resume({
465
+ resumeSessionId: sessionId,
466
+ agentOptions: this.agentOptions(),
467
+ setup: composition.setup,
468
+ })).agent;
469
+ }
470
+ catch (e_3) {
471
+ env_3.error = e_3;
472
+ env_3.hasError = true;
473
+ }
474
+ finally {
475
+ __disposeResources(env_3);
476
+ }
477
+ }
478
+ catch (error) {
479
+ if (!(error instanceof SessionQueryError)
480
+ || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND')
481
+ throw error;
482
+ }
483
+ }
484
+ try {
485
+ await mkdir(cwd, { recursive: true });
486
+ }
487
+ catch (error) {
488
+ throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error });
489
+ }
490
+ const composition = await this.composeAgent(presetId);
491
+ return (await this.ctx.agents.create({
492
+ sessionId,
493
+ agentOptions: this.agentOptions(),
494
+ meta: {
495
+ cwd,
496
+ ...(composition.agentPreset === undefined ? {} : { agentPreset: composition.agentPreset }),
497
+ },
498
+ setup: composition.setup,
499
+ })).agent;
500
+ }
501
+ agentOptions() {
502
+ const { provider, model } = this.ctx.agentDefaultModel.currentSelection();
503
+ return { provider, model };
504
+ }
505
+ installSelection(agentCtx) {
506
+ const agent = agentCtx.agent;
507
+ if (agent === undefined)
508
+ throw new Error('api-session: Agent setup has no scoped Agent');
509
+ this.selectionFor(agent);
510
+ }
511
+ /**
512
+ * Read the current Agent preset from an all-projections observation.
513
+ * @param observation - exact Session observation carrying its projection snapshot.
514
+ * @returns the current preset, or undefined when the capability is absent.
515
+ */
516
+ presetForObservation(observation) {
517
+ if (observation.projections === undefined) {
518
+ throw new Error('api-session: Agent activation requires a projected Session observation');
519
+ }
520
+ return observation.projections.values.agentPreset ?? undefined;
521
+ }
522
+ assertPresetUnchanged(sessionId, requested, existing) {
523
+ if (requested === undefined || requested === existing)
524
+ return;
525
+ throw new ApiSessionPresetConflict(sessionId, requested, existing);
526
+ }
527
+ }
528
+ function agentModelSelection(selection) {
529
+ return {
530
+ provider: selection.provider,
531
+ model: selection.model,
532
+ ...(selection.reasoningEffort === undefined
533
+ ? {}
534
+ : { reasoningEffort: ReasoningEffortId(selection.reasoningEffort) }),
535
+ };
536
+ }
537
+ //# sourceMappingURL=agent.js.map